code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
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 + ''.joi...
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'
3.021398
3.178304
0.950632
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.lower() == 'volume')): mirror_list = self.xcli_client.cmd.mirror_list(scope='Volume') for xcli_mirror in mirr...
returns a map volume_name -> volume, cg_name->cg scope is either None or CG or Volume
null
null
null
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.iscsi_ports port_names.extend(fc_ports.split(',') if fc_ports != '' else []) port_names.extend(iscsi_ports.sp...
return a list of the port names of XIV host
null
null
null
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.get_hosts_by_name(host_name)) return port_names
return a list of the port names under XIV CLuster
null
null
null
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)
remove all stale clients from pool
2.909803
2.36112
1.232382
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_conn...
def get(self, user, password, endpoints)
Gets an existing connection or opens a new one
2.783186
2.841449
0.979495
suffixes = suffixes or [ 'bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] order = int(log2(value) / 10) if value else 0 return '{:.4g} {}'.format(value / (1 << (order * 10)), suffixes[order])
def size(value: int, suffixes: list = None) -> str
>>> size(1024) '1 KB'
2.512638
2.189679
1.147492
if isinstance(value, (int, float)): return value elif not pattern_valid.fullmatch(value): raise ValueError(value) result = 0 for m in pattern.finditer(value): v = m.groupdict() n = int(v['n']) unit = v['unit'] if not unit: result += n ...
def parse_size(value)
>>> parse_size('1M') 1048576 >>> parse_size('512K512K') 1048576 >>> parse_size('512K 512K') 1048576 >>> parse_size('512K 512K 4') 1048580
3.178423
3.308726
0.960618
if isinstance(value, (int, float)): return value elif not pattern_valid.fullmatch(value): raise ValueError(value) result = 0 for m in pattern.finditer(value): v = m.groupdict() n = int(v['n']) unit = v['unit'] if not unit: result += n ...
def parse_duration(value)
>>> parse_duration('1h') 3600 >>> parse_duration('1m') 60 >>> parse_duration('1m 2s') 62 >>> parse_duration('1') 1
2.794204
2.887496
0.967691
# verify properties event_properties = dict() if (properties is None) else properties if type(event_properties) is not dict: raise TypeError('properties is not dict') # prepare event event_bunch = Bunch( Product=self.product_name, Ver...
def send_event(self, action, properties, event_severity=EVENT_SEVERITY)
send css_event and if fails send custom_event instead Args: action (ACTIONS): the action causing the event properties (dict): the action additional properties event_severity (string): the event severity Raises: XCLIError: if the xcli.cmd.custom_event faile...
3.0556
2.726463
1.120719
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
null
null
null
# pylint: disable=W0212 t, v, tb = sys.exc_info() if not t: return wrapping_exc wrapping_exc._inner_exc = v lines = traceback.format_exception(t, v, tb) wrapping_exc._inner_tb = "".join(lines[1:]) return wrapping_exc
def chained(wrapping_exc)
Embeds the current exception information into the given one (which will replace the current one). For example:: try: ... except OSError as ex: raise chained(MyError("database not found!"))
3.566025
4.513216
0.790129
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)
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...
6.51977
7.241845
0.900291
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)
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. ...
8.313314
9.604073
0.865603
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)
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. ...
6.656247
7.248192
0.918332
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)
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 specif...
4.949789
5.507275
0.898773
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.val...
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 sp...
3.725592
3.986432
0.934568
return self._make_req(endpoints.MATCH, dict( k=self.key, mp=match_id), 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.
15.504826
19.397411
0.799324
from aioworkers.storage.filesystem import FileSystemStorage if not isinstance(storage_dest, FileSystemStorage): return super().copy(key_source, storage_dest, key_dest) url = self.raw_key(key_source) logger = self.context.logger async with self._semaphore: ...
async def copy(self, key_source, storage_dest, key_dest)
Return True if data are copied * optimized for http->fs copy * not supported return_status
2.771867
2.687495
1.031394
h = stref p = [] m = None try: r = importlib.util.find_spec(stref) except (AttributeError, ImportError): r = None if r is not None: return importlib.import_module(stref) while '.' in h: h, t = h.rsplit('.', 1) p.append(t) if h in sys.mod...
def import_name(stref: str)
>>> import_name('datetime.datetime.utcnow') is not None True >>> import_name('aioworkers.utils.import_name') is not None True
2.342685
2.492387
0.939936
self._contexts.append(self._contexts[-1].copy()) self.set_options(**options) try: yield finally: self._contexts.pop(-1)
def options(self, **options)
A context-manager for setting connection options; the original values of the options will be restored when the context-manager exits. For example:: with c.options(gui_mode = False): c.cmd.vol_list()
4.696456
4.550803
1.032006
opt2 = self._contexts[-1] for k, v in options.items(): k2 = k.replace("_", "-") if v is None: opt2.pop(k2, None) else: opt2[k2] = v
def set_options(self, **options)
Sets the value of the given options (as keyword arguments). Note that underscored in the option's name will be replaced with hyphens (i.e., ``c.set_options(gui_mode = True)`` will set the option ``gui-mode``)
3.492731
3.28324
1.063806
if isinstance(endpoints, basestring): endpoints = [endpoints] transport = SingleEndpointTransport( SocketTransport.connect_ssl, endpoints, ca_certs=ca_certs, validate=validate) return cls(transport, user, password)
def connect_ssl(cls, user, password, endpoints, ca_certs=None, validate=None)
Creates an SSL transport to the first endpoint (aserver) to which we successfully connect
4.171908
4.29836
0.970581
if isinstance(endpoints, basestring): endpoints = [endpoints] client, transport = cls._initiate_client_for_multi_endpoint(user, password, endpoints...
def connect_multiendpoint_ssl(cls, user, password, endpoints, auto_discover=True, ca_certs=None, validate=None)
Creates a MultiEndpointTransport, so that if the current endpoint (aserver) fails, it would automatically move to the next available endpoint. If ``auto_discover`` is ``True``, we will execute ipinterface_list on the system to discover all management IP interfaces and add them t...
4.895545
4.190177
1.168338
data = self._build_command(cmd, kwargs, self._contexts[-1], remote_target) with self._lock: rootelem = self.transport.send(data) try: return self._build_response(rootelem) except ElementNotFoundException: xlo...
def execute_remote(self, remote_target, cmd, **kwargs)
Executes the given command (with the given arguments) on the given remote target of the connected machine
7.301114
7.808091
0.93507
return XCLIClientForUser(weakproxy(self), user, password, populate=populate)
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
20.281424
24.025116
0.844176
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)
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
7.48804
7.567726
0.98947
with self.options(user=user, password=password): yield self
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()
8.055981
19.297623
0.41746
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.count...
def accuracy(self, mode: OsuMode)
Calculated accuracy. See Also -------- <https://osu.ppy.sh/help/wiki/Accuracy>
1.71444
1.718616
0.99757
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 n...
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
null
null
null
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.name
return all non snapshots volumes in cg
null
null
null
''' 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), ...
def _certificate_required(cls, hostname, port=XCLI_DEFAULT_PORT, ca_certs=None, validate=None)
returns true if connection should verify certificate
9.285948
7.824953
1.18671
if isinstance(klass, str): klass = import_name(klass) item = klass, conv, score cls.converters.append(item) cls.converters.sort(key=lambda x: x[0]) return cls
def add_converter(cls, klass, conv, score=0)
Add converter :param klass: class or str :param conv: callable :param score: :return:
3.54686
3.424944
1.035597
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( ...
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.
3.217395
2.988318
1.076658
path = self.RETURN_PATH if response_path is not None: path += "/" + response_path response_element = self.response_etree.find(path) if response_element is None: return for subelement in self.response_etree.find(path).getchildren(): if ...
def all(self, element_type=None, response_path=None)
Generates Bunches, each representing a single subelement of the response. If an element_type is requested, only elements whose tag matches the element_type are returned. If the response has no subelements (for example, in a <return>-less command), yields None.
3.631953
3.001268
1.210139
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_r...
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
4.060575
3.966338
1.023759
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)
Return the objects for each individual set flag.
5.86675
4.963447
1.181991
return self.value == other.value or self.value & other.value
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.
5.794437
6.109057
0.948499
cumulative_elapsed_time = self.get_cumulative_elapsed_time() sum_elapsed_time = sum(cumulative_elapsed_time, datetime.timedelta()) if not sum_elapsed_time: raise ValueError("cannot get percentage if there is no any elapsed time") return [div_timedelta(t, sum_elapsed_...
def get_percentage(self)
Get the cumulative time percentage of each stopwatch (including the current split). Returns ------- cumulative_elapsed_time_percentage : List[float]
4.396631
3.967679
1.108112
return [div_timedelta(sum(stopwatch.split_elapsed_time, datetime.timedelta()), len(stopwatch.split_elapsed_time)) if stopwatch.split_elapsed_time else datetime.timedelta() for stopwatch in self]
def get_mean_per_split(self)
Get the mean elapsed time per split of each stopwatch (excluding the current split). Returns ------- mean_elapsed_time_per_split : List[datetime.timedelta]
6.45892
4.545362
1.420991
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)
Get all statistics as a dictionary. Returns ------- statistics : Dict[str, List]
3.627919
4.007736
0.905229
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.l...
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 passe...
6.075898
6.067453
1.001392
raise NotImplementedError("load_target must be overridden")
def load_target(cls, scheme, path, fragment, username, password, hostname, port, query, load_method, **kwargs)
Override this method to use values from the parsed uri to initialize the expected target.
11.642466
10.962566
1.06202
'''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) + "{} request...
def hog(concurrency, requests, limit, timeout, params, paramfile, headers, headerfile, method, url)
Sending multiple `HTTP` requests `ON` `GREEN` thread
5.448866
4.309073
1.26451
_tabs = '\t' * self._tctr _keys = '{tabs}<key>{name}</key>\n'.format(tabs=_tabs, name=_name) _file.seek(self._sptr, os.SEEK_SET) _file.write(_keys) self._append_dict(value, _file)
def _append_value(self, value, _file, _name)
Call this function to write contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file * _name - str, name of current content dict
5.346694
6.845952
0.781001
_tabs = '\t' * self._tctr _labs = '{tabs}<array>\n'.format(tabs=_tabs) _file.write(_labs) self._tctr += 1 for _item in value: if _item is None: continue _item = self.object_hook(_item) _type = type(_item).__name__ ...
def _append_array(self, value, _file)
Call this function to write array contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
3.081105
3.355109
0.918332
_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>{i...
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
2.801366
3.013157
0.929711
# 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) # ...
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
4.327239
4.582908
0.944212
_tabs = '\t' * self._tctr _text = value.strftime('%Y-%m-%dT%H:%M:%S.%fZ') _labs = '{tabs}<date>{text}</date>\n'.format(tabs=_tabs, text=_text) _file.write(_labs)
def _append_date(self, value, _file)
Call this function to write date contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
4.764006
5.823505
0.818065
_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)
Call this function to write integer contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
7.895438
10.042708
0.786186
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)
Register proper and improper file mappings.
2.795422
2.252768
1.240883
for ep in pkg_resources.iter_entry_points('yamlsettings10'): ext = ep.load() if callable(ext): ext = ext() self.add(ext)
def _discover(self)
Find and install all extensions
8.130645
5.736619
1.417323
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)
Retrieve extension for the given protocol :param protocol: name of the protocol :type protocol: string :raises NoProtocolError: no extension registered for protocol
3.893977
3.507016
1.110339
index = len(self.extensions) self.extensions[index] = extension for protocol in extension.protocols: self.registry[protocol] = index
def add(self, extension)
Adds an extension to the registry :param extension: Extension object :type extension: yamlsettings.extensions.base.YamlSettingsExtension
4.399946
5.842585
0.753082
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 co...
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
4.949212
5.21728
0.948619
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...
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
17.007517
15.738139
1.080656
''' Load *all* YAML settings from a list of file paths given. - File paths in the list gets the priority by their orders of the list. ''' yaml_series = self._load_first( target_uris, yamlsettings.yamldict.load_all, **kwargs ) yaml_dict...
def load_all(self, target_uris, **kwargs)
Load *all* YAML settings from a list of file paths given. - File paths in the list gets the priority by their orders of the list.
10.588613
3.755497
2.819497
loader = YAMLDictLoader(stream) try: while loader.check_data(): yield loader.get_data() finally: loader.dispose()
def load_all(stream)
Parse all YAML documents in a stream and produce corresponding YAMLDict objects.
4.155402
3.334531
1.246173
return yaml.dump_all( [data], stream=stream, Dumper=YAMLDictDumper, **kwargs )
def dump(data, stream=None, **kwargs)
Serialize YAMLDict into a YAML stream. If stream is None, return the produced string instead.
4.545763
3.80186
1.195668
return yaml.dump_all( data_list, stream=stream, Dumper=YAMLDictDumper, **kwargs )
def dump_all(data_list, stream=None, **kwargs)
Serialize YAMLDict into a YAML stream. If stream is None, return the produced string instead.
3.807907
3.036124
1.2542
''' Traverse through all keys and values (in-order) and replace keys and values with the return values from the callback function. ''' def _traverse_node(path, node, callback): ret_val = callback(path, node) if ret_val is not None: ...
def traverse(self, callback)
Traverse through all keys and values (in-order) and replace keys and values with the return values from the callback function.
3.062549
2.409954
1.270792
''' Update the content (i.e. keys and values) with yaml_dict. ''' def _update_node(base_node, update_node): if isinstance(update_node, YAMLDict) or \ isinstance(update_node, dict): if not (isinstance(base_node, YAMLDict)): # NOT...
def update(self, yaml_dict)
Update the content (i.e. keys and values) with yaml_dict.
2.36167
2.15995
1.093391
''' 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)
Use yaml_dict as self's new base and update with existing reverse of update.
10.858291
3.190012
3.403841
''' 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)
Remove all keys other than the keys specified.
2.836685
2.307484
1.229341
''' Save YAML settings to the specified file path. ''' yamldict.dump(yaml_dict, open(filepath, 'w'), default_flow_style=False)
def save(yaml_dict, filepath)
Save YAML settings to the specified file path.
4.862589
3.608594
1.347502
''' Save *all* YAML settings to the specified file path. ''' yamldict.dump_all(yaml_dicts, open(filepath, 'w'), default_flow_style=False)
def save_all(yaml_dicts, filepath)
Save *all* YAML settings to the specified file path.
5.844497
4.306303
1.357196
''' 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)
Override YAML settings with loaded values from filepaths. - File paths in the list gets the priority by their orders of the list.
20.546915
5.012551
4.099093
''' 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...
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.
5.895021
3.128047
1.884569
_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)
Draw a circle
2.7565
2.764585
0.997075
ctx = _state["ctx"] ctx.move_to(0, 0) ctx.line_to(x, y) ctx.close_path() # _ctx.set_source_rgb (0.3, 0.2, 0.5) ctx.set_line_width(width) ctx.stroke()
def line(x, y, width=0.1)
Draw a line
3.199786
3.171794
1.008825
# 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)
Draw a triangle
2.933796
2.925276
1.002912
half_side = side / 2 _state["ctx"].rectangle(-half_side, -half_side, side, side) _state["ctx"].fill()
def box(side=1)
Draw a box
4.360028
4.15309
1.049827
with open(self._file, 'w') as _file: _file.write(self._hsrt) self._sptr = _file.tell() _file.write(self._hend)
def _dump_header(self)
Initially dump file heads and tails.
6.471282
5.520843
1.172155
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
Simulate behaviour of "from package_name._version import VERSION", and return VERSION.
2.886009
2.067884
1.395634
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]
Find packages to pack.
4.26597
3.924886
1.086903
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 r...
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.
2.742362
2.750054
0.997203
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: ...
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.
2.650442
2.484523
1.066781
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...
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.
2.555902
2.429777
1.051908
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
Parse text assuming it's an RST markup.
1.732584
1.534557
1.129045
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: ...
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>`_.
3.337964
3.452771
0.966749
# 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(): ...
def visit_reference(self, node: docutils.nodes.reference) -> None
Called for "reference" nodes.
3.834842
3.604542
1.063892
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]
Return first existing of given class field names.
3.173023
2.795894
1.134887
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.vers...
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.
3.36788
2.715407
1.240285
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: ...
def prepare(cls) -> None
Fill in possibly missing package metadata.
2.58734
2.316843
1.116752
cls.prepare() setuptools.setup( name=cls.name, version=cls.version, description=cls.description, long_description=cls.long_description, url=cls.url, download_url=cls.download_url, author=cls.author, author_email=cls.author_email, maintainer=cls.tr...
def setup(cls) -> None
Run setuptools.setup() with correct arguments.
1.991575
1.853635
1.074416
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)
Renders current buffer surface to IPython image
2.522663
2.162617
1.166486
image_surface = render_record_surface() img = 0 + np.frombuffer(image_surface.get_data(), np.uint8) img.shape = (HEIGHT, WIDTH, 4) img = img[:, :, [2, 1, 0, 3]] if y_origin == "bottom": img = img[::-1] return img if transparent else img[:, :, : 3]
def get_npimage(transparent=False, y_origin="top")
Returns a WxHx[3-4] numpy array representing the RGB picture. If `transparent` is True the image is WxHx4 and represents a RGBA picture, i.e. array[i,j] is the [r,g,b,a] value of the pixel at position [i,j]. If `transparent` is false, a RGB array is returned. Parameter y_origin ("top" or "bottom") dec...
4.063409
4.372036
0.929409
def wrapper(*args, **kwargs): 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 m...
def check_limits(user_rule)
Stop recursion if resolution is too low on number of components is too high
5.109843
4.918478
1.038907
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: ...
def init(canvas_size=(512, 512), max_depth=12, face_color=None, background_color=None)
Initializes global state
3.614354
3.560004
1.015267
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)
function to convert HTML-styly color string to RGB values Args: s: Color in HTML format Returns: list of three RGB color components
2.590874
2.943185
0.880296
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 temp...
def compile_string(self, data, source_path=None, is_two_file=True, post=None, lang=None)
Compile docstrings into HTML strings, with shortcode support.
4.751556
4.530253
1.04885
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) ...
def compile(self, source, dest, is_two_file=True, post=None, lang=None)
Compile the docstring into HTML and save as dest.
3.714104
3.721341
0.998055
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)) ...
def create_post(self, path, **kw)
Create a new post.
3.967982
3.869775
1.025378
if self._flag: _keys = _name + '\n' else: _keys = '\n' + _name + '\n' _file.seek(self._sptr, os.SEEK_SET) _file.write(_keys) self._bctr = collections.defaultdict(int) # blank branch counter dict self._append_branch(value, _file)
def _append_value(self, value, _file, _name)
Call this function to write contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file * _name - str, name of current content dict
6.634733
7.159046
0.926762
if not value: self._append_none(None, _file) return _bptr = '' _tabs = '' _tlen = len(value) - 1 if _tlen: _bptr = ' |-->' for _ in range(self._tctr + 1): _tabs += _TEMP_SPACES if self._bctr[_] else _TEMP_...
def _append_array(self, value, _file)
Call this function to write array contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
5.217049
5.243137
0.995024
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__ fla...
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
3.428113
3.389293
1.011454
# binascii.b2a_base64(value) -> plistlib.Data # binascii.a2b_base64(Data) -> value(bytes) if not value: self._append_none(None, _file) return if len(value) > 16: _tabs = '' for _ in range(self._tctr + 1): _tabs += ...
def _append_bytes(self, value, _file)
Call this function to write bytes contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
4.601279
4.658662
0.987682
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
null
null
null
_tabs = '\t' * self._tctr _cmma = ',\n' if self._vctr[self._tctr] else '' _keys = '{cmma}{tabs}"{name}" :'.format(cmma=_cmma, tabs=_tabs, name=_name) _file.seek(self._sptr, os.SEEK_SET) _file.write(_keys) self._vctr[self._tctr] += 1 self._append_object(...
def _append_value(self, value, _file, _name)
Call this function to write contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file * _name - str, name of current content dict
5.084678
5.528496
0.919722
_labs = ' [' _file.write(_labs) self._tctr += 1 for _item in value: _cmma = ',' if self._vctr[self._tctr] else '' _file.write(_cmma) self._vctr[self._tctr] += 1 _item = self.object_hook(_item) _type = type(_item).__...
def _append_array(self, value, _file)
Call this function to write array contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
4.390567
4.621722
0.949985