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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
248,700 | dossier/dossier.web | dossier/web/label_folders.py | nub | def nub(it):
'''Dedups an iterable in arbitrary order.
Uses memory proportional to the number of unique items in ``it``.
'''
seen = set()
for v in it:
h = hash(v)
if h in seen:
continue
seen.add(h)
yield v | python | def nub(it):
'''Dedups an iterable in arbitrary order.
Uses memory proportional to the number of unique items in ``it``.
'''
seen = set()
for v in it:
h = hash(v)
if h in seen:
continue
seen.add(h)
yield v | [
"def",
"nub",
"(",
"it",
")",
":",
"seen",
"=",
"set",
"(",
")",
"for",
"v",
"in",
"it",
":",
"h",
"=",
"hash",
"(",
"v",
")",
"if",
"h",
"in",
"seen",
":",
"continue",
"seen",
".",
"add",
"(",
"h",
")",
"yield",
"v"
] | Dedups an iterable in arbitrary order.
Uses memory proportional to the number of unique items in ``it``. | [
"Dedups",
"an",
"iterable",
"in",
"arbitrary",
"order",
"."
] | 1cad1cce3c37d3a4e956abc710a2bc1afe16a092 | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/label_folders.py#L292-L303 |
248,701 | dossier/dossier.web | dossier/web/label_folders.py | Folders.folders | def folders(self, ann_id=None):
'''Yields an unordered generator for all available folders.
By default (with ``ann_id=None``), folders are shown for all
anonymous users. Optionally, ``ann_id`` can be set to a username,
which restricts the list to only folders owned by that user.
... | python | def folders(self, ann_id=None):
'''Yields an unordered generator for all available folders.
By default (with ``ann_id=None``), folders are shown for all
anonymous users. Optionally, ``ann_id`` can be set to a username,
which restricts the list to only folders owned by that user.
... | [
"def",
"folders",
"(",
"self",
",",
"ann_id",
"=",
"None",
")",
":",
"ann_id",
"=",
"self",
".",
"_annotator",
"(",
"ann_id",
")",
"if",
"len",
"(",
"self",
".",
"prefix",
")",
">",
"0",
":",
"prefix",
"=",
"'|'",
".",
"join",
"(",
"[",
"urllib",... | Yields an unordered generator for all available folders.
By default (with ``ann_id=None``), folders are shown for all
anonymous users. Optionally, ``ann_id`` can be set to a username,
which restricts the list to only folders owned by that user.
:param str ann_id: Username
:rtyp... | [
"Yields",
"an",
"unordered",
"generator",
"for",
"all",
"available",
"folders",
"."
] | 1cad1cce3c37d3a4e956abc710a2bc1afe16a092 | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/label_folders.py#L92-L110 |
248,702 | dossier/dossier.web | dossier/web/label_folders.py | Folders.subfolders | def subfolders(self, folder_id, ann_id=None):
'''Yields an unodered generator of subfolders in a folder.
By default (with ``ann_id=None``), subfolders are shown for all
anonymous users. Optionally, ``ann_id`` can be set to a username,
which restricts the list to only subfolders owned by... | python | def subfolders(self, folder_id, ann_id=None):
'''Yields an unodered generator of subfolders in a folder.
By default (with ``ann_id=None``), subfolders are shown for all
anonymous users. Optionally, ``ann_id`` can be set to a username,
which restricts the list to only subfolders owned by... | [
"def",
"subfolders",
"(",
"self",
",",
"folder_id",
",",
"ann_id",
"=",
"None",
")",
":",
"self",
".",
"assert_valid_folder_id",
"(",
"folder_id",
")",
"ann_id",
"=",
"self",
".",
"_annotator",
"(",
"ann_id",
")",
"folder_cid",
"=",
"self",
".",
"wrap_fold... | Yields an unodered generator of subfolders in a folder.
By default (with ``ann_id=None``), subfolders are shown for all
anonymous users. Optionally, ``ann_id`` can be set to a username,
which restricts the list to only subfolders owned by that user.
:param str folder_id: Folder id
... | [
"Yields",
"an",
"unodered",
"generator",
"of",
"subfolders",
"in",
"a",
"folder",
"."
] | 1cad1cce3c37d3a4e956abc710a2bc1afe16a092 | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/label_folders.py#L112-L129 |
248,703 | dossier/dossier.web | dossier/web/label_folders.py | Folders.parent_subfolders | def parent_subfolders(self, ident, ann_id=None):
'''An unordered generator of parent subfolders for ``ident``.
``ident`` can either be a ``content_id`` or a tuple of
``(content_id, subtopic_id)``.
Parent subfolders are limited to the annotator id given.
:param ident: identifie... | python | def parent_subfolders(self, ident, ann_id=None):
'''An unordered generator of parent subfolders for ``ident``.
``ident`` can either be a ``content_id`` or a tuple of
``(content_id, subtopic_id)``.
Parent subfolders are limited to the annotator id given.
:param ident: identifie... | [
"def",
"parent_subfolders",
"(",
"self",
",",
"ident",
",",
"ann_id",
"=",
"None",
")",
":",
"ann_id",
"=",
"self",
".",
"_annotator",
"(",
"ann_id",
")",
"cid",
",",
"_",
"=",
"normalize_ident",
"(",
"ident",
")",
"for",
"lab",
"in",
"self",
".",
"l... | An unordered generator of parent subfolders for ``ident``.
``ident`` can either be a ``content_id`` or a tuple of
``(content_id, subtopic_id)``.
Parent subfolders are limited to the annotator id given.
:param ident: identifier
:type ident: ``str`` or ``(str, str)``
:pa... | [
"An",
"unordered",
"generator",
"of",
"parent",
"subfolders",
"for",
"ident",
"."
] | 1cad1cce3c37d3a4e956abc710a2bc1afe16a092 | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/label_folders.py#L131-L155 |
248,704 | dossier/dossier.web | dossier/web/label_folders.py | Folders.items | def items(self, folder_id, subfolder_id, ann_id=None):
'''Yields an unodered generator of items in a subfolder.
The generator yields items, which are represented by a tuple
of ``content_id`` and ``subtopic_id``. The format of these
identifiers is unspecified.
By default (with `... | python | def items(self, folder_id, subfolder_id, ann_id=None):
'''Yields an unodered generator of items in a subfolder.
The generator yields items, which are represented by a tuple
of ``content_id`` and ``subtopic_id``. The format of these
identifiers is unspecified.
By default (with `... | [
"def",
"items",
"(",
"self",
",",
"folder_id",
",",
"subfolder_id",
",",
"ann_id",
"=",
"None",
")",
":",
"self",
".",
"assert_valid_folder_id",
"(",
"folder_id",
")",
"self",
".",
"assert_valid_folder_id",
"(",
"subfolder_id",
")",
"ann_id",
"=",
"self",
".... | Yields an unodered generator of items in a subfolder.
The generator yields items, which are represented by a tuple
of ``content_id`` and ``subtopic_id``. The format of these
identifiers is unspecified.
By default (with ``ann_id=None``), subfolders are shown for all
anonymous us... | [
"Yields",
"an",
"unodered",
"generator",
"of",
"items",
"in",
"a",
"subfolder",
"."
] | 1cad1cce3c37d3a4e956abc710a2bc1afe16a092 | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/label_folders.py#L157-L185 |
248,705 | dossier/dossier.web | dossier/web/label_folders.py | Folders.grouped_items | def grouped_items(self, folder_id, subfolder_id, ann_id=None):
'''Returns a dictionary from content ids to subtopic ids.
Namely, the mapping is ``content_id |--> list of subtopic id``.
By default (with ``ann_id=None``), subfolders are shown for all
anonymous users. Optionally, ``ann_id... | python | def grouped_items(self, folder_id, subfolder_id, ann_id=None):
'''Returns a dictionary from content ids to subtopic ids.
Namely, the mapping is ``content_id |--> list of subtopic id``.
By default (with ``ann_id=None``), subfolders are shown for all
anonymous users. Optionally, ``ann_id... | [
"def",
"grouped_items",
"(",
"self",
",",
"folder_id",
",",
"subfolder_id",
",",
"ann_id",
"=",
"None",
")",
":",
"d",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"cid",
",",
"subid",
"in",
"self",
".",
"items",
"(",
"folder_id",
",",
"subfolder_id",
... | Returns a dictionary from content ids to subtopic ids.
Namely, the mapping is ``content_id |--> list of subtopic id``.
By default (with ``ann_id=None``), subfolders are shown for all
anonymous users. Optionally, ``ann_id`` can be set to a username,
which restricts the list to only subf... | [
"Returns",
"a",
"dictionary",
"from",
"content",
"ids",
"to",
"subtopic",
"ids",
"."
] | 1cad1cce3c37d3a4e956abc710a2bc1afe16a092 | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/label_folders.py#L187-L204 |
248,706 | dossier/dossier.web | dossier/web/label_folders.py | Folders.add_folder | def add_folder(self, folder_id, ann_id=None):
'''Add a folder.
If ``ann_id`` is set, then the folder is owned by the given user.
Otherwise, the folder is owned and viewable by all anonymous
users.
:param str folder_id: Folder id
:param str ann_id: Username
'''
... | python | def add_folder(self, folder_id, ann_id=None):
'''Add a folder.
If ``ann_id`` is set, then the folder is owned by the given user.
Otherwise, the folder is owned and viewable by all anonymous
users.
:param str folder_id: Folder id
:param str ann_id: Username
'''
... | [
"def",
"add_folder",
"(",
"self",
",",
"folder_id",
",",
"ann_id",
"=",
"None",
")",
":",
"self",
".",
"assert_valid_folder_id",
"(",
"folder_id",
")",
"ann_id",
"=",
"self",
".",
"_annotator",
"(",
"ann_id",
")",
"cid",
"=",
"self",
".",
"wrap_folder_cont... | Add a folder.
If ``ann_id`` is set, then the folder is owned by the given user.
Otherwise, the folder is owned and viewable by all anonymous
users.
:param str folder_id: Folder id
:param str ann_id: Username | [
"Add",
"a",
"folder",
"."
] | 1cad1cce3c37d3a4e956abc710a2bc1afe16a092 | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/label_folders.py#L206-L220 |
248,707 | dossier/dossier.web | dossier/web/label_folders.py | Folders.add_item | def add_item(self, folder_id, subfolder_id, content_id, subtopic_id=None,
ann_id=None):
'''Add an item to a subfolder.
The format of ``content_id`` and ``subtopic_id`` is
unspecified. It is application specific.
If ``ann_id`` is set, then the item is owned by the given... | python | def add_item(self, folder_id, subfolder_id, content_id, subtopic_id=None,
ann_id=None):
'''Add an item to a subfolder.
The format of ``content_id`` and ``subtopic_id`` is
unspecified. It is application specific.
If ``ann_id`` is set, then the item is owned by the given... | [
"def",
"add_item",
"(",
"self",
",",
"folder_id",
",",
"subfolder_id",
",",
"content_id",
",",
"subtopic_id",
"=",
"None",
",",
"ann_id",
"=",
"None",
")",
":",
"self",
".",
"assert_valid_folder_id",
"(",
"folder_id",
")",
"self",
".",
"assert_valid_folder_id"... | Add an item to a subfolder.
The format of ``content_id`` and ``subtopic_id`` is
unspecified. It is application specific.
If ``ann_id`` is set, then the item is owned by the given user.
Otherwise, the item is owned and viewable by all anonymous
users.
:param str folder_... | [
"Add",
"an",
"item",
"to",
"a",
"subfolder",
"."
] | 1cad1cce3c37d3a4e956abc710a2bc1afe16a092 | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/label_folders.py#L222-L253 |
248,708 | treycucco/bidon | lib/generate_models.py | generate_models | def generate_models(args):
"""Generates models from the script input."""
data_table = get_data_table(args.filename)
tables = to_tables(data_table.rows_to_dicts())
attr_indent = "\n" + args.indent * 2
attr_sep = "," + attr_indent
for tname, cols in tables.items():
model_name = table_to_model_name(tname,... | python | def generate_models(args):
"""Generates models from the script input."""
data_table = get_data_table(args.filename)
tables = to_tables(data_table.rows_to_dicts())
attr_indent = "\n" + args.indent * 2
attr_sep = "," + attr_indent
for tname, cols in tables.items():
model_name = table_to_model_name(tname,... | [
"def",
"generate_models",
"(",
"args",
")",
":",
"data_table",
"=",
"get_data_table",
"(",
"args",
".",
"filename",
")",
"tables",
"=",
"to_tables",
"(",
"data_table",
".",
"rows_to_dicts",
"(",
")",
")",
"attr_indent",
"=",
"\"\\n\"",
"+",
"args",
".",
"i... | Generates models from the script input. | [
"Generates",
"models",
"from",
"the",
"script",
"input",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/lib/generate_models.py#L55-L82 |
248,709 | treycucco/bidon | lib/generate_models.py | get_data_table | def get_data_table(filename):
"""Returns a DataTable instance built from either the filename, or STDIN if filename is None."""
with get_file_object(filename, "r") as rf:
return DataTable(list(csv.reader(rf))) | python | def get_data_table(filename):
"""Returns a DataTable instance built from either the filename, or STDIN if filename is None."""
with get_file_object(filename, "r") as rf:
return DataTable(list(csv.reader(rf))) | [
"def",
"get_data_table",
"(",
"filename",
")",
":",
"with",
"get_file_object",
"(",
"filename",
",",
"\"r\"",
")",
"as",
"rf",
":",
"return",
"DataTable",
"(",
"list",
"(",
"csv",
".",
"reader",
"(",
"rf",
")",
")",
")"
] | Returns a DataTable instance built from either the filename, or STDIN if filename is None. | [
"Returns",
"a",
"DataTable",
"instance",
"built",
"from",
"either",
"the",
"filename",
"or",
"STDIN",
"if",
"filename",
"is",
"None",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/lib/generate_models.py#L85-L88 |
248,710 | treycucco/bidon | lib/generate_models.py | to_tables | def to_tables(cols):
"""Builds and returns a Dictionary whose keys are table names and values are OrderedDicts whose
keys are column names and values are the col objects from which the definition is derived.
"""
tables = OrderedDict()
for col in cols:
tname = col["table_name"]
if tname not in tables:
... | python | def to_tables(cols):
"""Builds and returns a Dictionary whose keys are table names and values are OrderedDicts whose
keys are column names and values are the col objects from which the definition is derived.
"""
tables = OrderedDict()
for col in cols:
tname = col["table_name"]
if tname not in tables:
... | [
"def",
"to_tables",
"(",
"cols",
")",
":",
"tables",
"=",
"OrderedDict",
"(",
")",
"for",
"col",
"in",
"cols",
":",
"tname",
"=",
"col",
"[",
"\"table_name\"",
"]",
"if",
"tname",
"not",
"in",
"tables",
":",
"tables",
"[",
"tname",
"]",
"=",
"Ordered... | Builds and returns a Dictionary whose keys are table names and values are OrderedDicts whose
keys are column names and values are the col objects from which the definition is derived. | [
"Builds",
"and",
"returns",
"a",
"Dictionary",
"whose",
"keys",
"are",
"table",
"names",
"and",
"values",
"are",
"OrderedDicts",
"whose",
"keys",
"are",
"column",
"names",
"and",
"values",
"are",
"the",
"col",
"objects",
"from",
"which",
"the",
"definition",
... | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/lib/generate_models.py#L91-L101 |
248,711 | treycucco/bidon | lib/generate_models.py | snake_to_pascal | def snake_to_pascal(name, singularize=False):
"""Converts snake_case to PascalCase. If singularize is True, an attempt is made at singularizing
each part of the resulting name.
"""
parts = name.split("_")
if singularize:
return "".join(p.upper() if p in _ALL_CAPS else to_singular(p.title()) for p in parts... | python | def snake_to_pascal(name, singularize=False):
"""Converts snake_case to PascalCase. If singularize is True, an attempt is made at singularizing
each part of the resulting name.
"""
parts = name.split("_")
if singularize:
return "".join(p.upper() if p in _ALL_CAPS else to_singular(p.title()) for p in parts... | [
"def",
"snake_to_pascal",
"(",
"name",
",",
"singularize",
"=",
"False",
")",
":",
"parts",
"=",
"name",
".",
"split",
"(",
"\"_\"",
")",
"if",
"singularize",
":",
"return",
"\"\"",
".",
"join",
"(",
"p",
".",
"upper",
"(",
")",
"if",
"p",
"in",
"_... | Converts snake_case to PascalCase. If singularize is True, an attempt is made at singularizing
each part of the resulting name. | [
"Converts",
"snake_case",
"to",
"PascalCase",
".",
"If",
"singularize",
"is",
"True",
"an",
"attempt",
"is",
"made",
"at",
"singularizing",
"each",
"part",
"of",
"the",
"resulting",
"name",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/lib/generate_models.py#L109-L117 |
248,712 | treycucco/bidon | lib/generate_models.py | to_singular | def to_singular(word):
"""Attempts to singularize a word."""
if word[-1] != "s":
return word
elif word.endswith("ies"):
return word[:-3] + "y"
elif word.endswith("ses"):
return word[:-2]
else:
return word[:-1] | python | def to_singular(word):
"""Attempts to singularize a word."""
if word[-1] != "s":
return word
elif word.endswith("ies"):
return word[:-3] + "y"
elif word.endswith("ses"):
return word[:-2]
else:
return word[:-1] | [
"def",
"to_singular",
"(",
"word",
")",
":",
"if",
"word",
"[",
"-",
"1",
"]",
"!=",
"\"s\"",
":",
"return",
"word",
"elif",
"word",
".",
"endswith",
"(",
"\"ies\"",
")",
":",
"return",
"word",
"[",
":",
"-",
"3",
"]",
"+",
"\"y\"",
"elif",
"word... | Attempts to singularize a word. | [
"Attempts",
"to",
"singularize",
"a",
"word",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/lib/generate_models.py#L120-L129 |
248,713 | treycucco/bidon | lib/generate_models.py | get_timestamps | def get_timestamps(cols, created_name, updated_name):
"""Returns a 2-tuple of the timestamp columns that were found on the table definition."""
has_created = created_name in cols
has_updated = updated_name in cols
return (created_name if has_created else None, updated_name if has_updated else None) | python | def get_timestamps(cols, created_name, updated_name):
"""Returns a 2-tuple of the timestamp columns that were found on the table definition."""
has_created = created_name in cols
has_updated = updated_name in cols
return (created_name if has_created else None, updated_name if has_updated else None) | [
"def",
"get_timestamps",
"(",
"cols",
",",
"created_name",
",",
"updated_name",
")",
":",
"has_created",
"=",
"created_name",
"in",
"cols",
"has_updated",
"=",
"updated_name",
"in",
"cols",
"return",
"(",
"created_name",
"if",
"has_created",
"else",
"None",
",",... | Returns a 2-tuple of the timestamp columns that were found on the table definition. | [
"Returns",
"a",
"2",
"-",
"tuple",
"of",
"the",
"timestamp",
"columns",
"that",
"were",
"found",
"on",
"the",
"table",
"definition",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/lib/generate_models.py#L145-L149 |
248,714 | Tinche/django-bower-cache | registry/gitwrapper.py | pull_from_origin | def pull_from_origin(repo_path):
"""Execute 'git pull' at the provided repo_path."""
LOG.info("Pulling from origin at %s." % repo_path)
command = GIT_PULL_CMD.format(repo_path)
resp = envoy.run(command)
if resp.status_code != 0:
LOG.exception("Pull failed.")
raise GitException(resp.s... | python | def pull_from_origin(repo_path):
"""Execute 'git pull' at the provided repo_path."""
LOG.info("Pulling from origin at %s." % repo_path)
command = GIT_PULL_CMD.format(repo_path)
resp = envoy.run(command)
if resp.status_code != 0:
LOG.exception("Pull failed.")
raise GitException(resp.s... | [
"def",
"pull_from_origin",
"(",
"repo_path",
")",
":",
"LOG",
".",
"info",
"(",
"\"Pulling from origin at %s.\"",
"%",
"repo_path",
")",
"command",
"=",
"GIT_PULL_CMD",
".",
"format",
"(",
"repo_path",
")",
"resp",
"=",
"envoy",
".",
"run",
"(",
"command",
"... | Execute 'git pull' at the provided repo_path. | [
"Execute",
"git",
"pull",
"at",
"the",
"provided",
"repo_path",
"."
] | 5245b2ee80c33c09d85ce0bf8f047825d9df2118 | https://github.com/Tinche/django-bower-cache/blob/5245b2ee80c33c09d85ce0bf8f047825d9df2118/registry/gitwrapper.py#L26-L35 |
248,715 | Tinche/django-bower-cache | registry/gitwrapper.py | read_remote_origin | def read_remote_origin(repo_dir):
"""Read the remote origin URL from the given git repo, or None if unset."""
conf = ConfigParser()
conf.read(os.path.join(repo_dir, '.git/config'))
return conf.get('remote "origin"', 'url') | python | def read_remote_origin(repo_dir):
"""Read the remote origin URL from the given git repo, or None if unset."""
conf = ConfigParser()
conf.read(os.path.join(repo_dir, '.git/config'))
return conf.get('remote "origin"', 'url') | [
"def",
"read_remote_origin",
"(",
"repo_dir",
")",
":",
"conf",
"=",
"ConfigParser",
"(",
")",
"conf",
".",
"read",
"(",
"os",
".",
"path",
".",
"join",
"(",
"repo_dir",
",",
"'.git/config'",
")",
")",
"return",
"conf",
".",
"get",
"(",
"'remote \"origin... | Read the remote origin URL from the given git repo, or None if unset. | [
"Read",
"the",
"remote",
"origin",
"URL",
"from",
"the",
"given",
"git",
"repo",
"or",
"None",
"if",
"unset",
"."
] | 5245b2ee80c33c09d85ce0bf8f047825d9df2118 | https://github.com/Tinche/django-bower-cache/blob/5245b2ee80c33c09d85ce0bf8f047825d9df2118/registry/gitwrapper.py#L38-L42 |
248,716 | Tinche/django-bower-cache | registry/gitwrapper.py | clone_from | def clone_from(repo_url, repo_dir):
"""Clone a remote git repo into a local directory."""
repo_url = _fix_repo_url(repo_url)
LOG.info("Cloning %s into %s." % (repo_url, repo_dir))
cmd = GIT_CLONE_CMD.format(repo_url, repo_dir)
resp = envoy.run(cmd)
if resp.status_code != 0:
LOG.error("Cl... | python | def clone_from(repo_url, repo_dir):
"""Clone a remote git repo into a local directory."""
repo_url = _fix_repo_url(repo_url)
LOG.info("Cloning %s into %s." % (repo_url, repo_dir))
cmd = GIT_CLONE_CMD.format(repo_url, repo_dir)
resp = envoy.run(cmd)
if resp.status_code != 0:
LOG.error("Cl... | [
"def",
"clone_from",
"(",
"repo_url",
",",
"repo_dir",
")",
":",
"repo_url",
"=",
"_fix_repo_url",
"(",
"repo_url",
")",
"LOG",
".",
"info",
"(",
"\"Cloning %s into %s.\"",
"%",
"(",
"repo_url",
",",
"repo_dir",
")",
")",
"cmd",
"=",
"GIT_CLONE_CMD",
".",
... | Clone a remote git repo into a local directory. | [
"Clone",
"a",
"remote",
"git",
"repo",
"into",
"a",
"local",
"directory",
"."
] | 5245b2ee80c33c09d85ce0bf8f047825d9df2118 | https://github.com/Tinche/django-bower-cache/blob/5245b2ee80c33c09d85ce0bf8f047825d9df2118/registry/gitwrapper.py#L45-L54 |
248,717 | zweifisch/biro | biro/__init__.py | route | def route(method, pattern, handler=None):
"""register a routing rule
Example:
route('GET', '/path/<param>', handler)
"""
if handler is None:
return partial(route, method, pattern)
return routes.append(method, pattern, handler) | python | def route(method, pattern, handler=None):
"""register a routing rule
Example:
route('GET', '/path/<param>', handler)
"""
if handler is None:
return partial(route, method, pattern)
return routes.append(method, pattern, handler) | [
"def",
"route",
"(",
"method",
",",
"pattern",
",",
"handler",
"=",
"None",
")",
":",
"if",
"handler",
"is",
"None",
":",
"return",
"partial",
"(",
"route",
",",
"method",
",",
"pattern",
")",
"return",
"routes",
".",
"append",
"(",
"method",
",",
"p... | register a routing rule
Example:
route('GET', '/path/<param>', handler) | [
"register",
"a",
"routing",
"rule"
] | 0712746de65ff1e25b4f99c669eddd1fb8d1043e | https://github.com/zweifisch/biro/blob/0712746de65ff1e25b4f99c669eddd1fb8d1043e/biro/__init__.py#L14-L24 |
248,718 | eallik/spinoff | spinoff/actor/util.py | Container.spawn | def spawn(self, owner, *args, **kwargs):
"""Spawns a new subordinate actor of `owner` and stores it in this container.
jobs = Container()
...
jobs.spawn(self, Job)
jobs.spawn(self, Job, some_param=123)
jobs = Container(Job)
...
jobs.spawn(self)
j... | python | def spawn(self, owner, *args, **kwargs):
"""Spawns a new subordinate actor of `owner` and stores it in this container.
jobs = Container()
...
jobs.spawn(self, Job)
jobs.spawn(self, Job, some_param=123)
jobs = Container(Job)
...
jobs.spawn(self)
j... | [
"def",
"spawn",
"(",
"self",
",",
"owner",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"(",
"self",
".",
"_spawn",
"(",
"owner",
",",
"self",
".",
"factory",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"self",
".",
... | Spawns a new subordinate actor of `owner` and stores it in this container.
jobs = Container()
...
jobs.spawn(self, Job)
jobs.spawn(self, Job, some_param=123)
jobs = Container(Job)
...
jobs.spawn(self)
jobs.spawn(self, some_param=123)
jobs = Cont... | [
"Spawns",
"a",
"new",
"subordinate",
"actor",
"of",
"owner",
"and",
"stores",
"it",
"in",
"this",
"container",
"."
] | 06b00d6b86c7422c9cb8f9a4b2915906e92b7d52 | https://github.com/eallik/spinoff/blob/06b00d6b86c7422c9cb8f9a4b2915906e92b7d52/spinoff/actor/util.py#L22-L44 |
248,719 | naphatkrit/easyci | easyci/commands/watch.py | watch | def watch(ctx):
"""Watch the directory for changes. Automatically run tests.
"""
vcs = ctx.obj['vcs']
event_handler = TestsEventHandler(vcs)
observer = Observer()
observer.schedule(event_handler, vcs.path, recursive=True)
observer.start()
click.echo('Watching directory `{path}`. Use ct... | python | def watch(ctx):
"""Watch the directory for changes. Automatically run tests.
"""
vcs = ctx.obj['vcs']
event_handler = TestsEventHandler(vcs)
observer = Observer()
observer.schedule(event_handler, vcs.path, recursive=True)
observer.start()
click.echo('Watching directory `{path}`. Use ct... | [
"def",
"watch",
"(",
"ctx",
")",
":",
"vcs",
"=",
"ctx",
".",
"obj",
"[",
"'vcs'",
"]",
"event_handler",
"=",
"TestsEventHandler",
"(",
"vcs",
")",
"observer",
"=",
"Observer",
"(",
")",
"observer",
".",
"schedule",
"(",
"event_handler",
",",
"vcs",
".... | Watch the directory for changes. Automatically run tests. | [
"Watch",
"the",
"directory",
"for",
"changes",
".",
"Automatically",
"run",
"tests",
"."
] | 7aee8d7694fe4e2da42ce35b0f700bc840c8b95f | https://github.com/naphatkrit/easyci/blob/7aee8d7694fe4e2da42ce35b0f700bc840c8b95f/easyci/commands/watch.py#L12-L24 |
248,720 | minhhoit/yacms | yacms/conf/context_processors.py | settings | def settings(request=None):
"""
Add the settings object to the template context.
"""
from yacms.conf import settings
allowed_settings = settings.TEMPLATE_ACCESSIBLE_SETTINGS
template_settings = TemplateSettings(settings, allowed_settings)
template_settings.update(DEPRECATED)
# This is... | python | def settings(request=None):
"""
Add the settings object to the template context.
"""
from yacms.conf import settings
allowed_settings = settings.TEMPLATE_ACCESSIBLE_SETTINGS
template_settings = TemplateSettings(settings, allowed_settings)
template_settings.update(DEPRECATED)
# This is... | [
"def",
"settings",
"(",
"request",
"=",
"None",
")",
":",
"from",
"yacms",
".",
"conf",
"import",
"settings",
"allowed_settings",
"=",
"settings",
".",
"TEMPLATE_ACCESSIBLE_SETTINGS",
"template_settings",
"=",
"TemplateSettings",
"(",
"settings",
",",
"allowed_setti... | Add the settings object to the template context. | [
"Add",
"the",
"settings",
"object",
"to",
"the",
"template",
"context",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/conf/context_processors.py#L51-L70 |
248,721 | jut-io/jut-python-tools | jut/commands/programs.py | list | def list(options):
"""
list programs that belong to the authenticated user
"""
configuration = config.get_default()
app_url = configuration['app_url']
if options.deployment != None:
deployment_name = options.deployment
else:
deployment_name = configuration['deployment_name'... | python | def list(options):
"""
list programs that belong to the authenticated user
"""
configuration = config.get_default()
app_url = configuration['app_url']
if options.deployment != None:
deployment_name = options.deployment
else:
deployment_name = configuration['deployment_name'... | [
"def",
"list",
"(",
"options",
")",
":",
"configuration",
"=",
"config",
".",
"get_default",
"(",
")",
"app_url",
"=",
"configuration",
"[",
"'app_url'",
"]",
"if",
"options",
".",
"deployment",
"!=",
"None",
":",
"deployment_name",
"=",
"options",
".",
"d... | list programs that belong to the authenticated user | [
"list",
"programs",
"that",
"belong",
"to",
"the",
"authenticated",
"user"
] | 65574d23f51a7bbced9bb25010d02da5ca5d906f | https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/commands/programs.py#L22-L82 |
248,722 | spookey/photon | photon/photon.py | Photon.m | def m(self, msg,
state=False, more=None, cmdd=None, critical=True, verbose=None):
'''
Mysterious mega method managing multiple meshed modules magically
.. note:: If this function is used, the code contains facepalms: ``m(``
* It is possible to just show a message, \
o... | python | def m(self, msg,
state=False, more=None, cmdd=None, critical=True, verbose=None):
'''
Mysterious mega method managing multiple meshed modules magically
.. note:: If this function is used, the code contains facepalms: ``m(``
* It is possible to just show a message, \
o... | [
"def",
"m",
"(",
"self",
",",
"msg",
",",
"state",
"=",
"False",
",",
"more",
"=",
"None",
",",
"cmdd",
"=",
"None",
",",
"critical",
"=",
"True",
",",
"verbose",
"=",
"None",
")",
":",
"if",
"verbose",
"is",
"None",
":",
"verbose",
"=",
"self",
... | Mysterious mega method managing multiple meshed modules magically
.. note:: If this function is used, the code contains facepalms: ``m(``
* It is possible to just show a message, \
or to run a command with message.
* But it is not possible to run a command without a message, \
... | [
"Mysterious",
"mega",
"method",
"managing",
"multiple",
"meshed",
"modules",
"magically"
] | 57212a26ce713ab7723910ee49e3d0ba1697799f | https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/photon.py#L91-L167 |
248,723 | spookey/photon | photon/photon.py | Photon.s2m | def s2m(self):
'''
Imports settings to meta
'''
m = '%s settings' % (IDENT)
self.meta.load(m, 'import %s' % (m), mdict=self.settings.get) | python | def s2m(self):
'''
Imports settings to meta
'''
m = '%s settings' % (IDENT)
self.meta.load(m, 'import %s' % (m), mdict=self.settings.get) | [
"def",
"s2m",
"(",
"self",
")",
":",
"m",
"=",
"'%s settings'",
"%",
"(",
"IDENT",
")",
"self",
".",
"meta",
".",
"load",
"(",
"m",
",",
"'import %s'",
"%",
"(",
"m",
")",
",",
"mdict",
"=",
"self",
".",
"settings",
".",
"get",
")"
] | Imports settings to meta | [
"Imports",
"settings",
"to",
"meta"
] | 57212a26ce713ab7723910ee49e3d0ba1697799f | https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/photon.py#L170-L176 |
248,724 | nickmilon/Hellas | Hellas/Pella.py | file_to_base64 | def file_to_base64(path_or_obj, max_mb=None):
"""converts contents of a file to base64 encoding
:param str_or_object path_or_obj: fool pathname string for a file or a file like object that supports read
:param int max_mb: maximum number in MegaBytes to accept
:param float lon2: longitude of second plac... | python | def file_to_base64(path_or_obj, max_mb=None):
"""converts contents of a file to base64 encoding
:param str_or_object path_or_obj: fool pathname string for a file or a file like object that supports read
:param int max_mb: maximum number in MegaBytes to accept
:param float lon2: longitude of second plac... | [
"def",
"file_to_base64",
"(",
"path_or_obj",
",",
"max_mb",
"=",
"None",
")",
":",
"if",
"not",
"hasattr",
"(",
"path_or_obj",
",",
"'read'",
")",
":",
"rt",
"=",
"read_file",
"(",
"path_or_obj",
")",
"else",
":",
"rt",
"=",
"path_or_obj",
".",
"read",
... | converts contents of a file to base64 encoding
:param str_or_object path_or_obj: fool pathname string for a file or a file like object that supports read
:param int max_mb: maximum number in MegaBytes to accept
:param float lon2: longitude of second place (decimal degrees)
:raises ErrorFileTooBig: if ... | [
"converts",
"contents",
"of",
"a",
"file",
"to",
"base64",
"encoding"
] | 542e4778692fbec90753942946f20100412ec9ee | https://github.com/nickmilon/Hellas/blob/542e4778692fbec90753942946f20100412ec9ee/Hellas/Pella.py#L27-L45 |
248,725 | nickmilon/Hellas | Hellas/Pella.py | dict_clip | def dict_clip(a_dict, inlude_keys_lst=[]):
"""returns a new dict with keys not in included in inlude_keys_lst clipped off"""
return dict([[i[0], i[1]] for i in list(a_dict.items()) if i[0] in inlude_keys_lst]) | python | def dict_clip(a_dict, inlude_keys_lst=[]):
"""returns a new dict with keys not in included in inlude_keys_lst clipped off"""
return dict([[i[0], i[1]] for i in list(a_dict.items()) if i[0] in inlude_keys_lst]) | [
"def",
"dict_clip",
"(",
"a_dict",
",",
"inlude_keys_lst",
"=",
"[",
"]",
")",
":",
"return",
"dict",
"(",
"[",
"[",
"i",
"[",
"0",
"]",
",",
"i",
"[",
"1",
"]",
"]",
"for",
"i",
"in",
"list",
"(",
"a_dict",
".",
"items",
"(",
")",
")",
"if",... | returns a new dict with keys not in included in inlude_keys_lst clipped off | [
"returns",
"a",
"new",
"dict",
"with",
"keys",
"not",
"in",
"included",
"in",
"inlude_keys_lst",
"clipped",
"off"
] | 542e4778692fbec90753942946f20100412ec9ee | https://github.com/nickmilon/Hellas/blob/542e4778692fbec90753942946f20100412ec9ee/Hellas/Pella.py#L63-L65 |
248,726 | nickmilon/Hellas | Hellas/Pella.py | list_pp | def list_pp(ll, separator='|', header_line=True, autonumber=True):
"""pretty print list of lists ll"""
if autonumber:
for cnt, i in enumerate(ll):
i.insert(0, cnt if cnt > 0 or not header_line else '#')
def lenlst(l):
return [len(str(i)) for i in l]
lst_len = [lenlst(i) for... | python | def list_pp(ll, separator='|', header_line=True, autonumber=True):
"""pretty print list of lists ll"""
if autonumber:
for cnt, i in enumerate(ll):
i.insert(0, cnt if cnt > 0 or not header_line else '#')
def lenlst(l):
return [len(str(i)) for i in l]
lst_len = [lenlst(i) for... | [
"def",
"list_pp",
"(",
"ll",
",",
"separator",
"=",
"'|'",
",",
"header_line",
"=",
"True",
",",
"autonumber",
"=",
"True",
")",
":",
"if",
"autonumber",
":",
"for",
"cnt",
",",
"i",
"in",
"enumerate",
"(",
"ll",
")",
":",
"i",
".",
"insert",
"(",
... | pretty print list of lists ll | [
"pretty",
"print",
"list",
"of",
"lists",
"ll"
] | 542e4778692fbec90753942946f20100412ec9ee | https://github.com/nickmilon/Hellas/blob/542e4778692fbec90753942946f20100412ec9ee/Hellas/Pella.py#L74-L95 |
248,727 | nickmilon/Hellas | Hellas/Pella.py | signal_terminate | def signal_terminate(on_terminate):
"""a common case program termination signal"""
for i in [signal.SIGINT, signal.SIGQUIT, signal.SIGUSR1, signal.SIGUSR2, signal.SIGTERM]:
signal.signal(i, on_terminate) | python | def signal_terminate(on_terminate):
"""a common case program termination signal"""
for i in [signal.SIGINT, signal.SIGQUIT, signal.SIGUSR1, signal.SIGUSR2, signal.SIGTERM]:
signal.signal(i, on_terminate) | [
"def",
"signal_terminate",
"(",
"on_terminate",
")",
":",
"for",
"i",
"in",
"[",
"signal",
".",
"SIGINT",
",",
"signal",
".",
"SIGQUIT",
",",
"signal",
".",
"SIGUSR1",
",",
"signal",
".",
"SIGUSR2",
",",
"signal",
".",
"SIGTERM",
"]",
":",
"signal",
".... | a common case program termination signal | [
"a",
"common",
"case",
"program",
"termination",
"signal"
] | 542e4778692fbec90753942946f20100412ec9ee | https://github.com/nickmilon/Hellas/blob/542e4778692fbec90753942946f20100412ec9ee/Hellas/Pella.py#L99-L102 |
248,728 | polysquare/jobstamps | jobstamps/jobstamp.py | _safe_mkdir | def _safe_mkdir(directory):
"""Create a directory, ignoring errors if it already exists."""
try:
os.makedirs(directory)
except OSError as error:
if error.errno != errno.EEXIST:
raise error | python | def _safe_mkdir(directory):
"""Create a directory, ignoring errors if it already exists."""
try:
os.makedirs(directory)
except OSError as error:
if error.errno != errno.EEXIST:
raise error | [
"def",
"_safe_mkdir",
"(",
"directory",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"directory",
")",
"except",
"OSError",
"as",
"error",
":",
"if",
"error",
".",
"errno",
"!=",
"errno",
".",
"EEXIST",
":",
"raise",
"error"
] | Create a directory, ignoring errors if it already exists. | [
"Create",
"a",
"directory",
"ignoring",
"errors",
"if",
"it",
"already",
"exists",
"."
] | 49b4dec93b38c9db55643226a9788c675a53ef25 | https://github.com/polysquare/jobstamps/blob/49b4dec93b38c9db55643226a9788c675a53ef25/jobstamps/jobstamp.py#L23-L29 |
248,729 | polysquare/jobstamps | jobstamps/jobstamp.py | _stamp_and_update_hook | def _stamp_and_update_hook(method, # suppress(too-many-arguments)
dependencies,
stampfile,
func,
*args,
**kwargs):
"""Write stamp and call update_stampfile_hook on method."""
r... | python | def _stamp_and_update_hook(method, # suppress(too-many-arguments)
dependencies,
stampfile,
func,
*args,
**kwargs):
"""Write stamp and call update_stampfile_hook on method."""
r... | [
"def",
"_stamp_and_update_hook",
"(",
"method",
",",
"# suppress(too-many-arguments)",
"dependencies",
",",
"stampfile",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"_stamp",
"(",
"stampfile",
",",
"func",
",",
"*",
"args... | Write stamp and call update_stampfile_hook on method. | [
"Write",
"stamp",
"and",
"call",
"update_stampfile_hook",
"on",
"method",
"."
] | 49b4dec93b38c9db55643226a9788c675a53ef25 | https://github.com/polysquare/jobstamps/blob/49b4dec93b38c9db55643226a9788c675a53ef25/jobstamps/jobstamp.py#L42-L51 |
248,730 | polysquare/jobstamps | jobstamps/jobstamp.py | _sha1_for_file | def _sha1_for_file(filename):
"""Return sha1 for contents of filename."""
with open(filename, "rb") as fileobj:
contents = fileobj.read()
return hashlib.sha1(contents).hexdigest() | python | def _sha1_for_file(filename):
"""Return sha1 for contents of filename."""
with open(filename, "rb") as fileobj:
contents = fileobj.read()
return hashlib.sha1(contents).hexdigest() | [
"def",
"_sha1_for_file",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"as",
"fileobj",
":",
"contents",
"=",
"fileobj",
".",
"read",
"(",
")",
"return",
"hashlib",
".",
"sha1",
"(",
"contents",
")",
".",
"hexdigest",
... | Return sha1 for contents of filename. | [
"Return",
"sha1",
"for",
"contents",
"of",
"filename",
"."
] | 49b4dec93b38c9db55643226a9788c675a53ef25 | https://github.com/polysquare/jobstamps/blob/49b4dec93b38c9db55643226a9788c675a53ef25/jobstamps/jobstamp.py#L54-L58 |
248,731 | polysquare/jobstamps | jobstamps/jobstamp.py | HashMethod.check_dependency | def check_dependency(self, dependency_path):
"""Check if mtime of dependency_path is greater than stored mtime."""
stored_hash = self._stamp_file_hashes.get(dependency_path)
# This file was newly added, or we don't have a file
# with stored hashes yet. Assume out of date.
if not... | python | def check_dependency(self, dependency_path):
"""Check if mtime of dependency_path is greater than stored mtime."""
stored_hash = self._stamp_file_hashes.get(dependency_path)
# This file was newly added, or we don't have a file
# with stored hashes yet. Assume out of date.
if not... | [
"def",
"check_dependency",
"(",
"self",
",",
"dependency_path",
")",
":",
"stored_hash",
"=",
"self",
".",
"_stamp_file_hashes",
".",
"get",
"(",
"dependency_path",
")",
"# This file was newly added, or we don't have a file",
"# with stored hashes yet. Assume out of date.",
"... | Check if mtime of dependency_path is greater than stored mtime. | [
"Check",
"if",
"mtime",
"of",
"dependency_path",
"is",
"greater",
"than",
"stored",
"mtime",
"."
] | 49b4dec93b38c9db55643226a9788c675a53ef25 | https://github.com/polysquare/jobstamps/blob/49b4dec93b38c9db55643226a9788c675a53ef25/jobstamps/jobstamp.py#L96-L105 |
248,732 | polysquare/jobstamps | jobstamps/jobstamp.py | HashMethod.update_stampfile_hook | def update_stampfile_hook(self, dependencies): # suppress(no-self-use)
"""Loop over all dependencies and store hash for each of them."""
hashes = {d: _sha1_for_file(d) for d in dependencies
if os.path.exists(d)}
with open(self._stamp_file_hashes_path, "wb") as hashes_file:
... | python | def update_stampfile_hook(self, dependencies): # suppress(no-self-use)
"""Loop over all dependencies and store hash for each of them."""
hashes = {d: _sha1_for_file(d) for d in dependencies
if os.path.exists(d)}
with open(self._stamp_file_hashes_path, "wb") as hashes_file:
... | [
"def",
"update_stampfile_hook",
"(",
"self",
",",
"dependencies",
")",
":",
"# suppress(no-self-use)",
"hashes",
"=",
"{",
"d",
":",
"_sha1_for_file",
"(",
"d",
")",
"for",
"d",
"in",
"dependencies",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"d",
")",
... | Loop over all dependencies and store hash for each of them. | [
"Loop",
"over",
"all",
"dependencies",
"and",
"store",
"hash",
"for",
"each",
"of",
"them",
"."
] | 49b4dec93b38c9db55643226a9788c675a53ef25 | https://github.com/polysquare/jobstamps/blob/49b4dec93b38c9db55643226a9788c675a53ef25/jobstamps/jobstamp.py#L107-L112 |
248,733 | markomanninen/abnum | abnum/main.py | Abnum.unicode_value | def unicode_value(self, string):
"""
String argument must be in unicode format.
"""
result = 0
# don't accept strings that contain numbers
if self.regex_has_numbers.search(string):
raise AbnumException(error_msg % string)
else:
num_str = se... | python | def unicode_value(self, string):
"""
String argument must be in unicode format.
"""
result = 0
# don't accept strings that contain numbers
if self.regex_has_numbers.search(string):
raise AbnumException(error_msg % string)
else:
num_str = se... | [
"def",
"unicode_value",
"(",
"self",
",",
"string",
")",
":",
"result",
"=",
"0",
"# don't accept strings that contain numbers",
"if",
"self",
".",
"regex_has_numbers",
".",
"search",
"(",
"string",
")",
":",
"raise",
"AbnumException",
"(",
"error_msg",
"%",
"st... | String argument must be in unicode format. | [
"String",
"argument",
"must",
"be",
"in",
"unicode",
"format",
"."
] | 9bfc8f06f34d9a51aab038638f87e2bb5f9f4c99 | https://github.com/markomanninen/abnum/blob/9bfc8f06f34d9a51aab038638f87e2bb5f9f4c99/abnum/main.py#L65-L81 |
248,734 | ionata/dj-core | dj_core/utils.py | import_from_string | def import_from_string(value):
"""Copy of rest_framework.settings.import_from_string"""
value = value.replace('-', '_')
try:
module_path, class_name = value.rsplit('.', 1)
module = import_module(module_path)
return getattr(module, class_name)
except (ImportError, AttributeError) ... | python | def import_from_string(value):
"""Copy of rest_framework.settings.import_from_string"""
value = value.replace('-', '_')
try:
module_path, class_name = value.rsplit('.', 1)
module = import_module(module_path)
return getattr(module, class_name)
except (ImportError, AttributeError) ... | [
"def",
"import_from_string",
"(",
"value",
")",
":",
"value",
"=",
"value",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"try",
":",
"module_path",
",",
"class_name",
"=",
"value",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"module",
"=",
"import_module... | Copy of rest_framework.settings.import_from_string | [
"Copy",
"of",
"rest_framework",
".",
"settings",
".",
"import_from_string"
] | 7a3139fc433c17f27e7dc2cee8775db21e0b5c89 | https://github.com/ionata/dj-core/blob/7a3139fc433c17f27e7dc2cee8775db21e0b5c89/dj_core/utils.py#L70-L79 |
248,735 | gebn/nibble | nibble/__main__.py | _parse_args | def _parse_args(args):
"""
Interpret command line arguments.
:param args: `sys.argv`
:return: The populated argparse namespace.
"""
parser = argparse.ArgumentParser(prog='nibble',
description='Speed, distance and time '
... | python | def _parse_args(args):
"""
Interpret command line arguments.
:param args: `sys.argv`
:return: The populated argparse namespace.
"""
parser = argparse.ArgumentParser(prog='nibble',
description='Speed, distance and time '
... | [
"def",
"_parse_args",
"(",
"args",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"prog",
"=",
"'nibble'",
",",
"description",
"=",
"'Speed, distance and time '",
"'calculations around '",
"'quantities of digital '",
"'information.'",
")",
"parser",
... | Interpret command line arguments.
:param args: `sys.argv`
:return: The populated argparse namespace. | [
"Interpret",
"command",
"line",
"arguments",
"."
] | e82a2c43509ed38f3d039040591cc630fa676cb0 | https://github.com/gebn/nibble/blob/e82a2c43509ed38f3d039040591cc630fa676cb0/nibble/__main__.py#L14-L38 |
248,736 | gebn/nibble | nibble/__main__.py | main | def main(args):
"""
Nibble's entry point.
:param args: Command-line arguments, with the program in position 0.
"""
args = _parse_args(args)
# sort out logging output and level
level = util.log_level_from_vebosity(args.verbosity)
root = logging.getLogger()
root.setLevel(level)
... | python | def main(args):
"""
Nibble's entry point.
:param args: Command-line arguments, with the program in position 0.
"""
args = _parse_args(args)
# sort out logging output and level
level = util.log_level_from_vebosity(args.verbosity)
root = logging.getLogger()
root.setLevel(level)
... | [
"def",
"main",
"(",
"args",
")",
":",
"args",
"=",
"_parse_args",
"(",
"args",
")",
"# sort out logging output and level",
"level",
"=",
"util",
".",
"log_level_from_vebosity",
"(",
"args",
".",
"verbosity",
")",
"root",
"=",
"logging",
".",
"getLogger",
"(",
... | Nibble's entry point.
:param args: Command-line arguments, with the program in position 0. | [
"Nibble",
"s",
"entry",
"point",
"."
] | e82a2c43509ed38f3d039040591cc630fa676cb0 | https://github.com/gebn/nibble/blob/e82a2c43509ed38f3d039040591cc630fa676cb0/nibble/__main__.py#L41-L68 |
248,737 | cirruscluster/cirruscluster | cirruscluster/ext/ansible/runner/action_plugins/normal.py | ActionModule.run | def run(self, conn, tmp, module_name, module_args, inject):
''' transfer & execute a module that is not 'copy' or 'template' '''
# shell and command are the same module
if module_name == 'shell':
module_name = 'command'
module_args += " #USE_SHELL"
vv("REMOTE_MO... | python | def run(self, conn, tmp, module_name, module_args, inject):
''' transfer & execute a module that is not 'copy' or 'template' '''
# shell and command are the same module
if module_name == 'shell':
module_name = 'command'
module_args += " #USE_SHELL"
vv("REMOTE_MO... | [
"def",
"run",
"(",
"self",
",",
"conn",
",",
"tmp",
",",
"module_name",
",",
"module_args",
",",
"inject",
")",
":",
"# shell and command are the same module",
"if",
"module_name",
"==",
"'shell'",
":",
"module_name",
"=",
"'command'",
"module_args",
"+=",
"\" #... | transfer & execute a module that is not 'copy' or 'template' | [
"transfer",
"&",
"execute",
"a",
"module",
"that",
"is",
"not",
"copy",
"or",
"template"
] | 977409929dd81322d886425cdced10608117d5d7 | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/runner/action_plugins/normal.py#L36-L45 |
248,738 | PSU-OIT-ARC/elasticmodels | elasticmodels/management/commands/__init__.py | get_models | def get_models(args):
"""
Parse a list of ModelName, appname or appname.ModelName list, and return
the list of model classes in the IndexRegistry. If the list if falsy,
return all the models in the registry.
"""
if args:
models = []
for arg in args:
match_found = Fals... | python | def get_models(args):
"""
Parse a list of ModelName, appname or appname.ModelName list, and return
the list of model classes in the IndexRegistry. If the list if falsy,
return all the models in the registry.
"""
if args:
models = []
for arg in args:
match_found = Fals... | [
"def",
"get_models",
"(",
"args",
")",
":",
"if",
"args",
":",
"models",
"=",
"[",
"]",
"for",
"arg",
"in",
"args",
":",
"match_found",
"=",
"False",
"for",
"model",
"in",
"registry",
".",
"get_models",
"(",
")",
":",
"if",
"model",
".",
"_meta",
"... | Parse a list of ModelName, appname or appname.ModelName list, and return
the list of model classes in the IndexRegistry. If the list if falsy,
return all the models in the registry. | [
"Parse",
"a",
"list",
"of",
"ModelName",
"appname",
"or",
"appname",
".",
"ModelName",
"list",
"and",
"return",
"the",
"list",
"of",
"model",
"classes",
"in",
"the",
"IndexRegistry",
".",
"If",
"the",
"list",
"if",
"falsy",
"return",
"all",
"the",
"models"... | 67870508096f66123ef10b89789bbac06571cc80 | https://github.com/PSU-OIT-ARC/elasticmodels/blob/67870508096f66123ef10b89789bbac06571cc80/elasticmodels/management/commands/__init__.py#L3-L26 |
248,739 | ryanjdillon/pyotelem | pyotelem/plots/plotdives.py | plot_dives | def plot_dives(dv0, dv1, p, dp, t_on, t_off):
'''Plots depths and delta depths with dive start stop markers
Args
----
dv0: int
Index position of dive start in cue array
dv1: int
Index position of dive stop in cue array
p: ndarray
Depth values
dp: ndarray
Delt... | python | def plot_dives(dv0, dv1, p, dp, t_on, t_off):
'''Plots depths and delta depths with dive start stop markers
Args
----
dv0: int
Index position of dive start in cue array
dv1: int
Index position of dive stop in cue array
p: ndarray
Depth values
dp: ndarray
Delt... | [
"def",
"plot_dives",
"(",
"dv0",
",",
"dv1",
",",
"p",
",",
"dp",
",",
"t_on",
",",
"t_off",
")",
":",
"fig",
",",
"(",
"ax1",
",",
"ax2",
")",
"=",
"plt",
".",
"subplots",
"(",
"2",
",",
"1",
",",
"sharex",
"=",
"True",
")",
"x0",
"=",
"t_... | Plots depths and delta depths with dive start stop markers
Args
----
dv0: int
Index position of dive start in cue array
dv1: int
Index position of dive stop in cue array
p: ndarray
Depth values
dp: ndarray
Delta depths
t_on: ndarray
Cue array with sta... | [
"Plots",
"depths",
"and",
"delta",
"depths",
"with",
"dive",
"start",
"stop",
"markers"
] | 816563a9c3feb3fa416f1c2921c6b75db34111ad | https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/plots/plotdives.py#L9-L63 |
248,740 | ryanjdillon/pyotelem | pyotelem/plots/plotdives.py | plot_dives_pitch | def plot_dives_pitch(depths, dive_mask, des, asc, pitch, pitch_lf):
'''Plot dives with phase and associated pitch angle with HF signal
Args
----
depths: ndarray
Depth values at each sensor sampling
dive_mask: ndarray
Boolean mask slicing dives from the tag data
des: ndarray
... | python | def plot_dives_pitch(depths, dive_mask, des, asc, pitch, pitch_lf):
'''Plot dives with phase and associated pitch angle with HF signal
Args
----
depths: ndarray
Depth values at each sensor sampling
dive_mask: ndarray
Boolean mask slicing dives from the tag data
des: ndarray
... | [
"def",
"plot_dives_pitch",
"(",
"depths",
",",
"dive_mask",
",",
"des",
",",
"asc",
",",
"pitch",
",",
"pitch_lf",
")",
":",
"import",
"copy",
"import",
"numpy",
"from",
".",
"import",
"plotutils",
"fig",
",",
"(",
"ax1",
",",
"ax2",
")",
"=",
"plt",
... | Plot dives with phase and associated pitch angle with HF signal
Args
----
depths: ndarray
Depth values at each sensor sampling
dive_mask: ndarray
Boolean mask slicing dives from the tag data
des: ndarray
boolean mask for slicing descent phases of dives from tag dta
asc: ... | [
"Plot",
"dives",
"with",
"phase",
"and",
"associated",
"pitch",
"angle",
"with",
"HF",
"signal"
] | 816563a9c3feb3fa416f1c2921c6b75db34111ad | https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/plots/plotdives.py#L66-L117 |
248,741 | ryanjdillon/pyotelem | pyotelem/plots/plotdives.py | plot_depth_descent_ascent | def plot_depth_descent_ascent(depths, dive_mask, des, asc):
'''Plot depth data for whole deployment, descents, and ascents
Args
----
depths: ndarray
Depth values at each sensor sampling
dive_mask: ndarray
Boolean mask slicing dives from the tag data
des: ndarray
boolean ... | python | def plot_depth_descent_ascent(depths, dive_mask, des, asc):
'''Plot depth data for whole deployment, descents, and ascents
Args
----
depths: ndarray
Depth values at each sensor sampling
dive_mask: ndarray
Boolean mask slicing dives from the tag data
des: ndarray
boolean ... | [
"def",
"plot_depth_descent_ascent",
"(",
"depths",
",",
"dive_mask",
",",
"des",
",",
"asc",
")",
":",
"import",
"numpy",
"from",
".",
"import",
"plotutils",
"# Indices where depths are descents or ascents",
"des_ind",
"=",
"numpy",
".",
"where",
"(",
"dive_mask",
... | Plot depth data for whole deployment, descents, and ascents
Args
----
depths: ndarray
Depth values at each sensor sampling
dive_mask: ndarray
Boolean mask slicing dives from the tag data
des: ndarray
boolean mask for slicing descent phases of dives from tag dta
asc: ndar... | [
"Plot",
"depth",
"data",
"for",
"whole",
"deployment",
"descents",
"and",
"ascents"
] | 816563a9c3feb3fa416f1c2921c6b75db34111ad | https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/plots/plotdives.py#L120-L157 |
248,742 | henrysher/kotocore | kotocore/resources.py | Resource._update_docstrings | def _update_docstrings(self):
"""
Runs through the operation methods & updates their docstrings if
necessary.
If the method has the default placeholder docstring, this will replace
it with the docstring from the underlying connection.
"""
ops = self._details.reso... | python | def _update_docstrings(self):
"""
Runs through the operation methods & updates their docstrings if
necessary.
If the method has the default placeholder docstring, this will replace
it with the docstring from the underlying connection.
"""
ops = self._details.reso... | [
"def",
"_update_docstrings",
"(",
"self",
")",
":",
"ops",
"=",
"self",
".",
"_details",
".",
"resource_data",
"[",
"'operations'",
"]",
"for",
"method_name",
"in",
"ops",
".",
"keys",
"(",
")",
":",
"meth",
"=",
"getattr",
"(",
"self",
".",
"__class__",... | Runs through the operation methods & updates their docstrings if
necessary.
If the method has the default placeholder docstring, this will replace
it with the docstring from the underlying connection. | [
"Runs",
"through",
"the",
"operation",
"methods",
"&",
"updates",
"their",
"docstrings",
"if",
"necessary",
"."
] | c52d2f3878b924ceabca07f61c91abcb1b230ecc | https://github.com/henrysher/kotocore/blob/c52d2f3878b924ceabca07f61c91abcb1b230ecc/kotocore/resources.py#L238-L271 |
248,743 | henrysher/kotocore | kotocore/resources.py | Resource.build_relation | def build_relation(self, name, klass=None):
"""
Constructs a related ``Resource`` or ``Collection``.
This allows for construction of classes with information prepopulated
from what the current instance has. This enables syntax like::
bucket = Bucket(bucket='some-bucket-name... | python | def build_relation(self, name, klass=None):
"""
Constructs a related ``Resource`` or ``Collection``.
This allows for construction of classes with information prepopulated
from what the current instance has. This enables syntax like::
bucket = Bucket(bucket='some-bucket-name... | [
"def",
"build_relation",
"(",
"self",
",",
"name",
",",
"klass",
"=",
"None",
")",
":",
"try",
":",
"rel_data",
"=",
"self",
".",
"_details",
".",
"relations",
"[",
"name",
"]",
"except",
"KeyError",
":",
"msg",
"=",
"\"No such relation named '{0}'.\"",
".... | Constructs a related ``Resource`` or ``Collection``.
This allows for construction of classes with information prepopulated
from what the current instance has. This enables syntax like::
bucket = Bucket(bucket='some-bucket-name')
for obj in bucket.objects.each():
... | [
"Constructs",
"a",
"related",
"Resource",
"or",
"Collection",
"."
] | c52d2f3878b924ceabca07f61c91abcb1b230ecc | https://github.com/henrysher/kotocore/blob/c52d2f3878b924ceabca07f61c91abcb1b230ecc/kotocore/resources.py#L312-L372 |
248,744 | henrysher/kotocore | kotocore/resources.py | Resource.post_process_get | def post_process_get(self, result):
"""
Given an object with identifiers, fetches the data for that object
from the service.
This alters the data on the object itself & simply passes through what
was received.
:param result: The response data
:type result: dict
... | python | def post_process_get(self, result):
"""
Given an object with identifiers, fetches the data for that object
from the service.
This alters the data on the object itself & simply passes through what
was received.
:param result: The response data
:type result: dict
... | [
"def",
"post_process_get",
"(",
"self",
",",
"result",
")",
":",
"if",
"not",
"hasattr",
"(",
"result",
",",
"'items'",
")",
":",
"# If it's not a dict, give up & just return whatever you get.",
"return",
"result",
"# We need to possibly drill into the response & get out the ... | Given an object with identifiers, fetches the data for that object
from the service.
This alters the data on the object itself & simply passes through what
was received.
:param result: The response data
:type result: dict
:returns: The unmodified response data | [
"Given",
"an",
"object",
"with",
"identifiers",
"fetches",
"the",
"data",
"for",
"that",
"object",
"from",
"the",
"service",
"."
] | c52d2f3878b924ceabca07f61c91abcb1b230ecc | https://github.com/henrysher/kotocore/blob/c52d2f3878b924ceabca07f61c91abcb1b230ecc/kotocore/resources.py#L489-L519 |
248,745 | henrysher/kotocore | kotocore/resources.py | ResourceFactory.construct_for | def construct_for(self, service_name, resource_name, base_class=None):
"""
Builds a new, specialized ``Resource`` subclass as part of a given
service.
This will load the ``ResourceJSON``, determine the correct
mappings/methods & constructs a brand new class with those methods on... | python | def construct_for(self, service_name, resource_name, base_class=None):
"""
Builds a new, specialized ``Resource`` subclass as part of a given
service.
This will load the ``ResourceJSON``, determine the correct
mappings/methods & constructs a brand new class with those methods on... | [
"def",
"construct_for",
"(",
"self",
",",
"service_name",
",",
"resource_name",
",",
"base_class",
"=",
"None",
")",
":",
"details",
"=",
"self",
".",
"details_class",
"(",
"self",
".",
"session",
",",
"service_name",
",",
"resource_name",
",",
"loader",
"="... | Builds a new, specialized ``Resource`` subclass as part of a given
service.
This will load the ``ResourceJSON``, determine the correct
mappings/methods & constructs a brand new class with those methods on
it.
:param service_name: The name of the service to construct a resource
... | [
"Builds",
"a",
"new",
"specialized",
"Resource",
"subclass",
"as",
"part",
"of",
"a",
"given",
"service",
"."
] | c52d2f3878b924ceabca07f61c91abcb1b230ecc | https://github.com/henrysher/kotocore/blob/c52d2f3878b924ceabca07f61c91abcb1b230ecc/kotocore/resources.py#L580-L624 |
248,746 | awacha/credolib | credolib/io.py | filter_headers | def filter_headers(criterion):
"""Filter already loaded headers against some criterion.
The criterion function must accept a single argument, which is an instance
of sastool.classes2.header.Header, or one of its subclasses. The function
must return True if the header is to be kept or False if it needs ... | python | def filter_headers(criterion):
"""Filter already loaded headers against some criterion.
The criterion function must accept a single argument, which is an instance
of sastool.classes2.header.Header, or one of its subclasses. The function
must return True if the header is to be kept or False if it needs ... | [
"def",
"filter_headers",
"(",
"criterion",
")",
":",
"ip",
"=",
"get_ipython",
"(",
")",
"for",
"headerkind",
"in",
"[",
"'processed'",
",",
"'raw'",
"]",
":",
"for",
"h",
"in",
"ip",
".",
"user_ns",
"[",
"'_headers'",
"]",
"[",
"headerkind",
"]",
"[",... | Filter already loaded headers against some criterion.
The criterion function must accept a single argument, which is an instance
of sastool.classes2.header.Header, or one of its subclasses. The function
must return True if the header is to be kept or False if it needs to be
discarded. All manipulations... | [
"Filter",
"already",
"loaded",
"headers",
"against",
"some",
"criterion",
"."
] | 11c0be3eea7257d3d6e13697d3e76ce538f2f1b2 | https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/io.py#L13-L27 |
248,747 | awacha/credolib | credolib/io.py | load_headers | def load_headers(fsns:List[int]):
"""Load header files
"""
ip = get_ipython()
ip.user_ns['_headers'] = {}
for type_ in ['raw', 'processed']:
print("Loading %d headers (%s)" % (len(fsns), type_), flush=True)
processed = type_ == 'processed'
headers = []
for f in fsns:
... | python | def load_headers(fsns:List[int]):
"""Load header files
"""
ip = get_ipython()
ip.user_ns['_headers'] = {}
for type_ in ['raw', 'processed']:
print("Loading %d headers (%s)" % (len(fsns), type_), flush=True)
processed = type_ == 'processed'
headers = []
for f in fsns:
... | [
"def",
"load_headers",
"(",
"fsns",
":",
"List",
"[",
"int",
"]",
")",
":",
"ip",
"=",
"get_ipython",
"(",
")",
"ip",
".",
"user_ns",
"[",
"'_headers'",
"]",
"=",
"{",
"}",
"for",
"type_",
"in",
"[",
"'raw'",
",",
"'processed'",
"]",
":",
"print",
... | Load header files | [
"Load",
"header",
"files"
] | 11c0be3eea7257d3d6e13697d3e76ce538f2f1b2 | https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/io.py#L29-L55 |
248,748 | hph/mov | mov.py | get_size | def get_size(path):
'''Return the size of path in bytes if it exists and can be determined.'''
size = os.path.getsize(path)
for item in os.walk(path):
for file in item[2]:
size += os.path.getsize(os.path.join(item[0], file))
return size | python | def get_size(path):
'''Return the size of path in bytes if it exists and can be determined.'''
size = os.path.getsize(path)
for item in os.walk(path):
for file in item[2]:
size += os.path.getsize(os.path.join(item[0], file))
return size | [
"def",
"get_size",
"(",
"path",
")",
":",
"size",
"=",
"os",
".",
"path",
".",
"getsize",
"(",
"path",
")",
"for",
"item",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"for",
"file",
"in",
"item",
"[",
"2",
"]",
":",
"size",
"+=",
"os",
".... | Return the size of path in bytes if it exists and can be determined. | [
"Return",
"the",
"size",
"of",
"path",
"in",
"bytes",
"if",
"it",
"exists",
"and",
"can",
"be",
"determined",
"."
] | 36a18d92836e1aff74ca02e16ce09d1c46e111b9 | https://github.com/hph/mov/blob/36a18d92836e1aff74ca02e16ce09d1c46e111b9/mov.py#L52-L58 |
248,749 | hph/mov | mov.py | local_data | def local_data(path):
"""Return tuples of names, directories, total sizes and files. Each
directory represents a single film and the files are the files contained
in the directory, such as video, audio and subtitle files."""
dirs = [os.path.join(path, item) for item in os.listdir(path)]
names,... | python | def local_data(path):
"""Return tuples of names, directories, total sizes and files. Each
directory represents a single film and the files are the files contained
in the directory, such as video, audio and subtitle files."""
dirs = [os.path.join(path, item) for item in os.listdir(path)]
names,... | [
"def",
"local_data",
"(",
"path",
")",
":",
"dirs",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"item",
")",
"for",
"item",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
"]",
"names",
",",
"sizes",
",",
"files",
"=",
"zip",
"(",... | Return tuples of names, directories, total sizes and files. Each
directory represents a single film and the files are the files contained
in the directory, such as video, audio and subtitle files. | [
"Return",
"tuples",
"of",
"names",
"directories",
"total",
"sizes",
"and",
"files",
".",
"Each",
"directory",
"represents",
"a",
"single",
"film",
"and",
"the",
"files",
"are",
"the",
"files",
"contained",
"in",
"the",
"directory",
"such",
"as",
"video",
"au... | 36a18d92836e1aff74ca02e16ce09d1c46e111b9 | https://github.com/hph/mov/blob/36a18d92836e1aff74ca02e16ce09d1c46e111b9/mov.py#L61-L69 |
248,750 | hph/mov | mov.py | create | def create():
"""Create a new database with information about the films in the specified
directory or directories."""
if not all(map(os.path.isdir, ARGS.directory)):
exit('Error: One or more of the specified directories does not exist.')
with sqlite3.connect(ARGS.database) as connection:
... | python | def create():
"""Create a new database with information about the films in the specified
directory or directories."""
if not all(map(os.path.isdir, ARGS.directory)):
exit('Error: One or more of the specified directories does not exist.')
with sqlite3.connect(ARGS.database) as connection:
... | [
"def",
"create",
"(",
")",
":",
"if",
"not",
"all",
"(",
"map",
"(",
"os",
".",
"path",
".",
"isdir",
",",
"ARGS",
".",
"directory",
")",
")",
":",
"exit",
"(",
"'Error: One or more of the specified directories does not exist.'",
")",
"with",
"sqlite3",
".",... | Create a new database with information about the films in the specified
directory or directories. | [
"Create",
"a",
"new",
"database",
"with",
"information",
"about",
"the",
"films",
"in",
"the",
"specified",
"directory",
"or",
"directories",
"."
] | 36a18d92836e1aff74ca02e16ce09d1c46e111b9 | https://github.com/hph/mov/blob/36a18d92836e1aff74ca02e16ce09d1c46e111b9/mov.py#L88-L101 |
248,751 | hph/mov | mov.py | ls | def ls():
"""List all items in the database in a predefined format."""
if not os.path.exists(ARGS.database):
exit('Error: The database does not exist; you must create it first.')
with sqlite3.connect(ARGS.database) as connection:
connection.text_factory = str
cursor = connection.curs... | python | def ls():
"""List all items in the database in a predefined format."""
if not os.path.exists(ARGS.database):
exit('Error: The database does not exist; you must create it first.')
with sqlite3.connect(ARGS.database) as connection:
connection.text_factory = str
cursor = connection.curs... | [
"def",
"ls",
"(",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"ARGS",
".",
"database",
")",
":",
"exit",
"(",
"'Error: The database does not exist; you must create it first.'",
")",
"with",
"sqlite3",
".",
"connect",
"(",
"ARGS",
".",
"data... | List all items in the database in a predefined format. | [
"List",
"all",
"items",
"in",
"the",
"database",
"in",
"a",
"predefined",
"format",
"."
] | 36a18d92836e1aff74ca02e16ce09d1c46e111b9 | https://github.com/hph/mov/blob/36a18d92836e1aff74ca02e16ce09d1c46e111b9/mov.py#L121-L152 |
248,752 | hph/mov | mov.py | play | def play():
"""Open the matched movie with a media player."""
with sqlite3.connect(ARGS.database) as connection:
connection.text_factory = str
cursor = connection.cursor()
if ARGS.pattern:
if not ARGS.strict:
ARGS.pattern = '%{0}%'.format(ARGS.pattern)
... | python | def play():
"""Open the matched movie with a media player."""
with sqlite3.connect(ARGS.database) as connection:
connection.text_factory = str
cursor = connection.cursor()
if ARGS.pattern:
if not ARGS.strict:
ARGS.pattern = '%{0}%'.format(ARGS.pattern)
... | [
"def",
"play",
"(",
")",
":",
"with",
"sqlite3",
".",
"connect",
"(",
"ARGS",
".",
"database",
")",
"as",
"connection",
":",
"connection",
".",
"text_factory",
"=",
"str",
"cursor",
"=",
"connection",
".",
"cursor",
"(",
")",
"if",
"ARGS",
".",
"patter... | Open the matched movie with a media player. | [
"Open",
"the",
"matched",
"movie",
"with",
"a",
"media",
"player",
"."
] | 36a18d92836e1aff74ca02e16ce09d1c46e111b9 | https://github.com/hph/mov/blob/36a18d92836e1aff74ca02e16ce09d1c46e111b9/mov.py#L155-L172 |
248,753 | amaas-fintech/amaas-utils-python | amaasutils/random_utils.py | random_string | def random_string(length, numeric_only=False):
"""
Generates a random string of length equal to the length parameter
"""
choices = string.digits if numeric_only else string.ascii_uppercase + string.digits
return ''.join(random.choice(choices) for _ in range(length)) | python | def random_string(length, numeric_only=False):
"""
Generates a random string of length equal to the length parameter
"""
choices = string.digits if numeric_only else string.ascii_uppercase + string.digits
return ''.join(random.choice(choices) for _ in range(length)) | [
"def",
"random_string",
"(",
"length",
",",
"numeric_only",
"=",
"False",
")",
":",
"choices",
"=",
"string",
".",
"digits",
"if",
"numeric_only",
"else",
"string",
".",
"ascii_uppercase",
"+",
"string",
".",
"digits",
"return",
"''",
".",
"join",
"(",
"ra... | Generates a random string of length equal to the length parameter | [
"Generates",
"a",
"random",
"string",
"of",
"length",
"equal",
"to",
"the",
"length",
"parameter"
] | 5aa64ca65ce0c77b513482d943345d94c9ae58e8 | https://github.com/amaas-fintech/amaas-utils-python/blob/5aa64ca65ce0c77b513482d943345d94c9ae58e8/amaasutils/random_utils.py#L10-L15 |
248,754 | amaas-fintech/amaas-utils-python | amaasutils/random_utils.py | random_date | def random_date(start_year=2000, end_year=2020):
"""
Generates a random "sensible" date for use in things like issue dates and maturities
"""
return date(random.randint(start_year, end_year), random.randint(1, 12), random.randint(1, 28)) | python | def random_date(start_year=2000, end_year=2020):
"""
Generates a random "sensible" date for use in things like issue dates and maturities
"""
return date(random.randint(start_year, end_year), random.randint(1, 12), random.randint(1, 28)) | [
"def",
"random_date",
"(",
"start_year",
"=",
"2000",
",",
"end_year",
"=",
"2020",
")",
":",
"return",
"date",
"(",
"random",
".",
"randint",
"(",
"start_year",
",",
"end_year",
")",
",",
"random",
".",
"randint",
"(",
"1",
",",
"12",
")",
",",
"ran... | Generates a random "sensible" date for use in things like issue dates and maturities | [
"Generates",
"a",
"random",
"sensible",
"date",
"for",
"use",
"in",
"things",
"like",
"issue",
"dates",
"and",
"maturities"
] | 5aa64ca65ce0c77b513482d943345d94c9ae58e8 | https://github.com/amaas-fintech/amaas-utils-python/blob/5aa64ca65ce0c77b513482d943345d94c9ae58e8/amaasutils/random_utils.py#L25-L29 |
248,755 | scott-maddox/simpleqw | src/simpleqw/_finite_well.py | _finite_well_energy | def _finite_well_energy(P, n=1, atol=1e-6):
'''
Returns the nth bound-state energy for a finite-potential quantum well
with the given well-strength parameter, `P`.
'''
assert n > 0 and n <= _finite_well_states(P)
pi_2 = pi / 2.
r = (1 / (P + pi_2)) * (n * pi_2)
eta = n * pi_2 - arcsin(r)... | python | def _finite_well_energy(P, n=1, atol=1e-6):
'''
Returns the nth bound-state energy for a finite-potential quantum well
with the given well-strength parameter, `P`.
'''
assert n > 0 and n <= _finite_well_states(P)
pi_2 = pi / 2.
r = (1 / (P + pi_2)) * (n * pi_2)
eta = n * pi_2 - arcsin(r)... | [
"def",
"_finite_well_energy",
"(",
"P",
",",
"n",
"=",
"1",
",",
"atol",
"=",
"1e-6",
")",
":",
"assert",
"n",
">",
"0",
"and",
"n",
"<=",
"_finite_well_states",
"(",
"P",
")",
"pi_2",
"=",
"pi",
"/",
"2.",
"r",
"=",
"(",
"1",
"/",
"(",
"P",
... | Returns the nth bound-state energy for a finite-potential quantum well
with the given well-strength parameter, `P`. | [
"Returns",
"the",
"nth",
"bound",
"-",
"state",
"energy",
"for",
"a",
"finite",
"-",
"potential",
"quantum",
"well",
"with",
"the",
"given",
"well",
"-",
"strength",
"parameter",
"P",
"."
] | 83c1c7ff1f0bac9ddeb6f00fcbb8fafe6ec97f6b | https://github.com/scott-maddox/simpleqw/blob/83c1c7ff1f0bac9ddeb6f00fcbb8fafe6ec97f6b/src/simpleqw/_finite_well.py#L46-L79 |
248,756 | Pringley/spyglass | spyglass/scraper.py | Scraper.top | def top(self, n=10, cache=None, prefetch=False):
"""Find the most popular torrents.
Return an array of Torrent objects representing the top n torrents. If
the cache option is non-None, override the Scraper's default caching
settings.
Use the prefetch option to hit each Torrent'... | python | def top(self, n=10, cache=None, prefetch=False):
"""Find the most popular torrents.
Return an array of Torrent objects representing the top n torrents. If
the cache option is non-None, override the Scraper's default caching
settings.
Use the prefetch option to hit each Torrent'... | [
"def",
"top",
"(",
"self",
",",
"n",
"=",
"10",
",",
"cache",
"=",
"None",
",",
"prefetch",
"=",
"False",
")",
":",
"use_cache",
"=",
"self",
".",
"_use_cache",
"(",
"cache",
")",
"if",
"use_cache",
"and",
"len",
"(",
"self",
".",
"_top_cache",
")"... | Find the most popular torrents.
Return an array of Torrent objects representing the top n torrents. If
the cache option is non-None, override the Scraper's default caching
settings.
Use the prefetch option to hit each Torrent's info page up front
(instead of lazy fetching the i... | [
"Find",
"the",
"most",
"popular",
"torrents",
"."
] | 091d74f34837673af936daa9f462ad8216be9916 | https://github.com/Pringley/spyglass/blob/091d74f34837673af936daa9f462ad8216be9916/spyglass/scraper.py#L15-L37 |
248,757 | Pringley/spyglass | spyglass/scraper.py | Scraper.torrent_from_url | def torrent_from_url(self, url, cache=True, prefetch=False):
"""Create a Torrent object from a given URL.
If the cache option is set, check to see if we already have a Torrent
object representing it. If prefetch is set, automatically query the
torrent's info page to fill in the torrent ... | python | def torrent_from_url(self, url, cache=True, prefetch=False):
"""Create a Torrent object from a given URL.
If the cache option is set, check to see if we already have a Torrent
object representing it. If prefetch is set, automatically query the
torrent's info page to fill in the torrent ... | [
"def",
"torrent_from_url",
"(",
"self",
",",
"url",
",",
"cache",
"=",
"True",
",",
"prefetch",
"=",
"False",
")",
":",
"if",
"self",
".",
"_use_cache",
"(",
"cache",
")",
"and",
"url",
"in",
"self",
".",
"_torrent_cache",
":",
"return",
"self",
".",
... | Create a Torrent object from a given URL.
If the cache option is set, check to see if we already have a Torrent
object representing it. If prefetch is set, automatically query the
torrent's info page to fill in the torrent object. (If prefetch is
false, then the torrent page will be que... | [
"Create",
"a",
"Torrent",
"object",
"from",
"a",
"given",
"URL",
"."
] | 091d74f34837673af936daa9f462ad8216be9916 | https://github.com/Pringley/spyglass/blob/091d74f34837673af936daa9f462ad8216be9916/spyglass/scraper.py#L61-L75 |
248,758 | frejanordsiek/GeminiMotorDrive | GeminiMotorDrive/drivers.py | ASCII_RS232._send_command | def _send_command(self, command, immediate=False, timeout=1.0,
check_echo=None):
""" Send a single command to the drive after sanitizing it.
Takes a single given `command`, sanitizes it (strips out
comments, extra whitespace, and newlines), sends the command to
the... | python | def _send_command(self, command, immediate=False, timeout=1.0,
check_echo=None):
""" Send a single command to the drive after sanitizing it.
Takes a single given `command`, sanitizes it (strips out
comments, extra whitespace, and newlines), sends the command to
the... | [
"def",
"_send_command",
"(",
"self",
",",
"command",
",",
"immediate",
"=",
"False",
",",
"timeout",
"=",
"1.0",
",",
"check_echo",
"=",
"None",
")",
":",
"# Use the default echo checking if None was given.",
"if",
"check_echo",
"is",
"None",
":",
"check_echo",
... | Send a single command to the drive after sanitizing it.
Takes a single given `command`, sanitizes it (strips out
comments, extra whitespace, and newlines), sends the command to
the drive, and returns the sanitized command. The validity of
the command is **NOT** checked.
Paramet... | [
"Send",
"a",
"single",
"command",
"to",
"the",
"drive",
"after",
"sanitizing",
"it",
"."
] | 8de347ffb91228fbfe3832098b4996fa0141d8f1 | https://github.com/frejanordsiek/GeminiMotorDrive/blob/8de347ffb91228fbfe3832098b4996fa0141d8f1/GeminiMotorDrive/drivers.py#L127-L251 |
248,759 | frejanordsiek/GeminiMotorDrive | GeminiMotorDrive/drivers.py | ASCII_RS232._get_response | def _get_response(self, timeout=1.0, eor=('\n', '\n- ')):
""" Reads a response from the drive.
Reads the response returned by the drive with an optional
timeout. All carriage returns and linefeeds are kept.
Parameters
----------
timeout : number, optional
Op... | python | def _get_response(self, timeout=1.0, eor=('\n', '\n- ')):
""" Reads a response from the drive.
Reads the response returned by the drive with an optional
timeout. All carriage returns and linefeeds are kept.
Parameters
----------
timeout : number, optional
Op... | [
"def",
"_get_response",
"(",
"self",
",",
"timeout",
"=",
"1.0",
",",
"eor",
"=",
"(",
"'\\n'",
",",
"'\\n- '",
")",
")",
":",
"# If no timeout is given or it is invalid and we are using '\\n'",
"# as the eor, use the wrapper to read a line with an infinite",
"# timeout. Othe... | Reads a response from the drive.
Reads the response returned by the drive with an optional
timeout. All carriage returns and linefeeds are kept.
Parameters
----------
timeout : number, optional
Optional timeout in seconds to use when reading the
response... | [
"Reads",
"a",
"response",
"from",
"the",
"drive",
"."
] | 8de347ffb91228fbfe3832098b4996fa0141d8f1 | https://github.com/frejanordsiek/GeminiMotorDrive/blob/8de347ffb91228fbfe3832098b4996fa0141d8f1/GeminiMotorDrive/drivers.py#L253-L338 |
248,760 | frejanordsiek/GeminiMotorDrive | GeminiMotorDrive/drivers.py | ASCII_RS232._process_response | def _process_response(self, response):
""" Processes a response from the drive.
Processes the response returned from the drive. It is broken
down into the echoed command (drive echoes it back), any error
returned by the drive (leading '*' is stripped), and the
different lines of... | python | def _process_response(self, response):
""" Processes a response from the drive.
Processes the response returned from the drive. It is broken
down into the echoed command (drive echoes it back), any error
returned by the drive (leading '*' is stripped), and the
different lines of... | [
"def",
"_process_response",
"(",
"self",
",",
"response",
")",
":",
"# Strip the trailing newline and split the response into lines",
"# by carriage returns.",
"rsp_lines",
"=",
"response",
".",
"rstrip",
"(",
"'\\r\\n'",
")",
".",
"split",
"(",
"'\\r'",
")",
"# If we h... | Processes a response from the drive.
Processes the response returned from the drive. It is broken
down into the echoed command (drive echoes it back), any error
returned by the drive (leading '*' is stripped), and the
different lines of the response.
Parameters
--------... | [
"Processes",
"a",
"response",
"from",
"the",
"drive",
"."
] | 8de347ffb91228fbfe3832098b4996fa0141d8f1 | https://github.com/frejanordsiek/GeminiMotorDrive/blob/8de347ffb91228fbfe3832098b4996fa0141d8f1/GeminiMotorDrive/drivers.py#L340-L391 |
248,761 | frejanordsiek/GeminiMotorDrive | GeminiMotorDrive/drivers.py | ASCII_RS232.send_command | def send_command(self, command, immediate=False, timeout=1.0,
max_retries=0, eor=('\n', '\n- ')):
""" Sends a single command to the drive and returns output.
Takes a single given `command`, sanitizes it, sends it to the
drive, reads the response, and returns the processed r... | python | def send_command(self, command, immediate=False, timeout=1.0,
max_retries=0, eor=('\n', '\n- ')):
""" Sends a single command to the drive and returns output.
Takes a single given `command`, sanitizes it, sends it to the
drive, reads the response, and returns the processed r... | [
"def",
"send_command",
"(",
"self",
",",
"command",
",",
"immediate",
"=",
"False",
",",
"timeout",
"=",
"1.0",
",",
"max_retries",
"=",
"0",
",",
"eor",
"=",
"(",
"'\\n'",
",",
"'\\n- '",
")",
")",
":",
"# Execute the command till it either doesn't have an er... | Sends a single command to the drive and returns output.
Takes a single given `command`, sanitizes it, sends it to the
drive, reads the response, and returns the processed response.
The command is first sanitized by removing comments, extra
whitespace, and newline characters. If `immedia... | [
"Sends",
"a",
"single",
"command",
"to",
"the",
"drive",
"and",
"returns",
"output",
"."
] | 8de347ffb91228fbfe3832098b4996fa0141d8f1 | https://github.com/frejanordsiek/GeminiMotorDrive/blob/8de347ffb91228fbfe3832098b4996fa0141d8f1/GeminiMotorDrive/drivers.py#L420-L527 |
248,762 | frejanordsiek/GeminiMotorDrive | GeminiMotorDrive/drivers.py | ASCII_RS232.send_commands | def send_commands(self, commands, timeout=1.0,
max_retries=1, eor=('\n', '\n- ')):
""" Send a sequence of commands to the drive and collect output.
Takes a sequence of many commands and executes them one by one
till either all are executed or one runs out of retries
... | python | def send_commands(self, commands, timeout=1.0,
max_retries=1, eor=('\n', '\n- ')):
""" Send a sequence of commands to the drive and collect output.
Takes a sequence of many commands and executes them one by one
till either all are executed or one runs out of retries
... | [
"def",
"send_commands",
"(",
"self",
",",
"commands",
",",
"timeout",
"=",
"1.0",
",",
"max_retries",
"=",
"1",
",",
"eor",
"=",
"(",
"'\\n'",
",",
"'\\n- '",
")",
")",
":",
"# If eor is not a list, make a list of it replicated enough for",
"# every command.",
"if... | Send a sequence of commands to the drive and collect output.
Takes a sequence of many commands and executes them one by one
till either all are executed or one runs out of retries
(`max_retries`). Retries are optionally performed if a command's
repsonse indicates that there was an error... | [
"Send",
"a",
"sequence",
"of",
"commands",
"to",
"the",
"drive",
"and",
"collect",
"output",
"."
] | 8de347ffb91228fbfe3832098b4996fa0141d8f1 | https://github.com/frejanordsiek/GeminiMotorDrive/blob/8de347ffb91228fbfe3832098b4996fa0141d8f1/GeminiMotorDrive/drivers.py#L529-L631 |
248,763 | tagcubeio/tagcube-cli | tagcube/client/api.py | TagCubeClient.low_level_scan | def low_level_scan(self, verification_resource, scan_profile_resource,
path_list, notification_resource_list):
"""
Low level implementation of the scan launch which allows you to start
a new scan when you already know the ids for the required resources.
:param ver... | python | def low_level_scan(self, verification_resource, scan_profile_resource,
path_list, notification_resource_list):
"""
Low level implementation of the scan launch which allows you to start
a new scan when you already know the ids for the required resources.
:param ver... | [
"def",
"low_level_scan",
"(",
"self",
",",
"verification_resource",
",",
"scan_profile_resource",
",",
"path_list",
",",
"notification_resource_list",
")",
":",
"data",
"=",
"{",
"\"verification_href\"",
":",
"verification_resource",
".",
"href",
",",
"\"profile_href\""... | Low level implementation of the scan launch which allows you to start
a new scan when you already know the ids for the required resources.
:param verification_resource: The verification associated with the
domain resource to scan
:param scan_profile_resourc... | [
"Low",
"level",
"implementation",
"of",
"the",
"scan",
"launch",
"which",
"allows",
"you",
"to",
"start",
"a",
"new",
"scan",
"when",
"you",
"already",
"know",
"the",
"ids",
"for",
"the",
"required",
"resources",
"."
] | 709e4b0b11331a4d2791dc79107e5081518d75bf | https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube/client/api.py#L182-L218 |
248,764 | xgvargas/smartside | smartside/__init__.py | setAsApplication | def setAsApplication(myappid):
"""
Tells Windows this is an independent application with an unique icon on task bar.
id is an unique string to identify this application, like: 'mycompany.myproduct.subproduct.version'
"""
if os.name == 'nt':
import ctypes
ctypes.windll.shell32.SetCu... | python | def setAsApplication(myappid):
"""
Tells Windows this is an independent application with an unique icon on task bar.
id is an unique string to identify this application, like: 'mycompany.myproduct.subproduct.version'
"""
if os.name == 'nt':
import ctypes
ctypes.windll.shell32.SetCu... | [
"def",
"setAsApplication",
"(",
"myappid",
")",
":",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"import",
"ctypes",
"ctypes",
".",
"windll",
".",
"shell32",
".",
"SetCurrentProcessExplicitAppUserModelID",
"(",
"myappid",
")"
] | Tells Windows this is an independent application with an unique icon on task bar.
id is an unique string to identify this application, like: 'mycompany.myproduct.subproduct.version' | [
"Tells",
"Windows",
"this",
"is",
"an",
"independent",
"application",
"with",
"an",
"unique",
"icon",
"on",
"task",
"bar",
"."
] | c63acb7d628b161f438e877eca12d550647de34d | https://github.com/xgvargas/smartside/blob/c63acb7d628b161f438e877eca12d550647de34d/smartside/__init__.py#L11-L20 |
248,765 | xgvargas/smartside | smartside/__init__.py | getBestTranslation | def getBestTranslation(basedir, lang=None):
"""
Find inside basedir the best translation available.
lang, if defined, should be a list of prefered languages.
It will look for file in the form:
- en-US.qm
- en_US.qm
- en.qm
"""
if not lang:
lang = QtCore.QLocale.system().uiL... | python | def getBestTranslation(basedir, lang=None):
"""
Find inside basedir the best translation available.
lang, if defined, should be a list of prefered languages.
It will look for file in the form:
- en-US.qm
- en_US.qm
- en.qm
"""
if not lang:
lang = QtCore.QLocale.system().uiL... | [
"def",
"getBestTranslation",
"(",
"basedir",
",",
"lang",
"=",
"None",
")",
":",
"if",
"not",
"lang",
":",
"lang",
"=",
"QtCore",
".",
"QLocale",
".",
"system",
"(",
")",
".",
"uiLanguages",
"(",
")",
"for",
"l",
"in",
"lang",
":",
"l",
"=",
"l",
... | Find inside basedir the best translation available.
lang, if defined, should be a list of prefered languages.
It will look for file in the form:
- en-US.qm
- en_US.qm
- en.qm | [
"Find",
"inside",
"basedir",
"the",
"best",
"translation",
"available",
"."
] | c63acb7d628b161f438e877eca12d550647de34d | https://github.com/xgvargas/smartside/blob/c63acb7d628b161f438e877eca12d550647de34d/smartside/__init__.py#L23-L56 |
248,766 | davisd50/sparc.cache | sparc/cache/sources/normalize.py | normalizedFieldNameCachableItemMixin.normalize | def normalize(cls, name):
"""Return string in all lower case with spaces and question marks removed"""
name = name.lower() # lower-case
for _replace in [' ','-','(',')','?']:
name = name.replace(_replace,'')
return name | python | def normalize(cls, name):
"""Return string in all lower case with spaces and question marks removed"""
name = name.lower() # lower-case
for _replace in [' ','-','(',')','?']:
name = name.replace(_replace,'')
return name | [
"def",
"normalize",
"(",
"cls",
",",
"name",
")",
":",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"# lower-case",
"for",
"_replace",
"in",
"[",
"' '",
",",
"'-'",
",",
"'('",
",",
"')'",
",",
"'?'",
"]",
":",
"name",
"=",
"name",
".",
"replace"... | Return string in all lower case with spaces and question marks removed | [
"Return",
"string",
"in",
"all",
"lower",
"case",
"with",
"spaces",
"and",
"question",
"marks",
"removed"
] | f2378aad48c368a53820e97b093ace790d4d4121 | https://github.com/davisd50/sparc.cache/blob/f2378aad48c368a53820e97b093ace790d4d4121/sparc/cache/sources/normalize.py#L67-L72 |
248,767 | abe-winter/pg13-py | pg13/threevl.py | ThreeVL.nein | def nein(x):
"this is 'not' but not is a keyword so it's 'nein'"
if not isinstance(x,(bool,ThreeVL)): raise TypeError(type(x))
return not x if isinstance(x,bool) else ThreeVL(dict(t='f',f='t',u='u')[x.value]) | python | def nein(x):
"this is 'not' but not is a keyword so it's 'nein'"
if not isinstance(x,(bool,ThreeVL)): raise TypeError(type(x))
return not x if isinstance(x,bool) else ThreeVL(dict(t='f',f='t',u='u')[x.value]) | [
"def",
"nein",
"(",
"x",
")",
":",
"if",
"not",
"isinstance",
"(",
"x",
",",
"(",
"bool",
",",
"ThreeVL",
")",
")",
":",
"raise",
"TypeError",
"(",
"type",
"(",
"x",
")",
")",
"return",
"not",
"x",
"if",
"isinstance",
"(",
"x",
",",
"bool",
")"... | this is 'not' but not is a keyword so it's 'nein | [
"this",
"is",
"not",
"but",
"not",
"is",
"a",
"keyword",
"so",
"it",
"s",
"nein"
] | c78806f99f35541a8756987e86edca3438aa97f5 | https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/threevl.py#L24-L27 |
248,768 | abe-winter/pg13-py | pg13/threevl.py | ThreeVL.compare | def compare(operator,a,b):
"this could be replaced by overloading but I want == to return a bool for 'in' use"
# todo(awinter): what about nested 3vl like "(a=b)=(c=d)". is that allowed by sql? It will choke here if there's a null involved.
f=({'=':lambda a,b:a==b,'!=':lambda a,b:a!=b,'>':lambda a,b:a>b,'<'... | python | def compare(operator,a,b):
"this could be replaced by overloading but I want == to return a bool for 'in' use"
# todo(awinter): what about nested 3vl like "(a=b)=(c=d)". is that allowed by sql? It will choke here if there's a null involved.
f=({'=':lambda a,b:a==b,'!=':lambda a,b:a!=b,'>':lambda a,b:a>b,'<'... | [
"def",
"compare",
"(",
"operator",
",",
"a",
",",
"b",
")",
":",
"# todo(awinter): what about nested 3vl like \"(a=b)=(c=d)\". is that allowed by sql? It will choke here if there's a null involved.",
"f",
"=",
"(",
"{",
"'='",
":",
"lambda",
"a",
",",
"b",
":",
"a",
"==... | this could be replaced by overloading but I want == to return a bool for 'in' use | [
"this",
"could",
"be",
"replaced",
"by",
"overloading",
"but",
"I",
"want",
"==",
"to",
"return",
"a",
"bool",
"for",
"in",
"use"
] | c78806f99f35541a8756987e86edca3438aa97f5 | https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/threevl.py#L41-L45 |
248,769 | PSU-OIT-ARC/django-cloak | cloak/views.py | login | def login(request, signature):
"""
Automatically logs in a user based on a signed PK of a user object. The
signature should be generated with the `login` management command.
The signature will only work for 60 seconds.
"""
signer = TimestampSigner()
try:
pk = signer.unsign(signature... | python | def login(request, signature):
"""
Automatically logs in a user based on a signed PK of a user object. The
signature should be generated with the `login` management command.
The signature will only work for 60 seconds.
"""
signer = TimestampSigner()
try:
pk = signer.unsign(signature... | [
"def",
"login",
"(",
"request",
",",
"signature",
")",
":",
"signer",
"=",
"TimestampSigner",
"(",
")",
"try",
":",
"pk",
"=",
"signer",
".",
"unsign",
"(",
"signature",
",",
"max_age",
"=",
"MAX_AGE_OF_SIGNATURE_IN_SECONDS",
")",
"except",
"(",
"BadSignatur... | Automatically logs in a user based on a signed PK of a user object. The
signature should be generated with the `login` management command.
The signature will only work for 60 seconds. | [
"Automatically",
"logs",
"in",
"a",
"user",
"based",
"on",
"a",
"signed",
"PK",
"of",
"a",
"user",
"object",
".",
"The",
"signature",
"should",
"be",
"generated",
"with",
"the",
"login",
"management",
"command",
"."
] | 3f09711837f4fe7b1813692daa064e536135ffa3 | https://github.com/PSU-OIT-ARC/django-cloak/blob/3f09711837f4fe7b1813692daa064e536135ffa3/cloak/views.py#L12-L30 |
248,770 | PSU-OIT-ARC/django-cloak | cloak/views.py | cloak | def cloak(request, pk=None):
"""
Masquerade as a particular user and redirect based on the
REDIRECT_FIELD_NAME parameter, or the LOGIN_REDIRECT_URL.
Callers can either pass the pk of the user in the URL itself, or as a POST
param.
"""
pk = request.POST.get('pk', pk)
if pk is None:
... | python | def cloak(request, pk=None):
"""
Masquerade as a particular user and redirect based on the
REDIRECT_FIELD_NAME parameter, or the LOGIN_REDIRECT_URL.
Callers can either pass the pk of the user in the URL itself, or as a POST
param.
"""
pk = request.POST.get('pk', pk)
if pk is None:
... | [
"def",
"cloak",
"(",
"request",
",",
"pk",
"=",
"None",
")",
":",
"pk",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"'pk'",
",",
"pk",
")",
"if",
"pk",
"is",
"None",
":",
"return",
"HttpResponse",
"(",
"\"You need to pass a pk POST parameter, or include ... | Masquerade as a particular user and redirect based on the
REDIRECT_FIELD_NAME parameter, or the LOGIN_REDIRECT_URL.
Callers can either pass the pk of the user in the URL itself, or as a POST
param. | [
"Masquerade",
"as",
"a",
"particular",
"user",
"and",
"redirect",
"based",
"on",
"the",
"REDIRECT_FIELD_NAME",
"parameter",
"or",
"the",
"LOGIN_REDIRECT_URL",
"."
] | 3f09711837f4fe7b1813692daa064e536135ffa3 | https://github.com/PSU-OIT-ARC/django-cloak/blob/3f09711837f4fe7b1813692daa064e536135ffa3/cloak/views.py#L34-L58 |
248,771 | chrisdrackett/django-support | support/templatetags/form_tags.py | select_template_from_string | def select_template_from_string(arg):
"""
Select a template from a string, which can include multiple
template paths separated by commas.
"""
if ',' in arg:
tpl = loader.select_template(
[tn.strip() for tn in arg.split(',')])
else:
tpl = loader.get_template(arg)
... | python | def select_template_from_string(arg):
"""
Select a template from a string, which can include multiple
template paths separated by commas.
"""
if ',' in arg:
tpl = loader.select_template(
[tn.strip() for tn in arg.split(',')])
else:
tpl = loader.get_template(arg)
... | [
"def",
"select_template_from_string",
"(",
"arg",
")",
":",
"if",
"','",
"in",
"arg",
":",
"tpl",
"=",
"loader",
".",
"select_template",
"(",
"[",
"tn",
".",
"strip",
"(",
")",
"for",
"tn",
"in",
"arg",
".",
"split",
"(",
"','",
")",
"]",
")",
"els... | Select a template from a string, which can include multiple
template paths separated by commas. | [
"Select",
"a",
"template",
"from",
"a",
"string",
"which",
"can",
"include",
"multiple",
"template",
"paths",
"separated",
"by",
"commas",
"."
] | a4f29421a31797e0b069637a0afec85328b4f0ca | https://github.com/chrisdrackett/django-support/blob/a4f29421a31797e0b069637a0afec85328b4f0ca/support/templatetags/form_tags.py#L6-L17 |
248,772 | cirruscluster/cirruscluster | cirruscluster/ext/ansible/utils/plugins.py | PluginLoader._get_package_path | def _get_package_path(self):
"""Gets the path of a Python package"""
if not self.package:
return []
if not hasattr(self, 'package_path'):
m = __import__(self.package)
parts = self.package.split('.')[1:]
self.package_path = os.path.join(os.path.dirn... | python | def _get_package_path(self):
"""Gets the path of a Python package"""
if not self.package:
return []
if not hasattr(self, 'package_path'):
m = __import__(self.package)
parts = self.package.split('.')[1:]
self.package_path = os.path.join(os.path.dirn... | [
"def",
"_get_package_path",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"package",
":",
"return",
"[",
"]",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'package_path'",
")",
":",
"m",
"=",
"__import__",
"(",
"self",
".",
"package",
")",
"parts",
... | Gets the path of a Python package | [
"Gets",
"the",
"path",
"of",
"a",
"Python",
"package"
] | 977409929dd81322d886425cdced10608117d5d7 | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/utils/plugins.py#L47-L55 |
248,773 | cirruscluster/cirruscluster | cirruscluster/ext/ansible/utils/plugins.py | PluginLoader._get_paths | def _get_paths(self):
"""Return a list of paths to search for plugins in
The list is searched in order."""
ret = []
ret += ['%s/library/' % os.path.dirname(os.path.dirname(__file__))]
ret += self._extra_dirs
for basedir in _basedirs:
fullpath... | python | def _get_paths(self):
"""Return a list of paths to search for plugins in
The list is searched in order."""
ret = []
ret += ['%s/library/' % os.path.dirname(os.path.dirname(__file__))]
ret += self._extra_dirs
for basedir in _basedirs:
fullpath... | [
"def",
"_get_paths",
"(",
"self",
")",
":",
"ret",
"=",
"[",
"]",
"ret",
"+=",
"[",
"'%s/library/'",
"%",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"]",
"ret",
"+=",
"self",
".",
"_extra... | Return a list of paths to search for plugins in
The list is searched in order. | [
"Return",
"a",
"list",
"of",
"paths",
"to",
"search",
"for",
"plugins",
"in"
] | 977409929dd81322d886425cdced10608117d5d7 | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/utils/plugins.py#L57-L71 |
248,774 | cirruscluster/cirruscluster | cirruscluster/ext/ansible/utils/plugins.py | PluginLoader.print_paths | def print_paths(self):
"""Returns a string suitable for printing of the search path"""
# Uses a list to get the order right
ret = []
for i in self._get_paths():
if i not in ret:
ret.append(i)
return os.pathsep.join(ret) | python | def print_paths(self):
"""Returns a string suitable for printing of the search path"""
# Uses a list to get the order right
ret = []
for i in self._get_paths():
if i not in ret:
ret.append(i)
return os.pathsep.join(ret) | [
"def",
"print_paths",
"(",
"self",
")",
":",
"# Uses a list to get the order right",
"ret",
"=",
"[",
"]",
"for",
"i",
"in",
"self",
".",
"_get_paths",
"(",
")",
":",
"if",
"i",
"not",
"in",
"ret",
":",
"ret",
".",
"append",
"(",
"i",
")",
"return",
... | Returns a string suitable for printing of the search path | [
"Returns",
"a",
"string",
"suitable",
"for",
"printing",
"of",
"the",
"search",
"path"
] | 977409929dd81322d886425cdced10608117d5d7 | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/utils/plugins.py#L78-L85 |
248,775 | cirruscluster/cirruscluster | cirruscluster/ext/ansible/utils/plugins.py | PluginLoader.find_plugin | def find_plugin(self, name):
"""Find a plugin named name"""
suffix = ".py"
if not self.class_name:
suffix = ""
for i in self._get_paths():
path = os.path.join(i, "%s%s" % (name, suffix))
if os.path.exists(path):
return path
retu... | python | def find_plugin(self, name):
"""Find a plugin named name"""
suffix = ".py"
if not self.class_name:
suffix = ""
for i in self._get_paths():
path = os.path.join(i, "%s%s" % (name, suffix))
if os.path.exists(path):
return path
retu... | [
"def",
"find_plugin",
"(",
"self",
",",
"name",
")",
":",
"suffix",
"=",
"\".py\"",
"if",
"not",
"self",
".",
"class_name",
":",
"suffix",
"=",
"\"\"",
"for",
"i",
"in",
"self",
".",
"_get_paths",
"(",
")",
":",
"path",
"=",
"os",
".",
"path",
".",... | Find a plugin named name | [
"Find",
"a",
"plugin",
"named",
"name"
] | 977409929dd81322d886425cdced10608117d5d7 | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/utils/plugins.py#L87-L96 |
248,776 | praekelt/jmbo-calendar | jmbo_calendar/admin.py | EventAdmin.get_fieldsets | def get_fieldsets(self, *args, **kwargs):
"""Re-order fields"""
result = super(EventAdmin, self).get_fieldsets(*args, **kwargs)
result = list(result)
fields = list(result[0][1]['fields'])
for name in ('content', 'start', 'end', 'repeat', 'repeat_until', \
'external_li... | python | def get_fieldsets(self, *args, **kwargs):
"""Re-order fields"""
result = super(EventAdmin, self).get_fieldsets(*args, **kwargs)
result = list(result)
fields = list(result[0][1]['fields'])
for name in ('content', 'start', 'end', 'repeat', 'repeat_until', \
'external_li... | [
"def",
"get_fieldsets",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"super",
"(",
"EventAdmin",
",",
"self",
")",
".",
"get_fieldsets",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"result",
"=",
"list",
"(",... | Re-order fields | [
"Re",
"-",
"order",
"fields"
] | ac39f3ad4c155d6755ec5c5a51fb815268b8c18c | https://github.com/praekelt/jmbo-calendar/blob/ac39f3ad4c155d6755ec5c5a51fb815268b8c18c/jmbo_calendar/admin.py#L36-L46 |
248,777 | shaypal5/utilitime | utilitime/datetime/datetime.py | utc_offset_by_timezone | def utc_offset_by_timezone(timezone_name):
"""Returns the UTC offset of the given timezone in hours.
Arguments
---------
timezone_name: str
A string with a name of a timezone.
Returns
-------
int
The UTC offset of the given timezone, in hours.
"""
return int(pytz.ti... | python | def utc_offset_by_timezone(timezone_name):
"""Returns the UTC offset of the given timezone in hours.
Arguments
---------
timezone_name: str
A string with a name of a timezone.
Returns
-------
int
The UTC offset of the given timezone, in hours.
"""
return int(pytz.ti... | [
"def",
"utc_offset_by_timezone",
"(",
"timezone_name",
")",
":",
"return",
"int",
"(",
"pytz",
".",
"timezone",
"(",
"timezone_name",
")",
".",
"utcoffset",
"(",
"utc_time",
"(",
")",
")",
".",
"total_seconds",
"(",
")",
"/",
"SECONDS_IN_HOUR",
")"
] | Returns the UTC offset of the given timezone in hours.
Arguments
---------
timezone_name: str
A string with a name of a timezone.
Returns
-------
int
The UTC offset of the given timezone, in hours. | [
"Returns",
"the",
"UTC",
"offset",
"of",
"the",
"given",
"timezone",
"in",
"hours",
"."
] | 554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609 | https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/datetime/datetime.py#L29-L43 |
248,778 | shaypal5/utilitime | utilitime/datetime/datetime.py | localize_datetime | def localize_datetime(datetime_obj, timezone_name):
"""Localizes the given UTC-aligned datetime by the given timezone.
Arguments
---------
datetime_obj : datetime.datetime
A datetime object decipting a specific point in time, aligned by UTC.
timezone_name: str
A string with a name o... | python | def localize_datetime(datetime_obj, timezone_name):
"""Localizes the given UTC-aligned datetime by the given timezone.
Arguments
---------
datetime_obj : datetime.datetime
A datetime object decipting a specific point in time, aligned by UTC.
timezone_name: str
A string with a name o... | [
"def",
"localize_datetime",
"(",
"datetime_obj",
",",
"timezone_name",
")",
":",
"return",
"datetime_obj",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
".",
"astimezone",
"(",
"pytz",
".",
"timezone",
"(",
"timezone_name",
")",
")"
] | Localizes the given UTC-aligned datetime by the given timezone.
Arguments
---------
datetime_obj : datetime.datetime
A datetime object decipting a specific point in time, aligned by UTC.
timezone_name: str
A string with a name of a timezone.
Returns
-------
datetime.datetim... | [
"Localizes",
"the",
"given",
"UTC",
"-",
"aligned",
"datetime",
"by",
"the",
"given",
"timezone",
"."
] | 554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609 | https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/datetime/datetime.py#L46-L62 |
248,779 | eallik/spinoff | spinoff/remoting/pickler.py | IncomingMessageUnpickler._load_build | def _load_build(self):
"""See `pickle.py` in Python's source code."""
# if the ctor. function (penultimate on the stack) is the `Ref` class...
if isinstance(self.stack[-2], Ref):
# Ref.__setstate__ will know it's a remote ref if the state is a tuple
self.stack[-1] = (self... | python | def _load_build(self):
"""See `pickle.py` in Python's source code."""
# if the ctor. function (penultimate on the stack) is the `Ref` class...
if isinstance(self.stack[-2], Ref):
# Ref.__setstate__ will know it's a remote ref if the state is a tuple
self.stack[-1] = (self... | [
"def",
"_load_build",
"(",
"self",
")",
":",
"# if the ctor. function (penultimate on the stack) is the `Ref` class...",
"if",
"isinstance",
"(",
"self",
".",
"stack",
"[",
"-",
"2",
"]",
",",
"Ref",
")",
":",
"# Ref.__setstate__ will know it's a remote ref if the state is ... | See `pickle.py` in Python's source code. | [
"See",
"pickle",
".",
"py",
"in",
"Python",
"s",
"source",
"code",
"."
] | 06b00d6b86c7422c9cb8f9a4b2915906e92b7d52 | https://github.com/eallik/spinoff/blob/06b00d6b86c7422c9cb8f9a4b2915906e92b7d52/spinoff/remoting/pickler.py#L17-L34 |
248,780 | edeposit/edeposit.amqp.storage | src/edeposit/amqp/storage/structures/db/shared.py | path_to_zip | def path_to_zip(path):
"""
Compress `path` to the ZIP.
Args:
path (str): Path to the directory.
Returns:
str: Path to the zipped file (in /tmp).
"""
if not os.path.exists(path):
raise IOError("%s doesn't exists!" % path)
with tempfile.NamedTemporaryFile(delete=Fals... | python | def path_to_zip(path):
"""
Compress `path` to the ZIP.
Args:
path (str): Path to the directory.
Returns:
str: Path to the zipped file (in /tmp).
"""
if not os.path.exists(path):
raise IOError("%s doesn't exists!" % path)
with tempfile.NamedTemporaryFile(delete=Fals... | [
"def",
"path_to_zip",
"(",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"raise",
"IOError",
"(",
"\"%s doesn't exists!\"",
"%",
"path",
")",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"delete",
"=",
"Fa... | Compress `path` to the ZIP.
Args:
path (str): Path to the directory.
Returns:
str: Path to the zipped file (in /tmp). | [
"Compress",
"path",
"to",
"the",
"ZIP",
"."
] | fb6bd326249847de04b17b64e856c878665cea92 | https://github.com/edeposit/edeposit.amqp.storage/blob/fb6bd326249847de04b17b64e856c878665cea92/src/edeposit/amqp/storage/structures/db/shared.py#L14-L35 |
248,781 | edeposit/edeposit.amqp.storage | src/edeposit/amqp/storage/structures/db/shared.py | read_as_base64 | def read_as_base64(fn):
"""
Convert given `fn` to base64 and return it. This method does the process
in not-so-much memory consuming way.
Args:
fn (str): Path to the file which should be converted.
Returns:
str: File encoded as base64.
"""
with open(fn) as unpacked_file:
... | python | def read_as_base64(fn):
"""
Convert given `fn` to base64 and return it. This method does the process
in not-so-much memory consuming way.
Args:
fn (str): Path to the file which should be converted.
Returns:
str: File encoded as base64.
"""
with open(fn) as unpacked_file:
... | [
"def",
"read_as_base64",
"(",
"fn",
")",
":",
"with",
"open",
"(",
"fn",
")",
"as",
"unpacked_file",
":",
"with",
"tempfile",
".",
"TemporaryFile",
"(",
")",
"as",
"b64_file",
":",
"base64",
".",
"encode",
"(",
"unpacked_file",
",",
"b64_file",
")",
"b64... | Convert given `fn` to base64 and return it. This method does the process
in not-so-much memory consuming way.
Args:
fn (str): Path to the file which should be converted.
Returns:
str: File encoded as base64. | [
"Convert",
"given",
"fn",
"to",
"base64",
"and",
"return",
"it",
".",
"This",
"method",
"does",
"the",
"process",
"in",
"not",
"-",
"so",
"-",
"much",
"memory",
"consuming",
"way",
"."
] | fb6bd326249847de04b17b64e856c878665cea92 | https://github.com/edeposit/edeposit.amqp.storage/blob/fb6bd326249847de04b17b64e856c878665cea92/src/edeposit/amqp/storage/structures/db/shared.py#L38-L55 |
248,782 | hkff/FodtlMon | fodtlmon/tools/color.py | _pad_input | def _pad_input(incoming):
"""Avoid IndexError and KeyError by ignoring un-related fields.
Example: '{0}{autored}' becomes '{{0}}{autored}'.
Positional arguments:
incoming -- the input unicode value.
Returns:
Padded unicode value.
"""
incoming_expanded = incoming.replace('{', '{{').rep... | python | def _pad_input(incoming):
"""Avoid IndexError and KeyError by ignoring un-related fields.
Example: '{0}{autored}' becomes '{{0}}{autored}'.
Positional arguments:
incoming -- the input unicode value.
Returns:
Padded unicode value.
"""
incoming_expanded = incoming.replace('{', '{{').rep... | [
"def",
"_pad_input",
"(",
"incoming",
")",
":",
"incoming_expanded",
"=",
"incoming",
".",
"replace",
"(",
"'{'",
",",
"'{{'",
")",
".",
"replace",
"(",
"'}'",
",",
"'}}'",
")",
"for",
"key",
"in",
"_BASE_CODES",
":",
"before",
",",
"after",
"=",
"'{{%... | Avoid IndexError and KeyError by ignoring un-related fields.
Example: '{0}{autored}' becomes '{{0}}{autored}'.
Positional arguments:
incoming -- the input unicode value.
Returns:
Padded unicode value. | [
"Avoid",
"IndexError",
"and",
"KeyError",
"by",
"ignoring",
"un",
"-",
"related",
"fields",
"."
] | 0c9015a1a1f0a4a64d52945c86b45441d5871c56 | https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/tools/color.py#L218-L234 |
248,783 | hkff/FodtlMon | fodtlmon/tools/color.py | _parse_input | def _parse_input(incoming):
"""Performs the actual conversion of tags to ANSI escaped codes.
Provides a version of the input without any colors for len() and other methods.
Positional arguments:
incoming -- the input unicode value.
Returns:
2-item tuple. First item is the parsed output. Secon... | python | def _parse_input(incoming):
"""Performs the actual conversion of tags to ANSI escaped codes.
Provides a version of the input without any colors for len() and other methods.
Positional arguments:
incoming -- the input unicode value.
Returns:
2-item tuple. First item is the parsed output. Secon... | [
"def",
"_parse_input",
"(",
"incoming",
")",
":",
"codes",
"=",
"dict",
"(",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"_AutoCodes",
"(",
")",
".",
"items",
"(",
")",
"if",
"'{%s}'",
"%",
"k",
"in",
"incoming",
")",
"color_codes",
"=",... | Performs the actual conversion of tags to ANSI escaped codes.
Provides a version of the input without any colors for len() and other methods.
Positional arguments:
incoming -- the input unicode value.
Returns:
2-item tuple. First item is the parsed output. Second item is a version of the input wi... | [
"Performs",
"the",
"actual",
"conversion",
"of",
"tags",
"to",
"ANSI",
"escaped",
"codes",
"."
] | 0c9015a1a1f0a4a64d52945c86b45441d5871c56 | https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/tools/color.py#L237-L267 |
248,784 | hkff/FodtlMon | fodtlmon/tools/color.py | list_tags | def list_tags():
"""Lists the available tags.
Returns:
Tuple of tuples. Child tuples are four items: ('opening tag', 'closing tag', main ansi value, closing ansi value).
"""
codes = _AutoCodes()
grouped = set([(k, '/{0}'.format(k), codes[k], codes['/{0}'.format(k)]) for k in codes if not k.star... | python | def list_tags():
"""Lists the available tags.
Returns:
Tuple of tuples. Child tuples are four items: ('opening tag', 'closing tag', main ansi value, closing ansi value).
"""
codes = _AutoCodes()
grouped = set([(k, '/{0}'.format(k), codes[k], codes['/{0}'.format(k)]) for k in codes if not k.star... | [
"def",
"list_tags",
"(",
")",
":",
"codes",
"=",
"_AutoCodes",
"(",
")",
"grouped",
"=",
"set",
"(",
"[",
"(",
"k",
",",
"'/{0}'",
".",
"format",
"(",
"k",
")",
",",
"codes",
"[",
"k",
"]",
",",
"codes",
"[",
"'/{0}'",
".",
"format",
"(",
"k",
... | Lists the available tags.
Returns:
Tuple of tuples. Child tuples are four items: ('opening tag', 'closing tag', main ansi value, closing ansi value). | [
"Lists",
"the",
"available",
"tags",
"."
] | 0c9015a1a1f0a4a64d52945c86b45441d5871c56 | https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/tools/color.py#L287-L312 |
248,785 | hkff/FodtlMon | fodtlmon/tools/color.py | _WindowsStream._set_color | def _set_color(self, color_code):
"""Changes the foreground and background colors for subsequently printed characters.
Since setting a color requires including both foreground and background codes (merged), setting just the
foreground color resets the background color to black, and vice versa.
... | python | def _set_color(self, color_code):
"""Changes the foreground and background colors for subsequently printed characters.
Since setting a color requires including both foreground and background codes (merged), setting just the
foreground color resets the background color to black, and vice versa.
... | [
"def",
"_set_color",
"(",
"self",
",",
"color_code",
")",
":",
"# Get current color code.",
"current_fg",
",",
"current_bg",
"=",
"self",
".",
"_get_colors",
"(",
")",
"# Handle special negative codes. Also determine the final color code.",
"if",
"color_code",
"==",
"-",
... | Changes the foreground and background colors for subsequently printed characters.
Since setting a color requires including both foreground and background codes (merged), setting just the
foreground color resets the background color to black, and vice versa.
This function first gets the current... | [
"Changes",
"the",
"foreground",
"and",
"background",
"colors",
"for",
"subsequently",
"printed",
"characters",
"."
] | 0c9015a1a1f0a4a64d52945c86b45441d5871c56 | https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/tools/color.py#L705-L738 |
248,786 | af/turrentine | turrentine/views.py | PageView.get_mimetype | def get_mimetype(self):
"""
Use the ending of the template name to infer response's Content-Type header.
"""
template_name = self.get_template_names()[0]
for extension, mimetype in turrentine_settings.TURRENTINE_MIMETYPE_EXTENSIONS:
if template_name.endswith(extension... | python | def get_mimetype(self):
"""
Use the ending of the template name to infer response's Content-Type header.
"""
template_name = self.get_template_names()[0]
for extension, mimetype in turrentine_settings.TURRENTINE_MIMETYPE_EXTENSIONS:
if template_name.endswith(extension... | [
"def",
"get_mimetype",
"(",
"self",
")",
":",
"template_name",
"=",
"self",
".",
"get_template_names",
"(",
")",
"[",
"0",
"]",
"for",
"extension",
",",
"mimetype",
"in",
"turrentine_settings",
".",
"TURRENTINE_MIMETYPE_EXTENSIONS",
":",
"if",
"template_name",
"... | Use the ending of the template name to infer response's Content-Type header. | [
"Use",
"the",
"ending",
"of",
"the",
"template",
"name",
"to",
"infer",
"response",
"s",
"Content",
"-",
"Type",
"header",
"."
] | bbbd5139744ccc6264595cc8960784e5c308c009 | https://github.com/af/turrentine/blob/bbbd5139744ccc6264595cc8960784e5c308c009/turrentine/views.py#L37-L45 |
248,787 | af/turrentine | turrentine/views.py | PageView.get | def get(self, request, *args, **kwargs):
"""
Check user authentication if the page requires a login.
We could do this by overriding dispatch() instead, but we assume
that only GET requests will be required by the CMS pages.
"""
try:
page = self.object = self.... | python | def get(self, request, *args, **kwargs):
"""
Check user authentication if the page requires a login.
We could do this by overriding dispatch() instead, but we assume
that only GET requests will be required by the CMS pages.
"""
try:
page = self.object = self.... | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"page",
"=",
"self",
".",
"object",
"=",
"self",
".",
"get_object",
"(",
")",
"except",
"Http404",
":",
"# If APPEND_SLASH is set and our url has ... | Check user authentication if the page requires a login.
We could do this by overriding dispatch() instead, but we assume
that only GET requests will be required by the CMS pages. | [
"Check",
"user",
"authentication",
"if",
"the",
"page",
"requires",
"a",
"login",
"."
] | bbbd5139744ccc6264595cc8960784e5c308c009 | https://github.com/af/turrentine/blob/bbbd5139744ccc6264595cc8960784e5c308c009/turrentine/views.py#L47-L76 |
248,788 | af/turrentine | turrentine/views.py | PageView._try_url_with_appended_slash | def _try_url_with_appended_slash(self):
"""
Try our URL with an appended slash. If a CMS page is found at that URL, redirect to it.
If no page is found at that URL, raise Http404.
"""
new_url_to_try = self.kwargs.get('path', '') + '/'
if not new_url_to_try.startswith('/')... | python | def _try_url_with_appended_slash(self):
"""
Try our URL with an appended slash. If a CMS page is found at that URL, redirect to it.
If no page is found at that URL, raise Http404.
"""
new_url_to_try = self.kwargs.get('path', '') + '/'
if not new_url_to_try.startswith('/')... | [
"def",
"_try_url_with_appended_slash",
"(",
"self",
")",
":",
"new_url_to_try",
"=",
"self",
".",
"kwargs",
".",
"get",
"(",
"'path'",
",",
"''",
")",
"+",
"'/'",
"if",
"not",
"new_url_to_try",
".",
"startswith",
"(",
"'/'",
")",
":",
"new_url_to_try",
"="... | Try our URL with an appended slash. If a CMS page is found at that URL, redirect to it.
If no page is found at that URL, raise Http404. | [
"Try",
"our",
"URL",
"with",
"an",
"appended",
"slash",
".",
"If",
"a",
"CMS",
"page",
"is",
"found",
"at",
"that",
"URL",
"redirect",
"to",
"it",
".",
"If",
"no",
"page",
"is",
"found",
"at",
"that",
"URL",
"raise",
"Http404",
"."
] | bbbd5139744ccc6264595cc8960784e5c308c009 | https://github.com/af/turrentine/blob/bbbd5139744ccc6264595cc8960784e5c308c009/turrentine/views.py#L78-L89 |
248,789 | sveetch/py-css-styleguide | py_css_styleguide/serializer.py | ManifestSerializer.validate_rule_name | def validate_rule_name(self, name):
"""
Validate rule name.
Arguments:
name (string): Rule name.
Returns:
bool: ``True`` if rule name is valid.
"""
if not name:
raise SerializerError("Rule name is empty".format(name))
if name... | python | def validate_rule_name(self, name):
"""
Validate rule name.
Arguments:
name (string): Rule name.
Returns:
bool: ``True`` if rule name is valid.
"""
if not name:
raise SerializerError("Rule name is empty".format(name))
if name... | [
"def",
"validate_rule_name",
"(",
"self",
",",
"name",
")",
":",
"if",
"not",
"name",
":",
"raise",
"SerializerError",
"(",
"\"Rule name is empty\"",
".",
"format",
"(",
"name",
")",
")",
"if",
"name",
"[",
"0",
"]",
"not",
"in",
"RULE_ALLOWED_START",
":",... | Validate rule name.
Arguments:
name (string): Rule name.
Returns:
bool: ``True`` if rule name is valid. | [
"Validate",
"rule",
"name",
"."
] | 5acc693f71b2fa7d944d7fed561ae0a7699ccd0f | https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L46-L69 |
248,790 | sveetch/py-css-styleguide | py_css_styleguide/serializer.py | ManifestSerializer.validate_variable_name | def validate_variable_name(self, name):
"""
Validate variable name.
Arguments:
name (string): Property name.
Returns:
bool: ``True`` if variable name is valid.
"""
if not name:
raise SerializerError("Variable name is empty".format(nam... | python | def validate_variable_name(self, name):
"""
Validate variable name.
Arguments:
name (string): Property name.
Returns:
bool: ``True`` if variable name is valid.
"""
if not name:
raise SerializerError("Variable name is empty".format(nam... | [
"def",
"validate_variable_name",
"(",
"self",
",",
"name",
")",
":",
"if",
"not",
"name",
":",
"raise",
"SerializerError",
"(",
"\"Variable name is empty\"",
".",
"format",
"(",
"name",
")",
")",
"if",
"name",
"[",
"0",
"]",
"not",
"in",
"PROPERTY_ALLOWED_ST... | Validate variable name.
Arguments:
name (string): Property name.
Returns:
bool: ``True`` if variable name is valid. | [
"Validate",
"variable",
"name",
"."
] | 5acc693f71b2fa7d944d7fed561ae0a7699ccd0f | https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L71-L94 |
248,791 | sveetch/py-css-styleguide | py_css_styleguide/serializer.py | ManifestSerializer.value_splitter | def value_splitter(self, reference, prop, value, mode):
"""
Split a string into a list items.
Default behavior is to split on white spaces.
Arguments:
reference (string): Reference name used when raising possible
error.
prop (string): Property n... | python | def value_splitter(self, reference, prop, value, mode):
"""
Split a string into a list items.
Default behavior is to split on white spaces.
Arguments:
reference (string): Reference name used when raising possible
error.
prop (string): Property n... | [
"def",
"value_splitter",
"(",
"self",
",",
"reference",
",",
"prop",
",",
"value",
",",
"mode",
")",
":",
"items",
"=",
"[",
"]",
"if",
"mode",
"==",
"'json-list'",
":",
"try",
":",
"items",
"=",
"json",
".",
"loads",
"(",
"value",
")",
"except",
"... | Split a string into a list items.
Default behavior is to split on white spaces.
Arguments:
reference (string): Reference name used when raising possible
error.
prop (string): Property name used when raising possible error.
value (string): Property v... | [
"Split",
"a",
"string",
"into",
"a",
"list",
"items",
"."
] | 5acc693f71b2fa7d944d7fed561ae0a7699ccd0f | https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L96-L134 |
248,792 | sveetch/py-css-styleguide | py_css_styleguide/serializer.py | ManifestSerializer.serialize_to_json | def serialize_to_json(self, name, datas):
"""
Serialize given datas to any object from assumed JSON string.
Arguments:
name (string): Name only used inside possible exception message.
datas (dict): Datas to serialize.
Returns:
object: Object dependin... | python | def serialize_to_json(self, name, datas):
"""
Serialize given datas to any object from assumed JSON string.
Arguments:
name (string): Name only used inside possible exception message.
datas (dict): Datas to serialize.
Returns:
object: Object dependin... | [
"def",
"serialize_to_json",
"(",
"self",
",",
"name",
",",
"datas",
")",
":",
"data_object",
"=",
"datas",
".",
"get",
"(",
"'object'",
",",
"None",
")",
"if",
"data_object",
"is",
"None",
":",
"msg",
"=",
"(",
"\"JSON reference '{}' lacks of required 'object'... | Serialize given datas to any object from assumed JSON string.
Arguments:
name (string): Name only used inside possible exception message.
datas (dict): Datas to serialize.
Returns:
object: Object depending from JSON content. | [
"Serialize",
"given",
"datas",
"to",
"any",
"object",
"from",
"assumed",
"JSON",
"string",
"."
] | 5acc693f71b2fa7d944d7fed561ae0a7699ccd0f | https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L136-L159 |
248,793 | sveetch/py-css-styleguide | py_css_styleguide/serializer.py | ManifestSerializer.serialize_to_list | def serialize_to_list(self, name, datas):
"""
Serialize given datas to a list structure.
List structure is very simple and only require a variable ``--items``
which is a string of values separated with an empty space. Every other
properties are ignored.
Arguments:
... | python | def serialize_to_list(self, name, datas):
"""
Serialize given datas to a list structure.
List structure is very simple and only require a variable ``--items``
which is a string of values separated with an empty space. Every other
properties are ignored.
Arguments:
... | [
"def",
"serialize_to_list",
"(",
"self",
",",
"name",
",",
"datas",
")",
":",
"items",
"=",
"datas",
".",
"get",
"(",
"'items'",
",",
"None",
")",
"splitter",
"=",
"datas",
".",
"get",
"(",
"'splitter'",
",",
"self",
".",
"_DEFAULT_SPLITTER",
")",
"if"... | Serialize given datas to a list structure.
List structure is very simple and only require a variable ``--items``
which is a string of values separated with an empty space. Every other
properties are ignored.
Arguments:
name (string): Name only used inside possible exception... | [
"Serialize",
"given",
"datas",
"to",
"a",
"list",
"structure",
"."
] | 5acc693f71b2fa7d944d7fed561ae0a7699ccd0f | https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L249-L274 |
248,794 | sveetch/py-css-styleguide | py_css_styleguide/serializer.py | ManifestSerializer.serialize_to_string | def serialize_to_string(self, name, datas):
"""
Serialize given datas to a string.
Simply return the value from required variable``value``.
Arguments:
name (string): Name only used inside possible exception message.
datas (dict): Datas to serialize.
Ret... | python | def serialize_to_string(self, name, datas):
"""
Serialize given datas to a string.
Simply return the value from required variable``value``.
Arguments:
name (string): Name only used inside possible exception message.
datas (dict): Datas to serialize.
Ret... | [
"def",
"serialize_to_string",
"(",
"self",
",",
"name",
",",
"datas",
")",
":",
"value",
"=",
"datas",
".",
"get",
"(",
"'value'",
",",
"None",
")",
"if",
"value",
"is",
"None",
":",
"msg",
"=",
"(",
"\"String reference '{}' lacks of required 'value' variable ... | Serialize given datas to a string.
Simply return the value from required variable``value``.
Arguments:
name (string): Name only used inside possible exception message.
datas (dict): Datas to serialize.
Returns:
string: Value. | [
"Serialize",
"given",
"datas",
"to",
"a",
"string",
"."
] | 5acc693f71b2fa7d944d7fed561ae0a7699ccd0f | https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L276-L296 |
248,795 | sveetch/py-css-styleguide | py_css_styleguide/serializer.py | ManifestSerializer.get_meta_references | def get_meta_references(self, datas):
"""
Get manifest enabled references declaration
This required declaration is readed from
``styleguide-metas-references`` rule that require either a ``--names``
or ``--auto`` variable, each one define the mode to enable reference:
Ma... | python | def get_meta_references(self, datas):
"""
Get manifest enabled references declaration
This required declaration is readed from
``styleguide-metas-references`` rule that require either a ``--names``
or ``--auto`` variable, each one define the mode to enable reference:
Ma... | [
"def",
"get_meta_references",
"(",
"self",
",",
"datas",
")",
":",
"rule",
"=",
"datas",
".",
"get",
"(",
"RULE_META_REFERENCES",
",",
"{",
"}",
")",
"if",
"not",
"rule",
":",
"msg",
"=",
"\"Manifest lacks of '.{}' or is empty\"",
"raise",
"SerializerError",
"... | Get manifest enabled references declaration
This required declaration is readed from
``styleguide-metas-references`` rule that require either a ``--names``
or ``--auto`` variable, each one define the mode to enable reference:
Manually
Using ``--names`` which define a list o... | [
"Get",
"manifest",
"enabled",
"references",
"declaration"
] | 5acc693f71b2fa7d944d7fed561ae0a7699ccd0f | https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L298-L344 |
248,796 | sveetch/py-css-styleguide | py_css_styleguide/serializer.py | ManifestSerializer.get_reference | def get_reference(self, datas, name):
"""
Get serialized reference datas
Because every reference is turned to a dict (that stands on ``keys``
variable that is a list of key names), every variables must have the
same exact length of word than the key name list.
A referen... | python | def get_reference(self, datas, name):
"""
Get serialized reference datas
Because every reference is turned to a dict (that stands on ``keys``
variable that is a list of key names), every variables must have the
same exact length of word than the key name list.
A referen... | [
"def",
"get_reference",
"(",
"self",
",",
"datas",
",",
"name",
")",
":",
"rule_name",
"=",
"'-'",
".",
"join",
"(",
"(",
"RULE_REFERENCE",
",",
"name",
")",
")",
"structure_mode",
"=",
"'nested'",
"if",
"rule_name",
"not",
"in",
"datas",
":",
"msg",
"... | Get serialized reference datas
Because every reference is turned to a dict (that stands on ``keys``
variable that is a list of key names), every variables must have the
same exact length of word than the key name list.
A reference name starts with 'styleguide-reference-' followed by
... | [
"Get",
"serialized",
"reference",
"datas"
] | 5acc693f71b2fa7d944d7fed561ae0a7699ccd0f | https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L346-L410 |
248,797 | sveetch/py-css-styleguide | py_css_styleguide/serializer.py | ManifestSerializer.get_available_references | def get_available_references(self, datas):
"""
Get available manifest reference names.
Every rules starting with prefix from ``nomenclature.RULE_REFERENCE``
are available references.
Only name validation is performed on these references.
Arguments:
datas (d... | python | def get_available_references(self, datas):
"""
Get available manifest reference names.
Every rules starting with prefix from ``nomenclature.RULE_REFERENCE``
are available references.
Only name validation is performed on these references.
Arguments:
datas (d... | [
"def",
"get_available_references",
"(",
"self",
",",
"datas",
")",
":",
"names",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"datas",
".",
"items",
"(",
")",
":",
"if",
"k",
".",
"startswith",
"(",
"RULE_REFERENCE",
")",
":",
"names",
".",
"append",
... | Get available manifest reference names.
Every rules starting with prefix from ``nomenclature.RULE_REFERENCE``
are available references.
Only name validation is performed on these references.
Arguments:
datas (dict): Data where to search for reference declarations.
... | [
"Get",
"available",
"manifest",
"reference",
"names",
"."
] | 5acc693f71b2fa7d944d7fed561ae0a7699ccd0f | https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L412-L434 |
248,798 | sveetch/py-css-styleguide | py_css_styleguide/serializer.py | ManifestSerializer.get_enabled_references | def get_enabled_references(self, datas, meta_references):
"""
Get enabled manifest references declarations.
Enabled references are defined through meta references declaration,
every other references are ignored.
Arguments:
datas (dict): Data where to search for refe... | python | def get_enabled_references(self, datas, meta_references):
"""
Get enabled manifest references declarations.
Enabled references are defined through meta references declaration,
every other references are ignored.
Arguments:
datas (dict): Data where to search for refe... | [
"def",
"get_enabled_references",
"(",
"self",
",",
"datas",
",",
"meta_references",
")",
":",
"references",
"=",
"OrderedDict",
"(",
")",
"for",
"section",
"in",
"meta_references",
":",
"references",
"[",
"section",
"]",
"=",
"self",
".",
"get_reference",
"(",... | Get enabled manifest references declarations.
Enabled references are defined through meta references declaration,
every other references are ignored.
Arguments:
datas (dict): Data where to search for reference declarations.
This is commonly the fully parsed manifest... | [
"Get",
"enabled",
"manifest",
"references",
"declarations",
"."
] | 5acc693f71b2fa7d944d7fed561ae0a7699ccd0f | https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L436-L456 |
248,799 | sveetch/py-css-styleguide | py_css_styleguide/serializer.py | ManifestSerializer.serialize | def serialize(self, datas):
"""
Serialize datas to manifest structure with metas and references.
Only references are returned, metas are assigned to attribute
``ManifestSerializer._metas``.
Arguments:
datas (dict): Data where to search for reference declarations. Th... | python | def serialize(self, datas):
"""
Serialize datas to manifest structure with metas and references.
Only references are returned, metas are assigned to attribute
``ManifestSerializer._metas``.
Arguments:
datas (dict): Data where to search for reference declarations. Th... | [
"def",
"serialize",
"(",
"self",
",",
"datas",
")",
":",
"self",
".",
"_metas",
"=",
"OrderedDict",
"(",
"{",
"'references'",
":",
"self",
".",
"get_meta_references",
"(",
"datas",
")",
",",
"}",
")",
"return",
"self",
".",
"get_enabled_references",
"(",
... | Serialize datas to manifest structure with metas and references.
Only references are returned, metas are assigned to attribute
``ManifestSerializer._metas``.
Arguments:
datas (dict): Data where to search for reference declarations. This
is commonly the fully parsed ... | [
"Serialize",
"datas",
"to",
"manifest",
"structure",
"with",
"metas",
"and",
"references",
"."
] | 5acc693f71b2fa7d944d7fed561ae0a7699ccd0f | https://github.com/sveetch/py-css-styleguide/blob/5acc693f71b2fa7d944d7fed561ae0a7699ccd0f/py_css_styleguide/serializer.py#L458-L476 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.