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
OzymandiasTheGreat/python-libinput
libinput/event.py
TabletPadEvent.strip_number
def strip_number(self): """The number of the strip that has changed state, with 0 being the first strip. On tablets with only one strip, this method always returns 0. For events not of type :attr:`~libinput.constant.EventType.TABLET_PAD_STRIP`, this property raises :exc:`AttributeError`. Returns: in...
python
def strip_number(self): """The number of the strip that has changed state, with 0 being the first strip. On tablets with only one strip, this method always returns 0. For events not of type :attr:`~libinput.constant.EventType.TABLET_PAD_STRIP`, this property raises :exc:`AttributeError`. Returns: in...
[ "def", "strip_number", "(", "self", ")", ":", "if", "self", ".", "type", "!=", "EventType", ".", "TABLET_PAD_STRIP", ":", "raise", "AttributeError", "(", "_wrong_prop", ".", "format", "(", "self", ".", "type", ")", ")", "return", "self", ".", "_libinput", ...
The number of the strip that has changed state, with 0 being the first strip. On tablets with only one strip, this method always returns 0. For events not of type :attr:`~libinput.constant.EventType.TABLET_PAD_STRIP`, this property raises :exc:`AttributeError`. Returns: int: The index of the strip tha...
[ "The", "number", "of", "the", "strip", "that", "has", "changed", "state", "with", "0", "being", "the", "first", "strip", "." ]
train
https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/event.py#L1548-L1567
OzymandiasTheGreat/python-libinput
libinput/event.py
TabletPadEvent.strip_source
def strip_source(self): """The source of the interaction with the strip. If the source is :attr:`~libinput.constant.TabletPadStripAxisSource.FINGER`, libinput sends a strip position value of -1 to terminate the current interaction. For events not of type :attr:`~libinput.constant.EventType.TABLET_PAD_STRI...
python
def strip_source(self): """The source of the interaction with the strip. If the source is :attr:`~libinput.constant.TabletPadStripAxisSource.FINGER`, libinput sends a strip position value of -1 to terminate the current interaction. For events not of type :attr:`~libinput.constant.EventType.TABLET_PAD_STRI...
[ "def", "strip_source", "(", "self", ")", ":", "if", "self", ".", "type", "!=", "EventType", ".", "TABLET_PAD_STRIP", ":", "raise", "AttributeError", "(", "_wrong_prop", ".", "format", "(", "self", ".", "type", ")", ")", "return", "self", ".", "_libinput", ...
The source of the interaction with the strip. If the source is :attr:`~libinput.constant.TabletPadStripAxisSource.FINGER`, libinput sends a strip position value of -1 to terminate the current interaction. For events not of type :attr:`~libinput.constant.EventType.TABLET_PAD_STRIP`, this property raises :e...
[ "The", "source", "of", "the", "interaction", "with", "the", "strip", "." ]
train
https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/event.py#L1570-L1591
OzymandiasTheGreat/python-libinput
libinput/event.py
TabletPadEvent.button_number
def button_number(self): """The button number that triggered this event, starting at 0. For events that are not of type :attr:`~libinput.constant.Event.TABLET_PAD_BUTTON`, this property raises :exc:`AttributeError`. Note that the number returned is a generic sequential button number and not a semantic but...
python
def button_number(self): """The button number that triggered this event, starting at 0. For events that are not of type :attr:`~libinput.constant.Event.TABLET_PAD_BUTTON`, this property raises :exc:`AttributeError`. Note that the number returned is a generic sequential button number and not a semantic but...
[ "def", "button_number", "(", "self", ")", ":", "if", "self", ".", "type", "!=", "EventType", ".", "TABLET_PAD_BUTTON", ":", "raise", "AttributeError", "(", "_wrong_prop", ".", "format", "(", "self", ".", "type", ")", ")", "return", "self", ".", "_libinput"...
The button number that triggered this event, starting at 0. For events that are not of type :attr:`~libinput.constant.Event.TABLET_PAD_BUTTON`, this property raises :exc:`AttributeError`. Note that the number returned is a generic sequential button number and not a semantic button code as defined in ``linux...
[ "The", "button", "number", "that", "triggered", "this", "event", "starting", "at", "0", "." ]
train
https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/event.py#L1594-L1614
OzymandiasTheGreat/python-libinput
libinput/event.py
TabletPadEvent.button_state
def button_state(self): """The button state of the event. For events not of type :attr:`~libinput.constant.EventType.TABLET_PAD_BUTTON`, this property raises :exc:`AttributeError`. Returns: ~libinput.constant.ButtonState: The button state triggering this event. Raises: AttributeError """ if ...
python
def button_state(self): """The button state of the event. For events not of type :attr:`~libinput.constant.EventType.TABLET_PAD_BUTTON`, this property raises :exc:`AttributeError`. Returns: ~libinput.constant.ButtonState: The button state triggering this event. Raises: AttributeError """ if ...
[ "def", "button_state", "(", "self", ")", ":", "if", "self", ".", "type", "!=", "EventType", ".", "TABLET_PAD_BUTTON", ":", "raise", "AttributeError", "(", "_wrong_prop", ".", "format", "(", "self", ".", "type", ")", ")", "return", "self", ".", "_libinput",...
The button state of the event. For events not of type :attr:`~libinput.constant.EventType.TABLET_PAD_BUTTON`, this property raises :exc:`AttributeError`. Returns: ~libinput.constant.ButtonState: The button state triggering this event. Raises: AttributeError
[ "The", "button", "state", "of", "the", "event", "." ]
train
https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/event.py#L1617-L1634
OzymandiasTheGreat/python-libinput
libinput/event.py
TabletPadEvent.mode_group
def mode_group(self): """The mode group that the button, ring, or strip that triggered this event is considered in. The mode is a virtual grouping of functionality, usually based on some visual feedback like LEDs on the pad. See `Tablet pad modes`_ for details. Returns: ~libinput.define.TabletPadModeGr...
python
def mode_group(self): """The mode group that the button, ring, or strip that triggered this event is considered in. The mode is a virtual grouping of functionality, usually based on some visual feedback like LEDs on the pad. See `Tablet pad modes`_ for details. Returns: ~libinput.define.TabletPadModeGr...
[ "def", "mode_group", "(", "self", ")", ":", "hmodegroup", "=", "self", ".", "_libinput", ".", "libinput_event_tablet_pad_get_mode_group", "(", "self", ".", "_handle", ")", "return", "TabletPadModeGroup", "(", "hmodegroup", ",", "self", ".", "_libinput", ")" ]
The mode group that the button, ring, or strip that triggered this event is considered in. The mode is a virtual grouping of functionality, usually based on some visual feedback like LEDs on the pad. See `Tablet pad modes`_ for details. Returns: ~libinput.define.TabletPadModeGroup: The mode group of the ...
[ "The", "mode", "group", "that", "the", "button", "ring", "or", "strip", "that", "triggered", "this", "event", "is", "considered", "in", "." ]
train
https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/event.py#L1665-L1680
sci-bots/svg-model
svg_model/bin/detect_connections.py
parse_args
def parse_args(args=None): """Parses arguments, returns (options, args).""" from argparse import ArgumentParser if args is None: args = sys.argv parser = ArgumentParser(description=''' Attempt to automatically find "adjacent" shapes in a SVG layer, and on a second SVG layer, draw each detected...
python
def parse_args(args=None): """Parses arguments, returns (options, args).""" from argparse import ArgumentParser if args is None: args = sys.argv parser = ArgumentParser(description=''' Attempt to automatically find "adjacent" shapes in a SVG layer, and on a second SVG layer, draw each detected...
[ "def", "parse_args", "(", "args", "=", "None", ")", ":", "from", "argparse", "import", "ArgumentParser", "if", "args", "is", "None", ":", "args", "=", "sys", ".", "argv", "parser", "=", "ArgumentParser", "(", "description", "=", "'''\nAttempt to automatically ...
Parses arguments, returns (options, args).
[ "Parses", "arguments", "returns", "(", "options", "args", ")", "." ]
train
https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/svg_model/bin/detect_connections.py#L13-L35
KelSolaar/Manager
setup.py
get_long_description
def get_long_description(): """ Returns the Package long description. :return: Package long description. :rtype: unicode """ description = [] with open("README.rst") as file: for line in file: if ".. code:: python" in line and len(description) >= 2: bloc...
python
def get_long_description(): """ Returns the Package long description. :return: Package long description. :rtype: unicode """ description = [] with open("README.rst") as file: for line in file: if ".. code:: python" in line and len(description) >= 2: bloc...
[ "def", "get_long_description", "(", ")", ":", "description", "=", "[", "]", "with", "open", "(", "\"README.rst\"", ")", "as", "file", ":", "for", "line", "in", "file", ":", "if", "\".. code:: python\"", "in", "line", "and", "len", "(", "description", ")", ...
Returns the Package long description. :return: Package long description. :rtype: unicode
[ "Returns", "the", "Package", "long", "description", "." ]
train
https://github.com/KelSolaar/Manager/blob/39c8153fc021fc8a76e345a6e336ec2644f089d1/setup.py#L35-L53
portfoliome/foil
foil/ftp.py
ftp_listing_paths
def ftp_listing_paths(ftpconn: FTP, root: str) -> Iterable[str]: """Generate the full file paths from a root path.""" for current_path, dirs, files in ftp_walk(ftpconn, root): yield from (os.path.join(current_path, file) for file in files)
python
def ftp_listing_paths(ftpconn: FTP, root: str) -> Iterable[str]: """Generate the full file paths from a root path.""" for current_path, dirs, files in ftp_walk(ftpconn, root): yield from (os.path.join(current_path, file) for file in files)
[ "def", "ftp_listing_paths", "(", "ftpconn", ":", "FTP", ",", "root", ":", "str", ")", "->", "Iterable", "[", "str", "]", ":", "for", "current_path", ",", "dirs", ",", "files", "in", "ftp_walk", "(", "ftpconn", ",", "root", ")", ":", "yield", "from", ...
Generate the full file paths from a root path.
[ "Generate", "the", "full", "file", "paths", "from", "a", "root", "path", "." ]
train
https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/ftp.py#L35-L39
portfoliome/foil
foil/ftp.py
ftp_walk
def ftp_walk(ftpconn: FTP, rootpath=''): """Recursively traverse an ftp directory to discovery directory listing.""" current_directory = rootpath try: directories, files = directory_listing(ftpconn, current_directory) except ftplib.error_perm: return # Yield before recursion y...
python
def ftp_walk(ftpconn: FTP, rootpath=''): """Recursively traverse an ftp directory to discovery directory listing.""" current_directory = rootpath try: directories, files = directory_listing(ftpconn, current_directory) except ftplib.error_perm: return # Yield before recursion y...
[ "def", "ftp_walk", "(", "ftpconn", ":", "FTP", ",", "rootpath", "=", "''", ")", ":", "current_directory", "=", "rootpath", "try", ":", "directories", ",", "files", "=", "directory_listing", "(", "ftpconn", ",", "current_directory", ")", "except", "ftplib", "...
Recursively traverse an ftp directory to discovery directory listing.
[ "Recursively", "traverse", "an", "ftp", "directory", "to", "discovery", "directory", "listing", "." ]
train
https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/ftp.py#L42-L62
portfoliome/foil
foil/ftp.py
directory_listing
def directory_listing(conn: FTP, path: str) -> Tuple[List, List]: """Return the directories and files for single FTP listing.""" entries = deque() conn.dir(path, entries.append) entries = map(parse_line, entries) grouped_entries = defaultdict(list) for key, value in entries: grouped_en...
python
def directory_listing(conn: FTP, path: str) -> Tuple[List, List]: """Return the directories and files for single FTP listing.""" entries = deque() conn.dir(path, entries.append) entries = map(parse_line, entries) grouped_entries = defaultdict(list) for key, value in entries: grouped_en...
[ "def", "directory_listing", "(", "conn", ":", "FTP", ",", "path", ":", "str", ")", "->", "Tuple", "[", "List", ",", "List", "]", ":", "entries", "=", "deque", "(", ")", "conn", ".", "dir", "(", "path", ",", "entries", ".", "append", ")", "entries",...
Return the directories and files for single FTP listing.
[ "Return", "the", "directories", "and", "files", "for", "single", "FTP", "listing", "." ]
train
https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/ftp.py#L65-L79
portfoliome/foil
foil/ftp.py
parse_line
def parse_line(line: str, char_index=0) -> Tuple[ListingType, str]: """Parse FTP directory listing into (type, filename).""" entry_name = str.rpartition(line, ' ')[-1] entry_type = LISTING_FLAG_MAP.get(line[char_index], ListingType.other) return entry_type, entry_name
python
def parse_line(line: str, char_index=0) -> Tuple[ListingType, str]: """Parse FTP directory listing into (type, filename).""" entry_name = str.rpartition(line, ' ')[-1] entry_type = LISTING_FLAG_MAP.get(line[char_index], ListingType.other) return entry_type, entry_name
[ "def", "parse_line", "(", "line", ":", "str", ",", "char_index", "=", "0", ")", "->", "Tuple", "[", "ListingType", ",", "str", "]", ":", "entry_name", "=", "str", ".", "rpartition", "(", "line", ",", "' '", ")", "[", "-", "1", "]", "entry_type", "=...
Parse FTP directory listing into (type, filename).
[ "Parse", "FTP", "directory", "listing", "into", "(", "type", "filename", ")", "." ]
train
https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/ftp.py#L82-L87
portfoliome/foil
foil/ftp.py
download_ftp_url
def download_ftp_url(source_url, target_uri, buffer_size=8192): """Uses urllib. thread safe?""" ensure_file_directory(target_uri) with urllib.request.urlopen(source_url) as source_file: with open(target_uri, 'wb') as target_file: shutil.copyfileobj(source_file, target_file, buffer_size...
python
def download_ftp_url(source_url, target_uri, buffer_size=8192): """Uses urllib. thread safe?""" ensure_file_directory(target_uri) with urllib.request.urlopen(source_url) as source_file: with open(target_uri, 'wb') as target_file: shutil.copyfileobj(source_file, target_file, buffer_size...
[ "def", "download_ftp_url", "(", "source_url", ",", "target_uri", ",", "buffer_size", "=", "8192", ")", ":", "ensure_file_directory", "(", "target_uri", ")", "with", "urllib", ".", "request", ".", "urlopen", "(", "source_url", ")", "as", "source_file", ":", "wi...
Uses urllib. thread safe?
[ "Uses", "urllib", ".", "thread", "safe?" ]
train
https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/ftp.py#L90-L97
BlueBrain/hpcbench
hpcbench/benchmark/babelstream.py
BabelStream.devices
def devices(self): """List of devices to test """ eax = self.attributes.get('devices') if eax is None: eax = self._all_devices if not isinstance(eax, list): eax = [eax] return [str(dev) for dev in eax]
python
def devices(self): """List of devices to test """ eax = self.attributes.get('devices') if eax is None: eax = self._all_devices if not isinstance(eax, list): eax = [eax] return [str(dev) for dev in eax]
[ "def", "devices", "(", "self", ")", ":", "eax", "=", "self", ".", "attributes", ".", "get", "(", "'devices'", ")", "if", "eax", "is", "None", ":", "eax", "=", "self", ".", "_all_devices", "if", "not", "isinstance", "(", "eax", ",", "list", ")", ":"...
List of devices to test
[ "List", "of", "devices", "to", "test" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/benchmark/babelstream.py#L69-L77
PolyJIT/benchbuild
benchbuild/utils/schema.py
exceptions
def exceptions(error_is_fatal=True, error_messages=None): """ Handle SQLAlchemy exceptions in a sane way. Args: func: An arbitrary function to wrap. error_is_fatal: Should we exit the program on exception? reraise: Should we reraise the exception, after logging? Only makes sense ...
python
def exceptions(error_is_fatal=True, error_messages=None): """ Handle SQLAlchemy exceptions in a sane way. Args: func: An arbitrary function to wrap. error_is_fatal: Should we exit the program on exception? reraise: Should we reraise the exception, after logging? Only makes sense ...
[ "def", "exceptions", "(", "error_is_fatal", "=", "True", ",", "error_messages", "=", "None", ")", ":", "def", "exception_decorator", "(", "func", ")", ":", "nonlocal", "error_messages", "@", "functools", ".", "wraps", "(", "func", ")", "def", "exc_wrapper", ...
Handle SQLAlchemy exceptions in a sane way. Args: func: An arbitrary function to wrap. error_is_fatal: Should we exit the program on exception? reraise: Should we reraise the exception, after logging? Only makes sense if error_is_fatal is False. error_messages: A diction...
[ "Handle", "SQLAlchemy", "exceptions", "in", "a", "sane", "way", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/schema.py#L50-L89
PolyJIT/benchbuild
benchbuild/utils/schema.py
get_version_data
def get_version_data(): """Retreive migration information.""" connect_str = str(settings.CFG["db"]["connect_string"]) repo_url = path.template_path("../db/") return (connect_str, repo_url)
python
def get_version_data(): """Retreive migration information.""" connect_str = str(settings.CFG["db"]["connect_string"]) repo_url = path.template_path("../db/") return (connect_str, repo_url)
[ "def", "get_version_data", "(", ")", ":", "connect_str", "=", "str", "(", "settings", ".", "CFG", "[", "\"db\"", "]", "[", "\"connect_string\"", "]", ")", "repo_url", "=", "path", ".", "template_path", "(", "\"../db/\"", ")", "return", "(", "connect_str", ...
Retreive migration information.
[ "Retreive", "migration", "information", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/schema.py#L339-L343
PolyJIT/benchbuild
benchbuild/utils/schema.py
enforce_versioning
def enforce_versioning(force=False): """Install versioning on the db.""" connect_str, repo_url = get_version_data() LOG.warning("Your database uses an unversioned benchbuild schema.") if not force and not ui.ask( "Should I enforce version control on your schema?"): LOG.error("User de...
python
def enforce_versioning(force=False): """Install versioning on the db.""" connect_str, repo_url = get_version_data() LOG.warning("Your database uses an unversioned benchbuild schema.") if not force and not ui.ask( "Should I enforce version control on your schema?"): LOG.error("User de...
[ "def", "enforce_versioning", "(", "force", "=", "False", ")", ":", "connect_str", ",", "repo_url", "=", "get_version_data", "(", ")", "LOG", ".", "warning", "(", "\"Your database uses an unversioned benchbuild schema.\"", ")", "if", "not", "force", "and", "not", "...
Install versioning on the db.
[ "Install", "versioning", "on", "the", "db", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/schema.py#L351-L361
PolyJIT/benchbuild
benchbuild/utils/schema.py
init_functions
def init_functions(connection): """Initialize all SQL functions in the database.""" if settings.CFG["db"]["create_functions"]: print("Refreshing SQL functions...") for file in path.template_files("../sql/", exts=[".sql"]): func = sa.DDL(path.template_str(file)) LOG.info("...
python
def init_functions(connection): """Initialize all SQL functions in the database.""" if settings.CFG["db"]["create_functions"]: print("Refreshing SQL functions...") for file in path.template_files("../sql/", exts=[".sql"]): func = sa.DDL(path.template_str(file)) LOG.info("...
[ "def", "init_functions", "(", "connection", ")", ":", "if", "settings", ".", "CFG", "[", "\"db\"", "]", "[", "\"create_functions\"", "]", ":", "print", "(", "\"Refreshing SQL functions...\"", ")", "for", "file", "in", "path", ".", "template_files", "(", "\"../...
Initialize all SQL functions in the database.
[ "Initialize", "all", "SQL", "functions", "in", "the", "database", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/schema.py#L494-L502
PolyJIT/benchbuild
benchbuild/utils/schema.py
SessionManager.connect_engine
def connect_engine(self): """ Establish a connection to the database. Provides simple error handling for fatal errors. Returns: True, if we could establish a connection, else False. """ try: self.connection = self.engine.connect() ret...
python
def connect_engine(self): """ Establish a connection to the database. Provides simple error handling for fatal errors. Returns: True, if we could establish a connection, else False. """ try: self.connection = self.engine.connect() ret...
[ "def", "connect_engine", "(", "self", ")", ":", "try", ":", "self", ".", "connection", "=", "self", ".", "engine", ".", "connect", "(", ")", "return", "True", "except", "sa", ".", "exc", ".", "OperationalError", "as", "opex", ":", "LOG", ".", "fatal", ...
Establish a connection to the database. Provides simple error handling for fatal errors. Returns: True, if we could establish a connection, else False.
[ "Establish", "a", "connection", "to", "the", "database", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/schema.py#L410-L425
PolyJIT/benchbuild
benchbuild/utils/schema.py
SessionManager.configure_engine
def configure_engine(self): """ Configure the databse connection. Sets appropriate transaction isolation levels and handle errors. Returns: True, if we did not encounter any unrecoverable errors, else False. """ try: self.connection.execution_opt...
python
def configure_engine(self): """ Configure the databse connection. Sets appropriate transaction isolation levels and handle errors. Returns: True, if we did not encounter any unrecoverable errors, else False. """ try: self.connection.execution_opt...
[ "def", "configure_engine", "(", "self", ")", ":", "try", ":", "self", ".", "connection", ".", "execution_options", "(", "isolation_level", "=", "\"SERIALIZABLE\"", ")", "except", "sa", ".", "exc", ".", "ArgumentError", ":", "LOG", ".", "debug", "(", "\"Unabl...
Configure the databse connection. Sets appropriate transaction isolation levels and handle errors. Returns: True, if we did not encounter any unrecoverable errors, else False.
[ "Configure", "the", "databse", "connection", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/schema.py#L427-L440
portfoliome/foil
foil/dates.py
parse_date
def parse_date(date_str: str, pattern=_RE_DATE) -> dt.date: """Parse datetime.date from YYYY-MM-DD format.""" groups = re.match(pattern, date_str) return dt.date(*_date_to_tuple(groups.groupdict()))
python
def parse_date(date_str: str, pattern=_RE_DATE) -> dt.date: """Parse datetime.date from YYYY-MM-DD format.""" groups = re.match(pattern, date_str) return dt.date(*_date_to_tuple(groups.groupdict()))
[ "def", "parse_date", "(", "date_str", ":", "str", ",", "pattern", "=", "_RE_DATE", ")", "->", "dt", ".", "date", ":", "groups", "=", "re", ".", "match", "(", "pattern", ",", "date_str", ")", "return", "dt", ".", "date", "(", "*", "_date_to_tuple", "(...
Parse datetime.date from YYYY-MM-DD format.
[ "Parse", "datetime", ".", "date", "from", "YYYY", "-", "MM", "-", "DD", "format", "." ]
train
https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/dates.py#L47-L52
portfoliome/foil
foil/dates.py
_datetime_to_tuple
def _datetime_to_tuple(dt_dict): """datetime.datetime components from dictionary to tuple. Example ------- dt_dict = {'year': '2014','month': '07','day': '23', 'hour': '13','minute': '12','second': '45','microsecond': '321'} _datetime_to_tuple(dt_dict) -> (2014, 7, 23, 13, 12, 45, 321)...
python
def _datetime_to_tuple(dt_dict): """datetime.datetime components from dictionary to tuple. Example ------- dt_dict = {'year': '2014','month': '07','day': '23', 'hour': '13','minute': '12','second': '45','microsecond': '321'} _datetime_to_tuple(dt_dict) -> (2014, 7, 23, 13, 12, 45, 321)...
[ "def", "_datetime_to_tuple", "(", "dt_dict", ")", ":", "year", ",", "month", ",", "day", "=", "_date_to_tuple", "(", "dt_dict", ")", "hour", ",", "minute", ",", "second", ",", "microsecond", "=", "_time_to_tuple", "(", "dt_dict", ")", "return", "year", ","...
datetime.datetime components from dictionary to tuple. Example ------- dt_dict = {'year': '2014','month': '07','day': '23', 'hour': '13','minute': '12','second': '45','microsecond': '321'} _datetime_to_tuple(dt_dict) -> (2014, 7, 23, 13, 12, 45, 321)
[ "datetime", ".", "datetime", "components", "from", "dictionary", "to", "tuple", "." ]
train
https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/dates.py#L81-L95
portfoliome/foil
foil/dates.py
DateTimeParser.convert_2_utc
def convert_2_utc(self, datetime_, timezone): """convert to datetime to UTC offset.""" datetime_ = self.tz_mapper[timezone].localize(datetime_) return datetime_.astimezone(pytz.UTC)
python
def convert_2_utc(self, datetime_, timezone): """convert to datetime to UTC offset.""" datetime_ = self.tz_mapper[timezone].localize(datetime_) return datetime_.astimezone(pytz.UTC)
[ "def", "convert_2_utc", "(", "self", ",", "datetime_", ",", "timezone", ")", ":", "datetime_", "=", "self", ".", "tz_mapper", "[", "timezone", "]", ".", "localize", "(", "datetime_", ")", "return", "datetime_", ".", "astimezone", "(", "pytz", ".", "UTC", ...
convert to datetime to UTC offset.
[ "convert", "to", "datetime", "to", "UTC", "offset", "." ]
train
https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/dates.py#L74-L78
jfear/sramongo
sramongo/services/entrez.py
esearch
def esearch(database, query, userhistory=True, webenv=False, query_key=False, retstart=False, retmax=False, api_key=False, email=False, **kwargs) -> Optional[EsearchResult]: """Search for a query using the Entrez ESearch API. Parameters ---------- database : str Entez database to se...
python
def esearch(database, query, userhistory=True, webenv=False, query_key=False, retstart=False, retmax=False, api_key=False, email=False, **kwargs) -> Optional[EsearchResult]: """Search for a query using the Entrez ESearch API. Parameters ---------- database : str Entez database to se...
[ "def", "esearch", "(", "database", ",", "query", ",", "userhistory", "=", "True", ",", "webenv", "=", "False", ",", "query_key", "=", "False", ",", "retstart", "=", "False", ",", "retmax", "=", "False", ",", "api_key", "=", "False", ",", "email", "=", ...
Search for a query using the Entrez ESearch API. Parameters ---------- database : str Entez database to search. query : str Query string userhistory : bool Tells API to return a WebEnV and query_key. webenv : str An Entrez WebEnv to use saved history. query_k...
[ "Search", "for", "a", "query", "using", "the", "Entrez", "ESearch", "API", "." ]
train
https://github.com/jfear/sramongo/blob/82a9a157e44bda4100be385c644b3ac21be66038/sramongo/services/entrez.py#L28-L83
jfear/sramongo
sramongo/services/entrez.py
epost
def epost(database, ids: List[str], webenv=False, api_key=False, email=False, **kwargs) -> Optional[EpostResult]: """Post IDs using the Entrez ESearch API. Parameters ---------- database : str Entez database to search. ids : list List of IDs to submit to the server. webenv : str...
python
def epost(database, ids: List[str], webenv=False, api_key=False, email=False, **kwargs) -> Optional[EpostResult]: """Post IDs using the Entrez ESearch API. Parameters ---------- database : str Entez database to search. ids : list List of IDs to submit to the server. webenv : str...
[ "def", "epost", "(", "database", ",", "ids", ":", "List", "[", "str", "]", ",", "webenv", "=", "False", ",", "api_key", "=", "False", ",", "email", "=", "False", ",", "*", "*", "kwargs", ")", "->", "Optional", "[", "EpostResult", "]", ":", "url", ...
Post IDs using the Entrez ESearch API. Parameters ---------- database : str Entez database to search. ids : list List of IDs to submit to the server. webenv : str An Entrez WebEnv to post ids to. api_key : str A users API key which allows more requests per second...
[ "Post", "IDs", "using", "the", "Entrez", "ESearch", "API", "." ]
train
https://github.com/jfear/sramongo/blob/82a9a157e44bda4100be385c644b3ac21be66038/sramongo/services/entrez.py#L86-L115
jfear/sramongo
sramongo/services/entrez.py
elink
def elink(db: str, dbfrom: str, ids=False, webenv=False, query_key=False, api_key=False, email=False, **kwargs) -> Optional[ElinkResult]: """Get document summaries using the Entrez ESearch API. Parameters ---------- db : str Entez database to get ids from. dbfrom : str Ent...
python
def elink(db: str, dbfrom: str, ids=False, webenv=False, query_key=False, api_key=False, email=False, **kwargs) -> Optional[ElinkResult]: """Get document summaries using the Entrez ESearch API. Parameters ---------- db : str Entez database to get ids from. dbfrom : str Ent...
[ "def", "elink", "(", "db", ":", "str", ",", "dbfrom", ":", "str", ",", "ids", "=", "False", ",", "webenv", "=", "False", ",", "query_key", "=", "False", ",", "api_key", "=", "False", ",", "email", "=", "False", ",", "*", "*", "kwargs", ")", "->",...
Get document summaries using the Entrez ESearch API. Parameters ---------- db : str Entez database to get ids from. dbfrom : str Entez database the provided ids are from. ids : list or str List of IDs to submit to the server. webenv : str An Entrez WebEnv to use ...
[ "Get", "document", "summaries", "using", "the", "Entrez", "ESearch", "API", "." ]
train
https://github.com/jfear/sramongo/blob/82a9a157e44bda4100be385c644b3ac21be66038/sramongo/services/entrez.py#L118-L171
jfear/sramongo
sramongo/services/entrez.py
esummary
def esummary(database: str, ids=False, webenv=False, query_key=False, count=False, retstart=False, retmax=False, api_key=False, email=False, **kwargs) -> Optional[List[EsummaryResult]]: """Get document summaries using the Entrez ESearch API. Parameters ---------- database : str Ent...
python
def esummary(database: str, ids=False, webenv=False, query_key=False, count=False, retstart=False, retmax=False, api_key=False, email=False, **kwargs) -> Optional[List[EsummaryResult]]: """Get document summaries using the Entrez ESearch API. Parameters ---------- database : str Ent...
[ "def", "esummary", "(", "database", ":", "str", ",", "ids", "=", "False", ",", "webenv", "=", "False", ",", "query_key", "=", "False", ",", "count", "=", "False", ",", "retstart", "=", "False", ",", "retmax", "=", "False", ",", "api_key", "=", "False...
Get document summaries using the Entrez ESearch API. Parameters ---------- database : str Entez database to search. ids : list or str List of IDs to submit to the server. webenv : str An Entrez WebEnv to use saved history. query_key : str An Entrez query_key to u...
[ "Get", "document", "summaries", "using", "the", "Entrez", "ESearch", "API", "." ]
train
https://github.com/jfear/sramongo/blob/82a9a157e44bda4100be385c644b3ac21be66038/sramongo/services/entrez.py#L174-L220
jfear/sramongo
sramongo/services/entrez.py
efetch
def efetch(database, ids=False, webenv=False, query_key=False, count=False, retstart=False, retmax=False, rettype='full', retmode='xml', api_key=False, email=False, **kwargs) -> str: """Get documents using the Entrez ESearch API.gg Parameters ---------- database : str Entez database ...
python
def efetch(database, ids=False, webenv=False, query_key=False, count=False, retstart=False, retmax=False, rettype='full', retmode='xml', api_key=False, email=False, **kwargs) -> str: """Get documents using the Entrez ESearch API.gg Parameters ---------- database : str Entez database ...
[ "def", "efetch", "(", "database", ",", "ids", "=", "False", ",", "webenv", "=", "False", ",", "query_key", "=", "False", ",", "count", "=", "False", ",", "retstart", "=", "False", ",", "retmax", "=", "False", ",", "rettype", "=", "'full'", ",", "retm...
Get documents using the Entrez ESearch API.gg Parameters ---------- database : str Entez database to search. ids : list or str List of IDs to submit to the server. webenv : str An Entrez WebEnv to use saved history. query_key : str An Entrez query_key to use save...
[ "Get", "documents", "using", "the", "Entrez", "ESearch", "API", ".", "gg" ]
train
https://github.com/jfear/sramongo/blob/82a9a157e44bda4100be385c644b3ac21be66038/sramongo/services/entrez.py#L223-L275
jfear/sramongo
sramongo/services/entrez.py
entrez_sets_of_results
def entrez_sets_of_results(url, retstart=False, retmax=False, count=False) -> Optional[List[requests.Response]]: """Gets sets of results back from Entrez. Entrez can only return 500 results at a time. This creates a generator that gets results by incrementing retstart and retmax. Parameters ------...
python
def entrez_sets_of_results(url, retstart=False, retmax=False, count=False) -> Optional[List[requests.Response]]: """Gets sets of results back from Entrez. Entrez can only return 500 results at a time. This creates a generator that gets results by incrementing retstart and retmax. Parameters ------...
[ "def", "entrez_sets_of_results", "(", "url", ",", "retstart", "=", "False", ",", "retmax", "=", "False", ",", "count", "=", "False", ")", "->", "Optional", "[", "List", "[", "requests", ".", "Response", "]", "]", ":", "if", "not", "retstart", ":", "ret...
Gets sets of results back from Entrez. Entrez can only return 500 results at a time. This creates a generator that gets results by incrementing retstart and retmax. Parameters ---------- url : str The Entrez API url to use. retstart : int Return values starting at this index. ...
[ "Gets", "sets", "of", "results", "back", "from", "Entrez", "." ]
train
https://github.com/jfear/sramongo/blob/82a9a157e44bda4100be385c644b3ac21be66038/sramongo/services/entrez.py#L358-L401
PolyJIT/benchbuild
benchbuild/cli/log.py
print_runs
def print_runs(query): """ Print all rows in this result query. """ if query is None: return for tup in query: print(("{0} @ {1} - {2} id: {3} group: {4}".format( tup.end, tup.experiment_name, tup.project_name, tup.experiment_group, tup.run_group)))
python
def print_runs(query): """ Print all rows in this result query. """ if query is None: return for tup in query: print(("{0} @ {1} - {2} id: {3} group: {4}".format( tup.end, tup.experiment_name, tup.project_name, tup.experiment_group, tup.run_group)))
[ "def", "print_runs", "(", "query", ")", ":", "if", "query", "is", "None", ":", "return", "for", "tup", "in", "query", ":", "print", "(", "(", "\"{0} @ {1} - {2} id: {3} group: {4}\"", ".", "format", "(", "tup", ".", "end", ",", "tup", ".", "experiment_name...
Print all rows in this result query.
[ "Print", "all", "rows", "in", "this", "result", "query", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/cli/log.py#L9-L18
PolyJIT/benchbuild
benchbuild/cli/log.py
print_logs
def print_logs(query, types=None): """ Print status logs. """ if query is None: return for run, log in query: print(("{0} @ {1} - {2} id: {3} group: {4} status: {5}".format( run.end, run.experiment_name, run.project_name, run.experiment_group, run.run_group, log.stat...
python
def print_logs(query, types=None): """ Print status logs. """ if query is None: return for run, log in query: print(("{0} @ {1} - {2} id: {3} group: {4} status: {5}".format( run.end, run.experiment_name, run.project_name, run.experiment_group, run.run_group, log.stat...
[ "def", "print_logs", "(", "query", ",", "types", "=", "None", ")", ":", "if", "query", "is", "None", ":", "return", "for", "run", ",", "log", "in", "query", ":", "print", "(", "(", "\"{0} @ {1} - {2} id: {3} group: {4} status: {5}\"", ".", "format", "(", "...
Print status logs.
[ "Print", "status", "logs", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/cli/log.py#L21-L37
sci-bots/svg-model
svg_model/merge.py
get_svg_layers
def get_svg_layers(svg_sources): ''' Collect layers from input svg sources. Args: svg_sources (list) : A list of file-like objects, each containing one or more XML layers. Returns ------- (width, height), layers : (int, int), list The first item in the tuple is the...
python
def get_svg_layers(svg_sources): ''' Collect layers from input svg sources. Args: svg_sources (list) : A list of file-like objects, each containing one or more XML layers. Returns ------- (width, height), layers : (int, int), list The first item in the tuple is the...
[ "def", "get_svg_layers", "(", "svg_sources", ")", ":", "layers", "=", "[", "]", "width", ",", "height", "=", "None", ",", "None", "def", "extract_length", "(", "attr", ")", ":", "'Extract length in pixels.'", "match", "=", "CRE_MM_LENGTH", ".", "match", "(",...
Collect layers from input svg sources. Args: svg_sources (list) : A list of file-like objects, each containing one or more XML layers. Returns ------- (width, height), layers : (int, int), list The first item in the tuple is the shape of the largest layer, and the ...
[ "Collect", "layers", "from", "input", "svg", "sources", "." ]
train
https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/svg_model/merge.py#L14-L53
sci-bots/svg-model
svg_model/merge.py
merge_svg_layers
def merge_svg_layers(svg_sources, share_transform=True): ''' Merge layers from input svg sources into a single XML document. Args: svg_sources (list) : A list of file-like objects, each containing one or more XML layers. share_transform (bool) : If exactly one layer has a trans...
python
def merge_svg_layers(svg_sources, share_transform=True): ''' Merge layers from input svg sources into a single XML document. Args: svg_sources (list) : A list of file-like objects, each containing one or more XML layers. share_transform (bool) : If exactly one layer has a trans...
[ "def", "merge_svg_layers", "(", "svg_sources", ",", "share_transform", "=", "True", ")", ":", "# Get list of XML layers.", "(", "width", ",", "height", ")", ",", "layers", "=", "get_svg_layers", "(", "svg_sources", ")", "if", "share_transform", ":", "transforms", ...
Merge layers from input svg sources into a single XML document. Args: svg_sources (list) : A list of file-like objects, each containing one or more XML layers. share_transform (bool) : If exactly one layer has a transform, apply it to *all* other layers as well. Return...
[ "Merge", "layers", "from", "input", "svg", "sources", "into", "a", "single", "XML", "document", "." ]
train
https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/svg_model/merge.py#L56-L97
BlueBrain/hpcbench
hpcbench/cli/bensh.py
main
def main(argv=None): """ben-sh entry point""" arguments = cli_common(__doc__, argv=argv) campaign_file = arguments['CAMPAIGN_FILE'] if arguments['-g']: if osp.exists(campaign_file): raise Exception('Campaign file already exists') with open(campaign_file, 'w') as ostr: ...
python
def main(argv=None): """ben-sh entry point""" arguments = cli_common(__doc__, argv=argv) campaign_file = arguments['CAMPAIGN_FILE'] if arguments['-g']: if osp.exists(campaign_file): raise Exception('Campaign file already exists') with open(campaign_file, 'w') as ostr: ...
[ "def", "main", "(", "argv", "=", "None", ")", ":", "arguments", "=", "cli_common", "(", "__doc__", ",", "argv", "=", "argv", ")", "campaign_file", "=", "arguments", "[", "'CAMPAIGN_FILE'", "]", "if", "arguments", "[", "'-g'", "]", ":", "if", "osp", "."...
ben-sh entry point
[ "ben", "-", "sh", "entry", "point" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/cli/bensh.py#L35-L61
BlueBrain/hpcbench
hpcbench/cli/benumb.py
main
def main(argv=None): """ben-umb entry point""" arguments = cli_common(__doc__, argv=argv) driver = CampaignDriver(arguments['CAMPAIGN-DIR'], expandcampvars=False) driver(no_exec=True) if argv is not None: return driver
python
def main(argv=None): """ben-umb entry point""" arguments = cli_common(__doc__, argv=argv) driver = CampaignDriver(arguments['CAMPAIGN-DIR'], expandcampvars=False) driver(no_exec=True) if argv is not None: return driver
[ "def", "main", "(", "argv", "=", "None", ")", ":", "arguments", "=", "cli_common", "(", "__doc__", ",", "argv", "=", "argv", ")", "driver", "=", "CampaignDriver", "(", "arguments", "[", "'CAMPAIGN-DIR'", "]", ",", "expandcampvars", "=", "False", ")", "dr...
ben-umb entry point
[ "ben", "-", "umb", "entry", "point" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/cli/benumb.py#L19-L25
portfoliome/foil
foil/counting.py
count_by
def count_by(records: Sequence[Dict], field_name: str) -> defaultdict: """ Frequency each value occurs in a record sequence for a given field name. """ counter = defaultdict(int) for record in records: name = record[field_name] counter[name] += 1 return counter
python
def count_by(records: Sequence[Dict], field_name: str) -> defaultdict: """ Frequency each value occurs in a record sequence for a given field name. """ counter = defaultdict(int) for record in records: name = record[field_name] counter[name] += 1 return counter
[ "def", "count_by", "(", "records", ":", "Sequence", "[", "Dict", "]", ",", "field_name", ":", "str", ")", "->", "defaultdict", ":", "counter", "=", "defaultdict", "(", "int", ")", "for", "record", "in", "records", ":", "name", "=", "record", "[", "fiel...
Frequency each value occurs in a record sequence for a given field name.
[ "Frequency", "each", "value", "occurs", "in", "a", "record", "sequence", "for", "a", "given", "field", "name", "." ]
train
https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/counting.py#L5-L16
PolyJIT/benchbuild
benchbuild/reports/status.py
FullDump.generate
def generate(self): """ Fetch all rows associated with this experiment. This will generate a huge .csv. """ exp_name = self.exp_name() fname = os.path.basename(self.out_path) fname = "{exp}_{prefix}_{name}{ending}".format( exp=exp_name, p...
python
def generate(self): """ Fetch all rows associated with this experiment. This will generate a huge .csv. """ exp_name = self.exp_name() fname = os.path.basename(self.out_path) fname = "{exp}_{prefix}_{name}{ending}".format( exp=exp_name, p...
[ "def", "generate", "(", "self", ")", ":", "exp_name", "=", "self", ".", "exp_name", "(", ")", "fname", "=", "os", ".", "path", ".", "basename", "(", "self", ".", "out_path", ")", "fname", "=", "\"{exp}_{prefix}_{name}{ending}\"", ".", "format", "(", "exp...
Fetch all rows associated with this experiment. This will generate a huge .csv.
[ "Fetch", "all", "rows", "associated", "with", "this", "experiment", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/reports/status.py#L82-L100
Metatab/metatab
metatab/appurl.py
MetatabUrl.doc
def doc(self): """Return the metatab document for the URL""" from metatab import MetatabDoc t = self.get_resource().get_target() return MetatabDoc(t.inner)
python
def doc(self): """Return the metatab document for the URL""" from metatab import MetatabDoc t = self.get_resource().get_target() return MetatabDoc(t.inner)
[ "def", "doc", "(", "self", ")", ":", "from", "metatab", "import", "MetatabDoc", "t", "=", "self", ".", "get_resource", "(", ")", ".", "get_target", "(", ")", "return", "MetatabDoc", "(", "t", ".", "inner", ")" ]
Return the metatab document for the URL
[ "Return", "the", "metatab", "document", "for", "the", "URL" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/appurl.py#L92-L96
BlueBrain/hpcbench
hpcbench/cli/bendoc.py
main
def main(argv=None): """ben-doc entry point""" arguments = cli_common(__doc__, argv=argv) campaign_path = arguments['CAMPAIGN-DIR'] driver = CampaignDriver(campaign_path, expandcampvars=False) with pushd(campaign_path): render( template=arguments['--template'], ostr=a...
python
def main(argv=None): """ben-doc entry point""" arguments = cli_common(__doc__, argv=argv) campaign_path = arguments['CAMPAIGN-DIR'] driver = CampaignDriver(campaign_path, expandcampvars=False) with pushd(campaign_path): render( template=arguments['--template'], ostr=a...
[ "def", "main", "(", "argv", "=", "None", ")", ":", "arguments", "=", "cli_common", "(", "__doc__", ",", "argv", "=", "argv", ")", "campaign_path", "=", "arguments", "[", "'CAMPAIGN-DIR'", "]", "driver", "=", "CampaignDriver", "(", "campaign_path", ",", "ex...
ben-doc entry point
[ "ben", "-", "doc", "entry", "point" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/cli/bendoc.py#L24-L36
chrisjsewell/jsonextended
jsonextended/utils.py
class_to_str
def class_to_str(obj): """ get class string from object Examples -------- >>> class_to_str(list).split('.')[1] 'list' """ mod_str = obj.__module__ name_str = obj.__name__ if mod_str == '__main__': return name_str else: return '.'.join([mod_str, name_str])
python
def class_to_str(obj): """ get class string from object Examples -------- >>> class_to_str(list).split('.')[1] 'list' """ mod_str = obj.__module__ name_str = obj.__name__ if mod_str == '__main__': return name_str else: return '.'.join([mod_str, name_str])
[ "def", "class_to_str", "(", "obj", ")", ":", "mod_str", "=", "obj", ".", "__module__", "name_str", "=", "obj", ".", "__name__", "if", "mod_str", "==", "'__main__'", ":", "return", "name_str", "else", ":", "return", "'.'", ".", "join", "(", "[", "mod_str"...
get class string from object Examples -------- >>> class_to_str(list).split('.')[1] 'list'
[ "get", "class", "string", "from", "object" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/utils.py#L22-L37
chrisjsewell/jsonextended
jsonextended/utils.py
get_module_path
def get_module_path(module): """return a directory path to a module""" return pathlib.Path( os.path.dirname(os.path.abspath(inspect.getfile(module))))
python
def get_module_path(module): """return a directory path to a module""" return pathlib.Path( os.path.dirname(os.path.abspath(inspect.getfile(module))))
[ "def", "get_module_path", "(", "module", ")", ":", "return", "pathlib", ".", "Path", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "inspect", ".", "getfile", "(", "module", ")", ")", ")", ")" ]
return a directory path to a module
[ "return", "a", "directory", "path", "to", "a", "module" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/utils.py#L40-L43
chrisjsewell/jsonextended
jsonextended/utils.py
get_data_path
def get_data_path(data, module, check_exists=True): """return a directory path to data within a module Parameters ---------- data : str or list[str] file name or list of sub-directories and file name (e.g. ['lammps','data.txt']) """ basepath = os.path.dirname(os.path.abspath(in...
python
def get_data_path(data, module, check_exists=True): """return a directory path to data within a module Parameters ---------- data : str or list[str] file name or list of sub-directories and file name (e.g. ['lammps','data.txt']) """ basepath = os.path.dirname(os.path.abspath(in...
[ "def", "get_data_path", "(", "data", ",", "module", ",", "check_exists", "=", "True", ")", ":", "basepath", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "inspect", ".", "getfile", "(", "module", ")", ")", ")", ...
return a directory path to data within a module Parameters ---------- data : str or list[str] file name or list of sub-directories and file name (e.g. ['lammps','data.txt'])
[ "return", "a", "directory", "path", "to", "data", "within", "a", "module" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/utils.py#L59-L79
chrisjsewell/jsonextended
jsonextended/utils.py
memory_usage
def memory_usage(): """return memory usage of python process in MB from http://fa.bianp.net/blog/2013/different-ways-to-get-memory-consumption-or-lessons-learned-from-memory_profiler/ psutil is quicker >>> isinstance(memory_usage(),float) True """ try: import psutil im...
python
def memory_usage(): """return memory usage of python process in MB from http://fa.bianp.net/blog/2013/different-ways-to-get-memory-consumption-or-lessons-learned-from-memory_profiler/ psutil is quicker >>> isinstance(memory_usage(),float) True """ try: import psutil im...
[ "def", "memory_usage", "(", ")", ":", "try", ":", "import", "psutil", "import", "os", "except", "ImportError", ":", "return", "_memory_usage_ps", "(", ")", "process", "=", "psutil", ".", "Process", "(", "os", ".", "getpid", "(", ")", ")", "mem", "=", "...
return memory usage of python process in MB from http://fa.bianp.net/blog/2013/different-ways-to-get-memory-consumption-or-lessons-learned-from-memory_profiler/ psutil is quicker >>> isinstance(memory_usage(),float) True
[ "return", "memory", "usage", "of", "python", "process", "in", "MB" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/utils.py#L110-L129
chrisjsewell/jsonextended
jsonextended/utils.py
_memory_usage_ps
def _memory_usage_ps(): """return memory usage of python process in MB >>> isinstance(_memory_usage_ps(),float) True """ out = subprocess.Popen( ['ps', 'v', '-p', str(os.getpid())], stdout=subprocess.PIPE).communicate()[0].split(b'\n') vsz_index = out[0].split().index(b'RSS') ...
python
def _memory_usage_ps(): """return memory usage of python process in MB >>> isinstance(_memory_usage_ps(),float) True """ out = subprocess.Popen( ['ps', 'v', '-p', str(os.getpid())], stdout=subprocess.PIPE).communicate()[0].split(b'\n') vsz_index = out[0].split().index(b'RSS') ...
[ "def", "_memory_usage_ps", "(", ")", ":", "out", "=", "subprocess", ".", "Popen", "(", "[", "'ps'", ",", "'v'", ",", "'-p'", ",", "str", "(", "os", ".", "getpid", "(", ")", ")", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", ".", "commu...
return memory usage of python process in MB >>> isinstance(_memory_usage_ps(),float) True
[ "return", "memory", "usage", "of", "python", "process", "in", "MB" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/utils.py#L132-L144
chrisjsewell/jsonextended
jsonextended/utils.py
load_memit
def load_memit(): """load memory usage ipython magic, require memory_profiler package to be installed to get usage: %memit? Author: Vlad Niculae <vlad@vene.ro> Makes use of memory_profiler from Fabian Pedregosa available at https://github.com/fabianp/memory_profiler """ from IPython.co...
python
def load_memit(): """load memory usage ipython magic, require memory_profiler package to be installed to get usage: %memit? Author: Vlad Niculae <vlad@vene.ro> Makes use of memory_profiler from Fabian Pedregosa available at https://github.com/fabianp/memory_profiler """ from IPython.co...
[ "def", "load_memit", "(", ")", ":", "from", "IPython", ".", "core", ".", "magic", "import", "Magics", ",", "line_magic", ",", "magics_class", "from", "memory_profiler", "import", "memory_usage", "as", "_mu", "try", ":", "ip", "=", "get_ipython", "(", ")", ...
load memory usage ipython magic, require memory_profiler package to be installed to get usage: %memit? Author: Vlad Niculae <vlad@vene.ro> Makes use of memory_profiler from Fabian Pedregosa available at https://github.com/fabianp/memory_profiler
[ "load", "memory", "usage", "ipython", "magic", "require", "memory_profiler", "package", "to", "be", "installed" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/utils.py#L147-L282
jfear/sramongo
sramongo/xml_helpers.py
parse_tree_from_dict
def parse_tree_from_dict(node, locs): """Processes key locations. Parameters ---------- node: xml.etree.ElementTree.ElementTree.element Current node. locs: dict A dictionary mapping key to a tuple. The tuple can either be 2 or 3 elements long. The first element maps to the l...
python
def parse_tree_from_dict(node, locs): """Processes key locations. Parameters ---------- node: xml.etree.ElementTree.ElementTree.element Current node. locs: dict A dictionary mapping key to a tuple. The tuple can either be 2 or 3 elements long. The first element maps to the l...
[ "def", "parse_tree_from_dict", "(", "node", ",", "locs", ")", ":", "d", "=", "dict", "(", ")", "for", "n", ",", "l", "in", "locs", ".", "items", "(", ")", ":", "try", ":", "if", "l", "[", "1", "]", "==", "'text'", ":", "d", "[", "n", "]", "...
Processes key locations. Parameters ---------- node: xml.etree.ElementTree.ElementTree.element Current node. locs: dict A dictionary mapping key to a tuple. The tuple can either be 2 or 3 elements long. The first element maps to the location in the current node. The seco...
[ "Processes", "key", "locations", "." ]
train
https://github.com/jfear/sramongo/blob/82a9a157e44bda4100be385c644b3ac21be66038/sramongo/xml_helpers.py#L26-L72
jfear/sramongo
sramongo/xml_helpers.py
xml_to_root
def xml_to_root(xml: Union[str, IO]) -> ElementTree.Element: """Parse XML into an ElemeTree object. Parameters ---------- xml : str or file-like object A filename, file object or string version of xml can be passed. Returns ------- Elementree.Element """ if isinstance(xml,...
python
def xml_to_root(xml: Union[str, IO]) -> ElementTree.Element: """Parse XML into an ElemeTree object. Parameters ---------- xml : str or file-like object A filename, file object or string version of xml can be passed. Returns ------- Elementree.Element """ if isinstance(xml,...
[ "def", "xml_to_root", "(", "xml", ":", "Union", "[", "str", ",", "IO", "]", ")", "->", "ElementTree", ".", "Element", ":", "if", "isinstance", "(", "xml", ",", "str", ")", ":", "if", "'<'", "in", "xml", ":", "return", "ElementTree", ".", "fromstring"...
Parse XML into an ElemeTree object. Parameters ---------- xml : str or file-like object A filename, file object or string version of xml can be passed. Returns ------- Elementree.Element
[ "Parse", "XML", "into", "an", "ElemeTree", "object", "." ]
train
https://github.com/jfear/sramongo/blob/82a9a157e44bda4100be385c644b3ac21be66038/sramongo/xml_helpers.py#L75-L95
elkiwy/paynter
paynter/image.py
Image.newLayer
def newLayer(self, effect=''): """ Creates a new :py:class:`Layer` and set that as the active. :param effect: A string with the blend mode for that layer that will be used when during the rendering process. The accepted values are: :code:`'soft_light','lighten','screen','dodge','addition','darken','multiply','...
python
def newLayer(self, effect=''): """ Creates a new :py:class:`Layer` and set that as the active. :param effect: A string with the blend mode for that layer that will be used when during the rendering process. The accepted values are: :code:`'soft_light','lighten','screen','dodge','addition','darken','multiply','...
[ "def", "newLayer", "(", "self", ",", "effect", "=", "''", ")", ":", "self", ".", "layers", ".", "append", "(", "Layer", "(", "effect", "=", "effect", ")", ")", "self", ".", "activeLayer", "=", "len", "(", "self", ".", "layers", ")", "-", "1" ]
Creates a new :py:class:`Layer` and set that as the active. :param effect: A string with the blend mode for that layer that will be used when during the rendering process. The accepted values are: :code:`'soft_light','lighten','screen','dodge','addition','darken','multiply','hard_light','difference','subtract','gr...
[ "Creates", "a", "new", ":", "py", ":", "class", ":", "Layer", "and", "set", "that", "as", "the", "active", ".", ":", "param", "effect", ":", "A", "string", "with", "the", "blend", "mode", "for", "that", "layer", "that", "will", "be", "used", "when", ...
train
https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/image.py#L54-L62
elkiwy/paynter
paynter/image.py
Image.duplicateActiveLayer
def duplicateActiveLayer(self): """ Duplicates the current active :py:class:`Layer`. :rtype: Nothing. """ activeLayer = self.layers[self.activeLayer] newLayer = Layer(data=activeLayer.data, effect=activeLayer.effect) self.layers.append(newLayer) self.activeLayer = len(self.layers)-1
python
def duplicateActiveLayer(self): """ Duplicates the current active :py:class:`Layer`. :rtype: Nothing. """ activeLayer = self.layers[self.activeLayer] newLayer = Layer(data=activeLayer.data, effect=activeLayer.effect) self.layers.append(newLayer) self.activeLayer = len(self.layers)-1
[ "def", "duplicateActiveLayer", "(", "self", ")", ":", "activeLayer", "=", "self", ".", "layers", "[", "self", ".", "activeLayer", "]", "newLayer", "=", "Layer", "(", "data", "=", "activeLayer", ".", "data", ",", "effect", "=", "activeLayer", ".", "effect",...
Duplicates the current active :py:class:`Layer`. :rtype: Nothing.
[ "Duplicates", "the", "current", "active", ":", "py", ":", "class", ":", "Layer", ".", ":", "rtype", ":", "Nothing", "." ]
train
https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/image.py#L65-L74
elkiwy/paynter
paynter/image.py
Image.mergeAllLayers
def mergeAllLayers(self): """ Merge all the layers together. :rtype: The result :py:class:`Layer` object. """ start = time.time() while(len(self.layers)>1): self.mergeBottomLayers() print('merge time:'+str(time.time()-start)) return self.layers[0]
python
def mergeAllLayers(self): """ Merge all the layers together. :rtype: The result :py:class:`Layer` object. """ start = time.time() while(len(self.layers)>1): self.mergeBottomLayers() print('merge time:'+str(time.time()-start)) return self.layers[0]
[ "def", "mergeAllLayers", "(", "self", ")", ":", "start", "=", "time", ".", "time", "(", ")", "while", "(", "len", "(", "self", ".", "layers", ")", ">", "1", ")", ":", "self", ".", "mergeBottomLayers", "(", ")", "print", "(", "'merge time:'", "+", "...
Merge all the layers together. :rtype: The result :py:class:`Layer` object.
[ "Merge", "all", "the", "layers", "together", "." ]
train
https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/image.py#L77-L87
Metatab/metatab
metatab/parser.py
TermParser.synonyms
def synonyms(self): """Return a dict of term synonyms""" syns = {} for k, v in self._declared_terms.items(): k = k.strip() if v.get('synonym'): syns[k.lower()] = v['synonym'] if not '.' in k: syns[ROOT_TERM + '.' + k.l...
python
def synonyms(self): """Return a dict of term synonyms""" syns = {} for k, v in self._declared_terms.items(): k = k.strip() if v.get('synonym'): syns[k.lower()] = v['synonym'] if not '.' in k: syns[ROOT_TERM + '.' + k.l...
[ "def", "synonyms", "(", "self", ")", ":", "syns", "=", "{", "}", "for", "k", ",", "v", "in", "self", ".", "_declared_terms", ".", "items", "(", ")", ":", "k", "=", "k", ".", "strip", "(", ")", "if", "v", ".", "get", "(", "'synonym'", ")", ":"...
Return a dict of term synonyms
[ "Return", "a", "dict", "of", "term", "synonyms" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/parser.py#L107-L119
Metatab/metatab
metatab/parser.py
TermParser.super_terms
def super_terms(self): """Return a dictionary mapping term names to their super terms""" # If the doc already has super terms, we've already parsed something, so # assume we parsed the declaration, and can use re-use the old decls. if self.doc and self.doc.super_terms: retur...
python
def super_terms(self): """Return a dictionary mapping term names to their super terms""" # If the doc already has super terms, we've already parsed something, so # assume we parsed the declaration, and can use re-use the old decls. if self.doc and self.doc.super_terms: retur...
[ "def", "super_terms", "(", "self", ")", ":", "# If the doc already has super terms, we've already parsed something, so", "# assume we parsed the declaration, and can use re-use the old decls.", "if", "self", ".", "doc", "and", "self", ".", "doc", ".", "super_terms", ":", "retur...
Return a dictionary mapping term names to their super terms
[ "Return", "a", "dictionary", "mapping", "term", "names", "to", "their", "super", "terms" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/parser.py#L123-L133
Metatab/metatab
metatab/parser.py
TermParser.declare_dict
def declare_dict(self): """Return declared sections, terms and synonyms as a dict""" # Run the parser, if it has not been run yet. if not self.root: for _ in self: pass return { 'sections': self._declared_sections, 'terms': self._declared_terms, ...
python
def declare_dict(self): """Return declared sections, terms and synonyms as a dict""" # Run the parser, if it has not been run yet. if not self.root: for _ in self: pass return { 'sections': self._declared_sections, 'terms': self._declared_terms, ...
[ "def", "declare_dict", "(", "self", ")", ":", "# Run the parser, if it has not been run yet.", "if", "not", "self", ".", "root", ":", "for", "_", "in", "self", ":", "pass", "return", "{", "'sections'", ":", "self", ".", "_declared_sections", ",", "'terms'", ":...
Return declared sections, terms and synonyms as a dict
[ "Return", "declared", "sections", "terms", "and", "synonyms", "as", "a", "dict" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/parser.py#L136-L146
Metatab/metatab
metatab/parser.py
TermParser.substitute_synonym
def substitute_synonym(self, nt): """ Replace the record_term and parent_term with a synonym :param nt: :return: """ if nt.join_lc in self.synonyms: nt.parent_term, nt.record_term = Term.split_term_lower(self.synonyms[nt.join_lc]);
python
def substitute_synonym(self, nt): """ Replace the record_term and parent_term with a synonym :param nt: :return: """ if nt.join_lc in self.synonyms: nt.parent_term, nt.record_term = Term.split_term_lower(self.synonyms[nt.join_lc]);
[ "def", "substitute_synonym", "(", "self", ",", "nt", ")", ":", "if", "nt", ".", "join_lc", "in", "self", ".", "synonyms", ":", "nt", ".", "parent_term", ",", "nt", ".", "record_term", "=", "Term", ".", "split_term_lower", "(", "self", ".", "synonyms", ...
Replace the record_term and parent_term with a synonym :param nt: :return:
[ "Replace", "the", "record_term", "and", "parent_term", "with", "a", "synonym", ":", "param", "nt", ":", ":", "return", ":" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/parser.py#L167-L175
Metatab/metatab
metatab/parser.py
TermParser.errors_as_dict
def errors_as_dict(self): """Return parse errors as a dict""" errors = [] for e in self.errors: errors.append({ 'file': e.term.file_name, 'row': e.term.row if e.term else '<unknown>', 'col': e.term.col if e.term else '<unknown>', ...
python
def errors_as_dict(self): """Return parse errors as a dict""" errors = [] for e in self.errors: errors.append({ 'file': e.term.file_name, 'row': e.term.row if e.term else '<unknown>', 'col': e.term.col if e.term else '<unknown>', ...
[ "def", "errors_as_dict", "(", "self", ")", ":", "errors", "=", "[", "]", "for", "e", "in", "self", ".", "errors", ":", "errors", ".", "append", "(", "{", "'file'", ":", "e", ".", "term", ".", "file_name", ",", "'row'", ":", "e", ".", "term", ".",...
Return parse errors as a dict
[ "Return", "parse", "errors", "as", "a", "dict" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/parser.py#L220-L234
Metatab/metatab
metatab/parser.py
TermParser.find_declare_doc
def find_declare_doc(self, d, name): """Given a name, try to resolve the name to a path or URL to a declaration document. It will try: * The name as a filesystem path * The name as a file name in the directory d * The name + '.csv' as a name in the directory d * The ...
python
def find_declare_doc(self, d, name): """Given a name, try to resolve the name to a path or URL to a declaration document. It will try: * The name as a filesystem path * The name as a file name in the directory d * The name + '.csv' as a name in the directory d * The ...
[ "def", "find_declare_doc", "(", "self", ",", "d", ",", "name", ")", ":", "path", "=", "None", "while", "True", ":", "if", "exists", "(", "name", ")", ":", "path", "=", "name", "break", "try", ":", "# Look for a local document", "path", "=", "declaration_...
Given a name, try to resolve the name to a path or URL to a declaration document. It will try: * The name as a filesystem path * The name as a file name in the directory d * The name + '.csv' as a name in the directory d * The name as a URL * The name as a key in th...
[ "Given", "a", "name", "try", "to", "resolve", "the", "name", "to", "a", "path", "or", "URL", "to", "a", "declaration", "document", ".", "It", "will", "try", ":" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/parser.py#L236-L281
Metatab/metatab
metatab/parser.py
TermParser.find_include_doc
def find_include_doc(self, d, name): """Resolve a name or path for an include doc to a an absolute path or url :param name: """ from metatab import parse_app_url include_ref = name.strip('/') if include_ref.startswith('http'): path = include_ref else...
python
def find_include_doc(self, d, name): """Resolve a name or path for an include doc to a an absolute path or url :param name: """ from metatab import parse_app_url include_ref = name.strip('/') if include_ref.startswith('http'): path = include_ref else...
[ "def", "find_include_doc", "(", "self", ",", "d", ",", "name", ")", ":", "from", "metatab", "import", "parse_app_url", "include_ref", "=", "name", ".", "strip", "(", "'/'", ")", "if", "include_ref", ".", "startswith", "(", "'http'", ")", ":", "path", "="...
Resolve a name or path for an include doc to a an absolute path or url :param name:
[ "Resolve", "a", "name", "or", "path", "for", "an", "include", "doc", "to", "a", "an", "absolute", "path", "or", "url", ":", "param", "name", ":" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/parser.py#L283-L300
Metatab/metatab
metatab/parser.py
TermParser.generate_terms
def generate_terms(self, ref, root, file_type=None): """An generator that yields term objects, handling includes and argument children. :param file_type: :param doc: :param root: :param ref: """ last_section = root t = None if isinstance...
python
def generate_terms(self, ref, root, file_type=None): """An generator that yields term objects, handling includes and argument children. :param file_type: :param doc: :param root: :param ref: """ last_section = root t = None if isinstance...
[ "def", "generate_terms", "(", "self", ",", "ref", ",", "root", ",", "file_type", "=", "None", ")", ":", "last_section", "=", "root", "t", "=", "None", "if", "isinstance", "(", "ref", ",", "Source", ")", ":", "row_gen", "=", "ref", "ref_path", "=", "r...
An generator that yields term objects, handling includes and argument children. :param file_type: :param doc: :param root: :param ref:
[ "An", "generator", "that", "yields", "term", "objects", "handling", "includes", "and", "argument", "children", ".", ":", "param", "file_type", ":", ":", "param", "doc", ":", ":", "param", "root", ":", ":", "param", "ref", ":" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/parser.py#L302-L410
Metatab/metatab
metatab/parser.py
TermParser.inherited_children
def inherited_children(self, t): """Generate inherited children based on a terms InhertsFrom property. The input term must have both an InheritsFrom property and a defined Section :param t: A subclassed terms -- has an InheritsFrom value """ if not t.get('inheritsfrom'): ...
python
def inherited_children(self, t): """Generate inherited children based on a terms InhertsFrom property. The input term must have both an InheritsFrom property and a defined Section :param t: A subclassed terms -- has an InheritsFrom value """ if not t.get('inheritsfrom'): ...
[ "def", "inherited_children", "(", "self", ",", "t", ")", ":", "if", "not", "t", ".", "get", "(", "'inheritsfrom'", ")", ":", "return", "if", "not", "'section'", "in", "t", ":", "raise", "DeclarationError", "(", "\"DeclareTerm for '{}' must specify a section to u...
Generate inherited children based on a terms InhertsFrom property. The input term must have both an InheritsFrom property and a defined Section :param t: A subclassed terms -- has an InheritsFrom value
[ "Generate", "inherited", "children", "based", "on", "a", "terms", "InhertsFrom", "property", ".", "The", "input", "term", "must", "have", "both", "an", "InheritsFrom", "property", "and", "a", "defined", "Section" ]
train
https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/parser.py#L548-L581
lazygunner/xunleipy
xunleipy/remote.py
XunLeiRemote.get_remote_peer_list
def get_remote_peer_list(self): ''' listPeer 返回列表 { "rtn":0, "peerList": [{ "category": "", "status": 0, "name": "GUNNER_HOME", "vodPort": 43566, "company": "XUNLEI_MIPS_BE_MIPS32", ...
python
def get_remote_peer_list(self): ''' listPeer 返回列表 { "rtn":0, "peerList": [{ "category": "", "status": 0, "name": "GUNNER_HOME", "vodPort": 43566, "company": "XUNLEI_MIPS_BE_MIPS32", ...
[ "def", "get_remote_peer_list", "(", "self", ")", ":", "params", "=", "{", "'type'", ":", "0", ",", "'v'", ":", "DEFAULT_V", ",", "'ct'", ":", "2", "}", "res", "=", "self", ".", "_get", "(", "'listPeer'", ",", "params", "=", "params", ")", "return", ...
listPeer 返回列表 { "rtn":0, "peerList": [{ "category": "", "status": 0, "name": "GUNNER_HOME", "vodPort": 43566, "company": "XUNLEI_MIPS_BE_MIPS32", "pid": "8498352EB4F5208X0001", ...
[ "listPeer", "返回列表", "{", "rtn", ":", "0", "peerList", ":", "[", "{", "category", ":", "status", ":", "0", "name", ":", "GUNNER_HOME", "vodPort", ":", "43566", "company", ":", "XUNLEI_MIPS_BE_MIPS32", "pid", ":", "8498352EB4F5208X0001", "lastLoginTime", ":", ...
train
https://github.com/lazygunner/xunleipy/blob/cded7598a7bf04495156bae2d747883d1eacb3f4/xunleipy/remote.py#L78-L108
lazygunner/xunleipy
xunleipy/remote.py
XunLeiRemote.get_remote_task_list
def get_remote_task_list( self, peer_id, list_type=ListType.downloading, pos=0, number=10): ''' list 返回列表 { "recycleNum": 0, "serverFailNum": 0, "rtn": 0, "completeNum": 34, "sync": 0, "tasks": [{ ...
python
def get_remote_task_list( self, peer_id, list_type=ListType.downloading, pos=0, number=10): ''' list 返回列表 { "recycleNum": 0, "serverFailNum": 0, "rtn": 0, "completeNum": 34, "sync": 0, "tasks": [{ ...
[ "def", "get_remote_task_list", "(", "self", ",", "peer_id", ",", "list_type", "=", "ListType", ".", "downloading", ",", "pos", "=", "0", ",", "number", "=", "10", ")", ":", "params", "=", "{", "'pid'", ":", "peer_id", ",", "'type'", ":", "list_type", "...
list 返回列表 { "recycleNum": 0, "serverFailNum": 0, "rtn": 0, "completeNum": 34, "sync": 0, "tasks": [{ "failCode": 15414, "vipChannel": { "available": 0, "failCode": 0, ...
[ "list", "返回列表", "{", "recycleNum", ":", "0", "serverFailNum", ":", "0", "rtn", ":", "0", "completeNum", ":", "34", "sync", ":", "0", "tasks", ":", "[", "{", "failCode", ":", "15414", "vipChannel", ":", "{", "available", ":", "0", "failCode", ":", "0"...
train
https://github.com/lazygunner/xunleipy/blob/cded7598a7bf04495156bae2d747883d1eacb3f4/xunleipy/remote.py#L118-L176
lazygunner/xunleipy
xunleipy/remote.py
XunLeiRemote.check_url
def check_url(self, pid, url_list): ''' urlCheck 返回数据 { "rtn": 0, "taskInfo": { "failCode": 0, "name": ".HDTVrip.1024X576.mkv", "url": "ed2k://|file|%E6%B0%", "type": 1, "id": "0", ...
python
def check_url(self, pid, url_list): ''' urlCheck 返回数据 { "rtn": 0, "taskInfo": { "failCode": 0, "name": ".HDTVrip.1024X576.mkv", "url": "ed2k://|file|%E6%B0%", "type": 1, "id": "0", ...
[ "def", "check_url", "(", "self", ",", "pid", ",", "url_list", ")", ":", "task_list", "=", "[", "]", "for", "url", "in", "url_list", ":", "params", "=", "{", "'pid'", ":", "pid", ",", "'url'", ":", "url", ",", "'type'", ":", "1", ",", "'v'", ":", ...
urlCheck 返回数据 { "rtn": 0, "taskInfo": { "failCode": 0, "name": ".HDTVrip.1024X576.mkv", "url": "ed2k://|file|%E6%B0%", "type": 1, "id": "0", "size": 505005442 } }
[ "urlCheck", "返回数据", "{", "rtn", ":", "0", "taskInfo", ":", "{", "failCode", ":", "0", "name", ":", ".", "HDTVrip", ".", "1024X576", ".", "mkv", "url", ":", "ed2k", ":", "//", "|file|%E6%B0%", "type", ":", "1", "id", ":", "0", "size", ":", "50500544...
train
https://github.com/lazygunner/xunleipy/blob/cded7598a7bf04495156bae2d747883d1eacb3f4/xunleipy/remote.py#L178-L220
lazygunner/xunleipy
xunleipy/remote.py
XunLeiRemote.add_tasks_to_remote
def add_tasks_to_remote(self, pid, path='C:/TDDOWNLOAD/', task_list=[]): ''' post data: { "path":"C:/TDDOWNLOAD/", "tasks":[{ "url":"ed2k://|file|%E6%B0%B8%E6%81%92.Forever...", "name":"永恒.Forever.S01E02.中英字幕.WEB-HR.mkv", "g...
python
def add_tasks_to_remote(self, pid, path='C:/TDDOWNLOAD/', task_list=[]): ''' post data: { "path":"C:/TDDOWNLOAD/", "tasks":[{ "url":"ed2k://|file|%E6%B0%B8%E6%81%92.Forever...", "name":"永恒.Forever.S01E02.中英字幕.WEB-HR.mkv", "g...
[ "def", "add_tasks_to_remote", "(", "self", ",", "pid", ",", "path", "=", "'C:/TDDOWNLOAD/'", ",", "task_list", "=", "[", "]", ")", ":", "if", "len", "(", "task_list", ")", "==", "0", ":", "return", "[", "]", "params", "=", "{", "'pid'", ":", "pid", ...
post data: { "path":"C:/TDDOWNLOAD/", "tasks":[{ "url":"ed2k://|file|%E6%B0%B8%E6%81%92.Forever...", "name":"永恒.Forever.S01E02.中英字幕.WEB-HR.mkv", "gcid":"", "cid":"", "filesize":512807020 }] ...
[ "post", "data", ":", "{", "path", ":", "C", ":", "/", "TDDOWNLOAD", "/", "tasks", ":", "[", "{", "url", ":", "ed2k", ":", "//", "|file|%E6%B0%B8%E6%81%92", ".", "Forever", "...", "name", ":", "永恒", ".", "Forever", ".", "S01E02", ".", "中英字幕", ".", "...
train
https://github.com/lazygunner/xunleipy/blob/cded7598a7bf04495156bae2d747883d1eacb3f4/xunleipy/remote.py#L233-L290
Capitains/Nautilus
capitains_nautilus/manager.py
read_levels
def read_levels(text): """ Read text and get there reffs :param text: Collection (Readable) :return: """ x = [] for i in range(0, len(NAUTILUSRESOLVER.getMetadata(text).citation)): x.append(NAUTILUSRESOLVER.getReffs(text, level=i)) return x
python
def read_levels(text): """ Read text and get there reffs :param text: Collection (Readable) :return: """ x = [] for i in range(0, len(NAUTILUSRESOLVER.getMetadata(text).citation)): x.append(NAUTILUSRESOLVER.getReffs(text, level=i)) return x
[ "def", "read_levels", "(", "text", ")", ":", "x", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "NAUTILUSRESOLVER", ".", "getMetadata", "(", "text", ")", ".", "citation", ")", ")", ":", "x", ".", "append", "(", "NAUTILUSRESOL...
Read text and get there reffs :param text: Collection (Readable) :return:
[ "Read", "text", "and", "get", "there", "reffs" ]
train
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/manager.py#L15-L24
Capitains/Nautilus
capitains_nautilus/manager.py
FlaskNautilusManager
def FlaskNautilusManager(resolver, flask_nautilus): """ Provides a manager for flask scripts to perform specific maintenance operations :param resolver: Nautilus Extension Instance :type resolver: NautilusCtsResolver :param flask_nautilus: Flask Application :type flask_nautilus: FlaskNautilus :...
python
def FlaskNautilusManager(resolver, flask_nautilus): """ Provides a manager for flask scripts to perform specific maintenance operations :param resolver: Nautilus Extension Instance :type resolver: NautilusCtsResolver :param flask_nautilus: Flask Application :type flask_nautilus: FlaskNautilus :...
[ "def", "FlaskNautilusManager", "(", "resolver", ",", "flask_nautilus", ")", ":", "global", "NAUTILUSRESOLVER", "NAUTILUSRESOLVER", "=", "resolver", "@", "click", ".", "group", "(", ")", "@", "click", ".", "option", "(", "'--verbose'", ",", "default", "=", "Fal...
Provides a manager for flask scripts to perform specific maintenance operations :param resolver: Nautilus Extension Instance :type resolver: NautilusCtsResolver :param flask_nautilus: Flask Application :type flask_nautilus: FlaskNautilus :return: CLI :rtype: click.group Import with .....
[ "Provides", "a", "manager", "for", "flask", "scripts", "to", "perform", "specific", "maintenance", "operations" ]
train
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/manager.py#L27-L102
chrisjsewell/jsonextended
jsonextended/edict.py
is_iter_non_string
def is_iter_non_string(obj): """test if object is a list or tuple""" if isinstance(obj, list) or isinstance(obj, tuple): return True return False
python
def is_iter_non_string(obj): """test if object is a list or tuple""" if isinstance(obj, list) or isinstance(obj, tuple): return True return False
[ "def", "is_iter_non_string", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "list", ")", "or", "isinstance", "(", "obj", ",", "tuple", ")", ":", "return", "True", "return", "False" ]
test if object is a list or tuple
[ "test", "if", "object", "is", "a", "list", "or", "tuple" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L45-L49
chrisjsewell/jsonextended
jsonextended/edict.py
is_dict_like
def is_dict_like(obj, attr=('keys', 'items')): """test if object is dict like""" for a in attr: if not hasattr(obj, a): return False return True
python
def is_dict_like(obj, attr=('keys', 'items')): """test if object is dict like""" for a in attr: if not hasattr(obj, a): return False return True
[ "def", "is_dict_like", "(", "obj", ",", "attr", "=", "(", "'keys'", ",", "'items'", ")", ")", ":", "for", "a", "in", "attr", ":", "if", "not", "hasattr", "(", "obj", ",", "a", ")", ":", "return", "False", "return", "True" ]
test if object is dict like
[ "test", "if", "object", "is", "dict", "like" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L58-L63
chrisjsewell/jsonextended
jsonextended/edict.py
is_list_of_dict_like
def is_list_of_dict_like(obj, attr=('keys', 'items')): """test if object is a list only containing dict like items """ try: if len(obj) == 0: return False return all([is_dict_like(i, attr) for i in obj]) except Exception: return False
python
def is_list_of_dict_like(obj, attr=('keys', 'items')): """test if object is a list only containing dict like items """ try: if len(obj) == 0: return False return all([is_dict_like(i, attr) for i in obj]) except Exception: return False
[ "def", "is_list_of_dict_like", "(", "obj", ",", "attr", "=", "(", "'keys'", ",", "'items'", ")", ")", ":", "try", ":", "if", "len", "(", "obj", ")", "==", "0", ":", "return", "False", "return", "all", "(", "[", "is_dict_like", "(", "i", ",", "attr"...
test if object is a list only containing dict like items
[ "test", "if", "object", "is", "a", "list", "only", "containing", "dict", "like", "items" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L66-L73
chrisjsewell/jsonextended
jsonextended/edict.py
is_path_like
def is_path_like(obj, attr=('name', 'is_file', 'is_dir', 'iterdir')): """test if object is pathlib.Path like""" for a in attr: if not hasattr(obj, a): return False return True
python
def is_path_like(obj, attr=('name', 'is_file', 'is_dir', 'iterdir')): """test if object is pathlib.Path like""" for a in attr: if not hasattr(obj, a): return False return True
[ "def", "is_path_like", "(", "obj", ",", "attr", "=", "(", "'name'", ",", "'is_file'", ",", "'is_dir'", ",", "'iterdir'", ")", ")", ":", "for", "a", "in", "attr", ":", "if", "not", "hasattr", "(", "obj", ",", "a", ")", ":", "return", "False", "retur...
test if object is pathlib.Path like
[ "test", "if", "object", "is", "pathlib", ".", "Path", "like" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L76-L81
chrisjsewell/jsonextended
jsonextended/edict.py
convert_type
def convert_type(d, intype, outtype, convert_list=True, in_place=True): """ convert all values of one type to another Parameters ---------- d : dict intype : type_class outtype : type_class convert_list : bool whether to convert instances inside lists and tuples in_place : bool ...
python
def convert_type(d, intype, outtype, convert_list=True, in_place=True): """ convert all values of one type to another Parameters ---------- d : dict intype : type_class outtype : type_class convert_list : bool whether to convert instances inside lists and tuples in_place : bool ...
[ "def", "convert_type", "(", "d", ",", "intype", ",", "outtype", ",", "convert_list", "=", "True", ",", "in_place", "=", "True", ")", ":", "if", "not", "in_place", ":", "out_dict", "=", "copy", ".", "deepcopy", "(", "d", ")", "else", ":", "out_dict", ...
convert all values of one type to another Parameters ---------- d : dict intype : type_class outtype : type_class convert_list : bool whether to convert instances inside lists and tuples in_place : bool if True, applies conversions to original dict, else returns copy Ex...
[ "convert", "all", "values", "of", "one", "type", "to", "another" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L84-L156
chrisjsewell/jsonextended
jsonextended/edict.py
pprint
def pprint(d, lvlindent=2, initindent=0, delim=':', max_width=80, depth=3, no_values=False, align_vals=True, print_func=None, keycolor=None, compress_lists=None, round_floats=None, _dlist=False): """ print a nested dict in readable format (- denotes an element in ...
python
def pprint(d, lvlindent=2, initindent=0, delim=':', max_width=80, depth=3, no_values=False, align_vals=True, print_func=None, keycolor=None, compress_lists=None, round_floats=None, _dlist=False): """ print a nested dict in readable format (- denotes an element in ...
[ "def", "pprint", "(", "d", ",", "lvlindent", "=", "2", ",", "initindent", "=", "0", ",", "delim", "=", "':'", ",", "max_width", "=", "80", ",", "depth", "=", "3", ",", "no_values", "=", "False", ",", "align_vals", "=", "True", ",", "print_func", "=...
print a nested dict in readable format (- denotes an element in a list of dictionaries) Parameters ---------- d : object lvlindent : int additional indentation spaces for each level initindent : int initial indentation spaces delim : str delimiter between key and...
[ "print", "a", "nested", "dict", "in", "readable", "format", "(", "-", "denotes", "an", "element", "in", "a", "list", "of", "dictionaries", ")" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L178-L364
chrisjsewell/jsonextended
jsonextended/edict.py
extract
def extract(d, path=None): """ extract section of dictionary Parameters ---------- d : dict path : list[str] keys to section Returns ------- new_dict : dict original, without extracted section extract_dict : dict extracted section Examples -------- ...
python
def extract(d, path=None): """ extract section of dictionary Parameters ---------- d : dict path : list[str] keys to section Returns ------- new_dict : dict original, without extracted section extract_dict : dict extracted section Examples -------- ...
[ "def", "extract", "(", "d", ",", "path", "=", "None", ")", ":", "path", "=", "[", "]", "if", "path", "is", "None", "else", "path", "d_new", "=", "copy", ".", "deepcopy", "(", "d", ")", "d_sub", "=", "d_new", "for", "key", "in", "path", "[", ":"...
extract section of dictionary Parameters ---------- d : dict path : list[str] keys to section Returns ------- new_dict : dict original, without extracted section extract_dict : dict extracted section Examples -------- >>> from pprint import pprint ...
[ "extract", "section", "of", "dictionary" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L367-L403
chrisjsewell/jsonextended
jsonextended/edict.py
indexes
def indexes(dic, keys=None): """ index dictionary by multiple keys Parameters ---------- dic : dict keys : list Examples -------- >>> d = {1:{"a":"A"},2:{"b":"B"}} >>> indexes(d,[1,'a']) 'A' """ keys = [] if keys is None else keys assert hasattr(dic, 'keys') ...
python
def indexes(dic, keys=None): """ index dictionary by multiple keys Parameters ---------- dic : dict keys : list Examples -------- >>> d = {1:{"a":"A"},2:{"b":"B"}} >>> indexes(d,[1,'a']) 'A' """ keys = [] if keys is None else keys assert hasattr(dic, 'keys') ...
[ "def", "indexes", "(", "dic", ",", "keys", "=", "None", ")", ":", "keys", "=", "[", "]", "if", "keys", "is", "None", "else", "keys", "assert", "hasattr", "(", "dic", ",", "'keys'", ")", "new", "=", "dic", ".", "copy", "(", ")", "old_key", "=", ...
index dictionary by multiple keys Parameters ---------- dic : dict keys : list Examples -------- >>> d = {1:{"a":"A"},2:{"b":"B"}} >>> indexes(d,[1,'a']) 'A'
[ "index", "dictionary", "by", "multiple", "keys" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L406-L432
chrisjsewell/jsonextended
jsonextended/edict.py
flatten
def flatten(d, key_as_tuple=True, sep='.', list_of_dicts=None, all_iters=None): """ get nested dict as flat {key:val,...}, where key is tuple/string of all nested keys Parameters ---------- d : object key_as_tuple : bool whether keys are list of nested keys or delimited string of nested...
python
def flatten(d, key_as_tuple=True, sep='.', list_of_dicts=None, all_iters=None): """ get nested dict as flat {key:val,...}, where key is tuple/string of all nested keys Parameters ---------- d : object key_as_tuple : bool whether keys are list of nested keys or delimited string of nested...
[ "def", "flatten", "(", "d", ",", "key_as_tuple", "=", "True", ",", "sep", "=", "'.'", ",", "list_of_dicts", "=", "None", ",", "all_iters", "=", "None", ")", ":", "def", "expand", "(", "key", ",", "value", ")", ":", "if", "is_dict_like", "(", "value",...
get nested dict as flat {key:val,...}, where key is tuple/string of all nested keys Parameters ---------- d : object key_as_tuple : bool whether keys are list of nested keys or delimited string of nested keys sep : str if key_as_tuple=False, delimiter for keys list_of_dicts:...
[ "get", "nested", "dict", "as", "flat", "{", "key", ":", "val", "...", "}", "where", "key", "is", "tuple", "/", "string", "of", "all", "nested", "keys" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L435-L520
chrisjsewell/jsonextended
jsonextended/edict.py
unflatten
def unflatten(d, key_as_tuple=True, delim='.', list_of_dicts=None, deepcopy=True): r""" unflatten dictionary with keys as tuples or delimited strings Parameters ---------- d : dict key_as_tuple : bool if true, keys are tuples, else, keys are delimited strings delim : str ...
python
def unflatten(d, key_as_tuple=True, delim='.', list_of_dicts=None, deepcopy=True): r""" unflatten dictionary with keys as tuples or delimited strings Parameters ---------- d : dict key_as_tuple : bool if true, keys are tuples, else, keys are delimited strings delim : str ...
[ "def", "unflatten", "(", "d", ",", "key_as_tuple", "=", "True", ",", "delim", "=", "'.'", ",", "list_of_dicts", "=", "None", ",", "deepcopy", "=", "True", ")", ":", "if", "not", "d", ":", "return", "d", "if", "deepcopy", ":", "try", ":", "d", "=", ...
r""" unflatten dictionary with keys as tuples or delimited strings Parameters ---------- d : dict key_as_tuple : bool if true, keys are tuples, else, keys are delimited strings delim : str if keys are strings, then split by delim list_of_dicts: str or None if key starts ...
[ "r", "unflatten", "dictionary", "with", "keys", "as", "tuples", "or", "delimited", "strings" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L543-L634
chrisjsewell/jsonextended
jsonextended/edict.py
_single_merge
def _single_merge(a, b, error_path=None, overwrite=False, append=False, list_of_dicts=False): """merges b into a """ if error_path is None: error_path = [] if list_of_dicts and is_list_of_dict_like(a) and is_list_of_dict_like(b): if len(a) != len(b): raise ...
python
def _single_merge(a, b, error_path=None, overwrite=False, append=False, list_of_dicts=False): """merges b into a """ if error_path is None: error_path = [] if list_of_dicts and is_list_of_dict_like(a) and is_list_of_dict_like(b): if len(a) != len(b): raise ...
[ "def", "_single_merge", "(", "a", ",", "b", ",", "error_path", "=", "None", ",", "overwrite", "=", "False", ",", "append", "=", "False", ",", "list_of_dicts", "=", "False", ")", ":", "if", "error_path", "is", "None", ":", "error_path", "=", "[", "]", ...
merges b into a
[ "merges", "b", "into", "a" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L637-L685
chrisjsewell/jsonextended
jsonextended/edict.py
merge
def merge(dicts, overwrite=False, append=False, list_of_dicts=False): """ merge dicts, starting with dicts[1] into dicts[0] Parameters ---------- dicts : list[dict] list of dictionaries overwrite : bool if true allow overwriting of current data append : bool if true ...
python
def merge(dicts, overwrite=False, append=False, list_of_dicts=False): """ merge dicts, starting with dicts[1] into dicts[0] Parameters ---------- dicts : list[dict] list of dictionaries overwrite : bool if true allow overwriting of current data append : bool if true ...
[ "def", "merge", "(", "dicts", ",", "overwrite", "=", "False", ",", "append", "=", "False", ",", "list_of_dicts", "=", "False", ")", ":", "# noqa: E501", "outdict", "=", "copy", ".", "deepcopy", "(", "dicts", "[", "0", "]", ")", "def", "single_merge", "...
merge dicts, starting with dicts[1] into dicts[0] Parameters ---------- dicts : list[dict] list of dictionaries overwrite : bool if true allow overwriting of current data append : bool if true and items are both lists, then add them list_of_dicts: bool treat ...
[ "merge", "dicts", "starting", "with", "dicts", "[", "1", "]", "into", "dicts", "[", "0", "]" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L688-L751
chrisjsewell/jsonextended
jsonextended/edict.py
flattennd
def flattennd(d, levels=0, key_as_tuple=True, delim='.', list_of_dicts=None): """ get nested dict as {key:dict,...}, where key is tuple/string of all-n levels of nested keys Parameters ---------- d : dict levels : int the number of levels to leave unflattened key_as_tu...
python
def flattennd(d, levels=0, key_as_tuple=True, delim='.', list_of_dicts=None): """ get nested dict as {key:dict,...}, where key is tuple/string of all-n levels of nested keys Parameters ---------- d : dict levels : int the number of levels to leave unflattened key_as_tu...
[ "def", "flattennd", "(", "d", ",", "levels", "=", "0", ",", "key_as_tuple", "=", "True", ",", "delim", "=", "'.'", ",", "list_of_dicts", "=", "None", ")", ":", "# noqa: E501", "if", "levels", "<", "0", ":", "raise", "ValueError", "(", "'unflattened level...
get nested dict as {key:dict,...}, where key is tuple/string of all-n levels of nested keys Parameters ---------- d : dict levels : int the number of levels to leave unflattened key_as_tuple : bool whether keys are list of nested keys or delimited string of nested keys delim...
[ "get", "nested", "dict", "as", "{", "key", ":", "dict", "...", "}", "where", "key", "is", "tuple", "/", "string", "of", "all", "-", "n", "levels", "of", "nested", "keys" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L754-L838
chrisjsewell/jsonextended
jsonextended/edict.py
flatten2d
def flatten2d(d, key_as_tuple=True, delim='.', list_of_dicts=None): """ get nested dict as {key:dict,...}, where key is tuple/string of all-1 nested keys NB: is same as flattennd(d,1,key_as_tuple,delim) Parameters ---------- d : dict key_as_tuple : bool whether keys a...
python
def flatten2d(d, key_as_tuple=True, delim='.', list_of_dicts=None): """ get nested dict as {key:dict,...}, where key is tuple/string of all-1 nested keys NB: is same as flattennd(d,1,key_as_tuple,delim) Parameters ---------- d : dict key_as_tuple : bool whether keys a...
[ "def", "flatten2d", "(", "d", ",", "key_as_tuple", "=", "True", ",", "delim", "=", "'.'", ",", "list_of_dicts", "=", "None", ")", ":", "return", "flattennd", "(", "d", ",", "1", ",", "key_as_tuple", ",", "delim", ",", "list_of_dicts", "=", "list_of_dicts...
get nested dict as {key:dict,...}, where key is tuple/string of all-1 nested keys NB: is same as flattennd(d,1,key_as_tuple,delim) Parameters ---------- d : dict key_as_tuple : bool whether keys are list of nested keys or delimited string of nested keys delim : str if key_a...
[ "get", "nested", "dict", "as", "{", "key", ":", "dict", "...", "}", "where", "key", "is", "tuple", "/", "string", "of", "all", "-", "1", "nested", "keys" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L841-L871
chrisjsewell/jsonextended
jsonextended/edict.py
remove_keys
def remove_keys(d, keys=None, use_wildcards=True, list_of_dicts=False, deepcopy=True): """remove certain keys from nested dict, retaining preceeding paths Parameters ---------- keys: list use_wildcards : bool if true, can use * (matches everything) and ? (matches any...
python
def remove_keys(d, keys=None, use_wildcards=True, list_of_dicts=False, deepcopy=True): """remove certain keys from nested dict, retaining preceeding paths Parameters ---------- keys: list use_wildcards : bool if true, can use * (matches everything) and ? (matches any...
[ "def", "remove_keys", "(", "d", ",", "keys", "=", "None", ",", "use_wildcards", "=", "True", ",", "list_of_dicts", "=", "False", ",", "deepcopy", "=", "True", ")", ":", "keys", "=", "[", "]", "if", "keys", "is", "None", "else", "keys", "list_of_dicts",...
remove certain keys from nested dict, retaining preceeding paths Parameters ---------- keys: list use_wildcards : bool if true, can use * (matches everything) and ? (matches any single character) list_of_dicts: bool treat list of dicts as additional branches deepcopy: bo...
[ "remove", "certain", "keys", "from", "nested", "dict", "retaining", "preceeding", "paths" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L874-L938
chrisjsewell/jsonextended
jsonextended/edict.py
remove_keyvals
def remove_keyvals(d, keyvals=None, list_of_dicts=False, deepcopy=True): """remove paths with at least one branch leading to certain (key,value) pairs from dict Parameters ---------- d : dict keyvals : dict or list[tuple] (key,value) pairs to remove list_of_dicts: bool treat...
python
def remove_keyvals(d, keyvals=None, list_of_dicts=False, deepcopy=True): """remove paths with at least one branch leading to certain (key,value) pairs from dict Parameters ---------- d : dict keyvals : dict or list[tuple] (key,value) pairs to remove list_of_dicts: bool treat...
[ "def", "remove_keyvals", "(", "d", ",", "keyvals", "=", "None", ",", "list_of_dicts", "=", "False", ",", "deepcopy", "=", "True", ")", ":", "keyvals", "=", "[", "]", "if", "keyvals", "is", "None", "else", "keyvals", "list_of_dicts", "=", "'__list__'", "i...
remove paths with at least one branch leading to certain (key,value) pairs from dict Parameters ---------- d : dict keyvals : dict or list[tuple] (key,value) pairs to remove list_of_dicts: bool treat list of dicts as additional branches Examples -------- >>> from p...
[ "remove", "paths", "with", "at", "least", "one", "branch", "leading", "to", "certain", "(", "key", "value", ")", "pairs", "from", "dict" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L941-L989
chrisjsewell/jsonextended
jsonextended/edict.py
remove_paths
def remove_paths(d, keys, list_of_dicts=False, deepcopy=True): """ remove paths containing certain keys from dict Parameters ---------- d: dict keys : list list of keys to find and remove path list_of_dicts: bool treat list of dicts as additional branches deepcopy: bool ...
python
def remove_paths(d, keys, list_of_dicts=False, deepcopy=True): """ remove paths containing certain keys from dict Parameters ---------- d: dict keys : list list of keys to find and remove path list_of_dicts: bool treat list of dicts as additional branches deepcopy: bool ...
[ "def", "remove_paths", "(", "d", ",", "keys", ",", "list_of_dicts", "=", "False", ",", "deepcopy", "=", "True", ")", ":", "keys", "=", "[", "(", "key", ",", ")", "if", "not", "isinstance", "(", "key", ",", "tuple", ")", "else", "key", "for", "key",...
remove paths containing certain keys from dict Parameters ---------- d: dict keys : list list of keys to find and remove path list_of_dicts: bool treat list of dicts as additional branches deepcopy: bool deepcopy values Examples -------- >>> from pprint imp...
[ "remove", "paths", "containing", "certain", "keys", "from", "dict" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L992-L1039
chrisjsewell/jsonextended
jsonextended/edict.py
filter_values
def filter_values(d, vals=None, list_of_dicts=False, deepcopy=True): """ filters leaf nodes of nested dictionary Parameters ---------- d : dict vals : list values to filter by list_of_dicts: bool treat list of dicts as additional branches deepcopy: bool deepcopy valu...
python
def filter_values(d, vals=None, list_of_dicts=False, deepcopy=True): """ filters leaf nodes of nested dictionary Parameters ---------- d : dict vals : list values to filter by list_of_dicts: bool treat list of dicts as additional branches deepcopy: bool deepcopy valu...
[ "def", "filter_values", "(", "d", ",", "vals", "=", "None", ",", "list_of_dicts", "=", "False", ",", "deepcopy", "=", "True", ")", ":", "vals", "=", "[", "]", "if", "vals", "is", "None", "else", "vals", "list_of_dicts", "=", "'__list__'", "if", "list_o...
filters leaf nodes of nested dictionary Parameters ---------- d : dict vals : list values to filter by list_of_dicts: bool treat list of dicts as additional branches deepcopy: bool deepcopy values Examples -------- >>> d = {1:{"a":"A"},2:{"b":"B"},4:{5:{6:'...
[ "filters", "leaf", "nodes", "of", "nested", "dictionary" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L1044-L1077
chrisjsewell/jsonextended
jsonextended/edict.py
filter_keyvals
def filter_keyvals(d, keyvals, logic="OR", keep_siblings=False, list_of_dicts=False, deepcopy=True): """ filters leaf nodes key:value pairs of nested dictionary Parameters ---------- d : dict keyvals : dict or list[tuple] (key,value) pairs to filter by logic : str ...
python
def filter_keyvals(d, keyvals, logic="OR", keep_siblings=False, list_of_dicts=False, deepcopy=True): """ filters leaf nodes key:value pairs of nested dictionary Parameters ---------- d : dict keyvals : dict or list[tuple] (key,value) pairs to filter by logic : str ...
[ "def", "filter_keyvals", "(", "d", ",", "keyvals", ",", "logic", "=", "\"OR\"", ",", "keep_siblings", "=", "False", ",", "list_of_dicts", "=", "False", ",", "deepcopy", "=", "True", ")", ":", "# noqa: E501", "if", "len", "(", "keyvals", ")", "!=", "len",...
filters leaf nodes key:value pairs of nested dictionary Parameters ---------- d : dict keyvals : dict or list[tuple] (key,value) pairs to filter by logic : str "OR" or "AND" for matching pairs keep_siblings : bool keep all sibling paths list_of_dicts : bool t...
[ "filters", "leaf", "nodes", "key", ":", "value", "pairs", "of", "nested", "dictionary" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L1088-L1177
chrisjsewell/jsonextended
jsonextended/edict.py
filter_keys
def filter_keys(d, keys, use_wildcards=False, list_of_dicts=False, deepcopy=True): """ filter dict by certain keys Parameters ---------- d : dict keys: list use_wildcards : bool if true, can use * (matches everything) and ? (matches any single character) list...
python
def filter_keys(d, keys, use_wildcards=False, list_of_dicts=False, deepcopy=True): """ filter dict by certain keys Parameters ---------- d : dict keys: list use_wildcards : bool if true, can use * (matches everything) and ? (matches any single character) list...
[ "def", "filter_keys", "(", "d", ",", "keys", ",", "use_wildcards", "=", "False", ",", "list_of_dicts", "=", "False", ",", "deepcopy", "=", "True", ")", ":", "list_of_dicts", "=", "'__list__'", "if", "list_of_dicts", "else", "None", "flatd", "=", "flatten", ...
filter dict by certain keys Parameters ---------- d : dict keys: list use_wildcards : bool if true, can use * (matches everything) and ? (matches any single character) list_of_dicts: bool treat list of dicts as additional branches deepcopy: bool deepcopy valu...
[ "filter", "dict", "by", "certain", "keys" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L1264-L1316
chrisjsewell/jsonextended
jsonextended/edict.py
filter_paths
def filter_paths(d, paths, list_of_dicts=False, deepcopy=True): """ filter dict by certain paths containing key sets Parameters ---------- d : dict paths : list[str] or list[tuple] list_of_dicts: bool treat list of dicts as additional branches deepcopy: bool deepcopy values ...
python
def filter_paths(d, paths, list_of_dicts=False, deepcopy=True): """ filter dict by certain paths containing key sets Parameters ---------- d : dict paths : list[str] or list[tuple] list_of_dicts: bool treat list of dicts as additional branches deepcopy: bool deepcopy values ...
[ "def", "filter_paths", "(", "d", ",", "paths", ",", "list_of_dicts", "=", "False", ",", "deepcopy", "=", "True", ")", ":", "list_of_dicts", "=", "'__list__'", "if", "list_of_dicts", "else", "None", "all_keys", "=", "[", "x", "for", "y", "in", "paths", "i...
filter dict by certain paths containing key sets Parameters ---------- d : dict paths : list[str] or list[tuple] list_of_dicts: bool treat list of dicts as additional branches deepcopy: bool deepcopy values Examples -------- >>> from pprint import pprint >>> d ...
[ "filter", "dict", "by", "certain", "paths", "containing", "key", "sets" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L1319-L1359
chrisjsewell/jsonextended
jsonextended/edict.py
rename_keys
def rename_keys(d, keymap=None, list_of_dicts=False, deepcopy=True): """ rename keys in dict Parameters ---------- d : dict keymap : dict dictionary of key name mappings list_of_dicts: bool treat list of dicts as additional branches deepcopy: bool deepcopy values ...
python
def rename_keys(d, keymap=None, list_of_dicts=False, deepcopy=True): """ rename keys in dict Parameters ---------- d : dict keymap : dict dictionary of key name mappings list_of_dicts: bool treat list of dicts as additional branches deepcopy: bool deepcopy values ...
[ "def", "rename_keys", "(", "d", ",", "keymap", "=", "None", ",", "list_of_dicts", "=", "False", ",", "deepcopy", "=", "True", ")", ":", "list_of_dicts", "=", "'__list__'", "if", "list_of_dicts", "else", "None", "keymap", "=", "{", "}", "if", "keymap", "i...
rename keys in dict Parameters ---------- d : dict keymap : dict dictionary of key name mappings list_of_dicts: bool treat list of dicts as additional branches deepcopy: bool deepcopy values Examples -------- >>> from pprint import pprint >>> d = {'a':{...
[ "rename", "keys", "in", "dict" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L1362-L1393
chrisjsewell/jsonextended
jsonextended/edict.py
split_key
def split_key(d, key, new_keys, before=True, list_of_dicts=False, deepcopy=True): """ split an existing key(s) into multiple levels Parameters ---------- d : dict or dict like key: str existing key value new_keys: list[str] new levels to add before: boo...
python
def split_key(d, key, new_keys, before=True, list_of_dicts=False, deepcopy=True): """ split an existing key(s) into multiple levels Parameters ---------- d : dict or dict like key: str existing key value new_keys: list[str] new levels to add before: boo...
[ "def", "split_key", "(", "d", ",", "key", ",", "new_keys", ",", "before", "=", "True", ",", "list_of_dicts", "=", "False", ",", "deepcopy", "=", "True", ")", ":", "list_of_dicts", "=", "'__list__'", "if", "list_of_dicts", "else", "None", "flatd", "=", "f...
split an existing key(s) into multiple levels Parameters ---------- d : dict or dict like key: str existing key value new_keys: list[str] new levels to add before: bool add level before existing key (else after) list_of_dicts: bool treat list of dicts...
[ "split", "an", "existing", "key", "(", "s", ")", "into", "multiple", "levels" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L1398-L1449
chrisjsewell/jsonextended
jsonextended/edict.py
apply
def apply(d, leaf_key, func, new_name=None, remove_lkey=True, list_of_dicts=False, unflatten_level=0, deepcopy=True, **kwargs): """ apply a function to all values with a certain leaf (terminal) key Parameters ---------- d : dict leaf_key : str name of leaf key func : callable ...
python
def apply(d, leaf_key, func, new_name=None, remove_lkey=True, list_of_dicts=False, unflatten_level=0, deepcopy=True, **kwargs): """ apply a function to all values with a certain leaf (terminal) key Parameters ---------- d : dict leaf_key : str name of leaf key func : callable ...
[ "def", "apply", "(", "d", ",", "leaf_key", ",", "func", ",", "new_name", "=", "None", ",", "remove_lkey", "=", "True", ",", "list_of_dicts", "=", "False", ",", "unflatten_level", "=", "0", ",", "deepcopy", "=", "True", ",", "*", "*", "kwargs", ")", "...
apply a function to all values with a certain leaf (terminal) key Parameters ---------- d : dict leaf_key : str name of leaf key func : callable function to apply new_name : str if not None, rename leaf_key remove_lkey: bool whether to remove original leaf_ke...
[ "apply", "a", "function", "to", "all", "values", "with", "a", "certain", "leaf", "(", "terminal", ")", "key" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L1452-L1508
chrisjsewell/jsonextended
jsonextended/edict.py
combine_apply
def combine_apply(d, leaf_keys, func, new_name, unflatten_level=1, remove_lkeys=True, overwrite=False, list_of_dicts=False, deepcopy=True, **kwargs): """ combine values with certain leaf (terminal) keys by a function Parameters ---------- d : dict leaf_keys : lis...
python
def combine_apply(d, leaf_keys, func, new_name, unflatten_level=1, remove_lkeys=True, overwrite=False, list_of_dicts=False, deepcopy=True, **kwargs): """ combine values with certain leaf (terminal) keys by a function Parameters ---------- d : dict leaf_keys : lis...
[ "def", "combine_apply", "(", "d", ",", "leaf_keys", ",", "func", ",", "new_name", ",", "unflatten_level", "=", "1", ",", "remove_lkeys", "=", "True", ",", "overwrite", "=", "False", ",", "list_of_dicts", "=", "False", ",", "deepcopy", "=", "True", ",", "...
combine values with certain leaf (terminal) keys by a function Parameters ---------- d : dict leaf_keys : list names of leaf keys func : callable function to apply, must take at least len(leaf_keys) arguments new_name : str new key name unflatten_level : int ...
[ "combine", "values", "with", "certain", "leaf", "(", "terminal", ")", "keys", "by", "a", "function" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L1511-L1585
chrisjsewell/jsonextended
jsonextended/edict.py
split_lists
def split_lists(d, split_keys, new_name='split', check_length=True, deepcopy=True): """split_lists key:list pairs into dicts for each item in the lists NB: will only split if all split_keys are present Parameters ---------- d : dict split_keys : list keys to split ne...
python
def split_lists(d, split_keys, new_name='split', check_length=True, deepcopy=True): """split_lists key:list pairs into dicts for each item in the lists NB: will only split if all split_keys are present Parameters ---------- d : dict split_keys : list keys to split ne...
[ "def", "split_lists", "(", "d", ",", "split_keys", ",", "new_name", "=", "'split'", ",", "check_length", "=", "True", ",", "deepcopy", "=", "True", ")", ":", "# noqa: E501", "flattened", "=", "flatten2d", "(", "d", ")", "new_d", "=", "{", "}", "for", "...
split_lists key:list pairs into dicts for each item in the lists NB: will only split if all split_keys are present Parameters ---------- d : dict split_keys : list keys to split new_name : str top level key for split items check_length : bool if true, raise error if ...
[ "split_lists", "key", ":", "list", "pairs", "into", "dicts", "for", "each", "item", "in", "the", "lists", "NB", ":", "will", "only", "split", "if", "all", "split_keys", "are", "present" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L1588-L1670
chrisjsewell/jsonextended
jsonextended/edict.py
combine_lists
def combine_lists(d, keys=None, deepcopy=True): """combine lists of dicts Parameters ---------- d : dict or list[dict] keys : list keys to combine (all if None) deepcopy: bool deepcopy values Example ------- >>> from pprint import pprint >>> d = {'path_key': {'a...
python
def combine_lists(d, keys=None, deepcopy=True): """combine lists of dicts Parameters ---------- d : dict or list[dict] keys : list keys to combine (all if None) deepcopy: bool deepcopy values Example ------- >>> from pprint import pprint >>> d = {'path_key': {'a...
[ "def", "combine_lists", "(", "d", ",", "keys", "=", "None", ",", "deepcopy", "=", "True", ")", ":", "# noqa: E501", "if", "isinstance", "(", "d", ",", "list", ")", ":", "init_list", "=", "True", "d", "=", "{", "'dummy_key843'", ":", "d", "}", "else",...
combine lists of dicts Parameters ---------- d : dict or list[dict] keys : list keys to combine (all if None) deepcopy: bool deepcopy values Example ------- >>> from pprint import pprint >>> d = {'path_key': {'a': 1, 'split': [{'x': 1, 'y': 3}, {'x': 2, 'y': 4}]}} ...
[ "combine", "lists", "of", "dicts" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L1673-L1727
chrisjsewell/jsonextended
jsonextended/edict.py
list_to_dict
def list_to_dict(lst, key=None, remove_key=True): """ convert a list of dicts to a dict with root keys Parameters ---------- lst : list[dict] key : str or None a key contained by all of the dicts if None use index number string remove_key : bool remove key from dicts in ...
python
def list_to_dict(lst, key=None, remove_key=True): """ convert a list of dicts to a dict with root keys Parameters ---------- lst : list[dict] key : str or None a key contained by all of the dicts if None use index number string remove_key : bool remove key from dicts in ...
[ "def", "list_to_dict", "(", "lst", ",", "key", "=", "None", ",", "remove_key", "=", "True", ")", ":", "assert", "all", "(", "[", "is_dict_like", "(", "d", ")", "for", "d", "in", "lst", "]", ")", "if", "key", "is", "not", "None", ":", "assert", "a...
convert a list of dicts to a dict with root keys Parameters ---------- lst : list[dict] key : str or None a key contained by all of the dicts if None use index number string remove_key : bool remove key from dicts in list Examples -------- >>> from pprint import...
[ "convert", "a", "list", "of", "dicts", "to", "a", "dict", "with", "root", "keys" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L1730-L1769
chrisjsewell/jsonextended
jsonextended/edict.py
diff
def diff(new_dict, old_dict, iter_prefix='__iter__', np_allclose=False, **kwargs): """ return the difference between two dict_like objects Parameters ---------- new_dict: dict old_dict: dict iter_prefix: str prefix to use for list and tuple indexes np_allclose: bool ...
python
def diff(new_dict, old_dict, iter_prefix='__iter__', np_allclose=False, **kwargs): """ return the difference between two dict_like objects Parameters ---------- new_dict: dict old_dict: dict iter_prefix: str prefix to use for list and tuple indexes np_allclose: bool ...
[ "def", "diff", "(", "new_dict", ",", "old_dict", ",", "iter_prefix", "=", "'__iter__'", ",", "np_allclose", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "np_allclose", ":", "try", ":", "import", "numpy", "except", "ImportError", ":", "raise", "...
return the difference between two dict_like objects Parameters ---------- new_dict: dict old_dict: dict iter_prefix: str prefix to use for list and tuple indexes np_allclose: bool if True, try using numpy.allclose to assess differences **kwargs: keyword arguments to ...
[ "return", "the", "difference", "between", "two", "dict_like", "objects" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L1772-L1862
chrisjsewell/jsonextended
jsonextended/edict.py
to_json
def to_json(dct, jfile, overwrite=False, dirlevel=0, sort_keys=True, indent=2, default_name='root.json', **kwargs): """ output dict to json Parameters ---------- dct : dict jfile : str or file_like if file_like, must have write method overwrite : bool whether to over...
python
def to_json(dct, jfile, overwrite=False, dirlevel=0, sort_keys=True, indent=2, default_name='root.json', **kwargs): """ output dict to json Parameters ---------- dct : dict jfile : str or file_like if file_like, must have write method overwrite : bool whether to over...
[ "def", "to_json", "(", "dct", ",", "jfile", ",", "overwrite", "=", "False", ",", "dirlevel", "=", "0", ",", "sort_keys", "=", "True", ",", "indent", "=", "2", ",", "default_name", "=", "'root.json'", ",", "*", "*", "kwargs", ")", ":", "if", "hasattr"...
output dict to json Parameters ---------- dct : dict jfile : str or file_like if file_like, must have write method overwrite : bool whether to overwrite existing files dirlevel : int if jfile is path to folder, defines how many key levels to set as sub-folders ...
[ "output", "dict", "to", "json" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L1865-L1978
chrisjsewell/jsonextended
jsonextended/edict.py
dump
def dump(dct, jfile, overwrite=False, dirlevel=0, sort_keys=True, indent=2, default_name='root.json', **kwargs): """ output dict to json Parameters ---------- dct : dict jfile : str or file_like if file_like, must have write method overwrite : bool whether to overwrite ...
python
def dump(dct, jfile, overwrite=False, dirlevel=0, sort_keys=True, indent=2, default_name='root.json', **kwargs): """ output dict to json Parameters ---------- dct : dict jfile : str or file_like if file_like, must have write method overwrite : bool whether to overwrite ...
[ "def", "dump", "(", "dct", ",", "jfile", ",", "overwrite", "=", "False", ",", "dirlevel", "=", "0", ",", "sort_keys", "=", "True", ",", "indent", "=", "2", ",", "default_name", "=", "'root.json'", ",", "*", "*", "kwargs", ")", ":", "to_json", "(", ...
output dict to json Parameters ---------- dct : dict jfile : str or file_like if file_like, must have write method overwrite : bool whether to overwrite existing files dirlevel : int if jfile is path to folder, defines how many key levels to set as sub-folders ...
[ "output", "dict", "to", "json" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/edict.py#L1981-L2005
bjodah/pycompilation
pycompilation/util.py
expand_collection_in_dict
def expand_collection_in_dict(d, key, new_items, no_duplicates=True): """ Parameters d: dict dict in which a key will be inserted/expanded key: hashable key in d new_items: iterable d[key] will be extended with items in new_items no_duplicates: bool avoid insertin...
python
def expand_collection_in_dict(d, key, new_items, no_duplicates=True): """ Parameters d: dict dict in which a key will be inserted/expanded key: hashable key in d new_items: iterable d[key] will be extended with items in new_items no_duplicates: bool avoid insertin...
[ "def", "expand_collection_in_dict", "(", "d", ",", "key", ",", "new_items", ",", "no_duplicates", "=", "True", ")", ":", "if", "key", "in", "d", ":", "if", "no_duplicates", ":", "new_items", "=", "filter", "(", "lambda", "x", ":", "x", "not", "in", "d"...
Parameters d: dict dict in which a key will be inserted/expanded key: hashable key in d new_items: iterable d[key] will be extended with items in new_items no_duplicates: bool avoid inserting duplicates in d[key] (default: True)
[ "Parameters", "d", ":", "dict", "dict", "in", "which", "a", "key", "will", "be", "inserted", "/", "expanded", "key", ":", "hashable", "key", "in", "d", "new_items", ":", "iterable", "d", "[", "key", "]", "will", "be", "extended", "with", "items", "in",...
train
https://github.com/bjodah/pycompilation/blob/43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18/pycompilation/util.py#L22-L44
bjodah/pycompilation
pycompilation/util.py
copy
def copy(src, dst, only_update=False, copystat=True, cwd=None, dest_is_dir=False, create_dest_dirs=False, logger=None): """ Augmented shutil.copy with extra options and slightly modified behaviour Parameters ========== src: string path to source file dst: string pat...
python
def copy(src, dst, only_update=False, copystat=True, cwd=None, dest_is_dir=False, create_dest_dirs=False, logger=None): """ Augmented shutil.copy with extra options and slightly modified behaviour Parameters ========== src: string path to source file dst: string pat...
[ "def", "copy", "(", "src", ",", "dst", ",", "only_update", "=", "False", ",", "copystat", "=", "True", ",", "cwd", "=", "None", ",", "dest_is_dir", "=", "False", ",", "create_dest_dirs", "=", "False", ",", "logger", "=", "None", ")", ":", "# Handle vir...
Augmented shutil.copy with extra options and slightly modified behaviour Parameters ========== src: string path to source file dst: string path to destingation only_update: bool only copy if source is newer than destination (returns None if it was newer), default...
[ "Augmented", "shutil", ".", "copy", "with", "extra", "options", "and", "slightly", "modified", "behaviour" ]
train
https://github.com/bjodah/pycompilation/blob/43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18/pycompilation/util.py#L92-L178
bjodah/pycompilation
pycompilation/util.py
md5_of_file
def md5_of_file(path, nblocks=128): """ Computes the md5 hash of a file. Parameters ========== path: string path to file to compute hash of Returns ======= hashlib md5 hash object. Use .digest() or .hexdigest() on returned object to get binary or hex encoded string. """...
python
def md5_of_file(path, nblocks=128): """ Computes the md5 hash of a file. Parameters ========== path: string path to file to compute hash of Returns ======= hashlib md5 hash object. Use .digest() or .hexdigest() on returned object to get binary or hex encoded string. """...
[ "def", "md5_of_file", "(", "path", ",", "nblocks", "=", "128", ")", ":", "md", "=", "md5", "(", ")", "with", "open", "(", "path", ",", "'rb'", ")", "as", "f", ":", "for", "chunk", "in", "iter", "(", "lambda", ":", "f", ".", "read", "(", "nblock...
Computes the md5 hash of a file. Parameters ========== path: string path to file to compute hash of Returns ======= hashlib md5 hash object. Use .digest() or .hexdigest() on returned object to get binary or hex encoded string.
[ "Computes", "the", "md5", "hash", "of", "a", "file", "." ]
train
https://github.com/bjodah/pycompilation/blob/43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18/pycompilation/util.py#L181-L199
bjodah/pycompilation
pycompilation/util.py
missing_or_other_newer
def missing_or_other_newer(path, other_path, cwd=None): """ Investigate if path is non-existant or older than provided reference path. Parameters ========== path: string path to path which might be missing or too old other_path: string reference path cwd: string ...
python
def missing_or_other_newer(path, other_path, cwd=None): """ Investigate if path is non-existant or older than provided reference path. Parameters ========== path: string path to path which might be missing or too old other_path: string reference path cwd: string ...
[ "def", "missing_or_other_newer", "(", "path", ",", "other_path", ",", "cwd", "=", "None", ")", ":", "cwd", "=", "cwd", "or", "'.'", "path", "=", "get_abspath", "(", "path", ",", "cwd", "=", "cwd", ")", "other_path", "=", "get_abspath", "(", "other_path",...
Investigate if path is non-existant or older than provided reference path. Parameters ========== path: string path to path which might be missing or too old other_path: string reference path cwd: string working directory (root of relative paths) Returns ======= ...
[ "Investigate", "if", "path", "is", "non", "-", "existant", "or", "older", "than", "provided", "reference", "path", "." ]
train
https://github.com/bjodah/pycompilation/blob/43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18/pycompilation/util.py#L208-L234
bjodah/pycompilation
pycompilation/util.py
import_module_from_file
def import_module_from_file(filename, only_if_newer_than=None): """ Imports (cython generated) shared object file (.so) Provide a list of paths in `only_if_newer_than` to check timestamps of dependencies. import_ raises an ImportError if any is newer. Word of warning: Python's caching or the O...
python
def import_module_from_file(filename, only_if_newer_than=None): """ Imports (cython generated) shared object file (.so) Provide a list of paths in `only_if_newer_than` to check timestamps of dependencies. import_ raises an ImportError if any is newer. Word of warning: Python's caching or the O...
[ "def", "import_module_from_file", "(", "filename", ",", "only_if_newer_than", "=", "None", ")", ":", "import", "imp", "path", ",", "name", "=", "os", ".", "path", ".", "split", "(", "filename", ")", "name", ",", "ext", "=", "os", ".", "path", ".", "spl...
Imports (cython generated) shared object file (.so) Provide a list of paths in `only_if_newer_than` to check timestamps of dependencies. import_ raises an ImportError if any is newer. Word of warning: Python's caching or the OS caching (unclear to author) is horrible for reimporting same path of a...
[ "Imports", "(", "cython", "generated", ")", "shared", "object", "file", "(", ".", "so", ")" ]
train
https://github.com/bjodah/pycompilation/blob/43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18/pycompilation/util.py#L281-L318