repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
andreycizov/python-xrpc
xrpc/examples/exceptional.py
Exceptional.ep
def ep(self, exc: Exception) -> bool: """Return False if the exception had not been handled gracefully""" if not isinstance(exc, ConnectionAbortedError): return False if len(exc.args) != 2: return False origin, reason = exc.args logging.getLogger(__name...
python
def ep(self, exc: Exception) -> bool: """Return False if the exception had not been handled gracefully""" if not isinstance(exc, ConnectionAbortedError): return False if len(exc.args) != 2: return False origin, reason = exc.args logging.getLogger(__name...
[ "def", "ep", "(", "self", ",", "exc", ":", "Exception", ")", "->", "bool", ":", "if", "not", "isinstance", "(", "exc", ",", "ConnectionAbortedError", ")", ":", "return", "False", "if", "len", "(", "exc", ".", "args", ")", "!=", "2", ":", "return", ...
Return False if the exception had not been handled gracefully
[ "Return", "False", "if", "the", "exception", "had", "not", "been", "handled", "gracefully" ]
train
https://github.com/andreycizov/python-xrpc/blob/4f916383cda7de3272962f3ba07a64f7ec451098/xrpc/examples/exceptional.py#L19-L31
s1s5/django_busybody
django_busybody/decorators.py
required
def required(wrapping_functions, patterns_rslt): ''' USAGE: from django.contrib.auth.decorators import login_required from django.contrib.admin.views.decorators import staff_member_required mypage_patterns = required( login_required, [ ... url patterns ... ] ...
python
def required(wrapping_functions, patterns_rslt): ''' USAGE: from django.contrib.auth.decorators import login_required from django.contrib.admin.views.decorators import staff_member_required mypage_patterns = required( login_required, [ ... url patterns ... ] ...
[ "def", "required", "(", "wrapping_functions", ",", "patterns_rslt", ")", ":", "if", "not", "hasattr", "(", "wrapping_functions", ",", "'__iter__'", ")", ":", "wrapping_functions", "=", "(", "wrapping_functions", ",", ")", "return", "[", "_wrap_instance__resolve", ...
USAGE: from django.contrib.auth.decorators import login_required from django.contrib.admin.views.decorators import staff_member_required mypage_patterns = required( login_required, [ ... url patterns ... ] ) staff_patterns = required( staff_member_requi...
[ "USAGE", ":" ]
train
https://github.com/s1s5/django_busybody/blob/5c6fd89824224f1de1be79ccd9a149f025af1b8f/django_busybody/decorators.py#L26-L57
wtsi-hgi/python-baton-wrapper
baton/mappers.py
IrodsMetadataMapper.get_all
def get_all(self, paths: Union[str, Sequence[str]]) -> Union[IrodsMetadata, List[IrodsMetadata]]: """ Gets all of the metadata for the iRODS entities at the given path or paths. If multiple paths are given, the metadata collection at index `i` on the output corresponds to the path at index ...
python
def get_all(self, paths: Union[str, Sequence[str]]) -> Union[IrodsMetadata, List[IrodsMetadata]]: """ Gets all of the metadata for the iRODS entities at the given path or paths. If multiple paths are given, the metadata collection at index `i` on the output corresponds to the path at index ...
[ "def", "get_all", "(", "self", ",", "paths", ":", "Union", "[", "str", ",", "Sequence", "[", "str", "]", "]", ")", "->", "Union", "[", "IrodsMetadata", ",", "List", "[", "IrodsMetadata", "]", "]", ":" ]
Gets all of the metadata for the iRODS entities at the given path or paths. If multiple paths are given, the metadata collection at index `i` on the output corresponds to the path at index `i` on the input. i.e. ``` output = mapper.get_all(["path_1", "path_2"]) metadata_for_path...
[ "Gets", "all", "of", "the", "metadata", "for", "the", "iRODS", "entities", "at", "the", "given", "path", "or", "paths", "." ]
train
https://github.com/wtsi-hgi/python-baton-wrapper/blob/ae0c9e3630e2c4729a0614cc86f493688436b0b7/baton/mappers.py#L15-L30
wtsi-hgi/python-baton-wrapper
baton/mappers.py
IrodsMetadataMapper.set
def set(self, paths: Union[str, Iterable[str]], metadata: Union[IrodsMetadata, List[IrodsMetadata]]): """ Sets the given metadata on the iRODS entities at the given path or paths. Similar to `add` excpet pre-existing metadata with matching keys will be overwritten. If a single metadata ...
python
def set(self, paths: Union[str, Iterable[str]], metadata: Union[IrodsMetadata, List[IrodsMetadata]]): """ Sets the given metadata on the iRODS entities at the given path or paths. Similar to `add` excpet pre-existing metadata with matching keys will be overwritten. If a single metadata ...
[ "def", "set", "(", "self", ",", "paths", ":", "Union", "[", "str", ",", "Iterable", "[", "str", "]", "]", ",", "metadata", ":", "Union", "[", "IrodsMetadata", ",", "List", "[", "IrodsMetadata", "]", "]", ")", ":" ]
Sets the given metadata on the iRODS entities at the given path or paths. Similar to `add` excpet pre-existing metadata with matching keys will be overwritten. If a single metadata collection is given, that metadata is set for all paths. If a list of metadata are given, each collection is set f...
[ "Sets", "the", "given", "metadata", "on", "the", "iRODS", "entities", "at", "the", "given", "path", "or", "paths", ".", "Similar", "to", "add", "excpet", "pre", "-", "existing", "metadata", "with", "matching", "keys", "will", "be", "overwritten", "." ]
train
https://github.com/wtsi-hgi/python-baton-wrapper/blob/ae0c9e3630e2c4729a0614cc86f493688436b0b7/baton/mappers.py#L46-L57
wtsi-hgi/python-baton-wrapper
baton/mappers.py
AccessControlMapper.get_all
def get_all(self, paths: Union[str, Sequence[str]]) -> Union[Set[AccessControl], Sequence[Set[AccessControl]]]: """ Gets all the access controls for the entity with the given path. :param path: the path of the entity to find access controls for :return: """
python
def get_all(self, paths: Union[str, Sequence[str]]) -> Union[Set[AccessControl], Sequence[Set[AccessControl]]]: """ Gets all the access controls for the entity with the given path. :param path: the path of the entity to find access controls for :return: """
[ "def", "get_all", "(", "self", ",", "paths", ":", "Union", "[", "str", ",", "Sequence", "[", "str", "]", "]", ")", "->", "Union", "[", "Set", "[", "AccessControl", "]", ",", "Sequence", "[", "Set", "[", "AccessControl", "]", "]", "]", ":" ]
Gets all the access controls for the entity with the given path. :param path: the path of the entity to find access controls for :return:
[ "Gets", "all", "the", "access", "controls", "for", "the", "entity", "with", "the", "given", "path", ".", ":", "param", "path", ":", "the", "path", "of", "the", "entity", "to", "find", "access", "controls", "for", ":", "return", ":" ]
train
https://github.com/wtsi-hgi/python-baton-wrapper/blob/ae0c9e3630e2c4729a0614cc86f493688436b0b7/baton/mappers.py#L92-L97
wtsi-hgi/python-baton-wrapper
baton/mappers.py
AccessControlMapper.add_or_replace
def add_or_replace(self, paths: Union[str, Iterable[str]], access_controls: Union[AccessControl, Iterable[AccessControl]]): """ Adds the given access controls to those associated with the given path or collection of paths. If an access control already exists for a user, th...
python
def add_or_replace(self, paths: Union[str, Iterable[str]], access_controls: Union[AccessControl, Iterable[AccessControl]]): """ Adds the given access controls to those associated with the given path or collection of paths. If an access control already exists for a user, th...
[ "def", "add_or_replace", "(", "self", ",", "paths", ":", "Union", "[", "str", ",", "Iterable", "[", "str", "]", "]", ",", "access_controls", ":", "Union", "[", "AccessControl", ",", "Iterable", "[", "AccessControl", "]", "]", ")", ":" ]
Adds the given access controls to those associated with the given path or collection of paths. If an access control already exists for a user, the access control is replaced. :param paths: the paths to add the access controls :param access_controls: the access controls to add
[ "Adds", "the", "given", "access", "controls", "to", "those", "associated", "with", "the", "given", "path", "or", "collection", "of", "paths", ".", "If", "an", "access", "control", "already", "exists", "for", "a", "user", "the", "access", "control", "is", "...
train
https://github.com/wtsi-hgi/python-baton-wrapper/blob/ae0c9e3630e2c4729a0614cc86f493688436b0b7/baton/mappers.py#L100-L107
wtsi-hgi/python-baton-wrapper
baton/mappers.py
AccessControlMapper.set
def set(self, paths: Union[str, Iterable[str]], access_controls: Union[AccessControl, Iterable[AccessControl]]): """ Sets the access controls associated to a give path or collection of paths to those given. :param paths: the paths to set the access controls for :param access_controls: th...
python
def set(self, paths: Union[str, Iterable[str]], access_controls: Union[AccessControl, Iterable[AccessControl]]): """ Sets the access controls associated to a give path or collection of paths to those given. :param paths: the paths to set the access controls for :param access_controls: th...
[ "def", "set", "(", "self", ",", "paths", ":", "Union", "[", "str", ",", "Iterable", "[", "str", "]", "]", ",", "access_controls", ":", "Union", "[", "AccessControl", ",", "Iterable", "[", "AccessControl", "]", "]", ")", ":" ]
Sets the access controls associated to a give path or collection of paths to those given. :param paths: the paths to set the access controls for :param access_controls: the access controls to set
[ "Sets", "the", "access", "controls", "associated", "to", "a", "give", "path", "or", "collection", "of", "paths", "to", "those", "given", ".", ":", "param", "paths", ":", "the", "paths", "to", "set", "the", "access", "controls", "for", ":", "param", "acce...
train
https://github.com/wtsi-hgi/python-baton-wrapper/blob/ae0c9e3630e2c4729a0614cc86f493688436b0b7/baton/mappers.py#L110-L115
wtsi-hgi/python-baton-wrapper
baton/mappers.py
AccessControlMapper.revoke
def revoke(self, paths: Union[str, Iterable[str]], users: Union[str, Iterable[str], User, Iterable[User]]): """ Revokes all access controls that are associated to the given path or collection of paths. :param paths: the paths to remove access controls on :param users: the users to revoke...
python
def revoke(self, paths: Union[str, Iterable[str]], users: Union[str, Iterable[str], User, Iterable[User]]): """ Revokes all access controls that are associated to the given path or collection of paths. :param paths: the paths to remove access controls on :param users: the users to revoke...
[ "def", "revoke", "(", "self", ",", "paths", ":", "Union", "[", "str", ",", "Iterable", "[", "str", "]", "]", ",", "users", ":", "Union", "[", "str", ",", "Iterable", "[", "str", "]", ",", "User", ",", "Iterable", "[", "User", "]", "]", ")", ":"...
Revokes all access controls that are associated to the given path or collection of paths. :param paths: the paths to remove access controls on :param users: the users to revoke access controls for. User may be in the represented as a `User` object or in the form "name#zone"
[ "Revokes", "all", "access", "controls", "that", "are", "associated", "to", "the", "given", "path", "or", "collection", "of", "paths", ".", ":", "param", "paths", ":", "the", "paths", "to", "remove", "access", "controls", "on", ":", "param", "users", ":", ...
train
https://github.com/wtsi-hgi/python-baton-wrapper/blob/ae0c9e3630e2c4729a0614cc86f493688436b0b7/baton/mappers.py#L118-L124
wtsi-hgi/python-baton-wrapper
baton/mappers.py
CollectionAccessControlMapper.add_or_replace
def add_or_replace(self, paths: Union[str, Iterable[str]], access_controls: Union[AccessControl, Iterable[AccessControl]], recursive: bool=False): """ See `AccessControlMapper.add`. :param paths: see `AccessControlMapper.add` :param access_controls: see `AccessCont...
python
def add_or_replace(self, paths: Union[str, Iterable[str]], access_controls: Union[AccessControl, Iterable[AccessControl]], recursive: bool=False): """ See `AccessControlMapper.add`. :param paths: see `AccessControlMapper.add` :param access_controls: see `AccessCont...
[ "def", "add_or_replace", "(", "self", ",", "paths", ":", "Union", "[", "str", ",", "Iterable", "[", "str", "]", "]", ",", "access_controls", ":", "Union", "[", "AccessControl", ",", "Iterable", "[", "AccessControl", "]", "]", ",", "recursive", ":", "bool...
See `AccessControlMapper.add`. :param paths: see `AccessControlMapper.add` :param access_controls: see `AccessControlMapper.add` :param recursive: whether the access control list should be changed recursively for all nested collections
[ "See", "AccessControlMapper", ".", "add", ".", ":", "param", "paths", ":", "see", "AccessControlMapper", ".", "add", ":", "param", "access_controls", ":", "see", "AccessControlMapper", ".", "add", ":", "param", "recursive", ":", "whether", "the", "access", "co...
train
https://github.com/wtsi-hgi/python-baton-wrapper/blob/ae0c9e3630e2c4729a0614cc86f493688436b0b7/baton/mappers.py#L139-L146
wtsi-hgi/python-baton-wrapper
baton/mappers.py
CollectionAccessControlMapper.revoke
def revoke(self, paths: Union[str, Iterable[str]], users: Union[str, Iterable[str], User, Iterable[User]], recursive: bool=False): """ See `AccessControlMapper.revoke`. :param paths: see `AccessControlMapper.revoke` :param users: see `AccessControlMapper.revoke` :p...
python
def revoke(self, paths: Union[str, Iterable[str]], users: Union[str, Iterable[str], User, Iterable[User]], recursive: bool=False): """ See `AccessControlMapper.revoke`. :param paths: see `AccessControlMapper.revoke` :param users: see `AccessControlMapper.revoke` :p...
[ "def", "revoke", "(", "self", ",", "paths", ":", "Union", "[", "str", ",", "Iterable", "[", "str", "]", "]", ",", "users", ":", "Union", "[", "str", ",", "Iterable", "[", "str", "]", ",", "User", ",", "Iterable", "[", "User", "]", "]", ",", "re...
See `AccessControlMapper.revoke`. :param paths: see `AccessControlMapper.revoke` :param users: see `AccessControlMapper.revoke` :param recursive: whether the access control list should be changed recursively for all nested collections
[ "See", "AccessControlMapper", ".", "revoke", ".", ":", "param", "paths", ":", "see", "AccessControlMapper", ".", "revoke", ":", "param", "users", ":", "see", "AccessControlMapper", ".", "revoke", ":", "param", "recursive", ":", "whether", "the", "access", "con...
train
https://github.com/wtsi-hgi/python-baton-wrapper/blob/ae0c9e3630e2c4729a0614cc86f493688436b0b7/baton/mappers.py#L159-L166
wtsi-hgi/python-baton-wrapper
baton/mappers.py
CollectionAccessControlMapper.revoke_all
def revoke_all(self, paths: Union[str, Iterable[str]], recursive: bool=False): """ See `AccessControlMapper.revoke_all`. :param paths: see `AccessControlMapper.revoke_all` :param access_controls: see `AccessControlMapper.revoke_all` :param recursive: whether the access control li...
python
def revoke_all(self, paths: Union[str, Iterable[str]], recursive: bool=False): """ See `AccessControlMapper.revoke_all`. :param paths: see `AccessControlMapper.revoke_all` :param access_controls: see `AccessControlMapper.revoke_all` :param recursive: whether the access control li...
[ "def", "revoke_all", "(", "self", ",", "paths", ":", "Union", "[", "str", ",", "Iterable", "[", "str", "]", "]", ",", "recursive", ":", "bool", "=", "False", ")", ":" ]
See `AccessControlMapper.revoke_all`. :param paths: see `AccessControlMapper.revoke_all` :param access_controls: see `AccessControlMapper.revoke_all` :param recursive: whether the access control list should be changed recursively for all nested collections
[ "See", "AccessControlMapper", ".", "revoke_all", ".", ":", "param", "paths", ":", "see", "AccessControlMapper", ".", "revoke_all", ":", "param", "access_controls", ":", "see", "AccessControlMapper", ".", "revoke_all", ":", "param", "recursive", ":", "whether", "th...
train
https://github.com/wtsi-hgi/python-baton-wrapper/blob/ae0c9e3630e2c4729a0614cc86f493688436b0b7/baton/mappers.py#L169-L175
wtsi-hgi/python-baton-wrapper
baton/mappers.py
IrodsEntityMapper.get_by_metadata
def get_by_metadata(self, metadata_search_criteria: Union[SearchCriterion, Iterable[SearchCriterion]], load_metadata: bool=True, zone: str=None) -> Sequence[EntityType]: """ Gets entities from iRODS that have metadata that matches the given search criteria. :param metadat...
python
def get_by_metadata(self, metadata_search_criteria: Union[SearchCriterion, Iterable[SearchCriterion]], load_metadata: bool=True, zone: str=None) -> Sequence[EntityType]: """ Gets entities from iRODS that have metadata that matches the given search criteria. :param metadat...
[ "def", "get_by_metadata", "(", "self", ",", "metadata_search_criteria", ":", "Union", "[", "SearchCriterion", ",", "Iterable", "[", "SearchCriterion", "]", "]", ",", "load_metadata", ":", "bool", "=", "True", ",", "zone", ":", "str", "=", "None", ")", "->", ...
Gets entities from iRODS that have metadata that matches the given search criteria. :param metadata_search_criteria: the metadata search criteria :param load_metadata: whether metadata associated to the entities should be loaded :param zone: limit query to specific zone in iRODS :return:...
[ "Gets", "entities", "from", "iRODS", "that", "have", "metadata", "that", "matches", "the", "given", "search", "criteria", ".", ":", "param", "metadata_search_criteria", ":", "the", "metadata", "search", "criteria", ":", "param", "load_metadata", ":", "whether", ...
train
https://github.com/wtsi-hgi/python-baton-wrapper/blob/ae0c9e3630e2c4729a0614cc86f493688436b0b7/baton/mappers.py#L197-L205
wtsi-hgi/python-baton-wrapper
baton/mappers.py
IrodsEntityMapper.get_by_path
def get_by_path(self, paths: Union[str, Iterable[str]], load_metadata: bool=True) \ -> Union[EntityType, Sequence[EntityType]]: """ Gets the entity or entities with the given path or paths from iRODS. If one or more of the entities does not exist, a `FileNotFound` exception will be ...
python
def get_by_path(self, paths: Union[str, Iterable[str]], load_metadata: bool=True) \ -> Union[EntityType, Sequence[EntityType]]: """ Gets the entity or entities with the given path or paths from iRODS. If one or more of the entities does not exist, a `FileNotFound` exception will be ...
[ "def", "get_by_path", "(", "self", ",", "paths", ":", "Union", "[", "str", ",", "Iterable", "[", "str", "]", "]", ",", "load_metadata", ":", "bool", "=", "True", ")", "->", "Union", "[", "EntityType", ",", "Sequence", "[", "EntityType", "]", "]", ":"...
Gets the entity or entities with the given path or paths from iRODS. If one or more of the entities does not exist, a `FileNotFound` exception will be raised. :param paths: the paths of the entities to get from iRODS :param load_metadata: whether metadata associated to the entities should be lo...
[ "Gets", "the", "entity", "or", "entities", "with", "the", "given", "path", "or", "paths", "from", "iRODS", "." ]
train
https://github.com/wtsi-hgi/python-baton-wrapper/blob/ae0c9e3630e2c4729a0614cc86f493688436b0b7/baton/mappers.py#L208-L217
wtsi-hgi/python-baton-wrapper
baton/mappers.py
IrodsEntityMapper.get_all_in_collection
def get_all_in_collection(self, collection_paths: Union[str, Iterable[str]], load_metadata: bool = True) \ -> Sequence[EntityType]: """ Gets entities contained within the given iRODS collections. If one or more of the collection_paths does not exist, a `FileNotFound` exception will ...
python
def get_all_in_collection(self, collection_paths: Union[str, Iterable[str]], load_metadata: bool = True) \ -> Sequence[EntityType]: """ Gets entities contained within the given iRODS collections. If one or more of the collection_paths does not exist, a `FileNotFound` exception will ...
[ "def", "get_all_in_collection", "(", "self", ",", "collection_paths", ":", "Union", "[", "str", ",", "Iterable", "[", "str", "]", "]", ",", "load_metadata", ":", "bool", "=", "True", ")", "->", "Sequence", "[", "EntityType", "]", ":" ]
Gets entities contained within the given iRODS collections. If one or more of the collection_paths does not exist, a `FileNotFound` exception will be raised. :param collection_paths: the collection(s) to get the entities from :param load_metadata: whether metadata associated to the entities sho...
[ "Gets", "entities", "contained", "within", "the", "given", "iRODS", "collections", "." ]
train
https://github.com/wtsi-hgi/python-baton-wrapper/blob/ae0c9e3630e2c4729a0614cc86f493688436b0b7/baton/mappers.py#L220-L229
edeposit/edeposit.amqp.ltp
src/edeposit/amqp/ltp/ltp.py
_get_package_name
def _get_package_name(prefix=settings.TEMP_DIR, book_id=None): """ Return package path. Use uuid to generate package's directory name. Args: book_id (str, default None): UUID of the book. prefix (str, default settings.TEMP_DIR): Where the package will be stored. Default :attr...
python
def _get_package_name(prefix=settings.TEMP_DIR, book_id=None): """ Return package path. Use uuid to generate package's directory name. Args: book_id (str, default None): UUID of the book. prefix (str, default settings.TEMP_DIR): Where the package will be stored. Default :attr...
[ "def", "_get_package_name", "(", "prefix", "=", "settings", ".", "TEMP_DIR", ",", "book_id", "=", "None", ")", ":", "if", "book_id", "is", "None", ":", "book_id", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "return", "os", ".", "path", ".",...
Return package path. Use uuid to generate package's directory name. Args: book_id (str, default None): UUID of the book. prefix (str, default settings.TEMP_DIR): Where the package will be stored. Default :attr:`settings.TEMP_DIR`. Returns: str: Path to the root directory...
[ "Return", "package", "path", ".", "Use", "uuid", "to", "generate", "package", "s", "directory", "name", "." ]
train
https://github.com/edeposit/edeposit.amqp.ltp/blob/df9ac7ec6cbdbeaaeed438ca66df75ea967b6d8e/src/edeposit/amqp/ltp/ltp.py#L22-L37
edeposit/edeposit.amqp.ltp
src/edeposit/amqp/ltp/ltp.py
_create_package_hierarchy
def _create_package_hierarchy(prefix=settings.TEMP_DIR, book_id=None): """ Create hierarchy of directories, at it is required in specification. `root_dir` is root of the package generated using :attr:`settings.TEMP_DIR` and :func:`_get_package_name`. `orig_dir` is path to the directory, where the ...
python
def _create_package_hierarchy(prefix=settings.TEMP_DIR, book_id=None): """ Create hierarchy of directories, at it is required in specification. `root_dir` is root of the package generated using :attr:`settings.TEMP_DIR` and :func:`_get_package_name`. `orig_dir` is path to the directory, where the ...
[ "def", "_create_package_hierarchy", "(", "prefix", "=", "settings", ".", "TEMP_DIR", ",", "book_id", "=", "None", ")", ":", "root_dir", "=", "_get_package_name", "(", "book_id", "=", "book_id", ",", "prefix", "=", "prefix", ")", "if", "os", ".", "path", "....
Create hierarchy of directories, at it is required in specification. `root_dir` is root of the package generated using :attr:`settings.TEMP_DIR` and :func:`_get_package_name`. `orig_dir` is path to the directory, where the data files are stored. `metadata_dir` is path to the directory with MODS metad...
[ "Create", "hierarchy", "of", "directories", "at", "it", "is", "required", "in", "specification", "." ]
train
https://github.com/edeposit/edeposit.amqp.ltp/blob/df9ac7ec6cbdbeaaeed438ca66df75ea967b6d8e/src/edeposit/amqp/ltp/ltp.py#L40-L75
edeposit/edeposit.amqp.ltp
src/edeposit/amqp/ltp/ltp.py
create_ltp_package
def create_ltp_package(aleph_record, book_id, ebook_fn, data, url, urn_nbn=None): """ Create LTP package as it is specified in specification v1.0 as I understand it. Args: aleph_record (str): XML containing full aleph record. book_id (str): UUID of the book. ...
python
def create_ltp_package(aleph_record, book_id, ebook_fn, data, url, urn_nbn=None): """ Create LTP package as it is specified in specification v1.0 as I understand it. Args: aleph_record (str): XML containing full aleph record. book_id (str): UUID of the book. ...
[ "def", "create_ltp_package", "(", "aleph_record", ",", "book_id", ",", "ebook_fn", ",", "data", ",", "url", ",", "urn_nbn", "=", "None", ")", ":", "root_dir", ",", "orig_dir", ",", "meta_dir", "=", "_create_package_hierarchy", "(", "book_id", "=", "book_id", ...
Create LTP package as it is specified in specification v1.0 as I understand it. Args: aleph_record (str): XML containing full aleph record. book_id (str): UUID of the book. ebook_fn (str): Original filename of the ebook. data (str/bytes): Ebook's content. url (str): URL ...
[ "Create", "LTP", "package", "as", "it", "is", "specified", "in", "specification", "v1", ".", "0", "as", "I", "understand", "it", "." ]
train
https://github.com/edeposit/edeposit.amqp.ltp/blob/df9ac7ec6cbdbeaaeed438ca66df75ea967b6d8e/src/edeposit/amqp/ltp/ltp.py#L78-L139
ArtoLabs/SimpleSteem
simplesteem/steemconnectutil.py
SteemConnect.steemconnect
def steemconnect(self, accesstoken=None): ''' Initializes the SteemConnect Client class ''' if self.sc is not None: return self.sc if accesstoken is not None: self.accesstoken = accesstoken if self.accesstoken is None: self.sc = Client(...
python
def steemconnect(self, accesstoken=None): ''' Initializes the SteemConnect Client class ''' if self.sc is not None: return self.sc if accesstoken is not None: self.accesstoken = accesstoken if self.accesstoken is None: self.sc = Client(...
[ "def", "steemconnect", "(", "self", ",", "accesstoken", "=", "None", ")", ":", "if", "self", ".", "sc", "is", "not", "None", ":", "return", "self", ".", "sc", "if", "accesstoken", "is", "not", "None", ":", "self", ".", "accesstoken", "=", "accesstoken"...
Initializes the SteemConnect Client class
[ "Initializes", "the", "SteemConnect", "Client", "class" ]
train
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/steemconnectutil.py#L24-L39
ArtoLabs/SimpleSteem
simplesteem/steemconnectutil.py
SteemConnect.get_token
def get_token(self, code=None): ''' Uses a SteemConnect refresh token to retreive an access token ''' tokenobj = self.steemconnect().get_access_token(code) for t in tokenobj: if t == 'error': self.msg.error_message(str(tokenobj[t])) ret...
python
def get_token(self, code=None): ''' Uses a SteemConnect refresh token to retreive an access token ''' tokenobj = self.steemconnect().get_access_token(code) for t in tokenobj: if t == 'error': self.msg.error_message(str(tokenobj[t])) ret...
[ "def", "get_token", "(", "self", ",", "code", "=", "None", ")", ":", "tokenobj", "=", "self", ".", "steemconnect", "(", ")", ".", "get_access_token", "(", "code", ")", "for", "t", "in", "tokenobj", ":", "if", "t", "==", "'error'", ":", "self", ".", ...
Uses a SteemConnect refresh token to retreive an access token
[ "Uses", "a", "SteemConnect", "refresh", "token", "to", "retreive", "an", "access", "token" ]
train
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/steemconnectutil.py#L42-L54
ArtoLabs/SimpleSteem
simplesteem/steemconnectutil.py
SteemConnect.vote
def vote(self, voter, author, permlink, voteweight): ''' Uses a SteemConnect accses token to vote. ''' vote = Vote(voter, author, permlink, voteweight) result = self.steemconnect().broadcast( [vote.to_operation_structure()]) return result
python
def vote(self, voter, author, permlink, voteweight): ''' Uses a SteemConnect accses token to vote. ''' vote = Vote(voter, author, permlink, voteweight) result = self.steemconnect().broadcast( [vote.to_operation_structure()]) return result
[ "def", "vote", "(", "self", ",", "voter", ",", "author", ",", "permlink", ",", "voteweight", ")", ":", "vote", "=", "Vote", "(", "voter", ",", "author", ",", "permlink", ",", "voteweight", ")", "result", "=", "self", ".", "steemconnect", "(", ")", "....
Uses a SteemConnect accses token to vote.
[ "Uses", "a", "SteemConnect", "accses", "token", "to", "vote", "." ]
train
https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/steemconnectutil.py#L67-L74
the01/python-paps
paps/si/sensorClientAdapter.py
SensorClientAdapter.on_person_new
def on_person_new(self, people): """ Add new people All people supported need to be added simultaneously, since on every call a unjoin() followed by a join() is issued :param people: People to add :type people: list[paps.people.People] :rtype: None :rais...
python
def on_person_new(self, people): """ Add new people All people supported need to be added simultaneously, since on every call a unjoin() followed by a join() is issued :param people: People to add :type people: list[paps.people.People] :rtype: None :rais...
[ "def", "on_person_new", "(", "self", ",", "people", ")", ":", "try", ":", "self", ".", "on_person_leave", "(", "[", "]", ")", "except", ":", "# Already caught and logged", "pass", "try", ":", "self", ".", "sensor_client", ".", "join", "(", "people", ")", ...
Add new people All people supported need to be added simultaneously, since on every call a unjoin() followed by a join() is issued :param people: People to add :type people: list[paps.people.People] :rtype: None :raises Exception: On error (for now just an exception)
[ "Add", "new", "people" ]
train
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/sensorClientAdapter.py#L48-L70
the01/python-paps
paps/si/sensorClientAdapter.py
SensorClientAdapter.on_person_update
def on_person_update(self, people): """ People have changed Should always include all people (all that were added via on_person_new) :param people: People to update :type people: list[paps.people.People] :rtype: None :raises Exception: On error (for now ...
python
def on_person_update(self, people): """ People have changed Should always include all people (all that were added via on_person_new) :param people: People to update :type people: list[paps.people.People] :rtype: None :raises Exception: On error (for now ...
[ "def", "on_person_update", "(", "self", ",", "people", ")", ":", "try", ":", "self", ".", "sensor_client", ".", "person_update", "(", "people", ")", "except", ":", "self", ".", "exception", "(", "\"Failed to update people\"", ")", "raise", "Exception", "(", ...
People have changed Should always include all people (all that were added via on_person_new) :param people: People to update :type people: list[paps.people.People] :rtype: None :raises Exception: On error (for now just an exception)
[ "People", "have", "changed" ]
train
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/sensorClientAdapter.py#L90-L106
diffeo/rejester
rejester/_redis.py
RedisBase.delete_namespace
def delete_namespace(self): '''Remove all keys from the namespace ''' conn = redis.Redis(connection_pool=self.pool) keys = conn.keys("%s*" % self._namespace_str) for i in xrange(0, len(keys), 10000): conn.delete(*keys[i:i+10000]) logger.debug('tearing down %r...
python
def delete_namespace(self): '''Remove all keys from the namespace ''' conn = redis.Redis(connection_pool=self.pool) keys = conn.keys("%s*" % self._namespace_str) for i in xrange(0, len(keys), 10000): conn.delete(*keys[i:i+10000]) logger.debug('tearing down %r...
[ "def", "delete_namespace", "(", "self", ")", ":", "conn", "=", "redis", ".", "Redis", "(", "connection_pool", "=", "self", ".", "pool", ")", "keys", "=", "conn", ".", "keys", "(", "\"%s*\"", "%", "self", ".", "_namespace_str", ")", "for", "i", "in", ...
Remove all keys from the namespace
[ "Remove", "all", "keys", "from", "the", "namespace" ]
train
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_redis.py#L67-L75
unitedstack/steth
stetho/agent/common/utils.py
create_deamon
def create_deamon(cmd, shell=False, root=False): """Usage: Create servcice process. """ try: if root: cmd.insert(0, 'sudo') LOG.info(cmd) subproc = subprocess.Popen(cmd, shell=shell, stdout=subprocess.PIPE, stderr=subprocess.PIPE...
python
def create_deamon(cmd, shell=False, root=False): """Usage: Create servcice process. """ try: if root: cmd.insert(0, 'sudo') LOG.info(cmd) subproc = subprocess.Popen(cmd, shell=shell, stdout=subprocess.PIPE, stderr=subprocess.PIPE...
[ "def", "create_deamon", "(", "cmd", ",", "shell", "=", "False", ",", "root", "=", "False", ")", ":", "try", ":", "if", "root", ":", "cmd", ".", "insert", "(", "0", ",", "'sudo'", ")", "LOG", ".", "info", "(", "cmd", ")", "subproc", "=", "subproce...
Usage: Create servcice process.
[ "Usage", ":", "Create", "servcice", "process", "." ]
train
https://github.com/unitedstack/steth/blob/955884ceebf3bdc474c93cc5cf555e67d16458f1/stetho/agent/common/utils.py#L62-L75
unitedstack/steth
stetho/agent/common/utils.py
get_interface
def get_interface(interface): """Support Centos standard physical interface, such as eth0. """ # Supported CentOS Version supported_dists = ['7.0', '6.5'] def format_centos_7_0(inf): pattern = r'<([A-Z]+)' state = re.search(pattern, stdout[0]).groups()[0] state = 'UP'...
python
def get_interface(interface): """Support Centos standard physical interface, such as eth0. """ # Supported CentOS Version supported_dists = ['7.0', '6.5'] def format_centos_7_0(inf): pattern = r'<([A-Z]+)' state = re.search(pattern, stdout[0]).groups()[0] state = 'UP'...
[ "def", "get_interface", "(", "interface", ")", ":", "# Supported CentOS Version", "supported_dists", "=", "[", "'7.0'", ",", "'6.5'", "]", "def", "format_centos_7_0", "(", "inf", ")", ":", "pattern", "=", "r'<([A-Z]+)'", "state", "=", "re", ".", "search", "(",...
Support Centos standard physical interface, such as eth0.
[ "Support", "Centos", "standard", "physical", "interface", "such", "as", "eth0", "." ]
train
https://github.com/unitedstack/steth/blob/955884ceebf3bdc474c93cc5cf555e67d16458f1/stetho/agent/common/utils.py#L84-L147
armstrong/armstrong.apps.images
setup.py
convert_to_str
def convert_to_str(d): """ Recursively convert all values in a dictionary to strings This is required because setup() does not like unicode in the values it is supplied. """ d2 = {} for k, v in d.items(): k = str(k) if type(v) in [list, tuple]: d2[k] = [str(a) fo...
python
def convert_to_str(d): """ Recursively convert all values in a dictionary to strings This is required because setup() does not like unicode in the values it is supplied. """ d2 = {} for k, v in d.items(): k = str(k) if type(v) in [list, tuple]: d2[k] = [str(a) fo...
[ "def", "convert_to_str", "(", "d", ")", ":", "d2", "=", "{", "}", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "k", "=", "str", "(", "k", ")", "if", "type", "(", "v", ")", "in", "[", "list", ",", "tuple", "]", ":", "d2", ...
Recursively convert all values in a dictionary to strings This is required because setup() does not like unicode in the values it is supplied.
[ "Recursively", "convert", "all", "values", "in", "a", "dictionary", "to", "strings" ]
train
https://github.com/armstrong/armstrong.apps.images/blob/f334697ee6e2273deac12092069d02119d913e67/setup.py#L15-L31
racker/torment
torment/contexts/docker/compose.py
up
def up(services: Iterable[str] = ()) -> int: '''Start the specified docker-compose services. Parameters ---------- :``services``: a list of docker-compose service names to start (must be defined in docker-compose.yml) Return Value(s) --------------- The integer status ...
python
def up(services: Iterable[str] = ()) -> int: '''Start the specified docker-compose services. Parameters ---------- :``services``: a list of docker-compose service names to start (must be defined in docker-compose.yml) Return Value(s) --------------- The integer status ...
[ "def", "up", "(", "services", ":", "Iterable", "[", "str", "]", "=", "(", ")", ")", "->", "int", ":", "services", "=", "list", "(", "services", ")", "if", "not", "len", "(", "services", ")", ":", "raise", "ValueError", "(", "'empty iterable passed to u...
Start the specified docker-compose services. Parameters ---------- :``services``: a list of docker-compose service names to start (must be defined in docker-compose.yml) Return Value(s) --------------- The integer status of ``docker-compose up``.
[ "Start", "the", "specified", "docker", "-", "compose", "services", "." ]
train
https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/contexts/docker/compose.py#L54-L75
racker/torment
torment/contexts/docker/compose.py
_call
def _call(command: str, *args, **kwargs) -> int: '''Wrapper around ``subprocess.Popen`` that sends command output to logger. .. seealso:: ``subprocess.Popen``_ Parameters ---------- :``command``: string form of the command to execute All other parameters are passed directly to ``subp...
python
def _call(command: str, *args, **kwargs) -> int: '''Wrapper around ``subprocess.Popen`` that sends command output to logger. .. seealso:: ``subprocess.Popen``_ Parameters ---------- :``command``: string form of the command to execute All other parameters are passed directly to ``subp...
[ "def", "_call", "(", "command", ":", "str", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "int", ":", "child", "=", "subprocess", ".", "Popen", "(", "command", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ...
Wrapper around ``subprocess.Popen`` that sends command output to logger. .. seealso:: ``subprocess.Popen``_ Parameters ---------- :``command``: string form of the command to execute All other parameters are passed directly to ``subprocess.Popen``. Return Value(s) ---------------...
[ "Wrapper", "around", "subprocess", ".", "Popen", "that", "sends", "command", "output", "to", "logger", "." ]
train
https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/contexts/docker/compose.py#L78-L118
samfcmc/fenixedu-python-sdk
fenixedu/__init__.py
FenixEduClient._api_private_request
def _api_private_request(self, endpoint, user, params=None, method=None, headers=None): params = params or {} url = self._get_api_endpoint_url(endpoint) params['access_token'] = user.access_token r = self._request(url, params = params, method = method, headers = headers) """ Check if everything was fine I...
python
def _api_private_request(self, endpoint, user, params=None, method=None, headers=None): params = params or {} url = self._get_api_endpoint_url(endpoint) params['access_token'] = user.access_token r = self._request(url, params = params, method = method, headers = headers) """ Check if everything was fine I...
[ "def", "_api_private_request", "(", "self", ",", "endpoint", ",", "user", ",", "params", "=", "None", ",", "method", "=", "None", ",", "headers", "=", "None", ")", ":", "params", "=", "params", "or", "{", "}", "url", "=", "self", ".", "_get_api_endpoin...
Check if everything was fine If not: Try to refresh the access token
[ "Check", "if", "everything", "was", "fine", "If", "not", ":", "Try", "to", "refresh", "the", "access", "token" ]
train
https://github.com/samfcmc/fenixedu-python-sdk/blob/b9a1366853b2e7a6e208c46c3b99a589062677a9/fenixedu/__init__.py#L53-L65
rmed/flask-waffleconf
flask_waffleconf/watcher.py
_file_watcher
def _file_watcher(state): """Watch for file changes and reload config when needed. Arguments: state (_WaffleState): Object that contains reference to app and its configstore. """ conf = state.app.config file_path = conf.get('WAFFLE_WATCHER_FILE', '/tmp/waffleconf.txt') if ...
python
def _file_watcher(state): """Watch for file changes and reload config when needed. Arguments: state (_WaffleState): Object that contains reference to app and its configstore. """ conf = state.app.config file_path = conf.get('WAFFLE_WATCHER_FILE', '/tmp/waffleconf.txt') if ...
[ "def", "_file_watcher", "(", "state", ")", ":", "conf", "=", "state", ".", "app", ".", "config", "file_path", "=", "conf", ".", "get", "(", "'WAFFLE_WATCHER_FILE'", ",", "'/tmp/waffleconf.txt'", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "f...
Watch for file changes and reload config when needed. Arguments: state (_WaffleState): Object that contains reference to app and its configstore.
[ "Watch", "for", "file", "changes", "and", "reload", "config", "when", "needed", "." ]
train
https://github.com/rmed/flask-waffleconf/blob/a75ed69101796c9f3f42eff9f91e91dc6dd13869/flask_waffleconf/watcher.py#L50-L74
rmed/flask-waffleconf
flask_waffleconf/watcher.py
_redis_watcher
def _redis_watcher(state): """Listen to redis channel for a configuration update notifications. Arguments: state (_WaffleState): Object that contains reference to app and its configstore. """ conf = state.app.config r = redis.client.StrictRedis( host=conf.get('WAFFLE_RE...
python
def _redis_watcher(state): """Listen to redis channel for a configuration update notifications. Arguments: state (_WaffleState): Object that contains reference to app and its configstore. """ conf = state.app.config r = redis.client.StrictRedis( host=conf.get('WAFFLE_RE...
[ "def", "_redis_watcher", "(", "state", ")", ":", "conf", "=", "state", ".", "app", ".", "config", "r", "=", "redis", ".", "client", ".", "StrictRedis", "(", "host", "=", "conf", ".", "get", "(", "'WAFFLE_REDIS_HOST'", ",", "'localhost'", ")", ",", "por...
Listen to redis channel for a configuration update notifications. Arguments: state (_WaffleState): Object that contains reference to app and its configstore.
[ "Listen", "to", "redis", "channel", "for", "a", "configuration", "update", "notifications", "." ]
train
https://github.com/rmed/flask-waffleconf/blob/a75ed69101796c9f3f42eff9f91e91dc6dd13869/flask_waffleconf/watcher.py#L76-L103
rmed/flask-waffleconf
flask_waffleconf/watcher.py
_file_notifier
def _file_notifier(state): """Notify of configuration update through file. Arguments: state (_WaffleState): Object that contains reference to app and its configstore. """ tstamp = time.time() state._tstamp = tstamp conf = state.app.config file_path = conf.get('WAFFLE_WA...
python
def _file_notifier(state): """Notify of configuration update through file. Arguments: state (_WaffleState): Object that contains reference to app and its configstore. """ tstamp = time.time() state._tstamp = tstamp conf = state.app.config file_path = conf.get('WAFFLE_WA...
[ "def", "_file_notifier", "(", "state", ")", ":", "tstamp", "=", "time", ".", "time", "(", ")", "state", ".", "_tstamp", "=", "tstamp", "conf", "=", "state", ".", "app", ".", "config", "file_path", "=", "conf", ".", "get", "(", "'WAFFLE_WATCHER_FILE'", ...
Notify of configuration update through file. Arguments: state (_WaffleState): Object that contains reference to app and its configstore.
[ "Notify", "of", "configuration", "update", "through", "file", "." ]
train
https://github.com/rmed/flask-waffleconf/blob/a75ed69101796c9f3f42eff9f91e91dc6dd13869/flask_waffleconf/watcher.py#L121-L139
rmed/flask-waffleconf
flask_waffleconf/watcher.py
_redis_notifier
def _redis_notifier(state): """Notify of configuration update through redis. Arguments: state (_WaffleState): Object that contains reference to app and its configstore. """ tstamp = time.time() state._tstamp = tstamp conf = state.app.config # Notify timestamp r = re...
python
def _redis_notifier(state): """Notify of configuration update through redis. Arguments: state (_WaffleState): Object that contains reference to app and its configstore. """ tstamp = time.time() state._tstamp = tstamp conf = state.app.config # Notify timestamp r = re...
[ "def", "_redis_notifier", "(", "state", ")", ":", "tstamp", "=", "time", ".", "time", "(", ")", "state", ".", "_tstamp", "=", "tstamp", "conf", "=", "state", ".", "app", ".", "config", "# Notify timestamp", "r", "=", "redis", ".", "client", ".", "Stric...
Notify of configuration update through redis. Arguments: state (_WaffleState): Object that contains reference to app and its configstore.
[ "Notify", "of", "configuration", "update", "through", "redis", "." ]
train
https://github.com/rmed/flask-waffleconf/blob/a75ed69101796c9f3f42eff9f91e91dc6dd13869/flask_waffleconf/watcher.py#L141-L154
jordanncg/Bison
bison/libs/common.py
Common.make_dir
def make_dir(cls, directory_name): """Create a directory in the system""" if not os.path.exists(directory_name): os.makedirs(directory_name)
python
def make_dir(cls, directory_name): """Create a directory in the system""" if not os.path.exists(directory_name): os.makedirs(directory_name)
[ "def", "make_dir", "(", "cls", ",", "directory_name", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "directory_name", ")", ":", "os", ".", "makedirs", "(", "directory_name", ")" ]
Create a directory in the system
[ "Create", "a", "directory", "in", "the", "system" ]
train
https://github.com/jordanncg/Bison/blob/c7f04fd67d141fe26cd29db3c3fb3fc0fd0c45df/bison/libs/common.py#L35-L38
edwards-lab/libGWAS
libgwas/pedigree_parser.py
Parser.ReportConfiguration
def ReportConfiguration(self, file): """ Report configuration for logging purposes. :param file: Destination for report details :return: None """ print >> file, BuildReportLine("PED FILE", self.datasource) print >> file, BuildReportLine("MAP FILE", self.mapfile)
python
def ReportConfiguration(self, file): """ Report configuration for logging purposes. :param file: Destination for report details :return: None """ print >> file, BuildReportLine("PED FILE", self.datasource) print >> file, BuildReportLine("MAP FILE", self.mapfile)
[ "def", "ReportConfiguration", "(", "self", ",", "file", ")", ":", "print", ">>", "file", ",", "BuildReportLine", "(", "\"PED FILE\"", ",", "self", ".", "datasource", ")", "print", ">>", "file", ",", "BuildReportLine", "(", "\"MAP FILE\"", ",", "self", ".", ...
Report configuration for logging purposes. :param file: Destination for report details :return: None
[ "Report", "configuration", "for", "logging", "purposes", "." ]
train
https://github.com/edwards-lab/libGWAS/blob/d68c9a083d443dfa5d7c5112de29010909cfe23f/libgwas/pedigree_parser.py#L83-L90
edwards-lab/libGWAS
libgwas/pedigree_parser.py
Parser.load_mapfile
def load_mapfile(self, map3=False): """Load the marker data :param map3: When true, ignore the gen. distance column Builds up the marker list according to the boundary configuration """ cols = [0, 1, 3] if map3: cols = [0, 1, 2] markers = numpy.loa...
python
def load_mapfile(self, map3=False): """Load the marker data :param map3: When true, ignore the gen. distance column Builds up the marker list according to the boundary configuration """ cols = [0, 1, 3] if map3: cols = [0, 1, 2] markers = numpy.loa...
[ "def", "load_mapfile", "(", "self", ",", "map3", "=", "False", ")", ":", "cols", "=", "[", "0", ",", "1", ",", "3", "]", "if", "map3", ":", "cols", "=", "[", "0", ",", "1", ",", "2", "]", "markers", "=", "numpy", ".", "loadtxt", "(", "self", ...
Load the marker data :param map3: When true, ignore the gen. distance column Builds up the marker list according to the boundary configuration
[ "Load", "the", "marker", "data" ]
train
https://github.com/edwards-lab/libGWAS/blob/d68c9a083d443dfa5d7c5112de29010909cfe23f/libgwas/pedigree_parser.py#L92-L138
edwards-lab/libGWAS
libgwas/pedigree_parser.py
Parser.load_genotypes
def load_genotypes(self, pheno_covar): """Load all data into memory and propagate valid individuals to \ pheno_covar. :param pheno_covar: Phenotype/covariate object is updated with subject information :return: None """ first_genotype = 6 pheno_col =...
python
def load_genotypes(self, pheno_covar): """Load all data into memory and propagate valid individuals to \ pheno_covar. :param pheno_covar: Phenotype/covariate object is updated with subject information :return: None """ first_genotype = 6 pheno_col =...
[ "def", "load_genotypes", "(", "self", ",", "pheno_covar", ")", ":", "first_genotype", "=", "6", "pheno_col", "=", "5", "if", "not", "DataParser", ".", "has_sex", ":", "first_genotype", "-=", "1", "pheno_col", "-=", "1", "if", "not", "DataParser", ".", "has...
Load all data into memory and propagate valid individuals to \ pheno_covar. :param pheno_covar: Phenotype/covariate object is updated with subject information :return: None
[ "Load", "all", "data", "into", "memory", "and", "propagate", "valid", "individuals", "to", "\\", "pheno_covar", "." ]
train
https://github.com/edwards-lab/libGWAS/blob/d68c9a083d443dfa5d7c5112de29010909cfe23f/libgwas/pedigree_parser.py#L141-L305
edwards-lab/libGWAS
libgwas/pedigree_parser.py
Parser.populate_iteration
def populate_iteration(self, iteration): """Parse genotypes from the file and iteration with relevant marker \ details. :param iteration: ParseLocus object which is returned per iteration :return: True indicates current locus is valid. StopIteration is thrown if the marker ...
python
def populate_iteration(self, iteration): """Parse genotypes from the file and iteration with relevant marker \ details. :param iteration: ParseLocus object which is returned per iteration :return: True indicates current locus is valid. StopIteration is thrown if the marker ...
[ "def", "populate_iteration", "(", "self", ",", "iteration", ")", ":", "cur_idx", "=", "iteration", ".", "cur_idx", "if", "cur_idx", "<", "self", ".", "locus_count", ":", "iteration", ".", "chr", "=", "self", ".", "markers", "[", "cur_idx", "]", "[", "0",...
Parse genotypes from the file and iteration with relevant marker \ details. :param iteration: ParseLocus object which is returned per iteration :return: True indicates current locus is valid. StopIteration is thrown if the marker reaches the end of the file or the valid gen...
[ "Parse", "genotypes", "from", "the", "file", "and", "iteration", "with", "relevant", "marker", "\\", "details", "." ]
train
https://github.com/edwards-lab/libGWAS/blob/d68c9a083d443dfa5d7c5112de29010909cfe23f/libgwas/pedigree_parser.py#L310-L337
juancarlospaco/apistar-msgpack
setup.py
find_this
def find_this(search, source=SOURCE): """Take a string and a filename path string and return the found value.""" print("Searching for {what}.".format(what=search)) if not search or not source: print("Not found on source: {what}.".format(what=search)) return "" return str(re.compile(r'.*_...
python
def find_this(search, source=SOURCE): """Take a string and a filename path string and return the found value.""" print("Searching for {what}.".format(what=search)) if not search or not source: print("Not found on source: {what}.".format(what=search)) return "" return str(re.compile(r'.*_...
[ "def", "find_this", "(", "search", ",", "source", "=", "SOURCE", ")", ":", "print", "(", "\"Searching for {what}.\"", ".", "format", "(", "what", "=", "search", ")", ")", "if", "not", "search", "or", "not", "source", ":", "print", "(", "\"Not found on sour...
Take a string and a filename path string and return the found value.
[ "Take", "a", "string", "and", "a", "filename", "path", "string", "and", "return", "the", "found", "value", "." ]
train
https://github.com/juancarlospaco/apistar-msgpack/blob/59858431321a32e5cea4b8660d89d8958bb86f7d/setup.py#L57-L64
hobson/pug-dj
pug/dj/db.py
normalize_values_queryset
def normalize_values_queryset(values_queryset, model=None, app=None, verbosity=1): '''Shoehorn the values from one database table into another * Remove padding (leading/trailing spaces) from `CharField` and `TextField` values * Truncate all `CharField`s to the max_length of the destination `model` * Su...
python
def normalize_values_queryset(values_queryset, model=None, app=None, verbosity=1): '''Shoehorn the values from one database table into another * Remove padding (leading/trailing spaces) from `CharField` and `TextField` values * Truncate all `CharField`s to the max_length of the destination `model` * Su...
[ "def", "normalize_values_queryset", "(", "values_queryset", ",", "model", "=", "None", ",", "app", "=", "None", ",", "verbosity", "=", "1", ")", ":", "model", "=", "model", "or", "values_queryset", ".", "model", "app", "=", "app", "or", "DEFAULT_APP", "new...
Shoehorn the values from one database table into another * Remove padding (leading/trailing spaces) from `CharField` and `TextField` values * Truncate all `CharField`s to the max_length of the destination `model` * Subsititue blanks ('') for any None values destined for `null=False` fields Returns a l...
[ "Shoehorn", "the", "values", "from", "one", "database", "table", "into", "another" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L110-L150
hobson/pug-dj
pug/dj/db.py
make_choices
def make_choices(*args): """Convert a 1-D sequence into a 2-D sequence of tuples for use in a Django field choices attribute >>> make_choices(range(3)) ((0, u'0'), (1, u'1'), (2, u'2')) >>> make_choices(dict(enumerate('abcd'))) ((0, u'a'), (1, u'b'), (2, u'c'), (3, u'd')) >>> make_choices('hell...
python
def make_choices(*args): """Convert a 1-D sequence into a 2-D sequence of tuples for use in a Django field choices attribute >>> make_choices(range(3)) ((0, u'0'), (1, u'1'), (2, u'2')) >>> make_choices(dict(enumerate('abcd'))) ((0, u'a'), (1, u'b'), (2, u'c'), (3, u'd')) >>> make_choices('hell...
[ "def", "make_choices", "(", "*", "args", ")", ":", "if", "not", "args", ":", "return", "tuple", "(", ")", "if", "isinstance", "(", "args", "[", "0", "]", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "make_choices", "(", "*", "tuple", ...
Convert a 1-D sequence into a 2-D sequence of tuples for use in a Django field choices attribute >>> make_choices(range(3)) ((0, u'0'), (1, u'1'), (2, u'2')) >>> make_choices(dict(enumerate('abcd'))) ((0, u'a'), (1, u'b'), (2, u'c'), (3, u'd')) >>> make_choices('hello') (('hello', u'hello'),) ...
[ "Convert", "a", "1", "-", "D", "sequence", "into", "a", "2", "-", "D", "sequence", "of", "tuples", "for", "use", "in", "a", "Django", "field", "choices", "attribute" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L153-L172
hobson/pug-dj
pug/dj/db.py
normalize_choices
def normalize_choices(db_values, field_name, app=DEFAULT_APP, model_name='', human_readable=True, none_value='Null', blank_value='Unknown', missing_value='Unknown DB Code'): '''Output the human-readable strings associated with the list of database values for a model field. Uses the trans...
python
def normalize_choices(db_values, field_name, app=DEFAULT_APP, model_name='', human_readable=True, none_value='Null', blank_value='Unknown', missing_value='Unknown DB Code'): '''Output the human-readable strings associated with the list of database values for a model field. Uses the trans...
[ "def", "normalize_choices", "(", "db_values", ",", "field_name", ",", "app", "=", "DEFAULT_APP", ",", "model_name", "=", "''", ",", "human_readable", "=", "True", ",", "none_value", "=", "'Null'", ",", "blank_value", "=", "'Unknown'", ",", "missing_value", "="...
Output the human-readable strings associated with the list of database values for a model field. Uses the translation dictionary `CHOICES_<FIELD_NAME>` attribute for the given `model_name`. In addition, translate `None` into 'Null', or whatever string is indicated by `none_value`.
[ "Output", "the", "human", "-", "readable", "strings", "associated", "with", "the", "list", "of", "database", "values", "for", "a", "model", "field", "." ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L177-L213
hobson/pug-dj
pug/dj/db.py
get_app
def get_app(app=None, verbosity=0): """Uses django.db.djmodels.get_app and fuzzywuzzy to get the models module for a django app Retrieve an app module from an app name string, even if mispelled (uses fuzzywuzzy to find the best match) To get a list of all the apps use `get_app(None)` or `get_app([]) or get...
python
def get_app(app=None, verbosity=0): """Uses django.db.djmodels.get_app and fuzzywuzzy to get the models module for a django app Retrieve an app module from an app name string, even if mispelled (uses fuzzywuzzy to find the best match) To get a list of all the apps use `get_app(None)` or `get_app([]) or get...
[ "def", "get_app", "(", "app", "=", "None", ",", "verbosity", "=", "0", ")", ":", "# print 'get_app(', app", "if", "not", "app", ":", "# for an empty list, tuple or None, just get all apps", "if", "isinstance", "(", "app", ",", "(", "type", "(", "None", ")", ",...
Uses django.db.djmodels.get_app and fuzzywuzzy to get the models module for a django app Retrieve an app module from an app name string, even if mispelled (uses fuzzywuzzy to find the best match) To get a list of all the apps use `get_app(None)` or `get_app([]) or get_app(())` To get a single random app us...
[ "Uses", "django", ".", "db", ".", "djmodels", ".", "get_app", "and", "fuzzywuzzy", "to", "get", "the", "models", "module", "for", "a", "django", "app" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L216-L267
hobson/pug-dj
pug/dj/db.py
get_model
def get_model(model=DEFAULT_MODEL, app=None, fuzziness=False): """Retrieve a Django model class for the indicated model name and app name (or module object) Args: model: A model class, queryset or string. E.g. one of: * derivative of django.db.models.base.ModelBase * derivative of django....
python
def get_model(model=DEFAULT_MODEL, app=None, fuzziness=False): """Retrieve a Django model class for the indicated model name and app name (or module object) Args: model: A model class, queryset or string. E.g. one of: * derivative of django.db.models.base.ModelBase * derivative of django....
[ "def", "get_model", "(", "model", "=", "DEFAULT_MODEL", ",", "app", "=", "None", ",", "fuzziness", "=", "False", ")", ":", "if", "isinstance", "(", "model", ",", "djmodels", ".", "base", ".", "ModelBase", ")", ":", "return", "model", "elif", "isinstance"...
Retrieve a Django model class for the indicated model name and app name (or module object) Args: model: A model class, queryset or string. E.g. one of: * derivative of django.db.models.base.ModelBase * derivative of django.db.models.query.QuerySet * string name of a django.db.models.M...
[ "Retrieve", "a", "Django", "model", "class", "for", "the", "indicated", "model", "name", "and", "app", "name", "(", "or", "module", "object", ")" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L271-L346
hobson/pug-dj
pug/dj/db.py
get_queryset
def get_queryset(qs=None, app=DEFAULT_APP, db_alias=None): """ >>> get_queryset('Permission', app='django.contrib.auth').count() > 0 True """ # app = get_app(app); # print 'get_model' + repr(model) + ' app ' + repr(app) if isinstance(qs, (djmodels.Manager, djmodels.query.QuerySet)): ...
python
def get_queryset(qs=None, app=DEFAULT_APP, db_alias=None): """ >>> get_queryset('Permission', app='django.contrib.auth').count() > 0 True """ # app = get_app(app); # print 'get_model' + repr(model) + ' app ' + repr(app) if isinstance(qs, (djmodels.Manager, djmodels.query.QuerySet)): ...
[ "def", "get_queryset", "(", "qs", "=", "None", ",", "app", "=", "DEFAULT_APP", ",", "db_alias", "=", "None", ")", ":", "# app = get_app(app);", "# print 'get_model' + repr(model) + ' app ' + repr(app)", "if", "isinstance", "(", "qs", ",", "(", "djmodels", ".", "Ma...
>>> get_queryset('Permission', app='django.contrib.auth').count() > 0 True
[ ">>>", "get_queryset", "(", "Permission", "app", "=", "django", ".", "contrib", ".", "auth", ")", ".", "count", "()", ">", "0", "True" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L349-L363
hobson/pug-dj
pug/dj/db.py
get_field
def get_field(field): """Return a field object based on a dot-delimited app.model.field name""" if isinstance(field, djmodels.fields.Field): return field elif isinstance(field, basestring): field = field.split('.') if len(field) == 3: model = get_model(app=field[0], model...
python
def get_field(field): """Return a field object based on a dot-delimited app.model.field name""" if isinstance(field, djmodels.fields.Field): return field elif isinstance(field, basestring): field = field.split('.') if len(field) == 3: model = get_model(app=field[0], model...
[ "def", "get_field", "(", "field", ")", ":", "if", "isinstance", "(", "field", ",", "djmodels", ".", "fields", ".", "Field", ")", ":", "return", "field", "elif", "isinstance", "(", "field", ",", "basestring", ")", ":", "field", "=", "field", ".", "split...
Return a field object based on a dot-delimited app.model.field name
[ "Return", "a", "field", "object", "based", "on", "a", "dot", "-", "delimited", "app", ".", "model", ".", "field", "name" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L380-L394
hobson/pug-dj
pug/dj/db.py
get_primary_key
def get_primary_key(model): """Get the name of the field in a model that has primary_key=True""" model = get_model(model) return (field.name for field in model._meta.fields if field.primary_key).next()
python
def get_primary_key(model): """Get the name of the field in a model that has primary_key=True""" model = get_model(model) return (field.name for field in model._meta.fields if field.primary_key).next()
[ "def", "get_primary_key", "(", "model", ")", ":", "model", "=", "get_model", "(", "model", ")", "return", "(", "field", ".", "name", "for", "field", "in", "model", ".", "_meta", ".", "fields", "if", "field", ".", "primary_key", ")", ".", "next", "(", ...
Get the name of the field in a model that has primary_key=True
[ "Get", "the", "name", "of", "the", "field", "in", "a", "model", "that", "has", "primary_key", "=", "True" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L397-L400
hobson/pug-dj
pug/dj/db.py
queryset_from_filter_dict
def queryset_from_filter_dict(filter_dict=None, model=None, app=None): """TODO: add fuzzy app, model and field (filter key) matching""" model = model or DEFAULT_MODEL app = app or DEFAULT_APP model = get_model(model, app) if filter_dict: return model.objects.filter(**filter_dict) re...
python
def queryset_from_filter_dict(filter_dict=None, model=None, app=None): """TODO: add fuzzy app, model and field (filter key) matching""" model = model or DEFAULT_MODEL app = app or DEFAULT_APP model = get_model(model, app) if filter_dict: return model.objects.filter(**filter_dict) re...
[ "def", "queryset_from_filter_dict", "(", "filter_dict", "=", "None", ",", "model", "=", "None", ",", "app", "=", "None", ")", ":", "model", "=", "model", "or", "DEFAULT_MODEL", "app", "=", "app", "or", "DEFAULT_APP", "model", "=", "get_model", "(", "model"...
TODO: add fuzzy app, model and field (filter key) matching
[ "TODO", ":", "add", "fuzzy", "app", "model", "and", "field", "(", "filter", "key", ")", "matching" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L470-L478
hobson/pug-dj
pug/dj/db.py
querysets_from_title_prefix
def querysets_from_title_prefix(title_prefix=None, model=DEFAULT_MODEL, app=DEFAULT_APP): """Return a list of Querysets from a list of model numbers""" if title_prefix is None: title_prefix = [None] filter_dicts = [] model_list = [] if isinstance(title_prefix, basestring): title_pr...
python
def querysets_from_title_prefix(title_prefix=None, model=DEFAULT_MODEL, app=DEFAULT_APP): """Return a list of Querysets from a list of model numbers""" if title_prefix is None: title_prefix = [None] filter_dicts = [] model_list = [] if isinstance(title_prefix, basestring): title_pr...
[ "def", "querysets_from_title_prefix", "(", "title_prefix", "=", "None", ",", "model", "=", "DEFAULT_MODEL", ",", "app", "=", "DEFAULT_APP", ")", ":", "if", "title_prefix", "is", "None", ":", "title_prefix", "=", "[", "None", "]", "filter_dicts", "=", "[", "]...
Return a list of Querysets from a list of model numbers
[ "Return", "a", "list", "of", "Querysets", "from", "a", "list", "of", "model", "numbers" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L481-L513
hobson/pug-dj
pug/dj/db.py
count_in_category
def count_in_category(x='call_type', filter_dict=None, model=DEFAULT_MODEL, app=DEFAULT_APP, sort=True, limit=1000): """ Count the number of records for each discrete (categorical) value of a field and return a dict of two lists, the field values and the counts. >>> x, y = count_in_category(x='call_type', ...
python
def count_in_category(x='call_type', filter_dict=None, model=DEFAULT_MODEL, app=DEFAULT_APP, sort=True, limit=1000): """ Count the number of records for each discrete (categorical) value of a field and return a dict of two lists, the field values and the counts. >>> x, y = count_in_category(x='call_type', ...
[ "def", "count_in_category", "(", "x", "=", "'call_type'", ",", "filter_dict", "=", "None", ",", "model", "=", "DEFAULT_MODEL", ",", "app", "=", "DEFAULT_APP", ",", "sort", "=", "True", ",", "limit", "=", "1000", ")", ":", "sort", "=", "sort_prefix", "(",...
Count the number of records for each discrete (categorical) value of a field and return a dict of two lists, the field values and the counts. >>> x, y = count_in_category(x='call_type', filter_dict={'model__startswith': 'LC60'}, limit=5, sort=1) >>> len(x) == len(y) == 5 True >>> y[1] >= y[0] True
[ "Count", "the", "number", "of", "records", "for", "each", "discrete", "(", "categorical", ")", "value", "of", "a", "field", "and", "return", "a", "dict", "of", "two", "lists", "the", "field", "values", "and", "the", "counts", "." ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L582-L612
hobson/pug-dj
pug/dj/db.py
count_in_date
def count_in_date(x='date_time', filter_dict=None, model=DEFAULT_MODEL, app=DEFAULT_APP, sort=True, limit=100000): """ Count the number of records for each discrete (categorical) value of a field and return a dict of two lists, the field values and the counts. >>> from django.db import transaction >>> ...
python
def count_in_date(x='date_time', filter_dict=None, model=DEFAULT_MODEL, app=DEFAULT_APP, sort=True, limit=100000): """ Count the number of records for each discrete (categorical) value of a field and return a dict of two lists, the field values and the counts. >>> from django.db import transaction >>> ...
[ "def", "count_in_date", "(", "x", "=", "'date_time'", ",", "filter_dict", "=", "None", ",", "model", "=", "DEFAULT_MODEL", ",", "app", "=", "DEFAULT_APP", ",", "sort", "=", "True", ",", "limit", "=", "100000", ")", ":", "sort", "=", "sort_prefix", "(", ...
Count the number of records for each discrete (categorical) value of a field and return a dict of two lists, the field values and the counts. >>> from django.db import transaction >>> transaction.rollback() >>> x, y = count_in_date(x='date', filter_dict={'model__icontains': 'LC5'}, limit=5, sort=1) >>>...
[ "Count", "the", "number", "of", "records", "for", "each", "discrete", "(", "categorical", ")", "value", "of", "a", "field", "and", "return", "a", "dict", "of", "two", "lists", "the", "field", "values", "and", "the", "counts", "." ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L615-L648
hobson/pug-dj
pug/dj/db.py
sum_in_date
def sum_in_date(x='date', y='net_sales', filter_dict=None, model='WikiItem', app=DEFAULT_APP, sort=True, limit=100000): """ Count the number of records for each discrete (categorical) value of a field and return a dict of two lists, the field values and the counts. FIXME: Tests need models with a date fiel...
python
def sum_in_date(x='date', y='net_sales', filter_dict=None, model='WikiItem', app=DEFAULT_APP, sort=True, limit=100000): """ Count the number of records for each discrete (categorical) value of a field and return a dict of two lists, the field values and the counts. FIXME: Tests need models with a date fiel...
[ "def", "sum_in_date", "(", "x", "=", "'date'", ",", "y", "=", "'net_sales'", ",", "filter_dict", "=", "None", ",", "model", "=", "'WikiItem'", ",", "app", "=", "DEFAULT_APP", ",", "sort", "=", "True", ",", "limit", "=", "100000", ")", ":", "sort", "=...
Count the number of records for each discrete (categorical) value of a field and return a dict of two lists, the field values and the counts. FIXME: Tests need models with a date field: Examples: >> x, y = sum_in_date(y='net_sales', filter_dict={'model__startswith': 'LC60'}, model='Permission', limit=5, ...
[ "Count", "the", "number", "of", "records", "for", "each", "discrete", "(", "categorical", ")", "value", "of", "a", "field", "and", "return", "a", "dict", "of", "two", "lists", "the", "field", "values", "and", "the", "counts", "." ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L651-L683
hobson/pug-dj
pug/dj/db.py
find_field_names
def find_field_names(fields, model=DEFAULT_MODEL, app=DEFAULT_APP, score_cutoff=50, pad_with_none=False): """Use fuzzy string matching to find similar model field names without consulting a synonyms list Returns: list: A list model field names (strings) sorted from most likely to least likely. []...
python
def find_field_names(fields, model=DEFAULT_MODEL, app=DEFAULT_APP, score_cutoff=50, pad_with_none=False): """Use fuzzy string matching to find similar model field names without consulting a synonyms list Returns: list: A list model field names (strings) sorted from most likely to least likely. []...
[ "def", "find_field_names", "(", "fields", ",", "model", "=", "DEFAULT_MODEL", ",", "app", "=", "DEFAULT_APP", ",", "score_cutoff", "=", "50", ",", "pad_with_none", "=", "False", ")", ":", "fields", "=", "util", ".", "listify", "(", "fields", ")", "model", ...
Use fuzzy string matching to find similar model field names without consulting a synonyms list Returns: list: A list model field names (strings) sorted from most likely to least likely. [] If no similar field names could be found in the indicated model [None] If none found and and `pad_with_n...
[ "Use", "fuzzy", "string", "matching", "to", "find", "similar", "model", "field", "names", "without", "consulting", "a", "synonyms", "list" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L709-L733
hobson/pug-dj
pug/dj/db.py
model_from_path
def model_from_path(model_path, fuzziness=False): """Find the model class for a given model path like 'project.app.model' Args: path (str): dot-delimited model path, like 'project.app.model' Returns: Django Model-based class """ app_name = '.'.join(model_path.split('.')[:-1]) m...
python
def model_from_path(model_path, fuzziness=False): """Find the model class for a given model path like 'project.app.model' Args: path (str): dot-delimited model path, like 'project.app.model' Returns: Django Model-based class """ app_name = '.'.join(model_path.split('.')[:-1]) m...
[ "def", "model_from_path", "(", "model_path", ",", "fuzziness", "=", "False", ")", ":", "app_name", "=", "'.'", ".", "join", "(", "model_path", ".", "split", "(", "'.'", ")", "[", ":", "-", "1", "]", ")", "model_name", "=", "model_path", ".", "split", ...
Find the model class for a given model path like 'project.app.model' Args: path (str): dot-delimited model path, like 'project.app.model' Returns: Django Model-based class
[ "Find", "the", "model", "class", "for", "a", "given", "model", "path", "like", "project", ".", "app", ".", "model" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L736-L760
hobson/pug-dj
pug/dj/db.py
find_synonymous_field
def find_synonymous_field(field, model=DEFAULT_MODEL, app=DEFAULT_APP, score_cutoff=50, root_preference=1.02): """Use a dictionary of synonyms and fuzzy string matching to find a similarly named field Returns: A single model field name (string) Examples: >>> find_synonymous_field('date', mode...
python
def find_synonymous_field(field, model=DEFAULT_MODEL, app=DEFAULT_APP, score_cutoff=50, root_preference=1.02): """Use a dictionary of synonyms and fuzzy string matching to find a similarly named field Returns: A single model field name (string) Examples: >>> find_synonymous_field('date', mode...
[ "def", "find_synonymous_field", "(", "field", ",", "model", "=", "DEFAULT_MODEL", ",", "app", "=", "DEFAULT_APP", ",", "score_cutoff", "=", "50", ",", "root_preference", "=", "1.02", ")", ":", "fields", "=", "util", ".", "listify", "(", "field", ")", "+", ...
Use a dictionary of synonyms and fuzzy string matching to find a similarly named field Returns: A single model field name (string) Examples: >>> find_synonymous_field('date', model='WikiItem') 'end_date_time' >>> find_synonymous_field('date', model='WikiItem') 'date_time' ...
[ "Use", "a", "dictionary", "of", "synonyms", "and", "fuzzy", "string", "matching", "to", "find", "a", "similarly", "named", "field" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L763-L789
hobson/pug-dj
pug/dj/db.py
find_model
def find_model(model_name, apps=settings.INSTALLED_APPS, fuzziness=0): """Find model_name among indicated Django apps and return Model class Examples: To find models in an app called "miner": >>> find_model('WikiItem', 'miner') >>> find_model('Connection', 'miner') >>> find_mod...
python
def find_model(model_name, apps=settings.INSTALLED_APPS, fuzziness=0): """Find model_name among indicated Django apps and return Model class Examples: To find models in an app called "miner": >>> find_model('WikiItem', 'miner') >>> find_model('Connection', 'miner') >>> find_mod...
[ "def", "find_model", "(", "model_name", ",", "apps", "=", "settings", ".", "INSTALLED_APPS", ",", "fuzziness", "=", "0", ")", ":", "# if it looks like a file system path rather than django project.app.model path the return it as a string", "if", "'/'", "in", "model_name", "...
Find model_name among indicated Django apps and return Model class Examples: To find models in an app called "miner": >>> find_model('WikiItem', 'miner') >>> find_model('Connection', 'miner') >>> find_model('InvalidModelName')
[ "Find", "model_name", "among", "indicated", "Django", "apps", "and", "return", "Model", "class" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L792-L814
hobson/pug-dj
pug/dj/db.py
find_field_name
def find_field_name(field, model=DEFAULT_MODEL, app=DEFAULT_APP, fuzziness=.5): """ >>> find_field_name('date_time', model='WikiItem') 'date' >>> find_field_name('$#!@', model='WikiItem') >>> find_field_name('date', model='WikiItem') 'end_date_time' >>> find_field_name('date', model='WikiIte...
python
def find_field_name(field, model=DEFAULT_MODEL, app=DEFAULT_APP, fuzziness=.5): """ >>> find_field_name('date_time', model='WikiItem') 'date' >>> find_field_name('$#!@', model='WikiItem') >>> find_field_name('date', model='WikiItem') 'end_date_time' >>> find_field_name('date', model='WikiIte...
[ "def", "find_field_name", "(", "field", ",", "model", "=", "DEFAULT_MODEL", ",", "app", "=", "DEFAULT_APP", ",", "fuzziness", "=", ".5", ")", ":", "return", "find_field_names", "(", "field", ",", "model", ",", "app", ",", "score_cutoff", "=", "int", "(", ...
>>> find_field_name('date_time', model='WikiItem') 'date' >>> find_field_name('$#!@', model='WikiItem') >>> find_field_name('date', model='WikiItem') 'end_date_time' >>> find_field_name('date', model='WikiItem') 'date_in_svc'
[ ">>>", "find_field_name", "(", "date_time", "model", "=", "WikiItem", ")", "date", ">>>", "find_field_name", "(", "$#!" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L817-L827
hobson/pug-dj
pug/dj/db.py
lagged_in_date
def lagged_in_date(x=None, y=None, filter_dict=None, model='WikiItem', app=DEFAULT_APP, sort=True, limit=30000, lag=1, pad=0, truncate=True): """ Lag the y values by the specified number of samples. FIXME: sort has no effect when sequences provided in x, y instead of field names >>> lagged_in_date(x=[...
python
def lagged_in_date(x=None, y=None, filter_dict=None, model='WikiItem', app=DEFAULT_APP, sort=True, limit=30000, lag=1, pad=0, truncate=True): """ Lag the y values by the specified number of samples. FIXME: sort has no effect when sequences provided in x, y instead of field names >>> lagged_in_date(x=[...
[ "def", "lagged_in_date", "(", "x", "=", "None", ",", "y", "=", "None", ",", "filter_dict", "=", "None", ",", "model", "=", "'WikiItem'", ",", "app", "=", "DEFAULT_APP", ",", "sort", "=", "True", ",", "limit", "=", "30000", ",", "lag", "=", "1", ","...
Lag the y values by the specified number of samples. FIXME: sort has no effect when sequences provided in x, y instead of field names >>> lagged_in_date(x=[.1,.2,.3,.4], y=[1,2,3,4], limit=4, lag=1) ([0.1, 0.2, 0.3, 0.4], [0, 1, 2, 3]) >>> lagged_in_date(x=[.1,.2,.3,.4], y=[1,2,3,4], lag=1, truncate=T...
[ "Lag", "the", "y", "values", "by", "the", "specified", "number", "of", "samples", "." ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L830-L861
hobson/pug-dj
pug/dj/db.py
django_object_from_row
def django_object_from_row(row, model, field_names=None, ignore_fields=('id', 'pk'), ignore_related=True, strip=True, ignore_errors=True, verbosity=0): """Construct Django model instance from values provided in a python dict or Mapping Args: row (list or dict): Data (values of any type) to be assigned to...
python
def django_object_from_row(row, model, field_names=None, ignore_fields=('id', 'pk'), ignore_related=True, strip=True, ignore_errors=True, verbosity=0): """Construct Django model instance from values provided in a python dict or Mapping Args: row (list or dict): Data (values of any type) to be assigned to...
[ "def", "django_object_from_row", "(", "row", ",", "model", ",", "field_names", "=", "None", ",", "ignore_fields", "=", "(", "'id'", ",", "'pk'", ")", ",", "ignore_related", "=", "True", ",", "strip", "=", "True", ",", "ignore_errors", "=", "True", ",", "...
Construct Django model instance from values provided in a python dict or Mapping Args: row (list or dict): Data (values of any type) to be assigned to fields in the Django object. If `row` is a list, then the column names (header row) can be provided in `field_names`. If `row` is a list and n...
[ "Construct", "Django", "model", "instance", "from", "values", "provided", "in", "a", "python", "dict", "or", "Mapping" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L1343-L1370
hobson/pug-dj
pug/dj/db.py
field_dict_from_row
def field_dict_from_row(row, model, field_names=None, ignore_fields=('id', 'pk'), strip=True, blank_none=True, ignore_related=True, ignore_values=(None,), ignore_errors=Tr...
python
def field_dict_from_row(row, model, field_names=None, ignore_fields=('id', 'pk'), strip=True, blank_none=True, ignore_related=True, ignore_values=(None,), ignore_errors=Tr...
[ "def", "field_dict_from_row", "(", "row", ",", "model", ",", "field_names", "=", "None", ",", "ignore_fields", "=", "(", "'id'", ",", "'pk'", ")", ",", "strip", "=", "True", ",", "blank_none", "=", "True", ",", "ignore_related", "=", "True", ",", "ignore...
Construct a Mapping (dict) from field names to values from a row of data Args: row (list or dict): Data (values) to be assigned to field_names in the dict. If `row` is a list, then the column names (header row) can be provided in `field_names`. If `row` is a list and no field_names are provid...
[ "Construct", "a", "Mapping", "(", "dict", ")", "from", "field", "names", "to", "values", "from", "a", "row", "of", "data" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L1373-L1484
hobson/pug-dj
pug/dj/db.py
count_lines
def count_lines(fname, mode='rU'): '''Count the number of lines in a file Only faster way would be to utilize multiple processor cores to perform parallel reads. http://stackoverflow.com/q/845058/623735 ''' with open(fname, mode) as f: for i, l in enumerate(f): pass return ...
python
def count_lines(fname, mode='rU'): '''Count the number of lines in a file Only faster way would be to utilize multiple processor cores to perform parallel reads. http://stackoverflow.com/q/845058/623735 ''' with open(fname, mode) as f: for i, l in enumerate(f): pass return ...
[ "def", "count_lines", "(", "fname", ",", "mode", "=", "'rU'", ")", ":", "with", "open", "(", "fname", ",", "mode", ")", "as", "f", ":", "for", "i", ",", "l", "in", "enumerate", "(", "f", ")", ":", "pass", "return", "i", "+", "1" ]
Count the number of lines in a file Only faster way would be to utilize multiple processor cores to perform parallel reads. http://stackoverflow.com/q/845058/623735
[ "Count", "the", "number", "of", "lines", "in", "a", "file" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L1487-L1497
hobson/pug-dj
pug/dj/db.py
clear_model
def clear_model(model, dry_run=True, verbosity=1): '''Delete all data records in a model, obeying `clear`, `dry_run`, and `verbosity` flags If a clear was requested (dry_run or otherwise), return the number of records deleted (# before minus # after) ''' N_existing = model.objects.count() if dr...
python
def clear_model(model, dry_run=True, verbosity=1): '''Delete all data records in a model, obeying `clear`, `dry_run`, and `verbosity` flags If a clear was requested (dry_run or otherwise), return the number of records deleted (# before minus # after) ''' N_existing = model.objects.count() if dr...
[ "def", "clear_model", "(", "model", ",", "dry_run", "=", "True", ",", "verbosity", "=", "1", ")", ":", "N_existing", "=", "model", ".", "objects", ".", "count", "(", ")", "if", "dry_run", ":", "print", "\"DRY_RUN: NOT deleting %d records in %r.\"", "%", "(",...
Delete all data records in a model, obeying `clear`, `dry_run`, and `verbosity` flags If a clear was requested (dry_run or otherwise), return the number of records deleted (# before minus # after)
[ "Delete", "all", "data", "records", "in", "a", "model", "obeying", "clear", "dry_run", "and", "verbosity", "flags", "If", "a", "clear", "was", "requested", "(", "dry_run", "or", "otherwise", ")", "return", "the", "number", "of", "records", "deleted", "(", ...
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L1500-L1515
hobson/pug-dj
pug/dj/db.py
load_csv_to_model
def load_csv_to_model(path, model, field_names=None, delimiter=None, batch_len=10000, dialect=None, num_header_rows=1, mode='rUb', strip=True, clear=False, dry_run=True, ignore_errors=True, verbosity=2): '''Bulk create database records from batches of rows in a csv file....
python
def load_csv_to_model(path, model, field_names=None, delimiter=None, batch_len=10000, dialect=None, num_header_rows=1, mode='rUb', strip=True, clear=False, dry_run=True, ignore_errors=True, verbosity=2): '''Bulk create database records from batches of rows in a csv file....
[ "def", "load_csv_to_model", "(", "path", ",", "model", ",", "field_names", "=", "None", ",", "delimiter", "=", "None", ",", "batch_len", "=", "10000", ",", "dialect", "=", "None", ",", "num_header_rows", "=", "1", ",", "mode", "=", "'rUb'", ",", "strip",...
Bulk create database records from batches of rows in a csv file.
[ "Bulk", "create", "database", "records", "from", "batches", "of", "rows", "in", "a", "csv", "file", "." ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L1518-L1612
hobson/pug-dj
pug/dj/db.py
path_size
def path_size(path, total=False, ext='', level=None, verbosity=0): """Walk the file tree and query the file.stat object(s) to compute their total (or individual) size in bytes Returns: dict: {relative_path: file_size_in_bytes, ...} Examples: >>> all(d >= 0 for d in path_size(__file__).values()...
python
def path_size(path, total=False, ext='', level=None, verbosity=0): """Walk the file tree and query the file.stat object(s) to compute their total (or individual) size in bytes Returns: dict: {relative_path: file_size_in_bytes, ...} Examples: >>> all(d >= 0 for d in path_size(__file__).values()...
[ "def", "path_size", "(", "path", ",", "total", "=", "False", ",", "ext", "=", "''", ",", "level", "=", "None", ",", "verbosity", "=", "0", ")", ":", "dict_of_path_sizes", "=", "dict", "(", "(", "d", "[", "'path'", "]", ",", "d", "[", "'size'", "]...
Walk the file tree and query the file.stat object(s) to compute their total (or individual) size in bytes Returns: dict: {relative_path: file_size_in_bytes, ...} Examples: >>> all(d >= 0 for d in path_size(__file__).values()) True >>> sum(path_size(os.path.dirname(__file__)).values()) ...
[ "Walk", "the", "file", "tree", "and", "query", "the", "file", ".", "stat", "object", "(", "s", ")", "to", "compute", "their", "total", "(", "or", "individual", ")", "size", "in", "bytes" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L1616-L1635
hobson/pug-dj
pug/dj/db.py
write_queryset_to_csv
def write_queryset_to_csv(qs, filename): """Write a QuerySet or ValuesListQuerySet to a CSV file based on djangosnippets by zbyte64 and http://palewi.re Arguments: qs (QuerySet or ValuesListQuerySet): The records your want to write to a text file (UTF-8) filename (str): full path and file ...
python
def write_queryset_to_csv(qs, filename): """Write a QuerySet or ValuesListQuerySet to a CSV file based on djangosnippets by zbyte64 and http://palewi.re Arguments: qs (QuerySet or ValuesListQuerySet): The records your want to write to a text file (UTF-8) filename (str): full path and file ...
[ "def", "write_queryset_to_csv", "(", "qs", ",", "filename", ")", ":", "model", "=", "qs", ".", "model", "with", "open", "(", "filename", ",", "'w'", ")", "as", "fp", ":", "writer", "=", "csv", ".", "writer", "(", "fp", ")", "try", ":", "headers", "...
Write a QuerySet or ValuesListQuerySet to a CSV file based on djangosnippets by zbyte64 and http://palewi.re Arguments: qs (QuerySet or ValuesListQuerySet): The records your want to write to a text file (UTF-8) filename (str): full path and file name to write to
[ "Write", "a", "QuerySet", "or", "ValuesListQuerySet", "to", "a", "CSV", "file" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L1638-L1670
hobson/pug-dj
pug/dj/db.py
load_all_csvs_to_model
def load_all_csvs_to_model(path, model, field_names=None, delimiter=None, batch_len=10000, dialect=None, num_header_rows=1, mode='rUb', strip=True, clear=False, dry_run=True, ignore_errors=True, sort_files=True, recursive=False, ext='', ...
python
def load_all_csvs_to_model(path, model, field_names=None, delimiter=None, batch_len=10000, dialect=None, num_header_rows=1, mode='rUb', strip=True, clear=False, dry_run=True, ignore_errors=True, sort_files=True, recursive=False, ext='', ...
[ "def", "load_all_csvs_to_model", "(", "path", ",", "model", ",", "field_names", "=", "None", ",", "delimiter", "=", "None", ",", "batch_len", "=", "10000", ",", "dialect", "=", "None", ",", "num_header_rows", "=", "1", ",", "mode", "=", "'rUb'", ",", "st...
Bulk create database records from all csv files found within a directory.
[ "Bulk", "create", "database", "records", "from", "all", "csv", "files", "found", "within", "a", "directory", "." ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L1673-L1731
hobson/pug-dj
pug/dj/db.py
dataframe_from_excel
def dataframe_from_excel(path, sheetname=0, header=0, skiprows=None): # , parse_dates=False): """Thin wrapper for pandas.io.excel.read_excel() that accepts a file path and sheet index/name Arguments: path (str): file or folder to retrieve CSV files and `pandas.DataFrame`s from ext (str): file name...
python
def dataframe_from_excel(path, sheetname=0, header=0, skiprows=None): # , parse_dates=False): """Thin wrapper for pandas.io.excel.read_excel() that accepts a file path and sheet index/name Arguments: path (str): file or folder to retrieve CSV files and `pandas.DataFrame`s from ext (str): file name...
[ "def", "dataframe_from_excel", "(", "path", ",", "sheetname", "=", "0", ",", "header", "=", "0", ",", "skiprows", "=", "None", ")", ":", "# , parse_dates=False):", "sheetname", "=", "sheetname", "or", "0", "if", "isinstance", "(", "sheetname", ",", "(", "b...
Thin wrapper for pandas.io.excel.read_excel() that accepts a file path and sheet index/name Arguments: path (str): file or folder to retrieve CSV files and `pandas.DataFrame`s from ext (str): file name extension (to filter files by) date_parser (function): if the MultiIndex can be interpretted as...
[ "Thin", "wrapper", "for", "pandas", ".", "io", ".", "excel", ".", "read_excel", "()", "that", "accepts", "a", "file", "path", "and", "sheet", "index", "/", "name" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L1737-L1761
hobson/pug-dj
pug/dj/db.py
make_date
def make_date(dt, date_parser=parse_date): """Coerce a datetime or string into datetime.date object Arguments: dt (str or datetime.datetime or atetime.time or numpy.Timestamp): time or date to be coerced into a `datetime.time` object Returns: datetime.time: Time of day portion of a `d...
python
def make_date(dt, date_parser=parse_date): """Coerce a datetime or string into datetime.date object Arguments: dt (str or datetime.datetime or atetime.time or numpy.Timestamp): time or date to be coerced into a `datetime.time` object Returns: datetime.time: Time of day portion of a `d...
[ "def", "make_date", "(", "dt", ",", "date_parser", "=", "parse_date", ")", ":", "if", "not", "dt", ":", "return", "datetime", ".", "date", "(", "1970", ",", "1", ",", "1", ")", "if", "isinstance", "(", "dt", ",", "basestring", ")", ":", "dt", "=", ...
Coerce a datetime or string into datetime.date object Arguments: dt (str or datetime.datetime or atetime.time or numpy.Timestamp): time or date to be coerced into a `datetime.time` object Returns: datetime.time: Time of day portion of a `datetime` string or object >>> make_date('') ...
[ "Coerce", "a", "datetime", "or", "string", "into", "datetime", ".", "date", "object" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L1764-L1791
hobson/pug-dj
pug/dj/db.py
make_time
def make_time(dt, date_parser=parse_date): """Ignore date information in a datetime string or object Arguments: dt (str or datetime.datetime or atetime.time or numpy.Timestamp): time or date to be coerced into a `datetime.time` object Returns: datetime.time: Time of day portion of a `...
python
def make_time(dt, date_parser=parse_date): """Ignore date information in a datetime string or object Arguments: dt (str or datetime.datetime or atetime.time or numpy.Timestamp): time or date to be coerced into a `datetime.time` object Returns: datetime.time: Time of day portion of a `...
[ "def", "make_time", "(", "dt", ",", "date_parser", "=", "parse_date", ")", ":", "if", "not", "dt", ":", "return", "datetime", ".", "time", "(", "0", ",", "0", ")", "if", "isinstance", "(", "dt", ",", "basestring", ")", ":", "try", ":", "dt", "=", ...
Ignore date information in a datetime string or object Arguments: dt (str or datetime.datetime or atetime.time or numpy.Timestamp): time or date to be coerced into a `datetime.time` object Returns: datetime.time: Time of day portion of a `datetime` string or object >>> make_time(None...
[ "Ignore", "date", "information", "in", "a", "datetime", "string", "or", "object" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L1794-L1824
hobson/pug-dj
pug/dj/db.py
flatten_dataframe
def flatten_dataframe(df, date_parser=parse_date, verbosity=0): """Creates 1-D timeseries (pandas.Series) coercing column labels into datetime.time objects Assumes that the columns are strings representing times of day (or datetime.time objects) Assumes that the index should be a datetime object. If it isn...
python
def flatten_dataframe(df, date_parser=parse_date, verbosity=0): """Creates 1-D timeseries (pandas.Series) coercing column labels into datetime.time objects Assumes that the columns are strings representing times of day (or datetime.time objects) Assumes that the index should be a datetime object. If it isn...
[ "def", "flatten_dataframe", "(", "df", ",", "date_parser", "=", "parse_date", ",", "verbosity", "=", "0", ")", ":", "# extract rows with nonull, nonnan index values", "df", "=", "df", "[", "pd", ".", "notnull", "(", "df", ".", "index", ")", "]", "# Make sure c...
Creates 1-D timeseries (pandas.Series) coercing column labels into datetime.time objects Assumes that the columns are strings representing times of day (or datetime.time objects) Assumes that the index should be a datetime object. If it isn't already, the first column with "date" (case insenstive) in its l...
[ "Creates", "1", "-", "D", "timeseries", "(", "pandas", ".", "Series", ")", "coercing", "column", "labels", "into", "datetime", ".", "time", "objects" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L1827-L1912
hobson/pug-dj
pug/dj/db.py
flatten_excel
def flatten_excel(path='.', ext='xlsx', sheetname=0, skiprows=None, header=0, date_parser=parse_date, verbosity=0, output_ext=None): """Load all Excel files in the given path, write .flat.csv files, return `DataFrame` dict Arguments: path (str): file or folder to retrieve CSV files and `pandas.DataFrame`...
python
def flatten_excel(path='.', ext='xlsx', sheetname=0, skiprows=None, header=0, date_parser=parse_date, verbosity=0, output_ext=None): """Load all Excel files in the given path, write .flat.csv files, return `DataFrame` dict Arguments: path (str): file or folder to retrieve CSV files and `pandas.DataFrame`...
[ "def", "flatten_excel", "(", "path", "=", "'.'", ",", "ext", "=", "'xlsx'", ",", "sheetname", "=", "0", ",", "skiprows", "=", "None", ",", "header", "=", "0", ",", "date_parser", "=", "parse_date", ",", "verbosity", "=", "0", ",", "output_ext", "=", ...
Load all Excel files in the given path, write .flat.csv files, return `DataFrame` dict Arguments: path (str): file or folder to retrieve CSV files and `pandas.DataFrame`s from ext (str): file name extension (to filter files by) date_parser (function): if the MultiIndex can be interpretted as a da...
[ "Load", "all", "Excel", "files", "in", "the", "given", "path", "write", ".", "flat", ".", "csv", "files", "return", "DataFrame", "dict" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L1915-L1941
hobson/pug-dj
pug/dj/db.py
hash_model_values
def hash_model_values(model, clear=True, hash_field='values_hash', hash_fun=hash, ignore_pk=True, ignore_fields=[]): """Hash values of DB table records to facilitate tracking changes to the DB table Intended for comparing records in one table to those in another (with potentially differing id/pk values) Fo...
python
def hash_model_values(model, clear=True, hash_field='values_hash', hash_fun=hash, ignore_pk=True, ignore_fields=[]): """Hash values of DB table records to facilitate tracking changes to the DB table Intended for comparing records in one table to those in another (with potentially differing id/pk values) Fo...
[ "def", "hash_model_values", "(", "model", ",", "clear", "=", "True", ",", "hash_field", "=", "'values_hash'", ",", "hash_fun", "=", "hash", ",", "ignore_pk", "=", "True", ",", "ignore_fields", "=", "[", "]", ")", ":", "qs", "=", "getattr", "(", "model", ...
Hash values of DB table records to facilitate tracking changes to the DB table Intended for comparing records in one table to those in another (with potentially differing id/pk values) For example, changes to a table in a read-only MS SQL database can be quickly identified and mirrored to a writeable PostG...
[ "Hash", "values", "of", "DB", "table", "records", "to", "facilitate", "tracking", "changes", "to", "the", "DB", "table" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L1982-L2000
hobson/pug-dj
pug/dj/db.py
import_items
def import_items(item_seq, dest_model, batch_len=500, clear=False, dry_run=True, start_batch=0, end_batch=None, overwrite=True, run_update=False, ignore_related=True, ignore_errors=False, verbosity=1): """Import a sequence (que...
python
def import_items(item_seq, dest_model, batch_len=500, clear=False, dry_run=True, start_batch=0, end_batch=None, overwrite=True, run_update=False, ignore_related=True, ignore_errors=False, verbosity=1): """Import a sequence (que...
[ "def", "import_items", "(", "item_seq", ",", "dest_model", ",", "batch_len", "=", "500", ",", "clear", "=", "False", ",", "dry_run", "=", "True", ",", "start_batch", "=", "0", ",", "end_batch", "=", "None", ",", "overwrite", "=", "True", ",", "run_update...
Import a sequence (queryset.values(), generator, tuple, list) of dicts into the given model
[ "Import", "a", "sequence", "(", "queryset", ".", "values", "()", "generator", "tuple", "list", ")", "of", "dicts", "into", "the", "given", "model" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L2034-L2192
hobson/pug-dj
pug/dj/db.py
update_items
def update_items(item_seq, batch_len=500, dry_run=True, start_batch=0, end_batch=None, ignore_errors=False, verbosity=1): """Given a sequence (queryset, generator, tuple, list) of dicts run the _update method on them and do bulk_update""" stats = collections.Counter() try: try: src_qs =...
python
def update_items(item_seq, batch_len=500, dry_run=True, start_batch=0, end_batch=None, ignore_errors=False, verbosity=1): """Given a sequence (queryset, generator, tuple, list) of dicts run the _update method on them and do bulk_update""" stats = collections.Counter() try: try: src_qs =...
[ "def", "update_items", "(", "item_seq", ",", "batch_len", "=", "500", ",", "dry_run", "=", "True", ",", "start_batch", "=", "0", ",", "end_batch", "=", "None", ",", "ignore_errors", "=", "False", ",", "verbosity", "=", "1", ")", ":", "stats", "=", "col...
Given a sequence (queryset, generator, tuple, list) of dicts run the _update method on them and do bulk_update
[ "Given", "a", "sequence", "(", "queryset", "generator", "tuple", "list", ")", "of", "dicts", "run", "the", "_update", "method", "on", "them", "and", "do", "bulk_update" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L2195-L2274
hobson/pug-dj
pug/dj/db.py
import_queryset_batches
def import_queryset_batches(qs, dest_qs, batch_len=500, clear=None, dry_run=True, verbosity=1): """Given a sequence (queryset, generator, tuple, list) of dicts import them into the given model FIXME: How is this differenct from import_items above? clear = model or queryset to be deleted/cleared ...
python
def import_queryset_batches(qs, dest_qs, batch_len=500, clear=None, dry_run=True, verbosity=1): """Given a sequence (queryset, generator, tuple, list) of dicts import them into the given model FIXME: How is this differenct from import_items above? clear = model or queryset to be deleted/cleared ...
[ "def", "import_queryset_batches", "(", "qs", ",", "dest_qs", ",", "batch_len", "=", "500", ",", "clear", "=", "None", ",", "dry_run", "=", "True", ",", "verbosity", "=", "1", ")", ":", "qs", "=", "get_queryset", "(", "qs", ")", "dest_qs", "=", "get_que...
Given a sequence (queryset, generator, tuple, list) of dicts import them into the given model FIXME: How is this differenct from import_items above? clear = model or queryset to be deleted/cleared False: do not clear/delete anything None: clear/delete the dest_qs True: clear all recor...
[ "Given", "a", "sequence", "(", "queryset", "generator", "tuple", "list", ")", "of", "dicts", "import", "them", "into", "the", "given", "model" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L2277-L2340
hobson/pug-dj
pug/dj/db.py
import_queryset
def import_queryset(qs, dest_model, clear=False, dry_run=True, verbosity=1): """Given a sequence (queryset, generator, tuple, list) of dicts import them into the given model""" # # FIXME: use this info to connect relationships, ignoring missing targets (unlike manage.py loaddata) # fields = dest_model._me...
python
def import_queryset(qs, dest_model, clear=False, dry_run=True, verbosity=1): """Given a sequence (queryset, generator, tuple, list) of dicts import them into the given model""" # # FIXME: use this info to connect relationships, ignoring missing targets (unlike manage.py loaddata) # fields = dest_model._me...
[ "def", "import_queryset", "(", "qs", ",", "dest_model", ",", "clear", "=", "False", ",", "dry_run", "=", "True", ",", "verbosity", "=", "1", ")", ":", "# # FIXME: use this info to connect relationships, ignoring missing targets (unlike manage.py loaddata)", "# fields = dest...
Given a sequence (queryset, generator, tuple, list) of dicts import them into the given model
[ "Given", "a", "sequence", "(", "queryset", "generator", "tuple", "list", ")", "of", "dicts", "import", "them", "into", "the", "given", "model" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L2344-L2381
hobson/pug-dj
pug/dj/db.py
import_json
def import_json(path, model, batch_len=100, db_alias='default', start_batch=0, end_batch=None, ignore_errors=False, verbosity=2): """Read json file (not in django fixture format) and create the appropriate records using the provided database model.""" # TODO: use a generator to save memory for large json files...
python
def import_json(path, model, batch_len=100, db_alias='default', start_batch=0, end_batch=None, ignore_errors=False, verbosity=2): """Read json file (not in django fixture format) and create the appropriate records using the provided database model.""" # TODO: use a generator to save memory for large json files...
[ "def", "import_json", "(", "path", ",", "model", ",", "batch_len", "=", "100", ",", "db_alias", "=", "'default'", ",", "start_batch", "=", "0", ",", "end_batch", "=", "None", ",", "ignore_errors", "=", "False", ",", "verbosity", "=", "2", ")", ":", "# ...
Read json file (not in django fixture format) and create the appropriate records using the provided database model.
[ "Read", "json", "file", "(", "not", "in", "django", "fixture", "format", ")", "and", "create", "the", "appropriate", "records", "using", "the", "provided", "database", "model", "." ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L2545-L2554
hobson/pug-dj
pug/dj/db.py
bulk_update
def bulk_update(object_list, ignore_errors=False, delete_first=False, verbosity=0): '''Bulk_create objects in provided list of model instances, delete database rows for the original pks in the object list. Returns any delta in the number of rows in the database table that resulted from the update. If nonze...
python
def bulk_update(object_list, ignore_errors=False, delete_first=False, verbosity=0): '''Bulk_create objects in provided list of model instances, delete database rows for the original pks in the object list. Returns any delta in the number of rows in the database table that resulted from the update. If nonze...
[ "def", "bulk_update", "(", "object_list", ",", "ignore_errors", "=", "False", ",", "delete_first", "=", "False", ",", "verbosity", "=", "0", ")", ":", "if", "not", "object_list", ":", "return", "0", "model", "=", "object_list", "[", "0", "]", ".", "__cla...
Bulk_create objects in provided list of model instances, delete database rows for the original pks in the object list. Returns any delta in the number of rows in the database table that resulted from the update. If nonzero, an error has likely occurred and database integrity is suspect. # delete_first = T...
[ "Bulk_create", "objects", "in", "provided", "list", "of", "model", "instances", "delete", "database", "rows", "for", "the", "original", "pks", "in", "the", "object", "list", "." ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L2561-L2614
hobson/pug-dj
pug/dj/db.py
generate_queryset_batches
def generate_queryset_batches(queryset, batch_len=1000, verbosity=1): """Filter a queryset by the pk in such a way that no batch is larger than the requested batch_len SEE ALSO: pug.nlp.util.generate_slices >>> from miner.models import TestModel >>> sum(len(list(batch)) for batch in generate_queryset_...
python
def generate_queryset_batches(queryset, batch_len=1000, verbosity=1): """Filter a queryset by the pk in such a way that no batch is larger than the requested batch_len SEE ALSO: pug.nlp.util.generate_slices >>> from miner.models import TestModel >>> sum(len(list(batch)) for batch in generate_queryset_...
[ "def", "generate_queryset_batches", "(", "queryset", ",", "batch_len", "=", "1000", ",", "verbosity", "=", "1", ")", ":", "if", "batch_len", "==", "1", ":", "for", "obj", "in", "queryset", ":", "yield", "obj", "N", "=", "queryset", ".", "count", "(", "...
Filter a queryset by the pk in such a way that no batch is larger than the requested batch_len SEE ALSO: pug.nlp.util.generate_slices >>> from miner.models import TestModel >>> sum(len(list(batch)) for batch in generate_queryset_batches(TestModel, batch_len=7)) == TestModel.objects.count() True
[ "Filter", "a", "queryset", "by", "the", "pk", "in", "such", "a", "way", "that", "no", "batch", "is", "larger", "than", "the", "requested", "batch_len" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L2617-L2673
hobson/pug-dj
pug/dj/db.py
optimize_filter_dict
def optimize_filter_dict(filter_dict, trgm=True): """Improve query speed for a Django queryset `filter` or `exclude` kwargs dict WARNING: Wtthout `trgm`, this only improves the speed of exclude filters by 0.4% Arguments: filter_dict (dict): kwargs for Django ORM queryset `filter` and `exclude` quer...
python
def optimize_filter_dict(filter_dict, trgm=True): """Improve query speed for a Django queryset `filter` or `exclude` kwargs dict WARNING: Wtthout `trgm`, this only improves the speed of exclude filters by 0.4% Arguments: filter_dict (dict): kwargs for Django ORM queryset `filter` and `exclude` quer...
[ "def", "optimize_filter_dict", "(", "filter_dict", ",", "trgm", "=", "True", ")", ":", "optimized", "=", "{", "}", "for", "k", ",", "v", "in", "filter_dict", ".", "iteritems", "(", ")", ":", "if", "k", ".", "endswith", "(", "'__in'", ")", ":", "v", ...
Improve query speed for a Django queryset `filter` or `exclude` kwargs dict WARNING: Wtthout `trgm`, this only improves the speed of exclude filters by 0.4% Arguments: filter_dict (dict): kwargs for Django ORM queryset `filter` and `exclude` queries trgm (bool): whether to assume the Django ORM t...
[ "Improve", "query", "speed", "for", "a", "Django", "queryset", "filter", "or", "exclude", "kwargs", "dict" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L2739-L2778
hobson/pug-dj
pug/dj/db.py
clean_filter_dict
def clean_filter_dict(filter_dict, strip=False): '''Clear/del Django ORM filter kwargs dict queries like `filter({"<field>__in": member_list` where `member_list` is empty Brute force processing of user-entered lists of query parameters can often produce null `__in` filters which will return no results if...
python
def clean_filter_dict(filter_dict, strip=False): '''Clear/del Django ORM filter kwargs dict queries like `filter({"<field>__in": member_list` where `member_list` is empty Brute force processing of user-entered lists of query parameters can often produce null `__in` filters which will return no results if...
[ "def", "clean_filter_dict", "(", "filter_dict", ",", "strip", "=", "False", ")", ":", "if", "not", "strip", ":", "strip", "=", "lambda", "s", ":", "s", "elif", "not", "callable", "(", "strip", ")", ":", "strip", "=", "lambda", "s", ":", "str", "(", ...
Clear/del Django ORM filter kwargs dict queries like `filter({"<field>__in": member_list` where `member_list` is empty Brute force processing of user-entered lists of query parameters can often produce null `__in` filters which will return no results if not "cleaned" by deleting these dict entries. Simil...
[ "Clear", "/", "del", "Django", "ORM", "filter", "kwargs", "dict", "queries", "like", "filter", "(", "{", "<field", ">", "__in", ":", "member_list", "where", "member_list", "is", "empty" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L2781-L2819
hobson/pug-dj
pug/dj/db.py
dump_json
def dump_json(model, batch_len=200000, use_natural_keys=True, verbosity=1): """Dump database records to .json Django fixture file, one file for each batch of `batch_len` records Files are suitable for loading with "python manage.py loaddata folder_name_containing_files/*". """ model = get_model(model) ...
python
def dump_json(model, batch_len=200000, use_natural_keys=True, verbosity=1): """Dump database records to .json Django fixture file, one file for each batch of `batch_len` records Files are suitable for loading with "python manage.py loaddata folder_name_containing_files/*". """ model = get_model(model) ...
[ "def", "dump_json", "(", "model", ",", "batch_len", "=", "200000", ",", "use_natural_keys", "=", "True", ",", "verbosity", "=", "1", ")", ":", "model", "=", "get_model", "(", "model", ")", "N", "=", "model", ".", "objects", ".", "count", "(", ")", "i...
Dump database records to .json Django fixture file, one file for each batch of `batch_len` records Files are suitable for loading with "python manage.py loaddata folder_name_containing_files/*".
[ "Dump", "database", "records", "to", ".", "json", "Django", "fixture", "file", "one", "file", "for", "each", "batch", "of", "batch_len", "records" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L2822-L2846
hobson/pug-dj
pug/dj/db.py
filter_exclude_dicts
def filter_exclude_dicts(filter_dict=None, exclude_dict=None, name='acctno', values=[], swap=False): """Produces kwargs dicts for Django Queryset `filter` and `exclude` from a list of values The last, critical step in generating Django ORM kwargs dicts from a natural language query. Properly parses "NOT" u...
python
def filter_exclude_dicts(filter_dict=None, exclude_dict=None, name='acctno', values=[], swap=False): """Produces kwargs dicts for Django Queryset `filter` and `exclude` from a list of values The last, critical step in generating Django ORM kwargs dicts from a natural language query. Properly parses "NOT" u...
[ "def", "filter_exclude_dicts", "(", "filter_dict", "=", "None", ",", "exclude_dict", "=", "None", ",", "name", "=", "'acctno'", ",", "values", "=", "[", "]", ",", "swap", "=", "False", ")", ":", "filter_dict", "=", "filter_dict", "or", "{", "}", "exclude...
Produces kwargs dicts for Django Queryset `filter` and `exclude` from a list of values The last, critical step in generating Django ORM kwargs dicts from a natural language query. Properly parses "NOT" unary operators on each field value in the list. Assumes the lists have been pre-processed to consolidate...
[ "Produces", "kwargs", "dicts", "for", "Django", "Queryset", "filter", "and", "exclude", "from", "a", "list", "of", "values" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L2849-L2876
hobson/pug-dj
pug/dj/db.py
Columns.process_kwargs
def process_kwargs(self, kwargs, prefix='default_', delete=True): """ set self attributes based on kwargs, optionally deleting kwargs that are processed """ processed = [] for k in kwargs: if hasattr(self, prefix + k): processed += [k] ...
python
def process_kwargs(self, kwargs, prefix='default_', delete=True): """ set self attributes based on kwargs, optionally deleting kwargs that are processed """ processed = [] for k in kwargs: if hasattr(self, prefix + k): processed += [k] ...
[ "def", "process_kwargs", "(", "self", ",", "kwargs", ",", "prefix", "=", "'default_'", ",", "delete", "=", "True", ")", ":", "processed", "=", "[", "]", "for", "k", "in", "kwargs", ":", "if", "hasattr", "(", "self", ",", "prefix", "+", "k", ")", ":...
set self attributes based on kwargs, optionally deleting kwargs that are processed
[ "set", "self", "attributes", "based", "on", "kwargs", "optionally", "deleting", "kwargs", "that", "are", "processed" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L1105-L1116
hobson/pug-dj
pug/dj/db.py
Columns.from_row_wise_lists
def from_row_wise_lists(self, lol, header_rows=0, transpose=False, names=None): """Create column-wise Columns object from a row-wise table (list of lists). Useful for reading a CSV file.""" #print '-'*10 #super(Columns, self).__init__() self.clear() #print(list(self)) ...
python
def from_row_wise_lists(self, lol, header_rows=0, transpose=False, names=None): """Create column-wise Columns object from a row-wise table (list of lists). Useful for reading a CSV file.""" #print '-'*10 #super(Columns, self).__init__() self.clear() #print(list(self)) ...
[ "def", "from_row_wise_lists", "(", "self", ",", "lol", ",", "header_rows", "=", "0", ",", "transpose", "=", "False", ",", "names", "=", "None", ")", ":", "#print '-'*10", "#super(Columns, self).__init__()", "self", ".", "clear", "(", ")", "#print(list(self))", ...
Create column-wise Columns object from a row-wise table (list of lists). Useful for reading a CSV file.
[ "Create", "column", "-", "wise", "Columns", "object", "from", "a", "row", "-", "wise", "table", "(", "list", "of", "lists", ")", "." ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L1185-L1223
hobson/pug-dj
pug/dj/db.py
Columns.from_column_wise_lists
def from_column_wise_lists(self, lol, header_rows=0, transpose=False, names=None): """Create column-wise Columns object from a row-wise table (list of lists). """ #super(Columns, self).__init__() self.clear() self.len_column = None if transpose: return self.f...
python
def from_column_wise_lists(self, lol, header_rows=0, transpose=False, names=None): """Create column-wise Columns object from a row-wise table (list of lists). """ #super(Columns, self).__init__() self.clear() self.len_column = None if transpose: return self.f...
[ "def", "from_column_wise_lists", "(", "self", ",", "lol", ",", "header_rows", "=", "0", ",", "transpose", "=", "False", ",", "names", "=", "None", ")", ":", "#super(Columns, self).__init__()", "self", ".", "clear", "(", ")", "self", ".", "len_column", "=", ...
Create column-wise Columns object from a row-wise table (list of lists).
[ "Create", "column", "-", "wise", "Columns", "object", "from", "a", "row", "-", "wise", "table", "(", "list", "of", "lists", ")", "." ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L1225-L1238
hobson/pug-dj
pug/dj/db.py
Columns.as_column_wise_lists
def as_column_wise_lists(self, transpose=False): """Generator over the columns of lists""" # make this a generator of generators? if transpose: ans = self.from_row_wise_lists(self.as_column_wise_lists(transpose=False)) return ans #print self return self.va...
python
def as_column_wise_lists(self, transpose=False): """Generator over the columns of lists""" # make this a generator of generators? if transpose: ans = self.from_row_wise_lists(self.as_column_wise_lists(transpose=False)) return ans #print self return self.va...
[ "def", "as_column_wise_lists", "(", "self", ",", "transpose", "=", "False", ")", ":", "# make this a generator of generators?", "if", "transpose", ":", "ans", "=", "self", ".", "from_row_wise_lists", "(", "self", ".", "as_column_wise_lists", "(", "transpose", "=", ...
Generator over the columns of lists
[ "Generator", "over", "the", "columns", "of", "lists" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L1257-L1264
hobson/pug-dj
pug/dj/db.py
Columns.pierson
def pierson(self, ddof=0): """Matrix of pierson linear correlation coefficients (rho values) for each pair of columns https://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient >>> Columns([[1, 2, 3], [4, 5, 6]]).pierson() [[1.0, 1.0], [1.0, 1.0]] >>> Columns([...
python
def pierson(self, ddof=0): """Matrix of pierson linear correlation coefficients (rho values) for each pair of columns https://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient >>> Columns([[1, 2, 3], [4, 5, 6]]).pierson() [[1.0, 1.0], [1.0, 1.0]] >>> Columns([...
[ "def", "pierson", "(", "self", ",", "ddof", "=", "0", ")", ":", "C", "=", "self", ".", "cov", "(", "ddof", "=", "ddof", ")", "rho", "=", "[", "]", "N", "=", "len", "(", "C", ")", "for", "i", "in", "range", "(", "N", ")", ":", "rho", "+=",...
Matrix of pierson linear correlation coefficients (rho values) for each pair of columns https://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient >>> Columns([[1, 2, 3], [4, 5, 6]]).pierson() [[1.0, 1.0], [1.0, 1.0]] >>> Columns([[1, 2, 3], [2.5, 3.5, 4.5]], transpose...
[ "Matrix", "of", "pierson", "linear", "correlation", "coefficients", "(", "rho", "values", ")", "for", "each", "pair", "of", "columns" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L1294-L1314
nabeen/gdwrap
gdwrap/Gdwrap.py
Gdwrap.file_list
def file_list(self, page_size: int, fields: str, order_by: str, query: str) -> dict: """ Get file list from Google Drive :param page_size: :param fields: :param order_by: :param query: :return: """ service = self.__get_service() results = s...
python
def file_list(self, page_size: int, fields: str, order_by: str, query: str) -> dict: """ Get file list from Google Drive :param page_size: :param fields: :param order_by: :param query: :return: """ service = self.__get_service() results = s...
[ "def", "file_list", "(", "self", ",", "page_size", ":", "int", ",", "fields", ":", "str", ",", "order_by", ":", "str", ",", "query", ":", "str", ")", "->", "dict", ":", "service", "=", "self", ".", "__get_service", "(", ")", "results", "=", "service"...
Get file list from Google Drive :param page_size: :param fields: :param order_by: :param query: :return:
[ "Get", "file", "list", "from", "Google", "Drive", ":", "param", "page_size", ":", ":", "param", "fields", ":", ":", "param", "order_by", ":", ":", "param", "query", ":", ":", "return", ":" ]
train
https://github.com/nabeen/gdwrap/blob/c51c27bc347f98ce334d84a943237080f1f3bb6d/gdwrap/Gdwrap.py#L40-L56
nabeen/gdwrap
gdwrap/Gdwrap.py
Gdwrap.create_folder
def create_folder(self, dir_name: str, parent_dir_id: str) -> str: """ Create folder into Google Drive :param dir_name: :param parent_dir_name: :return: """ service = self.__get_service() file_metadata = { 'name': dir_name, 'mimeTyp...
python
def create_folder(self, dir_name: str, parent_dir_id: str) -> str: """ Create folder into Google Drive :param dir_name: :param parent_dir_name: :return: """ service = self.__get_service() file_metadata = { 'name': dir_name, 'mimeTyp...
[ "def", "create_folder", "(", "self", ",", "dir_name", ":", "str", ",", "parent_dir_id", ":", "str", ")", "->", "str", ":", "service", "=", "self", ".", "__get_service", "(", ")", "file_metadata", "=", "{", "'name'", ":", "dir_name", ",", "'mimeType'", ":...
Create folder into Google Drive :param dir_name: :param parent_dir_name: :return:
[ "Create", "folder", "into", "Google", "Drive", ":", "param", "dir_name", ":", ":", "param", "parent_dir_name", ":", ":", "return", ":" ]
train
https://github.com/nabeen/gdwrap/blob/c51c27bc347f98ce334d84a943237080f1f3bb6d/gdwrap/Gdwrap.py#L58-L74
nabeen/gdwrap
gdwrap/Gdwrap.py
Gdwrap.file_download
def file_download(self, item_id: str, item_name: str, dir_name: str) -> bool: """ Download file from Google Drive :param item_id: :param dir_name: :return: """ service = self.__get_service() request = service.files().get_media(fileId=item_id) self....
python
def file_download(self, item_id: str, item_name: str, dir_name: str) -> bool: """ Download file from Google Drive :param item_id: :param dir_name: :return: """ service = self.__get_service() request = service.files().get_media(fileId=item_id) self....
[ "def", "file_download", "(", "self", ",", "item_id", ":", "str", ",", "item_name", ":", "str", ",", "dir_name", ":", "str", ")", "->", "bool", ":", "service", "=", "self", ".", "__get_service", "(", ")", "request", "=", "service", ".", "files", "(", ...
Download file from Google Drive :param item_id: :param dir_name: :return:
[ "Download", "file", "from", "Google", "Drive", ":", "param", "item_id", ":", ":", "param", "dir_name", ":", ":", "return", ":" ]
train
https://github.com/nabeen/gdwrap/blob/c51c27bc347f98ce334d84a943237080f1f3bb6d/gdwrap/Gdwrap.py#L76-L92
nabeen/gdwrap
gdwrap/Gdwrap.py
Gdwrap.file_upload
def file_upload(self, folder_id: str, file_name: str, mine_type: str) -> bool: """ Upload file into Google Drive :param folder_id: :param file_name: :param mine_type: :return: """ service = self.__get_service() media_body = MediaFileUpload(file_nam...
python
def file_upload(self, folder_id: str, file_name: str, mine_type: str) -> bool: """ Upload file into Google Drive :param folder_id: :param file_name: :param mine_type: :return: """ service = self.__get_service() media_body = MediaFileUpload(file_nam...
[ "def", "file_upload", "(", "self", ",", "folder_id", ":", "str", ",", "file_name", ":", "str", ",", "mine_type", ":", "str", ")", "->", "bool", ":", "service", "=", "self", ".", "__get_service", "(", ")", "media_body", "=", "MediaFileUpload", "(", "file_...
Upload file into Google Drive :param folder_id: :param file_name: :param mine_type: :return:
[ "Upload", "file", "into", "Google", "Drive", ":", "param", "folder_id", ":", ":", "param", "file_name", ":", ":", "param", "mine_type", ":", ":", "return", ":" ]
train
https://github.com/nabeen/gdwrap/blob/c51c27bc347f98ce334d84a943237080f1f3bb6d/gdwrap/Gdwrap.py#L94-L109
tBaxter/tango-articles
build/lib/articles/templatetags/article_tags.py
get_new_articles
def get_new_articles(last_seen, assignment_slug=None, brief=False, *args, **kwargs): """ Takes a 'last_seen' timestamp and assignment slug and returns a list. Note that you can pass no assignment slug and it will return all articles. Pass brief=True to get news briefs Usage: {% get_new_artic...
python
def get_new_articles(last_seen, assignment_slug=None, brief=False, *args, **kwargs): """ Takes a 'last_seen' timestamp and assignment slug and returns a list. Note that you can pass no assignment slug and it will return all articles. Pass brief=True to get news briefs Usage: {% get_new_artic...
[ "def", "get_new_articles", "(", "last_seen", ",", "assignment_slug", "=", "None", ",", "brief", "=", "False", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "brief", ":", "return", "Brief", ".", "objects", ".", "filter", "(", "pub_date__gte",...
Takes a 'last_seen' timestamp and assignment slug and returns a list. Note that you can pass no assignment slug and it will return all articles. Pass brief=True to get news briefs Usage: {% get_new_articles <LAST_SEEN> some_blog as blog_entries %} {% get_new_articles <LAST_SEEN> as latest_co...
[ "Takes", "a", "last_seen", "timestamp", "and", "assignment", "slug", "and", "returns", "a", "list", ".", "Note", "that", "you", "can", "pass", "no", "assignment", "slug", "and", "it", "will", "return", "all", "articles", ".", "Pass", "brief", "=", "True", ...
train
https://github.com/tBaxter/tango-articles/blob/93818dcca1b62042a4fc19af63474691b0fe931c/build/lib/articles/templatetags/article_tags.py#L26-L41
AliGhahraei/verarandom
verarandom/_random_generator.py
VeraRandom.random
def random(self, n: Optional[int] = None) -> Union[List[float], float]: """ Similar to :py:func:`randint` """ return self._generate_randoms(self._request_randoms, max_n=self.config.MAX_NUMBER_OF_FLOATS, n=n)
python
def random(self, n: Optional[int] = None) -> Union[List[float], float]: """ Similar to :py:func:`randint` """ return self._generate_randoms(self._request_randoms, max_n=self.config.MAX_NUMBER_OF_FLOATS, n=n)
[ "def", "random", "(", "self", ",", "n", ":", "Optional", "[", "int", "]", "=", "None", ")", "->", "Union", "[", "List", "[", "float", "]", ",", "float", "]", ":", "return", "self", ".", "_generate_randoms", "(", "self", ".", "_request_randoms", ",", ...
Similar to :py:func:`randint`
[ "Similar", "to", ":", "py", ":", "func", ":", "randint" ]
train
https://github.com/AliGhahraei/verarandom/blob/63d9a5bd2776e40368933f54e58c3f4b4f333f03/verarandom/_random_generator.py#L64-L67
AliGhahraei/verarandom
verarandom/_random_generator.py
VeraRandom.randint
def randint(self, a: int, b: int, n: Optional[int] = None) -> Union[List[int], int]: """ Generate n numbers as a list or a single one if no n is given. n is used to minimize the number of requests made and return type changes to be compatible with :py:mod:`random`'s interface """ ...
python
def randint(self, a: int, b: int, n: Optional[int] = None) -> Union[List[int], int]: """ Generate n numbers as a list or a single one if no n is given. n is used to minimize the number of requests made and return type changes to be compatible with :py:mod:`random`'s interface """ ...
[ "def", "randint", "(", "self", ",", "a", ":", "int", ",", "b", ":", "int", ",", "n", ":", "Optional", "[", "int", "]", "=", "None", ")", "->", "Union", "[", "List", "[", "int", "]", ",", "int", "]", ":", "max_n", "=", "self", ".", "config", ...
Generate n numbers as a list or a single one if no n is given. n is used to minimize the number of requests made and return type changes to be compatible with :py:mod:`random`'s interface
[ "Generate", "n", "numbers", "as", "a", "list", "or", "a", "single", "one", "if", "no", "n", "is", "given", "." ]
train
https://github.com/AliGhahraei/verarandom/blob/63d9a5bd2776e40368933f54e58c3f4b4f333f03/verarandom/_random_generator.py#L69-L76
AliGhahraei/verarandom
verarandom/_random_generator.py
VeraRandomQuota._check_quota
def _check_quota(self): """ If IP can't make requests, raise BitQuotaExceeded. Called before generating numbers. """ self._request_remaining_quota_if_unset() if self.quota_estimate < self.quota_limit: raise BitQuotaExceeded(self.quota_estimate)
python
def _check_quota(self): """ If IP can't make requests, raise BitQuotaExceeded. Called before generating numbers. """ self._request_remaining_quota_if_unset() if self.quota_estimate < self.quota_limit: raise BitQuotaExceeded(self.quota_estimate)
[ "def", "_check_quota", "(", "self", ")", ":", "self", ".", "_request_remaining_quota_if_unset", "(", ")", "if", "self", ".", "quota_estimate", "<", "self", ".", "quota_limit", ":", "raise", "BitQuotaExceeded", "(", "self", ".", "quota_estimate", ")" ]
If IP can't make requests, raise BitQuotaExceeded. Called before generating numbers.
[ "If", "IP", "can", "t", "make", "requests", "raise", "BitQuotaExceeded", ".", "Called", "before", "generating", "numbers", "." ]
train
https://github.com/AliGhahraei/verarandom/blob/63d9a5bd2776e40368933f54e58c3f4b4f333f03/verarandom/_random_generator.py#L171-L175
musicmetric/mmpy
src/entity.py
Entity._construct_timeseries
def _construct_timeseries(self, timeseries, constraints={}): """ wraps response_from for timeseries calls, returns the resulting dict """ self.response_from(timeseries, constraints) if self.response == None: return None return {'data':self.response['data'], ...
python
def _construct_timeseries(self, timeseries, constraints={}): """ wraps response_from for timeseries calls, returns the resulting dict """ self.response_from(timeseries, constraints) if self.response == None: return None return {'data':self.response['data'], ...
[ "def", "_construct_timeseries", "(", "self", ",", "timeseries", ",", "constraints", "=", "{", "}", ")", ":", "self", ".", "response_from", "(", "timeseries", ",", "constraints", ")", "if", "self", ".", "response", "==", "None", ":", "return", "None", "retu...
wraps response_from for timeseries calls, returns the resulting dict
[ "wraps", "response_from", "for", "timeseries", "calls", "returns", "the", "resulting", "dict" ]
train
https://github.com/musicmetric/mmpy/blob/2b5d975c61f9ea8c7f19f76a90b59771833ef881/src/entity.py#L58-L68
musicmetric/mmpy
src/entity.py
Entity.response_from
def response_from(self, ext_endpoint=None, params = {}): """ fetches and parses data from the semetric API, returning whatever is in the 'response' field in the top level dict on success (200) if the endpoint returns a 204, returns None (no data available for id) else throws a va...
python
def response_from(self, ext_endpoint=None, params = {}): """ fetches and parses data from the semetric API, returning whatever is in the 'response' field in the top level dict on success (200) if the endpoint returns a 204, returns None (no data available for id) else throws a va...
[ "def", "response_from", "(", "self", ",", "ext_endpoint", "=", "None", ",", "params", "=", "{", "}", ")", ":", "params", "[", "'token'", "]", "=", "API_KEY", "base_endpoint", "=", "\"{base_url}/{entity}/{entityID}\"", "uri", "=", "base_endpoint", ".", "format"...
fetches and parses data from the semetric API, returning whatever is in the 'response' field in the top level dict on success (200) if the endpoint returns a 204, returns None (no data available for id) else throws a value error self should have these attributes as needed: @entit...
[ "fetches", "and", "parses", "data", "from", "the", "semetric", "API", "returning", "whatever", "is", "in", "the", "response", "field", "in", "the", "top", "level", "dict", "on", "success", "(", "200", ")", "if", "the", "endpoint", "returns", "a", "204", ...
train
https://github.com/musicmetric/mmpy/blob/2b5d975c61f9ea8c7f19f76a90b59771833ef881/src/entity.py#L70-L104
shreyaspotnis/rampage
rampage/widgets/ChannelWidgets.py
QChannelInfoBox.edit_channel_info
def edit_channel_info(self, new_ch_name, ch_dct): """Parent widget calls this whenever the user edits channel info. """ self.ch_name = new_ch_name self.dct = ch_dct if ch_dct['type'] == 'analog': fmter = fmt.green else: fmter = fmt.blue sel...
python
def edit_channel_info(self, new_ch_name, ch_dct): """Parent widget calls this whenever the user edits channel info. """ self.ch_name = new_ch_name self.dct = ch_dct if ch_dct['type'] == 'analog': fmter = fmt.green else: fmter = fmt.blue sel...
[ "def", "edit_channel_info", "(", "self", ",", "new_ch_name", ",", "ch_dct", ")", ":", "self", ".", "ch_name", "=", "new_ch_name", "self", ".", "dct", "=", "ch_dct", "if", "ch_dct", "[", "'type'", "]", "==", "'analog'", ":", "fmter", "=", "fmt", ".", "g...
Parent widget calls this whenever the user edits channel info.
[ "Parent", "widget", "calls", "this", "whenever", "the", "user", "edits", "channel", "info", "." ]
train
https://github.com/shreyaspotnis/rampage/blob/e2565aef7ee16ee06523de975e8aa41aca14e3b2/rampage/widgets/ChannelWidgets.py#L135-L145
hobson/pug-dj
pug/dj/miner/views.py
connections
def connections(request, edges): """ Plot a force-directed graph based on the edges provided """ edge_list, node_list = parse.graph_definition(edges) data = {'nodes': json.dumps(node_list), 'edges': json.dumps(edge_list)} return render_to_response('miner/connections.html', data)
python
def connections(request, edges): """ Plot a force-directed graph based on the edges provided """ edge_list, node_list = parse.graph_definition(edges) data = {'nodes': json.dumps(node_list), 'edges': json.dumps(edge_list)} return render_to_response('miner/connections.html', data)
[ "def", "connections", "(", "request", ",", "edges", ")", ":", "edge_list", ",", "node_list", "=", "parse", ".", "graph_definition", "(", "edges", ")", "data", "=", "{", "'nodes'", ":", "json", ".", "dumps", "(", "node_list", ")", ",", "'edges'", ":", "...
Plot a force-directed graph based on the edges provided
[ "Plot", "a", "force", "-", "directed", "graph", "based", "on", "the", "edges", "provided" ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/miner/views.py#L56-L62