repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
geoadmin/lib-gatilegrid
gatilegrid/tilegrids.py
_TileGrid.getZoom
def getZoom(self, resolution): "Return the zoom level for a given resolution" assert resolution in self.RESOLUTIONS return self.RESOLUTIONS.index(resolution)
python
def getZoom(self, resolution): "Return the zoom level for a given resolution" assert resolution in self.RESOLUTIONS return self.RESOLUTIONS.index(resolution)
[ "def", "getZoom", "(", "self", ",", "resolution", ")", ":", "assert", "resolution", "in", "self", ".", "RESOLUTIONS", "return", "self", ".", "RESOLUTIONS", ".", "index", "(", "resolution", ")" ]
Return the zoom level for a given resolution
[ "Return", "the", "zoom", "level", "for", "a", "given", "resolution" ]
28e39cba22451f6ef0ddcb93cbc0838f06815505
https://github.com/geoadmin/lib-gatilegrid/blob/28e39cba22451f6ef0ddcb93cbc0838f06815505/gatilegrid/tilegrids.py#L298-L301
train
45,600
geoadmin/lib-gatilegrid
gatilegrid/tilegrids.py
_TileGrid._getZoomLevelRange
def _getZoomLevelRange(self, resolution, unit='meters'): "Return lower and higher zoom level given a resolution" assert unit in ('meters', 'degrees') if unit == 'meters' and self.unit == 'degrees': resolution = resolution / self.metersPerUnit elif unit == 'degrees' and self.unit == 'meters': resolution = resolution * EPSG4326_METERS_PER_UNIT lo = 0 hi = len(self.RESOLUTIONS) while lo < hi: mid = (lo + hi) // 2 if resolution > self.RESOLUTIONS[mid]: hi = mid else: lo = mid + 1 return lo, hi
python
def _getZoomLevelRange(self, resolution, unit='meters'): "Return lower and higher zoom level given a resolution" assert unit in ('meters', 'degrees') if unit == 'meters' and self.unit == 'degrees': resolution = resolution / self.metersPerUnit elif unit == 'degrees' and self.unit == 'meters': resolution = resolution * EPSG4326_METERS_PER_UNIT lo = 0 hi = len(self.RESOLUTIONS) while lo < hi: mid = (lo + hi) // 2 if resolution > self.RESOLUTIONS[mid]: hi = mid else: lo = mid + 1 return lo, hi
[ "def", "_getZoomLevelRange", "(", "self", ",", "resolution", ",", "unit", "=", "'meters'", ")", ":", "assert", "unit", "in", "(", "'meters'", ",", "'degrees'", ")", "if", "unit", "==", "'meters'", "and", "self", ".", "unit", "==", "'degrees'", ":", "reso...
Return lower and higher zoom level given a resolution
[ "Return", "lower", "and", "higher", "zoom", "level", "given", "a", "resolution" ]
28e39cba22451f6ef0ddcb93cbc0838f06815505
https://github.com/geoadmin/lib-gatilegrid/blob/28e39cba22451f6ef0ddcb93cbc0838f06815505/gatilegrid/tilegrids.py#L303-L318
train
45,601
geoadmin/lib-gatilegrid
gatilegrid/tilegrids.py
_TileGrid.getScale
def getScale(self, zoom): """Returns the scale at a given zoom level""" if self.unit == 'degrees': resolution = self.getResolution(zoom) * EPSG4326_METERS_PER_UNIT else: resolution = self.getResolution(zoom) return resolution / STANDARD_PIXEL_SIZE
python
def getScale(self, zoom): """Returns the scale at a given zoom level""" if self.unit == 'degrees': resolution = self.getResolution(zoom) * EPSG4326_METERS_PER_UNIT else: resolution = self.getResolution(zoom) return resolution / STANDARD_PIXEL_SIZE
[ "def", "getScale", "(", "self", ",", "zoom", ")", ":", "if", "self", ".", "unit", "==", "'degrees'", ":", "resolution", "=", "self", ".", "getResolution", "(", "zoom", ")", "*", "EPSG4326_METERS_PER_UNIT", "else", ":", "resolution", "=", "self", ".", "ge...
Returns the scale at a given zoom level
[ "Returns", "the", "scale", "at", "a", "given", "zoom", "level" ]
28e39cba22451f6ef0ddcb93cbc0838f06815505
https://github.com/geoadmin/lib-gatilegrid/blob/28e39cba22451f6ef0ddcb93cbc0838f06815505/gatilegrid/tilegrids.py#L353-L359
train
45,602
globality-corp/microcosm-logging
microcosm_logging/factories.py
make_dict_config
def make_dict_config(graph): """ Build a dictionary configuration from conventions and configuration. """ formatters = {} handlers = {} loggers = {} # create the console handler formatters["ExtraFormatter"] = make_extra_console_formatter(graph) handlers["console"] = make_stream_handler(graph, formatter="ExtraFormatter") # maybe create the loggly handler if enable_loggly(graph): formatters["JSONFormatter"] = make_json_formatter(graph) handlers["LogglyHTTPSHandler"] = make_loggly_handler(graph, formatter="JSONFormatter") # configure the root logger to output to all handlers loggers[""] = { "handlers": handlers.keys(), "level": graph.config.logging.level, } # set log levels for libraries loggers.update(make_library_levels(graph)) return dict( version=1, disable_existing_loggers=False, formatters=formatters, handlers=handlers, loggers=loggers, )
python
def make_dict_config(graph): """ Build a dictionary configuration from conventions and configuration. """ formatters = {} handlers = {} loggers = {} # create the console handler formatters["ExtraFormatter"] = make_extra_console_formatter(graph) handlers["console"] = make_stream_handler(graph, formatter="ExtraFormatter") # maybe create the loggly handler if enable_loggly(graph): formatters["JSONFormatter"] = make_json_formatter(graph) handlers["LogglyHTTPSHandler"] = make_loggly_handler(graph, formatter="JSONFormatter") # configure the root logger to output to all handlers loggers[""] = { "handlers": handlers.keys(), "level": graph.config.logging.level, } # set log levels for libraries loggers.update(make_library_levels(graph)) return dict( version=1, disable_existing_loggers=False, formatters=formatters, handlers=handlers, loggers=loggers, )
[ "def", "make_dict_config", "(", "graph", ")", ":", "formatters", "=", "{", "}", "handlers", "=", "{", "}", "loggers", "=", "{", "}", "# create the console handler", "formatters", "[", "\"ExtraFormatter\"", "]", "=", "make_extra_console_formatter", "(", "graph", ...
Build a dictionary configuration from conventions and configuration.
[ "Build", "a", "dictionary", "configuration", "from", "conventions", "and", "configuration", "." ]
f60ac971a343b661a47a0d0d4e0a58de76152bbc
https://github.com/globality-corp/microcosm-logging/blob/f60ac971a343b661a47a0d0d4e0a58de76152bbc/microcosm_logging/factories.py#L109-L142
train
45,603
globality-corp/microcosm-logging
microcosm_logging/factories.py
make_json_formatter
def make_json_formatter(graph): """ Create the default json formatter. """ return { "()": graph.config.logging.json_formatter.formatter, "fmt": graph.config.logging.json_required_keys, }
python
def make_json_formatter(graph): """ Create the default json formatter. """ return { "()": graph.config.logging.json_formatter.formatter, "fmt": graph.config.logging.json_required_keys, }
[ "def", "make_json_formatter", "(", "graph", ")", ":", "return", "{", "\"()\"", ":", "graph", ".", "config", ".", "logging", ".", "json_formatter", ".", "formatter", ",", "\"fmt\"", ":", "graph", ".", "config", ".", "logging", ".", "json_required_keys", ",", ...
Create the default json formatter.
[ "Create", "the", "default", "json", "formatter", "." ]
f60ac971a343b661a47a0d0d4e0a58de76152bbc
https://github.com/globality-corp/microcosm-logging/blob/f60ac971a343b661a47a0d0d4e0a58de76152bbc/microcosm_logging/factories.py#L145-L154
train
45,604
globality-corp/microcosm-logging
microcosm_logging/factories.py
make_loggly_handler
def make_loggly_handler(graph, formatter): """ Create the loggly handler. Used for searchable aggregation. """ base_url = graph.config.logging.loggly.base_url loggly_url = "{}/inputs/{}/tag/{}".format( base_url, graph.config.logging.loggly.token, ",".join([ graph.metadata.name, graph.config.logging.loggly.environment, ]), ) return { "class": graph.config.logging.https_handler.class_, "formatter": formatter, "level": graph.config.logging.level, "url": loggly_url, }
python
def make_loggly_handler(graph, formatter): """ Create the loggly handler. Used for searchable aggregation. """ base_url = graph.config.logging.loggly.base_url loggly_url = "{}/inputs/{}/tag/{}".format( base_url, graph.config.logging.loggly.token, ",".join([ graph.metadata.name, graph.config.logging.loggly.environment, ]), ) return { "class": graph.config.logging.https_handler.class_, "formatter": formatter, "level": graph.config.logging.level, "url": loggly_url, }
[ "def", "make_loggly_handler", "(", "graph", ",", "formatter", ")", ":", "base_url", "=", "graph", ".", "config", ".", "logging", ".", "loggly", ".", "base_url", "loggly_url", "=", "\"{}/inputs/{}/tag/{}\"", ".", "format", "(", "base_url", ",", "graph", ".", ...
Create the loggly handler. Used for searchable aggregation.
[ "Create", "the", "loggly", "handler", "." ]
f60ac971a343b661a47a0d0d4e0a58de76152bbc
https://github.com/globality-corp/microcosm-logging/blob/f60ac971a343b661a47a0d0d4e0a58de76152bbc/microcosm_logging/factories.py#L182-L203
train
45,605
globality-corp/microcosm-logging
microcosm_logging/factories.py
make_library_levels
def make_library_levels(graph): """ Create third party library logging level configurations. Tunes down overly verbose logs in commonly used libraries. """ # inject the default components; these can, but probably shouldn't, be overridden levels = {} for level in ["DEBUG", "INFO", "WARN", "ERROR"]: levels.update({ component: { "level": level, } for component in graph.config.logging.levels.default[level.lower()] }) # override components; these can be set per application for level in ["DEBUG", "INFO", "WARN", "ERROR"]: levels.update({ component: { "level": level, } for component in graph.config.logging.levels.override[level.lower()] }) return levels
python
def make_library_levels(graph): """ Create third party library logging level configurations. Tunes down overly verbose logs in commonly used libraries. """ # inject the default components; these can, but probably shouldn't, be overridden levels = {} for level in ["DEBUG", "INFO", "WARN", "ERROR"]: levels.update({ component: { "level": level, } for component in graph.config.logging.levels.default[level.lower()] }) # override components; these can be set per application for level in ["DEBUG", "INFO", "WARN", "ERROR"]: levels.update({ component: { "level": level, } for component in graph.config.logging.levels.override[level.lower()] }) return levels
[ "def", "make_library_levels", "(", "graph", ")", ":", "# inject the default components; these can, but probably shouldn't, be overridden", "levels", "=", "{", "}", "for", "level", "in", "[", "\"DEBUG\"", ",", "\"INFO\"", ",", "\"WARN\"", ",", "\"ERROR\"", "]", ":", "l...
Create third party library logging level configurations. Tunes down overly verbose logs in commonly used libraries.
[ "Create", "third", "party", "library", "logging", "level", "configurations", "." ]
f60ac971a343b661a47a0d0d4e0a58de76152bbc
https://github.com/globality-corp/microcosm-logging/blob/f60ac971a343b661a47a0d0d4e0a58de76152bbc/microcosm_logging/factories.py#L206-L228
train
45,606
edx/edx-django-sites-extensions
django_sites_extensions/middleware.py
RedirectMiddleware.process_request
def process_request(self, request): """ Redirects the current request if there is a matching Redirect model with the current request URL as the old_path field. """ site = request.site cache_key = '{prefix}-{site}'.format(prefix=settings.REDIRECT_CACHE_KEY_PREFIX, site=site.domain) redirects = cache.get(cache_key) if redirects is None: redirects = {redirect.old_path: redirect.new_path for redirect in Redirect.objects.filter(site=site)} cache.set(cache_key, redirects, settings.REDIRECT_CACHE_TIMEOUT) redirect_to = redirects.get(request.path) if redirect_to: return redirect(redirect_to, permanent=True)
python
def process_request(self, request): """ Redirects the current request if there is a matching Redirect model with the current request URL as the old_path field. """ site = request.site cache_key = '{prefix}-{site}'.format(prefix=settings.REDIRECT_CACHE_KEY_PREFIX, site=site.domain) redirects = cache.get(cache_key) if redirects is None: redirects = {redirect.old_path: redirect.new_path for redirect in Redirect.objects.filter(site=site)} cache.set(cache_key, redirects, settings.REDIRECT_CACHE_TIMEOUT) redirect_to = redirects.get(request.path) if redirect_to: return redirect(redirect_to, permanent=True)
[ "def", "process_request", "(", "self", ",", "request", ")", ":", "site", "=", "request", ".", "site", "cache_key", "=", "'{prefix}-{site}'", ".", "format", "(", "prefix", "=", "settings", ".", "REDIRECT_CACHE_KEY_PREFIX", ",", "site", "=", "site", ".", "doma...
Redirects the current request if there is a matching Redirect model with the current request URL as the old_path field.
[ "Redirects", "the", "current", "request", "if", "there", "is", "a", "matching", "Redirect", "model", "with", "the", "current", "request", "URL", "as", "the", "old_path", "field", "." ]
d4fc18cb4831b7b95ccd1b2f9afc9afa1f19b096
https://github.com/edx/edx-django-sites-extensions/blob/d4fc18cb4831b7b95ccd1b2f9afc9afa1f19b096/django_sites_extensions/middleware.py#L14-L27
train
45,607
globality-corp/microcosm-logging
microcosm_logging/decorators.py
context_logger
def context_logger(context_func, func, parent=None): """ The results of context_func will be executed and applied to a ContextLogger instance for the execution of func. The resulting ContextLogger instance will be available on parent.logger for the duration of func. :param context_func: callable which provides dictionary-like context information :param func: the function to wrap :param parent: object to attach the context logger to, if None, defaults to func.__self__ """ if parent is None: parent = func.__self__ def wrapped(*args, **kwargs): parent.logger = ContextLogger( getattr(parent, 'logger', getLogger(parent.__class__.__name__)), context_func(*args, **kwargs) or dict(), ) try: result = func(*args, **kwargs) return result finally: parent.logger = parent.logger.logger return wrapped
python
def context_logger(context_func, func, parent=None): """ The results of context_func will be executed and applied to a ContextLogger instance for the execution of func. The resulting ContextLogger instance will be available on parent.logger for the duration of func. :param context_func: callable which provides dictionary-like context information :param func: the function to wrap :param parent: object to attach the context logger to, if None, defaults to func.__self__ """ if parent is None: parent = func.__self__ def wrapped(*args, **kwargs): parent.logger = ContextLogger( getattr(parent, 'logger', getLogger(parent.__class__.__name__)), context_func(*args, **kwargs) or dict(), ) try: result = func(*args, **kwargs) return result finally: parent.logger = parent.logger.logger return wrapped
[ "def", "context_logger", "(", "context_func", ",", "func", ",", "parent", "=", "None", ")", ":", "if", "parent", "is", "None", ":", "parent", "=", "func", ".", "__self__", "def", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "parent...
The results of context_func will be executed and applied to a ContextLogger instance for the execution of func. The resulting ContextLogger instance will be available on parent.logger for the duration of func. :param context_func: callable which provides dictionary-like context information :param func: the function to wrap :param parent: object to attach the context logger to, if None, defaults to func.__self__
[ "The", "results", "of", "context_func", "will", "be", "executed", "and", "applied", "to", "a", "ContextLogger", "instance", "for", "the", "execution", "of", "func", ".", "The", "resulting", "ContextLogger", "instance", "will", "be", "available", "on", "parent", ...
f60ac971a343b661a47a0d0d4e0a58de76152bbc
https://github.com/globality-corp/microcosm-logging/blob/f60ac971a343b661a47a0d0d4e0a58de76152bbc/microcosm_logging/decorators.py#L38-L61
train
45,608
IBM/pyxcli
pyxcli/helpers/xml_util.py
str_brief
def str_brief(obj, lim=20, dots='...', use_repr=True): """Truncates a string, starting from 'lim' chars. The given object can be a string, or something that can be casted to a string. >>> import string >>> str_brief(string.uppercase) 'ABCDEFGHIJKLMNOPQRST...' >>> str_brief(2 ** 50, lim=10, dots='0') '11258999060' """ if isinstance(obj, basestring) or not use_repr: full = str(obj) else: full = repr(obj) postfix = [] CLOSERS = {'(': ')', '{': '}', '[': ']', '"': '"', "'": "'", '<': '>'} for i, c in enumerate(full): if i >= lim + len(postfix): return full[:i] + dots + ''.join(reversed(postfix)) if postfix and postfix[-1] == c: postfix.pop(-1) continue closer = CLOSERS.get(c, None) if closer is not None: postfix.append(closer) return full
python
def str_brief(obj, lim=20, dots='...', use_repr=True): """Truncates a string, starting from 'lim' chars. The given object can be a string, or something that can be casted to a string. >>> import string >>> str_brief(string.uppercase) 'ABCDEFGHIJKLMNOPQRST...' >>> str_brief(2 ** 50, lim=10, dots='0') '11258999060' """ if isinstance(obj, basestring) or not use_repr: full = str(obj) else: full = repr(obj) postfix = [] CLOSERS = {'(': ')', '{': '}', '[': ']', '"': '"', "'": "'", '<': '>'} for i, c in enumerate(full): if i >= lim + len(postfix): return full[:i] + dots + ''.join(reversed(postfix)) if postfix and postfix[-1] == c: postfix.pop(-1) continue closer = CLOSERS.get(c, None) if closer is not None: postfix.append(closer) return full
[ "def", "str_brief", "(", "obj", ",", "lim", "=", "20", ",", "dots", "=", "'...'", ",", "use_repr", "=", "True", ")", ":", "if", "isinstance", "(", "obj", ",", "basestring", ")", "or", "not", "use_repr", ":", "full", "=", "str", "(", "obj", ")", "...
Truncates a string, starting from 'lim' chars. The given object can be a string, or something that can be casted to a string. >>> import string >>> str_brief(string.uppercase) 'ABCDEFGHIJKLMNOPQRST...' >>> str_brief(2 ** 50, lim=10, dots='0') '11258999060'
[ "Truncates", "a", "string", "starting", "from", "lim", "chars", ".", "The", "given", "object", "can", "be", "a", "string", "or", "something", "that", "can", "be", "casted", "to", "a", "string", "." ]
7d8ece1dcc16f50246740a447aa81b94a0dbced4
https://github.com/IBM/pyxcli/blob/7d8ece1dcc16f50246740a447aa81b94a0dbced4/pyxcli/helpers/xml_util.py#L42-L67
train
45,609
IBM/pyxcli
pyxcli/mirroring/mirrored_entities.py
MirroredEntities.get_mirror_resources_by_name_map
def get_mirror_resources_by_name_map(self, scope=None): """ returns a map volume_name -> volume, cg_name->cg scope is either None or CG or Volume """ volumes_mirrors_by_name = dict() cgs_mirrors_by_name = dict() if ((scope is None) or (scope.lower() == 'volume')): mirror_list = self.xcli_client.cmd.mirror_list(scope='Volume') for xcli_mirror in mirror_list: name = MirroredEntities.get_mirrored_object_name(xcli_mirror) volumes_mirrors_by_name[name] = xcli_mirror if ((scope is None) or (scope.lower() == CG)): for xcli_mirror in self.xcli_client.cmd.mirror_list(scope='CG'): name = MirroredEntities.get_mirrored_object_name(xcli_mirror) cgs_mirrors_by_name[name] = xcli_mirror res = Bunch(volumes=volumes_mirrors_by_name, cgs=cgs_mirrors_by_name) return res
python
def get_mirror_resources_by_name_map(self, scope=None): """ returns a map volume_name -> volume, cg_name->cg scope is either None or CG or Volume """ volumes_mirrors_by_name = dict() cgs_mirrors_by_name = dict() if ((scope is None) or (scope.lower() == 'volume')): mirror_list = self.xcli_client.cmd.mirror_list(scope='Volume') for xcli_mirror in mirror_list: name = MirroredEntities.get_mirrored_object_name(xcli_mirror) volumes_mirrors_by_name[name] = xcli_mirror if ((scope is None) or (scope.lower() == CG)): for xcli_mirror in self.xcli_client.cmd.mirror_list(scope='CG'): name = MirroredEntities.get_mirrored_object_name(xcli_mirror) cgs_mirrors_by_name[name] = xcli_mirror res = Bunch(volumes=volumes_mirrors_by_name, cgs=cgs_mirrors_by_name) return res
[ "def", "get_mirror_resources_by_name_map", "(", "self", ",", "scope", "=", "None", ")", ":", "volumes_mirrors_by_name", "=", "dict", "(", ")", "cgs_mirrors_by_name", "=", "dict", "(", ")", "if", "(", "(", "scope", "is", "None", ")", "or", "(", "scope", "."...
returns a map volume_name -> volume, cg_name->cg scope is either None or CG or Volume
[ "returns", "a", "map", "volume_name", "-", ">", "volume", "cg_name", "-", ">", "cg", "scope", "is", "either", "None", "or", "CG", "or", "Volume" ]
7d8ece1dcc16f50246740a447aa81b94a0dbced4
https://github.com/IBM/pyxcli/blob/7d8ece1dcc16f50246740a447aa81b94a0dbced4/pyxcli/mirroring/mirrored_entities.py#L48-L64
train
45,610
IBM/pyxcli
pyxcli/mirroring/mirrored_entities.py
MirroredEntities.get_host_port_names
def get_host_port_names(self, host_name): """ return a list of the port names of XIV host """ port_names = list() host = self.get_hosts_by_name(host_name) fc_ports = host.fc_ports iscsi_ports = host.iscsi_ports port_names.extend(fc_ports.split(',') if fc_ports != '' else []) port_names.extend(iscsi_ports.split(',') if iscsi_ports != '' else []) return port_names
python
def get_host_port_names(self, host_name): """ return a list of the port names of XIV host """ port_names = list() host = self.get_hosts_by_name(host_name) fc_ports = host.fc_ports iscsi_ports = host.iscsi_ports port_names.extend(fc_ports.split(',') if fc_ports != '' else []) port_names.extend(iscsi_ports.split(',') if iscsi_ports != '' else []) return port_names
[ "def", "get_host_port_names", "(", "self", ",", "host_name", ")", ":", "port_names", "=", "list", "(", ")", "host", "=", "self", ".", "get_hosts_by_name", "(", "host_name", ")", "fc_ports", "=", "host", ".", "fc_ports", "iscsi_ports", "=", "host", ".", "is...
return a list of the port names of XIV host
[ "return", "a", "list", "of", "the", "port", "names", "of", "XIV", "host" ]
7d8ece1dcc16f50246740a447aa81b94a0dbced4
https://github.com/IBM/pyxcli/blob/7d8ece1dcc16f50246740a447aa81b94a0dbced4/pyxcli/mirroring/mirrored_entities.py#L115-L123
train
45,611
IBM/pyxcli
pyxcli/mirroring/mirrored_entities.py
MirroredEntities.get_cluster_port_names
def get_cluster_port_names(self, cluster_name): """ return a list of the port names under XIV CLuster """ port_names = list() for host_name in self.get_hosts_by_clusters()[cluster_name]: port_names.extend(self.get_hosts_by_name(host_name)) return port_names
python
def get_cluster_port_names(self, cluster_name): """ return a list of the port names under XIV CLuster """ port_names = list() for host_name in self.get_hosts_by_clusters()[cluster_name]: port_names.extend(self.get_hosts_by_name(host_name)) return port_names
[ "def", "get_cluster_port_names", "(", "self", ",", "cluster_name", ")", ":", "port_names", "=", "list", "(", ")", "for", "host_name", "in", "self", ".", "get_hosts_by_clusters", "(", ")", "[", "cluster_name", "]", ":", "port_names", ".", "extend", "(", "self...
return a list of the port names under XIV CLuster
[ "return", "a", "list", "of", "the", "port", "names", "under", "XIV", "CLuster" ]
7d8ece1dcc16f50246740a447aa81b94a0dbced4
https://github.com/IBM/pyxcli/blob/7d8ece1dcc16f50246740a447aa81b94a0dbced4/pyxcli/mirroring/mirrored_entities.py#L125-L130
train
45,612
IBM/pyxcli
pyxcli/pool.py
XCLIClientPool.flush
def flush(self): """remove all stale clients from pool""" now = time.time() to_remove = [] for k, entry in self.pool.items(): if entry.timestamp < now: entry.client.close() to_remove.append(k) for k in to_remove: del self.pool[k]
python
def flush(self): """remove all stale clients from pool""" now = time.time() to_remove = [] for k, entry in self.pool.items(): if entry.timestamp < now: entry.client.close() to_remove.append(k) for k in to_remove: del self.pool[k]
[ "def", "flush", "(", "self", ")", ":", "now", "=", "time", ".", "time", "(", ")", "to_remove", "=", "[", "]", "for", "k", ",", "entry", "in", "self", ".", "pool", ".", "items", "(", ")", ":", "if", "entry", ".", "timestamp", "<", "now", ":", ...
remove all stale clients from pool
[ "remove", "all", "stale", "clients", "from", "pool" ]
7d8ece1dcc16f50246740a447aa81b94a0dbced4
https://github.com/IBM/pyxcli/blob/7d8ece1dcc16f50246740a447aa81b94a0dbced4/pyxcli/pool.py#L70-L79
train
45,613
IBM/pyxcli
pyxcli/pool.py
XCLIClientPool.get
def get(self, user, password, endpoints): """Gets an existing connection or opens a new one """ now = time.time() # endpoints can either be str or list if isinstance(endpoints, str): endpoints = [endpoints] for ep in endpoints: if ep not in self.pool: continue entry = self.pool[ep] if (not entry.client.is_connected() or entry.timestamp + self.time_to_live < now): xlog.debug("XCLIClientPool: clearing stale client %s", ep) del self.pool[ep] entry.client.close() continue user_client = entry.user_clients.get(user, None) if not user_client or not user_client.is_connected(): user_client = entry.client.get_user_client(user, password) entry.user_clients[user] = user_client return user_client xlog.debug("XCLIClientPool: connecting to %s", endpoints) client = self.connector(None, None, endpoints) user_client = {user: client.get_user_client(user, password)} for ep in endpoints: self.pool[ep] = PoolEntry(client, now, user_client) return user_client[user]
python
def get(self, user, password, endpoints): """Gets an existing connection or opens a new one """ now = time.time() # endpoints can either be str or list if isinstance(endpoints, str): endpoints = [endpoints] for ep in endpoints: if ep not in self.pool: continue entry = self.pool[ep] if (not entry.client.is_connected() or entry.timestamp + self.time_to_live < now): xlog.debug("XCLIClientPool: clearing stale client %s", ep) del self.pool[ep] entry.client.close() continue user_client = entry.user_clients.get(user, None) if not user_client or not user_client.is_connected(): user_client = entry.client.get_user_client(user, password) entry.user_clients[user] = user_client return user_client xlog.debug("XCLIClientPool: connecting to %s", endpoints) client = self.connector(None, None, endpoints) user_client = {user: client.get_user_client(user, password)} for ep in endpoints: self.pool[ep] = PoolEntry(client, now, user_client) return user_client[user]
[ "def", "get", "(", "self", ",", "user", ",", "password", ",", "endpoints", ")", ":", "now", "=", "time", ".", "time", "(", ")", "# endpoints can either be str or list", "if", "isinstance", "(", "endpoints", ",", "str", ")", ":", "endpoints", "=", "[", "e...
Gets an existing connection or opens a new one
[ "Gets", "an", "existing", "connection", "or", "opens", "a", "new", "one" ]
7d8ece1dcc16f50246740a447aa81b94a0dbced4
https://github.com/IBM/pyxcli/blob/7d8ece1dcc16f50246740a447aa81b94a0dbced4/pyxcli/pool.py#L81-L110
train
45,614
IBM/pyxcli
pyxcli/mirroring/recovery_manager.py
RecoveryManager._create_mirror
def _create_mirror(self, resource_type, resource_name, target_name, mirror_type, slave_resource_name, create_slave='no', remote_pool=None, rpo=None, remote_rpo=None, schedule=None, remote_schedule=None, activate_mirror='no'): '''creates a mirror and returns a mirror object. resource_type must be 'vol' or 'cg', target name must be a valid target from target_list, mirror type must be 'sync' or 'async', slave_resource_name would be the slave_vol or slave_cg name''' kwargs = { resource_type: resource_name, 'target': target_name, 'type': mirror_type, 'slave_' + resource_type: slave_resource_name, 'create_slave': create_slave, 'remote_pool': remote_pool, 'rpo': rpo, 'remote_rpo': remote_rpo, 'schedule': schedule, 'remote_schedule': remote_schedule } if mirror_type == 'sync': kwargs['type'] = 'sync_best_effort' kwargs['rpo'] = None else: kwargs['type'] = 'async_interval' if kwargs['remote_schedule'] is None: kwargs['remote_schedule'] = kwargs['schedule'] # avoids a python3 issue of the dict changing # during iteration keys = set(kwargs.keys()).copy() for k in keys: if kwargs[k] is None: kwargs.pop(k) logger.info('creating mirror with arguments: %s' % kwargs) self.xcli_client.cmd.mirror_create(**kwargs) if activate_mirror == 'yes': logger.info('Activating mirror %s' % resource_name) self.activate_mirror(resource_name) return self.get_mirror_resources()[resource_name]
python
def _create_mirror(self, resource_type, resource_name, target_name, mirror_type, slave_resource_name, create_slave='no', remote_pool=None, rpo=None, remote_rpo=None, schedule=None, remote_schedule=None, activate_mirror='no'): '''creates a mirror and returns a mirror object. resource_type must be 'vol' or 'cg', target name must be a valid target from target_list, mirror type must be 'sync' or 'async', slave_resource_name would be the slave_vol or slave_cg name''' kwargs = { resource_type: resource_name, 'target': target_name, 'type': mirror_type, 'slave_' + resource_type: slave_resource_name, 'create_slave': create_slave, 'remote_pool': remote_pool, 'rpo': rpo, 'remote_rpo': remote_rpo, 'schedule': schedule, 'remote_schedule': remote_schedule } if mirror_type == 'sync': kwargs['type'] = 'sync_best_effort' kwargs['rpo'] = None else: kwargs['type'] = 'async_interval' if kwargs['remote_schedule'] is None: kwargs['remote_schedule'] = kwargs['schedule'] # avoids a python3 issue of the dict changing # during iteration keys = set(kwargs.keys()).copy() for k in keys: if kwargs[k] is None: kwargs.pop(k) logger.info('creating mirror with arguments: %s' % kwargs) self.xcli_client.cmd.mirror_create(**kwargs) if activate_mirror == 'yes': logger.info('Activating mirror %s' % resource_name) self.activate_mirror(resource_name) return self.get_mirror_resources()[resource_name]
[ "def", "_create_mirror", "(", "self", ",", "resource_type", ",", "resource_name", ",", "target_name", ",", "mirror_type", ",", "slave_resource_name", ",", "create_slave", "=", "'no'", ",", "remote_pool", "=", "None", ",", "rpo", "=", "None", ",", "remote_rpo", ...
creates a mirror and returns a mirror object. resource_type must be 'vol' or 'cg', target name must be a valid target from target_list, mirror type must be 'sync' or 'async', slave_resource_name would be the slave_vol or slave_cg name
[ "creates", "a", "mirror", "and", "returns", "a", "mirror", "object", ".", "resource_type", "must", "be", "vol", "or", "cg", "target", "name", "must", "be", "a", "valid", "target", "from", "target_list", "mirror", "type", "must", "be", "sync", "or", "async"...
7d8ece1dcc16f50246740a447aa81b94a0dbced4
https://github.com/IBM/pyxcli/blob/7d8ece1dcc16f50246740a447aa81b94a0dbced4/pyxcli/mirroring/recovery_manager.py#L273-L319
train
45,615
khazhyk/osuapi
osuapi/osu.py
OsuApi.get_user
def get_user(self, username, *, mode=OsuMode.osu, event_days=31): """Get a user profile. Parameters ---------- username : str or int A `str` representing the user's username, or an `int` representing the user's id. mode : :class:`osuapi.enums.OsuMode` The osu! game mode for which to look up. Defaults to osu!standard. event_days : int The number of days in the past to look for events. Defaults to 31 (the maximum). """ return self._make_req(endpoints.USER, dict( k=self.key, u=username, type=_username_type(username), m=mode.value, event_days=event_days ), JsonList(User))
python
def get_user(self, username, *, mode=OsuMode.osu, event_days=31): """Get a user profile. Parameters ---------- username : str or int A `str` representing the user's username, or an `int` representing the user's id. mode : :class:`osuapi.enums.OsuMode` The osu! game mode for which to look up. Defaults to osu!standard. event_days : int The number of days in the past to look for events. Defaults to 31 (the maximum). """ return self._make_req(endpoints.USER, dict( k=self.key, u=username, type=_username_type(username), m=mode.value, event_days=event_days ), JsonList(User))
[ "def", "get_user", "(", "self", ",", "username", ",", "*", ",", "mode", "=", "OsuMode", ".", "osu", ",", "event_days", "=", "31", ")", ":", "return", "self", ".", "_make_req", "(", "endpoints", ".", "USER", ",", "dict", "(", "k", "=", "self", ".", ...
Get a user profile. Parameters ---------- username : str or int A `str` representing the user's username, or an `int` representing the user's id. mode : :class:`osuapi.enums.OsuMode` The osu! game mode for which to look up. Defaults to osu!standard. event_days : int The number of days in the past to look for events. Defaults to 31 (the maximum).
[ "Get", "a", "user", "profile", "." ]
e46a76dc7c1f43e7ce63ab83ab7162ab5c3930ec
https://github.com/khazhyk/osuapi/blob/e46a76dc7c1f43e7ce63ab83ab7162ab5c3930ec/osuapi/osu.py#L33-L51
train
45,616
khazhyk/osuapi
osuapi/osu.py
OsuApi.get_user_best
def get_user_best(self, username, *, mode=OsuMode.osu, limit=50): """Get a user's best scores. Parameters ---------- username : str or int A `str` representing the user's username, or an `int` representing the user's id. mode : :class:`osuapi.enums.OsuMode` The osu! game mode for which to look up. Defaults to osu!standard. limit The maximum number of results to return. Defaults to 50, maximum 100. """ return self._make_req(endpoints.USER_BEST, dict( k=self.key, u=username, type=_username_type(username), m=mode.value, limit=limit ), JsonList(SoloScore))
python
def get_user_best(self, username, *, mode=OsuMode.osu, limit=50): """Get a user's best scores. Parameters ---------- username : str or int A `str` representing the user's username, or an `int` representing the user's id. mode : :class:`osuapi.enums.OsuMode` The osu! game mode for which to look up. Defaults to osu!standard. limit The maximum number of results to return. Defaults to 50, maximum 100. """ return self._make_req(endpoints.USER_BEST, dict( k=self.key, u=username, type=_username_type(username), m=mode.value, limit=limit ), JsonList(SoloScore))
[ "def", "get_user_best", "(", "self", ",", "username", ",", "*", ",", "mode", "=", "OsuMode", ".", "osu", ",", "limit", "=", "50", ")", ":", "return", "self", ".", "_make_req", "(", "endpoints", ".", "USER_BEST", ",", "dict", "(", "k", "=", "self", ...
Get a user's best scores. Parameters ---------- username : str or int A `str` representing the user's username, or an `int` representing the user's id. mode : :class:`osuapi.enums.OsuMode` The osu! game mode for which to look up. Defaults to osu!standard. limit The maximum number of results to return. Defaults to 50, maximum 100.
[ "Get", "a", "user", "s", "best", "scores", "." ]
e46a76dc7c1f43e7ce63ab83ab7162ab5c3930ec
https://github.com/khazhyk/osuapi/blob/e46a76dc7c1f43e7ce63ab83ab7162ab5c3930ec/osuapi/osu.py#L53-L71
train
45,617
khazhyk/osuapi
osuapi/osu.py
OsuApi.get_user_recent
def get_user_recent(self, username, *, mode=OsuMode.osu, limit=10): """Get a user's most recent scores, within the last 24 hours. Parameters ---------- username : str or int A `str` representing the user's username, or an `int` representing the user's id. mode : :class:`osuapi.enums.OsuMode` The osu! game mode for which to look up. Defaults to osu!standard. limit The maximum number of results to return. Defaults to 10, maximum 50. """ return self._make_req(endpoints.USER_RECENT, dict( k=self.key, u=username, type=_username_type(username), m=mode.value, limit=limit ), JsonList(RecentScore))
python
def get_user_recent(self, username, *, mode=OsuMode.osu, limit=10): """Get a user's most recent scores, within the last 24 hours. Parameters ---------- username : str or int A `str` representing the user's username, or an `int` representing the user's id. mode : :class:`osuapi.enums.OsuMode` The osu! game mode for which to look up. Defaults to osu!standard. limit The maximum number of results to return. Defaults to 10, maximum 50. """ return self._make_req(endpoints.USER_RECENT, dict( k=self.key, u=username, type=_username_type(username), m=mode.value, limit=limit ), JsonList(RecentScore))
[ "def", "get_user_recent", "(", "self", ",", "username", ",", "*", ",", "mode", "=", "OsuMode", ".", "osu", ",", "limit", "=", "10", ")", ":", "return", "self", ".", "_make_req", "(", "endpoints", ".", "USER_RECENT", ",", "dict", "(", "k", "=", "self"...
Get a user's most recent scores, within the last 24 hours. Parameters ---------- username : str or int A `str` representing the user's username, or an `int` representing the user's id. mode : :class:`osuapi.enums.OsuMode` The osu! game mode for which to look up. Defaults to osu!standard. limit The maximum number of results to return. Defaults to 10, maximum 50.
[ "Get", "a", "user", "s", "most", "recent", "scores", "within", "the", "last", "24", "hours", "." ]
e46a76dc7c1f43e7ce63ab83ab7162ab5c3930ec
https://github.com/khazhyk/osuapi/blob/e46a76dc7c1f43e7ce63ab83ab7162ab5c3930ec/osuapi/osu.py#L73-L91
train
45,618
khazhyk/osuapi
osuapi/osu.py
OsuApi.get_scores
def get_scores(self, beatmap_id, *, username=None, mode=OsuMode.osu, mods=None, limit=50): """Get the top scores for a given beatmap. Parameters ---------- beatmap_id Individual Beatmap ID to lookup. username : str or int A `str` representing the user's username, or an `int` representing the user's id. If specified, restricts returned scores to the specified user. mode : :class:`osuapi.enums.OsuMode` The osu! game mode for which to look up. Defaults to osu!standard. mods : :class:`osuap:class:`osuapi.enums.OsuMod` If specified, restricts returned scores to the specified mods. limit Number of results to return. Defaults to 50, maximum 100. """ return self._make_req(endpoints.SCORES, dict( k=self.key, b=beatmap_id, u=username, type=_username_type(username), m=mode.value, mods=mods.value if mods else None, limit=limit), JsonList(BeatmapScore))
python
def get_scores(self, beatmap_id, *, username=None, mode=OsuMode.osu, mods=None, limit=50): """Get the top scores for a given beatmap. Parameters ---------- beatmap_id Individual Beatmap ID to lookup. username : str or int A `str` representing the user's username, or an `int` representing the user's id. If specified, restricts returned scores to the specified user. mode : :class:`osuapi.enums.OsuMode` The osu! game mode for which to look up. Defaults to osu!standard. mods : :class:`osuap:class:`osuapi.enums.OsuMod` If specified, restricts returned scores to the specified mods. limit Number of results to return. Defaults to 50, maximum 100. """ return self._make_req(endpoints.SCORES, dict( k=self.key, b=beatmap_id, u=username, type=_username_type(username), m=mode.value, mods=mods.value if mods else None, limit=limit), JsonList(BeatmapScore))
[ "def", "get_scores", "(", "self", ",", "beatmap_id", ",", "*", ",", "username", "=", "None", ",", "mode", "=", "OsuMode", ".", "osu", ",", "mods", "=", "None", ",", "limit", "=", "50", ")", ":", "return", "self", ".", "_make_req", "(", "endpoints", ...
Get the top scores for a given beatmap. Parameters ---------- beatmap_id Individual Beatmap ID to lookup. username : str or int A `str` representing the user's username, or an `int` representing the user's id. If specified, restricts returned scores to the specified user. mode : :class:`osuapi.enums.OsuMode` The osu! game mode for which to look up. Defaults to osu!standard. mods : :class:`osuap:class:`osuapi.enums.OsuMod` If specified, restricts returned scores to the specified mods. limit Number of results to return. Defaults to 50, maximum 100.
[ "Get", "the", "top", "scores", "for", "a", "given", "beatmap", "." ]
e46a76dc7c1f43e7ce63ab83ab7162ab5c3930ec
https://github.com/khazhyk/osuapi/blob/e46a76dc7c1f43e7ce63ab83ab7162ab5c3930ec/osuapi/osu.py#L93-L116
train
45,619
khazhyk/osuapi
osuapi/osu.py
OsuApi.get_beatmaps
def get_beatmaps(self, *, since=None, beatmapset_id=None, beatmap_id=None, username=None, mode=None, include_converted=False, beatmap_hash=None, limit=500): """Get beatmaps. Parameters ---------- since : datetime If specified, restrict results to beatmaps *ranked* after this date. beatmapset_id If specified, restrict results to a specific beatmap set. beatmap_id If specified, restrict results to a specific beatmap. username : str or int A `str` representing the user's username, or an `int` representing the user's id. If specified, restrict results to a specific user. mode : :class:`osuapi.enums.OsuMode` If specified, restrict results to a specific osu! game mode. include_converted : bool Whether or not to include autoconverts. Defaults to false. beatmap_hash If specified, restricts results to a specific beatmap hash. limit Number of results to return. Defaults to 500, maximum 500. """ return self._make_req(endpoints.BEATMAPS, dict( k=self.key, s=beatmapset_id, b=beatmap_id, u=username, since="{:%Y-%m-%d %H:%M:%S}".format(since) if since is not None else None, type=_username_type(username), m=mode.value if mode else None, a=int(include_converted), h=beatmap_hash, limit=limit ), JsonList(Beatmap))
python
def get_beatmaps(self, *, since=None, beatmapset_id=None, beatmap_id=None, username=None, mode=None, include_converted=False, beatmap_hash=None, limit=500): """Get beatmaps. Parameters ---------- since : datetime If specified, restrict results to beatmaps *ranked* after this date. beatmapset_id If specified, restrict results to a specific beatmap set. beatmap_id If specified, restrict results to a specific beatmap. username : str or int A `str` representing the user's username, or an `int` representing the user's id. If specified, restrict results to a specific user. mode : :class:`osuapi.enums.OsuMode` If specified, restrict results to a specific osu! game mode. include_converted : bool Whether or not to include autoconverts. Defaults to false. beatmap_hash If specified, restricts results to a specific beatmap hash. limit Number of results to return. Defaults to 500, maximum 500. """ return self._make_req(endpoints.BEATMAPS, dict( k=self.key, s=beatmapset_id, b=beatmap_id, u=username, since="{:%Y-%m-%d %H:%M:%S}".format(since) if since is not None else None, type=_username_type(username), m=mode.value if mode else None, a=int(include_converted), h=beatmap_hash, limit=limit ), JsonList(Beatmap))
[ "def", "get_beatmaps", "(", "self", ",", "*", ",", "since", "=", "None", ",", "beatmapset_id", "=", "None", ",", "beatmap_id", "=", "None", ",", "username", "=", "None", ",", "mode", "=", "None", ",", "include_converted", "=", "False", ",", "beatmap_hash...
Get beatmaps. Parameters ---------- since : datetime If specified, restrict results to beatmaps *ranked* after this date. beatmapset_id If specified, restrict results to a specific beatmap set. beatmap_id If specified, restrict results to a specific beatmap. username : str or int A `str` representing the user's username, or an `int` representing the user's id. If specified, restrict results to a specific user. mode : :class:`osuapi.enums.OsuMode` If specified, restrict results to a specific osu! game mode. include_converted : bool Whether or not to include autoconverts. Defaults to false. beatmap_hash If specified, restricts results to a specific beatmap hash. limit Number of results to return. Defaults to 500, maximum 500.
[ "Get", "beatmaps", "." ]
e46a76dc7c1f43e7ce63ab83ab7162ab5c3930ec
https://github.com/khazhyk/osuapi/blob/e46a76dc7c1f43e7ce63ab83ab7162ab5c3930ec/osuapi/osu.py#L118-L153
train
45,620
khazhyk/osuapi
osuapi/osu.py
OsuApi.get_match
def get_match(self, match_id): """Get a multiplayer match. Parameters ---------- match_id The ID of the match to retrieve. This is the ID that you see in a online multiplayer match summary. This does not correspond the in-game game ID.""" return self._make_req(endpoints.MATCH, dict( k=self.key, mp=match_id), Match)
python
def get_match(self, match_id): """Get a multiplayer match. Parameters ---------- match_id The ID of the match to retrieve. This is the ID that you see in a online multiplayer match summary. This does not correspond the in-game game ID.""" return self._make_req(endpoints.MATCH, dict( k=self.key, mp=match_id), Match)
[ "def", "get_match", "(", "self", ",", "match_id", ")", ":", "return", "self", ".", "_make_req", "(", "endpoints", ".", "MATCH", ",", "dict", "(", "k", "=", "self", ".", "key", ",", "mp", "=", "match_id", ")", ",", "Match", ")" ]
Get a multiplayer match. Parameters ---------- match_id The ID of the match to retrieve. This is the ID that you see in a online multiplayer match summary. This does not correspond the in-game game ID.
[ "Get", "a", "multiplayer", "match", "." ]
e46a76dc7c1f43e7ce63ab83ab7162ab5c3930ec
https://github.com/khazhyk/osuapi/blob/e46a76dc7c1f43e7ce63ab83ab7162ab5c3930ec/osuapi/osu.py#L155-L165
train
45,621
IBM/pyxcli
pyxcli/client.py
XCLIClient.get_user_client
def get_user_client(self, user, password, populate=True): """ Returns a new client for the given user. This is a lightweight client that only uses different credentials and shares the transport with the underlying client """ return XCLIClientForUser(weakproxy(self), user, password, populate=populate)
python
def get_user_client(self, user, password, populate=True): """ Returns a new client for the given user. This is a lightweight client that only uses different credentials and shares the transport with the underlying client """ return XCLIClientForUser(weakproxy(self), user, password, populate=populate)
[ "def", "get_user_client", "(", "self", ",", "user", ",", "password", ",", "populate", "=", "True", ")", ":", "return", "XCLIClientForUser", "(", "weakproxy", "(", "self", ")", ",", "user", ",", "password", ",", "populate", "=", "populate", ")" ]
Returns a new client for the given user. This is a lightweight client that only uses different credentials and shares the transport with the underlying client
[ "Returns", "a", "new", "client", "for", "the", "given", "user", ".", "This", "is", "a", "lightweight", "client", "that", "only", "uses", "different", "credentials", "and", "shares", "the", "transport", "with", "the", "underlying", "client" ]
7d8ece1dcc16f50246740a447aa81b94a0dbced4
https://github.com/IBM/pyxcli/blob/7d8ece1dcc16f50246740a447aa81b94a0dbced4/pyxcli/client.py#L322-L329
train
45,622
IBM/pyxcli
pyxcli/client.py
XCLIClient.get_remote_client
def get_remote_client(self, target_name, user=None, password=None): """ Returns a new client for the remote target. This is a lightweight client that only uses different credentials and shares the transport with the underlying client """ if user: base = self.get_user_client(user, password, populate=False) else: base = weakproxy(self) return RemoteXCLIClient(base, target_name, populate=True)
python
def get_remote_client(self, target_name, user=None, password=None): """ Returns a new client for the remote target. This is a lightweight client that only uses different credentials and shares the transport with the underlying client """ if user: base = self.get_user_client(user, password, populate=False) else: base = weakproxy(self) return RemoteXCLIClient(base, target_name, populate=True)
[ "def", "get_remote_client", "(", "self", ",", "target_name", ",", "user", "=", "None", ",", "password", "=", "None", ")", ":", "if", "user", ":", "base", "=", "self", ".", "get_user_client", "(", "user", ",", "password", ",", "populate", "=", "False", ...
Returns a new client for the remote target. This is a lightweight client that only uses different credentials and shares the transport with the underlying client
[ "Returns", "a", "new", "client", "for", "the", "remote", "target", ".", "This", "is", "a", "lightweight", "client", "that", "only", "uses", "different", "credentials", "and", "shares", "the", "transport", "with", "the", "underlying", "client" ]
7d8ece1dcc16f50246740a447aa81b94a0dbced4
https://github.com/IBM/pyxcli/blob/7d8ece1dcc16f50246740a447aa81b94a0dbced4/pyxcli/client.py#L331-L341
train
45,623
IBM/pyxcli
pyxcli/client.py
XCLIClient.as_user
def as_user(self, user, password): """ A context-manager for ``get_user_client``. Allows the execution of commands as a different user with ease. Example: >>> c.cmd.vol_list() >>> with c.as_user("user", "password"): ... c.cmd.vol_list() """ with self.options(user=user, password=password): yield self
python
def as_user(self, user, password): """ A context-manager for ``get_user_client``. Allows the execution of commands as a different user with ease. Example: >>> c.cmd.vol_list() >>> with c.as_user("user", "password"): ... c.cmd.vol_list() """ with self.options(user=user, password=password): yield self
[ "def", "as_user", "(", "self", ",", "user", ",", "password", ")", ":", "with", "self", ".", "options", "(", "user", "=", "user", ",", "password", "=", "password", ")", ":", "yield", "self" ]
A context-manager for ``get_user_client``. Allows the execution of commands as a different user with ease. Example: >>> c.cmd.vol_list() >>> with c.as_user("user", "password"): ... c.cmd.vol_list()
[ "A", "context", "-", "manager", "for", "get_user_client", ".", "Allows", "the", "execution", "of", "commands", "as", "a", "different", "user", "with", "ease", "." ]
7d8ece1dcc16f50246740a447aa81b94a0dbced4
https://github.com/IBM/pyxcli/blob/7d8ece1dcc16f50246740a447aa81b94a0dbced4/pyxcli/client.py#L344-L358
train
45,624
khazhyk/osuapi
osuapi/model.py
Score.accuracy
def accuracy(self, mode: OsuMode): """Calculated accuracy. See Also -------- <https://osu.ppy.sh/help/wiki/Accuracy> """ if mode is OsuMode.osu: return ( (6 * self.count300 + 2 * self.count100 + self.count50) / (6 * (self.count300 + self.count100 + self.count50 + self.countmiss))) if mode is OsuMode.taiko: return ( (self.count300 + self.countgeki + (0.5*(self.count100 + self.countkatu))) / (self.count300 + self.countgeki + self.count100 + self.countkatu + self.countmiss)) if mode is OsuMode.mania: return ( (6 * (self.countgeki + self.count300) + 4 * self.countkatu + 2 * self.count100 + self.count50) / (6 * (self.countgeki + self.count300 + self.countkatu + self.count100 + self.count50 + self.countmiss))) if mode is OsuMode.ctb: return ( (self.count50 + self.count100 + self.count300) / (self.count50 + self.count100 + self.count300 + self.countmiss + self.countkatu))
python
def accuracy(self, mode: OsuMode): """Calculated accuracy. See Also -------- <https://osu.ppy.sh/help/wiki/Accuracy> """ if mode is OsuMode.osu: return ( (6 * self.count300 + 2 * self.count100 + self.count50) / (6 * (self.count300 + self.count100 + self.count50 + self.countmiss))) if mode is OsuMode.taiko: return ( (self.count300 + self.countgeki + (0.5*(self.count100 + self.countkatu))) / (self.count300 + self.countgeki + self.count100 + self.countkatu + self.countmiss)) if mode is OsuMode.mania: return ( (6 * (self.countgeki + self.count300) + 4 * self.countkatu + 2 * self.count100 + self.count50) / (6 * (self.countgeki + self.count300 + self.countkatu + self.count100 + self.count50 + self.countmiss))) if mode is OsuMode.ctb: return ( (self.count50 + self.count100 + self.count300) / (self.count50 + self.count100 + self.count300 + self.countmiss + self.countkatu))
[ "def", "accuracy", "(", "self", ",", "mode", ":", "OsuMode", ")", ":", "if", "mode", "is", "OsuMode", ".", "osu", ":", "return", "(", "(", "6", "*", "self", ".", "count300", "+", "2", "*", "self", ".", "count100", "+", "self", ".", "count50", ")"...
Calculated accuracy. See Also -------- <https://osu.ppy.sh/help/wiki/Accuracy>
[ "Calculated", "accuracy", "." ]
e46a76dc7c1f43e7ce63ab83ab7162ab5c3930ec
https://github.com/khazhyk/osuapi/blob/e46a76dc7c1f43e7ce63ab83ab7162ab5c3930ec/osuapi/model.py#L62-L84
train
45,625
IBM/pyxcli
pyxcli/mirroring/cg_recovery_manager.py
CGRecoveryManager.create_mirror
def create_mirror(self, resource_name, target_name, mirror_type, slave_resource_name, rpo=None, remote_rpo=None, schedule=None, remote_schedule=None, activate_mirror='no'): '''creates a mirror and returns a mirror object. target name must be a valid target from target_list, mirror type must be 'sync' or 'async', slave_resource_name would be the slave_cg name''' return self._create_mirror('cg', resource_name, target_name, mirror_type, slave_resource_name, rpo=rpo, remote_rpo=remote_rpo, schedule=schedule, remote_schedule=remote_schedule, activate_mirror=activate_mirror)
python
def create_mirror(self, resource_name, target_name, mirror_type, slave_resource_name, rpo=None, remote_rpo=None, schedule=None, remote_schedule=None, activate_mirror='no'): '''creates a mirror and returns a mirror object. target name must be a valid target from target_list, mirror type must be 'sync' or 'async', slave_resource_name would be the slave_cg name''' return self._create_mirror('cg', resource_name, target_name, mirror_type, slave_resource_name, rpo=rpo, remote_rpo=remote_rpo, schedule=schedule, remote_schedule=remote_schedule, activate_mirror=activate_mirror)
[ "def", "create_mirror", "(", "self", ",", "resource_name", ",", "target_name", ",", "mirror_type", ",", "slave_resource_name", ",", "rpo", "=", "None", ",", "remote_rpo", "=", "None", ",", "schedule", "=", "None", ",", "remote_schedule", "=", "None", ",", "a...
creates a mirror and returns a mirror object. target name must be a valid target from target_list, mirror type must be 'sync' or 'async', slave_resource_name would be the slave_cg name
[ "creates", "a", "mirror", "and", "returns", "a", "mirror", "object", ".", "target", "name", "must", "be", "a", "valid", "target", "from", "target_list", "mirror", "type", "must", "be", "sync", "or", "async", "slave_resource_name", "would", "be", "the", "slav...
7d8ece1dcc16f50246740a447aa81b94a0dbced4
https://github.com/IBM/pyxcli/blob/7d8ece1dcc16f50246740a447aa81b94a0dbced4/pyxcli/mirroring/cg_recovery_manager.py#L105-L118
train
45,626
IBM/pyxcli
pyxcli/mirroring/cg_recovery_manager.py
CGRecoveryManager.get_cg_volumes
def get_cg_volumes(self, group_id): """ return all non snapshots volumes in cg """ for volume in self.xcli_client.cmd.vol_list(cg=group_id): if volume.snapshot_of == '': yield volume.name
python
def get_cg_volumes(self, group_id): """ return all non snapshots volumes in cg """ for volume in self.xcli_client.cmd.vol_list(cg=group_id): if volume.snapshot_of == '': yield volume.name
[ "def", "get_cg_volumes", "(", "self", ",", "group_id", ")", ":", "for", "volume", "in", "self", ".", "xcli_client", ".", "cmd", ".", "vol_list", "(", "cg", "=", "group_id", ")", ":", "if", "volume", ".", "snapshot_of", "==", "''", ":", "yield", "volume...
return all non snapshots volumes in cg
[ "return", "all", "non", "snapshots", "volumes", "in", "cg" ]
7d8ece1dcc16f50246740a447aa81b94a0dbced4
https://github.com/IBM/pyxcli/blob/7d8ece1dcc16f50246740a447aa81b94a0dbced4/pyxcli/mirroring/cg_recovery_manager.py#L206-L210
train
45,627
IBM/pyxcli
pyxcli/transports.py
SocketTransport._certificate_required
def _certificate_required(cls, hostname, port=XCLI_DEFAULT_PORT, ca_certs=None, validate=None): ''' returns true if connection should verify certificate ''' if not ca_certs: return False xlog.debug("CONNECT SSL %s:%s, cert_file=%s", hostname, port, ca_certs) certificate = ssl.get_server_certificate((hostname, port), ca_certs=None) # handle XIV pre-defined certifications # if a validation function was given - we let the user check # the certificate himself, with the user's own validate function. # if the validate returned True - the user checked the cert # and we don't need check it, so we return false. if validate: return not validate(certificate) return True
python
def _certificate_required(cls, hostname, port=XCLI_DEFAULT_PORT, ca_certs=None, validate=None): ''' returns true if connection should verify certificate ''' if not ca_certs: return False xlog.debug("CONNECT SSL %s:%s, cert_file=%s", hostname, port, ca_certs) certificate = ssl.get_server_certificate((hostname, port), ca_certs=None) # handle XIV pre-defined certifications # if a validation function was given - we let the user check # the certificate himself, with the user's own validate function. # if the validate returned True - the user checked the cert # and we don't need check it, so we return false. if validate: return not validate(certificate) return True
[ "def", "_certificate_required", "(", "cls", ",", "hostname", ",", "port", "=", "XCLI_DEFAULT_PORT", ",", "ca_certs", "=", "None", ",", "validate", "=", "None", ")", ":", "if", "not", "ca_certs", ":", "return", "False", "xlog", ".", "debug", "(", "\"CONNECT...
returns true if connection should verify certificate
[ "returns", "true", "if", "connection", "should", "verify", "certificate" ]
7d8ece1dcc16f50246740a447aa81b94a0dbced4
https://github.com/IBM/pyxcli/blob/7d8ece1dcc16f50246740a447aa81b94a0dbced4/pyxcli/transports.py#L161-L180
train
45,628
IBM/pyxcli
pyxcli/response.py
_populate_bunch_with_element
def _populate_bunch_with_element(element): """ Helper function to recursively populates a Bunch from an XML tree. Returns leaf XML elements as a simple value, branch elements are returned as Bunches containing their subelements as value or recursively generated Bunch members. """ if 'value' in element.attrib: return element.get('value') current_bunch = Bunch() if element.get('id'): current_bunch['nextra_element_id'] = element.get('id') for subelement in element.getchildren(): current_bunch[subelement.tag] = _populate_bunch_with_element( subelement) return current_bunch
python
def _populate_bunch_with_element(element): """ Helper function to recursively populates a Bunch from an XML tree. Returns leaf XML elements as a simple value, branch elements are returned as Bunches containing their subelements as value or recursively generated Bunch members. """ if 'value' in element.attrib: return element.get('value') current_bunch = Bunch() if element.get('id'): current_bunch['nextra_element_id'] = element.get('id') for subelement in element.getchildren(): current_bunch[subelement.tag] = _populate_bunch_with_element( subelement) return current_bunch
[ "def", "_populate_bunch_with_element", "(", "element", ")", ":", "if", "'value'", "in", "element", ".", "attrib", ":", "return", "element", ".", "get", "(", "'value'", ")", "current_bunch", "=", "Bunch", "(", ")", "if", "element", ".", "get", "(", "'id'", ...
Helper function to recursively populates a Bunch from an XML tree. Returns leaf XML elements as a simple value, branch elements are returned as Bunches containing their subelements as value or recursively generated Bunch members.
[ "Helper", "function", "to", "recursively", "populates", "a", "Bunch", "from", "an", "XML", "tree", ".", "Returns", "leaf", "XML", "elements", "as", "a", "simple", "value", "branch", "elements", "are", "returned", "as", "Bunches", "containing", "their", "subele...
7d8ece1dcc16f50246740a447aa81b94a0dbced4
https://github.com/IBM/pyxcli/blob/7d8ece1dcc16f50246740a447aa81b94a0dbced4/pyxcli/response.py#L122-L138
train
45,629
IBM/pyxcli
pyxcli/response.py
XCLIResponse.as_single_element
def as_single_element(self): """ Processes the response as a single-element response, like config_get or system_counters_get. If there is more then one element in the response or no elements this raises a ResponseError """ if self.as_return_etree is None: return None if len(self.as_return_etree.getchildren()) == 1: return _populate_bunch_with_element(self.as_return_etree. getchildren()[0]) return _populate_bunch_with_element(self.as_return_etree)
python
def as_single_element(self): """ Processes the response as a single-element response, like config_get or system_counters_get. If there is more then one element in the response or no elements this raises a ResponseError """ if self.as_return_etree is None: return None if len(self.as_return_etree.getchildren()) == 1: return _populate_bunch_with_element(self.as_return_etree. getchildren()[0]) return _populate_bunch_with_element(self.as_return_etree)
[ "def", "as_single_element", "(", "self", ")", ":", "if", "self", ".", "as_return_etree", "is", "None", ":", "return", "None", "if", "len", "(", "self", ".", "as_return_etree", ".", "getchildren", "(", ")", ")", "==", "1", ":", "return", "_populate_bunch_wi...
Processes the response as a single-element response, like config_get or system_counters_get. If there is more then one element in the response or no elements this raises a ResponseError
[ "Processes", "the", "response", "as", "a", "single", "-", "element", "response", "like", "config_get", "or", "system_counters_get", ".", "If", "there", "is", "more", "then", "one", "element", "in", "the", "response", "or", "no", "elements", "this", "raises", ...
7d8ece1dcc16f50246740a447aa81b94a0dbced4
https://github.com/IBM/pyxcli/blob/7d8ece1dcc16f50246740a447aa81b94a0dbced4/pyxcli/response.py#L75-L87
train
45,630
khazhyk/osuapi
osuapi/flags.py
Flags.enabled_flags
def enabled_flags(self): """Return the objects for each individual set flag.""" if not self.value: yield self.__flags_members__[0] return val = self.value while val: lowest_bit = val & -val val ^= lowest_bit yield self.__flags_members__[lowest_bit]
python
def enabled_flags(self): """Return the objects for each individual set flag.""" if not self.value: yield self.__flags_members__[0] return val = self.value while val: lowest_bit = val & -val val ^= lowest_bit yield self.__flags_members__[lowest_bit]
[ "def", "enabled_flags", "(", "self", ")", ":", "if", "not", "self", ".", "value", ":", "yield", "self", ".", "__flags_members__", "[", "0", "]", "return", "val", "=", "self", ".", "value", "while", "val", ":", "lowest_bit", "=", "val", "&", "-", "val...
Return the objects for each individual set flag.
[ "Return", "the", "objects", "for", "each", "individual", "set", "flag", "." ]
e46a76dc7c1f43e7ce63ab83ab7162ab5c3930ec
https://github.com/khazhyk/osuapi/blob/e46a76dc7c1f43e7ce63ab83ab7162ab5c3930ec/osuapi/flags.py#L78-L88
train
45,631
khazhyk/osuapi
osuapi/flags.py
Flags.contains_any
def contains_any(self, other): """Check if any flags are set. (OsuMod.Hidden | OsuMod.HardRock) in flags # Check if either hidden or hardrock are enabled. OsuMod.keyMod in flags # Check if any keymod is enabled. """ return self.value == other.value or self.value & other.value
python
def contains_any(self, other): """Check if any flags are set. (OsuMod.Hidden | OsuMod.HardRock) in flags # Check if either hidden or hardrock are enabled. OsuMod.keyMod in flags # Check if any keymod is enabled. """ return self.value == other.value or self.value & other.value
[ "def", "contains_any", "(", "self", ",", "other", ")", ":", "return", "self", ".", "value", "==", "other", ".", "value", "or", "self", ".", "value", "&", "other", ".", "value" ]
Check if any flags are set. (OsuMod.Hidden | OsuMod.HardRock) in flags # Check if either hidden or hardrock are enabled. OsuMod.keyMod in flags # Check if any keymod is enabled.
[ "Check", "if", "any", "flags", "are", "set", "." ]
e46a76dc7c1f43e7ce63ab83ab7162ab5c3930ec
https://github.com/khazhyk/osuapi/blob/e46a76dc7c1f43e7ce63ab83ab7162ab5c3930ec/osuapi/flags.py#L90-L96
train
45,632
ianlini/bistiming
bistiming/multistopwatch.py
MultiStopwatch.get_statistics
def get_statistics(self): """Get all statistics as a dictionary. Returns ------- statistics : Dict[str, List] """ return { 'cumulative_elapsed_time': self.get_cumulative_elapsed_time(), 'percentage': self.get_percentage(), 'n_splits': self.get_n_splits(), 'mean_per_split': self.get_mean_per_split(), }
python
def get_statistics(self): """Get all statistics as a dictionary. Returns ------- statistics : Dict[str, List] """ return { 'cumulative_elapsed_time': self.get_cumulative_elapsed_time(), 'percentage': self.get_percentage(), 'n_splits': self.get_n_splits(), 'mean_per_split': self.get_mean_per_split(), }
[ "def", "get_statistics", "(", "self", ")", ":", "return", "{", "'cumulative_elapsed_time'", ":", "self", ".", "get_cumulative_elapsed_time", "(", ")", ",", "'percentage'", ":", "self", ".", "get_percentage", "(", ")", ",", "'n_splits'", ":", "self", ".", "get_...
Get all statistics as a dictionary. Returns ------- statistics : Dict[str, List]
[ "Get", "all", "statistics", "as", "a", "dictionary", "." ]
46a78ec647723c3516fc4fc73f2619ab41f647f2
https://github.com/ianlini/bistiming/blob/46a78ec647723c3516fc4fc73f2619ab41f647f2/bistiming/multistopwatch.py#L76-L88
train
45,633
KyleJamesWalker/yamlsettings
yamlsettings/extensions/base.py
YamlSettingsExtension.conform_query
def conform_query(cls, query): """Converts the query string from a target uri, uses cls.default_query to populate default arguments. :param query: Unparsed query string :type query: urllib.parse.unsplit(uri).query :returns: Dictionary of parsed values, everything in cls.default_query will be set if not passed. """ query = parse_qs(query, keep_blank_values=True) # Load yaml of passed values for key, vals in query.items(): # Multiple values of the same name could be passed use first # Also params without strings will be treated as true values query[key] = yaml.load(vals[0] or 'true', Loader=yaml.FullLoader) # If expected, populate with defaults for key, val in cls.default_query.items(): if key not in query: query[key] = val return query
python
def conform_query(cls, query): """Converts the query string from a target uri, uses cls.default_query to populate default arguments. :param query: Unparsed query string :type query: urllib.parse.unsplit(uri).query :returns: Dictionary of parsed values, everything in cls.default_query will be set if not passed. """ query = parse_qs(query, keep_blank_values=True) # Load yaml of passed values for key, vals in query.items(): # Multiple values of the same name could be passed use first # Also params without strings will be treated as true values query[key] = yaml.load(vals[0] or 'true', Loader=yaml.FullLoader) # If expected, populate with defaults for key, val in cls.default_query.items(): if key not in query: query[key] = val return query
[ "def", "conform_query", "(", "cls", ",", "query", ")", ":", "query", "=", "parse_qs", "(", "query", ",", "keep_blank_values", "=", "True", ")", "# Load yaml of passed values", "for", "key", ",", "vals", "in", "query", ".", "items", "(", ")", ":", "# Multip...
Converts the query string from a target uri, uses cls.default_query to populate default arguments. :param query: Unparsed query string :type query: urllib.parse.unsplit(uri).query :returns: Dictionary of parsed values, everything in cls.default_query will be set if not passed.
[ "Converts", "the", "query", "string", "from", "a", "target", "uri", "uses", "cls", ".", "default_query", "to", "populate", "default", "arguments", "." ]
ddd7df2ca995ddf191b24c4d35e9dd28186e4535
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/extensions/base.py#L15-L38
train
45,634
lqez/hog
hog/hog.py
hog
def hog(concurrency, requests, limit, timeout, params, paramfile, headers, headerfile, method, url): '''Sending multiple `HTTP` requests `ON` `GREEN` thread''' params = parse_from_list_and_file(params, paramfile) headers = parse_from_list_and_file(headers, headerfile) # Running information click.echo(HR) click.echo("Hog is running with {} threads, ".format(concurrency) + "{} requests ".format(requests) + "and timeout in {} second(s).".format(timeout)) if limit != 0: click.echo(">>> Limit: {} request(s) per second.".format(limit)) click.echo(HR) # Let's begin! result = Hog(callback).run(url, params, headers, method, timeout, concurrency, requests, limit) sys.stdout.write("\n") print_result(result)
python
def hog(concurrency, requests, limit, timeout, params, paramfile, headers, headerfile, method, url): '''Sending multiple `HTTP` requests `ON` `GREEN` thread''' params = parse_from_list_and_file(params, paramfile) headers = parse_from_list_and_file(headers, headerfile) # Running information click.echo(HR) click.echo("Hog is running with {} threads, ".format(concurrency) + "{} requests ".format(requests) + "and timeout in {} second(s).".format(timeout)) if limit != 0: click.echo(">>> Limit: {} request(s) per second.".format(limit)) click.echo(HR) # Let's begin! result = Hog(callback).run(url, params, headers, method, timeout, concurrency, requests, limit) sys.stdout.write("\n") print_result(result)
[ "def", "hog", "(", "concurrency", ",", "requests", ",", "limit", ",", "timeout", ",", "params", ",", "paramfile", ",", "headers", ",", "headerfile", ",", "method", ",", "url", ")", ":", "params", "=", "parse_from_list_and_file", "(", "params", ",", "paramf...
Sending multiple `HTTP` requests `ON` `GREEN` thread
[ "Sending", "multiple", "HTTP", "requests", "ON", "GREEN", "thread" ]
c88038a56a829015ab3d10119d6533d9b8d4784e
https://github.com/lqez/hog/blob/c88038a56a829015ab3d10119d6533d9b8d4784e/hog/hog.py#L200-L220
train
45,635
JarryShaw/DictDumper
src/plist.py
PLIST._append_dict
def _append_dict(self, value, _file): """Call this function to write dict contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file """ _tabs = '\t' * self._tctr _labs = '{tabs}<dict>\n'.format(tabs=_tabs) _file.write(_labs) self._tctr += 1 for (_item, _text) in value.items(): if _text is None: continue _tabs = '\t' * self._tctr _keys = '{tabs}<key>{item}</key>\n'.format(tabs=_tabs, item=_item) _file.write(_keys) _text = self.object_hook(_text) _type = type(_text).__name__ _MAGIC_TYPES[_type](self, _text, _file) self._tctr -= 1 _tabs = '\t' * self._tctr _labs = '{tabs}</dict>\n'.format(tabs=_tabs) _file.write(_labs)
python
def _append_dict(self, value, _file): """Call this function to write dict contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file """ _tabs = '\t' * self._tctr _labs = '{tabs}<dict>\n'.format(tabs=_tabs) _file.write(_labs) self._tctr += 1 for (_item, _text) in value.items(): if _text is None: continue _tabs = '\t' * self._tctr _keys = '{tabs}<key>{item}</key>\n'.format(tabs=_tabs, item=_item) _file.write(_keys) _text = self.object_hook(_text) _type = type(_text).__name__ _MAGIC_TYPES[_type](self, _text, _file) self._tctr -= 1 _tabs = '\t' * self._tctr _labs = '{tabs}</dict>\n'.format(tabs=_tabs) _file.write(_labs)
[ "def", "_append_dict", "(", "self", ",", "value", ",", "_file", ")", ":", "_tabs", "=", "'\\t'", "*", "self", ".", "_tctr", "_labs", "=", "'{tabs}<dict>\\n'", ".", "format", "(", "tabs", "=", "_tabs", ")", "_file", ".", "write", "(", "_labs", ")", "s...
Call this function to write dict contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
[ "Call", "this", "function", "to", "write", "dict", "contents", "." ]
430efcfdff18bb2421c3f27059ff94c93e621483
https://github.com/JarryShaw/DictDumper/blob/430efcfdff18bb2421c3f27059ff94c93e621483/src/plist.py#L192-L220
train
45,636
JarryShaw/DictDumper
src/plist.py
PLIST._append_data
def _append_data(self, value, _file): """Call this function to write data contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file """ # binascii.b2a_base64(value) -> plistlib.Data # binascii.a2b_base64(Data) -> value(bytes) _tabs = '\t' * self._tctr _text = base64.b64encode(value).decode() # value.hex() # str(value)[2:-1] _labs = '{tabs}<data>{text}</data>\n'.format(tabs=_tabs, text=_text) # _labs = '{tabs}<data>\n'.format(tabs=_tabs) # _list = [] # for _item in textwrap.wrap(value.hex(), 32): # _text = ' '.join(textwrap.wrap(_item, 2)) # _item = '{tabs}\t{text}'.format(tabs=_tabs, text=_text) # _list.append(_item) # _labs += '\n'.join(_list) # _data = [H for H in iter( # functools.partial(io.StringIO(value.hex()).read, 2), '') # ] # to split bytes string into length-2 hex string list # _labs += '\n{tabs}</data>\n'.format(tabs=_tabs) _file.write(_labs)
python
def _append_data(self, value, _file): """Call this function to write data contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file """ # binascii.b2a_base64(value) -> plistlib.Data # binascii.a2b_base64(Data) -> value(bytes) _tabs = '\t' * self._tctr _text = base64.b64encode(value).decode() # value.hex() # str(value)[2:-1] _labs = '{tabs}<data>{text}</data>\n'.format(tabs=_tabs, text=_text) # _labs = '{tabs}<data>\n'.format(tabs=_tabs) # _list = [] # for _item in textwrap.wrap(value.hex(), 32): # _text = ' '.join(textwrap.wrap(_item, 2)) # _item = '{tabs}\t{text}'.format(tabs=_tabs, text=_text) # _list.append(_item) # _labs += '\n'.join(_list) # _data = [H for H in iter( # functools.partial(io.StringIO(value.hex()).read, 2), '') # ] # to split bytes string into length-2 hex string list # _labs += '\n{tabs}</data>\n'.format(tabs=_tabs) _file.write(_labs)
[ "def", "_append_data", "(", "self", ",", "value", ",", "_file", ")", ":", "# binascii.b2a_base64(value) -> plistlib.Data", "# binascii.a2b_base64(Data) -> value(bytes)", "_tabs", "=", "'\\t'", "*", "self", ".", "_tctr", "_text", "=", "base64", ".", "b64encode", "(", ...
Call this function to write data contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
[ "Call", "this", "function", "to", "write", "data", "contents", "." ]
430efcfdff18bb2421c3f27059ff94c93e621483
https://github.com/JarryShaw/DictDumper/blob/430efcfdff18bb2421c3f27059ff94c93e621483/src/plist.py#L235-L262
train
45,637
JarryShaw/DictDumper
src/plist.py
PLIST._append_integer
def _append_integer(self, value, _file): """Call this function to write integer contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file """ _tabs = '\t' * self._tctr _text = value _labs = '{tabs}<integer>{text}</integer>\n'.format(tabs=_tabs, text=_text) _file.write(_labs)
python
def _append_integer(self, value, _file): """Call this function to write integer contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file """ _tabs = '\t' * self._tctr _text = value _labs = '{tabs}<integer>{text}</integer>\n'.format(tabs=_tabs, text=_text) _file.write(_labs)
[ "def", "_append_integer", "(", "self", ",", "value", ",", "_file", ")", ":", "_tabs", "=", "'\\t'", "*", "self", ".", "_tctr", "_text", "=", "value", "_labs", "=", "'{tabs}<integer>{text}</integer>\\n'", ".", "format", "(", "tabs", "=", "_tabs", ",", "text...
Call this function to write integer contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
[ "Call", "this", "function", "to", "write", "integer", "contents", "." ]
430efcfdff18bb2421c3f27059ff94c93e621483
https://github.com/JarryShaw/DictDumper/blob/430efcfdff18bb2421c3f27059ff94c93e621483/src/plist.py#L277-L288
train
45,638
undertherain/pycontextfree
site/plugins/copy_pics/copy_pics.py
CopyPics.register_output_name
def register_output_name(self, input_folder, rel_name, rel_output_name): """Register proper and improper file mappings.""" self.improper_input_file_mapping[rel_name].add(rel_output_name) self.proper_input_file_mapping[os.path.join(input_folder, rel_name)] = rel_output_name self.proper_input_file_mapping[rel_output_name] = rel_output_name
python
def register_output_name(self, input_folder, rel_name, rel_output_name): """Register proper and improper file mappings.""" self.improper_input_file_mapping[rel_name].add(rel_output_name) self.proper_input_file_mapping[os.path.join(input_folder, rel_name)] = rel_output_name self.proper_input_file_mapping[rel_output_name] = rel_output_name
[ "def", "register_output_name", "(", "self", ",", "input_folder", ",", "rel_name", ",", "rel_output_name", ")", ":", "self", ".", "improper_input_file_mapping", "[", "rel_name", "]", ".", "add", "(", "rel_output_name", ")", "self", ".", "proper_input_file_mapping", ...
Register proper and improper file mappings.
[ "Register", "proper", "and", "improper", "file", "mappings", "." ]
91505e978f6034863747c98d919ac11b029b1ac3
https://github.com/undertherain/pycontextfree/blob/91505e978f6034863747c98d919ac11b029b1ac3/site/plugins/copy_pics/copy_pics.py#L25-L29
train
45,639
KyleJamesWalker/yamlsettings
yamlsettings/extensions/registry.py
ExtensionRegistry._discover
def _discover(self): """Find and install all extensions""" for ep in pkg_resources.iter_entry_points('yamlsettings10'): ext = ep.load() if callable(ext): ext = ext() self.add(ext)
python
def _discover(self): """Find and install all extensions""" for ep in pkg_resources.iter_entry_points('yamlsettings10'): ext = ep.load() if callable(ext): ext = ext() self.add(ext)
[ "def", "_discover", "(", "self", ")", ":", "for", "ep", "in", "pkg_resources", ".", "iter_entry_points", "(", "'yamlsettings10'", ")", ":", "ext", "=", "ep", ".", "load", "(", ")", "if", "callable", "(", "ext", ")", ":", "ext", "=", "ext", "(", ")", ...
Find and install all extensions
[ "Find", "and", "install", "all", "extensions" ]
ddd7df2ca995ddf191b24c4d35e9dd28186e4535
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/extensions/registry.py#L39-L45
train
45,640
KyleJamesWalker/yamlsettings
yamlsettings/extensions/registry.py
ExtensionRegistry.get_extension
def get_extension(self, protocol): """Retrieve extension for the given protocol :param protocol: name of the protocol :type protocol: string :raises NoProtocolError: no extension registered for protocol """ if protocol not in self.registry: raise NoProtocolError("No protocol for %s" % protocol) index = self.registry[protocol] return self.extensions[index]
python
def get_extension(self, protocol): """Retrieve extension for the given protocol :param protocol: name of the protocol :type protocol: string :raises NoProtocolError: no extension registered for protocol """ if protocol not in self.registry: raise NoProtocolError("No protocol for %s" % protocol) index = self.registry[protocol] return self.extensions[index]
[ "def", "get_extension", "(", "self", ",", "protocol", ")", ":", "if", "protocol", "not", "in", "self", ".", "registry", ":", "raise", "NoProtocolError", "(", "\"No protocol for %s\"", "%", "protocol", ")", "index", "=", "self", ".", "registry", "[", "protoco...
Retrieve extension for the given protocol :param protocol: name of the protocol :type protocol: string :raises NoProtocolError: no extension registered for protocol
[ "Retrieve", "extension", "for", "the", "given", "protocol" ]
ddd7df2ca995ddf191b24c4d35e9dd28186e4535
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/extensions/registry.py#L47-L58
train
45,641
KyleJamesWalker/yamlsettings
yamlsettings/extensions/registry.py
ExtensionRegistry.add
def add(self, extension): """Adds an extension to the registry :param extension: Extension object :type extension: yamlsettings.extensions.base.YamlSettingsExtension """ index = len(self.extensions) self.extensions[index] = extension for protocol in extension.protocols: self.registry[protocol] = index
python
def add(self, extension): """Adds an extension to the registry :param extension: Extension object :type extension: yamlsettings.extensions.base.YamlSettingsExtension """ index = len(self.extensions) self.extensions[index] = extension for protocol in extension.protocols: self.registry[protocol] = index
[ "def", "add", "(", "self", ",", "extension", ")", ":", "index", "=", "len", "(", "self", ".", "extensions", ")", "self", ".", "extensions", "[", "index", "]", "=", "extension", "for", "protocol", "in", "extension", ".", "protocols", ":", "self", ".", ...
Adds an extension to the registry :param extension: Extension object :type extension: yamlsettings.extensions.base.YamlSettingsExtension
[ "Adds", "an", "extension", "to", "the", "registry" ]
ddd7df2ca995ddf191b24c4d35e9dd28186e4535
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/extensions/registry.py#L60-L70
train
45,642
KyleJamesWalker/yamlsettings
yamlsettings/extensions/registry.py
ExtensionRegistry._load_first
def _load_first(self, target_uris, load_method, **kwargs): """Load first yamldict target found in uri list. :param target_uris: Uris to try and open :param load_method: load callback :type target_uri: list or string :type load_method: callback :returns: yamldict """ if isinstance(target_uris, string_types): target_uris = [target_uris] # TODO: Move the list logic into the extension, otherwise a # load will always try all missing files first. # TODO: How would multiple protocols work, should the registry hold # persist copies? for target_uri in target_uris: target = urlsplit(target_uri, scheme=self.default_protocol) extension = self.get_extension(target.scheme) query = extension.conform_query(target.query) try: yaml_dict = extension.load_target( target.scheme, target.path, target.fragment, target.username, target.password, target.hostname, target.port, query, load_method, **kwargs ) return yaml_dict except extension.not_found_exception: pass raise IOError("unable to load: {0}".format(target_uris))
python
def _load_first(self, target_uris, load_method, **kwargs): """Load first yamldict target found in uri list. :param target_uris: Uris to try and open :param load_method: load callback :type target_uri: list or string :type load_method: callback :returns: yamldict """ if isinstance(target_uris, string_types): target_uris = [target_uris] # TODO: Move the list logic into the extension, otherwise a # load will always try all missing files first. # TODO: How would multiple protocols work, should the registry hold # persist copies? for target_uri in target_uris: target = urlsplit(target_uri, scheme=self.default_protocol) extension = self.get_extension(target.scheme) query = extension.conform_query(target.query) try: yaml_dict = extension.load_target( target.scheme, target.path, target.fragment, target.username, target.password, target.hostname, target.port, query, load_method, **kwargs ) return yaml_dict except extension.not_found_exception: pass raise IOError("unable to load: {0}".format(target_uris))
[ "def", "_load_first", "(", "self", ",", "target_uris", ",", "load_method", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "target_uris", ",", "string_types", ")", ":", "target_uris", "=", "[", "target_uris", "]", "# TODO: Move the list logic into th...
Load first yamldict target found in uri list. :param target_uris: Uris to try and open :param load_method: load callback :type target_uri: list or string :type load_method: callback :returns: yamldict
[ "Load", "first", "yamldict", "target", "found", "in", "uri", "list", "." ]
ddd7df2ca995ddf191b24c4d35e9dd28186e4535
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/extensions/registry.py#L72-L112
train
45,643
KyleJamesWalker/yamlsettings
yamlsettings/extensions/registry.py
ExtensionRegistry.load
def load(self, target_uris, fields=None, **kwargs): """Load first yamldict target found in uri. :param target_uris: Uris to try and open :param fields: Fields to filter. Default: None :type target_uri: list or string :type fields: list :returns: yamldict """ yaml_dict = self._load_first( target_uris, yamlsettings.yamldict.load, **kwargs ) # TODO: Move this into the extension, otherwise every load from # a persistant location will refilter fields. if fields: yaml_dict.limit(fields) return yaml_dict
python
def load(self, target_uris, fields=None, **kwargs): """Load first yamldict target found in uri. :param target_uris: Uris to try and open :param fields: Fields to filter. Default: None :type target_uri: list or string :type fields: list :returns: yamldict """ yaml_dict = self._load_first( target_uris, yamlsettings.yamldict.load, **kwargs ) # TODO: Move this into the extension, otherwise every load from # a persistant location will refilter fields. if fields: yaml_dict.limit(fields) return yaml_dict
[ "def", "load", "(", "self", ",", "target_uris", ",", "fields", "=", "None", ",", "*", "*", "kwargs", ")", ":", "yaml_dict", "=", "self", ".", "_load_first", "(", "target_uris", ",", "yamlsettings", ".", "yamldict", ".", "load", ",", "*", "*", "kwargs",...
Load first yamldict target found in uri. :param target_uris: Uris to try and open :param fields: Fields to filter. Default: None :type target_uri: list or string :type fields: list :returns: yamldict
[ "Load", "first", "yamldict", "target", "found", "in", "uri", "." ]
ddd7df2ca995ddf191b24c4d35e9dd28186e4535
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/extensions/registry.py#L114-L133
train
45,644
KyleJamesWalker/yamlsettings
yamlsettings/yamldict.py
load_all
def load_all(stream): """ Parse all YAML documents in a stream and produce corresponding YAMLDict objects. """ loader = YAMLDictLoader(stream) try: while loader.check_data(): yield loader.get_data() finally: loader.dispose()
python
def load_all(stream): """ Parse all YAML documents in a stream and produce corresponding YAMLDict objects. """ loader = YAMLDictLoader(stream) try: while loader.check_data(): yield loader.get_data() finally: loader.dispose()
[ "def", "load_all", "(", "stream", ")", ":", "loader", "=", "YAMLDictLoader", "(", "stream", ")", "try", ":", "while", "loader", ".", "check_data", "(", ")", ":", "yield", "loader", ".", "get_data", "(", ")", "finally", ":", "loader", ".", "dispose", "(...
Parse all YAML documents in a stream and produce corresponding YAMLDict objects.
[ "Parse", "all", "YAML", "documents", "in", "a", "stream", "and", "produce", "corresponding", "YAMLDict", "objects", "." ]
ddd7df2ca995ddf191b24c4d35e9dd28186e4535
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/yamldict.py#L192-L202
train
45,645
KyleJamesWalker/yamlsettings
yamlsettings/yamldict.py
YAMLDict.rebase
def rebase(self, yaml_dict): ''' Use yaml_dict as self's new base and update with existing reverse of update. ''' base = yaml_dict.clone() base.update(self) self.clear() self.update(base)
python
def rebase(self, yaml_dict): ''' Use yaml_dict as self's new base and update with existing reverse of update. ''' base = yaml_dict.clone() base.update(self) self.clear() self.update(base)
[ "def", "rebase", "(", "self", ",", "yaml_dict", ")", ":", "base", "=", "yaml_dict", ".", "clone", "(", ")", "base", ".", "update", "(", "self", ")", "self", ".", "clear", "(", ")", "self", ".", "update", "(", "base", ")" ]
Use yaml_dict as self's new base and update with existing reverse of update.
[ "Use", "yaml_dict", "as", "self", "s", "new", "base", "and", "update", "with", "existing", "reverse", "of", "update", "." ]
ddd7df2ca995ddf191b24c4d35e9dd28186e4535
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/yamldict.py#L110-L117
train
45,646
KyleJamesWalker/yamlsettings
yamlsettings/yamldict.py
YAMLDict.limit
def limit(self, keys): ''' Remove all keys other than the keys specified. ''' if not isinstance(keys, list) and not isinstance(keys, tuple): keys = [keys] remove_keys = [k for k in self.keys() if k not in keys] for k in remove_keys: self.pop(k)
python
def limit(self, keys): ''' Remove all keys other than the keys specified. ''' if not isinstance(keys, list) and not isinstance(keys, tuple): keys = [keys] remove_keys = [k for k in self.keys() if k not in keys] for k in remove_keys: self.pop(k)
[ "def", "limit", "(", "self", ",", "keys", ")", ":", "if", "not", "isinstance", "(", "keys", ",", "list", ")", "and", "not", "isinstance", "(", "keys", ",", "tuple", ")", ":", "keys", "=", "[", "keys", "]", "remove_keys", "=", "[", "k", "for", "k"...
Remove all keys other than the keys specified.
[ "Remove", "all", "keys", "other", "than", "the", "keys", "specified", "." ]
ddd7df2ca995ddf191b24c4d35e9dd28186e4535
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/yamldict.py#L119-L126
train
45,647
KyleJamesWalker/yamlsettings
yamlsettings/helpers.py
save
def save(yaml_dict, filepath): ''' Save YAML settings to the specified file path. ''' yamldict.dump(yaml_dict, open(filepath, 'w'), default_flow_style=False)
python
def save(yaml_dict, filepath): ''' Save YAML settings to the specified file path. ''' yamldict.dump(yaml_dict, open(filepath, 'w'), default_flow_style=False)
[ "def", "save", "(", "yaml_dict", ",", "filepath", ")", ":", "yamldict", ".", "dump", "(", "yaml_dict", ",", "open", "(", "filepath", ",", "'w'", ")", ",", "default_flow_style", "=", "False", ")" ]
Save YAML settings to the specified file path.
[ "Save", "YAML", "settings", "to", "the", "specified", "file", "path", "." ]
ddd7df2ca995ddf191b24c4d35e9dd28186e4535
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/helpers.py#L13-L17
train
45,648
KyleJamesWalker/yamlsettings
yamlsettings/helpers.py
update_from_file
def update_from_file(yaml_dict, filepaths): ''' Override YAML settings with loaded values from filepaths. - File paths in the list gets the priority by their orders of the list. ''' # load YAML settings with only fields in yaml_dict yaml_dict.update(registry.load(filepaths, list(yaml_dict)))
python
def update_from_file(yaml_dict, filepaths): ''' Override YAML settings with loaded values from filepaths. - File paths in the list gets the priority by their orders of the list. ''' # load YAML settings with only fields in yaml_dict yaml_dict.update(registry.load(filepaths, list(yaml_dict)))
[ "def", "update_from_file", "(", "yaml_dict", ",", "filepaths", ")", ":", "# load YAML settings with only fields in yaml_dict", "yaml_dict", ".", "update", "(", "registry", ".", "load", "(", "filepaths", ",", "list", "(", "yaml_dict", ")", ")", ")" ]
Override YAML settings with loaded values from filepaths. - File paths in the list gets the priority by their orders of the list.
[ "Override", "YAML", "settings", "with", "loaded", "values", "from", "filepaths", "." ]
ddd7df2ca995ddf191b24c4d35e9dd28186e4535
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/helpers.py#L28-L35
train
45,649
KyleJamesWalker/yamlsettings
yamlsettings/helpers.py
update_from_env
def update_from_env(yaml_dict, prefix=None): ''' Override YAML settings with values from the environment variables. - The letter '_' is delimit the hierarchy of the YAML settings such that the value of 'config.databases.local' will be overridden by CONFIG_DATABASES_LOCAL. ''' prefix = prefix or "" def _set_env_var(path, node): env_path = "{0}{1}{2}".format( prefix.upper(), '_' if prefix else '', '_'.join([str(key).upper() for key in path]) ) env_val = os.environ.get(env_path, None) if env_val is not None: # convert the value to a YAML-defined type env_dict = yamldict.load('val: {0}'.format(env_val)) return env_dict.val else: return None # traverse yaml_dict with the callback function yaml_dict.traverse(_set_env_var)
python
def update_from_env(yaml_dict, prefix=None): ''' Override YAML settings with values from the environment variables. - The letter '_' is delimit the hierarchy of the YAML settings such that the value of 'config.databases.local' will be overridden by CONFIG_DATABASES_LOCAL. ''' prefix = prefix or "" def _set_env_var(path, node): env_path = "{0}{1}{2}".format( prefix.upper(), '_' if prefix else '', '_'.join([str(key).upper() for key in path]) ) env_val = os.environ.get(env_path, None) if env_val is not None: # convert the value to a YAML-defined type env_dict = yamldict.load('val: {0}'.format(env_val)) return env_dict.val else: return None # traverse yaml_dict with the callback function yaml_dict.traverse(_set_env_var)
[ "def", "update_from_env", "(", "yaml_dict", ",", "prefix", "=", "None", ")", ":", "prefix", "=", "prefix", "or", "\"\"", "def", "_set_env_var", "(", "path", ",", "node", ")", ":", "env_path", "=", "\"{0}{1}{2}\"", ".", "format", "(", "prefix", ".", "uppe...
Override YAML settings with values from the environment variables. - The letter '_' is delimit the hierarchy of the YAML settings such that the value of 'config.databases.local' will be overridden by CONFIG_DATABASES_LOCAL.
[ "Override", "YAML", "settings", "with", "values", "from", "the", "environment", "variables", "." ]
ddd7df2ca995ddf191b24c4d35e9dd28186e4535
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/helpers.py#L38-L63
train
45,650
undertherain/pycontextfree
contextfree/shapes.py
circle
def circle(rad=0.5): """Draw a circle""" _ctx = _state["ctx"] _ctx.arc(0, 0, rad, 0, 2 * math.pi) _ctx.set_line_width(0) _ctx.stroke_preserve() # _ctx.set_source_rgb(0.3, 0.4, 0.6) _ctx.fill()
python
def circle(rad=0.5): """Draw a circle""" _ctx = _state["ctx"] _ctx.arc(0, 0, rad, 0, 2 * math.pi) _ctx.set_line_width(0) _ctx.stroke_preserve() # _ctx.set_source_rgb(0.3, 0.4, 0.6) _ctx.fill()
[ "def", "circle", "(", "rad", "=", "0.5", ")", ":", "_ctx", "=", "_state", "[", "\"ctx\"", "]", "_ctx", ".", "arc", "(", "0", ",", "0", ",", "rad", ",", "0", ",", "2", "*", "math", ".", "pi", ")", "_ctx", ".", "set_line_width", "(", "0", ")", ...
Draw a circle
[ "Draw", "a", "circle" ]
91505e978f6034863747c98d919ac11b029b1ac3
https://github.com/undertherain/pycontextfree/blob/91505e978f6034863747c98d919ac11b029b1ac3/contextfree/shapes.py#L7-L14
train
45,651
undertherain/pycontextfree
contextfree/shapes.py
triangle
def triangle(rad=0.5): """Draw a triangle""" # half_height = math.sqrt(3) * side / 6 # half_height = side / 2 ctx = _state["ctx"] side = 3 * rad / math.sqrt(3) ctx.move_to(0, -rad / 2) ctx.line_to(-side / 2, -rad / 2) ctx.line_to(0, rad) ctx.line_to(side / 2, -rad / 2) ctx.close_path() ctx.fill()
python
def triangle(rad=0.5): """Draw a triangle""" # half_height = math.sqrt(3) * side / 6 # half_height = side / 2 ctx = _state["ctx"] side = 3 * rad / math.sqrt(3) ctx.move_to(0, -rad / 2) ctx.line_to(-side / 2, -rad / 2) ctx.line_to(0, rad) ctx.line_to(side / 2, -rad / 2) ctx.close_path() ctx.fill()
[ "def", "triangle", "(", "rad", "=", "0.5", ")", ":", "# half_height = math.sqrt(3) * side / 6", "# half_height = side / 2", "ctx", "=", "_state", "[", "\"ctx\"", "]", "side", "=", "3", "*", "rad", "/", "math", ".", "sqrt", "(", "3", ")", "ctx", ".", "move_...
Draw a triangle
[ "Draw", "a", "triangle" ]
91505e978f6034863747c98d919ac11b029b1ac3
https://github.com/undertherain/pycontextfree/blob/91505e978f6034863747c98d919ac11b029b1ac3/contextfree/shapes.py#L28-L39
train
45,652
undertherain/pycontextfree
contextfree/shapes.py
box
def box(side=1): """Draw a box""" half_side = side / 2 _state["ctx"].rectangle(-half_side, -half_side, side, side) _state["ctx"].fill()
python
def box(side=1): """Draw a box""" half_side = side / 2 _state["ctx"].rectangle(-half_side, -half_side, side, side) _state["ctx"].fill()
[ "def", "box", "(", "side", "=", "1", ")", ":", "half_side", "=", "side", "/", "2", "_state", "[", "\"ctx\"", "]", ".", "rectangle", "(", "-", "half_side", ",", "-", "half_side", ",", "side", ",", "side", ")", "_state", "[", "\"ctx\"", "]", ".", "...
Draw a box
[ "Draw", "a", "box" ]
91505e978f6034863747c98d919ac11b029b1ac3
https://github.com/undertherain/pycontextfree/blob/91505e978f6034863747c98d919ac11b029b1ac3/contextfree/shapes.py#L42-L46
train
45,653
JarryShaw/DictDumper
src/dumper.py
Dumper._dump_header
def _dump_header(self): """Initially dump file heads and tails.""" with open(self._file, 'w') as _file: _file.write(self._hsrt) self._sptr = _file.tell() _file.write(self._hend)
python
def _dump_header(self): """Initially dump file heads and tails.""" with open(self._file, 'w') as _file: _file.write(self._hsrt) self._sptr = _file.tell() _file.write(self._hend)
[ "def", "_dump_header", "(", "self", ")", ":", "with", "open", "(", "self", ".", "_file", ",", "'w'", ")", "as", "_file", ":", "_file", ".", "write", "(", "self", ".", "_hsrt", ")", "self", ".", "_sptr", "=", "_file", ".", "tell", "(", ")", "_file...
Initially dump file heads and tails.
[ "Initially", "dump", "file", "heads", "and", "tails", "." ]
430efcfdff18bb2421c3f27059ff94c93e621483
https://github.com/JarryShaw/DictDumper/blob/430efcfdff18bb2421c3f27059ff94c93e621483/src/dumper.py#L116-L121
train
45,654
undertherain/pycontextfree
setup_boilerplate.py
find_version
def find_version( package_name: str, version_module_name: str = '_version', version_variable_name: str = 'VERSION') -> str: """Simulate behaviour of "from package_name._version import VERSION", and return VERSION.""" version_module = importlib.import_module( '{}.{}'.format(package_name.replace('-', '_'), version_module_name)) return getattr(version_module, version_variable_name)
python
def find_version( package_name: str, version_module_name: str = '_version', version_variable_name: str = 'VERSION') -> str: """Simulate behaviour of "from package_name._version import VERSION", and return VERSION.""" version_module = importlib.import_module( '{}.{}'.format(package_name.replace('-', '_'), version_module_name)) return getattr(version_module, version_variable_name)
[ "def", "find_version", "(", "package_name", ":", "str", ",", "version_module_name", ":", "str", "=", "'_version'", ",", "version_variable_name", ":", "str", "=", "'VERSION'", ")", "->", "str", ":", "version_module", "=", "importlib", ".", "import_module", "(", ...
Simulate behaviour of "from package_name._version import VERSION", and return VERSION.
[ "Simulate", "behaviour", "of", "from", "package_name", ".", "_version", "import", "VERSION", "and", "return", "VERSION", "." ]
91505e978f6034863747c98d919ac11b029b1ac3
https://github.com/undertherain/pycontextfree/blob/91505e978f6034863747c98d919ac11b029b1ac3/setup_boilerplate.py#L50-L56
train
45,655
undertherain/pycontextfree
setup_boilerplate.py
find_packages
def find_packages(root_directory: str = '.') -> t.List[str]: """Find packages to pack.""" exclude = ['test*', 'test.*'] if ('bdist_wheel' in sys.argv or 'bdist' in sys.argv) else [] packages_list = setuptools.find_packages(root_directory, exclude=exclude) return packages_list
python
def find_packages(root_directory: str = '.') -> t.List[str]: """Find packages to pack.""" exclude = ['test*', 'test.*'] if ('bdist_wheel' in sys.argv or 'bdist' in sys.argv) else [] packages_list = setuptools.find_packages(root_directory, exclude=exclude) return packages_list
[ "def", "find_packages", "(", "root_directory", ":", "str", "=", "'.'", ")", "->", "t", ".", "List", "[", "str", "]", ":", "exclude", "=", "[", "'test*'", ",", "'test.*'", "]", "if", "(", "'bdist_wheel'", "in", "sys", ".", "argv", "or", "'bdist'", "in...
Find packages to pack.
[ "Find", "packages", "to", "pack", "." ]
91505e978f6034863747c98d919ac11b029b1ac3
https://github.com/undertherain/pycontextfree/blob/91505e978f6034863747c98d919ac11b029b1ac3/setup_boilerplate.py#L59-L63
train
45,656
undertherain/pycontextfree
setup_boilerplate.py
parse_requirements
def parse_requirements( requirements_path: str = 'requirements.txt') -> t.List[str]: """Read contents of requirements.txt file and return data from its relevant lines. Only non-empty and non-comment lines are relevant. """ requirements = [] with HERE.joinpath(requirements_path).open() as reqs_file: for requirement in [line.strip() for line in reqs_file.read().splitlines()]: if not requirement or requirement.startswith('#'): continue requirements.append(requirement) return requirements
python
def parse_requirements( requirements_path: str = 'requirements.txt') -> t.List[str]: """Read contents of requirements.txt file and return data from its relevant lines. Only non-empty and non-comment lines are relevant. """ requirements = [] with HERE.joinpath(requirements_path).open() as reqs_file: for requirement in [line.strip() for line in reqs_file.read().splitlines()]: if not requirement or requirement.startswith('#'): continue requirements.append(requirement) return requirements
[ "def", "parse_requirements", "(", "requirements_path", ":", "str", "=", "'requirements.txt'", ")", "->", "t", ".", "List", "[", "str", "]", ":", "requirements", "=", "[", "]", "with", "HERE", ".", "joinpath", "(", "requirements_path", ")", ".", "open", "("...
Read contents of requirements.txt file and return data from its relevant lines. Only non-empty and non-comment lines are relevant.
[ "Read", "contents", "of", "requirements", ".", "txt", "file", "and", "return", "data", "from", "its", "relevant", "lines", "." ]
91505e978f6034863747c98d919ac11b029b1ac3
https://github.com/undertherain/pycontextfree/blob/91505e978f6034863747c98d919ac11b029b1ac3/setup_boilerplate.py#L66-L78
train
45,657
undertherain/pycontextfree
setup_boilerplate.py
partition_version_classifiers
def partition_version_classifiers( classifiers: t.Sequence[str], version_prefix: str = 'Programming Language :: Python :: ', only_suffix: str = ' :: Only') -> t.Tuple[t.List[str], t.List[str]]: """Find version number classifiers in given list and partition them into 2 groups.""" versions_min, versions_only = [], [] for classifier in classifiers: version = classifier.replace(version_prefix, '') versions = versions_min if version.endswith(only_suffix): version = version.replace(only_suffix, '') versions = versions_only try: versions.append(tuple([int(_) for _ in version.split('.')])) except ValueError: pass return versions_min, versions_only
python
def partition_version_classifiers( classifiers: t.Sequence[str], version_prefix: str = 'Programming Language :: Python :: ', only_suffix: str = ' :: Only') -> t.Tuple[t.List[str], t.List[str]]: """Find version number classifiers in given list and partition them into 2 groups.""" versions_min, versions_only = [], [] for classifier in classifiers: version = classifier.replace(version_prefix, '') versions = versions_min if version.endswith(only_suffix): version = version.replace(only_suffix, '') versions = versions_only try: versions.append(tuple([int(_) for _ in version.split('.')])) except ValueError: pass return versions_min, versions_only
[ "def", "partition_version_classifiers", "(", "classifiers", ":", "t", ".", "Sequence", "[", "str", "]", ",", "version_prefix", ":", "str", "=", "'Programming Language :: Python :: '", ",", "only_suffix", ":", "str", "=", "' :: Only'", ")", "->", "t", ".", "Tuple...
Find version number classifiers in given list and partition them into 2 groups.
[ "Find", "version", "number", "classifiers", "in", "given", "list", "and", "partition", "them", "into", "2", "groups", "." ]
91505e978f6034863747c98d919ac11b029b1ac3
https://github.com/undertherain/pycontextfree/blob/91505e978f6034863747c98d919ac11b029b1ac3/setup_boilerplate.py#L81-L96
train
45,658
undertherain/pycontextfree
setup_boilerplate.py
find_required_python_version
def find_required_python_version( classifiers: t.Sequence[str], version_prefix: str = 'Programming Language :: Python :: ', only_suffix: str = ' :: Only') -> t.Optional[str]: """Determine the minimum required Python version.""" versions_min, versions_only = partition_version_classifiers( classifiers, version_prefix, only_suffix) if len(versions_only) > 1: raise ValueError( 'more than one "{}" version encountered in {}'.format(only_suffix, versions_only)) only_version = None if len(versions_only) == 1: only_version = versions_only[0] for version in versions_min: if version[:len(only_version)] != only_version: raise ValueError( 'the "{}" version {} is inconsistent with version {}' .format(only_suffix, only_version, version)) min_supported_version = None for version in versions_min: if min_supported_version is None or \ (len(version) >= len(min_supported_version) and version < min_supported_version): min_supported_version = version if min_supported_version is None: if only_version is not None: return '.'.join([str(_) for _ in only_version]) else: return '>=' + '.'.join([str(_) for _ in min_supported_version]) return None
python
def find_required_python_version( classifiers: t.Sequence[str], version_prefix: str = 'Programming Language :: Python :: ', only_suffix: str = ' :: Only') -> t.Optional[str]: """Determine the minimum required Python version.""" versions_min, versions_only = partition_version_classifiers( classifiers, version_prefix, only_suffix) if len(versions_only) > 1: raise ValueError( 'more than one "{}" version encountered in {}'.format(only_suffix, versions_only)) only_version = None if len(versions_only) == 1: only_version = versions_only[0] for version in versions_min: if version[:len(only_version)] != only_version: raise ValueError( 'the "{}" version {} is inconsistent with version {}' .format(only_suffix, only_version, version)) min_supported_version = None for version in versions_min: if min_supported_version is None or \ (len(version) >= len(min_supported_version) and version < min_supported_version): min_supported_version = version if min_supported_version is None: if only_version is not None: return '.'.join([str(_) for _ in only_version]) else: return '>=' + '.'.join([str(_) for _ in min_supported_version]) return None
[ "def", "find_required_python_version", "(", "classifiers", ":", "t", ".", "Sequence", "[", "str", "]", ",", "version_prefix", ":", "str", "=", "'Programming Language :: Python :: '", ",", "only_suffix", ":", "str", "=", "' :: Only'", ")", "->", "t", ".", "Option...
Determine the minimum required Python version.
[ "Determine", "the", "minimum", "required", "Python", "version", "." ]
91505e978f6034863747c98d919ac11b029b1ac3
https://github.com/undertherain/pycontextfree/blob/91505e978f6034863747c98d919ac11b029b1ac3/setup_boilerplate.py#L99-L126
train
45,659
undertherain/pycontextfree
setup_boilerplate.py
parse_rst
def parse_rst(text: str) -> docutils.nodes.document: """Parse text assuming it's an RST markup.""" parser = docutils.parsers.rst.Parser() components = (docutils.parsers.rst.Parser,) settings = docutils.frontend.OptionParser(components=components).get_default_values() document = docutils.utils.new_document('<rst-doc>', settings=settings) parser.parse(text, document) return document
python
def parse_rst(text: str) -> docutils.nodes.document: """Parse text assuming it's an RST markup.""" parser = docutils.parsers.rst.Parser() components = (docutils.parsers.rst.Parser,) settings = docutils.frontend.OptionParser(components=components).get_default_values() document = docutils.utils.new_document('<rst-doc>', settings=settings) parser.parse(text, document) return document
[ "def", "parse_rst", "(", "text", ":", "str", ")", "->", "docutils", ".", "nodes", ".", "document", ":", "parser", "=", "docutils", ".", "parsers", ".", "rst", ".", "Parser", "(", ")", "components", "=", "(", "docutils", ".", "parsers", ".", "rst", "....
Parse text assuming it's an RST markup.
[ "Parse", "text", "assuming", "it", "s", "an", "RST", "markup", "." ]
91505e978f6034863747c98d919ac11b029b1ac3
https://github.com/undertherain/pycontextfree/blob/91505e978f6034863747c98d919ac11b029b1ac3/setup_boilerplate.py#L129-L136
train
45,660
undertherain/pycontextfree
setup_boilerplate.py
resolve_relative_rst_links
def resolve_relative_rst_links(text: str, base_link: str): """Resolve all relative links in a given RST document. All links of form `link`_ become `link <base_link/link>`_. """ document = parse_rst(text) visitor = SimpleRefCounter(document) document.walk(visitor) for target in visitor.references: name = target.attributes['name'] uri = target.attributes['refuri'] new_link = '`{} <{}{}>`_'.format(name, base_link, uri) if name == uri: text = text.replace('`<{}>`_'.format(uri), new_link) else: text = text.replace('`{} <{}>`_'.format(name, uri), new_link) return text
python
def resolve_relative_rst_links(text: str, base_link: str): """Resolve all relative links in a given RST document. All links of form `link`_ become `link <base_link/link>`_. """ document = parse_rst(text) visitor = SimpleRefCounter(document) document.walk(visitor) for target in visitor.references: name = target.attributes['name'] uri = target.attributes['refuri'] new_link = '`{} <{}{}>`_'.format(name, base_link, uri) if name == uri: text = text.replace('`<{}>`_'.format(uri), new_link) else: text = text.replace('`{} <{}>`_'.format(name, uri), new_link) return text
[ "def", "resolve_relative_rst_links", "(", "text", ":", "str", ",", "base_link", ":", "str", ")", ":", "document", "=", "parse_rst", "(", "text", ")", "visitor", "=", "SimpleRefCounter", "(", "document", ")", "document", ".", "walk", "(", "visitor", ")", "f...
Resolve all relative links in a given RST document. All links of form `link`_ become `link <base_link/link>`_.
[ "Resolve", "all", "relative", "links", "in", "a", "given", "RST", "document", "." ]
91505e978f6034863747c98d919ac11b029b1ac3
https://github.com/undertherain/pycontextfree/blob/91505e978f6034863747c98d919ac11b029b1ac3/setup_boilerplate.py#L175-L191
train
45,661
undertherain/pycontextfree
setup_boilerplate.py
SimpleRefCounter.visit_reference
def visit_reference(self, node: docutils.nodes.reference) -> None: """Called for "reference" nodes.""" # if len(node.children) != 1 or not isinstance(node.children[0], docutils.nodes.Text) \ # or not all(_ in node.attributes for _ in ('name', 'refuri')): # return path = pathlib.Path(node.attributes['refuri']) try: if path.is_absolute(): return resolved_path = path.resolve() except FileNotFoundError: # in resolve(), prior to Python 3.6 return # except OSError: # in is_absolute() and resolve(), on URLs in Windows # return try: resolved_path.relative_to(HERE) except ValueError: return if not path.is_file(): return assert node.attributes['name'] == node.children[0].astext() self.references.append(node)
python
def visit_reference(self, node: docutils.nodes.reference) -> None: """Called for "reference" nodes.""" # if len(node.children) != 1 or not isinstance(node.children[0], docutils.nodes.Text) \ # or not all(_ in node.attributes for _ in ('name', 'refuri')): # return path = pathlib.Path(node.attributes['refuri']) try: if path.is_absolute(): return resolved_path = path.resolve() except FileNotFoundError: # in resolve(), prior to Python 3.6 return # except OSError: # in is_absolute() and resolve(), on URLs in Windows # return try: resolved_path.relative_to(HERE) except ValueError: return if not path.is_file(): return assert node.attributes['name'] == node.children[0].astext() self.references.append(node)
[ "def", "visit_reference", "(", "self", ",", "node", ":", "docutils", ".", "nodes", ".", "reference", ")", "->", "None", ":", "# if len(node.children) != 1 or not isinstance(node.children[0], docutils.nodes.Text) \\", "# or not all(_ in node.attributes for _ in ('name', 'ref...
Called for "reference" nodes.
[ "Called", "for", "reference", "nodes", "." ]
91505e978f6034863747c98d919ac11b029b1ac3
https://github.com/undertherain/pycontextfree/blob/91505e978f6034863747c98d919ac11b029b1ac3/setup_boilerplate.py#L147-L168
train
45,662
undertherain/pycontextfree
setup_boilerplate.py
Package.try_fields
def try_fields(cls, *names) -> t.Optional[t.Any]: """Return first existing of given class field names.""" for name in names: if hasattr(cls, name): return getattr(cls, name) raise AttributeError((cls, names))
python
def try_fields(cls, *names) -> t.Optional[t.Any]: """Return first existing of given class field names.""" for name in names: if hasattr(cls, name): return getattr(cls, name) raise AttributeError((cls, names))
[ "def", "try_fields", "(", "cls", ",", "*", "names", ")", "->", "t", ".", "Optional", "[", "t", ".", "Any", "]", ":", "for", "name", "in", "names", ":", "if", "hasattr", "(", "cls", ",", "name", ")", ":", "return", "getattr", "(", "cls", ",", "n...
Return first existing of given class field names.
[ "Return", "first", "existing", "of", "given", "class", "field", "names", "." ]
91505e978f6034863747c98d919ac11b029b1ac3
https://github.com/undertherain/pycontextfree/blob/91505e978f6034863747c98d919ac11b029b1ac3/setup_boilerplate.py#L249-L254
train
45,663
undertherain/pycontextfree
setup_boilerplate.py
Package.parse_readme
def parse_readme(cls, readme_path: str = 'README.rst', encoding: str = 'utf-8') -> str: """Parse readme and resolve relative links in it if it is feasible. Links are resolved if readme is in rst format and the package is hosted on GitHub. """ with HERE.joinpath(readme_path).open(encoding=encoding) as readme_file: long_description = readme_file.read() # type: str if readme_path.endswith('.rst') and cls.download_url.startswith('https://github.com/'): base_url = '{}/blob/v{}/'.format(cls.download_url, cls.version) long_description = resolve_relative_rst_links(long_description, base_url) return long_description
python
def parse_readme(cls, readme_path: str = 'README.rst', encoding: str = 'utf-8') -> str: """Parse readme and resolve relative links in it if it is feasible. Links are resolved if readme is in rst format and the package is hosted on GitHub. """ with HERE.joinpath(readme_path).open(encoding=encoding) as readme_file: long_description = readme_file.read() # type: str if readme_path.endswith('.rst') and cls.download_url.startswith('https://github.com/'): base_url = '{}/blob/v{}/'.format(cls.download_url, cls.version) long_description = resolve_relative_rst_links(long_description, base_url) return long_description
[ "def", "parse_readme", "(", "cls", ",", "readme_path", ":", "str", "=", "'README.rst'", ",", "encoding", ":", "str", "=", "'utf-8'", ")", "->", "str", ":", "with", "HERE", ".", "joinpath", "(", "readme_path", ")", ".", "open", "(", "encoding", "=", "en...
Parse readme and resolve relative links in it if it is feasible. Links are resolved if readme is in rst format and the package is hosted on GitHub.
[ "Parse", "readme", "and", "resolve", "relative", "links", "in", "it", "if", "it", "is", "feasible", "." ]
91505e978f6034863747c98d919ac11b029b1ac3
https://github.com/undertherain/pycontextfree/blob/91505e978f6034863747c98d919ac11b029b1ac3/setup_boilerplate.py#L257-L269
train
45,664
undertherain/pycontextfree
setup_boilerplate.py
Package.prepare
def prepare(cls) -> None: """Fill in possibly missing package metadata.""" if cls.version is None: cls.version = find_version(cls.name) if cls.long_description is None: cls.long_description = cls.parse_readme() if cls.packages is None: cls.packages = find_packages(cls.root_directory) if cls.install_requires is None: cls.install_requires = parse_requirements() if cls.python_requires is None: cls.python_requires = find_required_python_version(cls.classifiers)
python
def prepare(cls) -> None: """Fill in possibly missing package metadata.""" if cls.version is None: cls.version = find_version(cls.name) if cls.long_description is None: cls.long_description = cls.parse_readme() if cls.packages is None: cls.packages = find_packages(cls.root_directory) if cls.install_requires is None: cls.install_requires = parse_requirements() if cls.python_requires is None: cls.python_requires = find_required_python_version(cls.classifiers)
[ "def", "prepare", "(", "cls", ")", "->", "None", ":", "if", "cls", ".", "version", "is", "None", ":", "cls", ".", "version", "=", "find_version", "(", "cls", ".", "name", ")", "if", "cls", ".", "long_description", "is", "None", ":", "cls", ".", "lo...
Fill in possibly missing package metadata.
[ "Fill", "in", "possibly", "missing", "package", "metadata", "." ]
91505e978f6034863747c98d919ac11b029b1ac3
https://github.com/undertherain/pycontextfree/blob/91505e978f6034863747c98d919ac11b029b1ac3/setup_boilerplate.py#L272-L283
train
45,665
undertherain/pycontextfree
contextfree/core.py
surface_to_image
def surface_to_image(surface): """Renders current buffer surface to IPython image""" from IPython.display import Image buf = BytesIO() surface.write_to_png(buf) data = buf.getvalue() buf.close() return Image(data=data)
python
def surface_to_image(surface): """Renders current buffer surface to IPython image""" from IPython.display import Image buf = BytesIO() surface.write_to_png(buf) data = buf.getvalue() buf.close() return Image(data=data)
[ "def", "surface_to_image", "(", "surface", ")", ":", "from", "IPython", ".", "display", "import", "Image", "buf", "=", "BytesIO", "(", ")", "surface", ".", "write_to_png", "(", "buf", ")", "data", "=", "buf", ".", "getvalue", "(", ")", "buf", ".", "clo...
Renders current buffer surface to IPython image
[ "Renders", "current", "buffer", "surface", "to", "IPython", "image" ]
91505e978f6034863747c98d919ac11b029b1ac3
https://github.com/undertherain/pycontextfree/blob/91505e978f6034863747c98d919ac11b029b1ac3/contextfree/core.py#L34-L41
train
45,666
undertherain/pycontextfree
contextfree/core.py
check_limits
def check_limits(user_rule): """Stop recursion if resolution is too low on number of components is too high """ def wrapper(*args, **kwargs): """The body of the decorator """ global _state _state["cnt_elements"] += 1 _state["depth"] += 1 matrix = _state["ctx"].get_matrix() # TODO: add check of transparency = 0 if _state["depth"] >= MAX_DEPTH: logger.info("stop recursion by reaching max depth {}".format(MAX_DEPTH)) else: min_size_scaled = SIZE_MIN_FEATURE / min(WIDTH, HEIGHT) current_scale = max([abs(matrix[i]) for i in range(2)]) if (current_scale < min_size_scaled): logger.info("stop recursion by reaching min feature size") # TODO: check feature size with respect to current ink size else: if _state["cnt_elements"] > MAX_ELEMENTS: logger.info("stop recursion by reaching max elements") else: user_rule(*args, **kwargs) _state["depth"] -= 1 return wrapper
python
def check_limits(user_rule): """Stop recursion if resolution is too low on number of components is too high """ def wrapper(*args, **kwargs): """The body of the decorator """ global _state _state["cnt_elements"] += 1 _state["depth"] += 1 matrix = _state["ctx"].get_matrix() # TODO: add check of transparency = 0 if _state["depth"] >= MAX_DEPTH: logger.info("stop recursion by reaching max depth {}".format(MAX_DEPTH)) else: min_size_scaled = SIZE_MIN_FEATURE / min(WIDTH, HEIGHT) current_scale = max([abs(matrix[i]) for i in range(2)]) if (current_scale < min_size_scaled): logger.info("stop recursion by reaching min feature size") # TODO: check feature size with respect to current ink size else: if _state["cnt_elements"] > MAX_ELEMENTS: logger.info("stop recursion by reaching max elements") else: user_rule(*args, **kwargs) _state["depth"] -= 1 return wrapper
[ "def", "check_limits", "(", "user_rule", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"The body of the decorator \"\"\"", "global", "_state", "_state", "[", "\"cnt_elements\"", "]", "+=", "1", "_state", "[", "\"depth\"...
Stop recursion if resolution is too low on number of components is too high
[ "Stop", "recursion", "if", "resolution", "is", "too", "low", "on", "number", "of", "components", "is", "too", "high" ]
91505e978f6034863747c98d919ac11b029b1ac3
https://github.com/undertherain/pycontextfree/blob/91505e978f6034863747c98d919ac11b029b1ac3/contextfree/core.py#L100-L124
train
45,667
undertherain/pycontextfree
contextfree/core.py
init
def init(canvas_size=(512, 512), max_depth=12, face_color=None, background_color=None): """Initializes global state""" global _background_color _background_color = background_color global _ctx global cnt_elements global MAX_DEPTH global WIDTH global HEIGHT _init_state() sys.setrecursionlimit(20000) MAX_DEPTH = max_depth WIDTH, HEIGHT = canvas_size if face_color is not None: r, g, b = htmlcolor_to_rgb(face_color) _state["ctx"].set_source_rgb(r, g, b) hue, saturation, brightness = colorsys.rgb_to_hsv(r, g, b) _state["color"] = (hue, saturation, brightness, 1) logger.debug("Init done")
python
def init(canvas_size=(512, 512), max_depth=12, face_color=None, background_color=None): """Initializes global state""" global _background_color _background_color = background_color global _ctx global cnt_elements global MAX_DEPTH global WIDTH global HEIGHT _init_state() sys.setrecursionlimit(20000) MAX_DEPTH = max_depth WIDTH, HEIGHT = canvas_size if face_color is not None: r, g, b = htmlcolor_to_rgb(face_color) _state["ctx"].set_source_rgb(r, g, b) hue, saturation, brightness = colorsys.rgb_to_hsv(r, g, b) _state["color"] = (hue, saturation, brightness, 1) logger.debug("Init done")
[ "def", "init", "(", "canvas_size", "=", "(", "512", ",", "512", ")", ",", "max_depth", "=", "12", ",", "face_color", "=", "None", ",", "background_color", "=", "None", ")", ":", "global", "_background_color", "_background_color", "=", "background_color", "gl...
Initializes global state
[ "Initializes", "global", "state" ]
91505e978f6034863747c98d919ac11b029b1ac3
https://github.com/undertherain/pycontextfree/blob/91505e978f6034863747c98d919ac11b029b1ac3/contextfree/core.py#L164-L184
train
45,668
undertherain/pycontextfree
contextfree/core.py
htmlcolor_to_rgb
def htmlcolor_to_rgb(str_color): """function to convert HTML-styly color string to RGB values Args: s: Color in HTML format Returns: list of three RGB color components """ if not (str_color.startswith('#') and len(str_color) == 7): raise ValueError("Bad html color format. Expected: '#RRGGBB' ") result = [1.0 * int(n, 16) / 255 for n in (str_color[1:3], str_color[3:5], str_color[5:])] return result
python
def htmlcolor_to_rgb(str_color): """function to convert HTML-styly color string to RGB values Args: s: Color in HTML format Returns: list of three RGB color components """ if not (str_color.startswith('#') and len(str_color) == 7): raise ValueError("Bad html color format. Expected: '#RRGGBB' ") result = [1.0 * int(n, 16) / 255 for n in (str_color[1:3], str_color[3:5], str_color[5:])] return result
[ "def", "htmlcolor_to_rgb", "(", "str_color", ")", ":", "if", "not", "(", "str_color", ".", "startswith", "(", "'#'", ")", "and", "len", "(", "str_color", ")", "==", "7", ")", ":", "raise", "ValueError", "(", "\"Bad html color format. Expected: '#RRGGBB' \"", "...
function to convert HTML-styly color string to RGB values Args: s: Color in HTML format Returns: list of three RGB color components
[ "function", "to", "convert", "HTML", "-", "styly", "color", "string", "to", "RGB", "values" ]
91505e978f6034863747c98d919ac11b029b1ac3
https://github.com/undertherain/pycontextfree/blob/91505e978f6034863747c98d919ac11b029b1ac3/contextfree/core.py#L262-L274
train
45,669
undertherain/pycontextfree
site/plugins/pdoc/pdoc.py
CompilePdoc.compile_string
def compile_string(self, data, source_path=None, is_two_file=True, post=None, lang=None): """Compile docstrings into HTML strings, with shortcode support.""" if not is_two_file: _, data = self.split_metadata(data, None, lang) new_data, shortcodes = sc.extract_shortcodes(data) # The way pdoc generates output is a bit inflexible path_templates = os.path.join(self.plugin_path, "tempaltes") LOGGER.info(f"set path tempaltes to {path_templates}") with tempfile.TemporaryDirectory() as tmpdir: subprocess.check_call(['pdoc', '--html', '--html-no-source', '--html-dir', tmpdir, "--template-dir", path_templates] + shlex.split(new_data.strip())) fname = os.listdir(tmpdir)[0] tmd_subdir = os.path.join(tmpdir, fname) fname = os.listdir(tmd_subdir)[0] LOGGER.info(f"tmpdir = {tmd_subdir}, fname = {fname}") with open(os.path.join(tmd_subdir, fname), 'r', encoding='utf8') as inf: output = inf.read() return self.site.apply_shortcodes_uuid(output, shortcodes, filename=source_path, extra_context={'post': post})
python
def compile_string(self, data, source_path=None, is_two_file=True, post=None, lang=None): """Compile docstrings into HTML strings, with shortcode support.""" if not is_two_file: _, data = self.split_metadata(data, None, lang) new_data, shortcodes = sc.extract_shortcodes(data) # The way pdoc generates output is a bit inflexible path_templates = os.path.join(self.plugin_path, "tempaltes") LOGGER.info(f"set path tempaltes to {path_templates}") with tempfile.TemporaryDirectory() as tmpdir: subprocess.check_call(['pdoc', '--html', '--html-no-source', '--html-dir', tmpdir, "--template-dir", path_templates] + shlex.split(new_data.strip())) fname = os.listdir(tmpdir)[0] tmd_subdir = os.path.join(tmpdir, fname) fname = os.listdir(tmd_subdir)[0] LOGGER.info(f"tmpdir = {tmd_subdir}, fname = {fname}") with open(os.path.join(tmd_subdir, fname), 'r', encoding='utf8') as inf: output = inf.read() return self.site.apply_shortcodes_uuid(output, shortcodes, filename=source_path, extra_context={'post': post})
[ "def", "compile_string", "(", "self", ",", "data", ",", "source_path", "=", "None", ",", "is_two_file", "=", "True", ",", "post", "=", "None", ",", "lang", "=", "None", ")", ":", "if", "not", "is_two_file", ":", "_", ",", "data", "=", "self", ".", ...
Compile docstrings into HTML strings, with shortcode support.
[ "Compile", "docstrings", "into", "HTML", "strings", "with", "shortcode", "support", "." ]
91505e978f6034863747c98d919ac11b029b1ac3
https://github.com/undertherain/pycontextfree/blob/91505e978f6034863747c98d919ac11b029b1ac3/site/plugins/pdoc/pdoc.py#L58-L74
train
45,670
undertherain/pycontextfree
site/plugins/pdoc/pdoc.py
CompilePdoc.compile
def compile(self, source, dest, is_two_file=True, post=None, lang=None): """Compile the docstring into HTML and save as dest.""" makedirs(os.path.dirname(dest)) with io.open(dest, "w+", encoding="utf8") as out_file: with io.open(source, "r", encoding="utf8") as in_file: data = in_file.read() data, shortcode_deps = self.compile_string(data, source, is_two_file, post, lang) out_file.write(data) if post is None: if shortcode_deps: self.logger.error( "Cannot save dependencies for post {0} (post unknown)", source) else: post._depfile[dest] += shortcode_deps return True
python
def compile(self, source, dest, is_two_file=True, post=None, lang=None): """Compile the docstring into HTML and save as dest.""" makedirs(os.path.dirname(dest)) with io.open(dest, "w+", encoding="utf8") as out_file: with io.open(source, "r", encoding="utf8") as in_file: data = in_file.read() data, shortcode_deps = self.compile_string(data, source, is_two_file, post, lang) out_file.write(data) if post is None: if shortcode_deps: self.logger.error( "Cannot save dependencies for post {0} (post unknown)", source) else: post._depfile[dest] += shortcode_deps return True
[ "def", "compile", "(", "self", ",", "source", ",", "dest", ",", "is_two_file", "=", "True", ",", "post", "=", "None", ",", "lang", "=", "None", ")", ":", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "dest", ")", ")", "with", "io", "."...
Compile the docstring into HTML and save as dest.
[ "Compile", "the", "docstring", "into", "HTML", "and", "save", "as", "dest", "." ]
91505e978f6034863747c98d919ac11b029b1ac3
https://github.com/undertherain/pycontextfree/blob/91505e978f6034863747c98d919ac11b029b1ac3/site/plugins/pdoc/pdoc.py#L76-L91
train
45,671
undertherain/pycontextfree
site/plugins/pdoc/pdoc.py
CompilePdoc.create_post
def create_post(self, path, **kw): """Create a new post.""" content = kw.pop('content', None) onefile = kw.pop('onefile', False) # is_page is not used by create_post as of now. kw.pop('is_page', False) metadata = {} metadata.update(self.default_metadata) metadata.update(kw) makedirs(os.path.dirname(path)) if not content.endswith('\n'): content += '\n' with io.open(path, "w+", encoding="utf8") as fd: if onefile: fd.write(write_metadata(metadata, comment_wrap=False, site=self.site, compiler=self)) fd.write(content)
python
def create_post(self, path, **kw): """Create a new post.""" content = kw.pop('content', None) onefile = kw.pop('onefile', False) # is_page is not used by create_post as of now. kw.pop('is_page', False) metadata = {} metadata.update(self.default_metadata) metadata.update(kw) makedirs(os.path.dirname(path)) if not content.endswith('\n'): content += '\n' with io.open(path, "w+", encoding="utf8") as fd: if onefile: fd.write(write_metadata(metadata, comment_wrap=False, site=self.site, compiler=self)) fd.write(content)
[ "def", "create_post", "(", "self", ",", "path", ",", "*", "*", "kw", ")", ":", "content", "=", "kw", ".", "pop", "(", "'content'", ",", "None", ")", "onefile", "=", "kw", ".", "pop", "(", "'onefile'", ",", "False", ")", "# is_page is not used by create...
Create a new post.
[ "Create", "a", "new", "post", "." ]
91505e978f6034863747c98d919ac11b029b1ac3
https://github.com/undertherain/pycontextfree/blob/91505e978f6034863747c98d919ac11b029b1ac3/site/plugins/pdoc/pdoc.py#L93-L108
train
45,672
JarryShaw/DictDumper
src/tree.py
Tree._append_branch
def _append_branch(self, value, _file): """Call this function to write branch contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file """ if not value: return # return self._append_none(None, _file) self._tctr += 1 _vlen = len(value) for (_vctr, (_item, _text)) in enumerate(value.items()): _text = self.object_hook(_text) _type = type(_text).__name__ flag_dict = (_type == 'dict') flag_list = (_type == 'list' and (len(_text) > 1 or (len(_text) == 1 and type(_text[0]).__name__ == 'dict'))) # noqa pylint: disable=line-too-long flag_tuple = (_type == 'tuple' and (len(_text) > 1 or (len(_text) == 1 and type(_text[0]).__name__ == 'dict'))) # noqa pylint: disable=line-too-long flag_bytes = (_type == 'bytes' and len(_text) > 16) if any((flag_dict, flag_list, flag_tuple, flag_bytes)): _pref = '\n' else: _pref = ' ->' _labs = '' for _ in range(self._tctr): _labs += _TEMP_SPACES if self._bctr[_] else _TEMP_BRANCH _keys = '{labs} |-- {item}{pref}'.format(labs=_labs, item=_item, pref=_pref) _file.write(_keys) if _vctr == _vlen - 1: self._bctr[self._tctr] = 1 _MAGIC_TYPES[_type](self, _text, _file) _suff = '' if _type == 'dict' else '\n' _file.write(_suff) self._bctr[self._tctr] = 0 self._tctr -= 1
python
def _append_branch(self, value, _file): """Call this function to write branch contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file """ if not value: return # return self._append_none(None, _file) self._tctr += 1 _vlen = len(value) for (_vctr, (_item, _text)) in enumerate(value.items()): _text = self.object_hook(_text) _type = type(_text).__name__ flag_dict = (_type == 'dict') flag_list = (_type == 'list' and (len(_text) > 1 or (len(_text) == 1 and type(_text[0]).__name__ == 'dict'))) # noqa pylint: disable=line-too-long flag_tuple = (_type == 'tuple' and (len(_text) > 1 or (len(_text) == 1 and type(_text[0]).__name__ == 'dict'))) # noqa pylint: disable=line-too-long flag_bytes = (_type == 'bytes' and len(_text) > 16) if any((flag_dict, flag_list, flag_tuple, flag_bytes)): _pref = '\n' else: _pref = ' ->' _labs = '' for _ in range(self._tctr): _labs += _TEMP_SPACES if self._bctr[_] else _TEMP_BRANCH _keys = '{labs} |-- {item}{pref}'.format(labs=_labs, item=_item, pref=_pref) _file.write(_keys) if _vctr == _vlen - 1: self._bctr[self._tctr] = 1 _MAGIC_TYPES[_type](self, _text, _file) _suff = '' if _type == 'dict' else '\n' _file.write(_suff) self._bctr[self._tctr] = 0 self._tctr -= 1
[ "def", "_append_branch", "(", "self", ",", "value", ",", "_file", ")", ":", "if", "not", "value", ":", "return", "# return self._append_none(None, _file)", "self", ".", "_tctr", "+=", "1", "_vlen", "=", "len", "(", "value", ")", "for", "(", "_vctr", ",", ...
Call this function to write branch contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
[ "Call", "this", "function", "to", "write", "branch", "contents", "." ]
430efcfdff18bb2421c3f27059ff94c93e621483
https://github.com/JarryShaw/DictDumper/blob/430efcfdff18bb2421c3f27059ff94c93e621483/src/tree.py#L221-L264
train
45,673
JarryShaw/DictDumper
src/tree.py
Tree._append_number
def _append_number(self, value, _file): # pylint: disable=no-self-use """Call this function to write number contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file """ _text = value _labs = ' {text}'.format(text=_text) _file.write(_labs)
python
def _append_number(self, value, _file): # pylint: disable=no-self-use """Call this function to write number contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file """ _text = value _labs = ' {text}'.format(text=_text) _file.write(_labs)
[ "def", "_append_number", "(", "self", ",", "value", ",", "_file", ")", ":", "# pylint: disable=no-self-use", "_text", "=", "value", "_labs", "=", "' {text}'", ".", "format", "(", "text", "=", "_text", ")", "_file", ".", "write", "(", "_labs", ")" ]
Call this function to write number contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
[ "Call", "this", "function", "to", "write", "number", "contents", "." ]
430efcfdff18bb2421c3f27059ff94c93e621483
https://github.com/JarryShaw/DictDumper/blob/430efcfdff18bb2421c3f27059ff94c93e621483/src/tree.py#L325-L335
train
45,674
JarryShaw/DictDumper
src/json.py
JSON._append_object
def _append_object(self, value, _file): """Call this function to write object contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file """ _labs = ' {' _file.write(_labs) self._tctr += 1 for (_item, _text) in value.items(): _tabs = '\t' * self._tctr _cmma = ',' if self._vctr[self._tctr] else '' _keys = '{cmma}\n{tabs}"{item}" :'.format(cmma=_cmma, tabs=_tabs, item=_item) _file.write(_keys) self._vctr[self._tctr] += 1 _text = self.object_hook(_text) _type = type(_text).__name__ _MAGIC_TYPES[_type](self, _text, _file) self._vctr[self._tctr] = 0 self._tctr -= 1 _tabs = '\t' * self._tctr _labs = '\n{tabs}{}'.format('}', tabs=_tabs) _file.write(_labs)
python
def _append_object(self, value, _file): """Call this function to write object contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file """ _labs = ' {' _file.write(_labs) self._tctr += 1 for (_item, _text) in value.items(): _tabs = '\t' * self._tctr _cmma = ',' if self._vctr[self._tctr] else '' _keys = '{cmma}\n{tabs}"{item}" :'.format(cmma=_cmma, tabs=_tabs, item=_item) _file.write(_keys) self._vctr[self._tctr] += 1 _text = self.object_hook(_text) _type = type(_text).__name__ _MAGIC_TYPES[_type](self, _text, _file) self._vctr[self._tctr] = 0 self._tctr -= 1 _tabs = '\t' * self._tctr _labs = '\n{tabs}{}'.format('}', tabs=_tabs) _file.write(_labs)
[ "def", "_append_object", "(", "self", ",", "value", ",", "_file", ")", ":", "_labs", "=", "' {'", "_file", ".", "write", "(", "_labs", ")", "self", ".", "_tctr", "+=", "1", "for", "(", "_item", ",", "_text", ")", "in", "value", ".", "items", "(", ...
Call this function to write object contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
[ "Call", "this", "function", "to", "write", "object", "contents", "." ]
430efcfdff18bb2421c3f27059ff94c93e621483
https://github.com/JarryShaw/DictDumper/blob/430efcfdff18bb2421c3f27059ff94c93e621483/src/json.py#L195-L223
train
45,675
JarryShaw/DictDumper
src/json.py
JSON._append_string
def _append_string(self, value, _file): # pylint: disable=no-self-use """Call this function to write string contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file """ _text = str(value).replace('"', '\\"') _labs = ' "{text}"'.format(text=_text) _file.write(_labs)
python
def _append_string(self, value, _file): # pylint: disable=no-self-use """Call this function to write string contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file """ _text = str(value).replace('"', '\\"') _labs = ' "{text}"'.format(text=_text) _file.write(_labs)
[ "def", "_append_string", "(", "self", ",", "value", ",", "_file", ")", ":", "# pylint: disable=no-self-use", "_text", "=", "str", "(", "value", ")", ".", "replace", "(", "'\"'", ",", "'\\\\\"'", ")", "_labs", "=", "' \"{text}\"'", ".", "format", "(", "text...
Call this function to write string contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
[ "Call", "this", "function", "to", "write", "string", "contents", "." ]
430efcfdff18bb2421c3f27059ff94c93e621483
https://github.com/JarryShaw/DictDumper/blob/430efcfdff18bb2421c3f27059ff94c93e621483/src/json.py#L225-L235
train
45,676
ianlini/bistiming
bistiming/stopwatch.py
Stopwatch.start
def start(self, verbose=None, end_in_new_line=None): """Start the stopwatch if it is paused. If the stopwatch is already started, then nothing will happen. Parameters ---------- verbose : Optional[bool] Wether to log. If `None`, use `verbose_start` set during initialization. end_in_new_line : Optional[bool]] If `False`, prevent logging the trailing new line. If `None`, use `end_in_new_line` set during initialization. """ if self._start_time is not None and self._end_time is None: # the stopwatch is already running return self if verbose is None: verbose = self.verbose_start if verbose: if end_in_new_line is None: end_in_new_line = self.end_in_new_line if end_in_new_line: self.log(self.description) else: self.log(self.description, end="", flush=True) self._end_time = None self._start_time = datetime.datetime.now() return self
python
def start(self, verbose=None, end_in_new_line=None): """Start the stopwatch if it is paused. If the stopwatch is already started, then nothing will happen. Parameters ---------- verbose : Optional[bool] Wether to log. If `None`, use `verbose_start` set during initialization. end_in_new_line : Optional[bool]] If `False`, prevent logging the trailing new line. If `None`, use `end_in_new_line` set during initialization. """ if self._start_time is not None and self._end_time is None: # the stopwatch is already running return self if verbose is None: verbose = self.verbose_start if verbose: if end_in_new_line is None: end_in_new_line = self.end_in_new_line if end_in_new_line: self.log(self.description) else: self.log(self.description, end="", flush=True) self._end_time = None self._start_time = datetime.datetime.now() return self
[ "def", "start", "(", "self", ",", "verbose", "=", "None", ",", "end_in_new_line", "=", "None", ")", ":", "if", "self", ".", "_start_time", "is", "not", "None", "and", "self", ".", "_end_time", "is", "None", ":", "# the stopwatch is already running", "return"...
Start the stopwatch if it is paused. If the stopwatch is already started, then nothing will happen. Parameters ---------- verbose : Optional[bool] Wether to log. If `None`, use `verbose_start` set during initialization. end_in_new_line : Optional[bool]] If `False`, prevent logging the trailing new line. If `None`, use `end_in_new_line` set during initialization.
[ "Start", "the", "stopwatch", "if", "it", "is", "paused", "." ]
46a78ec647723c3516fc4fc73f2619ab41f647f2
https://github.com/ianlini/bistiming/blob/46a78ec647723c3516fc4fc73f2619ab41f647f2/bistiming/stopwatch.py#L64-L91
train
45,677
ianlini/bistiming
bistiming/stopwatch.py
Stopwatch.pause
def pause(self): """Pause the stopwatch. If the stopwatch is already paused, nothing will happen. """ if self._end_time is not None: # the stopwatch is already paused return self._end_time = datetime.datetime.now() self._elapsed_time += self._end_time - self._start_time
python
def pause(self): """Pause the stopwatch. If the stopwatch is already paused, nothing will happen. """ if self._end_time is not None: # the stopwatch is already paused return self._end_time = datetime.datetime.now() self._elapsed_time += self._end_time - self._start_time
[ "def", "pause", "(", "self", ")", ":", "if", "self", ".", "_end_time", "is", "not", "None", ":", "# the stopwatch is already paused", "return", "self", ".", "_end_time", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "self", ".", "_elapsed_time", ...
Pause the stopwatch. If the stopwatch is already paused, nothing will happen.
[ "Pause", "the", "stopwatch", "." ]
46a78ec647723c3516fc4fc73f2619ab41f647f2
https://github.com/ianlini/bistiming/blob/46a78ec647723c3516fc4fc73f2619ab41f647f2/bistiming/stopwatch.py#L93-L102
train
45,678
ianlini/bistiming
bistiming/stopwatch.py
Stopwatch.get_elapsed_time
def get_elapsed_time(self): """Get the elapsed time of the current split. """ if self._start_time is None or self._end_time is not None: # the stopwatch is paused return self._elapsed_time return self._elapsed_time + (datetime.datetime.now() - self._start_time)
python
def get_elapsed_time(self): """Get the elapsed time of the current split. """ if self._start_time is None or self._end_time is not None: # the stopwatch is paused return self._elapsed_time return self._elapsed_time + (datetime.datetime.now() - self._start_time)
[ "def", "get_elapsed_time", "(", "self", ")", ":", "if", "self", ".", "_start_time", "is", "None", "or", "self", ".", "_end_time", "is", "not", "None", ":", "# the stopwatch is paused", "return", "self", ".", "_elapsed_time", "return", "self", ".", "_elapsed_ti...
Get the elapsed time of the current split.
[ "Get", "the", "elapsed", "time", "of", "the", "current", "split", "." ]
46a78ec647723c3516fc4fc73f2619ab41f647f2
https://github.com/ianlini/bistiming/blob/46a78ec647723c3516fc4fc73f2619ab41f647f2/bistiming/stopwatch.py#L104-L110
train
45,679
ianlini/bistiming
bistiming/stopwatch.py
Stopwatch.split
def split(self, verbose=None, end_in_new_line=None): """Save the elapsed time of the current split and restart the stopwatch. The current elapsed time will be appended to :attr:`split_elapsed_time`. If the stopwatch is paused, then it will remain paused. Otherwise, it will continue running. Parameters ---------- verbose : Optional[bool] Wether to log. If `None`, use `verbose_end` set during initialization. end_in_new_line : Optional[bool]] Wether to log the `description`. If `None`, use `end_in_new_line` set during initialization. """ elapsed_time = self.get_elapsed_time() self.split_elapsed_time.append(elapsed_time) self._cumulative_elapsed_time += elapsed_time self._elapsed_time = datetime.timedelta() if verbose is None: verbose = self.verbose_end if verbose: if end_in_new_line is None: end_in_new_line = self.end_in_new_line if end_in_new_line: self.log("{} done in {}".format(self.description, elapsed_time)) else: self.log(" done in {}".format(elapsed_time)) self._start_time = datetime.datetime.now()
python
def split(self, verbose=None, end_in_new_line=None): """Save the elapsed time of the current split and restart the stopwatch. The current elapsed time will be appended to :attr:`split_elapsed_time`. If the stopwatch is paused, then it will remain paused. Otherwise, it will continue running. Parameters ---------- verbose : Optional[bool] Wether to log. If `None`, use `verbose_end` set during initialization. end_in_new_line : Optional[bool]] Wether to log the `description`. If `None`, use `end_in_new_line` set during initialization. """ elapsed_time = self.get_elapsed_time() self.split_elapsed_time.append(elapsed_time) self._cumulative_elapsed_time += elapsed_time self._elapsed_time = datetime.timedelta() if verbose is None: verbose = self.verbose_end if verbose: if end_in_new_line is None: end_in_new_line = self.end_in_new_line if end_in_new_line: self.log("{} done in {}".format(self.description, elapsed_time)) else: self.log(" done in {}".format(elapsed_time)) self._start_time = datetime.datetime.now()
[ "def", "split", "(", "self", ",", "verbose", "=", "None", ",", "end_in_new_line", "=", "None", ")", ":", "elapsed_time", "=", "self", ".", "get_elapsed_time", "(", ")", "self", ".", "split_elapsed_time", ".", "append", "(", "elapsed_time", ")", "self", "."...
Save the elapsed time of the current split and restart the stopwatch. The current elapsed time will be appended to :attr:`split_elapsed_time`. If the stopwatch is paused, then it will remain paused. Otherwise, it will continue running. Parameters ---------- verbose : Optional[bool] Wether to log. If `None`, use `verbose_end` set during initialization. end_in_new_line : Optional[bool]] Wether to log the `description`. If `None`, use `end_in_new_line` set during initialization.
[ "Save", "the", "elapsed", "time", "of", "the", "current", "split", "and", "restart", "the", "stopwatch", "." ]
46a78ec647723c3516fc4fc73f2619ab41f647f2
https://github.com/ianlini/bistiming/blob/46a78ec647723c3516fc4fc73f2619ab41f647f2/bistiming/stopwatch.py#L127-L155
train
45,680
ianlini/bistiming
bistiming/stopwatch.py
Stopwatch.reset
def reset(self): """Reset the stopwatch. """ self._start_time = None self._end_time = None self._elapsed_time = datetime.timedelta() self._cumulative_elapsed_time = datetime.timedelta() self.split_elapsed_time = []
python
def reset(self): """Reset the stopwatch. """ self._start_time = None self._end_time = None self._elapsed_time = datetime.timedelta() self._cumulative_elapsed_time = datetime.timedelta() self.split_elapsed_time = []
[ "def", "reset", "(", "self", ")", ":", "self", ".", "_start_time", "=", "None", "self", ".", "_end_time", "=", "None", "self", ".", "_elapsed_time", "=", "datetime", ".", "timedelta", "(", ")", "self", ".", "_cumulative_elapsed_time", "=", "datetime", ".",...
Reset the stopwatch.
[ "Reset", "the", "stopwatch", "." ]
46a78ec647723c3516fc4fc73f2619ab41f647f2
https://github.com/ianlini/bistiming/blob/46a78ec647723c3516fc4fc73f2619ab41f647f2/bistiming/stopwatch.py#L157-L164
train
45,681
google/identity-toolkit-python-client
identitytoolkit/rpchelper.py
RpcHelper.DownloadAccount
def DownloadAccount(self, next_page_token=None, max_results=None): """Downloads multiple accounts from Gitkit server. Args: next_page_token: string, pagination token. max_results: pagination size. Returns: An array of accounts. """ param = {} if next_page_token: param['nextPageToken'] = next_page_token if max_results: param['maxResults'] = max_results response = self._InvokeGitkitApi('downloadAccount', param) # pylint does not recognize the return type of simplejson.loads # pylint: disable=maybe-no-member return response.get('nextPageToken', None), response.get('users', {})
python
def DownloadAccount(self, next_page_token=None, max_results=None): """Downloads multiple accounts from Gitkit server. Args: next_page_token: string, pagination token. max_results: pagination size. Returns: An array of accounts. """ param = {} if next_page_token: param['nextPageToken'] = next_page_token if max_results: param['maxResults'] = max_results response = self._InvokeGitkitApi('downloadAccount', param) # pylint does not recognize the return type of simplejson.loads # pylint: disable=maybe-no-member return response.get('nextPageToken', None), response.get('users', {})
[ "def", "DownloadAccount", "(", "self", ",", "next_page_token", "=", "None", ",", "max_results", "=", "None", ")", ":", "param", "=", "{", "}", "if", "next_page_token", ":", "param", "[", "'nextPageToken'", "]", "=", "next_page_token", "if", "max_results", ":...
Downloads multiple accounts from Gitkit server. Args: next_page_token: string, pagination token. max_results: pagination size. Returns: An array of accounts.
[ "Downloads", "multiple", "accounts", "from", "Gitkit", "server", "." ]
4cfe3013569c21576daa5d22ad21f9f4f8b30c4d
https://github.com/google/identity-toolkit-python-client/blob/4cfe3013569c21576daa5d22ad21f9f4f8b30c4d/identitytoolkit/rpchelper.py#L109-L127
train
45,682
google/identity-toolkit-python-client
identitytoolkit/rpchelper.py
RpcHelper.UploadAccount
def UploadAccount(self, hash_algorithm, hash_key, accounts): """Uploads multiple accounts to Gitkit server. Args: hash_algorithm: string, algorithm to hash password. hash_key: string, base64-encoded key of the algorithm. accounts: array of accounts to be uploaded. Returns: Response of the API. """ param = { 'hashAlgorithm': hash_algorithm, 'signerKey': hash_key, 'users': accounts } # pylint does not recognize the return type of simplejson.loads # pylint: disable=maybe-no-member return self._InvokeGitkitApi('uploadAccount', param)
python
def UploadAccount(self, hash_algorithm, hash_key, accounts): """Uploads multiple accounts to Gitkit server. Args: hash_algorithm: string, algorithm to hash password. hash_key: string, base64-encoded key of the algorithm. accounts: array of accounts to be uploaded. Returns: Response of the API. """ param = { 'hashAlgorithm': hash_algorithm, 'signerKey': hash_key, 'users': accounts } # pylint does not recognize the return type of simplejson.loads # pylint: disable=maybe-no-member return self._InvokeGitkitApi('uploadAccount', param)
[ "def", "UploadAccount", "(", "self", ",", "hash_algorithm", ",", "hash_key", ",", "accounts", ")", ":", "param", "=", "{", "'hashAlgorithm'", ":", "hash_algorithm", ",", "'signerKey'", ":", "hash_key", ",", "'users'", ":", "accounts", "}", "# pylint does not rec...
Uploads multiple accounts to Gitkit server. Args: hash_algorithm: string, algorithm to hash password. hash_key: string, base64-encoded key of the algorithm. accounts: array of accounts to be uploaded. Returns: Response of the API.
[ "Uploads", "multiple", "accounts", "to", "Gitkit", "server", "." ]
4cfe3013569c21576daa5d22ad21f9f4f8b30c4d
https://github.com/google/identity-toolkit-python-client/blob/4cfe3013569c21576daa5d22ad21f9f4f8b30c4d/identitytoolkit/rpchelper.py#L129-L147
train
45,683
google/identity-toolkit-python-client
identitytoolkit/rpchelper.py
RpcHelper.GetPublicCert
def GetPublicCert(self): """Download Gitkit public cert. Returns: dict of public certs. """ cert_url = self.google_api_url + 'publicKeys' resp, content = self.http.request(cert_url) if resp.status == 200: return simplejson.loads(content) else: raise errors.GitkitServerError('Error response for cert url: %s' % content)
python
def GetPublicCert(self): """Download Gitkit public cert. Returns: dict of public certs. """ cert_url = self.google_api_url + 'publicKeys' resp, content = self.http.request(cert_url) if resp.status == 200: return simplejson.loads(content) else: raise errors.GitkitServerError('Error response for cert url: %s' % content)
[ "def", "GetPublicCert", "(", "self", ")", ":", "cert_url", "=", "self", ".", "google_api_url", "+", "'publicKeys'", "resp", ",", "content", "=", "self", ".", "http", ".", "request", "(", "cert_url", ")", "if", "resp", ".", "status", "==", "200", ":", "...
Download Gitkit public cert. Returns: dict of public certs.
[ "Download", "Gitkit", "public", "cert", "." ]
4cfe3013569c21576daa5d22ad21f9f4f8b30c4d
https://github.com/google/identity-toolkit-python-client/blob/4cfe3013569c21576daa5d22ad21f9f4f8b30c4d/identitytoolkit/rpchelper.py#L172-L186
train
45,684
google/identity-toolkit-python-client
identitytoolkit/rpchelper.py
RpcHelper._InvokeGitkitApi
def _InvokeGitkitApi(self, method, params=None, need_service_account=True): """Invokes Gitkit API, with optional access token for service account. Args: method: string, the api method name. params: dict of optional parameters for the API. need_service_account: false if service account is not needed. Raises: GitkitClientError: if the request is bad. GitkitServerError: if Gitkit can not handle the request. Returns: API response as dict. """ body = simplejson.dumps(params) if params else None req = urllib_request.Request(self.google_api_url + method) req.add_header('Content-type', 'application/json') if need_service_account: if self.credentials: access_token = self.credentials.get_access_token().access_token elif self.service_account_email and self.service_account_key: access_token = self._GetAccessToken() else: raise errors.GitkitClientError('Missing service account credentials') req.add_header('Authorization', 'Bearer ' + access_token) try: binary_body = body.encode('utf-8') if body else None raw_response = urllib_request.urlopen(req, binary_body).read() except urllib_request.HTTPError as err: if err.code == 400: raw_response = err.read() else: raise return self._CheckGitkitError(raw_response)
python
def _InvokeGitkitApi(self, method, params=None, need_service_account=True): """Invokes Gitkit API, with optional access token for service account. Args: method: string, the api method name. params: dict of optional parameters for the API. need_service_account: false if service account is not needed. Raises: GitkitClientError: if the request is bad. GitkitServerError: if Gitkit can not handle the request. Returns: API response as dict. """ body = simplejson.dumps(params) if params else None req = urllib_request.Request(self.google_api_url + method) req.add_header('Content-type', 'application/json') if need_service_account: if self.credentials: access_token = self.credentials.get_access_token().access_token elif self.service_account_email and self.service_account_key: access_token = self._GetAccessToken() else: raise errors.GitkitClientError('Missing service account credentials') req.add_header('Authorization', 'Bearer ' + access_token) try: binary_body = body.encode('utf-8') if body else None raw_response = urllib_request.urlopen(req, binary_body).read() except urllib_request.HTTPError as err: if err.code == 400: raw_response = err.read() else: raise return self._CheckGitkitError(raw_response)
[ "def", "_InvokeGitkitApi", "(", "self", ",", "method", ",", "params", "=", "None", ",", "need_service_account", "=", "True", ")", ":", "body", "=", "simplejson", ".", "dumps", "(", "params", ")", "if", "params", "else", "None", "req", "=", "urllib_request"...
Invokes Gitkit API, with optional access token for service account. Args: method: string, the api method name. params: dict of optional parameters for the API. need_service_account: false if service account is not needed. Raises: GitkitClientError: if the request is bad. GitkitServerError: if Gitkit can not handle the request. Returns: API response as dict.
[ "Invokes", "Gitkit", "API", "with", "optional", "access", "token", "for", "service", "account", "." ]
4cfe3013569c21576daa5d22ad21f9f4f8b30c4d
https://github.com/google/identity-toolkit-python-client/blob/4cfe3013569c21576daa5d22ad21f9f4f8b30c4d/identitytoolkit/rpchelper.py#L188-L222
train
45,685
google/identity-toolkit-python-client
identitytoolkit/rpchelper.py
RpcHelper._GetAccessToken
def _GetAccessToken(self): """Gets oauth2 access token for Gitkit API using service account. Returns: string, oauth2 access token. """ d = { 'assertion': self._GenerateAssertion(), 'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer', } try: body = parse.urlencode(d) except AttributeError: body = urllib.urlencode(d) req = urllib_request.Request(RpcHelper.TOKEN_ENDPOINT) req.add_header('Content-type', 'application/x-www-form-urlencoded') binary_body = body.encode('utf-8') raw_response = urllib_request.urlopen(req, binary_body) return simplejson.loads(raw_response.read())['access_token']
python
def _GetAccessToken(self): """Gets oauth2 access token for Gitkit API using service account. Returns: string, oauth2 access token. """ d = { 'assertion': self._GenerateAssertion(), 'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer', } try: body = parse.urlencode(d) except AttributeError: body = urllib.urlencode(d) req = urllib_request.Request(RpcHelper.TOKEN_ENDPOINT) req.add_header('Content-type', 'application/x-www-form-urlencoded') binary_body = body.encode('utf-8') raw_response = urllib_request.urlopen(req, binary_body) return simplejson.loads(raw_response.read())['access_token']
[ "def", "_GetAccessToken", "(", "self", ")", ":", "d", "=", "{", "'assertion'", ":", "self", ".", "_GenerateAssertion", "(", ")", ",", "'grant_type'", ":", "'urn:ietf:params:oauth:grant-type:jwt-bearer'", ",", "}", "try", ":", "body", "=", "parse", ".", "urlenc...
Gets oauth2 access token for Gitkit API using service account. Returns: string, oauth2 access token.
[ "Gets", "oauth2", "access", "token", "for", "Gitkit", "API", "using", "service", "account", "." ]
4cfe3013569c21576daa5d22ad21f9f4f8b30c4d
https://github.com/google/identity-toolkit-python-client/blob/4cfe3013569c21576daa5d22ad21f9f4f8b30c4d/identitytoolkit/rpchelper.py#L224-L242
train
45,686
google/identity-toolkit-python-client
identitytoolkit/rpchelper.py
RpcHelper._GenerateAssertion
def _GenerateAssertion(self): """Generates the signed assertion that will be used in the request. Returns: string, signed Json Web Token (JWT) assertion. """ now = int(time.time()) payload = { 'aud': RpcHelper.TOKEN_ENDPOINT, 'scope': 'https://www.googleapis.com/auth/identitytoolkit', 'iat': now, 'exp': now + RpcHelper.MAX_TOKEN_LIFETIME_SECS, 'iss': self.service_account_email } return crypt.make_signed_jwt( crypt.Signer.from_string(self.service_account_key), payload)
python
def _GenerateAssertion(self): """Generates the signed assertion that will be used in the request. Returns: string, signed Json Web Token (JWT) assertion. """ now = int(time.time()) payload = { 'aud': RpcHelper.TOKEN_ENDPOINT, 'scope': 'https://www.googleapis.com/auth/identitytoolkit', 'iat': now, 'exp': now + RpcHelper.MAX_TOKEN_LIFETIME_SECS, 'iss': self.service_account_email } return crypt.make_signed_jwt( crypt.Signer.from_string(self.service_account_key), payload)
[ "def", "_GenerateAssertion", "(", "self", ")", ":", "now", "=", "int", "(", "time", ".", "time", "(", ")", ")", "payload", "=", "{", "'aud'", ":", "RpcHelper", ".", "TOKEN_ENDPOINT", ",", "'scope'", ":", "'https://www.googleapis.com/auth/identitytoolkit'", ","...
Generates the signed assertion that will be used in the request. Returns: string, signed Json Web Token (JWT) assertion.
[ "Generates", "the", "signed", "assertion", "that", "will", "be", "used", "in", "the", "request", "." ]
4cfe3013569c21576daa5d22ad21f9f4f8b30c4d
https://github.com/google/identity-toolkit-python-client/blob/4cfe3013569c21576daa5d22ad21f9f4f8b30c4d/identitytoolkit/rpchelper.py#L244-L260
train
45,687
google/identity-toolkit-python-client
identitytoolkit/rpchelper.py
RpcHelper._CheckGitkitError
def _CheckGitkitError(self, raw_response): """Raises error if API invocation failed. Args: raw_response: string, the http response. Raises: GitkitClientError: if the error code is 4xx. GitkitServerError: if the response if malformed. Returns: Successful response as dict. """ try: response = simplejson.loads(raw_response) if 'error' not in response: return response else: error = response['error'] if 'code' in error: code = error['code'] if str(code).startswith('4'): raise errors.GitkitClientError(error['message']) else: raise errors.GitkitServerError(error['message']) except simplejson.JSONDecodeError: pass raise errors.GitkitServerError('null error code from Gitkit server')
python
def _CheckGitkitError(self, raw_response): """Raises error if API invocation failed. Args: raw_response: string, the http response. Raises: GitkitClientError: if the error code is 4xx. GitkitServerError: if the response if malformed. Returns: Successful response as dict. """ try: response = simplejson.loads(raw_response) if 'error' not in response: return response else: error = response['error'] if 'code' in error: code = error['code'] if str(code).startswith('4'): raise errors.GitkitClientError(error['message']) else: raise errors.GitkitServerError(error['message']) except simplejson.JSONDecodeError: pass raise errors.GitkitServerError('null error code from Gitkit server')
[ "def", "_CheckGitkitError", "(", "self", ",", "raw_response", ")", ":", "try", ":", "response", "=", "simplejson", ".", "loads", "(", "raw_response", ")", "if", "'error'", "not", "in", "response", ":", "return", "response", "else", ":", "error", "=", "resp...
Raises error if API invocation failed. Args: raw_response: string, the http response. Raises: GitkitClientError: if the error code is 4xx. GitkitServerError: if the response if malformed. Returns: Successful response as dict.
[ "Raises", "error", "if", "API", "invocation", "failed", "." ]
4cfe3013569c21576daa5d22ad21f9f4f8b30c4d
https://github.com/google/identity-toolkit-python-client/blob/4cfe3013569c21576daa5d22ad21f9f4f8b30c4d/identitytoolkit/rpchelper.py#L262-L289
train
45,688
google/identity-toolkit-python-client
identitytoolkit/gitkitclient.py
GitkitUser.FromDictionary
def FromDictionary(cls, dictionary): """Initializes from user specified dictionary. Args: dictionary: dict of user specified attributes Returns: GitkitUser object """ if 'user_id' in dictionary: raise errors.GitkitClientError('use localId instead') if 'localId' not in dictionary: raise errors.GitkitClientError('must specify localId') if 'email' not in dictionary: raise errors.GitkitClientError('must specify email') return cls(decode=False, **dictionary)
python
def FromDictionary(cls, dictionary): """Initializes from user specified dictionary. Args: dictionary: dict of user specified attributes Returns: GitkitUser object """ if 'user_id' in dictionary: raise errors.GitkitClientError('use localId instead') if 'localId' not in dictionary: raise errors.GitkitClientError('must specify localId') if 'email' not in dictionary: raise errors.GitkitClientError('must specify email') return cls(decode=False, **dictionary)
[ "def", "FromDictionary", "(", "cls", ",", "dictionary", ")", ":", "if", "'user_id'", "in", "dictionary", ":", "raise", "errors", ".", "GitkitClientError", "(", "'use localId instead'", ")", "if", "'localId'", "not", "in", "dictionary", ":", "raise", "errors", ...
Initializes from user specified dictionary. Args: dictionary: dict of user specified attributes Returns: GitkitUser object
[ "Initializes", "from", "user", "specified", "dictionary", "." ]
4cfe3013569c21576daa5d22ad21f9f4f8b30c4d
https://github.com/google/identity-toolkit-python-client/blob/4cfe3013569c21576daa5d22ad21f9f4f8b30c4d/identitytoolkit/gitkitclient.py#L118-L133
train
45,689
google/identity-toolkit-python-client
identitytoolkit/gitkitclient.py
GitkitUser.ToRequest
def ToRequest(self): """Converts to gitkit api request parameter dict. Returns: Dict, containing non-empty user attributes. """ param = {} if self.email: param['email'] = self.email if self.user_id: param['localId'] = self.user_id if self.name: param['displayName'] = self.name if self.photo_url: param['photoUrl'] = self.photo_url if self.email_verified is not None: param['emailVerified'] = self.email_verified if self.password_hash: param['passwordHash'] = base64.urlsafe_b64encode(self.password_hash) if self.salt: param['salt'] = base64.urlsafe_b64encode(self.salt) if self.provider_info: param['providerUserInfo'] = self.provider_info return param
python
def ToRequest(self): """Converts to gitkit api request parameter dict. Returns: Dict, containing non-empty user attributes. """ param = {} if self.email: param['email'] = self.email if self.user_id: param['localId'] = self.user_id if self.name: param['displayName'] = self.name if self.photo_url: param['photoUrl'] = self.photo_url if self.email_verified is not None: param['emailVerified'] = self.email_verified if self.password_hash: param['passwordHash'] = base64.urlsafe_b64encode(self.password_hash) if self.salt: param['salt'] = base64.urlsafe_b64encode(self.salt) if self.provider_info: param['providerUserInfo'] = self.provider_info return param
[ "def", "ToRequest", "(", "self", ")", ":", "param", "=", "{", "}", "if", "self", ".", "email", ":", "param", "[", "'email'", "]", "=", "self", ".", "email", "if", "self", ".", "user_id", ":", "param", "[", "'localId'", "]", "=", "self", ".", "use...
Converts to gitkit api request parameter dict. Returns: Dict, containing non-empty user attributes.
[ "Converts", "to", "gitkit", "api", "request", "parameter", "dict", "." ]
4cfe3013569c21576daa5d22ad21f9f4f8b30c4d
https://github.com/google/identity-toolkit-python-client/blob/4cfe3013569c21576daa5d22ad21f9f4f8b30c4d/identitytoolkit/gitkitclient.py#L135-L158
train
45,690
google/identity-toolkit-python-client
identitytoolkit/gitkitclient.py
GitkitClient.VerifyGitkitToken
def VerifyGitkitToken(self, jwt): """Verifies a Gitkit token string. Args: jwt: string, the token to be checked Returns: GitkitUser, if the token is valid. None otherwise. """ certs = self.rpc_helper.GetPublicCert() crypt.MAX_TOKEN_LIFETIME_SECS = 30 * 86400 # 30 days parsed = None for aud in filter(lambda x: x is not None, [self.project_id, self.client_id]): try: parsed = crypt.verify_signed_jwt_with_certs(jwt, certs, aud) except crypt.AppIdentityError as e: if "Wrong recipient" not in e.message: return None if parsed: return GitkitUser.FromToken(parsed) return None
python
def VerifyGitkitToken(self, jwt): """Verifies a Gitkit token string. Args: jwt: string, the token to be checked Returns: GitkitUser, if the token is valid. None otherwise. """ certs = self.rpc_helper.GetPublicCert() crypt.MAX_TOKEN_LIFETIME_SECS = 30 * 86400 # 30 days parsed = None for aud in filter(lambda x: x is not None, [self.project_id, self.client_id]): try: parsed = crypt.verify_signed_jwt_with_certs(jwt, certs, aud) except crypt.AppIdentityError as e: if "Wrong recipient" not in e.message: return None if parsed: return GitkitUser.FromToken(parsed) return None
[ "def", "VerifyGitkitToken", "(", "self", ",", "jwt", ")", ":", "certs", "=", "self", ".", "rpc_helper", ".", "GetPublicCert", "(", ")", "crypt", ".", "MAX_TOKEN_LIFETIME_SECS", "=", "30", "*", "86400", "# 30 days", "parsed", "=", "None", "for", "aud", "in"...
Verifies a Gitkit token string. Args: jwt: string, the token to be checked Returns: GitkitUser, if the token is valid. None otherwise.
[ "Verifies", "a", "Gitkit", "token", "string", "." ]
4cfe3013569c21576daa5d22ad21f9f4f8b30c4d
https://github.com/google/identity-toolkit-python-client/blob/4cfe3013569c21576daa5d22ad21f9f4f8b30c4d/identitytoolkit/gitkitclient.py#L252-L272
train
45,691
google/identity-toolkit-python-client
identitytoolkit/gitkitclient.py
GitkitClient.GetUserByEmail
def GetUserByEmail(self, email): """Gets user info by email. Args: email: string, the user email. Returns: GitkitUser, containing the user info. """ user = self.rpc_helper.GetAccountInfoByEmail(email) return GitkitUser.FromApiResponse(user)
python
def GetUserByEmail(self, email): """Gets user info by email. Args: email: string, the user email. Returns: GitkitUser, containing the user info. """ user = self.rpc_helper.GetAccountInfoByEmail(email) return GitkitUser.FromApiResponse(user)
[ "def", "GetUserByEmail", "(", "self", ",", "email", ")", ":", "user", "=", "self", ".", "rpc_helper", ".", "GetAccountInfoByEmail", "(", "email", ")", "return", "GitkitUser", ".", "FromApiResponse", "(", "user", ")" ]
Gets user info by email. Args: email: string, the user email. Returns: GitkitUser, containing the user info.
[ "Gets", "user", "info", "by", "email", "." ]
4cfe3013569c21576daa5d22ad21f9f4f8b30c4d
https://github.com/google/identity-toolkit-python-client/blob/4cfe3013569c21576daa5d22ad21f9f4f8b30c4d/identitytoolkit/gitkitclient.py#L274-L284
train
45,692
google/identity-toolkit-python-client
identitytoolkit/gitkitclient.py
GitkitClient.GetUserById
def GetUserById(self, local_id): """Gets user info by id. Args: local_id: string, the user id at Gitkit server. Returns: GitkitUser, containing the user info. """ user = self.rpc_helper.GetAccountInfoById(local_id) return GitkitUser.FromApiResponse(user)
python
def GetUserById(self, local_id): """Gets user info by id. Args: local_id: string, the user id at Gitkit server. Returns: GitkitUser, containing the user info. """ user = self.rpc_helper.GetAccountInfoById(local_id) return GitkitUser.FromApiResponse(user)
[ "def", "GetUserById", "(", "self", ",", "local_id", ")", ":", "user", "=", "self", ".", "rpc_helper", ".", "GetAccountInfoById", "(", "local_id", ")", "return", "GitkitUser", ".", "FromApiResponse", "(", "user", ")" ]
Gets user info by id. Args: local_id: string, the user id at Gitkit server. Returns: GitkitUser, containing the user info.
[ "Gets", "user", "info", "by", "id", "." ]
4cfe3013569c21576daa5d22ad21f9f4f8b30c4d
https://github.com/google/identity-toolkit-python-client/blob/4cfe3013569c21576daa5d22ad21f9f4f8b30c4d/identitytoolkit/gitkitclient.py#L286-L296
train
45,693
google/identity-toolkit-python-client
identitytoolkit/gitkitclient.py
GitkitClient.UploadUsers
def UploadUsers(self, hash_algorithm, hash_key, accounts): """Uploads multiple users to Gitkit server. Args: hash_algorithm: string, the hash algorithm. hash_key: array, raw key of the hash algorithm. accounts: list of GitkitUser. Returns: A dict of failed accounts. The key is the index of the 'accounts' list, starting from 0. """ return self.rpc_helper.UploadAccount(hash_algorithm, base64.urlsafe_b64encode(hash_key), [GitkitUser.ToRequest(i) for i in accounts])
python
def UploadUsers(self, hash_algorithm, hash_key, accounts): """Uploads multiple users to Gitkit server. Args: hash_algorithm: string, the hash algorithm. hash_key: array, raw key of the hash algorithm. accounts: list of GitkitUser. Returns: A dict of failed accounts. The key is the index of the 'accounts' list, starting from 0. """ return self.rpc_helper.UploadAccount(hash_algorithm, base64.urlsafe_b64encode(hash_key), [GitkitUser.ToRequest(i) for i in accounts])
[ "def", "UploadUsers", "(", "self", ",", "hash_algorithm", ",", "hash_key", ",", "accounts", ")", ":", "return", "self", ".", "rpc_helper", ".", "UploadAccount", "(", "hash_algorithm", ",", "base64", ".", "urlsafe_b64encode", "(", "hash_key", ")", ",", "[", "...
Uploads multiple users to Gitkit server. Args: hash_algorithm: string, the hash algorithm. hash_key: array, raw key of the hash algorithm. accounts: list of GitkitUser. Returns: A dict of failed accounts. The key is the index of the 'accounts' list, starting from 0.
[ "Uploads", "multiple", "users", "to", "Gitkit", "server", "." ]
4cfe3013569c21576daa5d22ad21f9f4f8b30c4d
https://github.com/google/identity-toolkit-python-client/blob/4cfe3013569c21576daa5d22ad21f9f4f8b30c4d/identitytoolkit/gitkitclient.py#L298-L312
train
45,694
google/identity-toolkit-python-client
identitytoolkit/gitkitclient.py
GitkitClient.GetAllUsers
def GetAllUsers(self, pagination_size=10): """Gets all user info from Gitkit server. Args: pagination_size: int, how many users should be returned per request. The account info are retrieved in pagination. Yields: A generator to iterate all users. """ next_page_token, accounts = self.rpc_helper.DownloadAccount( None, pagination_size) while accounts: for account in accounts: yield GitkitUser.FromApiResponse(account) next_page_token, accounts = self.rpc_helper.DownloadAccount( next_page_token, pagination_size)
python
def GetAllUsers(self, pagination_size=10): """Gets all user info from Gitkit server. Args: pagination_size: int, how many users should be returned per request. The account info are retrieved in pagination. Yields: A generator to iterate all users. """ next_page_token, accounts = self.rpc_helper.DownloadAccount( None, pagination_size) while accounts: for account in accounts: yield GitkitUser.FromApiResponse(account) next_page_token, accounts = self.rpc_helper.DownloadAccount( next_page_token, pagination_size)
[ "def", "GetAllUsers", "(", "self", ",", "pagination_size", "=", "10", ")", ":", "next_page_token", ",", "accounts", "=", "self", ".", "rpc_helper", ".", "DownloadAccount", "(", "None", ",", "pagination_size", ")", "while", "accounts", ":", "for", "account", ...
Gets all user info from Gitkit server. Args: pagination_size: int, how many users should be returned per request. The account info are retrieved in pagination. Yields: A generator to iterate all users.
[ "Gets", "all", "user", "info", "from", "Gitkit", "server", "." ]
4cfe3013569c21576daa5d22ad21f9f4f8b30c4d
https://github.com/google/identity-toolkit-python-client/blob/4cfe3013569c21576daa5d22ad21f9f4f8b30c4d/identitytoolkit/gitkitclient.py#L314-L330
train
45,695
google/identity-toolkit-python-client
identitytoolkit/gitkitclient.py
GitkitClient._BuildOobLink
def _BuildOobLink(self, param, mode): """Builds out-of-band URL. Gitkit API GetOobCode() is called and the returning code is combined with Gitkit widget URL to building the out-of-band url. Args: param: dict of request. mode: string, Gitkit widget mode to handle the oob action after user clicks the oob url in the email. Raises: GitkitClientError: if oob code is not returned. Returns: A string of oob url. """ code = self.rpc_helper.GetOobCode(param) if code: parsed = list(parse.urlparse(self.widget_url)) query = dict(parse.parse_qsl(parsed[4])) query.update({'mode': mode, 'oobCode': code}) try: parsed[4] = parse.urlencode(query) except AttributeError: parsed[4] = urllib.urlencode(query) return code, parse.urlunparse(parsed) raise errors.GitkitClientError('invalid request')
python
def _BuildOobLink(self, param, mode): """Builds out-of-band URL. Gitkit API GetOobCode() is called and the returning code is combined with Gitkit widget URL to building the out-of-band url. Args: param: dict of request. mode: string, Gitkit widget mode to handle the oob action after user clicks the oob url in the email. Raises: GitkitClientError: if oob code is not returned. Returns: A string of oob url. """ code = self.rpc_helper.GetOobCode(param) if code: parsed = list(parse.urlparse(self.widget_url)) query = dict(parse.parse_qsl(parsed[4])) query.update({'mode': mode, 'oobCode': code}) try: parsed[4] = parse.urlencode(query) except AttributeError: parsed[4] = urllib.urlencode(query) return code, parse.urlunparse(parsed) raise errors.GitkitClientError('invalid request')
[ "def", "_BuildOobLink", "(", "self", ",", "param", ",", "mode", ")", ":", "code", "=", "self", ".", "rpc_helper", ".", "GetOobCode", "(", "param", ")", "if", "code", ":", "parsed", "=", "list", "(", "parse", ".", "urlparse", "(", "self", ".", "widget...
Builds out-of-band URL. Gitkit API GetOobCode() is called and the returning code is combined with Gitkit widget URL to building the out-of-band url. Args: param: dict of request. mode: string, Gitkit widget mode to handle the oob action after user clicks the oob url in the email. Raises: GitkitClientError: if oob code is not returned. Returns: A string of oob url.
[ "Builds", "out", "-", "of", "-", "band", "URL", "." ]
4cfe3013569c21576daa5d22ad21f9f4f8b30c4d
https://github.com/google/identity-toolkit-python-client/blob/4cfe3013569c21576daa5d22ad21f9f4f8b30c4d/identitytoolkit/gitkitclient.py#L418-L448
train
45,696
weso/CWR-DataApi
cwr/grammar/field/table.py
char_code
def char_code(columns, name=None): """ Character set code field. :param name: name for the field :return: an instance of the Character set code field rules """ if name is None: name = 'Char Code Field (' + str(columns) + ' columns)' if columns <= 0: raise BaseException() char_sets = None for char_set in _tables.get_data('character_set'): regex = '[ ]{' + str(15 - len(char_set)) + '}' + char_set if char_sets is None: char_sets = regex else: char_sets += '|' + regex # Accepted sets _character_sets = pp.Regex(char_sets) _unicode_1_16b = pp.Regex('U\+0[0-8,A-F]{3}[ ]{' + str(columns - 6) + '}') _unicode_2_21b = pp.Regex('U\+0[0-8,A-F]{4}[ ]{' + str(columns - 7) + '}') # Basic field char_code_field = (_character_sets | _unicode_1_16b | _unicode_2_21b) # Parse action char_code_field = char_code_field.setParseAction(lambda s: s[0].strip()) # Name char_code_field.setName(name) return char_code_field
python
def char_code(columns, name=None): """ Character set code field. :param name: name for the field :return: an instance of the Character set code field rules """ if name is None: name = 'Char Code Field (' + str(columns) + ' columns)' if columns <= 0: raise BaseException() char_sets = None for char_set in _tables.get_data('character_set'): regex = '[ ]{' + str(15 - len(char_set)) + '}' + char_set if char_sets is None: char_sets = regex else: char_sets += '|' + regex # Accepted sets _character_sets = pp.Regex(char_sets) _unicode_1_16b = pp.Regex('U\+0[0-8,A-F]{3}[ ]{' + str(columns - 6) + '}') _unicode_2_21b = pp.Regex('U\+0[0-8,A-F]{4}[ ]{' + str(columns - 7) + '}') # Basic field char_code_field = (_character_sets | _unicode_1_16b | _unicode_2_21b) # Parse action char_code_field = char_code_field.setParseAction(lambda s: s[0].strip()) # Name char_code_field.setName(name) return char_code_field
[ "def", "char_code", "(", "columns", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "'Char Code Field ('", "+", "str", "(", "columns", ")", "+", "' columns)'", "if", "columns", "<=", "0", ":", "raise", "BaseException", ...
Character set code field. :param name: name for the field :return: an instance of the Character set code field rules
[ "Character", "set", "code", "field", "." ]
f3b6ba8308c901b6ab87073c155c08e30692333c
https://github.com/weso/CWR-DataApi/blob/f3b6ba8308c901b6ab87073c155c08e30692333c/cwr/grammar/field/table.py#L41-L76
train
45,697
calmjs/calmjs
src/calmjs/ui.py
make_choice_validator
def make_choice_validator( choices, default_key=None, normalizer=None): """ Returns a callable that accepts the choices provided. Choices should be provided as a list of 2-tuples, where the first element is a string that should match user input (the key); the second being the value associated with the key. The callable by default will match, upon complete match the first value associated with the result will be returned. Partial matches are supported. If a default is provided, that value will be returned if the user provided input is empty, i.e. the value that is mapped to the empty string. Finally, a normalizer function can be passed. This normalizes all keys and validation value. """ def normalize_all(_choices): # normalize all the keys for easier comparison if normalizer: _choices = [(normalizer(key), value) for key, value in choices] return _choices choices = normalize_all(choices) def choice_validator(value): if normalizer: value = normalizer(value) if not value and default_key: value = choices[default_key][0] results = [] for choice, mapped in choices: if value == choice: return mapped if choice.startswith(value): results.append((choice, mapped)) if len(results) == 1: return results[0][1] elif not results: raise ValueError('Invalid choice.') else: raise ValueError( 'Choice ambiguous between (%s)' % ', '.join( k for k, v in normalize_all(results)) ) return choice_validator
python
def make_choice_validator( choices, default_key=None, normalizer=None): """ Returns a callable that accepts the choices provided. Choices should be provided as a list of 2-tuples, where the first element is a string that should match user input (the key); the second being the value associated with the key. The callable by default will match, upon complete match the first value associated with the result will be returned. Partial matches are supported. If a default is provided, that value will be returned if the user provided input is empty, i.e. the value that is mapped to the empty string. Finally, a normalizer function can be passed. This normalizes all keys and validation value. """ def normalize_all(_choices): # normalize all the keys for easier comparison if normalizer: _choices = [(normalizer(key), value) for key, value in choices] return _choices choices = normalize_all(choices) def choice_validator(value): if normalizer: value = normalizer(value) if not value and default_key: value = choices[default_key][0] results = [] for choice, mapped in choices: if value == choice: return mapped if choice.startswith(value): results.append((choice, mapped)) if len(results) == 1: return results[0][1] elif not results: raise ValueError('Invalid choice.') else: raise ValueError( 'Choice ambiguous between (%s)' % ', '.join( k for k, v in normalize_all(results)) ) return choice_validator
[ "def", "make_choice_validator", "(", "choices", ",", "default_key", "=", "None", ",", "normalizer", "=", "None", ")", ":", "def", "normalize_all", "(", "_choices", ")", ":", "# normalize all the keys for easier comparison", "if", "normalizer", ":", "_choices", "=", ...
Returns a callable that accepts the choices provided. Choices should be provided as a list of 2-tuples, where the first element is a string that should match user input (the key); the second being the value associated with the key. The callable by default will match, upon complete match the first value associated with the result will be returned. Partial matches are supported. If a default is provided, that value will be returned if the user provided input is empty, i.e. the value that is mapped to the empty string. Finally, a normalizer function can be passed. This normalizes all keys and validation value.
[ "Returns", "a", "callable", "that", "accepts", "the", "choices", "provided", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/ui.py#L47-L97
train
45,698
calmjs/calmjs
src/calmjs/ui.py
prompt
def prompt(question, validator=None, choices=None, default_key=NotImplemented, normalizer=str.lower, _stdin=None, _stdout=None): """ Prompt user for question, maybe choices, and get answer. Arguments: question The question to prompt. It will only be prompted once. validator Defaults to None. Must be a callable that takes in a value. The callable should raise ValueError when the value leads to an error, otherwise return a converted value. choices If choices are provided instead, a validator will be constructed using make_choice_validator along with the next default_value argument. Please refer to documentation for that function. default_value See above. normalizer Defaults to str.lower. See above. """ def write_choices(choice_keys, default_key): _stdout.write('(') _stdout.write('/'.join(choice_keys)) _stdout.write(') ') if default_key is not NotImplemented: _stdout.write('[') _stdout.write(choice_keys[default_key]) _stdout.write('] ') if _stdin is None: _stdin = sys.stdin if _stdout is None: _stdout = sys.stdout _stdout.write(question) _stdout.write(' ') if not check_interactive(): if choices and default_key is not NotImplemented: choice_keys = [choice for choice, mapped in choices] write_choices(choice_keys, default_key) display, answer = choices[default_key] _stdout.write(display) _stdout.write('\n') logger.warning( 'non-interactive mode; auto-selected default option [%s]', display) return answer logger.warning( 'interactive code triggered within non-interactive session') _stdout.write('Aborted.\n') return None choice_keys = [] if validator is None: if choices: validator = make_choice_validator( choices, default_key, normalizer) choice_keys = [choice for choice, mapped in choices] else: validator = null_validator answer = NotImplemented while answer is NotImplemented: if choice_keys: write_choices(choice_keys, default_key) _stdout.flush() try: answer = validator( _stdin.readline().strip().encode(locale).decode(locale)) except ValueError as e: _stdout.write('%s\n' % e) _stdout.write(question.splitlines()[-1]) _stdout.write(' ') except KeyboardInterrupt: _stdout.write('Aborted.\n') answer = None return answer
python
def prompt(question, validator=None, choices=None, default_key=NotImplemented, normalizer=str.lower, _stdin=None, _stdout=None): """ Prompt user for question, maybe choices, and get answer. Arguments: question The question to prompt. It will only be prompted once. validator Defaults to None. Must be a callable that takes in a value. The callable should raise ValueError when the value leads to an error, otherwise return a converted value. choices If choices are provided instead, a validator will be constructed using make_choice_validator along with the next default_value argument. Please refer to documentation for that function. default_value See above. normalizer Defaults to str.lower. See above. """ def write_choices(choice_keys, default_key): _stdout.write('(') _stdout.write('/'.join(choice_keys)) _stdout.write(') ') if default_key is not NotImplemented: _stdout.write('[') _stdout.write(choice_keys[default_key]) _stdout.write('] ') if _stdin is None: _stdin = sys.stdin if _stdout is None: _stdout = sys.stdout _stdout.write(question) _stdout.write(' ') if not check_interactive(): if choices and default_key is not NotImplemented: choice_keys = [choice for choice, mapped in choices] write_choices(choice_keys, default_key) display, answer = choices[default_key] _stdout.write(display) _stdout.write('\n') logger.warning( 'non-interactive mode; auto-selected default option [%s]', display) return answer logger.warning( 'interactive code triggered within non-interactive session') _stdout.write('Aborted.\n') return None choice_keys = [] if validator is None: if choices: validator = make_choice_validator( choices, default_key, normalizer) choice_keys = [choice for choice, mapped in choices] else: validator = null_validator answer = NotImplemented while answer is NotImplemented: if choice_keys: write_choices(choice_keys, default_key) _stdout.flush() try: answer = validator( _stdin.readline().strip().encode(locale).decode(locale)) except ValueError as e: _stdout.write('%s\n' % e) _stdout.write(question.splitlines()[-1]) _stdout.write(' ') except KeyboardInterrupt: _stdout.write('Aborted.\n') answer = None return answer
[ "def", "prompt", "(", "question", ",", "validator", "=", "None", ",", "choices", "=", "None", ",", "default_key", "=", "NotImplemented", ",", "normalizer", "=", "str", ".", "lower", ",", "_stdin", "=", "None", ",", "_stdout", "=", "None", ")", ":", "de...
Prompt user for question, maybe choices, and get answer. Arguments: question The question to prompt. It will only be prompted once. validator Defaults to None. Must be a callable that takes in a value. The callable should raise ValueError when the value leads to an error, otherwise return a converted value. choices If choices are provided instead, a validator will be constructed using make_choice_validator along with the next default_value argument. Please refer to documentation for that function. default_value See above. normalizer Defaults to str.lower. See above.
[ "Prompt", "user", "for", "question", "maybe", "choices", "and", "get", "answer", "." ]
b9b407c2b6a7662da64bccba93bb8d92e7a5fafd
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/ui.py#L104-L190
train
45,699