repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 3
values | summary stringlengths 4 350 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
Capitains/MyCapytain | MyCapytain/common/utils/_json_ld.py | dict_to_literal | def dict_to_literal(dict_container: dict):
""" Transforms a JSON+LD PyLD dictionary into
an RDFLib object"""
if isinstance(dict_container["@value"], int):
return dict_container["@value"],
else:
return dict_container["@value"], dict_container.get("@language", None) | python | def dict_to_literal(dict_container: dict):
""" Transforms a JSON+LD PyLD dictionary into
an RDFLib object"""
if isinstance(dict_container["@value"], int):
return dict_container["@value"],
else:
return dict_container["@value"], dict_container.get("@language", None) | [
"def",
"dict_to_literal",
"(",
"dict_container",
":",
"dict",
")",
":",
"if",
"isinstance",
"(",
"dict_container",
"[",
"\"@value\"",
"]",
",",
"int",
")",
":",
"return",
"dict_container",
"[",
"\"@value\"",
"]",
",",
"else",
":",
"return",
"dict_container",
... | Transforms a JSON+LD PyLD dictionary into
an RDFLib object | [
"Transforms",
"a",
"JSON",
"+",
"LD",
"PyLD",
"dictionary",
"into",
"an",
"RDFLib",
"object"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/utils/_json_ld.py#L22-L28 | train | Transforms a JSON + LD dictionary into a RDFLib object |
jedie/PyHardLinkBackup | PyHardLinkBackup/phlb/path_helper.py | PathHelper.set_src_filepath | def set_src_filepath(self, src_dir_path):
"""
Set one filepath to backup this file.
Called for every file in the source directory.
:argument src_dir_path: filesystem_walk.DirEntryPath() instance
"""
log.debug("set_src_filepath() with: '%s'", src_dir_path)
self.ab... | python | def set_src_filepath(self, src_dir_path):
"""
Set one filepath to backup this file.
Called for every file in the source directory.
:argument src_dir_path: filesystem_walk.DirEntryPath() instance
"""
log.debug("set_src_filepath() with: '%s'", src_dir_path)
self.ab... | [
"def",
"set_src_filepath",
"(",
"self",
",",
"src_dir_path",
")",
":",
"log",
".",
"debug",
"(",
"\"set_src_filepath() with: '%s'\"",
",",
"src_dir_path",
")",
"self",
".",
"abs_src_filepath",
"=",
"src_dir_path",
".",
"resolved_path",
"log",
".",
"debug",
"(",
... | Set one filepath to backup this file.
Called for every file in the source directory.
:argument src_dir_path: filesystem_walk.DirEntryPath() instance | [
"Set",
"one",
"filepath",
"to",
"backup",
"this",
"file",
".",
"Called",
"for",
"every",
"file",
"in",
"the",
"source",
"directory",
"."
] | be28666834d2d9e3d8aac1b661cb2d5bd4056c29 | https://github.com/jedie/PyHardLinkBackup/blob/be28666834d2d9e3d8aac1b661cb2d5bd4056c29/PyHardLinkBackup/phlb/path_helper.py#L109-L140 | train | Set the filepath to backup this file. |
etingof/pysnmpcrypto | pysnmpcrypto/__init__.py | _cryptodome_encrypt | def _cryptodome_encrypt(cipher_factory, plaintext, key, iv):
"""Use a Pycryptodome cipher factory to encrypt data.
:param cipher_factory: Factory callable that builds a Pycryptodome Cipher
instance based on the key and IV
:type cipher_factory: callable
:param bytes plaintext: Plaintext data to ... | python | def _cryptodome_encrypt(cipher_factory, plaintext, key, iv):
"""Use a Pycryptodome cipher factory to encrypt data.
:param cipher_factory: Factory callable that builds a Pycryptodome Cipher
instance based on the key and IV
:type cipher_factory: callable
:param bytes plaintext: Plaintext data to ... | [
"def",
"_cryptodome_encrypt",
"(",
"cipher_factory",
",",
"plaintext",
",",
"key",
",",
"iv",
")",
":",
"encryptor",
"=",
"cipher_factory",
"(",
"key",
",",
"iv",
")",
"return",
"encryptor",
".",
"encrypt",
"(",
"plaintext",
")"
] | Use a Pycryptodome cipher factory to encrypt data.
:param cipher_factory: Factory callable that builds a Pycryptodome Cipher
instance based on the key and IV
:type cipher_factory: callable
:param bytes plaintext: Plaintext data to encrypt
:param bytes key: Encryption key
:param bytes IV: In... | [
"Use",
"a",
"Pycryptodome",
"cipher",
"factory",
"to",
"encrypt",
"data",
"."
] | 9b92959f5e2fce833fa220343ca12add3134a77c | https://github.com/etingof/pysnmpcrypto/blob/9b92959f5e2fce833fa220343ca12add3134a77c/pysnmpcrypto/__init__.py#L36-L49 | train | Use a Pycryptodome cipher factory to encrypt data. |
etingof/pysnmpcrypto | pysnmpcrypto/__init__.py | _cryptodome_decrypt | def _cryptodome_decrypt(cipher_factory, ciphertext, key, iv):
"""Use a Pycryptodome cipher factory to decrypt data.
:param cipher_factory: Factory callable that builds a Pycryptodome Cipher
instance based on the key and IV
:type cipher_factory: callable
:param bytes ciphertext: Ciphertext data ... | python | def _cryptodome_decrypt(cipher_factory, ciphertext, key, iv):
"""Use a Pycryptodome cipher factory to decrypt data.
:param cipher_factory: Factory callable that builds a Pycryptodome Cipher
instance based on the key and IV
:type cipher_factory: callable
:param bytes ciphertext: Ciphertext data ... | [
"def",
"_cryptodome_decrypt",
"(",
"cipher_factory",
",",
"ciphertext",
",",
"key",
",",
"iv",
")",
":",
"decryptor",
"=",
"cipher_factory",
"(",
"key",
",",
"iv",
")",
"return",
"decryptor",
".",
"decrypt",
"(",
"ciphertext",
")"
] | Use a Pycryptodome cipher factory to decrypt data.
:param cipher_factory: Factory callable that builds a Pycryptodome Cipher
instance based on the key and IV
:type cipher_factory: callable
:param bytes ciphertext: Ciphertext data to decrypt
:param bytes key: Encryption key
:param bytes IV: ... | [
"Use",
"a",
"Pycryptodome",
"cipher",
"factory",
"to",
"decrypt",
"data",
"."
] | 9b92959f5e2fce833fa220343ca12add3134a77c | https://github.com/etingof/pysnmpcrypto/blob/9b92959f5e2fce833fa220343ca12add3134a77c/pysnmpcrypto/__init__.py#L52-L65 | train | Use a Pycryptodome cipher factory to decrypt data. |
etingof/pysnmpcrypto | pysnmpcrypto/__init__.py | _cryptography_encrypt | def _cryptography_encrypt(cipher_factory, plaintext, key, iv):
"""Use a cryptography cipher factory to encrypt data.
:param cipher_factory: Factory callable that builds a cryptography Cipher
instance based on the key and IV
:type cipher_factory: callable
:param bytes plaintext: Plaintext data t... | python | def _cryptography_encrypt(cipher_factory, plaintext, key, iv):
"""Use a cryptography cipher factory to encrypt data.
:param cipher_factory: Factory callable that builds a cryptography Cipher
instance based on the key and IV
:type cipher_factory: callable
:param bytes plaintext: Plaintext data t... | [
"def",
"_cryptography_encrypt",
"(",
"cipher_factory",
",",
"plaintext",
",",
"key",
",",
"iv",
")",
":",
"encryptor",
"=",
"cipher_factory",
"(",
"key",
",",
"iv",
")",
".",
"encryptor",
"(",
")",
"return",
"encryptor",
".",
"update",
"(",
"plaintext",
")... | Use a cryptography cipher factory to encrypt data.
:param cipher_factory: Factory callable that builds a cryptography Cipher
instance based on the key and IV
:type cipher_factory: callable
:param bytes plaintext: Plaintext data to encrypt
:param bytes key: Encryption key
:param bytes IV: In... | [
"Use",
"a",
"cryptography",
"cipher",
"factory",
"to",
"encrypt",
"data",
"."
] | 9b92959f5e2fce833fa220343ca12add3134a77c | https://github.com/etingof/pysnmpcrypto/blob/9b92959f5e2fce833fa220343ca12add3134a77c/pysnmpcrypto/__init__.py#L68-L81 | train | Use a cryptography cipher factory to encrypt data. |
etingof/pysnmpcrypto | pysnmpcrypto/__init__.py | _cryptography_decrypt | def _cryptography_decrypt(cipher_factory, ciphertext, key, iv):
"""Use a cryptography cipher factory to decrypt data.
:param cipher_factory: Factory callable that builds a cryptography Cipher
instance based on the key and IV
:type cipher_factory: callable
:param bytes ciphertext: Ciphertext dat... | python | def _cryptography_decrypt(cipher_factory, ciphertext, key, iv):
"""Use a cryptography cipher factory to decrypt data.
:param cipher_factory: Factory callable that builds a cryptography Cipher
instance based on the key and IV
:type cipher_factory: callable
:param bytes ciphertext: Ciphertext dat... | [
"def",
"_cryptography_decrypt",
"(",
"cipher_factory",
",",
"ciphertext",
",",
"key",
",",
"iv",
")",
":",
"decryptor",
"=",
"cipher_factory",
"(",
"key",
",",
"iv",
")",
".",
"decryptor",
"(",
")",
"return",
"decryptor",
".",
"update",
"(",
"ciphertext",
... | Use a cryptography cipher factory to decrypt data.
:param cipher_factory: Factory callable that builds a cryptography Cipher
instance based on the key and IV
:type cipher_factory: callable
:param bytes ciphertext: Ciphertext data to decrypt
:param bytes key: Encryption key
:param bytes IV: ... | [
"Use",
"a",
"cryptography",
"cipher",
"factory",
"to",
"decrypt",
"data",
"."
] | 9b92959f5e2fce833fa220343ca12add3134a77c | https://github.com/etingof/pysnmpcrypto/blob/9b92959f5e2fce833fa220343ca12add3134a77c/pysnmpcrypto/__init__.py#L84-L97 | train | Use a cryptography cipher factory to decrypt data. |
etingof/pysnmpcrypto | pysnmpcrypto/__init__.py | generic_encrypt | def generic_encrypt(cipher_factory_map, plaintext, key, iv):
"""Encrypt data using the available backend.
:param dict cipher_factory_map: Dictionary that maps the backend name to
a cipher factory callable for that backend
:param bytes plaintext: Plaintext data to encrypt
:param bytes key: Encry... | python | def generic_encrypt(cipher_factory_map, plaintext, key, iv):
"""Encrypt data using the available backend.
:param dict cipher_factory_map: Dictionary that maps the backend name to
a cipher factory callable for that backend
:param bytes plaintext: Plaintext data to encrypt
:param bytes key: Encry... | [
"def",
"generic_encrypt",
"(",
"cipher_factory_map",
",",
"plaintext",
",",
"key",
",",
"iv",
")",
":",
"if",
"backend",
"is",
"None",
":",
"raise",
"PysnmpCryptoError",
"(",
"'Crypto backend not available'",
")",
"return",
"_ENCRYPT_MAP",
"[",
"backend",
"]",
"... | Encrypt data using the available backend.
:param dict cipher_factory_map: Dictionary that maps the backend name to
a cipher factory callable for that backend
:param bytes plaintext: Plaintext data to encrypt
:param bytes key: Encryption key
:param bytes IV: Initialization vector
:returns: E... | [
"Encrypt",
"data",
"using",
"the",
"available",
"backend",
"."
] | 9b92959f5e2fce833fa220343ca12add3134a77c | https://github.com/etingof/pysnmpcrypto/blob/9b92959f5e2fce833fa220343ca12add3134a77c/pysnmpcrypto/__init__.py#L110-L125 | train | Encrypt data using the available backend. |
etingof/pysnmpcrypto | pysnmpcrypto/__init__.py | generic_decrypt | def generic_decrypt(cipher_factory_map, ciphertext, key, iv):
"""Decrypt data using the available backend.
:param dict cipher_factory_map: Dictionary that maps the backend name
to a cipher factory callable for that backend
:param bytes ciphertext: Ciphertext data to decrypt
:param bytes key: En... | python | def generic_decrypt(cipher_factory_map, ciphertext, key, iv):
"""Decrypt data using the available backend.
:param dict cipher_factory_map: Dictionary that maps the backend name
to a cipher factory callable for that backend
:param bytes ciphertext: Ciphertext data to decrypt
:param bytes key: En... | [
"def",
"generic_decrypt",
"(",
"cipher_factory_map",
",",
"ciphertext",
",",
"key",
",",
"iv",
")",
":",
"if",
"backend",
"is",
"None",
":",
"raise",
"PysnmpCryptoError",
"(",
"'Crypto backend not available'",
")",
"return",
"_DECRYPT_MAP",
"[",
"backend",
"]",
... | Decrypt data using the available backend.
:param dict cipher_factory_map: Dictionary that maps the backend name
to a cipher factory callable for that backend
:param bytes ciphertext: Ciphertext data to decrypt
:param bytes key: Encryption key
:param bytes IV: Initialization vector
:returns:... | [
"Decrypt",
"data",
"using",
"the",
"available",
"backend",
"."
] | 9b92959f5e2fce833fa220343ca12add3134a77c | https://github.com/etingof/pysnmpcrypto/blob/9b92959f5e2fce833fa220343ca12add3134a77c/pysnmpcrypto/__init__.py#L128-L143 | train | This function will decrypt data using the available backend. |
jiasir/playback | playback/swift_storage.py | SwiftStorage._prepare_disks | def _prepare_disks(self, disks_name):
"""format disks to xfs and mount it"""
fstab = '/etc/fstab'
for disk in tqdm(disks_name.split(',')):
sudo('umount /dev/{0}'.format(disk), warn_only=True)
if sudo('mkfs.xfs -f /dev/{0}'.format(disk), warn_only=True).failed:
... | python | def _prepare_disks(self, disks_name):
"""format disks to xfs and mount it"""
fstab = '/etc/fstab'
for disk in tqdm(disks_name.split(',')):
sudo('umount /dev/{0}'.format(disk), warn_only=True)
if sudo('mkfs.xfs -f /dev/{0}'.format(disk), warn_only=True).failed:
... | [
"def",
"_prepare_disks",
"(",
"self",
",",
"disks_name",
")",
":",
"fstab",
"=",
"'/etc/fstab'",
"for",
"disk",
"in",
"tqdm",
"(",
"disks_name",
".",
"split",
"(",
"','",
")",
")",
":",
"sudo",
"(",
"'umount /dev/{0}'",
".",
"format",
"(",
"disk",
")",
... | format disks to xfs and mount it | [
"format",
"disks",
"to",
"xfs",
"and",
"mount",
"it"
] | 58b2a5d669dcfaa8cad50c544a4b068dcacf9b69 | https://github.com/jiasir/playback/blob/58b2a5d669dcfaa8cad50c544a4b068dcacf9b69/playback/swift_storage.py#L260-L272 | train | format disks to xfs and mount it |
exosite-labs/pyonep | pyonep/onephttp.py | OneP_Request.request | def request(self,
method,
path,
body=None,
headers={},
exception_fn=None,
notimeout=False,
verify=True):
"""Wraps HTTPConnection.request. On exception it calls exception_fn
with the exception ... | python | def request(self,
method,
path,
body=None,
headers={},
exception_fn=None,
notimeout=False,
verify=True):
"""Wraps HTTPConnection.request. On exception it calls exception_fn
with the exception ... | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"path",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"{",
"}",
",",
"exception_fn",
"=",
"None",
",",
"notimeout",
"=",
"False",
",",
"verify",
"=",
"True",
")",
":",
"# This needs to be done first bec... | Wraps HTTPConnection.request. On exception it calls exception_fn
with the exception object. If exception_fn is None, it re-raises the
exception. If notimeout is True, create a new connection (regardless of
self.reuseconnection setting) that uses the global default timeout for
sockets (us... | [
"Wraps",
"HTTPConnection",
".",
"request",
".",
"On",
"exception",
"it",
"calls",
"exception_fn",
"with",
"the",
"exception",
"object",
".",
"If",
"exception_fn",
"is",
"None",
"it",
"re",
"-",
"raises",
"the",
"exception",
".",
"If",
"notimeout",
"is",
"Tru... | d27b621b00688a542e0adcc01f3e3354c05238a1 | https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onephttp.py#L39-L103 | train | Wraps HTTPConnection. request. |
hbldh/dlxsudoku | dlxsudoku/sudoku.py | Sudoku.load_file | def load_file(cls, file_path):
"""Load a Sudoku from file.
:param file_path: The path to the file to load_file.
:type file_path: str, unicode
:return: A Sudoku instance with the parsed
information from the file.
:rtype: :py:class:`dlxsudoku.sudoku.Sudoku`
... | python | def load_file(cls, file_path):
"""Load a Sudoku from file.
:param file_path: The path to the file to load_file.
:type file_path: str, unicode
:return: A Sudoku instance with the parsed
information from the file.
:rtype: :py:class:`dlxsudoku.sudoku.Sudoku`
... | [
"def",
"load_file",
"(",
"cls",
",",
"file_path",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"file_path",
")",
",",
"'rt'",
")",
"as",
"f",
":",
"s",
"=",
"Sudoku",
"(",
"f",
".",
"read",
"(",
")",
".",
"strip",
"(",... | Load a Sudoku from file.
:param file_path: The path to the file to load_file.
:type file_path: str, unicode
:return: A Sudoku instance with the parsed
information from the file.
:rtype: :py:class:`dlxsudoku.sudoku.Sudoku` | [
"Load",
"a",
"Sudoku",
"from",
"file",
"."
] | 8d774e0883eb615533d04f07e58a95db716226e0 | https://github.com/hbldh/dlxsudoku/blob/8d774e0883eb615533d04f07e58a95db716226e0/dlxsudoku/sudoku.py#L55-L67 | train | Load a Sudoku from file. |
hbldh/dlxsudoku | dlxsudoku/sudoku.py | Sudoku._parse_from_string | def _parse_from_string(string_input):
"""Parses a Sudoku instance from string input.
:param string_input: A string containing the Sudoku to parse.
:type string_input: str
:return: The parsed Sudoku.
:rtype: :py:class:`dlxsudoku.sudoku.Sudoku`
"""
# Check if comm... | python | def _parse_from_string(string_input):
"""Parses a Sudoku instance from string input.
:param string_input: A string containing the Sudoku to parse.
:type string_input: str
:return: The parsed Sudoku.
:rtype: :py:class:`dlxsudoku.sudoku.Sudoku`
"""
# Check if comm... | [
"def",
"_parse_from_string",
"(",
"string_input",
")",
":",
"# Check if comment line is present.",
"read_lines",
"=",
"list",
"(",
"filter",
"(",
"None",
",",
"string_input",
".",
"split",
"(",
"'\\n'",
")",
")",
")",
"if",
"read_lines",
"[",
"0",
"]",
".",
... | Parses a Sudoku instance from string input.
:param string_input: A string containing the Sudoku to parse.
:type string_input: str
:return: The parsed Sudoku.
:rtype: :py:class:`dlxsudoku.sudoku.Sudoku` | [
"Parses",
"a",
"Sudoku",
"instance",
"from",
"string",
"input",
"."
] | 8d774e0883eb615533d04f07e58a95db716226e0 | https://github.com/hbldh/dlxsudoku/blob/8d774e0883eb615533d04f07e58a95db716226e0/dlxsudoku/sudoku.py#L70-L104 | train | Parses a Sudoku instance from a string containing the Sudoku. |
hbldh/dlxsudoku | dlxsudoku/sudoku.py | Sudoku.row_iter | def row_iter(self):
"""Get an iterator over all rows in the Sudoku"""
for k in utils.range_(self.side):
yield self.row(k) | python | def row_iter(self):
"""Get an iterator over all rows in the Sudoku"""
for k in utils.range_(self.side):
yield self.row(k) | [
"def",
"row_iter",
"(",
"self",
")",
":",
"for",
"k",
"in",
"utils",
".",
"range_",
"(",
"self",
".",
"side",
")",
":",
"yield",
"self",
".",
"row",
"(",
"k",
")"
] | Get an iterator over all rows in the Sudoku | [
"Get",
"an",
"iterator",
"over",
"all",
"rows",
"in",
"the",
"Sudoku"
] | 8d774e0883eb615533d04f07e58a95db716226e0 | https://github.com/hbldh/dlxsudoku/blob/8d774e0883eb615533d04f07e58a95db716226e0/dlxsudoku/sudoku.py#L147-L150 | train | Get an iterator over all rows in the Sudoku |
hbldh/dlxsudoku | dlxsudoku/sudoku.py | Sudoku.col_iter | def col_iter(self):
"""Get an iterator over all columns in the Sudoku"""
for k in utils.range_(self.side):
yield self.col(k) | python | def col_iter(self):
"""Get an iterator over all columns in the Sudoku"""
for k in utils.range_(self.side):
yield self.col(k) | [
"def",
"col_iter",
"(",
"self",
")",
":",
"for",
"k",
"in",
"utils",
".",
"range_",
"(",
"self",
".",
"side",
")",
":",
"yield",
"self",
".",
"col",
"(",
"k",
")"
] | Get an iterator over all columns in the Sudoku | [
"Get",
"an",
"iterator",
"over",
"all",
"columns",
"in",
"the",
"Sudoku"
] | 8d774e0883eb615533d04f07e58a95db716226e0 | https://github.com/hbldh/dlxsudoku/blob/8d774e0883eb615533d04f07e58a95db716226e0/dlxsudoku/sudoku.py#L156-L159 | train | Get an iterator over all columns in the Sudoku |
hbldh/dlxsudoku | dlxsudoku/sudoku.py | Sudoku.box | def box(self, row, col):
"""Get the values of the box pertaining to the specified row and column of the Sudoku"""
box = []
box_i = (row // self.order) * self.order
box_j = (col // self.order) * self.order
for i in utils.range_(box_i, box_i + self.order):
for j in util... | python | def box(self, row, col):
"""Get the values of the box pertaining to the specified row and column of the Sudoku"""
box = []
box_i = (row // self.order) * self.order
box_j = (col // self.order) * self.order
for i in utils.range_(box_i, box_i + self.order):
for j in util... | [
"def",
"box",
"(",
"self",
",",
"row",
",",
"col",
")",
":",
"box",
"=",
"[",
"]",
"box_i",
"=",
"(",
"row",
"//",
"self",
".",
"order",
")",
"*",
"self",
".",
"order",
"box_j",
"=",
"(",
"col",
"//",
"self",
".",
"order",
")",
"*",
"self",
... | Get the values of the box pertaining to the specified row and column of the Sudoku | [
"Get",
"the",
"values",
"of",
"the",
"box",
"pertaining",
"to",
"the",
"specified",
"row",
"and",
"column",
"of",
"the",
"Sudoku"
] | 8d774e0883eb615533d04f07e58a95db716226e0 | https://github.com/hbldh/dlxsudoku/blob/8d774e0883eb615533d04f07e58a95db716226e0/dlxsudoku/sudoku.py#L161-L169 | train | Get the values of the box pertaining to the specified row and column of the Sudoku |
hbldh/dlxsudoku | dlxsudoku/sudoku.py | Sudoku.box_iter | def box_iter(self):
"""Get an iterator over all boxes in the Sudoku"""
for i in utils.range_(self.order):
for j in utils.range_(self.order):
yield self.box(i * 3, j * 3) | python | def box_iter(self):
"""Get an iterator over all boxes in the Sudoku"""
for i in utils.range_(self.order):
for j in utils.range_(self.order):
yield self.box(i * 3, j * 3) | [
"def",
"box_iter",
"(",
"self",
")",
":",
"for",
"i",
"in",
"utils",
".",
"range_",
"(",
"self",
".",
"order",
")",
":",
"for",
"j",
"in",
"utils",
".",
"range_",
"(",
"self",
".",
"order",
")",
":",
"yield",
"self",
".",
"box",
"(",
"i",
"*",
... | Get an iterator over all boxes in the Sudoku | [
"Get",
"an",
"iterator",
"over",
"all",
"boxes",
"in",
"the",
"Sudoku"
] | 8d774e0883eb615533d04f07e58a95db716226e0 | https://github.com/hbldh/dlxsudoku/blob/8d774e0883eb615533d04f07e58a95db716226e0/dlxsudoku/sudoku.py#L171-L175 | train | Get an iterator over all boxes in the Sudoku |
hbldh/dlxsudoku | dlxsudoku/sudoku.py | Sudoku.set_cell | def set_cell(self, i, j, value):
"""Set a cell's value, with a series of safety checks
:param i: The row number
:type i: int
:param j: The column number
:type j: int
:param value: The value to set
:type value: int
:raises: :py:class:`dlxsudoku.exceptions.... | python | def set_cell(self, i, j, value):
"""Set a cell's value, with a series of safety checks
:param i: The row number
:type i: int
:param j: The column number
:type j: int
:param value: The value to set
:type value: int
:raises: :py:class:`dlxsudoku.exceptions.... | [
"def",
"set_cell",
"(",
"self",
",",
"i",
",",
"j",
",",
"value",
")",
":",
"bool_tests",
"=",
"[",
"value",
"in",
"self",
".",
"_possibles",
"[",
"i",
"]",
"[",
"j",
"]",
",",
"value",
"in",
"self",
".",
"_poss_rows",
"[",
"i",
"]",
",",
"valu... | Set a cell's value, with a series of safety checks
:param i: The row number
:type i: int
:param j: The column number
:type j: int
:param value: The value to set
:type value: int
:raises: :py:class:`dlxsudoku.exceptions.SudokuHasNoSolutionError` | [
"Set",
"a",
"cell",
"s",
"value",
"with",
"a",
"series",
"of",
"safety",
"checks"
] | 8d774e0883eb615533d04f07e58a95db716226e0 | https://github.com/hbldh/dlxsudoku/blob/8d774e0883eb615533d04f07e58a95db716226e0/dlxsudoku/sudoku.py#L177-L202 | train | Set a cell s value with a series of safety checks |
hbldh/dlxsudoku | dlxsudoku/sudoku.py | Sudoku.solve | def solve(self, verbose=False, allow_brute_force=True):
"""Solve the Sudoku.
:param verbose: If the steps used for solving the Sudoku
should be printed. Default is `False`
:type verbose: bool
:param allow_brute_force: If Dancing Links Brute Force method
... | python | def solve(self, verbose=False, allow_brute_force=True):
"""Solve the Sudoku.
:param verbose: If the steps used for solving the Sudoku
should be printed. Default is `False`
:type verbose: bool
:param allow_brute_force: If Dancing Links Brute Force method
... | [
"def",
"solve",
"(",
"self",
",",
"verbose",
"=",
"False",
",",
"allow_brute_force",
"=",
"True",
")",
":",
"while",
"not",
"self",
".",
"is_solved",
":",
"# Update possibles arrays.",
"self",
".",
"_update",
"(",
")",
"# See if any position can be singled out.",
... | Solve the Sudoku.
:param verbose: If the steps used for solving the Sudoku
should be printed. Default is `False`
:type verbose: bool
:param allow_brute_force: If Dancing Links Brute Force method
should be used if necessary. Default is `T... | [
"Solve",
"the",
"Sudoku",
"."
] | 8d774e0883eb615533d04f07e58a95db716226e0 | https://github.com/hbldh/dlxsudoku/blob/8d774e0883eb615533d04f07e58a95db716226e0/dlxsudoku/sudoku.py#L209-L257 | train | Solve the Sudoku. |
hbldh/dlxsudoku | dlxsudoku/sudoku.py | Sudoku._fill_naked_singles | def _fill_naked_singles(self):
"""Look for naked singles, i.e. cells with ony one possible value.
:return: If any Naked Single has been found.
:rtype: bool
"""
simple_found = False
for i in utils.range_(self.side):
for j in utils.range_(self.side):
... | python | def _fill_naked_singles(self):
"""Look for naked singles, i.e. cells with ony one possible value.
:return: If any Naked Single has been found.
:rtype: bool
"""
simple_found = False
for i in utils.range_(self.side):
for j in utils.range_(self.side):
... | [
"def",
"_fill_naked_singles",
"(",
"self",
")",
":",
"simple_found",
"=",
"False",
"for",
"i",
"in",
"utils",
".",
"range_",
"(",
"self",
".",
"side",
")",
":",
"for",
"j",
"in",
"utils",
".",
"range_",
"(",
"self",
".",
"side",
")",
":",
"if",
"se... | Look for naked singles, i.e. cells with ony one possible value.
:return: If any Naked Single has been found.
:rtype: bool | [
"Look",
"for",
"naked",
"singles",
"i",
".",
"e",
".",
"cells",
"with",
"ony",
"one",
"possible",
"value",
"."
] | 8d774e0883eb615533d04f07e58a95db716226e0 | https://github.com/hbldh/dlxsudoku/blob/8d774e0883eb615533d04f07e58a95db716226e0/dlxsudoku/sudoku.py#L279-L299 | train | Look for naked singles i. e. cells with ony one possible value. |
hbldh/dlxsudoku | dlxsudoku/sudoku.py | Sudoku._fill_hidden_singles | def _fill_hidden_singles(self):
"""Look for hidden singles, i.e. cells with only one unique possible value in row, column or box.
:return: If any Hidden Single has been found.
:rtype: bool
"""
for i in utils.range_(self.side):
box_i = (i // self.order) * self.order
... | python | def _fill_hidden_singles(self):
"""Look for hidden singles, i.e. cells with only one unique possible value in row, column or box.
:return: If any Hidden Single has been found.
:rtype: bool
"""
for i in utils.range_(self.side):
box_i = (i // self.order) * self.order
... | [
"def",
"_fill_hidden_singles",
"(",
"self",
")",
":",
"for",
"i",
"in",
"utils",
".",
"range_",
"(",
"self",
".",
"side",
")",
":",
"box_i",
"=",
"(",
"i",
"//",
"self",
".",
"order",
")",
"*",
"self",
".",
"order",
"for",
"j",
"in",
"utils",
"."... | Look for hidden singles, i.e. cells with only one unique possible value in row, column or box.
:return: If any Hidden Single has been found.
:rtype: bool | [
"Look",
"for",
"hidden",
"singles",
"i",
".",
"e",
".",
"cells",
"with",
"only",
"one",
"unique",
"possible",
"value",
"in",
"row",
"column",
"or",
"box",
"."
] | 8d774e0883eb615533d04f07e58a95db716226e0 | https://github.com/hbldh/dlxsudoku/blob/8d774e0883eb615533d04f07e58a95db716226e0/dlxsudoku/sudoku.py#L301-L353 | train | Look for hidden singles i. e. cells with only one unique possible value in row column or box. |
Capitains/MyCapytain | MyCapytain/resources/collections/dts/_base.py | DtsCollection.parse | def parse(cls, resource, direction="children", **additional_parameters) -> "DtsCollection":
""" Given a dict representation of a json object, generate a DTS Collection
:param resource:
:type resource: dict
:param direction: Direction of the hydra:members value
:return: DTSCollec... | python | def parse(cls, resource, direction="children", **additional_parameters) -> "DtsCollection":
""" Given a dict representation of a json object, generate a DTS Collection
:param resource:
:type resource: dict
:param direction: Direction of the hydra:members value
:return: DTSCollec... | [
"def",
"parse",
"(",
"cls",
",",
"resource",
",",
"direction",
"=",
"\"children\"",
",",
"*",
"*",
"additional_parameters",
")",
"->",
"\"DtsCollection\"",
":",
"data",
"=",
"jsonld",
".",
"expand",
"(",
"resource",
")",
"if",
"len",
"(",
"data",
")",
"=... | Given a dict representation of a json object, generate a DTS Collection
:param resource:
:type resource: dict
:param direction: Direction of the hydra:members value
:return: DTSCollection parsed
:rtype: DtsCollection | [
"Given",
"a",
"dict",
"representation",
"of",
"a",
"json",
"object",
"generate",
"a",
"DTS",
"Collection"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/collections/dts/_base.py#L72-L95 | train | Given a dict representation of a json object generate a DTSCollection object. |
Capitains/MyCapytain | MyCapytain/resources/collections/dts/_base.py | DtsCollection.parse_member | def parse_member(
cls,
obj: dict,
collection: "DtsCollection",
direction: str,
**additional_parameters) -> List["DtsCollection"]:
""" Parse the member value of a Collection response
and returns the list of object while setting the graph
... | python | def parse_member(
cls,
obj: dict,
collection: "DtsCollection",
direction: str,
**additional_parameters) -> List["DtsCollection"]:
""" Parse the member value of a Collection response
and returns the list of object while setting the graph
... | [
"def",
"parse_member",
"(",
"cls",
",",
"obj",
":",
"dict",
",",
"collection",
":",
"\"DtsCollection\"",
",",
"direction",
":",
"str",
",",
"*",
"*",
"additional_parameters",
")",
"->",
"List",
"[",
"\"DtsCollection\"",
"]",
":",
"members",
"=",
"[",
"]",
... | Parse the member value of a Collection response
and returns the list of object while setting the graph
relationship based on `direction`
:param obj: PyLD parsed JSON+LD
:param collection: Collection attached to the member property
:param direction: Direction of the member (child... | [
"Parse",
"the",
"member",
"value",
"of",
"a",
"Collection",
"response",
"and",
"returns",
"the",
"list",
"of",
"object",
"while",
"setting",
"the",
"graph",
"relationship",
"based",
"on",
"direction"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/collections/dts/_base.py#L149-L171 | train | Parses the member value of a Collection response and returns the list of objects while setting the graph
relationship based on the direction |
ChrisBeaumont/smother | smother/python.py | Visitor._filldown | def _filldown(self, lineno):
"""
Copy current_context into `lines` down up until lineno
"""
if self.line > lineno:
# XXX decorated functions make us jump backwards.
# understand this more
return
self.lines.extend(
self.current_cont... | python | def _filldown(self, lineno):
"""
Copy current_context into `lines` down up until lineno
"""
if self.line > lineno:
# XXX decorated functions make us jump backwards.
# understand this more
return
self.lines.extend(
self.current_cont... | [
"def",
"_filldown",
"(",
"self",
",",
"lineno",
")",
":",
"if",
"self",
".",
"line",
">",
"lineno",
":",
"# XXX decorated functions make us jump backwards.",
"# understand this more",
"return",
"self",
".",
"lines",
".",
"extend",
"(",
"self",
".",
"current_contex... | Copy current_context into `lines` down up until lineno | [
"Copy",
"current_context",
"into",
"lines",
"down",
"up",
"until",
"lineno"
] | 65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb | https://github.com/ChrisBeaumont/smother/blob/65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb/smother/python.py#L50-L61 | train | Copy current_context into lines down until lineno. |
ChrisBeaumont/smother | smother/python.py | Visitor._add_section | def _add_section(self, node):
"""
Register the current node as a new context block
"""
self._filldown(node.lineno)
# push a new context onto stack
self.context.append(node.name)
self._update_current_context()
for _ in map(self.visit, iter_child_nodes(nod... | python | def _add_section(self, node):
"""
Register the current node as a new context block
"""
self._filldown(node.lineno)
# push a new context onto stack
self.context.append(node.name)
self._update_current_context()
for _ in map(self.visit, iter_child_nodes(nod... | [
"def",
"_add_section",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"_filldown",
"(",
"node",
".",
"lineno",
")",
"# push a new context onto stack",
"self",
".",
"context",
".",
"append",
"(",
"node",
".",
"name",
")",
"self",
".",
"_update_current_conte... | Register the current node as a new context block | [
"Register",
"the",
"current",
"node",
"as",
"a",
"new",
"context",
"block"
] | 65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb | https://github.com/ChrisBeaumont/smother/blob/65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb/smother/python.py#L63-L78 | train | Add a section to the current context. |
ChrisBeaumont/smother | smother/python.py | PythonFile._module_name | def _module_name(filename):
"""
Try to find a module name for a file path
by stripping off a prefix found in sys.modules.
"""
absfile = os.path.abspath(filename)
match = filename
for base in [''] + sys.path:
base = os.path.abspath(base)
i... | python | def _module_name(filename):
"""
Try to find a module name for a file path
by stripping off a prefix found in sys.modules.
"""
absfile = os.path.abspath(filename)
match = filename
for base in [''] + sys.path:
base = os.path.abspath(base)
i... | [
"def",
"_module_name",
"(",
"filename",
")",
":",
"absfile",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"filename",
")",
"match",
"=",
"filename",
"for",
"base",
"in",
"[",
"''",
"]",
"+",
"sys",
".",
"path",
":",
"base",
"=",
"os",
".",
"path",
... | Try to find a module name for a file path
by stripping off a prefix found in sys.modules. | [
"Try",
"to",
"find",
"a",
"module",
"name",
"for",
"a",
"file",
"path",
"by",
"stripping",
"off",
"a",
"prefix",
"found",
"in",
"sys",
".",
"modules",
"."
] | 65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb | https://github.com/ChrisBeaumont/smother/blob/65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb/smother/python.py#L140-L155 | train | Try to find a module name for a file path by stripping off a prefix found in sys. modules. |
ChrisBeaumont/smother | smother/python.py | PythonFile.from_modulename | def from_modulename(cls, module_name):
"""
Build a PythonFile given a dotted module name like a.b.c
"""
# XXX make this more robust (pyc files? zip archives? etc)
slug = module_name.replace('.', '/')
paths = [slug + '.py', slug + '/__init__.py']
# always search f... | python | def from_modulename(cls, module_name):
"""
Build a PythonFile given a dotted module name like a.b.c
"""
# XXX make this more robust (pyc files? zip archives? etc)
slug = module_name.replace('.', '/')
paths = [slug + '.py', slug + '/__init__.py']
# always search f... | [
"def",
"from_modulename",
"(",
"cls",
",",
"module_name",
")",
":",
"# XXX make this more robust (pyc files? zip archives? etc)",
"slug",
"=",
"module_name",
".",
"replace",
"(",
"'.'",
",",
"'/'",
")",
"paths",
"=",
"[",
"slug",
"+",
"'.py'",
",",
"slug",
"+",
... | Build a PythonFile given a dotted module name like a.b.c | [
"Build",
"a",
"PythonFile",
"given",
"a",
"dotted",
"module",
"name",
"like",
"a",
".",
"b",
".",
"c"
] | 65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb | https://github.com/ChrisBeaumont/smother/blob/65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb/smother/python.py#L158-L173 | train | Build a PythonFile from a dotted module name like a. b. c
|
ChrisBeaumont/smother | smother/python.py | PythonFile.context_range | def context_range(self, context):
"""
Return the 1-offset, right-open range of lines spanned by
a particular context name.
Parameters
----------
context : str
Raises
------
ValueError, if context is not present in the file.
"""
if... | python | def context_range(self, context):
"""
Return the 1-offset, right-open range of lines spanned by
a particular context name.
Parameters
----------
context : str
Raises
------
ValueError, if context is not present in the file.
"""
if... | [
"def",
"context_range",
"(",
"self",
",",
"context",
")",
":",
"if",
"not",
"context",
".",
"startswith",
"(",
"self",
".",
"prefix",
")",
":",
"context",
"=",
"self",
".",
"prefix",
"+",
"'.'",
"+",
"context",
"lo",
"=",
"hi",
"=",
"None",
"for",
... | Return the 1-offset, right-open range of lines spanned by
a particular context name.
Parameters
----------
context : str
Raises
------
ValueError, if context is not present in the file. | [
"Return",
"the",
"1",
"-",
"offset",
"right",
"-",
"open",
"range",
"of",
"lines",
"spanned",
"by",
"a",
"particular",
"context",
"name",
"."
] | 65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb | https://github.com/ChrisBeaumont/smother/blob/65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb/smother/python.py#L179-L208 | train | Return the 1 - offset right - open range of lines spanned by a particular context name. |
ChrisBeaumont/smother | smother/python.py | PythonFile.context | def context(self, line):
"""
Return the context for a given 1-offset line number.
"""
# XXX due to a limitation in Visitor,
# non-python code after the last python code
# in a file is not added to self.lines, so we
# have to guard against IndexErrors.
idx ... | python | def context(self, line):
"""
Return the context for a given 1-offset line number.
"""
# XXX due to a limitation in Visitor,
# non-python code after the last python code
# in a file is not added to self.lines, so we
# have to guard against IndexErrors.
idx ... | [
"def",
"context",
"(",
"self",
",",
"line",
")",
":",
"# XXX due to a limitation in Visitor,",
"# non-python code after the last python code",
"# in a file is not added to self.lines, so we",
"# have to guard against IndexErrors.",
"idx",
"=",
"line",
"-",
"1",
"if",
"idx",
">=... | Return the context for a given 1-offset line number. | [
"Return",
"the",
"context",
"for",
"a",
"given",
"1",
"-",
"offset",
"line",
"number",
"."
] | 65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb | https://github.com/ChrisBeaumont/smother/blob/65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb/smother/python.py#L210-L221 | train | Return the context for a given line number. |
infothrill/python-launchd | launchd/plist.py | discover_filename | def discover_filename(label, scopes=None):
'''
Check the filesystem for the existence of a .plist file matching the job label.
Optionally specify one or more scopes to search (default all).
:param label: string
:param scope: tuple or list or oneOf(USER, USER_ADMIN, DAEMON_ADMIN, USER_OS, DAEMON_OS)... | python | def discover_filename(label, scopes=None):
'''
Check the filesystem for the existence of a .plist file matching the job label.
Optionally specify one or more scopes to search (default all).
:param label: string
:param scope: tuple or list or oneOf(USER, USER_ADMIN, DAEMON_ADMIN, USER_OS, DAEMON_OS)... | [
"def",
"discover_filename",
"(",
"label",
",",
"scopes",
"=",
"None",
")",
":",
"if",
"scopes",
"is",
"None",
":",
"scopes",
"=",
"[",
"k",
"for",
"k",
"in",
"PLIST_LOCATIONS",
"]",
"elif",
"not",
"isinstance",
"(",
"scopes",
",",
"(",
"list",
",",
"... | Check the filesystem for the existence of a .plist file matching the job label.
Optionally specify one or more scopes to search (default all).
:param label: string
:param scope: tuple or list or oneOf(USER, USER_ADMIN, DAEMON_ADMIN, USER_OS, DAEMON_OS) | [
"Check",
"the",
"filesystem",
"for",
"the",
"existence",
"of",
"a",
".",
"plist",
"file",
"matching",
"the",
"job",
"label",
".",
"Optionally",
"specify",
"one",
"or",
"more",
"scopes",
"to",
"search",
"(",
"default",
"all",
")",
"."
] | 2cd50579e808851b116f5a26f9b871a32b65ce0e | https://github.com/infothrill/python-launchd/blob/2cd50579e808851b116f5a26f9b871a32b65ce0e/launchd/plist.py#L25-L41 | train | Find the filename of a. plist file matching the given label. |
infothrill/python-launchd | launchd/plist.py | write | def write(label, plist, scope=USER):
'''
Writes the given property list to the appropriate file on disk and returns
the absolute filename.
:param plist: dict
:param label: string
:param scope: oneOf(USER, USER_ADMIN, DAEMON_ADMIN, USER_OS, DAEMON_OS)
'''
fname = compute_filename(label, ... | python | def write(label, plist, scope=USER):
'''
Writes the given property list to the appropriate file on disk and returns
the absolute filename.
:param plist: dict
:param label: string
:param scope: oneOf(USER, USER_ADMIN, DAEMON_ADMIN, USER_OS, DAEMON_OS)
'''
fname = compute_filename(label, ... | [
"def",
"write",
"(",
"label",
",",
"plist",
",",
"scope",
"=",
"USER",
")",
":",
"fname",
"=",
"compute_filename",
"(",
"label",
",",
"scope",
")",
"with",
"open",
"(",
"fname",
",",
"\"wb\"",
")",
"as",
"f",
":",
"plistlib",
".",
"writePlist",
"(",
... | Writes the given property list to the appropriate file on disk and returns
the absolute filename.
:param plist: dict
:param label: string
:param scope: oneOf(USER, USER_ADMIN, DAEMON_ADMIN, USER_OS, DAEMON_OS) | [
"Writes",
"the",
"given",
"property",
"list",
"to",
"the",
"appropriate",
"file",
"on",
"disk",
"and",
"returns",
"the",
"absolute",
"filename",
"."
] | 2cd50579e808851b116f5a26f9b871a32b65ce0e | https://github.com/infothrill/python-launchd/blob/2cd50579e808851b116f5a26f9b871a32b65ce0e/launchd/plist.py#L49-L61 | train | Writes the given property list to the appropriate file on disk and returns the absolute filename. |
SHDShim/pytheos | pytheos/eqn_therm.py | alphakt_pth | def alphakt_pth(v, temp, v0, alpha0, k0, n, z, t_ref=300.,
three_r=3. * constants.R):
"""
calculate thermal pressure from thermal expansion and bulk modulus
:param v: unit-cell volume in A^3
:param temp: temperature in K
:param v0: unit-cell volume in A^3 at 1 bar
:param alpha0:... | python | def alphakt_pth(v, temp, v0, alpha0, k0, n, z, t_ref=300.,
three_r=3. * constants.R):
"""
calculate thermal pressure from thermal expansion and bulk modulus
:param v: unit-cell volume in A^3
:param temp: temperature in K
:param v0: unit-cell volume in A^3 at 1 bar
:param alpha0:... | [
"def",
"alphakt_pth",
"(",
"v",
",",
"temp",
",",
"v0",
",",
"alpha0",
",",
"k0",
",",
"n",
",",
"z",
",",
"t_ref",
"=",
"300.",
",",
"three_r",
"=",
"3.",
"*",
"constants",
".",
"R",
")",
":",
"return",
"alpha0",
"*",
"k0",
"*",
"(",
"temp",
... | calculate thermal pressure from thermal expansion and bulk modulus
:param v: unit-cell volume in A^3
:param temp: temperature in K
:param v0: unit-cell volume in A^3 at 1 bar
:param alpha0: thermal expansion parameter at 1 bar in K-1
:param k0: bulk modulus in GPa
:param n: number of atoms in a... | [
"calculate",
"thermal",
"pressure",
"from",
"thermal",
"expansion",
"and",
"bulk",
"modulus"
] | be079624405e92fbec60c5ead253eb5917e55237 | https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_therm.py#L5-L21 | train | calculate thermal pressure from alphakt formula |
exosite-labs/pyonep | pyonep/portals/utils.py | dictify_device_meta | def dictify_device_meta(device_object):
""" Input: Portals device object.
Output: The same device object with the device meta
converted to a python dictionary. """
try:
if isinstance(device_object['info']['description']['meta'], str) or \
isinstance(device_object['in... | python | def dictify_device_meta(device_object):
""" Input: Portals device object.
Output: The same device object with the device meta
converted to a python dictionary. """
try:
if isinstance(device_object['info']['description']['meta'], str) or \
isinstance(device_object['in... | [
"def",
"dictify_device_meta",
"(",
"device_object",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"device_object",
"[",
"'info'",
"]",
"[",
"'description'",
"]",
"[",
"'meta'",
"]",
",",
"str",
")",
"or",
"isinstance",
"(",
"device_object",
"[",
"'info'",
... | Input: Portals device object.
Output: The same device object with the device meta
converted to a python dictionary. | [
"Input",
":",
"Portals",
"device",
"object",
".",
"Output",
":",
"The",
"same",
"device",
"object",
"with",
"the",
"device",
"meta",
"converted",
"to",
"a",
"python",
"dictionary",
"."
] | d27b621b00688a542e0adcc01f3e3354c05238a1 | https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/utils.py#L15-L26 | train | Convert the device object meta to a python dictionary. |
exosite-labs/pyonep | pyonep/portals/utils.py | stringify_device_meta | def stringify_device_meta(device_object):
""" Input: Portals device object.
Output: The same device object with the device meta
converted to a python string. """
try:
if isinstance(device_object['info']['description']['meta'], dict):
device_object['info']['description... | python | def stringify_device_meta(device_object):
""" Input: Portals device object.
Output: The same device object with the device meta
converted to a python string. """
try:
if isinstance(device_object['info']['description']['meta'], dict):
device_object['info']['description... | [
"def",
"stringify_device_meta",
"(",
"device_object",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"device_object",
"[",
"'info'",
"]",
"[",
"'description'",
"]",
"[",
"'meta'",
"]",
",",
"dict",
")",
":",
"device_object",
"[",
"'info'",
"]",
"[",
"'desc... | Input: Portals device object.
Output: The same device object with the device meta
converted to a python string. | [
"Input",
":",
"Portals",
"device",
"object",
".",
"Output",
":",
"The",
"same",
"device",
"object",
"with",
"the",
"device",
"meta",
"converted",
"to",
"a",
"python",
"string",
"."
] | d27b621b00688a542e0adcc01f3e3354c05238a1 | https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/utils.py#L28-L38 | train | Convert the device object meta to a python string. |
aiidateam/aiida-codtools | aiida_codtools/parsers/cif_cod_deposit.py | CifCodDepositParser._get_output_nodes | def _get_output_nodes(self, output_path, error_path):
"""
Extracts output nodes from the standard output and standard error files
"""
status = cod_deposition_states.UNKNOWN
messages = []
if output_path is not None:
content = None
with open(output_... | python | def _get_output_nodes(self, output_path, error_path):
"""
Extracts output nodes from the standard output and standard error files
"""
status = cod_deposition_states.UNKNOWN
messages = []
if output_path is not None:
content = None
with open(output_... | [
"def",
"_get_output_nodes",
"(",
"self",
",",
"output_path",
",",
"error_path",
")",
":",
"status",
"=",
"cod_deposition_states",
".",
"UNKNOWN",
"messages",
"=",
"[",
"]",
"if",
"output_path",
"is",
"not",
"None",
":",
"content",
"=",
"None",
"with",
"open"... | Extracts output nodes from the standard output and standard error files | [
"Extracts",
"output",
"nodes",
"from",
"the",
"standard",
"output",
"and",
"standard",
"error",
"files"
] | da5e4259b7a2e86cf0cc3f997e11dd36d445fa94 | https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/parsers/cif_cod_deposit.py#L35-L63 | train | Extracts output nodes from the standard output and standard error files and returns a list of output nodes and the list of output nodes that are returned. |
chaoss/grimoirelab-cereslib | cereslib/dfutils/filter.py | FilterRows.filter_ | def filter_(self, columns, value):
""" This method filter some of the rows where the 'value'
is found in each of the 'columns'.
:param column: list of strings
:param value: any type
:returns: filtered dataframe
:rtype: pandas.DataFrame
"""
for column in... | python | def filter_(self, columns, value):
""" This method filter some of the rows where the 'value'
is found in each of the 'columns'.
:param column: list of strings
:param value: any type
:returns: filtered dataframe
:rtype: pandas.DataFrame
"""
for column in... | [
"def",
"filter_",
"(",
"self",
",",
"columns",
",",
"value",
")",
":",
"for",
"column",
"in",
"columns",
":",
"if",
"column",
"not",
"in",
"self",
".",
"data",
".",
"columns",
":",
"raise",
"ValueError",
"(",
"\"Column %s not in DataFrame columns: %s\"",
"%"... | This method filter some of the rows where the 'value'
is found in each of the 'columns'.
:param column: list of strings
:param value: any type
:returns: filtered dataframe
:rtype: pandas.DataFrame | [
"This",
"method",
"filter",
"some",
"of",
"the",
"rows",
"where",
"the",
"value",
"is",
"found",
"in",
"each",
"of",
"the",
"columns",
"."
] | 5110e6ca490a4f24bec3124286ebf51fd4e08bdd | https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/dfutils/filter.py#L54-L75 | train | This method filters the dataframe by the value in each of the columns. |
crdoconnor/commandlib | commandlib/utils.py | _check_directory | def _check_directory(directory):
"""Raise exception if directory does not exist."""
if directory is not None:
if not exists(directory):
raise CommandError(
"Cannot run command - directory {0} does not exist".format(directory)
)
if not isdir(directory):
... | python | def _check_directory(directory):
"""Raise exception if directory does not exist."""
if directory is not None:
if not exists(directory):
raise CommandError(
"Cannot run command - directory {0} does not exist".format(directory)
)
if not isdir(directory):
... | [
"def",
"_check_directory",
"(",
"directory",
")",
":",
"if",
"directory",
"is",
"not",
"None",
":",
"if",
"not",
"exists",
"(",
"directory",
")",
":",
"raise",
"CommandError",
"(",
"\"Cannot run command - directory {0} does not exist\"",
".",
"format",
"(",
"direc... | Raise exception if directory does not exist. | [
"Raise",
"exception",
"if",
"directory",
"does",
"not",
"exist",
"."
] | b630364fd7b0d189b388e22a7f43235d182e12e4 | https://github.com/crdoconnor/commandlib/blob/b630364fd7b0d189b388e22a7f43235d182e12e4/commandlib/utils.py#L5-L18 | train | Raise exception if directory does not exist. |
totalgood/twip | twip/features.py | load_tweets | def load_tweets(filename='tweets.zip'):
r"""Extract the cached tweets "database" if necessary and load + parse the json.
>>> js = load_tweets()
>>> len(js)
8000
>>> js[0].keys()
[u'contributors',
u'truncated',
u'text',
u'is_quote_status',
u'in_reply_to_status_id',
u'id'... | python | def load_tweets(filename='tweets.zip'):
r"""Extract the cached tweets "database" if necessary and load + parse the json.
>>> js = load_tweets()
>>> len(js)
8000
>>> js[0].keys()
[u'contributors',
u'truncated',
u'text',
u'is_quote_status',
u'in_reply_to_status_id',
u'id'... | [
"def",
"load_tweets",
"(",
"filename",
"=",
"'tweets.zip'",
")",
":",
"basename",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"json_file",
"=",
"basename",
"+",
"'.json'",
"json_path",
"=",
"os",
".",
"path",
".",
"join",
... | r"""Extract the cached tweets "database" if necessary and load + parse the json.
>>> js = load_tweets()
>>> len(js)
8000
>>> js[0].keys()
[u'contributors',
u'truncated',
u'text',
u'is_quote_status',
u'in_reply_to_status_id',
u'id',
u'favorite_count',
u'source',
... | [
"r",
"Extract",
"the",
"cached",
"tweets",
"database",
"if",
"necessary",
"and",
"load",
"+",
"parse",
"the",
"json",
"."
] | 5c0411d2acfbe5b421841072814c9152591c03f7 | https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/twip/features.py#L21-L249 | train | r Loads the tweets from a zip file. |
totalgood/twip | twip/features.py | features | def features(filename='tweets.zip'):
"""NotImplemented"""
raise NotImplemented("Need to implement feature extraction.")
js = load_tweets(filename)
index = []
table = []
columns = [u'text', u'is_quote_status',
u'in_reply_to_status_id', u'in_reply_to_user_id',
u'favor... | python | def features(filename='tweets.zip'):
"""NotImplemented"""
raise NotImplemented("Need to implement feature extraction.")
js = load_tweets(filename)
index = []
table = []
columns = [u'text', u'is_quote_status',
u'in_reply_to_status_id', u'in_reply_to_user_id',
u'favor... | [
"def",
"features",
"(",
"filename",
"=",
"'tweets.zip'",
")",
":",
"raise",
"NotImplemented",
"(",
"\"Need to implement feature extraction.\"",
")",
"js",
"=",
"load_tweets",
"(",
"filename",
")",
"index",
"=",
"[",
"]",
"table",
"=",
"[",
"]",
"columns",
"=",... | NotImplemented | [
"NotImplemented"
] | 5c0411d2acfbe5b421841072814c9152591c03f7 | https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/twip/features.py#L252-L276 | train | Extract the features from a Tweets. zip file. |
totalgood/twip | twip/scripts/cat_tweets.py | parse_args | def parse_args(args):
"""
Parse command line parameters
:param args: command line parameters as list of strings
:return: command line parameters as :obj:`argparse.Namespace`
"""
parser = argparse.ArgumentParser(
description="Concatenate and preprocess tweet json files dumped by tweetget... | python | def parse_args(args):
"""
Parse command line parameters
:param args: command line parameters as list of strings
:return: command line parameters as :obj:`argparse.Namespace`
"""
parser = argparse.ArgumentParser(
description="Concatenate and preprocess tweet json files dumped by tweetget... | [
"def",
"parse_args",
"(",
"args",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Concatenate and preprocess tweet json files dumped by tweetget\"",
")",
"parser",
".",
"add_argument",
"(",
"'-v'",
",",
"'--verbose'",
",",
"help... | Parse command line parameters
:param args: command line parameters as list of strings
:return: command line parameters as :obj:`argparse.Namespace` | [
"Parse",
"command",
"line",
"parameters"
] | 5c0411d2acfbe5b421841072814c9152591c03f7 | https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/twip/scripts/cat_tweets.py#L47-L87 | train | Parse command line parameters and return a list of strings |
totalgood/twip | twip/scripts/cat_tweets.py | main | def main(args):
"""API with args object containing configuration parameters"""
global logging, log
args = parse_args(args)
logging.basicConfig(format=LOG_FORMAT,
level=logging.DEBUG if args.verbose else logging.INFO,
stream=sys.stdout)
df = cat_tweets... | python | def main(args):
"""API with args object containing configuration parameters"""
global logging, log
args = parse_args(args)
logging.basicConfig(format=LOG_FORMAT,
level=logging.DEBUG if args.verbose else logging.INFO,
stream=sys.stdout)
df = cat_tweets... | [
"def",
"main",
"(",
"args",
")",
":",
"global",
"logging",
",",
"log",
"args",
"=",
"parse_args",
"(",
"args",
")",
"logging",
".",
"basicConfig",
"(",
"format",
"=",
"LOG_FORMAT",
",",
"level",
"=",
"logging",
".",
"DEBUG",
"if",
"args",
".",
"verbose... | API with args object containing configuration parameters | [
"API",
"with",
"args",
"object",
"containing",
"configuration",
"parameters"
] | 5c0411d2acfbe5b421841072814c9152591c03f7 | https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/twip/scripts/cat_tweets.py#L90-L105 | train | API with args object containing configuration parameters |
totalgood/twip | twip/scripts/cat_tweets.py | cat_tweets | def cat_tweets(filename='all_tweets.json.gz', path=DATA_PATH, ext='.json', save_tmp=False, verbosity=1, numtweets=10000000, ignore_suspicious=True):
"""Find json files that were dumped by tweetget and combine them into a single CSV
Normalize some (lat/lon)"""
log.info('Finding {} files in {}...'.format(ext... | python | def cat_tweets(filename='all_tweets.json.gz', path=DATA_PATH, ext='.json', save_tmp=False, verbosity=1, numtweets=10000000, ignore_suspicious=True):
"""Find json files that were dumped by tweetget and combine them into a single CSV
Normalize some (lat/lon)"""
log.info('Finding {} files in {}...'.format(ext... | [
"def",
"cat_tweets",
"(",
"filename",
"=",
"'all_tweets.json.gz'",
",",
"path",
"=",
"DATA_PATH",
",",
"ext",
"=",
"'.json'",
",",
"save_tmp",
"=",
"False",
",",
"verbosity",
"=",
"1",
",",
"numtweets",
"=",
"10000000",
",",
"ignore_suspicious",
"=",
"True",... | Find json files that were dumped by tweetget and combine them into a single CSV
Normalize some (lat/lon) | [
"Find",
"json",
"files",
"that",
"were",
"dumped",
"by",
"tweetget",
"and",
"combine",
"them",
"into",
"a",
"single",
"CSV"
] | 5c0411d2acfbe5b421841072814c9152591c03f7 | https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/twip/scripts/cat_tweets.py#L113-L181 | train | Combine all tweetget json files into a single dataframe |
totalgood/twip | twip/scripts/cat_tweets.py | drop_nan_columns | def drop_nan_columns(df, thresh=325):
"""Drop columns that are mostly NaNs
Excel files can only have 256 columns, so you may have to drop a lot in order to get down to this
"""
if thresh < 1:
thresh = int(thresh * df)
return df.dropna(axis=1, thresh=thresh, inplace=False) | python | def drop_nan_columns(df, thresh=325):
"""Drop columns that are mostly NaNs
Excel files can only have 256 columns, so you may have to drop a lot in order to get down to this
"""
if thresh < 1:
thresh = int(thresh * df)
return df.dropna(axis=1, thresh=thresh, inplace=False) | [
"def",
"drop_nan_columns",
"(",
"df",
",",
"thresh",
"=",
"325",
")",
":",
"if",
"thresh",
"<",
"1",
":",
"thresh",
"=",
"int",
"(",
"thresh",
"*",
"df",
")",
"return",
"df",
".",
"dropna",
"(",
"axis",
"=",
"1",
",",
"thresh",
"=",
"thresh",
","... | Drop columns that are mostly NaNs
Excel files can only have 256 columns, so you may have to drop a lot in order to get down to this | [
"Drop",
"columns",
"that",
"are",
"mostly",
"NaNs"
] | 5c0411d2acfbe5b421841072814c9152591c03f7 | https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/twip/scripts/cat_tweets.py#L184-L191 | train | Drop columns that are mostly NaNs |
jedie/PyHardLinkBackup | PyHardLinkBackup/phlb/phlb_main.py | FileBackup.fast_deduplication_backup | def fast_deduplication_backup(self, old_backup_entry, process_bar):
"""
We can just link a old backup entry
:param latest_backup: old BackupEntry model instance
:param process_bar: tqdm process bar
"""
# TODO: merge code with parts from deduplication_backup()
src... | python | def fast_deduplication_backup(self, old_backup_entry, process_bar):
"""
We can just link a old backup entry
:param latest_backup: old BackupEntry model instance
:param process_bar: tqdm process bar
"""
# TODO: merge code with parts from deduplication_backup()
src... | [
"def",
"fast_deduplication_backup",
"(",
"self",
",",
"old_backup_entry",
",",
"process_bar",
")",
":",
"# TODO: merge code with parts from deduplication_backup()",
"src_path",
"=",
"self",
".",
"dir_path",
".",
"resolved_path",
"log",
".",
"debug",
"(",
"\"*** fast dedup... | We can just link a old backup entry
:param latest_backup: old BackupEntry model instance
:param process_bar: tqdm process bar | [
"We",
"can",
"just",
"link",
"a",
"old",
"backup",
"entry"
] | be28666834d2d9e3d8aac1b661cb2d5bd4056c29 | https://github.com/jedie/PyHardLinkBackup/blob/be28666834d2d9e3d8aac1b661cb2d5bd4056c29/PyHardLinkBackup/phlb/phlb_main.py#L100-L154 | train | This method will link a backup entry to the new one and then deduplication the new one. |
jedie/PyHardLinkBackup | PyHardLinkBackup/phlb/phlb_main.py | FileBackup.deduplication_backup | def deduplication_backup(self, process_bar):
"""
Backup the current file and compare the content.
:param process_bar: tqdm process bar
"""
self.fast_backup = False # Was a fast backup used?
src_path = self.dir_path.resolved_path
log.debug("*** deduplication bac... | python | def deduplication_backup(self, process_bar):
"""
Backup the current file and compare the content.
:param process_bar: tqdm process bar
"""
self.fast_backup = False # Was a fast backup used?
src_path = self.dir_path.resolved_path
log.debug("*** deduplication bac... | [
"def",
"deduplication_backup",
"(",
"self",
",",
"process_bar",
")",
":",
"self",
".",
"fast_backup",
"=",
"False",
"# Was a fast backup used?",
"src_path",
"=",
"self",
".",
"dir_path",
".",
"resolved_path",
"log",
".",
"debug",
"(",
"\"*** deduplication backup: '%... | Backup the current file and compare the content.
:param process_bar: tqdm process bar | [
"Backup",
"the",
"current",
"file",
"and",
"compare",
"the",
"content",
"."
] | be28666834d2d9e3d8aac1b661cb2d5bd4056c29 | https://github.com/jedie/PyHardLinkBackup/blob/be28666834d2d9e3d8aac1b661cb2d5bd4056c29/PyHardLinkBackup/phlb/phlb_main.py#L156-L225 | train | Backup the current file and compare the content. |
jedie/PyHardLinkBackup | PyHardLinkBackup/phlb/phlb_main.py | HardLinkBackup.fast_compare | def fast_compare(self, dir_path):
"""
:param dir_path: filesystem_walk.DirEntryPath() instance
"""
if self.latest_backup is None:
# No old backup run was found
return
if self.latest_mtime_ns is None:
# No timestamp from old backup run was foun... | python | def fast_compare(self, dir_path):
"""
:param dir_path: filesystem_walk.DirEntryPath() instance
"""
if self.latest_backup is None:
# No old backup run was found
return
if self.latest_mtime_ns is None:
# No timestamp from old backup run was foun... | [
"def",
"fast_compare",
"(",
"self",
",",
"dir_path",
")",
":",
"if",
"self",
".",
"latest_backup",
"is",
"None",
":",
"# No old backup run was found",
"return",
"if",
"self",
".",
"latest_mtime_ns",
"is",
"None",
":",
"# No timestamp from old backup run was found",
... | :param dir_path: filesystem_walk.DirEntryPath() instance | [
":",
"param",
"dir_path",
":",
"filesystem_walk",
".",
"DirEntryPath",
"()",
"instance"
] | be28666834d2d9e3d8aac1b661cb2d5bd4056c29 | https://github.com/jedie/PyHardLinkBackup/blob/be28666834d2d9e3d8aac1b661cb2d5bd4056c29/PyHardLinkBackup/phlb/phlb_main.py#L390-L454 | train | This method is used to compare the contents of the directory to the latest backup run. |
jedie/PyHardLinkBackup | PyHardLinkBackup/phlb/phlb_main.py | HardLinkBackup._backup_dir_item | def _backup_dir_item(self, dir_path, process_bar):
"""
Backup one dir item
:param dir_path: filesystem_walk.DirEntryPath() instance
"""
self.path_helper.set_src_filepath(dir_path)
if self.path_helper.abs_src_filepath is None:
self.total_errored_items += 1
... | python | def _backup_dir_item(self, dir_path, process_bar):
"""
Backup one dir item
:param dir_path: filesystem_walk.DirEntryPath() instance
"""
self.path_helper.set_src_filepath(dir_path)
if self.path_helper.abs_src_filepath is None:
self.total_errored_items += 1
... | [
"def",
"_backup_dir_item",
"(",
"self",
",",
"dir_path",
",",
"process_bar",
")",
":",
"self",
".",
"path_helper",
".",
"set_src_filepath",
"(",
"dir_path",
")",
"if",
"self",
".",
"path_helper",
".",
"abs_src_filepath",
"is",
"None",
":",
"self",
".",
"tota... | Backup one dir item
:param dir_path: filesystem_walk.DirEntryPath() instance | [
"Backup",
"one",
"dir",
"item"
] | be28666834d2d9e3d8aac1b661cb2d5bd4056c29 | https://github.com/jedie/PyHardLinkBackup/blob/be28666834d2d9e3d8aac1b661cb2d5bd4056c29/PyHardLinkBackup/phlb/phlb_main.py#L456-L511 | train | This function is called by the backup_dir_item method. It will backup one directory item and return the corresponding instance of the class. |
jedie/PyHardLinkBackup | PyHardLinkBackup/phlb/phlb_main.py | HardLinkBackup.print_update | def print_update(self):
"""
print some status information in between.
"""
print("\r\n")
now = datetime.datetime.now()
print("Update info: (from: %s)" % now.strftime("%c"))
current_total_size = self.total_stined_bytes + self.total_new_bytes
if self.total_... | python | def print_update(self):
"""
print some status information in between.
"""
print("\r\n")
now = datetime.datetime.now()
print("Update info: (from: %s)" % now.strftime("%c"))
current_total_size = self.total_stined_bytes + self.total_new_bytes
if self.total_... | [
"def",
"print_update",
"(",
"self",
")",
":",
"print",
"(",
"\"\\r\\n\"",
")",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"print",
"(",
"\"Update info: (from: %s)\"",
"%",
"now",
".",
"strftime",
"(",
"\"%c\"",
")",
")",
"current_total_... | print some status information in between. | [
"print",
"some",
"status",
"information",
"in",
"between",
"."
] | be28666834d2d9e3d8aac1b661cb2d5bd4056c29 | https://github.com/jedie/PyHardLinkBackup/blob/be28666834d2d9e3d8aac1b661cb2d5bd4056c29/PyHardLinkBackup/phlb/phlb_main.py#L551-L586 | train | print some status information in between. |
aiidateam/aiida-codtools | aiida_codtools/cli/calculations/cod_tools.py | cli | def cli(code, cif, parameters, daemon):
"""Run any cod-tools calculation for the given ``CifData`` node.
The ``-p/--parameters`` option takes a single string with any command line parameters that you want to be passed
to the calculation, and by extension the cod-tools script. Example::
launch_calc... | python | def cli(code, cif, parameters, daemon):
"""Run any cod-tools calculation for the given ``CifData`` node.
The ``-p/--parameters`` option takes a single string with any command line parameters that you want to be passed
to the calculation, and by extension the cod-tools script. Example::
launch_calc... | [
"def",
"cli",
"(",
"code",
",",
"cif",
",",
"parameters",
",",
"daemon",
")",
":",
"from",
"aiida",
"import",
"orm",
"from",
"aiida",
".",
"plugins",
"import",
"factories",
"from",
"aiida_codtools",
".",
"common",
".",
"cli",
"import",
"CliParameters",
","... | Run any cod-tools calculation for the given ``CifData`` node.
The ``-p/--parameters`` option takes a single string with any command line parameters that you want to be passed
to the calculation, and by extension the cod-tools script. Example::
launch_calculation_cod_tools -X cif-filter -N 95 -p '--use... | [
"Run",
"any",
"cod",
"-",
"tools",
"calculation",
"for",
"the",
"given",
"CifData",
"node",
"."
] | da5e4259b7a2e86cf0cc3f997e11dd36d445fa94 | https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/cli/calculations/cod_tools.py#L22-L50 | train | Runs any cod - tools calculation for the given CifData node. |
jiasir/playback | playback/keystone.py | Keystone._update_keystone_paste_ini | def _update_keystone_paste_ini(self):
"""remove admin_token_auth from the [pipeline:public_api],
[pipeline:admin_api], and [pipeline:api_v3] sections"""
with open('tmp_keystone_paste_ini_' + env.host_string, 'w') as f:
f.write(conf_keystone_paste_ini)
files.upload_templa... | python | def _update_keystone_paste_ini(self):
"""remove admin_token_auth from the [pipeline:public_api],
[pipeline:admin_api], and [pipeline:api_v3] sections"""
with open('tmp_keystone_paste_ini_' + env.host_string, 'w') as f:
f.write(conf_keystone_paste_ini)
files.upload_templa... | [
"def",
"_update_keystone_paste_ini",
"(",
"self",
")",
":",
"with",
"open",
"(",
"'tmp_keystone_paste_ini_'",
"+",
"env",
".",
"host_string",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"conf_keystone_paste_ini",
")",
"files",
".",
"upload_templat... | remove admin_token_auth from the [pipeline:public_api],
[pipeline:admin_api], and [pipeline:api_v3] sections | [
"remove",
"admin_token_auth",
"from",
"the",
"[",
"pipeline",
":",
"public_api",
"]",
"[",
"pipeline",
":",
"admin_api",
"]",
"and",
"[",
"pipeline",
":",
"api_v3",
"]",
"sections"
] | 58b2a5d669dcfaa8cad50c544a4b068dcacf9b69 | https://github.com/jiasir/playback/blob/58b2a5d669dcfaa8cad50c544a4b068dcacf9b69/playback/keystone.py#L272-L281 | train | Update the keystone - paste. ini file |
totalgood/twip | twip/plot.py | compose_suffix | def compose_suffix(num_docs=0, num_topics=0, suffix=None):
"""Create a short, informative, but not-so-unique identifying string for a trained model
If a str suffix is provided then just pass it through.
>>> compose_suffix(num_docs=100, num_topics=20)
'_100X20'
>>> compose_suffix(suffix='_sfx')
'... | python | def compose_suffix(num_docs=0, num_topics=0, suffix=None):
"""Create a short, informative, but not-so-unique identifying string for a trained model
If a str suffix is provided then just pass it through.
>>> compose_suffix(num_docs=100, num_topics=20)
'_100X20'
>>> compose_suffix(suffix='_sfx')
'... | [
"def",
"compose_suffix",
"(",
"num_docs",
"=",
"0",
",",
"num_topics",
"=",
"0",
",",
"suffix",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"suffix",
",",
"basestring",
")",
":",
"suffix",
"=",
"'_{}X{}'",
".",
"format",
"(",
"num_docs",
","... | Create a short, informative, but not-so-unique identifying string for a trained model
If a str suffix is provided then just pass it through.
>>> compose_suffix(num_docs=100, num_topics=20)
'_100X20'
>>> compose_suffix(suffix='_sfx')
'_sfx'
>>> compose_suffix(suffix='')
''
>>> compose_suf... | [
"Create",
"a",
"short",
"informative",
"but",
"not",
"-",
"so",
"-",
"unique",
"identifying",
"string",
"for",
"a",
"trained",
"model",
"If",
"a",
"str",
"suffix",
"is",
"provided",
"then",
"just",
"pass",
"it",
"through",
".",
">>>",
"compose_suffix",
"("... | 5c0411d2acfbe5b421841072814c9152591c03f7 | https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/twip/plot.py#L57-L71 | train | Create a short informative but not - so - unique identifying string for a trained model. |
totalgood/twip | twip/plot.py | summarize_topics | def summarize_topics(f='lsi_topics.json', num_topics=1000, num_tokens=10, column_width=10, do_print=True, justify=True, data_path=DATA_PATH):
"""Load json file containing topic key/value pairs and print the top m words for the top n features"""
if isinstance(f, basestring):
if os.path.sep not in f:
... | python | def summarize_topics(f='lsi_topics.json', num_topics=1000, num_tokens=10, column_width=10, do_print=True, justify=True, data_path=DATA_PATH):
"""Load json file containing topic key/value pairs and print the top m words for the top n features"""
if isinstance(f, basestring):
if os.path.sep not in f:
... | [
"def",
"summarize_topics",
"(",
"f",
"=",
"'lsi_topics.json'",
",",
"num_topics",
"=",
"1000",
",",
"num_tokens",
"=",
"10",
",",
"column_width",
"=",
"10",
",",
"do_print",
"=",
"True",
",",
"justify",
"=",
"True",
",",
"data_path",
"=",
"DATA_PATH",
")",... | Load json file containing topic key/value pairs and print the top m words for the top n features | [
"Load",
"json",
"file",
"containing",
"topic",
"key",
"/",
"value",
"pairs",
"and",
"print",
"the",
"top",
"m",
"words",
"for",
"the",
"top",
"n",
"features"
] | 5c0411d2acfbe5b421841072814c9152591c03f7 | https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/twip/plot.py#L102-L127 | train | Load a json file containing topic key value pairs and print the top m words for the top n features |
totalgood/twip | twip/plot.py | df_from_groups | def df_from_groups(groups, columns=None):
"""Create DataFrame of GroupBy object with columns for each product(grouped_value, column_label)"""
if columns is None:
columns = list(groups.get_group(groups.indices.keys()[0]).columns)
df = pd.DataFrame()
for col, group_label in product(columns, groups... | python | def df_from_groups(groups, columns=None):
"""Create DataFrame of GroupBy object with columns for each product(grouped_value, column_label)"""
if columns is None:
columns = list(groups.get_group(groups.indices.keys()[0]).columns)
df = pd.DataFrame()
for col, group_label in product(columns, groups... | [
"def",
"df_from_groups",
"(",
"groups",
",",
"columns",
"=",
"None",
")",
":",
"if",
"columns",
"is",
"None",
":",
"columns",
"=",
"list",
"(",
"groups",
".",
"get_group",
"(",
"groups",
".",
"indices",
".",
"keys",
"(",
")",
"[",
"0",
"]",
")",
".... | Create DataFrame of GroupBy object with columns for each product(grouped_value, column_label) | [
"Create",
"DataFrame",
"of",
"GroupBy",
"object",
"with",
"columns",
"for",
"each",
"product",
"(",
"grouped_value",
"column_label",
")"
] | 5c0411d2acfbe5b421841072814c9152591c03f7 | https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/twip/plot.py#L130-L138 | train | Create DataFrame of GroupBy object with columns for each product |
totalgood/twip | twip/plot.py | score_hist | def score_hist(df, columns=None, groupby=None, threshold=0.7, stacked=True,
bins=20, percent=True, alpha=0.33, show=True, block=False, save=False):
"""Plot multiple histograms on one plot, typically of "score" values between 0 and 1
Typically the groupby or columns of the dataframe are the classi... | python | def score_hist(df, columns=None, groupby=None, threshold=0.7, stacked=True,
bins=20, percent=True, alpha=0.33, show=True, block=False, save=False):
"""Plot multiple histograms on one plot, typically of "score" values between 0 and 1
Typically the groupby or columns of the dataframe are the classi... | [
"def",
"score_hist",
"(",
"df",
",",
"columns",
"=",
"None",
",",
"groupby",
"=",
"None",
",",
"threshold",
"=",
"0.7",
",",
"stacked",
"=",
"True",
",",
"bins",
"=",
"20",
",",
"percent",
"=",
"True",
",",
"alpha",
"=",
"0.33",
",",
"show",
"=",
... | Plot multiple histograms on one plot, typically of "score" values between 0 and 1
Typically the groupby or columns of the dataframe are the classification categories (0, .5, 1)
And the values are scores between 0 and 1. | [
"Plot",
"multiple",
"histograms",
"on",
"one",
"plot",
"typically",
"of",
"score",
"values",
"between",
"0",
"and",
"1",
"Typically",
"the",
"groupby",
"or",
"columns",
"of",
"the",
"dataframe",
"are",
"the",
"classification",
"categories",
"(",
"0",
".",
"5... | 5c0411d2acfbe5b421841072814c9152591c03f7 | https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/twip/plot.py#L153-L191 | train | Plot multiple histograms on one plot typically of score values between 0 and 1 |
jiasir/playback | playback/cli/environment.py | cmd | def cmd(user, hosts, key_filename, password, run):
"""DEPRECATED"""
try:
remote = Cmd(user, hosts, key_filename, password)
except AttributeError:
sys.stderr.write('No hosts found. Please using --hosts param.')
sys.exit(1)
remote.cmd(run) | python | def cmd(user, hosts, key_filename, password, run):
"""DEPRECATED"""
try:
remote = Cmd(user, hosts, key_filename, password)
except AttributeError:
sys.stderr.write('No hosts found. Please using --hosts param.')
sys.exit(1)
remote.cmd(run) | [
"def",
"cmd",
"(",
"user",
",",
"hosts",
",",
"key_filename",
",",
"password",
",",
"run",
")",
":",
"try",
":",
"remote",
"=",
"Cmd",
"(",
"user",
",",
"hosts",
",",
"key_filename",
",",
"password",
")",
"except",
"AttributeError",
":",
"sys",
".",
... | DEPRECATED | [
"DEPRECATED"
] | 58b2a5d669dcfaa8cad50c544a4b068dcacf9b69 | https://github.com/jiasir/playback/blob/58b2a5d669dcfaa8cad50c544a4b068dcacf9b69/playback/cli/environment.py#L29-L36 | train | Command for the neccesary version of the command line. |
jiasir/playback | playback/cli/environment.py | make | def make(parser):
"""DEPRECATED
prepare OpenStack basic environment"""
s = parser.add_subparsers(
title='commands',
metavar='COMMAND',
help='description',
)
def gen_pass_f(args):
gen_pass()
gen_pass_parser = s.add_parser('gen-pass', help='generate the passwor... | python | def make(parser):
"""DEPRECATED
prepare OpenStack basic environment"""
s = parser.add_subparsers(
title='commands',
metavar='COMMAND',
help='description',
)
def gen_pass_f(args):
gen_pass()
gen_pass_parser = s.add_parser('gen-pass', help='generate the passwor... | [
"def",
"make",
"(",
"parser",
")",
":",
"s",
"=",
"parser",
".",
"add_subparsers",
"(",
"title",
"=",
"'commands'",
",",
"metavar",
"=",
"'COMMAND'",
",",
"help",
"=",
"'description'",
",",
")",
"def",
"gen_pass_f",
"(",
"args",
")",
":",
"gen_pass",
"... | DEPRECATED
prepare OpenStack basic environment | [
"DEPRECATED",
"prepare",
"OpenStack",
"basic",
"environment"
] | 58b2a5d669dcfaa8cad50c544a4b068dcacf9b69 | https://github.com/jiasir/playback/blob/58b2a5d669dcfaa8cad50c544a4b068dcacf9b69/playback/cli/environment.py#L39-L57 | train | DEPRECATED - prepare OpenStack basic environment |
Capitains/MyCapytain | MyCapytain/resolvers/prototypes.py | Resolver.getTextualNode | def getTextualNode(
self,
textId: str,
subreference: Union[str, BaseReference]=None,
prevnext: bool=False,
metadata: bool=False
) -> TextualNode:
""" Retrieve a text node from the API
:param textId: CtsTextMetadata Identifier
:type... | python | def getTextualNode(
self,
textId: str,
subreference: Union[str, BaseReference]=None,
prevnext: bool=False,
metadata: bool=False
) -> TextualNode:
""" Retrieve a text node from the API
:param textId: CtsTextMetadata Identifier
:type... | [
"def",
"getTextualNode",
"(",
"self",
",",
"textId",
":",
"str",
",",
"subreference",
":",
"Union",
"[",
"str",
",",
"BaseReference",
"]",
"=",
"None",
",",
"prevnext",
":",
"bool",
"=",
"False",
",",
"metadata",
":",
"bool",
"=",
"False",
")",
"->",
... | Retrieve a text node from the API
:param textId: CtsTextMetadata Identifier
:type textId: str
:param subreference: CapitainsCtsPassage Reference
:type subreference: str
:param prevnext: Retrieve graph representing previous and next passage
:type prevnext: boolean
... | [
"Retrieve",
"a",
"text",
"node",
"from",
"the",
"API"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resolvers/prototypes.py#L38-L58 | train | Retrieve a text node from the API. |
Capitains/MyCapytain | MyCapytain/resolvers/prototypes.py | Resolver.getSiblings | def getSiblings(self, textId: str, subreference: Union[str, BaseReference]) -> Tuple[BaseReference, BaseReference]:
""" Retrieve the siblings of a textual node
:param textId: CtsTextMetadata Identifier
:type textId: str
:param subreference: CapitainsCtsPassage Reference
:type su... | python | def getSiblings(self, textId: str, subreference: Union[str, BaseReference]) -> Tuple[BaseReference, BaseReference]:
""" Retrieve the siblings of a textual node
:param textId: CtsTextMetadata Identifier
:type textId: str
:param subreference: CapitainsCtsPassage Reference
:type su... | [
"def",
"getSiblings",
"(",
"self",
",",
"textId",
":",
"str",
",",
"subreference",
":",
"Union",
"[",
"str",
",",
"BaseReference",
"]",
")",
"->",
"Tuple",
"[",
"BaseReference",
",",
"BaseReference",
"]",
":",
"raise",
"NotImplementedError",
"(",
")"
] | Retrieve the siblings of a textual node
:param textId: CtsTextMetadata Identifier
:type textId: str
:param subreference: CapitainsCtsPassage Reference
:type subreference: str
:return: Tuple of references
:rtype: (str, str) | [
"Retrieve",
"the",
"siblings",
"of",
"a",
"textual",
"node"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resolvers/prototypes.py#L60-L70 | train | Retrieve the siblings of a textual node. |
Capitains/MyCapytain | MyCapytain/resolvers/prototypes.py | Resolver.getReffs | def getReffs(
self,
textId: str,
level: int=1,
subreference: Union[str, BaseReference]=None,
include_descendants: bool=False,
additional_parameters: Optional[Dict[str, Any]]=None
) -> BaseReferenceSet:
""" Retrieve the siblings of a tex... | python | def getReffs(
self,
textId: str,
level: int=1,
subreference: Union[str, BaseReference]=None,
include_descendants: bool=False,
additional_parameters: Optional[Dict[str, Any]]=None
) -> BaseReferenceSet:
""" Retrieve the siblings of a tex... | [
"def",
"getReffs",
"(",
"self",
",",
"textId",
":",
"str",
",",
"level",
":",
"int",
"=",
"1",
",",
"subreference",
":",
"Union",
"[",
"str",
",",
"BaseReference",
"]",
"=",
"None",
",",
"include_descendants",
":",
"bool",
"=",
"False",
",",
"additiona... | Retrieve the siblings of a textual node
:param textId: CtsTextMetadata Identifier
:type textId: str
:param level: Depth for retrieval
:type level: int
:param subreference: CapitainsCtsPassage Reference
:type subreference: str
:param include_descendants:
:... | [
"Retrieve",
"the",
"siblings",
"of",
"a",
"textual",
"node"
] | b11bbf6b6ae141fc02be70471e3fbf6907be6593 | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resolvers/prototypes.py#L72-L95 | train | Retrieve siblings of a textual node. |
aloetesting/aloe_webdriver | aloe_webdriver/django.py | visit_page | def visit_page(self, page):
"""
Visit the specific page of the site, e.g.
.. code-block:: gherkin
When I visit site page "/users"
"""
url = urljoin(django_url(self), page)
self.given('I visit "%s"' % url) | python | def visit_page(self, page):
"""
Visit the specific page of the site, e.g.
.. code-block:: gherkin
When I visit site page "/users"
"""
url = urljoin(django_url(self), page)
self.given('I visit "%s"' % url) | [
"def",
"visit_page",
"(",
"self",
",",
"page",
")",
":",
"url",
"=",
"urljoin",
"(",
"django_url",
"(",
"self",
")",
",",
"page",
")",
"self",
".",
"given",
"(",
"'I visit \"%s\"'",
"%",
"url",
")"
] | Visit the specific page of the site, e.g.
.. code-block:: gherkin
When I visit site page "/users" | [
"Visit",
"the",
"specific",
"page",
"of",
"the",
"site",
"e",
".",
"g",
"."
] | 65d847da4bdc63f9c015cb19d4efdee87df8ffad | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/django.py#L28-L38 | train | Visit the specific page of the site |
klen/muffin-admin | muffin_admin/peewee.py | pw_converter | def pw_converter(handler, flt):
"""Convert column name to filter."""
import peewee as pw
if isinstance(flt, Filter):
return flt
model = handler.model
field = getattr(model, flt)
if isinstance(field, pw.BooleanField):
return PWBoolFilter(flt)
if field.choices:
choi... | python | def pw_converter(handler, flt):
"""Convert column name to filter."""
import peewee as pw
if isinstance(flt, Filter):
return flt
model = handler.model
field = getattr(model, flt)
if isinstance(field, pw.BooleanField):
return PWBoolFilter(flt)
if field.choices:
choi... | [
"def",
"pw_converter",
"(",
"handler",
",",
"flt",
")",
":",
"import",
"peewee",
"as",
"pw",
"if",
"isinstance",
"(",
"flt",
",",
"Filter",
")",
":",
"return",
"flt",
"model",
"=",
"handler",
".",
"model",
"field",
"=",
"getattr",
"(",
"model",
",",
... | Convert column name to filter. | [
"Convert",
"column",
"name",
"to",
"filter",
"."
] | 404dc8e5107e943b7c42fa21c679c34ddb4de1d5 | https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/peewee.py#L24-L41 | train | Convert column name to filter. |
klen/muffin-admin | muffin_admin/peewee.py | RawIDField.process | def process(self, *args, **kwargs):
"""Get a description."""
super(RawIDField, self).process(*args, **kwargs)
if self.object_data:
self.description = self.description or str(self.object_data) | python | def process(self, *args, **kwargs):
"""Get a description."""
super(RawIDField, self).process(*args, **kwargs)
if self.object_data:
self.description = self.description or str(self.object_data) | [
"def",
"process",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"RawIDField",
",",
"self",
")",
".",
"process",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"self",
".",
"object_data",
":",
"self",
".",
... | Get a description. | [
"Get",
"a",
"description",
"."
] | 404dc8e5107e943b7c42fa21c679c34ddb4de1d5 | https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/peewee.py#L53-L57 | train | Get a description. |
klen/muffin-admin | muffin_admin/peewee.py | RawIDField._value | def _value(self):
"""Get field value."""
if self.data is not None:
value = self.data._data.get(self.field.to_field.name)
return str(value)
return '' | python | def _value(self):
"""Get field value."""
if self.data is not None:
value = self.data._data.get(self.field.to_field.name)
return str(value)
return '' | [
"def",
"_value",
"(",
"self",
")",
":",
"if",
"self",
".",
"data",
"is",
"not",
"None",
":",
"value",
"=",
"self",
".",
"data",
".",
"_data",
".",
"get",
"(",
"self",
".",
"field",
".",
"to_field",
".",
"name",
")",
"return",
"str",
"(",
"value",... | Get field value. | [
"Get",
"field",
"value",
"."
] | 404dc8e5107e943b7c42fa21c679c34ddb4de1d5 | https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/peewee.py#L59-L64 | train | Get field value. |
klen/muffin-admin | muffin_admin/peewee.py | PWAdminHandler.load_one | def load_one(self, request):
"""Load a resource."""
resource = request.query.get('pk')
if not resource:
return None
try:
return self.collection.where(self.model._meta.primary_key == resource).get()
except Exception:
raise muffin.HTTPNotFound() | python | def load_one(self, request):
"""Load a resource."""
resource = request.query.get('pk')
if not resource:
return None
try:
return self.collection.where(self.model._meta.primary_key == resource).get()
except Exception:
raise muffin.HTTPNotFound() | [
"def",
"load_one",
"(",
"self",
",",
"request",
")",
":",
"resource",
"=",
"request",
".",
"query",
".",
"get",
"(",
"'pk'",
")",
"if",
"not",
"resource",
":",
"return",
"None",
"try",
":",
"return",
"self",
".",
"collection",
".",
"where",
"(",
"sel... | Load a resource. | [
"Load",
"a",
"resource",
"."
] | 404dc8e5107e943b7c42fa21c679c34ddb4de1d5 | https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/peewee.py#L146-L155 | train | Load a resource from the database. |
klen/muffin-admin | muffin_admin/peewee.py | PWAdminHandler.sort | def sort(self, request, reverse=False):
"""Sort current collection."""
field = self.model._meta.fields.get(self.columns_sort)
if not field:
return self.collection
if reverse:
field = field.desc()
return self.collection.order_by(field) | python | def sort(self, request, reverse=False):
"""Sort current collection."""
field = self.model._meta.fields.get(self.columns_sort)
if not field:
return self.collection
if reverse:
field = field.desc()
return self.collection.order_by(field) | [
"def",
"sort",
"(",
"self",
",",
"request",
",",
"reverse",
"=",
"False",
")",
":",
"field",
"=",
"self",
".",
"model",
".",
"_meta",
".",
"fields",
".",
"get",
"(",
"self",
".",
"columns_sort",
")",
"if",
"not",
"field",
":",
"return",
"self",
"."... | Sort current collection. | [
"Sort",
"current",
"collection",
"."
] | 404dc8e5107e943b7c42fa21c679c34ddb4de1d5 | https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/peewee.py#L157-L166 | train | Sort current collection. |
klen/muffin-admin | muffin_admin/peewee.py | PWAdminHandler.paginate | def paginate(self, request):
"""Paginate collection."""
return self.collection.offset(self.offset).limit(self.limit) | python | def paginate(self, request):
"""Paginate collection."""
return self.collection.offset(self.offset).limit(self.limit) | [
"def",
"paginate",
"(",
"self",
",",
"request",
")",
":",
"return",
"self",
".",
"collection",
".",
"offset",
"(",
"self",
".",
"offset",
")",
".",
"limit",
"(",
"self",
".",
"limit",
")"
] | Paginate collection. | [
"Paginate",
"collection",
"."
] | 404dc8e5107e943b7c42fa21c679c34ddb4de1d5 | https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/peewee.py#L168-L170 | train | Paginate collection. |
klen/muffin-admin | muffin_admin/peewee.py | PWAdminHandler.save_form | def save_form(self, form, request, **resources):
"""Save self form."""
resource = yield from super(PWAdminHandler, self).save_form(form, request, **resources)
resource.save()
return resource | python | def save_form(self, form, request, **resources):
"""Save self form."""
resource = yield from super(PWAdminHandler, self).save_form(form, request, **resources)
resource.save()
return resource | [
"def",
"save_form",
"(",
"self",
",",
"form",
",",
"request",
",",
"*",
"*",
"resources",
")",
":",
"resource",
"=",
"yield",
"from",
"super",
"(",
"PWAdminHandler",
",",
"self",
")",
".",
"save_form",
"(",
"form",
",",
"request",
",",
"*",
"*",
"res... | Save self form. | [
"Save",
"self",
"form",
"."
] | 404dc8e5107e943b7c42fa21c679c34ddb4de1d5 | https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/peewee.py#L180-L184 | train | Save self form. |
klen/muffin-admin | muffin_admin/peewee.py | PWAdminHandler.delete | def delete(self, request):
"""Delete an item."""
if not self.can_delete:
raise muffin.HTTPMethodNotAllowed()
if not self.resource:
raise muffin.HTTPNotFound(reason='Resource not found')
self.resource.delete_instance() | python | def delete(self, request):
"""Delete an item."""
if not self.can_delete:
raise muffin.HTTPMethodNotAllowed()
if not self.resource:
raise muffin.HTTPNotFound(reason='Resource not found')
self.resource.delete_instance() | [
"def",
"delete",
"(",
"self",
",",
"request",
")",
":",
"if",
"not",
"self",
".",
"can_delete",
":",
"raise",
"muffin",
".",
"HTTPMethodNotAllowed",
"(",
")",
"if",
"not",
"self",
".",
"resource",
":",
"raise",
"muffin",
".",
"HTTPNotFound",
"(",
"reason... | Delete an item. | [
"Delete",
"an",
"item",
"."
] | 404dc8e5107e943b7c42fa21c679c34ddb4de1d5 | https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/peewee.py#L186-L194 | train | Delete an item. |
klen/muffin-admin | muffin_admin/peewee.py | PWFilter.apply | def apply(self, query, data):
"""Filter a query."""
field = self.model_field or query.model_class._meta.fields.get(self.name)
if not field or self.name not in data:
return query
value = self.value(data)
if value is self.default:
return query
value ... | python | def apply(self, query, data):
"""Filter a query."""
field = self.model_field or query.model_class._meta.fields.get(self.name)
if not field or self.name not in data:
return query
value = self.value(data)
if value is self.default:
return query
value ... | [
"def",
"apply",
"(",
"self",
",",
"query",
",",
"data",
")",
":",
"field",
"=",
"self",
".",
"model_field",
"or",
"query",
".",
"model_class",
".",
"_meta",
".",
"fields",
".",
"get",
"(",
"self",
".",
"name",
")",
"if",
"not",
"field",
"or",
"self... | Filter a query. | [
"Filter",
"a",
"query",
"."
] | 404dc8e5107e943b7c42fa21c679c34ddb4de1d5 | https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/peewee.py#L212-L221 | train | Filter a query based on the current value of the attribute. |
klen/muffin-admin | muffin_admin/peewee.py | PWLikeFilter.filter_query | def filter_query(self, query, field, value):
"""Filter a query."""
return query.where(field ** "%{}%".format(value.lower())) | python | def filter_query(self, query, field, value):
"""Filter a query."""
return query.where(field ** "%{}%".format(value.lower())) | [
"def",
"filter_query",
"(",
"self",
",",
"query",
",",
"field",
",",
"value",
")",
":",
"return",
"query",
".",
"where",
"(",
"field",
"**",
"\"%{}%\"",
".",
"format",
"(",
"value",
".",
"lower",
"(",
")",
")",
")"
] | Filter a query. | [
"Filter",
"a",
"query",
"."
] | 404dc8e5107e943b7c42fa21c679c34ddb4de1d5 | https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/peewee.py#L233-L235 | train | Filter a query. |
klen/muffin-admin | muffin_admin/peewee.py | PWBoolFilter.value | def value(self, data):
"""Get value from data."""
value = data.get(self.name)
if value:
return int(value)
return self.default | python | def value(self, data):
"""Get value from data."""
value = data.get(self.name)
if value:
return int(value)
return self.default | [
"def",
"value",
"(",
"self",
",",
"data",
")",
":",
"value",
"=",
"data",
".",
"get",
"(",
"self",
".",
"name",
")",
"if",
"value",
":",
"return",
"int",
"(",
"value",
")",
"return",
"self",
".",
"default"
] | Get value from data. | [
"Get",
"value",
"from",
"data",
"."
] | 404dc8e5107e943b7c42fa21c679c34ddb4de1d5 | https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/peewee.py#L251-L256 | train | Get value from data. |
uyar/pygenstub | pygenstub.py | get_fields | def get_fields(node, fields_tag="field_list"):
"""Get the field names and their values from a node.
:sig: (Document, str) -> Dict[str, str]
:param node: Node to get the fields from.
:param fields_tag: Tag of child node that contains the fields.
:return: Names and values of fields.
"""
field... | python | def get_fields(node, fields_tag="field_list"):
"""Get the field names and their values from a node.
:sig: (Document, str) -> Dict[str, str]
:param node: Node to get the fields from.
:param fields_tag: Tag of child node that contains the fields.
:return: Names and values of fields.
"""
field... | [
"def",
"get_fields",
"(",
"node",
",",
"fields_tag",
"=",
"\"field_list\"",
")",
":",
"fields_nodes",
"=",
"[",
"c",
"for",
"c",
"in",
"node",
".",
"children",
"if",
"c",
".",
"tagname",
"==",
"fields_tag",
"]",
"if",
"len",
"(",
"fields_nodes",
")",
"... | Get the field names and their values from a node.
:sig: (Document, str) -> Dict[str, str]
:param node: Node to get the fields from.
:param fields_tag: Tag of child node that contains the fields.
:return: Names and values of fields. | [
"Get",
"the",
"field",
"names",
"and",
"their",
"values",
"from",
"a",
"node",
"."
] | a6b18a823382d3c6be29c411fb33c58b6090d22c | https://github.com/uyar/pygenstub/blob/a6b18a823382d3c6be29c411fb33c58b6090d22c/pygenstub.py#L81-L99 | train | Get the field names and values from a node. |
uyar/pygenstub | pygenstub.py | extract_signature | def extract_signature(docstring):
"""Extract the signature from a docstring.
:sig: (str) -> Optional[str]
:param docstring: Docstring to extract the signature from.
:return: Extracted signature, or ``None`` if there's no signature.
"""
root = publish_doctree(docstring, settings_overrides={"repo... | python | def extract_signature(docstring):
"""Extract the signature from a docstring.
:sig: (str) -> Optional[str]
:param docstring: Docstring to extract the signature from.
:return: Extracted signature, or ``None`` if there's no signature.
"""
root = publish_doctree(docstring, settings_overrides={"repo... | [
"def",
"extract_signature",
"(",
"docstring",
")",
":",
"root",
"=",
"publish_doctree",
"(",
"docstring",
",",
"settings_overrides",
"=",
"{",
"\"report_level\"",
":",
"5",
"}",
")",
"fields",
"=",
"get_fields",
"(",
"root",
")",
"return",
"fields",
".",
"ge... | Extract the signature from a docstring.
:sig: (str) -> Optional[str]
:param docstring: Docstring to extract the signature from.
:return: Extracted signature, or ``None`` if there's no signature. | [
"Extract",
"the",
"signature",
"from",
"a",
"docstring",
"."
] | a6b18a823382d3c6be29c411fb33c58b6090d22c | https://github.com/uyar/pygenstub/blob/a6b18a823382d3c6be29c411fb33c58b6090d22c/pygenstub.py#L102-L111 | train | Extract the signature from a docstring. |
uyar/pygenstub | pygenstub.py | split_parameter_types | def split_parameter_types(parameters):
"""Split a parameter types declaration into individual types.
The input is the left hand side of a signature (the part before the arrow),
excluding the parentheses.
:sig: (str) -> List[str]
:param parameters: Comma separated parameter types.
:return: Para... | python | def split_parameter_types(parameters):
"""Split a parameter types declaration into individual types.
The input is the left hand side of a signature (the part before the arrow),
excluding the parentheses.
:sig: (str) -> List[str]
:param parameters: Comma separated parameter types.
:return: Para... | [
"def",
"split_parameter_types",
"(",
"parameters",
")",
":",
"if",
"parameters",
"==",
"\"\"",
":",
"return",
"[",
"]",
"# only consider the top level commas, ignore the ones in []",
"commas",
"=",
"[",
"]",
"bracket_depth",
"=",
"0",
"for",
"i",
",",
"char",
"in"... | Split a parameter types declaration into individual types.
The input is the left hand side of a signature (the part before the arrow),
excluding the parentheses.
:sig: (str) -> List[str]
:param parameters: Comma separated parameter types.
:return: Parameter types. | [
"Split",
"a",
"parameter",
"types",
"declaration",
"into",
"individual",
"types",
"."
] | a6b18a823382d3c6be29c411fb33c58b6090d22c | https://github.com/uyar/pygenstub/blob/a6b18a823382d3c6be29c411fb33c58b6090d22c/pygenstub.py#L127-L158 | train | Splits a parameter types declaration into individual types. |
uyar/pygenstub | pygenstub.py | parse_signature | def parse_signature(signature):
"""Parse a signature into its input and return parameter types.
This will also collect the types that are required by any of the input
and return types.
:sig: (str) -> Tuple[List[str], str, Set[str]]
:param signature: Signature to parse.
:return: Input parameter... | python | def parse_signature(signature):
"""Parse a signature into its input and return parameter types.
This will also collect the types that are required by any of the input
and return types.
:sig: (str) -> Tuple[List[str], str, Set[str]]
:param signature: Signature to parse.
:return: Input parameter... | [
"def",
"parse_signature",
"(",
"signature",
")",
":",
"if",
"\" -> \"",
"not",
"in",
"signature",
":",
"# signature comment: no parameters, treat variable type as return type",
"param_types",
",",
"return_type",
"=",
"None",
",",
"signature",
".",
"strip",
"(",
")",
"... | Parse a signature into its input and return parameter types.
This will also collect the types that are required by any of the input
and return types.
:sig: (str) -> Tuple[List[str], str, Set[str]]
:param signature: Signature to parse.
:return: Input parameter types, return type, and all required t... | [
"Parse",
"a",
"signature",
"into",
"its",
"input",
"and",
"return",
"parameter",
"types",
"."
] | a6b18a823382d3c6be29c411fb33c58b6090d22c | https://github.com/uyar/pygenstub/blob/a6b18a823382d3c6be29c411fb33c58b6090d22c/pygenstub.py#L161-L179 | train | Parse a signature into its input and return parameter types and all required types. |
uyar/pygenstub | pygenstub.py | get_aliases | def get_aliases(lines):
"""Get the type aliases in the source.
:sig: (Sequence[str]) -> Dict[str, str]
:param lines: Lines of the source code.
:return: Aliases and their their definitions.
"""
aliases = {}
for line in lines:
line = line.strip()
if len(line) > 0 and line.star... | python | def get_aliases(lines):
"""Get the type aliases in the source.
:sig: (Sequence[str]) -> Dict[str, str]
:param lines: Lines of the source code.
:return: Aliases and their their definitions.
"""
aliases = {}
for line in lines:
line = line.strip()
if len(line) > 0 and line.star... | [
"def",
"get_aliases",
"(",
"lines",
")",
":",
"aliases",
"=",
"{",
"}",
"for",
"line",
"in",
"lines",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"len",
"(",
"line",
")",
">",
"0",
"and",
"line",
".",
"startswith",
"(",
"SIG_ALIAS",
"... | Get the type aliases in the source.
:sig: (Sequence[str]) -> Dict[str, str]
:param lines: Lines of the source code.
:return: Aliases and their their definitions. | [
"Get",
"the",
"type",
"aliases",
"in",
"the",
"source",
"."
] | a6b18a823382d3c6be29c411fb33c58b6090d22c | https://github.com/uyar/pygenstub/blob/a6b18a823382d3c6be29c411fb33c58b6090d22c/pygenstub.py#L372-L386 | train | Get the type aliases in the source code. |
uyar/pygenstub | pygenstub.py | get_stub | def get_stub(source, generic=False):
"""Get the stub code for a source code.
:sig: (str, bool) -> str
:param source: Source code to generate the stub for.
:param generic: Whether to produce generic stubs.
:return: Generated stub code.
"""
generator = StubGenerator(source, generic=generic)
... | python | def get_stub(source, generic=False):
"""Get the stub code for a source code.
:sig: (str, bool) -> str
:param source: Source code to generate the stub for.
:param generic: Whether to produce generic stubs.
:return: Generated stub code.
"""
generator = StubGenerator(source, generic=generic)
... | [
"def",
"get_stub",
"(",
"source",
",",
"generic",
"=",
"False",
")",
":",
"generator",
"=",
"StubGenerator",
"(",
"source",
",",
"generic",
"=",
"generic",
")",
"stub",
"=",
"generator",
".",
"generate_stub",
"(",
")",
"return",
"stub"
] | Get the stub code for a source code.
:sig: (str, bool) -> str
:param source: Source code to generate the stub for.
:param generic: Whether to produce generic stubs.
:return: Generated stub code. | [
"Get",
"the",
"stub",
"code",
"for",
"a",
"source",
"code",
"."
] | a6b18a823382d3c6be29c411fb33c58b6090d22c | https://github.com/uyar/pygenstub/blob/a6b18a823382d3c6be29c411fb33c58b6090d22c/pygenstub.py#L745-L755 | train | Generate a stub code for a source code. |
uyar/pygenstub | pygenstub.py | get_mod_paths | def get_mod_paths(mod_name, out_dir):
"""Get source and stub paths for a module."""
paths = []
try:
mod = get_loader(mod_name)
source = Path(mod.path)
if source.name.endswith(".py"):
source_rel = Path(*mod_name.split("."))
if source.name == "__init__.py":
... | python | def get_mod_paths(mod_name, out_dir):
"""Get source and stub paths for a module."""
paths = []
try:
mod = get_loader(mod_name)
source = Path(mod.path)
if source.name.endswith(".py"):
source_rel = Path(*mod_name.split("."))
if source.name == "__init__.py":
... | [
"def",
"get_mod_paths",
"(",
"mod_name",
",",
"out_dir",
")",
":",
"paths",
"=",
"[",
"]",
"try",
":",
"mod",
"=",
"get_loader",
"(",
"mod_name",
")",
"source",
"=",
"Path",
"(",
"mod",
".",
"path",
")",
"if",
"source",
".",
"name",
".",
"endswith",
... | Get source and stub paths for a module. | [
"Get",
"source",
"and",
"stub",
"paths",
"for",
"a",
"module",
"."
] | a6b18a823382d3c6be29c411fb33c58b6090d22c | https://github.com/uyar/pygenstub/blob/a6b18a823382d3c6be29c411fb33c58b6090d22c/pygenstub.py#L758-L773 | train | Get source and stub paths for a module. |
uyar/pygenstub | pygenstub.py | get_pkg_paths | def get_pkg_paths(pkg_name, out_dir):
"""Recursively get all source and stub paths for a package."""
paths = []
try:
pkg = import_module(pkg_name)
if not hasattr(pkg, "__path__"):
return get_mod_paths(pkg_name, out_dir)
for mod_info in walk_packages(pkg.__path__, pkg.__na... | python | def get_pkg_paths(pkg_name, out_dir):
"""Recursively get all source and stub paths for a package."""
paths = []
try:
pkg = import_module(pkg_name)
if not hasattr(pkg, "__path__"):
return get_mod_paths(pkg_name, out_dir)
for mod_info in walk_packages(pkg.__path__, pkg.__na... | [
"def",
"get_pkg_paths",
"(",
"pkg_name",
",",
"out_dir",
")",
":",
"paths",
"=",
"[",
"]",
"try",
":",
"pkg",
"=",
"import_module",
"(",
"pkg_name",
")",
"if",
"not",
"hasattr",
"(",
"pkg",
",",
"\"__path__\"",
")",
":",
"return",
"get_mod_paths",
"(",
... | Recursively get all source and stub paths for a package. | [
"Recursively",
"get",
"all",
"source",
"and",
"stub",
"paths",
"for",
"a",
"package",
"."
] | a6b18a823382d3c6be29c411fb33c58b6090d22c | https://github.com/uyar/pygenstub/blob/a6b18a823382d3c6be29c411fb33c58b6090d22c/pygenstub.py#L776-L789 | train | Recursively get all source and stub paths for a package. |
uyar/pygenstub | pygenstub.py | process_docstring | def process_docstring(app, what, name, obj, options, lines):
"""Modify the docstring before generating documentation.
This will insert type declarations for parameters and return type
into the docstring, and remove the signature field so that it will
be excluded from the generated document.
"""
... | python | def process_docstring(app, what, name, obj, options, lines):
"""Modify the docstring before generating documentation.
This will insert type declarations for parameters and return type
into the docstring, and remove the signature field so that it will
be excluded from the generated document.
"""
... | [
"def",
"process_docstring",
"(",
"app",
",",
"what",
",",
"name",
",",
"obj",
",",
"options",
",",
"lines",
")",
":",
"aliases",
"=",
"getattr",
"(",
"app",
",",
"\"_sigaliases\"",
",",
"None",
")",
"if",
"aliases",
"is",
"None",
":",
"if",
"what",
"... | Modify the docstring before generating documentation.
This will insert type declarations for parameters and return type
into the docstring, and remove the signature field so that it will
be excluded from the generated document. | [
"Modify",
"the",
"docstring",
"before",
"generating",
"documentation",
"."
] | a6b18a823382d3c6be29c411fb33c58b6090d22c | https://github.com/uyar/pygenstub/blob/a6b18a823382d3c6be29c411fb33c58b6090d22c/pygenstub.py#L797-L874 | train | Modify the docstring before generating documentation. |
uyar/pygenstub | pygenstub.py | main | def main(argv=None):
"""Start the command line interface."""
parser = ArgumentParser(prog="pygenstub")
parser.add_argument("--version", action="version", version="%(prog)s " + __version__)
parser.add_argument("files", nargs="*", help="generate stubs for given files")
parser.add_argument(
"-m... | python | def main(argv=None):
"""Start the command line interface."""
parser = ArgumentParser(prog="pygenstub")
parser.add_argument("--version", action="version", version="%(prog)s " + __version__)
parser.add_argument("files", nargs="*", help="generate stubs for given files")
parser.add_argument(
"-m... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
"prog",
"=",
"\"pygenstub\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--version\"",
",",
"action",
"=",
"\"version\"",
",",
"version",
"=",
"\"%(prog)s \"",
"+",
"... | Start the command line interface. | [
"Start",
"the",
"command",
"line",
"interface",
"."
] | a6b18a823382d3c6be29c411fb33c58b6090d22c | https://github.com/uyar/pygenstub/blob/a6b18a823382d3c6be29c411fb33c58b6090d22c/pygenstub.py#L888-L951 | train | Main entry point for the pygenstub command line interface. |
uyar/pygenstub | pygenstub.py | StubNode.add_variable | def add_variable(self, node):
"""Add a variable node to this node.
:sig: (VariableNode) -> None
:param node: Variable node to add.
"""
if node.name not in self.variable_names:
self.variables.append(node)
self.variable_names.add(node.name)
node... | python | def add_variable(self, node):
"""Add a variable node to this node.
:sig: (VariableNode) -> None
:param node: Variable node to add.
"""
if node.name not in self.variable_names:
self.variables.append(node)
self.variable_names.add(node.name)
node... | [
"def",
"add_variable",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"name",
"not",
"in",
"self",
".",
"variable_names",
":",
"self",
".",
"variables",
".",
"append",
"(",
"node",
")",
"self",
".",
"variable_names",
".",
"add",
"(",
"node",
... | Add a variable node to this node.
:sig: (VariableNode) -> None
:param node: Variable node to add. | [
"Add",
"a",
"variable",
"node",
"to",
"this",
"node",
"."
] | a6b18a823382d3c6be29c411fb33c58b6090d22c | https://github.com/uyar/pygenstub/blob/a6b18a823382d3c6be29c411fb33c58b6090d22c/pygenstub.py#L195-L204 | train | Adds a variable node to this node. |
uyar/pygenstub | pygenstub.py | StubNode.get_code | def get_code(self):
"""Get the stub code for this node.
The stub code for a node consists of the type annotations of its variables,
followed by the prototypes of its functions/methods and classes.
:sig: () -> List[str]
:return: Lines of stub code for this node.
"""
... | python | def get_code(self):
"""Get the stub code for this node.
The stub code for a node consists of the type annotations of its variables,
followed by the prototypes of its functions/methods and classes.
:sig: () -> List[str]
:return: Lines of stub code for this node.
"""
... | [
"def",
"get_code",
"(",
"self",
")",
":",
"stub",
"=",
"[",
"]",
"for",
"child",
"in",
"self",
".",
"variables",
":",
"stub",
".",
"extend",
"(",
"child",
".",
"get_code",
"(",
")",
")",
"if",
"(",
"(",
"len",
"(",
"self",
".",
"variables",
")",
... | Get the stub code for this node.
The stub code for a node consists of the type annotations of its variables,
followed by the prototypes of its functions/methods and classes.
:sig: () -> List[str]
:return: Lines of stub code for this node. | [
"Get",
"the",
"stub",
"code",
"for",
"this",
"node",
"."
] | a6b18a823382d3c6be29c411fb33c58b6090d22c | https://github.com/uyar/pygenstub/blob/a6b18a823382d3c6be29c411fb33c58b6090d22c/pygenstub.py#L215-L235 | train | Get the stub code for this node. |
uyar/pygenstub | pygenstub.py | FunctionNode.get_code | def get_code(self):
"""Get the stub code for this function.
:sig: () -> List[str]
:return: Lines of stub code for this function.
"""
stub = []
for deco in self.decorators:
if (deco in DECORATORS) or deco.endswith(".setter"):
stub.append("@" +... | python | def get_code(self):
"""Get the stub code for this function.
:sig: () -> List[str]
:return: Lines of stub code for this function.
"""
stub = []
for deco in self.decorators:
if (deco in DECORATORS) or deco.endswith(".setter"):
stub.append("@" +... | [
"def",
"get_code",
"(",
"self",
")",
":",
"stub",
"=",
"[",
"]",
"for",
"deco",
"in",
"self",
".",
"decorators",
":",
"if",
"(",
"deco",
"in",
"DECORATORS",
")",
"or",
"deco",
".",
"endswith",
"(",
"\".setter\"",
")",
":",
"stub",
".",
"append",
"(... | Get the stub code for this function.
:sig: () -> List[str]
:return: Lines of stub code for this function. | [
"Get",
"the",
"stub",
"code",
"for",
"this",
"function",
"."
] | a6b18a823382d3c6be29c411fb33c58b6090d22c | https://github.com/uyar/pygenstub/blob/a6b18a823382d3c6be29c411fb33c58b6090d22c/pygenstub.py#L290-L331 | train | Get the stub code for this function. |
uyar/pygenstub | pygenstub.py | ClassNode.get_code | def get_code(self):
"""Get the stub code for this class.
:sig: () -> List[str]
:return: Lines of stub code for this class.
"""
stub = []
bases = ("(" + ", ".join(self.bases) + ")") if len(self.bases) > 0 else ""
slots = {"n": self.name, "b": bases}
if (le... | python | def get_code(self):
"""Get the stub code for this class.
:sig: () -> List[str]
:return: Lines of stub code for this class.
"""
stub = []
bases = ("(" + ", ".join(self.bases) + ")") if len(self.bases) > 0 else ""
slots = {"n": self.name, "b": bases}
if (le... | [
"def",
"get_code",
"(",
"self",
")",
":",
"stub",
"=",
"[",
"]",
"bases",
"=",
"(",
"\"(\"",
"+",
"\", \"",
".",
"join",
"(",
"self",
".",
"bases",
")",
"+",
"\")\"",
")",
"if",
"len",
"(",
"self",
".",
"bases",
")",
">",
"0",
"else",
"\"\"",
... | Get the stub code for this class.
:sig: () -> List[str]
:return: Lines of stub code for this class. | [
"Get",
"the",
"stub",
"code",
"for",
"this",
"class",
"."
] | a6b18a823382d3c6be29c411fb33c58b6090d22c | https://github.com/uyar/pygenstub/blob/a6b18a823382d3c6be29c411fb33c58b6090d22c/pygenstub.py#L353-L369 | train | Get the stub code for this class. |
uyar/pygenstub | pygenstub.py | StubGenerator.collect_aliases | def collect_aliases(self):
"""Collect the type aliases in the source.
:sig: () -> None
"""
self.aliases = get_aliases(self._code_lines)
for alias, signature in self.aliases.items():
_, _, requires = parse_signature(signature)
self.required_types |= requir... | python | def collect_aliases(self):
"""Collect the type aliases in the source.
:sig: () -> None
"""
self.aliases = get_aliases(self._code_lines)
for alias, signature in self.aliases.items():
_, _, requires = parse_signature(signature)
self.required_types |= requir... | [
"def",
"collect_aliases",
"(",
"self",
")",
":",
"self",
".",
"aliases",
"=",
"get_aliases",
"(",
"self",
".",
"_code_lines",
")",
"for",
"alias",
",",
"signature",
"in",
"self",
".",
"aliases",
".",
"items",
"(",
")",
":",
"_",
",",
"_",
",",
"requi... | Collect the type aliases in the source.
:sig: () -> None | [
"Collect",
"the",
"type",
"aliases",
"in",
"the",
"source",
"."
] | a6b18a823382d3c6be29c411fb33c58b6090d22c | https://github.com/uyar/pygenstub/blob/a6b18a823382d3c6be29c411fb33c58b6090d22c/pygenstub.py#L417-L426 | train | Collect the type aliases in the source. |
uyar/pygenstub | pygenstub.py | StubGenerator.visit_Import | def visit_Import(self, node):
"""Visit an import node."""
line = self._code_lines[node.lineno - 1]
module_name = line.split("import")[0].strip()
for name in node.names:
imported_name = name.name
if name.asname:
imported_name = name.asname + "::" + ... | python | def visit_Import(self, node):
"""Visit an import node."""
line = self._code_lines[node.lineno - 1]
module_name = line.split("import")[0].strip()
for name in node.names:
imported_name = name.name
if name.asname:
imported_name = name.asname + "::" + ... | [
"def",
"visit_Import",
"(",
"self",
",",
"node",
")",
":",
"line",
"=",
"self",
".",
"_code_lines",
"[",
"node",
".",
"lineno",
"-",
"1",
"]",
"module_name",
"=",
"line",
".",
"split",
"(",
"\"import\"",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
... | Visit an import node. | [
"Visit",
"an",
"import",
"node",
"."
] | a6b18a823382d3c6be29c411fb33c58b6090d22c | https://github.com/uyar/pygenstub/blob/a6b18a823382d3c6be29c411fb33c58b6090d22c/pygenstub.py#L428-L436 | train | Visit an import node. |
uyar/pygenstub | pygenstub.py | StubGenerator.visit_ImportFrom | def visit_ImportFrom(self, node):
"""Visit an from-import node."""
line = self._code_lines[node.lineno - 1]
module_name = line.split("from")[1].split("import")[0].strip()
for name in node.names:
imported_name = name.name
if name.asname:
imported_na... | python | def visit_ImportFrom(self, node):
"""Visit an from-import node."""
line = self._code_lines[node.lineno - 1]
module_name = line.split("from")[1].split("import")[0].strip()
for name in node.names:
imported_name = name.name
if name.asname:
imported_na... | [
"def",
"visit_ImportFrom",
"(",
"self",
",",
"node",
")",
":",
"line",
"=",
"self",
".",
"_code_lines",
"[",
"node",
".",
"lineno",
"-",
"1",
"]",
"module_name",
"=",
"line",
".",
"split",
"(",
"\"from\"",
")",
"[",
"1",
"]",
".",
"split",
"(",
"\"... | Visit an from-import node. | [
"Visit",
"an",
"from",
"-",
"import",
"node",
"."
] | a6b18a823382d3c6be29c411fb33c58b6090d22c | https://github.com/uyar/pygenstub/blob/a6b18a823382d3c6be29c411fb33c58b6090d22c/pygenstub.py#L438-L446 | train | Visit an from - import node. |
uyar/pygenstub | pygenstub.py | StubGenerator.visit_Assign | def visit_Assign(self, node):
"""Visit an assignment node."""
line = self._code_lines[node.lineno - 1]
if SIG_COMMENT in line:
line = _RE_COMMENT_IN_STRING.sub("", line)
if (SIG_COMMENT not in line) and (not self.generic):
return
if SIG_COMMENT in line:
... | python | def visit_Assign(self, node):
"""Visit an assignment node."""
line = self._code_lines[node.lineno - 1]
if SIG_COMMENT in line:
line = _RE_COMMENT_IN_STRING.sub("", line)
if (SIG_COMMENT not in line) and (not self.generic):
return
if SIG_COMMENT in line:
... | [
"def",
"visit_Assign",
"(",
"self",
",",
"node",
")",
":",
"line",
"=",
"self",
".",
"_code_lines",
"[",
"node",
".",
"lineno",
"-",
"1",
"]",
"if",
"SIG_COMMENT",
"in",
"line",
":",
"line",
"=",
"_RE_COMMENT_IN_STRING",
".",
"sub",
"(",
"\"\"",
",",
... | Visit an assignment node. | [
"Visit",
"an",
"assignment",
"node",
"."
] | a6b18a823382d3c6be29c411fb33c58b6090d22c | https://github.com/uyar/pygenstub/blob/a6b18a823382d3c6be29c411fb33c58b6090d22c/pygenstub.py#L448-L480 | train | Visit an assignment node. |
uyar/pygenstub | pygenstub.py | StubGenerator.get_function_node | def get_function_node(self, node):
"""Process a function node.
:sig: (Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> FunctionNode
:param node: Node to process.
:return: Generated function node in stub tree.
"""
decorators = []
for d in node.decorator_list:
... | python | def get_function_node(self, node):
"""Process a function node.
:sig: (Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> FunctionNode
:param node: Node to process.
:return: Generated function node in stub tree.
"""
decorators = []
for d in node.decorator_list:
... | [
"def",
"get_function_node",
"(",
"self",
",",
"node",
")",
":",
"decorators",
"=",
"[",
"]",
"for",
"d",
"in",
"node",
".",
"decorator_list",
":",
"if",
"hasattr",
"(",
"d",
",",
"\"id\"",
")",
":",
"decorators",
".",
"append",
"(",
"d",
".",
"id",
... | Process a function node.
:sig: (Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> FunctionNode
:param node: Node to process.
:return: Generated function node in stub tree. | [
"Process",
"a",
"function",
"node",
"."
] | a6b18a823382d3c6be29c411fb33c58b6090d22c | https://github.com/uyar/pygenstub/blob/a6b18a823382d3c6be29c411fb33c58b6090d22c/pygenstub.py#L482-L575 | train | Process a function node. |
uyar/pygenstub | pygenstub.py | StubGenerator.visit_FunctionDef | def visit_FunctionDef(self, node):
"""Visit a function node."""
node = self.get_function_node(node)
if node is not None:
node._async = False | python | def visit_FunctionDef(self, node):
"""Visit a function node."""
node = self.get_function_node(node)
if node is not None:
node._async = False | [
"def",
"visit_FunctionDef",
"(",
"self",
",",
"node",
")",
":",
"node",
"=",
"self",
".",
"get_function_node",
"(",
"node",
")",
"if",
"node",
"is",
"not",
"None",
":",
"node",
".",
"_async",
"=",
"False"
] | Visit a function node. | [
"Visit",
"a",
"function",
"node",
"."
] | a6b18a823382d3c6be29c411fb33c58b6090d22c | https://github.com/uyar/pygenstub/blob/a6b18a823382d3c6be29c411fb33c58b6090d22c/pygenstub.py#L577-L581 | train | Visit a function node. |
uyar/pygenstub | pygenstub.py | StubGenerator.visit_AsyncFunctionDef | def visit_AsyncFunctionDef(self, node):
"""Visit an async function node."""
node = self.get_function_node(node)
if node is not None:
node._async = True | python | def visit_AsyncFunctionDef(self, node):
"""Visit an async function node."""
node = self.get_function_node(node)
if node is not None:
node._async = True | [
"def",
"visit_AsyncFunctionDef",
"(",
"self",
",",
"node",
")",
":",
"node",
"=",
"self",
".",
"get_function_node",
"(",
"node",
")",
"if",
"node",
"is",
"not",
"None",
":",
"node",
".",
"_async",
"=",
"True"
] | Visit an async function node. | [
"Visit",
"an",
"async",
"function",
"node",
"."
] | a6b18a823382d3c6be29c411fb33c58b6090d22c | https://github.com/uyar/pygenstub/blob/a6b18a823382d3c6be29c411fb33c58b6090d22c/pygenstub.py#L583-L587 | train | Visit an async function node. |
uyar/pygenstub | pygenstub.py | StubGenerator.visit_ClassDef | def visit_ClassDef(self, node):
"""Visit a class node."""
self.defined_types.add(node.name)
bases = []
for n in node.bases:
base_parts = []
while True:
if not isinstance(n, ast.Attribute):
base_parts.append(n.id)
... | python | def visit_ClassDef(self, node):
"""Visit a class node."""
self.defined_types.add(node.name)
bases = []
for n in node.bases:
base_parts = []
while True:
if not isinstance(n, ast.Attribute):
base_parts.append(n.id)
... | [
"def",
"visit_ClassDef",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"defined_types",
".",
"add",
"(",
"node",
".",
"name",
")",
"bases",
"=",
"[",
"]",
"for",
"n",
"in",
"node",
".",
"bases",
":",
"base_parts",
"=",
"[",
"]",
"while",
"True",... | Visit a class node. | [
"Visit",
"a",
"class",
"node",
"."
] | a6b18a823382d3c6be29c411fb33c58b6090d22c | https://github.com/uyar/pygenstub/blob/a6b18a823382d3c6be29c411fb33c58b6090d22c/pygenstub.py#L589-L612 | train | Visit a class node. |
uyar/pygenstub | pygenstub.py | StubGenerator.generate_import_from | def generate_import_from(module_, names):
"""Generate an import line.
:sig: (str, Set[str]) -> str
:param module_: Name of module to import the names from.
:param names: Names to import.
:return: Import line in stub code.
"""
regular_names = [n for n in names if ... | python | def generate_import_from(module_, names):
"""Generate an import line.
:sig: (str, Set[str]) -> str
:param module_: Name of module to import the names from.
:param names: Names to import.
:return: Import line in stub code.
"""
regular_names = [n for n in names if ... | [
"def",
"generate_import_from",
"(",
"module_",
",",
"names",
")",
":",
"regular_names",
"=",
"[",
"n",
"for",
"n",
"in",
"names",
"if",
"\"::\"",
"not",
"in",
"n",
"]",
"as_names",
"=",
"[",
"n",
"for",
"n",
"in",
"names",
"if",
"\"::\"",
"in",
"n",
... | Generate an import line.
:sig: (str, Set[str]) -> str
:param module_: Name of module to import the names from.
:param names: Names to import.
:return: Import line in stub code. | [
"Generate",
"an",
"import",
"line",
"."
] | a6b18a823382d3c6be29c411fb33c58b6090d22c | https://github.com/uyar/pygenstub/blob/a6b18a823382d3c6be29c411fb33c58b6090d22c/pygenstub.py#L615-L639 | train | Generate an import line. |
uyar/pygenstub | pygenstub.py | StubGenerator.generate_stub | def generate_stub(self):
"""Generate the stub code for this source.
:sig: () -> str
:return: Generated stub code.
"""
needed_types = self.required_types - BUILTIN_TYPES
needed_types -= self.defined_types
_logger.debug("defined types: %s", self.defined_types)
... | python | def generate_stub(self):
"""Generate the stub code for this source.
:sig: () -> str
:return: Generated stub code.
"""
needed_types = self.required_types - BUILTIN_TYPES
needed_types -= self.defined_types
_logger.debug("defined types: %s", self.defined_types)
... | [
"def",
"generate_stub",
"(",
"self",
")",
":",
"needed_types",
"=",
"self",
".",
"required_types",
"-",
"BUILTIN_TYPES",
"needed_types",
"-=",
"self",
".",
"defined_types",
"_logger",
".",
"debug",
"(",
"\"defined types: %s\"",
",",
"self",
".",
"defined_types",
... | Generate the stub code for this source.
:sig: () -> str
:return: Generated stub code. | [
"Generate",
"the",
"stub",
"code",
"for",
"this",
"source",
"."
] | a6b18a823382d3c6be29c411fb33c58b6090d22c | https://github.com/uyar/pygenstub/blob/a6b18a823382d3c6be29c411fb33c58b6090d22c/pygenstub.py#L641-L742 | train | Generate the stub code for this source. |
infothrill/python-launchd | launchd/launchctl.py | LaunchdJob.properties | def properties(self):
'''
This is a lazily loaded dictionary containing the launchd runtime
information of the job in question. Internally, this is retrieved
using ServiceManagement.SMJobCopyDictionary(). Keep in mind that
some dictionary keys are not always present (for example ... | python | def properties(self):
'''
This is a lazily loaded dictionary containing the launchd runtime
information of the job in question. Internally, this is retrieved
using ServiceManagement.SMJobCopyDictionary(). Keep in mind that
some dictionary keys are not always present (for example ... | [
"def",
"properties",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_nsproperties'",
")",
":",
"self",
".",
"_properties",
"=",
"convert_NSDictionary_to_dict",
"(",
"self",
".",
"_nsproperties",
")",
"del",
"self",
".",
"_nsproperties",
"#self._ns... | This is a lazily loaded dictionary containing the launchd runtime
information of the job in question. Internally, this is retrieved
using ServiceManagement.SMJobCopyDictionary(). Keep in mind that
some dictionary keys are not always present (for example 'PID').
If the job specified by th... | [
"This",
"is",
"a",
"lazily",
"loaded",
"dictionary",
"containing",
"the",
"launchd",
"runtime",
"information",
"of",
"the",
"job",
"in",
"question",
".",
"Internally",
"this",
"is",
"retrieved",
"using",
"ServiceManagement",
".",
"SMJobCopyDictionary",
"()",
".",
... | 2cd50579e808851b116f5a26f9b871a32b65ce0e | https://github.com/infothrill/python-launchd/blob/2cd50579e808851b116f5a26f9b871a32b65ce0e/launchd/launchctl.py#L55-L70 | train | Returns the properties of the job in question. |
infothrill/python-launchd | launchd/launchctl.py | LaunchdJob.plistfilename | def plistfilename(self):
'''
This is a lazily detected absolute filename of the corresponding
property list file (*.plist). None if it doesn't exist.
'''
if self._plist_fname is None:
self._plist_fname = discover_filename(self.label)
return self._plist_fname | python | def plistfilename(self):
'''
This is a lazily detected absolute filename of the corresponding
property list file (*.plist). None if it doesn't exist.
'''
if self._plist_fname is None:
self._plist_fname = discover_filename(self.label)
return self._plist_fname | [
"def",
"plistfilename",
"(",
"self",
")",
":",
"if",
"self",
".",
"_plist_fname",
"is",
"None",
":",
"self",
".",
"_plist_fname",
"=",
"discover_filename",
"(",
"self",
".",
"label",
")",
"return",
"self",
".",
"_plist_fname"
] | This is a lazily detected absolute filename of the corresponding
property list file (*.plist). None if it doesn't exist. | [
"This",
"is",
"a",
"lazily",
"detected",
"absolute",
"filename",
"of",
"the",
"corresponding",
"property",
"list",
"file",
"(",
"*",
".",
"plist",
")",
".",
"None",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | 2cd50579e808851b116f5a26f9b871a32b65ce0e | https://github.com/infothrill/python-launchd/blob/2cd50579e808851b116f5a26f9b871a32b65ce0e/launchd/launchctl.py#L92-L99 | train | Returns the absolute filename of the corresponding
property list file. |
rochapps/django-csv-exports | django_csv_exports/admin.py | export_as_csv | def export_as_csv(admin_model, request, queryset):
"""
Generic csv export admin action.
based on http://djangosnippets.org/snippets/1697/
"""
# everyone has perms to export as csv unless explicitly defined
if getattr(settings, 'DJANGO_EXPORTS_REQUIRE_PERM', None):
admin_opts = admin_mode... | python | def export_as_csv(admin_model, request, queryset):
"""
Generic csv export admin action.
based on http://djangosnippets.org/snippets/1697/
"""
# everyone has perms to export as csv unless explicitly defined
if getattr(settings, 'DJANGO_EXPORTS_REQUIRE_PERM', None):
admin_opts = admin_mode... | [
"def",
"export_as_csv",
"(",
"admin_model",
",",
"request",
",",
"queryset",
")",
":",
"# everyone has perms to export as csv unless explicitly defined",
"if",
"getattr",
"(",
"settings",
",",
"'DJANGO_EXPORTS_REQUIRE_PERM'",
",",
"None",
")",
":",
"admin_opts",
"=",
"a... | Generic csv export admin action.
based on http://djangosnippets.org/snippets/1697/ | [
"Generic",
"csv",
"export",
"admin",
"action",
".",
"based",
"on",
"http",
":",
"//",
"djangosnippets",
".",
"org",
"/",
"snippets",
"/",
"1697",
"/"
] | efcdde401d66f38a64b37afa909bfc16a6c21e9e | https://github.com/rochapps/django-csv-exports/blob/efcdde401d66f38a64b37afa909bfc16a6c21e9e/django_csv_exports/admin.py#L12-L43 | train | Generic csv export admin action. |
rochapps/django-csv-exports | django_csv_exports/admin.py | CSVExportAdmin.has_csv_permission | def has_csv_permission(self, request, obj=None):
"""
Returns True if the given request has permission to add an object.
Can be overridden by the user in subclasses. By default, we assume
all staff users can use this action unless `DJANGO_EXPORTS_REQUIRE_PERM`
is set to True in yo... | python | def has_csv_permission(self, request, obj=None):
"""
Returns True if the given request has permission to add an object.
Can be overridden by the user in subclasses. By default, we assume
all staff users can use this action unless `DJANGO_EXPORTS_REQUIRE_PERM`
is set to True in yo... | [
"def",
"has_csv_permission",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
")",
":",
"if",
"getattr",
"(",
"settings",
",",
"'DJANGO_EXPORTS_REQUIRE_PERM'",
",",
"None",
")",
":",
"opts",
"=",
"self",
".",
"opts",
"codename",
"=",
"'%s_%s'",
"%",
... | Returns True if the given request has permission to add an object.
Can be overridden by the user in subclasses. By default, we assume
all staff users can use this action unless `DJANGO_EXPORTS_REQUIRE_PERM`
is set to True in your django settings. | [
"Returns",
"True",
"if",
"the",
"given",
"request",
"has",
"permission",
"to",
"add",
"an",
"object",
".",
"Can",
"be",
"overridden",
"by",
"the",
"user",
"in",
"subclasses",
".",
"By",
"default",
"we",
"assume",
"all",
"staff",
"users",
"can",
"use",
"t... | efcdde401d66f38a64b37afa909bfc16a6c21e9e | https://github.com/rochapps/django-csv-exports/blob/efcdde401d66f38a64b37afa909bfc16a6c21e9e/django_csv_exports/admin.py#L54-L65 | train | Returns True if the given request has permission to add an object. |
zhemao/funktown | funktown/dictionary.py | ImmutableDict.assoc | def assoc(self, key, value):
'''Returns a new ImmutableDict instance with value associated with key.
The implicit parameter is not modified.'''
copydict = ImmutableDict()
copydict.tree = self.tree.assoc(hash(key), (key, value))
copydict._length = self._length + 1
return c... | python | def assoc(self, key, value):
'''Returns a new ImmutableDict instance with value associated with key.
The implicit parameter is not modified.'''
copydict = ImmutableDict()
copydict.tree = self.tree.assoc(hash(key), (key, value))
copydict._length = self._length + 1
return c... | [
"def",
"assoc",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"copydict",
"=",
"ImmutableDict",
"(",
")",
"copydict",
".",
"tree",
"=",
"self",
".",
"tree",
".",
"assoc",
"(",
"hash",
"(",
"key",
")",
",",
"(",
"key",
",",
"value",
")",
")",
... | Returns a new ImmutableDict instance with value associated with key.
The implicit parameter is not modified. | [
"Returns",
"a",
"new",
"ImmutableDict",
"instance",
"with",
"value",
"associated",
"with",
"key",
".",
"The",
"implicit",
"parameter",
"is",
"not",
"modified",
"."
] | 8d5c5a8bdad2b85b33b4cea3febd820c2657c375 | https://github.com/zhemao/funktown/blob/8d5c5a8bdad2b85b33b4cea3febd820c2657c375/funktown/dictionary.py#L22-L28 | train | Returns a new ImmutableDict instance with value associated with key. |
zhemao/funktown | funktown/dictionary.py | ImmutableDict.update | def update(self, other=None, **kwargs):
'''Takes the same arguments as the update method in the builtin dict
class. However, this version returns a new ImmutableDict instead of
modifying in-place.'''
copydict = ImmutableDict()
if other:
vallist = [(hash(key), (key, ot... | python | def update(self, other=None, **kwargs):
'''Takes the same arguments as the update method in the builtin dict
class. However, this version returns a new ImmutableDict instead of
modifying in-place.'''
copydict = ImmutableDict()
if other:
vallist = [(hash(key), (key, ot... | [
"def",
"update",
"(",
"self",
",",
"other",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"copydict",
"=",
"ImmutableDict",
"(",
")",
"if",
"other",
":",
"vallist",
"=",
"[",
"(",
"hash",
"(",
"key",
")",
",",
"(",
"key",
",",
"other",
"[",
"... | Takes the same arguments as the update method in the builtin dict
class. However, this version returns a new ImmutableDict instead of
modifying in-place. | [
"Takes",
"the",
"same",
"arguments",
"as",
"the",
"update",
"method",
"in",
"the",
"builtin",
"dict",
"class",
".",
"However",
"this",
"version",
"returns",
"a",
"new",
"ImmutableDict",
"instead",
"of",
"modifying",
"in",
"-",
"place",
"."
] | 8d5c5a8bdad2b85b33b4cea3febd820c2657c375 | https://github.com/zhemao/funktown/blob/8d5c5a8bdad2b85b33b4cea3febd820c2657c375/funktown/dictionary.py#L30-L42 | train | Takes the same arguments as the builtin dict
class. However this version returns a new ImmutableDict instead of
modifying in - place. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.