id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
242,700 | jonathansick/paperweight | paperweight/nlputils.py | wordify | def wordify(text):
"""Generate a list of words given text, removing punctuation.
Parameters
----------
text : unicode
A piece of english text.
Returns
-------
words : list
List of words.
"""
stopset = set(nltk.corpus.stopwords.words('english'))
tokens = nltk.Wor... | python | def wordify(text):
"""Generate a list of words given text, removing punctuation.
Parameters
----------
text : unicode
A piece of english text.
Returns
-------
words : list
List of words.
"""
stopset = set(nltk.corpus.stopwords.words('english'))
tokens = nltk.Wor... | [
"def",
"wordify",
"(",
"text",
")",
":",
"stopset",
"=",
"set",
"(",
"nltk",
".",
"corpus",
".",
"stopwords",
".",
"words",
"(",
"'english'",
")",
")",
"tokens",
"=",
"nltk",
".",
"WordPunctTokenizer",
"(",
")",
".",
"tokenize",
"(",
"text",
")",
"re... | Generate a list of words given text, removing punctuation.
Parameters
----------
text : unicode
A piece of english text.
Returns
-------
words : list
List of words. | [
"Generate",
"a",
"list",
"of",
"words",
"given",
"text",
"removing",
"punctuation",
"."
] | 803535b939a56d375967cefecd5fdca81323041e | https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/nlputils.py#L10-L25 |
242,701 | mkurnikov/typed-env | typed_env/initialize.py | initialize_env | def initialize_env(env_file=None, fail_silently=True, load_globally=True):
"""
Returns an instance of _Environment after reading the system environment an
optionally provided file.
"""
data = {}
data.update(os.environ)
if env_file:
data.update(read_file_values(env_file, fail_silently... | python | def initialize_env(env_file=None, fail_silently=True, load_globally=True):
"""
Returns an instance of _Environment after reading the system environment an
optionally provided file.
"""
data = {}
data.update(os.environ)
if env_file:
data.update(read_file_values(env_file, fail_silently... | [
"def",
"initialize_env",
"(",
"env_file",
"=",
"None",
",",
"fail_silently",
"=",
"True",
",",
"load_globally",
"=",
"True",
")",
":",
"data",
"=",
"{",
"}",
"data",
".",
"update",
"(",
"os",
".",
"environ",
")",
"if",
"env_file",
":",
"data",
".",
"... | Returns an instance of _Environment after reading the system environment an
optionally provided file. | [
"Returns",
"an",
"instance",
"of",
"_Environment",
"after",
"reading",
"the",
"system",
"environment",
"an",
"optionally",
"provided",
"file",
"."
] | d0f3e947f0d5561c9fd1679d6faa9830de24d870 | https://github.com/mkurnikov/typed-env/blob/d0f3e947f0d5561c9fd1679d6faa9830de24d870/typed_env/initialize.py#L10-L23 |
242,702 | inveniosoftware-attic/invenio-knowledge | docs/_ext/flask_app.py | setup | def setup(sphinx):
"""Setup Sphinx object."""
from flask import has_app_context
from invenio_base.factory import create_app
PACKAGES = ['invenio_base', 'invenio.modules.accounts',
'invenio.modules.records', 'invenio_knowledge']
if not has_app_context():
app = create_app(PACK... | python | def setup(sphinx):
"""Setup Sphinx object."""
from flask import has_app_context
from invenio_base.factory import create_app
PACKAGES = ['invenio_base', 'invenio.modules.accounts',
'invenio.modules.records', 'invenio_knowledge']
if not has_app_context():
app = create_app(PACK... | [
"def",
"setup",
"(",
"sphinx",
")",
":",
"from",
"flask",
"import",
"has_app_context",
"from",
"invenio_base",
".",
"factory",
"import",
"create_app",
"PACKAGES",
"=",
"[",
"'invenio_base'",
",",
"'invenio.modules.accounts'",
",",
"'invenio.modules.records'",
",",
"... | Setup Sphinx object. | [
"Setup",
"Sphinx",
"object",
"."
] | b31722dc14243ca8f626f8b3bce9718d0119de55 | https://github.com/inveniosoftware-attic/invenio-knowledge/blob/b31722dc14243ca8f626f8b3bce9718d0119de55/docs/_ext/flask_app.py#L23-L33 |
242,703 | oleg-golovanov/unilog | unilog/convert.py | pretty_spaces | def pretty_spaces(level):
"""
Return spaces and new line.
:type level: int or None
:param level: deep level
:rtype: unicode
:return: string with new line and spaces
"""
if level is None:
return u''
return (os.linesep if level >= 0 else u'') + (u' ' * (INDENT * level)) | python | def pretty_spaces(level):
"""
Return spaces and new line.
:type level: int or None
:param level: deep level
:rtype: unicode
:return: string with new line and spaces
"""
if level is None:
return u''
return (os.linesep if level >= 0 else u'') + (u' ' * (INDENT * level)) | [
"def",
"pretty_spaces",
"(",
"level",
")",
":",
"if",
"level",
"is",
"None",
":",
"return",
"u''",
"return",
"(",
"os",
".",
"linesep",
"if",
"level",
">=",
"0",
"else",
"u''",
")",
"+",
"(",
"u' '",
"*",
"(",
"INDENT",
"*",
"level",
")",
")"
] | Return spaces and new line.
:type level: int or None
:param level: deep level
:rtype: unicode
:return: string with new line and spaces | [
"Return",
"spaces",
"and",
"new",
"line",
"."
] | 4d59cd910032383a71796c4df7446fd5875938c3 | https://github.com/oleg-golovanov/unilog/blob/4d59cd910032383a71796c4df7446fd5875938c3/unilog/convert.py#L20-L33 |
242,704 | oleg-golovanov/unilog | unilog/convert.py | unimapping | def unimapping(arg, level):
"""
Mapping object to unicode string.
:type arg: collections.Mapping
:param arg: mapping object
:type level: int
:param level: deep level
:rtype: unicode
:return: mapping object as unicode string
"""
if not isinstance(arg, collections.Mapping):
... | python | def unimapping(arg, level):
"""
Mapping object to unicode string.
:type arg: collections.Mapping
:param arg: mapping object
:type level: int
:param level: deep level
:rtype: unicode
:return: mapping object as unicode string
"""
if not isinstance(arg, collections.Mapping):
... | [
"def",
"unimapping",
"(",
"arg",
",",
"level",
")",
":",
"if",
"not",
"isinstance",
"(",
"arg",
",",
"collections",
".",
"Mapping",
")",
":",
"raise",
"TypeError",
"(",
"'expected collections.Mapping, {} received'",
".",
"format",
"(",
"type",
"(",
"arg",
")... | Mapping object to unicode string.
:type arg: collections.Mapping
:param arg: mapping object
:type level: int
:param level: deep level
:rtype: unicode
:return: mapping object as unicode string | [
"Mapping",
"object",
"to",
"unicode",
"string",
"."
] | 4d59cd910032383a71796c4df7446fd5875938c3 | https://github.com/oleg-golovanov/unilog/blob/4d59cd910032383a71796c4df7446fd5875938c3/unilog/convert.py#L52-L80 |
242,705 | oleg-golovanov/unilog | unilog/convert.py | uniiterable | def uniiterable(arg, level):
"""
Iterable object to unicode string.
:type arg: collections.Iterable
:param arg: iterable object
:type level: int
:param level: deep level
:rtype: unicode
:return: iterable object as unicode string
"""
if not isinstance(arg, collections.Iterable)... | python | def uniiterable(arg, level):
"""
Iterable object to unicode string.
:type arg: collections.Iterable
:param arg: iterable object
:type level: int
:param level: deep level
:rtype: unicode
:return: iterable object as unicode string
"""
if not isinstance(arg, collections.Iterable)... | [
"def",
"uniiterable",
"(",
"arg",
",",
"level",
")",
":",
"if",
"not",
"isinstance",
"(",
"arg",
",",
"collections",
".",
"Iterable",
")",
":",
"raise",
"TypeError",
"(",
"'expected collections.Iterable, {} received'",
".",
"format",
"(",
"type",
"(",
"arg",
... | Iterable object to unicode string.
:type arg: collections.Iterable
:param arg: iterable object
:type level: int
:param level: deep level
:rtype: unicode
:return: iterable object as unicode string | [
"Iterable",
"object",
"to",
"unicode",
"string",
"."
] | 4d59cd910032383a71796c4df7446fd5875938c3 | https://github.com/oleg-golovanov/unilog/blob/4d59cd910032383a71796c4df7446fd5875938c3/unilog/convert.py#L83-L114 |
242,706 | oleg-golovanov/unilog | unilog/convert.py | convert | def convert(obj, encoding=LOCALE, level=None):
"""
Covert any object to unicode string.
:param obj: any object
:type encoding: str
:param encoding: codec for encoding unicode strings
(locale.getpreferredencoding() by default)
:type level: int
:param level: Deep level. I... | python | def convert(obj, encoding=LOCALE, level=None):
"""
Covert any object to unicode string.
:param obj: any object
:type encoding: str
:param encoding: codec for encoding unicode strings
(locale.getpreferredencoding() by default)
:type level: int
:param level: Deep level. I... | [
"def",
"convert",
"(",
"obj",
",",
"encoding",
"=",
"LOCALE",
",",
"level",
"=",
"None",
")",
":",
"callable_",
"=",
"CONVERTERS",
".",
"get",
"(",
"type",
"(",
"obj",
")",
")",
"if",
"callable_",
"is",
"not",
"None",
":",
"obj",
"=",
"callable_",
... | Covert any object to unicode string.
:param obj: any object
:type encoding: str
:param encoding: codec for encoding unicode strings
(locale.getpreferredencoding() by default)
:type level: int
:param level: Deep level. If None level is not considered.
:rtype: unicode
:r... | [
"Covert",
"any",
"object",
"to",
"unicode",
"string",
"."
] | 4d59cd910032383a71796c4df7446fd5875938c3 | https://github.com/oleg-golovanov/unilog/blob/4d59cd910032383a71796c4df7446fd5875938c3/unilog/convert.py#L117-L159 |
242,707 | pyvec/pyvodb | pyvodb/cli/show.py | show | def show(ctx, city, date):
"""Show a particular meetup.
city: The meetup series.
\b
date: The date. May be:
- YYYY-MM-DD or YY-MM-DD (e.g. 2015-08-27)
- YYYY-MM or YY-MM (e.g. 2015-08)
- MM (e.g. 08): the given month in the current year
- pN (e.g. p1): show the N-th las... | python | def show(ctx, city, date):
"""Show a particular meetup.
city: The meetup series.
\b
date: The date. May be:
- YYYY-MM-DD or YY-MM-DD (e.g. 2015-08-27)
- YYYY-MM or YY-MM (e.g. 2015-08)
- MM (e.g. 08): the given month in the current year
- pN (e.g. p1): show the N-th las... | [
"def",
"show",
"(",
"ctx",
",",
"city",
",",
"date",
")",
":",
"db",
"=",
"ctx",
".",
"obj",
"[",
"'db'",
"]",
"today",
"=",
"ctx",
".",
"obj",
"[",
"'now'",
"]",
".",
"date",
"(",
")",
"term",
"=",
"ctx",
".",
"obj",
"[",
"'term'",
"]",
"e... | Show a particular meetup.
city: The meetup series.
\b
date: The date. May be:
- YYYY-MM-DD or YY-MM-DD (e.g. 2015-08-27)
- YYYY-MM or YY-MM (e.g. 2015-08)
- MM (e.g. 08): the given month in the current year
- pN (e.g. p1): show the N-th last meetup
- +N (e.g. +2): s... | [
"Show",
"a",
"particular",
"meetup",
"."
] | 07183333df26eb12c5c2b98802cde3fb3a6c1339 | https://github.com/pyvec/pyvodb/blob/07183333df26eb12c5c2b98802cde3fb3a6c1339/pyvodb/cli/show.py#L14-L36 |
242,708 | krukas/Trionyx | trionyx/config.py | ModelConfig.get_list_fields | def get_list_fields(self):
"""Get all list fields"""
from trionyx.renderer import renderer
model_fields = {f.name: f for f in self.model.get_fields(True, True)}
def create_list_fields(config_fields, list_fields=None):
list_fields = list_fields if list_fields else {}
... | python | def get_list_fields(self):
"""Get all list fields"""
from trionyx.renderer import renderer
model_fields = {f.name: f for f in self.model.get_fields(True, True)}
def create_list_fields(config_fields, list_fields=None):
list_fields = list_fields if list_fields else {}
... | [
"def",
"get_list_fields",
"(",
"self",
")",
":",
"from",
"trionyx",
".",
"renderer",
"import",
"renderer",
"model_fields",
"=",
"{",
"f",
".",
"name",
":",
"f",
"for",
"f",
"in",
"self",
".",
"model",
".",
"get_fields",
"(",
"True",
",",
"True",
")",
... | Get all list fields | [
"Get",
"all",
"list",
"fields"
] | edac132cc0797190153f2e60bc7e88cb50e80da6 | https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/config.py#L162-L193 |
242,709 | krukas/Trionyx | trionyx/config.py | ModelConfig._get_form | def _get_form(self, config_name, only_required=False):
"""Get form for given config else create form"""
if getattr(self, config_name, None):
return import_object_by_string(getattr(self, config_name))
def use_field(field):
if not only_required:
return True... | python | def _get_form(self, config_name, only_required=False):
"""Get form for given config else create form"""
if getattr(self, config_name, None):
return import_object_by_string(getattr(self, config_name))
def use_field(field):
if not only_required:
return True... | [
"def",
"_get_form",
"(",
"self",
",",
"config_name",
",",
"only_required",
"=",
"False",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"config_name",
",",
"None",
")",
":",
"return",
"import_object_by_string",
"(",
"getattr",
"(",
"self",
",",
"config_name",
... | Get form for given config else create form | [
"Get",
"form",
"for",
"given",
"config",
"else",
"create",
"form"
] | edac132cc0797190153f2e60bc7e88cb50e80da6 | https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/config.py#L195-L205 |
242,710 | krukas/Trionyx | trionyx/config.py | Models.auto_load_configs | def auto_load_configs(self):
"""Auto load all configs from app configs"""
for app in apps.get_app_configs():
for model in app.get_models():
config = ModelConfig(model, getattr(app, model.__name__, None))
self.configs[self.get_model_name(model)] = config | python | def auto_load_configs(self):
"""Auto load all configs from app configs"""
for app in apps.get_app_configs():
for model in app.get_models():
config = ModelConfig(model, getattr(app, model.__name__, None))
self.configs[self.get_model_name(model)] = config | [
"def",
"auto_load_configs",
"(",
"self",
")",
":",
"for",
"app",
"in",
"apps",
".",
"get_app_configs",
"(",
")",
":",
"for",
"model",
"in",
"app",
".",
"get_models",
"(",
")",
":",
"config",
"=",
"ModelConfig",
"(",
"model",
",",
"getattr",
"(",
"app",... | Auto load all configs from app configs | [
"Auto",
"load",
"all",
"configs",
"from",
"app",
"configs"
] | edac132cc0797190153f2e60bc7e88cb50e80da6 | https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/config.py#L215-L220 |
242,711 | krukas/Trionyx | trionyx/config.py | Models.get_config | def get_config(self, model):
"""Get config for given model"""
if not inspect.isclass(model):
model = model.__class__
return self.configs.get(self.get_model_name(model)) | python | def get_config(self, model):
"""Get config for given model"""
if not inspect.isclass(model):
model = model.__class__
return self.configs.get(self.get_model_name(model)) | [
"def",
"get_config",
"(",
"self",
",",
"model",
")",
":",
"if",
"not",
"inspect",
".",
"isclass",
"(",
"model",
")",
":",
"model",
"=",
"model",
".",
"__class__",
"return",
"self",
".",
"configs",
".",
"get",
"(",
"self",
".",
"get_model_name",
"(",
... | Get config for given model | [
"Get",
"config",
"for",
"given",
"model"
] | edac132cc0797190153f2e60bc7e88cb50e80da6 | https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/config.py#L222-L226 |
242,712 | krukas/Trionyx | trionyx/config.py | Models.get_all_configs | def get_all_configs(self, trionyx_models_only=True):
"""Get all model configs"""
from trionyx.models import BaseModel
for index, config in self.configs.items():
if not isinstance(config.model(), BaseModel):
continue
yield config | python | def get_all_configs(self, trionyx_models_only=True):
"""Get all model configs"""
from trionyx.models import BaseModel
for index, config in self.configs.items():
if not isinstance(config.model(), BaseModel):
continue
yield config | [
"def",
"get_all_configs",
"(",
"self",
",",
"trionyx_models_only",
"=",
"True",
")",
":",
"from",
"trionyx",
".",
"models",
"import",
"BaseModel",
"for",
"index",
",",
"config",
"in",
"self",
".",
"configs",
".",
"items",
"(",
")",
":",
"if",
"not",
"isi... | Get all model configs | [
"Get",
"all",
"model",
"configs"
] | edac132cc0797190153f2e60bc7e88cb50e80da6 | https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/config.py#L228-L236 |
242,713 | CivicSpleen/ckcache | ckcache/multi.py | MultiCache.put | def put(self, source, rel_path, metadata=None):
"""Puts to only the first upstream. This is to be symmetric with put_stream."""
return self.upstreams[0].put(source, rel_path, metadata) | python | def put(self, source, rel_path, metadata=None):
"""Puts to only the first upstream. This is to be symmetric with put_stream."""
return self.upstreams[0].put(source, rel_path, metadata) | [
"def",
"put",
"(",
"self",
",",
"source",
",",
"rel_path",
",",
"metadata",
"=",
"None",
")",
":",
"return",
"self",
".",
"upstreams",
"[",
"0",
"]",
".",
"put",
"(",
"source",
",",
"rel_path",
",",
"metadata",
")"
] | Puts to only the first upstream. This is to be symmetric with put_stream. | [
"Puts",
"to",
"only",
"the",
"first",
"upstream",
".",
"This",
"is",
"to",
"be",
"symmetric",
"with",
"put_stream",
"."
] | 0c699b6ba97ff164e9702504f0e1643dd4cd39e1 | https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/multi.py#L52-L54 |
242,714 | CivicSpleen/ckcache | ckcache/multi.py | AltReadCache.list | def list(self, path=None, with_metadata=False, include_partitions=False):
"""Combine a listing of all of the upstreams, and add a metadata item for the
repo_id"""
l = {}
for upstream in [self.alternate, self.upstream]:
for k, v in upstream.list(path, with_metadata, include_... | python | def list(self, path=None, with_metadata=False, include_partitions=False):
"""Combine a listing of all of the upstreams, and add a metadata item for the
repo_id"""
l = {}
for upstream in [self.alternate, self.upstream]:
for k, v in upstream.list(path, with_metadata, include_... | [
"def",
"list",
"(",
"self",
",",
"path",
"=",
"None",
",",
"with_metadata",
"=",
"False",
",",
"include_partitions",
"=",
"False",
")",
":",
"l",
"=",
"{",
"}",
"for",
"upstream",
"in",
"[",
"self",
".",
"alternate",
",",
"self",
".",
"upstream",
"]"... | Combine a listing of all of the upstreams, and add a metadata item for the
repo_id | [
"Combine",
"a",
"listing",
"of",
"all",
"of",
"the",
"upstreams",
"and",
"add",
"a",
"metadata",
"item",
"for",
"the",
"repo_id"
] | 0c699b6ba97ff164e9702504f0e1643dd4cd39e1 | https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/multi.py#L132-L146 |
242,715 | CivicSpleen/ckcache | ckcache/multi.py | AltReadCache._copy_across | def _copy_across(self, rel_path, cb=None):
"""If the upstream doesn't have the file, get it from the alternate and store it in the upstream"""
from . import copy_file_or_flo
if not self.upstream.has(rel_path):
if not self.alternate.has(rel_path):
return None
... | python | def _copy_across(self, rel_path, cb=None):
"""If the upstream doesn't have the file, get it from the alternate and store it in the upstream"""
from . import copy_file_or_flo
if not self.upstream.has(rel_path):
if not self.alternate.has(rel_path):
return None
... | [
"def",
"_copy_across",
"(",
"self",
",",
"rel_path",
",",
"cb",
"=",
"None",
")",
":",
"from",
".",
"import",
"copy_file_or_flo",
"if",
"not",
"self",
".",
"upstream",
".",
"has",
"(",
"rel_path",
")",
":",
"if",
"not",
"self",
".",
"alternate",
".",
... | If the upstream doesn't have the file, get it from the alternate and store it in the upstream | [
"If",
"the",
"upstream",
"doesn",
"t",
"have",
"the",
"file",
"get",
"it",
"from",
"the",
"alternate",
"and",
"store",
"it",
"in",
"the",
"upstream"
] | 0c699b6ba97ff164e9702504f0e1643dd4cd39e1 | https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/multi.py#L148-L170 |
242,716 | CitrineInformatics/dftparse | dftparse/wien2k/sigmak_parser.py | _parse_sigmak | def _parse_sigmak(line, lines):
"""Parse Energy, Re sigma xx, Im sigma xx, Re sigma zz, Im sigma zz"""
split_line = line.split()
energy = float(split_line[0])
re_sigma_xx = float(split_line[1])
im_sigma_xx = float(split_line[2])
re_sigma_zz = float(split_line[3])
im_sigma_zz = float(split_... | python | def _parse_sigmak(line, lines):
"""Parse Energy, Re sigma xx, Im sigma xx, Re sigma zz, Im sigma zz"""
split_line = line.split()
energy = float(split_line[0])
re_sigma_xx = float(split_line[1])
im_sigma_xx = float(split_line[2])
re_sigma_zz = float(split_line[3])
im_sigma_zz = float(split_... | [
"def",
"_parse_sigmak",
"(",
"line",
",",
"lines",
")",
":",
"split_line",
"=",
"line",
".",
"split",
"(",
")",
"energy",
"=",
"float",
"(",
"split_line",
"[",
"0",
"]",
")",
"re_sigma_xx",
"=",
"float",
"(",
"split_line",
"[",
"1",
"]",
")",
"im_sig... | Parse Energy, Re sigma xx, Im sigma xx, Re sigma zz, Im sigma zz | [
"Parse",
"Energy",
"Re",
"sigma",
"xx",
"Im",
"sigma",
"xx",
"Re",
"sigma",
"zz",
"Im",
"sigma",
"zz"
] | 53a1bf19945cf1c195d6af9beccb3d1b7f4a4c1d | https://github.com/CitrineInformatics/dftparse/blob/53a1bf19945cf1c195d6af9beccb3d1b7f4a4c1d/dftparse/wien2k/sigmak_parser.py#L4-L16 |
242,717 | armstrong/armstrong.dev | armstrong/dev/tasks.py | require_self | def require_self(func, *args, **kwargs):
"""Decorator to require that this component be installed"""
try:
__import__(package['name'])
except ImportError:
sys.stderr.write(
"This component needs to be installed first. Run " +
"`invoke install`\n")
sys.exit(1)
... | python | def require_self(func, *args, **kwargs):
"""Decorator to require that this component be installed"""
try:
__import__(package['name'])
except ImportError:
sys.stderr.write(
"This component needs to be installed first. Run " +
"`invoke install`\n")
sys.exit(1)
... | [
"def",
"require_self",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"__import__",
"(",
"package",
"[",
"'name'",
"]",
")",
"except",
"ImportError",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"This component needs to ... | Decorator to require that this component be installed | [
"Decorator",
"to",
"require",
"that",
"this",
"component",
"be",
"installed"
] | 6fd8b863038d9e5ebfd52dfe5ce6c85fb441c267 | https://github.com/armstrong/armstrong.dev/blob/6fd8b863038d9e5ebfd52dfe5ce6c85fb441c267/armstrong/dev/tasks.py#L35-L45 |
242,718 | armstrong/armstrong.dev | armstrong/dev/tasks.py | require_pip_module | def require_pip_module(module):
"""Decorator to check for a module and helpfully exit if it's not found"""
def wrapper(func, *args, **kwargs):
try:
__import__(module)
except ImportError:
sys.stderr.write(
"`pip install %s` to enable this feature\n" % modu... | python | def require_pip_module(module):
"""Decorator to check for a module and helpfully exit if it's not found"""
def wrapper(func, *args, **kwargs):
try:
__import__(module)
except ImportError:
sys.stderr.write(
"`pip install %s` to enable this feature\n" % modu... | [
"def",
"require_pip_module",
"(",
"module",
")",
":",
"def",
"wrapper",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"__import__",
"(",
"module",
")",
"except",
"ImportError",
":",
"sys",
".",
"stderr",
".",
"write",
... | Decorator to check for a module and helpfully exit if it's not found | [
"Decorator",
"to",
"check",
"for",
"a",
"module",
"and",
"helpfully",
"exit",
"if",
"it",
"s",
"not",
"found"
] | 6fd8b863038d9e5ebfd52dfe5ce6c85fb441c267 | https://github.com/armstrong/armstrong.dev/blob/6fd8b863038d9e5ebfd52dfe5ce6c85fb441c267/armstrong/dev/tasks.py#L48-L60 |
242,719 | armstrong/armstrong.dev | armstrong/dev/tasks.py | replaced_by_django_migrations | def replaced_by_django_migrations(func, *args, **kwargs):
"""Decorator to preempt South requirement"""
DjangoSettings() # trigger helpful messages if Django is missing
import django
if django.VERSION >= (1, 7):
print("Django 1.7+ has its own migrations system.")
print("Use this instea... | python | def replaced_by_django_migrations(func, *args, **kwargs):
"""Decorator to preempt South requirement"""
DjangoSettings() # trigger helpful messages if Django is missing
import django
if django.VERSION >= (1, 7):
print("Django 1.7+ has its own migrations system.")
print("Use this instea... | [
"def",
"replaced_by_django_migrations",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"DjangoSettings",
"(",
")",
"# trigger helpful messages if Django is missing",
"import",
"django",
"if",
"django",
".",
"VERSION",
">=",
"(",
"1",
",",
"7",... | Decorator to preempt South requirement | [
"Decorator",
"to",
"preempt",
"South",
"requirement"
] | 6fd8b863038d9e5ebfd52dfe5ce6c85fb441c267 | https://github.com/armstrong/armstrong.dev/blob/6fd8b863038d9e5ebfd52dfe5ce6c85fb441c267/armstrong/dev/tasks.py#L64-L74 |
242,720 | armstrong/armstrong.dev | armstrong/dev/tasks.py | create_migration | def create_migration(initial=False):
"""Create a South migration for this project"""
settings = DjangoSettings()
if 'south' not in (name.lower() for name in settings.INSTALLED_APPS):
print("Temporarily adding 'south' into INSTALLED_APPS.")
settings.INSTALLED_APPS.append('south')
kwargs... | python | def create_migration(initial=False):
"""Create a South migration for this project"""
settings = DjangoSettings()
if 'south' not in (name.lower() for name in settings.INSTALLED_APPS):
print("Temporarily adding 'south' into INSTALLED_APPS.")
settings.INSTALLED_APPS.append('south')
kwargs... | [
"def",
"create_migration",
"(",
"initial",
"=",
"False",
")",
":",
"settings",
"=",
"DjangoSettings",
"(",
")",
"if",
"'south'",
"not",
"in",
"(",
"name",
".",
"lower",
"(",
")",
"for",
"name",
"in",
"settings",
".",
"INSTALLED_APPS",
")",
":",
"print",
... | Create a South migration for this project | [
"Create",
"a",
"South",
"migration",
"for",
"this",
"project"
] | 6fd8b863038d9e5ebfd52dfe5ce6c85fb441c267 | https://github.com/armstrong/armstrong.dev/blob/6fd8b863038d9e5ebfd52dfe5ce6c85fb441c267/armstrong/dev/tasks.py#L87-L96 |
242,721 | armstrong/armstrong.dev | armstrong/dev/tasks.py | coverage | def coverage(reportdir=None, extra=None):
"""Test this project with coverage reports"""
import coverage as coverage_api
cov = coverage_api.coverage()
opts = {'directory': reportdir} if reportdir else {}
cov.start()
test(extra)
cov.stop()
cov.html_report(**opts) | python | def coverage(reportdir=None, extra=None):
"""Test this project with coverage reports"""
import coverage as coverage_api
cov = coverage_api.coverage()
opts = {'directory': reportdir} if reportdir else {}
cov.start()
test(extra)
cov.stop()
cov.html_report(**opts) | [
"def",
"coverage",
"(",
"reportdir",
"=",
"None",
",",
"extra",
"=",
"None",
")",
":",
"import",
"coverage",
"as",
"coverage_api",
"cov",
"=",
"coverage_api",
".",
"coverage",
"(",
")",
"opts",
"=",
"{",
"'directory'",
":",
"reportdir",
"}",
"if",
"repor... | Test this project with coverage reports | [
"Test",
"this",
"project",
"with",
"coverage",
"reports"
] | 6fd8b863038d9e5ebfd52dfe5ce6c85fb441c267 | https://github.com/armstrong/armstrong.dev/blob/6fd8b863038d9e5ebfd52dfe5ce6c85fb441c267/armstrong/dev/tasks.py#L116-L126 |
242,722 | armstrong/armstrong.dev | armstrong/dev/tasks.py | managepy | def managepy(cmd, extra=None):
"""Run manage.py using this component's specific Django settings"""
extra = extra.split() if extra else []
run_django_cli(['invoke', cmd] + extra) | python | def managepy(cmd, extra=None):
"""Run manage.py using this component's specific Django settings"""
extra = extra.split() if extra else []
run_django_cli(['invoke', cmd] + extra) | [
"def",
"managepy",
"(",
"cmd",
",",
"extra",
"=",
"None",
")",
":",
"extra",
"=",
"extra",
".",
"split",
"(",
")",
"if",
"extra",
"else",
"[",
"]",
"run_django_cli",
"(",
"[",
"'invoke'",
",",
"cmd",
"]",
"+",
"extra",
")"
] | Run manage.py using this component's specific Django settings | [
"Run",
"manage",
".",
"py",
"using",
"this",
"component",
"s",
"specific",
"Django",
"settings"
] | 6fd8b863038d9e5ebfd52dfe5ce6c85fb441c267 | https://github.com/armstrong/armstrong.dev/blob/6fd8b863038d9e5ebfd52dfe5ce6c85fb441c267/armstrong/dev/tasks.py#L130-L134 |
242,723 | CitrineInformatics/dftparse | dftparse/vasp/outcar_parser.py | _parse_total_magnetization | def _parse_total_magnetization(line, lines):
"""Parse the total magnetization, which is somewhat hidden"""
toks = line.split()
res = {"number of electrons": float(toks[3])}
if len(toks) > 5:
res["total magnetization"] = float(toks[5])
return res | python | def _parse_total_magnetization(line, lines):
"""Parse the total magnetization, which is somewhat hidden"""
toks = line.split()
res = {"number of electrons": float(toks[3])}
if len(toks) > 5:
res["total magnetization"] = float(toks[5])
return res | [
"def",
"_parse_total_magnetization",
"(",
"line",
",",
"lines",
")",
":",
"toks",
"=",
"line",
".",
"split",
"(",
")",
"res",
"=",
"{",
"\"number of electrons\"",
":",
"float",
"(",
"toks",
"[",
"3",
"]",
")",
"}",
"if",
"len",
"(",
"toks",
")",
">",... | Parse the total magnetization, which is somewhat hidden | [
"Parse",
"the",
"total",
"magnetization",
"which",
"is",
"somewhat",
"hidden"
] | 53a1bf19945cf1c195d6af9beccb3d1b7f4a4c1d | https://github.com/CitrineInformatics/dftparse/blob/53a1bf19945cf1c195d6af9beccb3d1b7f4a4c1d/dftparse/vasp/outcar_parser.py#L4-L10 |
242,724 | bitlabstudio/django-server-guardian-api | server_guardian_api/processors/django_mailer.py | deferred_emails | def deferred_emails():
"""Checks for deferred email, that otherwise fill up the queue."""
status = SERVER_STATUS['OK']
count = Message.objects.deferred().count()
if DEFERRED_WARNING_THRESHOLD <= count < DEFERRED_DANGER_THRESHOLD:
status = SERVER_STATUS['WARNING']
if count >= DEFERRED_DANGER... | python | def deferred_emails():
"""Checks for deferred email, that otherwise fill up the queue."""
status = SERVER_STATUS['OK']
count = Message.objects.deferred().count()
if DEFERRED_WARNING_THRESHOLD <= count < DEFERRED_DANGER_THRESHOLD:
status = SERVER_STATUS['WARNING']
if count >= DEFERRED_DANGER... | [
"def",
"deferred_emails",
"(",
")",
":",
"status",
"=",
"SERVER_STATUS",
"[",
"'OK'",
"]",
"count",
"=",
"Message",
".",
"objects",
".",
"deferred",
"(",
")",
".",
"count",
"(",
")",
"if",
"DEFERRED_WARNING_THRESHOLD",
"<=",
"count",
"<",
"DEFERRED_DANGER_TH... | Checks for deferred email, that otherwise fill up the queue. | [
"Checks",
"for",
"deferred",
"email",
"that",
"otherwise",
"fill",
"up",
"the",
"queue",
"."
] | c996245b5a8e8f6f590251a8757adcca79d114e3 | https://github.com/bitlabstudio/django-server-guardian-api/blob/c996245b5a8e8f6f590251a8757adcca79d114e3/server_guardian_api/processors/django_mailer.py#L22-L36 |
242,725 | bitlabstudio/django-server-guardian-api | server_guardian_api/processors/django_mailer.py | email_queue | def email_queue():
"""Checks for emails, that fill up the queue without getting sent."""
status = SERVER_STATUS['OK']
count = Message.objects.exclude(priority=PRIORITY_DEFERRED).filter(
when_added__lte=now() - timedelta(minutes=QUEUE_TIMEOUT)).count()
if QUEUE_WARNING_THRESHOLD <= count < QUEUE... | python | def email_queue():
"""Checks for emails, that fill up the queue without getting sent."""
status = SERVER_STATUS['OK']
count = Message.objects.exclude(priority=PRIORITY_DEFERRED).filter(
when_added__lte=now() - timedelta(minutes=QUEUE_TIMEOUT)).count()
if QUEUE_WARNING_THRESHOLD <= count < QUEUE... | [
"def",
"email_queue",
"(",
")",
":",
"status",
"=",
"SERVER_STATUS",
"[",
"'OK'",
"]",
"count",
"=",
"Message",
".",
"objects",
".",
"exclude",
"(",
"priority",
"=",
"PRIORITY_DEFERRED",
")",
".",
"filter",
"(",
"when_added__lte",
"=",
"now",
"(",
")",
"... | Checks for emails, that fill up the queue without getting sent. | [
"Checks",
"for",
"emails",
"that",
"fill",
"up",
"the",
"queue",
"without",
"getting",
"sent",
"."
] | c996245b5a8e8f6f590251a8757adcca79d114e3 | https://github.com/bitlabstudio/django-server-guardian-api/blob/c996245b5a8e8f6f590251a8757adcca79d114e3/server_guardian_api/processors/django_mailer.py#L39-L55 |
242,726 | AoiKuiyuyou/AoikI18n | src/aoiki18n/aoiki18n_.py | I18n.yaml_force_unicode | def yaml_force_unicode():
"""
Force pyyaml to return unicode values.
"""
#/
## modified from |http://stackoverflow.com/a/2967461|
if sys.version_info[0] == 2:
def construct_func(self, node):
return self.construct_scalar(node)
yaml.L... | python | def yaml_force_unicode():
"""
Force pyyaml to return unicode values.
"""
#/
## modified from |http://stackoverflow.com/a/2967461|
if sys.version_info[0] == 2:
def construct_func(self, node):
return self.construct_scalar(node)
yaml.L... | [
"def",
"yaml_force_unicode",
"(",
")",
":",
"#/",
"## modified from |http://stackoverflow.com/a/2967461|",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"2",
":",
"def",
"construct_func",
"(",
"self",
",",
"node",
")",
":",
"return",
"self",
".",
"con... | Force pyyaml to return unicode values. | [
"Force",
"pyyaml",
"to",
"return",
"unicode",
"values",
"."
] | 8d60ea6a2be24e533a9cf92b433a8cfdb67f813e | https://github.com/AoiKuiyuyou/AoikI18n/blob/8d60ea6a2be24e533a9cf92b433a8cfdb67f813e/src/aoiki18n/aoiki18n_.py#L78-L88 |
242,727 | AoiKuiyuyou/AoikI18n | src/aoiki18n/aoiki18n_.py | I18n.get_locale_hints | def get_locale_hints():
"""
Get a list of locale hints,
guessed according to Python's default locale info.
"""
#/
lang, encoding = locale.getdefaultlocale()
## can both be None
#/
if lang and '_' in lang:
lang3, _, lang2 = la... | python | def get_locale_hints():
"""
Get a list of locale hints,
guessed according to Python's default locale info.
"""
#/
lang, encoding = locale.getdefaultlocale()
## can both be None
#/
if lang and '_' in lang:
lang3, _, lang2 = la... | [
"def",
"get_locale_hints",
"(",
")",
":",
"#/",
"lang",
",",
"encoding",
"=",
"locale",
".",
"getdefaultlocale",
"(",
")",
"## can both be None",
"#/",
"if",
"lang",
"and",
"'_'",
"in",
"lang",
":",
"lang3",
",",
"_",
",",
"lang2",
"=",
"lang",
".",
"p... | Get a list of locale hints,
guessed according to Python's default locale info. | [
"Get",
"a",
"list",
"of",
"locale",
"hints",
"guessed",
"according",
"to",
"Python",
"s",
"default",
"locale",
"info",
"."
] | 8d60ea6a2be24e533a9cf92b433a8cfdb67f813e | https://github.com/AoiKuiyuyou/AoikI18n/blob/8d60ea6a2be24e533a9cf92b433a8cfdb67f813e/src/aoiki18n/aoiki18n_.py#L91-L123 |
242,728 | AoiKuiyuyou/AoikI18n | src/aoiki18n/aoiki18n_.py | I18n.get_locale_choices | def get_locale_choices(locale_dir):
"""
Get a list of locale file names in the given locale dir.
"""
#/
file_name_s = os.listdir(locale_dir)
#/
choice_s = []
for file_name in file_name_s:
if file_name.endswith(I18n.TT_FILE_EXT... | python | def get_locale_choices(locale_dir):
"""
Get a list of locale file names in the given locale dir.
"""
#/
file_name_s = os.listdir(locale_dir)
#/
choice_s = []
for file_name in file_name_s:
if file_name.endswith(I18n.TT_FILE_EXT... | [
"def",
"get_locale_choices",
"(",
"locale_dir",
")",
":",
"#/",
"file_name_s",
"=",
"os",
".",
"listdir",
"(",
"locale_dir",
")",
"#/",
"choice_s",
"=",
"[",
"]",
"for",
"file_name",
"in",
"file_name_s",
":",
"if",
"file_name",
".",
"endswith",
"(",
"I18n"... | Get a list of locale file names in the given locale dir. | [
"Get",
"a",
"list",
"of",
"locale",
"file",
"names",
"in",
"the",
"given",
"locale",
"dir",
"."
] | 8d60ea6a2be24e533a9cf92b433a8cfdb67f813e | https://github.com/AoiKuiyuyou/AoikI18n/blob/8d60ea6a2be24e533a9cf92b433a8cfdb67f813e/src/aoiki18n/aoiki18n_.py#L126-L146 |
242,729 | Infinidat/infi.recipe.console_scripts | src/infi/recipe/console_scripts/egg.py | Eggs.working_set | def working_set(self, extra=()):
"""Separate method to just get the working set
This is intended for reuse by similar recipes.
"""
options = self.options
b_options = self.buildout['buildout']
# Backward compat. :(
options['executable'] = sys.executable
... | python | def working_set(self, extra=()):
"""Separate method to just get the working set
This is intended for reuse by similar recipes.
"""
options = self.options
b_options = self.buildout['buildout']
# Backward compat. :(
options['executable'] = sys.executable
... | [
"def",
"working_set",
"(",
"self",
",",
"extra",
"=",
"(",
")",
")",
":",
"options",
"=",
"self",
".",
"options",
"b_options",
"=",
"self",
".",
"buildout",
"[",
"'buildout'",
"]",
"# Backward compat. :(",
"options",
"[",
"'executable'",
"]",
"=",
"sys",
... | Separate method to just get the working set
This is intended for reuse by similar recipes. | [
"Separate",
"method",
"to",
"just",
"get",
"the",
"working",
"set"
] | 7beab59537654ee475527dbbd59b0aa49348ebd3 | https://github.com/Infinidat/infi.recipe.console_scripts/blob/7beab59537654ee475527dbbd59b0aa49348ebd3/src/infi/recipe/console_scripts/egg.py#L38-L70 |
242,730 | storax/upme | src/upme/main.py | get_required | def get_required(dist):
"""Return a set with all distributions that are required of dist
This also includes subdependencies and the given distribution.
:param dist: the distribution to query. Can also be the name of the distribution
:type dist: :class:`pkg_resources.Distribution` | str
:returns: a... | python | def get_required(dist):
"""Return a set with all distributions that are required of dist
This also includes subdependencies and the given distribution.
:param dist: the distribution to query. Can also be the name of the distribution
:type dist: :class:`pkg_resources.Distribution` | str
:returns: a... | [
"def",
"get_required",
"(",
"dist",
")",
":",
"d",
"=",
"pkg_resources",
".",
"get_distribution",
"(",
"dist",
")",
"reqs",
"=",
"set",
"(",
"d",
".",
"requires",
"(",
")",
")",
"allds",
"=",
"set",
"(",
"[",
"d",
"]",
")",
"while",
"reqs",
":",
... | Return a set with all distributions that are required of dist
This also includes subdependencies and the given distribution.
:param dist: the distribution to query. Can also be the name of the distribution
:type dist: :class:`pkg_resources.Distribution` | str
:returns: a list of distributions that are... | [
"Return",
"a",
"set",
"with",
"all",
"distributions",
"that",
"are",
"required",
"of",
"dist"
] | 41c2d91f922691e31ff940f33b755d2cb64dfef8 | https://github.com/storax/upme/blob/41c2d91f922691e31ff940f33b755d2cb64dfef8/src/upme/main.py#L8-L29 |
242,731 | storax/upme | src/upme/main.py | is_outdated | def is_outdated(dist, dep=False):
"""Return a dict with outdated distributions
If the given distribution has dependencies, they are checked as well.
:param dist: a distribution to check
:type dist: :class:`pkg_resources.Distribution` | str
:param dep: If True, also return all outdated dependencies... | python | def is_outdated(dist, dep=False):
"""Return a dict with outdated distributions
If the given distribution has dependencies, they are checked as well.
:param dist: a distribution to check
:type dist: :class:`pkg_resources.Distribution` | str
:param dep: If True, also return all outdated dependencies... | [
"def",
"is_outdated",
"(",
"dist",
",",
"dep",
"=",
"False",
")",
":",
"if",
"dep",
":",
"required",
"=",
"get_required",
"(",
"dist",
")",
"else",
":",
"required",
"=",
"set",
"(",
"[",
"dist",
"]",
")",
"ListCommand",
"=",
"pip",
".",
"commands",
... | Return a dict with outdated distributions
If the given distribution has dependencies, they are checked as well.
:param dist: a distribution to check
:type dist: :class:`pkg_resources.Distribution` | str
:param dep: If True, also return all outdated dependencies. If False, only check given dist.
:t... | [
"Return",
"a",
"dict",
"with",
"outdated",
"distributions"
] | 41c2d91f922691e31ff940f33b755d2cb64dfef8 | https://github.com/storax/upme/blob/41c2d91f922691e31ff940f33b755d2cb64dfef8/src/upme/main.py#L32-L60 |
242,732 | storax/upme | src/upme/main.py | update | def update(dist, args=None):
"""Update the given distribution and all of its dependencies
:param dist: the distribution to check
:type dist: :class:`pkg_resources.Distribution` | str
:param args: extra arguments for the install command.
this is somewhat equivalent to: pip install -U <d... | python | def update(dist, args=None):
"""Update the given distribution and all of its dependencies
:param dist: the distribution to check
:type dist: :class:`pkg_resources.Distribution` | str
:param args: extra arguments for the install command.
this is somewhat equivalent to: pip install -U <d... | [
"def",
"update",
"(",
"dist",
",",
"args",
"=",
"None",
")",
":",
"dist",
"=",
"pkg_resources",
".",
"get_distribution",
"(",
"dist",
")",
"InstallCommand",
"=",
"pip",
".",
"commands",
"[",
"'install'",
"]",
"ic",
"=",
"InstallCommand",
"(",
")",
"iargs... | Update the given distribution and all of its dependencies
:param dist: the distribution to check
:type dist: :class:`pkg_resources.Distribution` | str
:param args: extra arguments for the install command.
this is somewhat equivalent to: pip install -U <dist> args
:type args: list
:... | [
"Update",
"the",
"given",
"distribution",
"and",
"all",
"of",
"its",
"dependencies"
] | 41c2d91f922691e31ff940f33b755d2cb64dfef8 | https://github.com/storax/upme/blob/41c2d91f922691e31ff940f33b755d2cb64dfef8/src/upme/main.py#L63-L81 |
242,733 | storax/upme | src/upme/main.py | restart | def restart():
"""Restart the application the same way it was started
:returns: None
:rtype: None
:raises: SystemExit
"""
python = sys.executable
os.execl(python, python, * sys.argv) | python | def restart():
"""Restart the application the same way it was started
:returns: None
:rtype: None
:raises: SystemExit
"""
python = sys.executable
os.execl(python, python, * sys.argv) | [
"def",
"restart",
"(",
")",
":",
"python",
"=",
"sys",
".",
"executable",
"os",
".",
"execl",
"(",
"python",
",",
"python",
",",
"*",
"sys",
".",
"argv",
")"
] | Restart the application the same way it was started
:returns: None
:rtype: None
:raises: SystemExit | [
"Restart",
"the",
"application",
"the",
"same",
"way",
"it",
"was",
"started"
] | 41c2d91f922691e31ff940f33b755d2cb64dfef8 | https://github.com/storax/upme/blob/41c2d91f922691e31ff940f33b755d2cb64dfef8/src/upme/main.py#L84-L92 |
242,734 | fr33jc/bang | bang/providers/openstack/__init__.py | authenticated | def authenticated(f):
"""Decorator that authenticates to Keystone automatically."""
@wraps(f)
def new_f(self, *args, **kwargs):
if not self.nova_client.client.auth_token:
self.authenticate()
return f(self, *args, **kwargs)
return new_f | python | def authenticated(f):
"""Decorator that authenticates to Keystone automatically."""
@wraps(f)
def new_f(self, *args, **kwargs):
if not self.nova_client.client.auth_token:
self.authenticate()
return f(self, *args, **kwargs)
return new_f | [
"def",
"authenticated",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"new_f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"nova_client",
".",
"client",
".",
"auth_token",
":",
"self",
"."... | Decorator that authenticates to Keystone automatically. | [
"Decorator",
"that",
"authenticates",
"to",
"Keystone",
"automatically",
"."
] | 8f000713f88d2a9a8c1193b63ca10a6578560c16 | https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/providers/openstack/__init__.py#L438-L445 |
242,735 | thisfred/val | val/tp.py | _translate_struct | def _translate_struct(inner_dict):
"""Translate a teleport Struct into a val subschema."""
try:
optional = inner_dict['optional'].items()
required = inner_dict['required'].items()
except KeyError as ex:
raise DeserializationError("Missing key: {}".format(ex))
except AttributeErro... | python | def _translate_struct(inner_dict):
"""Translate a teleport Struct into a val subschema."""
try:
optional = inner_dict['optional'].items()
required = inner_dict['required'].items()
except KeyError as ex:
raise DeserializationError("Missing key: {}".format(ex))
except AttributeErro... | [
"def",
"_translate_struct",
"(",
"inner_dict",
")",
":",
"try",
":",
"optional",
"=",
"inner_dict",
"[",
"'optional'",
"]",
".",
"items",
"(",
")",
"required",
"=",
"inner_dict",
"[",
"'required'",
"]",
".",
"items",
"(",
")",
"except",
"KeyError",
"as",
... | Translate a teleport Struct into a val subschema. | [
"Translate",
"a",
"teleport",
"Struct",
"into",
"a",
"val",
"subschema",
"."
] | ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/tp.py#L76-L89 |
242,736 | thisfred/val | val/tp.py | _translate_composite | def _translate_composite(teleport_value):
"""Translate a composite teleport value into a val subschema."""
for key in ("Array", "Map", "Struct"):
value = teleport_value.get(key)
if value is None:
continue
return COMPOSITES[key](value)
raise DeserializationError(
... | python | def _translate_composite(teleport_value):
"""Translate a composite teleport value into a val subschema."""
for key in ("Array", "Map", "Struct"):
value = teleport_value.get(key)
if value is None:
continue
return COMPOSITES[key](value)
raise DeserializationError(
... | [
"def",
"_translate_composite",
"(",
"teleport_value",
")",
":",
"for",
"key",
"in",
"(",
"\"Array\"",
",",
"\"Map\"",
",",
"\"Struct\"",
")",
":",
"value",
"=",
"teleport_value",
".",
"get",
"(",
"key",
")",
"if",
"value",
"is",
"None",
":",
"continue",
... | Translate a composite teleport value into a val subschema. | [
"Translate",
"a",
"composite",
"teleport",
"value",
"into",
"a",
"val",
"subschema",
"."
] | ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/tp.py#L98-L107 |
242,737 | thisfred/val | val/tp.py | _translate | def _translate(teleport_value):
"""Translate a teleport value in to a val subschema."""
if isinstance(teleport_value, dict):
return _translate_composite(teleport_value)
if teleport_value in PRIMITIVES:
return PRIMITIVES[teleport_value]
raise DeserializationError(
"Could not int... | python | def _translate(teleport_value):
"""Translate a teleport value in to a val subschema."""
if isinstance(teleport_value, dict):
return _translate_composite(teleport_value)
if teleport_value in PRIMITIVES:
return PRIMITIVES[teleport_value]
raise DeserializationError(
"Could not int... | [
"def",
"_translate",
"(",
"teleport_value",
")",
":",
"if",
"isinstance",
"(",
"teleport_value",
",",
"dict",
")",
":",
"return",
"_translate_composite",
"(",
"teleport_value",
")",
"if",
"teleport_value",
"in",
"PRIMITIVES",
":",
"return",
"PRIMITIVES",
"[",
"t... | Translate a teleport value in to a val subschema. | [
"Translate",
"a",
"teleport",
"value",
"in",
"to",
"a",
"val",
"subschema",
"."
] | ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/tp.py#L110-L119 |
242,738 | thisfred/val | val/tp.py | to_val | def to_val(teleport_schema):
"""Convert a parsed teleport schema to a val schema."""
translated = _translate(teleport_schema)
if isinstance(translated, BaseSchema):
return translated
return Schema(translated) | python | def to_val(teleport_schema):
"""Convert a parsed teleport schema to a val schema."""
translated = _translate(teleport_schema)
if isinstance(translated, BaseSchema):
return translated
return Schema(translated) | [
"def",
"to_val",
"(",
"teleport_schema",
")",
":",
"translated",
"=",
"_translate",
"(",
"teleport_schema",
")",
"if",
"isinstance",
"(",
"translated",
",",
"BaseSchema",
")",
":",
"return",
"translated",
"return",
"Schema",
"(",
"translated",
")"
] | Convert a parsed teleport schema to a val schema. | [
"Convert",
"a",
"parsed",
"teleport",
"schema",
"to",
"a",
"val",
"schema",
"."
] | ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/tp.py#L122-L128 |
242,739 | thisfred/val | val/tp.py | _dict_to_teleport | def _dict_to_teleport(dict_value):
"""Convert a val schema dictionary to teleport."""
if len(dict_value) == 1:
for key, value in dict_value.items():
if key is str:
return {"Map": from_val(value)}
optional = {}
required = {}
for key, value in dict_value.items():
... | python | def _dict_to_teleport(dict_value):
"""Convert a val schema dictionary to teleport."""
if len(dict_value) == 1:
for key, value in dict_value.items():
if key is str:
return {"Map": from_val(value)}
optional = {}
required = {}
for key, value in dict_value.items():
... | [
"def",
"_dict_to_teleport",
"(",
"dict_value",
")",
":",
"if",
"len",
"(",
"dict_value",
")",
"==",
"1",
":",
"for",
"key",
",",
"value",
"in",
"dict_value",
".",
"items",
"(",
")",
":",
"if",
"key",
"is",
"str",
":",
"return",
"{",
"\"Map\"",
":",
... | Convert a val schema dictionary to teleport. | [
"Convert",
"a",
"val",
"schema",
"dictionary",
"to",
"teleport",
"."
] | ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/tp.py#L131-L148 |
242,740 | thisfred/val | val/tp.py | from_val | def from_val(val_schema):
"""Serialize a val schema to teleport."""
definition = getattr(val_schema, "definition", val_schema) if isinstance(
val_schema, BaseSchema) else val_schema
if isinstance(definition, dict):
return _dict_to_teleport(definition)
if isinstance(definition, list):
... | python | def from_val(val_schema):
"""Serialize a val schema to teleport."""
definition = getattr(val_schema, "definition", val_schema) if isinstance(
val_schema, BaseSchema) else val_schema
if isinstance(definition, dict):
return _dict_to_teleport(definition)
if isinstance(definition, list):
... | [
"def",
"from_val",
"(",
"val_schema",
")",
":",
"definition",
"=",
"getattr",
"(",
"val_schema",
",",
"\"definition\"",
",",
"val_schema",
")",
"if",
"isinstance",
"(",
"val_schema",
",",
"BaseSchema",
")",
"else",
"val_schema",
"if",
"isinstance",
"(",
"defin... | Serialize a val schema to teleport. | [
"Serialize",
"a",
"val",
"schema",
"to",
"teleport",
"."
] | ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/tp.py#L151-L167 |
242,741 | thisfred/val | val/tp.py | document | def document(schema):
"""Print a documented teleport version of the schema."""
teleport_schema = from_val(schema)
return json.dumps(teleport_schema, sort_keys=True, indent=2) | python | def document(schema):
"""Print a documented teleport version of the schema."""
teleport_schema = from_val(schema)
return json.dumps(teleport_schema, sort_keys=True, indent=2) | [
"def",
"document",
"(",
"schema",
")",
":",
"teleport_schema",
"=",
"from_val",
"(",
"schema",
")",
"return",
"json",
".",
"dumps",
"(",
"teleport_schema",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"2",
")"
] | Print a documented teleport version of the schema. | [
"Print",
"a",
"documented",
"teleport",
"version",
"of",
"the",
"schema",
"."
] | ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c | https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/tp.py#L170-L173 |
242,742 | diffeo/rejester | rejester/_registry.py | nice_identifier | def nice_identifier():
'do not use uuid.uuid4, because it can block'
big = reduce(mul, struct.unpack('<LLLL', os.urandom(16)), 1)
big = big % 2**128
return uuid.UUID(int=big).hex | python | def nice_identifier():
'do not use uuid.uuid4, because it can block'
big = reduce(mul, struct.unpack('<LLLL', os.urandom(16)), 1)
big = big % 2**128
return uuid.UUID(int=big).hex | [
"def",
"nice_identifier",
"(",
")",
":",
"big",
"=",
"reduce",
"(",
"mul",
",",
"struct",
".",
"unpack",
"(",
"'<LLLL'",
",",
"os",
".",
"urandom",
"(",
"16",
")",
")",
",",
"1",
")",
"big",
"=",
"big",
"%",
"2",
"**",
"128",
"return",
"uuid",
... | do not use uuid.uuid4, because it can block | [
"do",
"not",
"use",
"uuid",
".",
"uuid4",
"because",
"it",
"can",
"block"
] | 5438a4a18be2801d7826c46e2079ba9639d2ecb4 | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L30-L34 |
242,743 | diffeo/rejester | rejester/_registry.py | Registry._acquire_lock | def _acquire_lock(self, identifier, atime=30, ltime=5):
'''Acquire a lock for a given identifier.
If the lock cannot be obtained immediately, keep trying at random
intervals, up to 3 seconds, until `atime` has passed. Once the
lock has been obtained, continue to hold it for `ltime`.
... | python | def _acquire_lock(self, identifier, atime=30, ltime=5):
'''Acquire a lock for a given identifier.
If the lock cannot be obtained immediately, keep trying at random
intervals, up to 3 seconds, until `atime` has passed. Once the
lock has been obtained, continue to hold it for `ltime`.
... | [
"def",
"_acquire_lock",
"(",
"self",
",",
"identifier",
",",
"atime",
"=",
"30",
",",
"ltime",
"=",
"5",
")",
":",
"conn",
"=",
"redis",
".",
"Redis",
"(",
"connection_pool",
"=",
"self",
".",
"pool",
")",
"end",
"=",
"time",
".",
"time",
"(",
")",... | Acquire a lock for a given identifier.
If the lock cannot be obtained immediately, keep trying at random
intervals, up to 3 seconds, until `atime` has passed. Once the
lock has been obtained, continue to hold it for `ltime`.
:param str identifier: lock token to write
:param in... | [
"Acquire",
"a",
"lock",
"for",
"a",
"given",
"identifier",
"."
] | 5438a4a18be2801d7826c46e2079ba9639d2ecb4 | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L104-L129 |
242,744 | diffeo/rejester | rejester/_registry.py | Registry.re_acquire_lock | def re_acquire_lock(self, ltime=5):
'''Re-acquire the lock.
You must already own the lock; this is best called from
within a :meth:`lock` block.
:param int ltime: maximum time (in seconds) to own lock
:return: the session lock identifier
:raise rejester.exceptions.Envir... | python | def re_acquire_lock(self, ltime=5):
'''Re-acquire the lock.
You must already own the lock; this is best called from
within a :meth:`lock` block.
:param int ltime: maximum time (in seconds) to own lock
:return: the session lock identifier
:raise rejester.exceptions.Envir... | [
"def",
"re_acquire_lock",
"(",
"self",
",",
"ltime",
"=",
"5",
")",
":",
"conn",
"=",
"redis",
".",
"Redis",
"(",
"connection_pool",
"=",
"self",
".",
"pool",
")",
"script",
"=",
"conn",
".",
"register_script",
"(",
"'''\n if redis.call(\"get\", KEYS[1]... | Re-acquire the lock.
You must already own the lock; this is best called from
within a :meth:`lock` block.
:param int ltime: maximum time (in seconds) to own lock
:return: the session lock identifier
:raise rejester.exceptions.EnvironmentError:
if we didn't already own... | [
"Re",
"-",
"acquire",
"the",
"lock",
"."
] | 5438a4a18be2801d7826c46e2079ba9639d2ecb4 | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L131-L158 |
242,745 | diffeo/rejester | rejester/_registry.py | Registry.lock | def lock(self, atime=30, ltime=5, identifier=None):
'''Context manager to acquire the namespace global lock.
This is typically used for multi-step registry operations,
such as a read-modify-write sequence::
with registry.lock() as session:
d = session.get('dict', 'k... | python | def lock(self, atime=30, ltime=5, identifier=None):
'''Context manager to acquire the namespace global lock.
This is typically used for multi-step registry operations,
such as a read-modify-write sequence::
with registry.lock() as session:
d = session.get('dict', 'k... | [
"def",
"lock",
"(",
"self",
",",
"atime",
"=",
"30",
",",
"ltime",
"=",
"5",
",",
"identifier",
"=",
"None",
")",
":",
"if",
"identifier",
"is",
"None",
":",
"identifier",
"=",
"nice_identifier",
"(",
")",
"if",
"self",
".",
"_acquire_lock",
"(",
"id... | Context manager to acquire the namespace global lock.
This is typically used for multi-step registry operations,
such as a read-modify-write sequence::
with registry.lock() as session:
d = session.get('dict', 'key')
del d['traceback']
session... | [
"Context",
"manager",
"to",
"acquire",
"the",
"namespace",
"global",
"lock",
"."
] | 5438a4a18be2801d7826c46e2079ba9639d2ecb4 | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L186-L216 |
242,746 | diffeo/rejester | rejester/_registry.py | Registry.read_lock | def read_lock(self):
'''Find out who currently owns the namespace global lock.
This is purely a diagnostic tool. If you are trying to get
the global lock, it is better to just call :meth:`lock`, which
will atomically get the lock if possible and retry.
:return: session identif... | python | def read_lock(self):
'''Find out who currently owns the namespace global lock.
This is purely a diagnostic tool. If you are trying to get
the global lock, it is better to just call :meth:`lock`, which
will atomically get the lock if possible and retry.
:return: session identif... | [
"def",
"read_lock",
"(",
"self",
")",
":",
"return",
"redis",
".",
"Redis",
"(",
"connection_pool",
"=",
"self",
".",
"pool",
")",
".",
"get",
"(",
"self",
".",
"_lock_name",
")"
] | Find out who currently owns the namespace global lock.
This is purely a diagnostic tool. If you are trying to get
the global lock, it is better to just call :meth:`lock`, which
will atomically get the lock if possible and retry.
:return: session identifier of the lock holder, or :cons... | [
"Find",
"out",
"who",
"currently",
"owns",
"the",
"namespace",
"global",
"lock",
"."
] | 5438a4a18be2801d7826c46e2079ba9639d2ecb4 | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L218-L228 |
242,747 | diffeo/rejester | rejester/_registry.py | Registry.force_clear_lock | def force_clear_lock(self):
'''Kick out whoever currently owns the namespace global lock.
This is intended as purely a last-resort tool. If another
process has managed to get the global lock for a very long time,
or if it requested the lock with a long expiration and then
crash... | python | def force_clear_lock(self):
'''Kick out whoever currently owns the namespace global lock.
This is intended as purely a last-resort tool. If another
process has managed to get the global lock for a very long time,
or if it requested the lock with a long expiration and then
crash... | [
"def",
"force_clear_lock",
"(",
"self",
")",
":",
"return",
"redis",
".",
"Redis",
"(",
"connection_pool",
"=",
"self",
".",
"pool",
")",
".",
"delete",
"(",
"self",
".",
"_lock_name",
")"
] | Kick out whoever currently owns the namespace global lock.
This is intended as purely a last-resort tool. If another
process has managed to get the global lock for a very long time,
or if it requested the lock with a long expiration and then
crashed, this can make the system functional... | [
"Kick",
"out",
"whoever",
"currently",
"owns",
"the",
"namespace",
"global",
"lock",
"."
] | 5438a4a18be2801d7826c46e2079ba9639d2ecb4 | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L230-L241 |
242,748 | diffeo/rejester | rejester/_registry.py | Registry.update | def update(self, dict_name, mapping=None, priorities=None, expire=None,
locks=None):
'''Add mapping to a dictionary, replacing previous values
Can be called with only dict_name and expire to refresh the
expiration time.
NB: locks are only enforced if present, so nothing ... | python | def update(self, dict_name, mapping=None, priorities=None, expire=None,
locks=None):
'''Add mapping to a dictionary, replacing previous values
Can be called with only dict_name and expire to refresh the
expiration time.
NB: locks are only enforced if present, so nothing ... | [
"def",
"update",
"(",
"self",
",",
"dict_name",
",",
"mapping",
"=",
"None",
",",
"priorities",
"=",
"None",
",",
"expire",
"=",
"None",
",",
"locks",
"=",
"None",
")",
":",
"if",
"self",
".",
"_session_lock_identifier",
"is",
"None",
":",
"raise",
"Pr... | Add mapping to a dictionary, replacing previous values
Can be called with only dict_name and expire to refresh the
expiration time.
NB: locks are only enforced if present, so nothing prevents
another caller from coming in an modifying data without using
locks.
:param m... | [
"Add",
"mapping",
"to",
"a",
"dictionary",
"replacing",
"previous",
"values"
] | 5438a4a18be2801d7826c46e2079ba9639d2ecb4 | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L263-L350 |
242,749 | diffeo/rejester | rejester/_registry.py | Registry.reset_priorities | def reset_priorities(self, dict_name, priority):
'''set all priorities in dict_name to priority
:type priority: float or int
'''
if self._session_lock_identifier is None:
raise ProgrammerError('must acquire lock first')
## see comment above for script in update
... | python | def reset_priorities(self, dict_name, priority):
'''set all priorities in dict_name to priority
:type priority: float or int
'''
if self._session_lock_identifier is None:
raise ProgrammerError('must acquire lock first')
## see comment above for script in update
... | [
"def",
"reset_priorities",
"(",
"self",
",",
"dict_name",
",",
"priority",
")",
":",
"if",
"self",
".",
"_session_lock_identifier",
"is",
"None",
":",
"raise",
"ProgrammerError",
"(",
"'must acquire lock first'",
")",
"## see comment above for script in update",
"conn",... | set all priorities in dict_name to priority
:type priority: float or int | [
"set",
"all",
"priorities",
"in",
"dict_name",
"to",
"priority"
] | 5438a4a18be2801d7826c46e2079ba9639d2ecb4 | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L353-L383 |
242,750 | diffeo/rejester | rejester/_registry.py | Registry.popitem | def popitem(self, dict_name, priority_min='-inf', priority_max='+inf'):
'''Select an item and remove it.
The item comes from `dict_name`, and has the lowest score
at least `priority_min` and at most `priority_max`. If some
item is found, remove it from `dict_name` and return it.
... | python | def popitem(self, dict_name, priority_min='-inf', priority_max='+inf'):
'''Select an item and remove it.
The item comes from `dict_name`, and has the lowest score
at least `priority_min` and at most `priority_max`. If some
item is found, remove it from `dict_name` and return it.
... | [
"def",
"popitem",
"(",
"self",
",",
"dict_name",
",",
"priority_min",
"=",
"'-inf'",
",",
"priority_max",
"=",
"'+inf'",
")",
":",
"if",
"self",
".",
"_session_lock_identifier",
"is",
"None",
":",
"raise",
"ProgrammerError",
"(",
"'must acquire lock first'",
")"... | Select an item and remove it.
The item comes from `dict_name`, and has the lowest score
at least `priority_min` and at most `priority_max`. If some
item is found, remove it from `dict_name` and return it.
This runs as a single atomic operation but still requires a
session lock... | [
"Select",
"an",
"item",
"and",
"remove",
"it",
"."
] | 5438a4a18be2801d7826c46e2079ba9639d2ecb4 | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L524-L579 |
242,751 | diffeo/rejester | rejester/_registry.py | Registry.popitem_move | def popitem_move(self, from_dict, to_dict,
priority_min='-inf', priority_max='+inf'):
'''Select an item and move it to another dictionary.
The item comes from `from_dict`, and has the lowest score
at least `priority_min` and at most `priority_max`. If some
item is ... | python | def popitem_move(self, from_dict, to_dict,
priority_min='-inf', priority_max='+inf'):
'''Select an item and move it to another dictionary.
The item comes from `from_dict`, and has the lowest score
at least `priority_min` and at most `priority_max`. If some
item is ... | [
"def",
"popitem_move",
"(",
"self",
",",
"from_dict",
",",
"to_dict",
",",
"priority_min",
"=",
"'-inf'",
",",
"priority_max",
"=",
"'+inf'",
")",
":",
"if",
"self",
".",
"_session_lock_identifier",
"is",
"None",
":",
"raise",
"ProgrammerError",
"(",
"'must ac... | Select an item and move it to another dictionary.
The item comes from `from_dict`, and has the lowest score
at least `priority_min` and at most `priority_max`. If some
item is found, remove it from `from_dict`, add it to `to_dict`,
and return it.
This runs as a single atomic o... | [
"Select",
"an",
"item",
"and",
"move",
"it",
"to",
"another",
"dictionary",
"."
] | 5438a4a18be2801d7826c46e2079ba9639d2ecb4 | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L581-L650 |
242,752 | diffeo/rejester | rejester/_registry.py | Registry.move | def move(self, from_dict, to_dict, mapping, priority=None):
'''Move keys between dictionaries, possibly with changes.
Every key in `mapping` is removed from `from_dict`, and added to
`to_dict` with its corresponding value. The priority will be
`priority`, if specified, or else its curr... | python | def move(self, from_dict, to_dict, mapping, priority=None):
'''Move keys between dictionaries, possibly with changes.
Every key in `mapping` is removed from `from_dict`, and added to
`to_dict` with its corresponding value. The priority will be
`priority`, if specified, or else its curr... | [
"def",
"move",
"(",
"self",
",",
"from_dict",
",",
"to_dict",
",",
"mapping",
",",
"priority",
"=",
"None",
")",
":",
"items",
"=",
"[",
"]",
"## This flattens the dictionary into a list",
"for",
"key",
",",
"value",
"in",
"mapping",
".",
"iteritems",
"(",
... | Move keys between dictionaries, possibly with changes.
Every key in `mapping` is removed from `from_dict`, and added to
`to_dict` with its corresponding value. The priority will be
`priority`, if specified, or else its current priority.
This operation on its own is atomic and does not... | [
"Move",
"keys",
"between",
"dictionaries",
"possibly",
"with",
"changes",
"."
] | 5438a4a18be2801d7826c46e2079ba9639d2ecb4 | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L652-L725 |
242,753 | diffeo/rejester | rejester/_registry.py | Registry.move_all | def move_all(self, from_dict, to_dict):
'''Move everything from one dictionary to another.
This can be expensive if the source dictionary is large.
This always requires a session lock.
:param str from_dict: source dictionary
:param str to_dict: destination dictionary
... | python | def move_all(self, from_dict, to_dict):
'''Move everything from one dictionary to another.
This can be expensive if the source dictionary is large.
This always requires a session lock.
:param str from_dict: source dictionary
:param str to_dict: destination dictionary
... | [
"def",
"move_all",
"(",
"self",
",",
"from_dict",
",",
"to_dict",
")",
":",
"if",
"self",
".",
"_session_lock_identifier",
"is",
"None",
":",
"raise",
"ProgrammerError",
"(",
"'must acquire lock first'",
")",
"conn",
"=",
"redis",
".",
"Redis",
"(",
"connectio... | Move everything from one dictionary to another.
This can be expensive if the source dictionary is large.
This always requires a session lock.
:param str from_dict: source dictionary
:param str to_dict: destination dictionary | [
"Move",
"everything",
"from",
"one",
"dictionary",
"to",
"another",
"."
] | 5438a4a18be2801d7826c46e2079ba9639d2ecb4 | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L728-L772 |
242,754 | diffeo/rejester | rejester/_registry.py | Registry.pull | def pull(self, dict_name):
'''Get the entire contents of a single dictionary.
This operates without a session lock, but is still atomic. In
particular this will run even if someone else holds a session
lock and you do not.
This is only suitable for "small" dictionaries; if you... | python | def pull(self, dict_name):
'''Get the entire contents of a single dictionary.
This operates without a session lock, but is still atomic. In
particular this will run even if someone else holds a session
lock and you do not.
This is only suitable for "small" dictionaries; if you... | [
"def",
"pull",
"(",
"self",
",",
"dict_name",
")",
":",
"dict_name",
"=",
"self",
".",
"_namespace",
"(",
"dict_name",
")",
"conn",
"=",
"redis",
".",
"Redis",
"(",
"connection_pool",
"=",
"self",
".",
"pool",
")",
"res",
"=",
"conn",
".",
"hgetall",
... | Get the entire contents of a single dictionary.
This operates without a session lock, but is still atomic. In
particular this will run even if someone else holds a session
lock and you do not.
This is only suitable for "small" dictionaries; if you have
hundreds of thousands of... | [
"Get",
"the",
"entire",
"contents",
"of",
"a",
"single",
"dictionary",
"."
] | 5438a4a18be2801d7826c46e2079ba9639d2ecb4 | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L775-L796 |
242,755 | diffeo/rejester | rejester/_registry.py | Registry.filter | def filter(self, dict_name, priority_min='-inf', priority_max='+inf',
start=0, limit=None):
'''Get a subset of a dictionary.
This retrieves only keys with priority scores greater than or
equal to `priority_min` and less than or equal to `priority_max`.
Of those keys, it s... | python | def filter(self, dict_name, priority_min='-inf', priority_max='+inf',
start=0, limit=None):
'''Get a subset of a dictionary.
This retrieves only keys with priority scores greater than or
equal to `priority_min` and less than or equal to `priority_max`.
Of those keys, it s... | [
"def",
"filter",
"(",
"self",
",",
"dict_name",
",",
"priority_min",
"=",
"'-inf'",
",",
"priority_max",
"=",
"'+inf'",
",",
"start",
"=",
"0",
",",
"limit",
"=",
"None",
")",
":",
"conn",
"=",
"redis",
".",
"Redis",
"(",
"connection_pool",
"=",
"self"... | Get a subset of a dictionary.
This retrieves only keys with priority scores greater than or
equal to `priority_min` and less than or equal to `priority_max`.
Of those keys, it skips the first `start` ones, and then returns
at most `limit` keys.
With default parameters, this ret... | [
"Get",
"a",
"subset",
"of",
"a",
"dictionary",
"."
] | 5438a4a18be2801d7826c46e2079ba9639d2ecb4 | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L798-L865 |
242,756 | diffeo/rejester | rejester/_registry.py | Registry.set_1to1 | def set_1to1(self, dict_name, key1, key2):
'''Set two keys to be equal in a 1-to-1 mapping.
Within `dict_name`, `key1` is set to `key2`, and `key2` is set
to `key1`.
This always requires a session lock.
:param str dict_name: dictionary to update
:param str key1: first ... | python | def set_1to1(self, dict_name, key1, key2):
'''Set two keys to be equal in a 1-to-1 mapping.
Within `dict_name`, `key1` is set to `key2`, and `key2` is set
to `key1`.
This always requires a session lock.
:param str dict_name: dictionary to update
:param str key1: first ... | [
"def",
"set_1to1",
"(",
"self",
",",
"dict_name",
",",
"key1",
",",
"key2",
")",
":",
"if",
"self",
".",
"_session_lock_identifier",
"is",
"None",
":",
"raise",
"ProgrammerError",
"(",
"'must acquire lock first'",
")",
"conn",
"=",
"redis",
".",
"Redis",
"("... | Set two keys to be equal in a 1-to-1 mapping.
Within `dict_name`, `key1` is set to `key2`, and `key2` is set
to `key1`.
This always requires a session lock.
:param str dict_name: dictionary to update
:param str key1: first key/value
:param str key2: second key/value | [
"Set",
"two",
"keys",
"to",
"be",
"equal",
"in",
"a",
"1",
"-",
"to",
"-",
"1",
"mapping",
"."
] | 5438a4a18be2801d7826c46e2079ba9639d2ecb4 | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L867-L899 |
242,757 | diffeo/rejester | rejester/_registry.py | Registry.get | def get(self, dict_name, key, default=None, include_priority=False):
'''Get the value for a specific key in a specific dictionary.
If `include_priority` is false (default), returns the value
for that key, or `default` (defaults to :const:`None`) if it
is absent. If `include_priority` i... | python | def get(self, dict_name, key, default=None, include_priority=False):
'''Get the value for a specific key in a specific dictionary.
If `include_priority` is false (default), returns the value
for that key, or `default` (defaults to :const:`None`) if it
is absent. If `include_priority` i... | [
"def",
"get",
"(",
"self",
",",
"dict_name",
",",
"key",
",",
"default",
"=",
"None",
",",
"include_priority",
"=",
"False",
")",
":",
"dict_name",
"=",
"self",
".",
"_namespace",
"(",
"dict_name",
")",
"key",
"=",
"self",
".",
"_encode",
"(",
"key",
... | Get the value for a specific key in a specific dictionary.
If `include_priority` is false (default), returns the value
for that key, or `default` (defaults to :const:`None`) if it
is absent. If `include_priority` is true, returns a pair of
the value and its priority, or of `default` an... | [
"Get",
"the",
"value",
"for",
"a",
"specific",
"key",
"in",
"a",
"specific",
"dictionary",
"."
] | 5438a4a18be2801d7826c46e2079ba9639d2ecb4 | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L901-L934 |
242,758 | diffeo/rejester | rejester/_registry.py | Registry.set | def set(self, dict_name, key, value, priority=None):
'''Set a single value for a single key.
This requires a session lock.
:param str dict_name: name of the dictionary to update
:param str key: key to update
:param str value: value to assign to `key`
:param int priority... | python | def set(self, dict_name, key, value, priority=None):
'''Set a single value for a single key.
This requires a session lock.
:param str dict_name: name of the dictionary to update
:param str key: key to update
:param str value: value to assign to `key`
:param int priority... | [
"def",
"set",
"(",
"self",
",",
"dict_name",
",",
"key",
",",
"value",
",",
"priority",
"=",
"None",
")",
":",
"if",
"priority",
"is",
"not",
"None",
":",
"priorities",
"=",
"{",
"key",
":",
"priority",
"}",
"else",
":",
"priorities",
"=",
"None",
... | Set a single value for a single key.
This requires a session lock.
:param str dict_name: name of the dictionary to update
:param str key: key to update
:param str value: value to assign to `key`
:param int priority: priority score for the value (if any) | [
"Set",
"a",
"single",
"value",
"for",
"a",
"single",
"key",
"."
] | 5438a4a18be2801d7826c46e2079ba9639d2ecb4 | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L936-L951 |
242,759 | diffeo/rejester | rejester/_registry.py | Registry.delete | def delete(self, dict_name):
'''Delete an entire dictionary.
This operation on its own is atomic and does not require a
session lock, but a session lock is honored.
:param str dict_name: name of the dictionary to delete
:raises rejester.exceptions.LockError: if called with a se... | python | def delete(self, dict_name):
'''Delete an entire dictionary.
This operation on its own is atomic and does not require a
session lock, but a session lock is honored.
:param str dict_name: name of the dictionary to delete
:raises rejester.exceptions.LockError: if called with a se... | [
"def",
"delete",
"(",
"self",
",",
"dict_name",
")",
":",
"conn",
"=",
"redis",
".",
"Redis",
"(",
"connection_pool",
"=",
"self",
".",
"pool",
")",
"script",
"=",
"conn",
".",
"register_script",
"(",
"'''\n if redis.call(\"get\", KEYS[1]) == ARGV[1]\n ... | Delete an entire dictionary.
This operation on its own is atomic and does not require a
session lock, but a session lock is honored.
:param str dict_name: name of the dictionary to delete
:raises rejester.exceptions.LockError: if called with a session
lock, but the system doe... | [
"Delete",
"an",
"entire",
"dictionary",
"."
] | 5438a4a18be2801d7826c46e2079ba9639d2ecb4 | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L953-L979 |
242,760 | diffeo/rejester | rejester/_registry.py | Registry.direct_call | def direct_call(self, *args):
'''execute a direct redis call against this Registry instances
namespaced keys. This is low level is should only be used for
prototyping.
arg[0] = redis function
arg[1] = key --- will be namespaced before execution
args[2:] = args to functi... | python | def direct_call(self, *args):
'''execute a direct redis call against this Registry instances
namespaced keys. This is low level is should only be used for
prototyping.
arg[0] = redis function
arg[1] = key --- will be namespaced before execution
args[2:] = args to functi... | [
"def",
"direct_call",
"(",
"self",
",",
"*",
"args",
")",
":",
"conn",
"=",
"redis",
".",
"Redis",
"(",
"connection_pool",
"=",
"self",
".",
"pool",
")",
"command",
"=",
"args",
"[",
"0",
"]",
"key",
"=",
"self",
".",
"_namespace",
"(",
"args",
"["... | execute a direct redis call against this Registry instances
namespaced keys. This is low level is should only be used for
prototyping.
arg[0] = redis function
arg[1] = key --- will be namespaced before execution
args[2:] = args to function
:returns raw return value of ... | [
"execute",
"a",
"direct",
"redis",
"call",
"against",
"this",
"Registry",
"instances",
"namespaced",
"keys",
".",
"This",
"is",
"low",
"level",
"is",
"should",
"only",
"be",
"used",
"for",
"prototyping",
"."
] | 5438a4a18be2801d7826c46e2079ba9639d2ecb4 | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L981-L999 |
242,761 | tslight/yorn | yorn/ask.py | ask | def ask(question):
'''
Infinite loop to get yes or no answer or quit the script.
'''
while True:
ans = input(question)
al = ans.lower()
if match('^y(es)?$', al):
return True
elif match('^n(o)?$', al):
return False
elif match('^q(uit)?$', al... | python | def ask(question):
'''
Infinite loop to get yes or no answer or quit the script.
'''
while True:
ans = input(question)
al = ans.lower()
if match('^y(es)?$', al):
return True
elif match('^n(o)?$', al):
return False
elif match('^q(uit)?$', al... | [
"def",
"ask",
"(",
"question",
")",
":",
"while",
"True",
":",
"ans",
"=",
"input",
"(",
"question",
")",
"al",
"=",
"ans",
".",
"lower",
"(",
")",
"if",
"match",
"(",
"'^y(es)?$'",
",",
"al",
")",
":",
"return",
"True",
"elif",
"match",
"(",
"'^... | Infinite loop to get yes or no answer or quit the script. | [
"Infinite",
"loop",
"to",
"get",
"yes",
"or",
"no",
"answer",
"or",
"quit",
"the",
"script",
"."
] | be577261065a53d3f4a585038c597c72950aa5ce | https://github.com/tslight/yorn/blob/be577261065a53d3f4a585038c597c72950aa5ce/yorn/ask.py#L13-L32 |
242,762 | fangpenlin/pyramid-handy | pyramid_handy/tweens/basic_auth.py | get_remote_user | def get_remote_user(request):
"""Parse basic HTTP_AUTHORIZATION and return user name
"""
if 'HTTP_AUTHORIZATION' not in request.environ:
return
authorization = request.environ['HTTP_AUTHORIZATION']
try:
authmeth, auth = authorization.split(' ', 1)
except ValueError: # not enoug... | python | def get_remote_user(request):
"""Parse basic HTTP_AUTHORIZATION and return user name
"""
if 'HTTP_AUTHORIZATION' not in request.environ:
return
authorization = request.environ['HTTP_AUTHORIZATION']
try:
authmeth, auth = authorization.split(' ', 1)
except ValueError: # not enoug... | [
"def",
"get_remote_user",
"(",
"request",
")",
":",
"if",
"'HTTP_AUTHORIZATION'",
"not",
"in",
"request",
".",
"environ",
":",
"return",
"authorization",
"=",
"request",
".",
"environ",
"[",
"'HTTP_AUTHORIZATION'",
"]",
"try",
":",
"authmeth",
",",
"auth",
"="... | Parse basic HTTP_AUTHORIZATION and return user name | [
"Parse",
"basic",
"HTTP_AUTHORIZATION",
"and",
"return",
"user",
"name"
] | e3cbc19224ab1f0a14aab556990bceabd2d1f658 | https://github.com/fangpenlin/pyramid-handy/blob/e3cbc19224ab1f0a14aab556990bceabd2d1f658/pyramid_handy/tweens/basic_auth.py#L7-L28 |
242,763 | fangpenlin/pyramid-handy | pyramid_handy/tweens/basic_auth.py | basic_auth_tween_factory | def basic_auth_tween_factory(handler, registry):
"""Do basic authentication, parse HTTP_AUTHORIZATION and set remote_user
variable to request
"""
def basic_auth_tween(request):
remote_user = get_remote_user(request)
if remote_user is not None:
request.environ['REMOTE_USER'] ... | python | def basic_auth_tween_factory(handler, registry):
"""Do basic authentication, parse HTTP_AUTHORIZATION and set remote_user
variable to request
"""
def basic_auth_tween(request):
remote_user = get_remote_user(request)
if remote_user is not None:
request.environ['REMOTE_USER'] ... | [
"def",
"basic_auth_tween_factory",
"(",
"handler",
",",
"registry",
")",
":",
"def",
"basic_auth_tween",
"(",
"request",
")",
":",
"remote_user",
"=",
"get_remote_user",
"(",
"request",
")",
"if",
"remote_user",
"is",
"not",
"None",
":",
"request",
".",
"envir... | Do basic authentication, parse HTTP_AUTHORIZATION and set remote_user
variable to request | [
"Do",
"basic",
"authentication",
"parse",
"HTTP_AUTHORIZATION",
"and",
"set",
"remote_user",
"variable",
"to",
"request"
] | e3cbc19224ab1f0a14aab556990bceabd2d1f658 | https://github.com/fangpenlin/pyramid-handy/blob/e3cbc19224ab1f0a14aab556990bceabd2d1f658/pyramid_handy/tweens/basic_auth.py#L31-L41 |
242,764 | ryanjdillon/pylleo | pylleo/calapp/main.py | plot_triaxial | def plot_triaxial(height, width, tools):
'''Plot pandas dataframe containing an x, y, and z column'''
import bokeh.plotting
p = bokeh.plotting.figure(x_axis_type='datetime',
plot_height=height,
plot_width=width,
title... | python | def plot_triaxial(height, width, tools):
'''Plot pandas dataframe containing an x, y, and z column'''
import bokeh.plotting
p = bokeh.plotting.figure(x_axis_type='datetime',
plot_height=height,
plot_width=width,
title... | [
"def",
"plot_triaxial",
"(",
"height",
",",
"width",
",",
"tools",
")",
":",
"import",
"bokeh",
".",
"plotting",
"p",
"=",
"bokeh",
".",
"plotting",
".",
"figure",
"(",
"x_axis_type",
"=",
"'datetime'",
",",
"plot_height",
"=",
"height",
",",
"plot_width",... | Plot pandas dataframe containing an x, y, and z column | [
"Plot",
"pandas",
"dataframe",
"containing",
"an",
"x",
"y",
"and",
"z",
"column"
] | b9b999fef19eaeccce4f207ab1b6198287c1bfec | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/calapp/main.py#L18-L43 |
242,765 | ryanjdillon/pylleo | pylleo/calapp/main.py | load_data | def load_data(path_dir):
'''Load data, directory parameters, and accelerometer parameter names
Args
----
path_dir: str
Path to the data directory
Returns
-------
data: pandas.DataFrame
Experiment data
params_tag: dict
A dictionary of parameters parsed from the d... | python | def load_data(path_dir):
'''Load data, directory parameters, and accelerometer parameter names
Args
----
path_dir: str
Path to the data directory
Returns
-------
data: pandas.DataFrame
Experiment data
params_tag: dict
A dictionary of parameters parsed from the d... | [
"def",
"load_data",
"(",
"path_dir",
")",
":",
"import",
"os",
"import",
"pylleo",
"exp_name",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path_dir",
")",
"[",
"1",
"]",
"params_tag",
"=",
"pylleo",
".",
"utils",
".",
"parse_experiment_params",
"(",
"exp... | Load data, directory parameters, and accelerometer parameter names
Args
----
path_dir: str
Path to the data directory
Returns
-------
data: pandas.DataFrame
Experiment data
params_tag: dict
A dictionary of parameters parsed from the directory name
params_data: l... | [
"Load",
"data",
"directory",
"parameters",
"and",
"accelerometer",
"parameter",
"names"
] | b9b999fef19eaeccce4f207ab1b6198287c1bfec | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/calapp/main.py#L46-L79 |
242,766 | ryanjdillon/pylleo | pylleo/calapp/main.py | callback_checkbox | def callback_checkbox(attr, old, new):
'''Update visible data from parameters selectin in the CheckboxSelect'''
import numpy
for i in range(len(lines)):
lines[i].visible = i in param_checkbox.active
scats[i].visible = i in param_checkbox.active
return None | python | def callback_checkbox(attr, old, new):
'''Update visible data from parameters selectin in the CheckboxSelect'''
import numpy
for i in range(len(lines)):
lines[i].visible = i in param_checkbox.active
scats[i].visible = i in param_checkbox.active
return None | [
"def",
"callback_checkbox",
"(",
"attr",
",",
"old",
",",
"new",
")",
":",
"import",
"numpy",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"lines",
")",
")",
":",
"lines",
"[",
"i",
"]",
".",
"visible",
"=",
"i",
"in",
"param_checkbox",
".",
"active... | Update visible data from parameters selectin in the CheckboxSelect | [
"Update",
"visible",
"data",
"from",
"parameters",
"selectin",
"in",
"the",
"CheckboxSelect"
] | b9b999fef19eaeccce4f207ab1b6198287c1bfec | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/calapp/main.py#L179-L187 |
242,767 | pablorecio/Cobaya | src/cobaya/password.py | get_password | def get_password(config):
"""Returns the password for a remote server
It tries to fetch the password from the following
locations in this order:
1. config file [remote] section, password option
2. GNOME keyring
3. interactively, from the user
"""
password = config.get_option('remote... | python | def get_password(config):
"""Returns the password for a remote server
It tries to fetch the password from the following
locations in this order:
1. config file [remote] section, password option
2. GNOME keyring
3. interactively, from the user
"""
password = config.get_option('remote... | [
"def",
"get_password",
"(",
"config",
")",
":",
"password",
"=",
"config",
".",
"get_option",
"(",
"'remote.password'",
")",
"if",
"password",
"==",
"''",
":",
"user",
"=",
"config",
".",
"get_option",
"(",
"'remote.user'",
")",
"url",
"=",
"config",
".",
... | Returns the password for a remote server
It tries to fetch the password from the following
locations in this order:
1. config file [remote] section, password option
2. GNOME keyring
3. interactively, from the user | [
"Returns",
"the",
"password",
"for",
"a",
"remote",
"server"
] | 70b107dea5f31f51e7b6738da3c2a1df5b9f3f20 | https://github.com/pablorecio/Cobaya/blob/70b107dea5f31f51e7b6738da3c2a1df5b9f3f20/src/cobaya/password.py#L34-L61 |
242,768 | gear11/pypelogs | pypelogs.py | process | def process(specs):
"""
Executes the passed in list of specs
"""
pout, pin = chain_specs(specs)
LOG.info("Processing")
sw = StopWatch().start()
r = pout.process(pin)
if r:
print(r)
LOG.info("Finished in %s", sw.read()) | python | def process(specs):
"""
Executes the passed in list of specs
"""
pout, pin = chain_specs(specs)
LOG.info("Processing")
sw = StopWatch().start()
r = pout.process(pin)
if r:
print(r)
LOG.info("Finished in %s", sw.read()) | [
"def",
"process",
"(",
"specs",
")",
":",
"pout",
",",
"pin",
"=",
"chain_specs",
"(",
"specs",
")",
"LOG",
".",
"info",
"(",
"\"Processing\"",
")",
"sw",
"=",
"StopWatch",
"(",
")",
".",
"start",
"(",
")",
"r",
"=",
"pout",
".",
"process",
"(",
... | Executes the passed in list of specs | [
"Executes",
"the",
"passed",
"in",
"list",
"of",
"specs"
] | da5dc0fee5373a4be294798b5e32cd0a803d8bbe | https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypelogs.py#L33-L43 |
242,769 | unfoldingWord-dev/tx-shared-tools | general_tools/smartquotes.py | smartquotes | def smartquotes(text):
"""
Runs text through pandoc for smartquote correction.
"""
command = shlex.split('pandoc --smart -t plain')
com = Popen(command, shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE)
out, err = com.communicate(text.encode('utf-8'))
com_out = out.decode('utf-8')
text ... | python | def smartquotes(text):
"""
Runs text through pandoc for smartquote correction.
"""
command = shlex.split('pandoc --smart -t plain')
com = Popen(command, shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE)
out, err = com.communicate(text.encode('utf-8'))
com_out = out.decode('utf-8')
text ... | [
"def",
"smartquotes",
"(",
"text",
")",
":",
"command",
"=",
"shlex",
".",
"split",
"(",
"'pandoc --smart -t plain'",
")",
"com",
"=",
"Popen",
"(",
"command",
",",
"shell",
"=",
"False",
",",
"stdin",
"=",
"PIPE",
",",
"stdout",
"=",
"PIPE",
",",
"std... | Runs text through pandoc for smartquote correction. | [
"Runs",
"text",
"through",
"pandoc",
"for",
"smartquote",
"correction",
"."
] | 6ff5cd024e1ab54c53dd1bc788bbc78e2358772e | https://github.com/unfoldingWord-dev/tx-shared-tools/blob/6ff5cd024e1ab54c53dd1bc788bbc78e2358772e/general_tools/smartquotes.py#L22-L31 |
242,770 | GreenBankObservatory/django-resetdb | django_resetdb/util.py | shell | def shell(cmd, **kwargs):
"""Execute cmd, check exit code, return stdout"""
logger.debug("$ %s", cmd)
return subprocess.check_output(cmd, shell=True, **kwargs) | python | def shell(cmd, **kwargs):
"""Execute cmd, check exit code, return stdout"""
logger.debug("$ %s", cmd)
return subprocess.check_output(cmd, shell=True, **kwargs) | [
"def",
"shell",
"(",
"cmd",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"debug",
"(",
"\"$ %s\"",
",",
"cmd",
")",
"return",
"subprocess",
".",
"check_output",
"(",
"cmd",
",",
"shell",
"=",
"True",
",",
"*",
"*",
"kwargs",
")"
] | Execute cmd, check exit code, return stdout | [
"Execute",
"cmd",
"check",
"exit",
"code",
"return",
"stdout"
] | 767bddacb53823bb003e2abebfe8139a14b843f7 | https://github.com/GreenBankObservatory/django-resetdb/blob/767bddacb53823bb003e2abebfe8139a14b843f7/django_resetdb/util.py#L16-L19 |
242,771 | vinu76jsr/pipsort | deploy.py | main | def main(argv=None):
""" Script execution.
The project repo will be cloned to a temporary directory, and the desired
branch, tag, or commit will be checked out. Then, the application will be
installed into a self-contained virtualenv environment.
"""
@contextmanager
def tmpdir():
"... | python | def main(argv=None):
""" Script execution.
The project repo will be cloned to a temporary directory, and the desired
branch, tag, or commit will be checked out. Then, the application will be
installed into a self-contained virtualenv environment.
"""
@contextmanager
def tmpdir():
"... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"@",
"contextmanager",
"def",
"tmpdir",
"(",
")",
":",
"\"\"\" Create a self-deleting temporary directory. \"\"\"",
"path",
"=",
"mkdtemp",
"(",
")",
"try",
":",
"yield",
"path",
"finally",
":",
"rmtree",
"(",... | Script execution.
The project repo will be cloned to a temporary directory, and the desired
branch, tag, or commit will be checked out. Then, the application will be
installed into a self-contained virtualenv environment. | [
"Script",
"execution",
"."
] | 71ead1269de85ee0255741390bf1da85d81b7d16 | https://github.com/vinu76jsr/pipsort/blob/71ead1269de85ee0255741390bf1da85d81b7d16/deploy.py#L44-L88 |
242,772 | krukas/Trionyx | trionyx/trionyx/models.py | UserManager._create_user | def _create_user(self, email, password, is_superuser, **extra_fields):
"""Create new user"""
now = timezone.now()
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(
email=email,
... | python | def _create_user(self, email, password, is_superuser, **extra_fields):
"""Create new user"""
now = timezone.now()
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(
email=email,
... | [
"def",
"_create_user",
"(",
"self",
",",
"email",
",",
"password",
",",
"is_superuser",
",",
"*",
"*",
"extra_fields",
")",
":",
"now",
"=",
"timezone",
".",
"now",
"(",
")",
"if",
"not",
"email",
":",
"raise",
"ValueError",
"(",
"'The given email must be ... | Create new user | [
"Create",
"new",
"user"
] | edac132cc0797190153f2e60bc7e88cb50e80da6 | https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/models.py#L19-L35 |
242,773 | krukas/Trionyx | trionyx/trionyx/models.py | User.get_full_name | def get_full_name(self):
"""Get full username if no name is set email is given"""
if self.first_name and self.last_name:
return "{} {}".format(self.first_name, self.last_name)
return self.email | python | def get_full_name(self):
"""Get full username if no name is set email is given"""
if self.first_name and self.last_name:
return "{} {}".format(self.first_name, self.last_name)
return self.email | [
"def",
"get_full_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"first_name",
"and",
"self",
".",
"last_name",
":",
"return",
"\"{} {}\"",
".",
"format",
"(",
"self",
".",
"first_name",
",",
"self",
".",
"last_name",
")",
"return",
"self",
".",
"email"... | Get full username if no name is set email is given | [
"Get",
"full",
"username",
"if",
"no",
"name",
"is",
"set",
"email",
"is",
"given"
] | edac132cc0797190153f2e60bc7e88cb50e80da6 | https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/models.py#L64-L68 |
242,774 | krukas/Trionyx | trionyx/trionyx/models.py | UserAttributeManager.set_attribute | def set_attribute(self, code, value):
"""Set attribute for user"""
attr, _ = self.get_or_create(code=code)
attr.value = value
attr.save() | python | def set_attribute(self, code, value):
"""Set attribute for user"""
attr, _ = self.get_or_create(code=code)
attr.value = value
attr.save() | [
"def",
"set_attribute",
"(",
"self",
",",
"code",
",",
"value",
")",
":",
"attr",
",",
"_",
"=",
"self",
".",
"get_or_create",
"(",
"code",
"=",
"code",
")",
"attr",
".",
"value",
"=",
"value",
"attr",
".",
"save",
"(",
")"
] | Set attribute for user | [
"Set",
"attribute",
"for",
"user"
] | edac132cc0797190153f2e60bc7e88cb50e80da6 | https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/models.py#L84-L88 |
242,775 | krukas/Trionyx | trionyx/trionyx/models.py | UserAttributeManager.get_attribute | def get_attribute(self, code, default=None):
"""Get attribute for user"""
try:
return self.get(code=code).value
except models.ObjectDoesNotExist:
return default | python | def get_attribute(self, code, default=None):
"""Get attribute for user"""
try:
return self.get(code=code).value
except models.ObjectDoesNotExist:
return default | [
"def",
"get_attribute",
"(",
"self",
",",
"code",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"get",
"(",
"code",
"=",
"code",
")",
".",
"value",
"except",
"models",
".",
"ObjectDoesNotExist",
":",
"return",
"default"
] | Get attribute for user | [
"Get",
"attribute",
"for",
"user"
] | edac132cc0797190153f2e60bc7e88cb50e80da6 | https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/models.py#L90-L95 |
242,776 | musicmetric/mmpy | src/chart.py | Chart.next | def next(self):
"""
fetch the chart identified by this chart's next_id attribute
if the next_id is either null or not present for this chart return None
returns the new chart instance on sucess"""
try:
if self.next_id:
return Chart(self.next_id)
... | python | def next(self):
"""
fetch the chart identified by this chart's next_id attribute
if the next_id is either null or not present for this chart return None
returns the new chart instance on sucess"""
try:
if self.next_id:
return Chart(self.next_id)
... | [
"def",
"next",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"next_id",
":",
"return",
"Chart",
"(",
"self",
".",
"next_id",
")",
"else",
":",
"log",
".",
"debug",
"(",
"'attempted to get next chart, but none was found'",
")",
"return",
"except",
"... | fetch the chart identified by this chart's next_id attribute
if the next_id is either null or not present for this chart return None
returns the new chart instance on sucess | [
"fetch",
"the",
"chart",
"identified",
"by",
"this",
"chart",
"s",
"next_id",
"attribute",
"if",
"the",
"next_id",
"is",
"either",
"null",
"or",
"not",
"present",
"for",
"this",
"chart",
"return",
"None",
"returns",
"the",
"new",
"chart",
"instance",
"on",
... | 2b5d975c61f9ea8c7f19f76a90b59771833ef881 | https://github.com/musicmetric/mmpy/blob/2b5d975c61f9ea8c7f19f76a90b59771833ef881/src/chart.py#L69-L83 |
242,777 | musicmetric/mmpy | src/chart.py | Chart.previous | def previous(self):
"""
fetch the chart identified by this chart's previous_id attribute
if the previous_id is either null or not present for this chart return None
returns the new chart instance on sucess"""
try:
if self.previous_id:
return Ch... | python | def previous(self):
"""
fetch the chart identified by this chart's previous_id attribute
if the previous_id is either null or not present for this chart return None
returns the new chart instance on sucess"""
try:
if self.previous_id:
return Ch... | [
"def",
"previous",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"previous_id",
":",
"return",
"Chart",
"(",
"self",
".",
"previous_id",
")",
"else",
":",
"log",
".",
"debug",
"(",
"'attempted to get previous chart, but none was found'",
")",
"return",... | fetch the chart identified by this chart's previous_id attribute
if the previous_id is either null or not present for this chart return None
returns the new chart instance on sucess | [
"fetch",
"the",
"chart",
"identified",
"by",
"this",
"chart",
"s",
"previous_id",
"attribute",
"if",
"the",
"previous_id",
"is",
"either",
"null",
"or",
"not",
"present",
"for",
"this",
"chart",
"return",
"None",
"returns",
"the",
"new",
"chart",
"instance",
... | 2b5d975c61f9ea8c7f19f76a90b59771833ef881 | https://github.com/musicmetric/mmpy/blob/2b5d975c61f9ea8c7f19f76a90b59771833ef881/src/chart.py#L85-L99 |
242,778 | musicmetric/mmpy | src/chart.py | Chart.now | def now(self):
"""
fetch the chart identified by this chart's now_id attribute
if the now_id is either null or not present for this chart return None
returns the new chart instance on sucess"""
try:
if self.now_id:
return Chart(self.now_id)
... | python | def now(self):
"""
fetch the chart identified by this chart's now_id attribute
if the now_id is either null or not present for this chart return None
returns the new chart instance on sucess"""
try:
if self.now_id:
return Chart(self.now_id)
... | [
"def",
"now",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"now_id",
":",
"return",
"Chart",
"(",
"self",
".",
"now_id",
")",
"else",
":",
"log",
".",
"debug",
"(",
"'attempted to get current chart, but none was found'",
")",
"return",
"except",
"... | fetch the chart identified by this chart's now_id attribute
if the now_id is either null or not present for this chart return None
returns the new chart instance on sucess | [
"fetch",
"the",
"chart",
"identified",
"by",
"this",
"chart",
"s",
"now_id",
"attribute",
"if",
"the",
"now_id",
"is",
"either",
"null",
"or",
"not",
"present",
"for",
"this",
"chart",
"return",
"None",
"returns",
"the",
"new",
"chart",
"instance",
"on",
"... | 2b5d975c61f9ea8c7f19f76a90b59771833ef881 | https://github.com/musicmetric/mmpy/blob/2b5d975c61f9ea8c7f19f76a90b59771833ef881/src/chart.py#L101-L115 |
242,779 | MacHu-GWU/angora-project | angora/dtypes/dicttree.py | DictTree.initial | def initial(key, **kwarg):
"""Create an empty dicttree.
The root node has a special attribute "_rootname".
Because root node is the only dictionary doesn't have key.
So we assign the key as a special attribute.
Usage::
>>> from weatherlab.lib.dtypes.dicttree impor... | python | def initial(key, **kwarg):
"""Create an empty dicttree.
The root node has a special attribute "_rootname".
Because root node is the only dictionary doesn't have key.
So we assign the key as a special attribute.
Usage::
>>> from weatherlab.lib.dtypes.dicttree impor... | [
"def",
"initial",
"(",
"key",
",",
"*",
"*",
"kwarg",
")",
":",
"d",
"=",
"dict",
"(",
")",
"DictTree",
".",
"setattr",
"(",
"d",
",",
"_rootname",
"=",
"key",
",",
"*",
"*",
"kwarg",
")",
"return",
"d"
] | Create an empty dicttree.
The root node has a special attribute "_rootname".
Because root node is the only dictionary doesn't have key.
So we assign the key as a special attribute.
Usage::
>>> from weatherlab.lib.dtypes.dicttree import DictTree as DT
>>> d = D... | [
"Create",
"an",
"empty",
"dicttree",
"."
] | 689a60da51cd88680ddbe26e28dbe81e6b01d275 | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dtypes/dicttree.py#L149-L165 |
242,780 | MacHu-GWU/angora-project | angora/dtypes/dicttree.py | DictTree.setattr | def setattr(d, **kwarg):
"""Set an attribute.
set attributes is actually add a special key, value pair in this dict
under key = "_meta".
Usage::
>>> DT.setattr(d, population=27800000)
>>> d
{'_meta': {'population': 27800000, '_rootname': 'US'}}
... | python | def setattr(d, **kwarg):
"""Set an attribute.
set attributes is actually add a special key, value pair in this dict
under key = "_meta".
Usage::
>>> DT.setattr(d, population=27800000)
>>> d
{'_meta': {'population': 27800000, '_rootname': 'US'}}
... | [
"def",
"setattr",
"(",
"d",
",",
"*",
"*",
"kwarg",
")",
":",
"if",
"_meta",
"not",
"in",
"d",
":",
"d",
"[",
"_meta",
"]",
"=",
"dict",
"(",
")",
"for",
"k",
",",
"v",
"in",
"kwarg",
".",
"items",
"(",
")",
":",
"d",
"[",
"_meta",
"]",
"... | Set an attribute.
set attributes is actually add a special key, value pair in this dict
under key = "_meta".
Usage::
>>> DT.setattr(d, population=27800000)
>>> d
{'_meta': {'population': 27800000, '_rootname': 'US'}} | [
"Set",
"an",
"attribute",
"."
] | 689a60da51cd88680ddbe26e28dbe81e6b01d275 | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dtypes/dicttree.py#L168-L183 |
242,781 | MacHu-GWU/angora-project | angora/dtypes/dicttree.py | DictTree.add_children | def add_children(d, key, **kwarg):
"""Add a children with key and attributes. If children already EXISTS,
OVERWRITE it.
Usage::
>>> from pprint import pprint as ppt
>>> DT.add_children(d, "VA", name="virginia", population=100*1000)
>>> DT.add_children(d, "M... | python | def add_children(d, key, **kwarg):
"""Add a children with key and attributes. If children already EXISTS,
OVERWRITE it.
Usage::
>>> from pprint import pprint as ppt
>>> DT.add_children(d, "VA", name="virginia", population=100*1000)
>>> DT.add_children(d, "M... | [
"def",
"add_children",
"(",
"d",
",",
"key",
",",
"*",
"*",
"kwarg",
")",
":",
"if",
"kwarg",
":",
"d",
"[",
"key",
"]",
"=",
"{",
"_meta",
":",
"kwarg",
"}",
"else",
":",
"d",
"[",
"key",
"]",
"=",
"dict",
"(",
")"
] | Add a children with key and attributes. If children already EXISTS,
OVERWRITE it.
Usage::
>>> from pprint import pprint as ppt
>>> DT.add_children(d, "VA", name="virginia", population=100*1000)
>>> DT.add_children(d, "MD", name="maryland", population=200*1000)
... | [
"Add",
"a",
"children",
"with",
"key",
"and",
"attributes",
".",
"If",
"children",
"already",
"EXISTS",
"OVERWRITE",
"it",
"."
] | 689a60da51cd88680ddbe26e28dbe81e6b01d275 | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dtypes/dicttree.py#L197-L248 |
242,782 | MacHu-GWU/angora-project | angora/dtypes/dicttree.py | DictTree.del_depth | def del_depth(d, depth):
"""Delete all the nodes on specific depth in this dict
"""
for node in DictTree.v_depth(d, depth-1):
for key in [key for key in DictTree.k(node)]:
del node[key] | python | def del_depth(d, depth):
"""Delete all the nodes on specific depth in this dict
"""
for node in DictTree.v_depth(d, depth-1):
for key in [key for key in DictTree.k(node)]:
del node[key] | [
"def",
"del_depth",
"(",
"d",
",",
"depth",
")",
":",
"for",
"node",
"in",
"DictTree",
".",
"v_depth",
"(",
"d",
",",
"depth",
"-",
"1",
")",
":",
"for",
"key",
"in",
"[",
"key",
"for",
"key",
"in",
"DictTree",
".",
"k",
"(",
"node",
")",
"]",
... | Delete all the nodes on specific depth in this dict | [
"Delete",
"all",
"the",
"nodes",
"on",
"specific",
"depth",
"in",
"this",
"dict"
] | 689a60da51cd88680ddbe26e28dbe81e6b01d275 | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dtypes/dicttree.py#L370-L375 |
242,783 | MacHu-GWU/angora-project | angora/dtypes/dicttree.py | DictTree.prettyprint | def prettyprint(d):
"""Print dicttree in Json-like format. keys are sorted
"""
print(json.dumps(d, sort_keys=True,
indent=4, separators=("," , ": "))) | python | def prettyprint(d):
"""Print dicttree in Json-like format. keys are sorted
"""
print(json.dumps(d, sort_keys=True,
indent=4, separators=("," , ": "))) | [
"def",
"prettyprint",
"(",
"d",
")",
":",
"print",
"(",
"json",
".",
"dumps",
"(",
"d",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"4",
",",
"separators",
"=",
"(",
"\",\"",
",",
"\": \"",
")",
")",
")"
] | Print dicttree in Json-like format. keys are sorted | [
"Print",
"dicttree",
"in",
"Json",
"-",
"like",
"format",
".",
"keys",
"are",
"sorted"
] | 689a60da51cd88680ddbe26e28dbe81e6b01d275 | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dtypes/dicttree.py#L378-L382 |
242,784 | MacHu-GWU/angora-project | angora/dtypes/dicttree.py | DictTree.stats_on_depth | def stats_on_depth(d, depth):
"""Display the node stats info on specific depth in this dict
"""
root_nodes, leaf_nodes = 0, 0
for _, node in DictTree.kv_depth(d, depth):
if DictTree.length(node) == 0:
leaf_nodes += 1
else:
root_node... | python | def stats_on_depth(d, depth):
"""Display the node stats info on specific depth in this dict
"""
root_nodes, leaf_nodes = 0, 0
for _, node in DictTree.kv_depth(d, depth):
if DictTree.length(node) == 0:
leaf_nodes += 1
else:
root_node... | [
"def",
"stats_on_depth",
"(",
"d",
",",
"depth",
")",
":",
"root_nodes",
",",
"leaf_nodes",
"=",
"0",
",",
"0",
"for",
"_",
",",
"node",
"in",
"DictTree",
".",
"kv_depth",
"(",
"d",
",",
"depth",
")",
":",
"if",
"DictTree",
".",
"length",
"(",
"nod... | Display the node stats info on specific depth in this dict | [
"Display",
"the",
"node",
"stats",
"info",
"on",
"specific",
"depth",
"in",
"this",
"dict"
] | 689a60da51cd88680ddbe26e28dbe81e6b01d275 | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dtypes/dicttree.py#L385-L396 |
242,785 | hobson/pug-dj | pug/dj/db_routers.py | AppRouter.db_for_read | def db_for_read(self, model, **hints):
"""
If the app has its own database, use it for reads
"""
if model._meta.app_label in self._apps:
return getattr(model, '_db_alias', model._meta.app_label)
return None | python | def db_for_read(self, model, **hints):
"""
If the app has its own database, use it for reads
"""
if model._meta.app_label in self._apps:
return getattr(model, '_db_alias', model._meta.app_label)
return None | [
"def",
"db_for_read",
"(",
"self",
",",
"model",
",",
"*",
"*",
"hints",
")",
":",
"if",
"model",
".",
"_meta",
".",
"app_label",
"in",
"self",
".",
"_apps",
":",
"return",
"getattr",
"(",
"model",
",",
"'_db_alias'",
",",
"model",
".",
"_meta",
".",... | If the app has its own database, use it for reads | [
"If",
"the",
"app",
"has",
"its",
"own",
"database",
"use",
"it",
"for",
"reads"
] | 55678b08755a55366ce18e7d3b8ea8fa4491ab04 | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db_routers.py#L20-L26 |
242,786 | hobson/pug-dj | pug/dj/db_routers.py | AppRouter.db_for_write | def db_for_write(self, model, **hints):
"""
If the app has its own database, use it for writes
"""
if model._meta.app_label in self._apps:
return getattr(model, '_db_alias', model._meta.app_label)
return None | python | def db_for_write(self, model, **hints):
"""
If the app has its own database, use it for writes
"""
if model._meta.app_label in self._apps:
return getattr(model, '_db_alias', model._meta.app_label)
return None | [
"def",
"db_for_write",
"(",
"self",
",",
"model",
",",
"*",
"*",
"hints",
")",
":",
"if",
"model",
".",
"_meta",
".",
"app_label",
"in",
"self",
".",
"_apps",
":",
"return",
"getattr",
"(",
"model",
",",
"'_db_alias'",
",",
"model",
".",
"_meta",
"."... | If the app has its own database, use it for writes | [
"If",
"the",
"app",
"has",
"its",
"own",
"database",
"use",
"it",
"for",
"writes"
] | 55678b08755a55366ce18e7d3b8ea8fa4491ab04 | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db_routers.py#L28-L34 |
242,787 | hobson/pug-dj | pug/dj/db_routers.py | AppRouter.allow_migrate | def allow_migrate(self, db, model):
"""
Make sure self._apps go to their own db
"""
if model._meta.app_label in self._apps:
return getattr(model, '_db_alias', model._meta.app_label) == db
return None | python | def allow_migrate(self, db, model):
"""
Make sure self._apps go to their own db
"""
if model._meta.app_label in self._apps:
return getattr(model, '_db_alias', model._meta.app_label) == db
return None | [
"def",
"allow_migrate",
"(",
"self",
",",
"db",
",",
"model",
")",
":",
"if",
"model",
".",
"_meta",
".",
"app_label",
"in",
"self",
".",
"_apps",
":",
"return",
"getattr",
"(",
"model",
",",
"'_db_alias'",
",",
"model",
".",
"_meta",
".",
"app_label",... | Make sure self._apps go to their own db | [
"Make",
"sure",
"self",
".",
"_apps",
"go",
"to",
"their",
"own",
"db"
] | 55678b08755a55366ce18e7d3b8ea8fa4491ab04 | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db_routers.py#L44-L50 |
242,788 | joaopcanario/imports | imports/imports.py | check | def check(path_dir, requirements_name='requirements.txt'):
'''Look for unused packages listed on project requirements'''
requirements = _load_requirements(requirements_name, path_dir)
imported_modules = _iter_modules(path_dir)
installed_packages = _list_installed_packages()
imported_modules.update(... | python | def check(path_dir, requirements_name='requirements.txt'):
'''Look for unused packages listed on project requirements'''
requirements = _load_requirements(requirements_name, path_dir)
imported_modules = _iter_modules(path_dir)
installed_packages = _list_installed_packages()
imported_modules.update(... | [
"def",
"check",
"(",
"path_dir",
",",
"requirements_name",
"=",
"'requirements.txt'",
")",
":",
"requirements",
"=",
"_load_requirements",
"(",
"requirements_name",
",",
"path_dir",
")",
"imported_modules",
"=",
"_iter_modules",
"(",
"path_dir",
")",
"installed_packag... | Look for unused packages listed on project requirements | [
"Look",
"for",
"unused",
"packages",
"listed",
"on",
"project",
"requirements"
] | 46db0d3d2aa55427027bf0e91d61a24d52730337 | https://github.com/joaopcanario/imports/blob/46db0d3d2aa55427027bf0e91d61a24d52730337/imports/imports.py#L94-L112 |
242,789 | jhorman/pledge | pledge/__init__.py | pre | def pre(cond):
"""
Add a precondition check to the annotated method. The condition
is passed the arguments from the annotated method. It does not
need to accept all of the methods parameters. The condition
is inspected to figure out which parameters to pass.
"""
cond_args, cond_varargs, ... | python | def pre(cond):
"""
Add a precondition check to the annotated method. The condition
is passed the arguments from the annotated method. It does not
need to accept all of the methods parameters. The condition
is inspected to figure out which parameters to pass.
"""
cond_args, cond_varargs, ... | [
"def",
"pre",
"(",
"cond",
")",
":",
"cond_args",
",",
"cond_varargs",
",",
"cond_varkw",
",",
"cond_defaults",
"=",
"inspect",
".",
"getargspec",
"(",
"cond",
")",
"source",
"=",
"inspect",
".",
"getsource",
"(",
"cond",
")",
".",
"strip",
"(",
")",
"... | Add a precondition check to the annotated method. The condition
is passed the arguments from the annotated method. It does not
need to accept all of the methods parameters. The condition
is inspected to figure out which parameters to pass. | [
"Add",
"a",
"precondition",
"check",
"to",
"the",
"annotated",
"method",
".",
"The",
"condition",
"is",
"passed",
"the",
"arguments",
"from",
"the",
"annotated",
"method",
".",
"It",
"does",
"not",
"need",
"to",
"accept",
"all",
"of",
"the",
"methods",
"pa... | 062ba5b788aeb15e68c85a329374a50b4618544d | https://github.com/jhorman/pledge/blob/062ba5b788aeb15e68c85a329374a50b4618544d/pledge/__init__.py#L24-L76 |
242,790 | jhorman/pledge | pledge/__init__.py | post | def post(cond):
"""
Add a postcondition check to the annotated method. The condition
is passed the return value of the annotated method.
"""
source = inspect.getsource(cond).strip()
def inner(f):
if enabled:
# deal with the real function, not a wrapper
f = geta... | python | def post(cond):
"""
Add a postcondition check to the annotated method. The condition
is passed the return value of the annotated method.
"""
source = inspect.getsource(cond).strip()
def inner(f):
if enabled:
# deal with the real function, not a wrapper
f = geta... | [
"def",
"post",
"(",
"cond",
")",
":",
"source",
"=",
"inspect",
".",
"getsource",
"(",
"cond",
")",
".",
"strip",
"(",
")",
"def",
"inner",
"(",
"f",
")",
":",
"if",
"enabled",
":",
"# deal with the real function, not a wrapper",
"f",
"=",
"getattr",
"("... | Add a postcondition check to the annotated method. The condition
is passed the return value of the annotated method. | [
"Add",
"a",
"postcondition",
"check",
"to",
"the",
"annotated",
"method",
".",
"The",
"condition",
"is",
"passed",
"the",
"return",
"value",
"of",
"the",
"annotated",
"method",
"."
] | 062ba5b788aeb15e68c85a329374a50b4618544d | https://github.com/jhorman/pledge/blob/062ba5b788aeb15e68c85a329374a50b4618544d/pledge/__init__.py#L78-L103 |
242,791 | jhorman/pledge | pledge/__init__.py | takes | def takes(*type_list):
"""
Decorates a function with type checks. Examples
@takes(int): take an int as the first param
@takes(int, str): take and int as first, string as 2nd
@takes(int, (int, None)): take an int as first, and an int or None as second
"""
def inner(f):
if enabled:
... | python | def takes(*type_list):
"""
Decorates a function with type checks. Examples
@takes(int): take an int as the first param
@takes(int, str): take and int as first, string as 2nd
@takes(int, (int, None)): take an int as first, and an int or None as second
"""
def inner(f):
if enabled:
... | [
"def",
"takes",
"(",
"*",
"type_list",
")",
":",
"def",
"inner",
"(",
"f",
")",
":",
"if",
"enabled",
":",
"# deal with the real function, not a wrapper",
"f",
"=",
"getattr",
"(",
"f",
",",
"'wrapped_fn'",
",",
"f",
")",
"# need to check if 'self' is the first ... | Decorates a function with type checks. Examples
@takes(int): take an int as the first param
@takes(int, str): take and int as first, string as 2nd
@takes(int, (int, None)): take an int as first, and an int or None as second | [
"Decorates",
"a",
"function",
"with",
"type",
"checks",
".",
"Examples"
] | 062ba5b788aeb15e68c85a329374a50b4618544d | https://github.com/jhorman/pledge/blob/062ba5b788aeb15e68c85a329374a50b4618544d/pledge/__init__.py#L105-L153 |
242,792 | jhorman/pledge | pledge/__init__.py | check_conditions | def check_conditions(f, args, kwargs):
"""
This is what runs all of the conditions attached to a method,
along with the conditions on the superclasses.
"""
member_function = is_member_function(f)
# check the functions direct pre conditions
check_preconditions(f, args, kwargs)
# for mem... | python | def check_conditions(f, args, kwargs):
"""
This is what runs all of the conditions attached to a method,
along with the conditions on the superclasses.
"""
member_function = is_member_function(f)
# check the functions direct pre conditions
check_preconditions(f, args, kwargs)
# for mem... | [
"def",
"check_conditions",
"(",
"f",
",",
"args",
",",
"kwargs",
")",
":",
"member_function",
"=",
"is_member_function",
"(",
"f",
")",
"# check the functions direct pre conditions",
"check_preconditions",
"(",
"f",
",",
"args",
",",
"kwargs",
")",
"# for member fun... | This is what runs all of the conditions attached to a method,
along with the conditions on the superclasses. | [
"This",
"is",
"what",
"runs",
"all",
"of",
"the",
"conditions",
"attached",
"to",
"a",
"method",
"along",
"with",
"the",
"conditions",
"on",
"the",
"superclasses",
"."
] | 062ba5b788aeb15e68c85a329374a50b4618544d | https://github.com/jhorman/pledge/blob/062ba5b788aeb15e68c85a329374a50b4618544d/pledge/__init__.py#L185-L215 |
242,793 | jhorman/pledge | pledge/__init__.py | check_preconditions | def check_preconditions(f, args, kwargs):
""" Runs all of the preconditions. """
f = getattr(f, 'wrapped_fn', f)
if f and hasattr(f, 'preconditions'):
for cond in f.preconditions:
cond(args, kwargs) | python | def check_preconditions(f, args, kwargs):
""" Runs all of the preconditions. """
f = getattr(f, 'wrapped_fn', f)
if f and hasattr(f, 'preconditions'):
for cond in f.preconditions:
cond(args, kwargs) | [
"def",
"check_preconditions",
"(",
"f",
",",
"args",
",",
"kwargs",
")",
":",
"f",
"=",
"getattr",
"(",
"f",
",",
"'wrapped_fn'",
",",
"f",
")",
"if",
"f",
"and",
"hasattr",
"(",
"f",
",",
"'preconditions'",
")",
":",
"for",
"cond",
"in",
"f",
".",... | Runs all of the preconditions. | [
"Runs",
"all",
"of",
"the",
"preconditions",
"."
] | 062ba5b788aeb15e68c85a329374a50b4618544d | https://github.com/jhorman/pledge/blob/062ba5b788aeb15e68c85a329374a50b4618544d/pledge/__init__.py#L217-L222 |
242,794 | jhorman/pledge | pledge/__init__.py | check_postconditions | def check_postconditions(f, return_value):
""" Runs all of the postconditions. """
f = getattr(f, 'wrapped_fn', f)
if f and hasattr(f, 'postconditions'):
for cond in f.postconditions:
cond(return_value) | python | def check_postconditions(f, return_value):
""" Runs all of the postconditions. """
f = getattr(f, 'wrapped_fn', f)
if f and hasattr(f, 'postconditions'):
for cond in f.postconditions:
cond(return_value) | [
"def",
"check_postconditions",
"(",
"f",
",",
"return_value",
")",
":",
"f",
"=",
"getattr",
"(",
"f",
",",
"'wrapped_fn'",
",",
"f",
")",
"if",
"f",
"and",
"hasattr",
"(",
"f",
",",
"'postconditions'",
")",
":",
"for",
"cond",
"in",
"f",
".",
"postc... | Runs all of the postconditions. | [
"Runs",
"all",
"of",
"the",
"postconditions",
"."
] | 062ba5b788aeb15e68c85a329374a50b4618544d | https://github.com/jhorman/pledge/blob/062ba5b788aeb15e68c85a329374a50b4618544d/pledge/__init__.py#L224-L229 |
242,795 | jhorman/pledge | pledge/__init__.py | is_member_function | def is_member_function(f):
""" Checks if the first argument to the method is 'self'. """
f_args, f_varargs, f_varkw, f_defaults = inspect.getargspec(f)
return 1 if 'self' in f_args else 0 | python | def is_member_function(f):
""" Checks if the first argument to the method is 'self'. """
f_args, f_varargs, f_varkw, f_defaults = inspect.getargspec(f)
return 1 if 'self' in f_args else 0 | [
"def",
"is_member_function",
"(",
"f",
")",
":",
"f_args",
",",
"f_varargs",
",",
"f_varkw",
",",
"f_defaults",
"=",
"inspect",
".",
"getargspec",
"(",
"f",
")",
"return",
"1",
"if",
"'self'",
"in",
"f_args",
"else",
"0"
] | Checks if the first argument to the method is 'self'. | [
"Checks",
"if",
"the",
"first",
"argument",
"to",
"the",
"method",
"is",
"self",
"."
] | 062ba5b788aeb15e68c85a329374a50b4618544d | https://github.com/jhorman/pledge/blob/062ba5b788aeb15e68c85a329374a50b4618544d/pledge/__init__.py#L231-L234 |
242,796 | jhorman/pledge | pledge/__init__.py | list_of | def list_of(cls):
"""
Returns a function that checks that each element in a
list is of a specific type.
"""
return lambda l: isinstance(l, list) and all(isinstance(x, cls) for x in l) | python | def list_of(cls):
"""
Returns a function that checks that each element in a
list is of a specific type.
"""
return lambda l: isinstance(l, list) and all(isinstance(x, cls) for x in l) | [
"def",
"list_of",
"(",
"cls",
")",
":",
"return",
"lambda",
"l",
":",
"isinstance",
"(",
"l",
",",
"list",
")",
"and",
"all",
"(",
"isinstance",
"(",
"x",
",",
"cls",
")",
"for",
"x",
"in",
"l",
")"
] | Returns a function that checks that each element in a
list is of a specific type. | [
"Returns",
"a",
"function",
"that",
"checks",
"that",
"each",
"element",
"in",
"a",
"list",
"is",
"of",
"a",
"specific",
"type",
"."
] | 062ba5b788aeb15e68c85a329374a50b4618544d | https://github.com/jhorman/pledge/blob/062ba5b788aeb15e68c85a329374a50b4618544d/pledge/__init__.py#L243-L248 |
242,797 | jhorman/pledge | pledge/__init__.py | set_of | def set_of(cls):
"""
Returns a function that checks that each element in a
set is of a specific type.
"""
return lambda l: isinstance(l, set) and all(isinstance(x, cls) for x in l) | python | def set_of(cls):
"""
Returns a function that checks that each element in a
set is of a specific type.
"""
return lambda l: isinstance(l, set) and all(isinstance(x, cls) for x in l) | [
"def",
"set_of",
"(",
"cls",
")",
":",
"return",
"lambda",
"l",
":",
"isinstance",
"(",
"l",
",",
"set",
")",
"and",
"all",
"(",
"isinstance",
"(",
"x",
",",
"cls",
")",
"for",
"x",
"in",
"l",
")"
] | Returns a function that checks that each element in a
set is of a specific type. | [
"Returns",
"a",
"function",
"that",
"checks",
"that",
"each",
"element",
"in",
"a",
"set",
"is",
"of",
"a",
"specific",
"type",
"."
] | 062ba5b788aeb15e68c85a329374a50b4618544d | https://github.com/jhorman/pledge/blob/062ba5b788aeb15e68c85a329374a50b4618544d/pledge/__init__.py#L250-L255 |
242,798 | jalanb/pysyte | pysyte/streams.py | swallow_stdout | def swallow_stdout(stream=None):
"""Divert stdout into the given stream
>>> string = StringIO()
>>> with swallow_stdout(string):
... print('hello')
>>> assert string.getvalue().rstrip() == 'hello'
"""
saved = sys.stdout
if stream is None:
stream = StringIO()
sys.stdout =... | python | def swallow_stdout(stream=None):
"""Divert stdout into the given stream
>>> string = StringIO()
>>> with swallow_stdout(string):
... print('hello')
>>> assert string.getvalue().rstrip() == 'hello'
"""
saved = sys.stdout
if stream is None:
stream = StringIO()
sys.stdout =... | [
"def",
"swallow_stdout",
"(",
"stream",
"=",
"None",
")",
":",
"saved",
"=",
"sys",
".",
"stdout",
"if",
"stream",
"is",
"None",
":",
"stream",
"=",
"StringIO",
"(",
")",
"sys",
".",
"stdout",
"=",
"stream",
"try",
":",
"yield",
"finally",
":",
"sys"... | Divert stdout into the given stream
>>> string = StringIO()
>>> with swallow_stdout(string):
... print('hello')
>>> assert string.getvalue().rstrip() == 'hello' | [
"Divert",
"stdout",
"into",
"the",
"given",
"stream"
] | 4e278101943d1ceb1a6bcaf6ddc72052ecf13114 | https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/streams.py#L11-L26 |
242,799 | cdeboever3/cdpybio | cdpybio/star.py | read_sj_out_tab | def read_sj_out_tab(filename):
"""Read an SJ.out.tab file as produced by the RNA-STAR aligner into a
pandas Dataframe.
Parameters
----------
filename : str of filename or file handle
Filename of the SJ.out.tab file you want to read in
Returns
-------
sj : pandas.DataFrame
... | python | def read_sj_out_tab(filename):
"""Read an SJ.out.tab file as produced by the RNA-STAR aligner into a
pandas Dataframe.
Parameters
----------
filename : str of filename or file handle
Filename of the SJ.out.tab file you want to read in
Returns
-------
sj : pandas.DataFrame
... | [
"def",
"read_sj_out_tab",
"(",
"filename",
")",
":",
"def",
"int_to_intron_motif",
"(",
"n",
")",
":",
"if",
"n",
"==",
"0",
":",
"return",
"'non-canonical'",
"if",
"n",
"==",
"1",
":",
"return",
"'GT/AG'",
"if",
"n",
"==",
"2",
":",
"return",
"'CT/AC'... | Read an SJ.out.tab file as produced by the RNA-STAR aligner into a
pandas Dataframe.
Parameters
----------
filename : str of filename or file handle
Filename of the SJ.out.tab file you want to read in
Returns
-------
sj : pandas.DataFrame
Dataframe of splice junctions | [
"Read",
"an",
"SJ",
".",
"out",
".",
"tab",
"file",
"as",
"produced",
"by",
"the",
"RNA",
"-",
"STAR",
"aligner",
"into",
"a",
"pandas",
"Dataframe",
"."
] | 38efdf0e11d01bc00a135921cb91a19c03db5d5c | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/star.py#L47-L87 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.