text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def get_version(filename, encoding='utf8'): """ Get __version__ definition out of a source file """ with io.open(filename, encoding=encoding) as sourcecode: for line in sourcecode: version = RE_VERSION.match(line) if version: return version.group(1) ...
[ "def", "get_version", "(", "filename", ",", "encoding", "=", "'utf8'", ")", ":", "with", "io", ".", "open", "(", "filename", ",", "encoding", "=", "encoding", ")", "as", "sourcecode", ":", "for", "line", "in", "sourcecode", ":", "version", "=", "RE_VERSI...
26.666667
0.003021
def filepath_to_uri(path): """ Convert an file system path to a URI portion that is suitable for inclusion in a URL. We are assuming input is either UTF-8 or unicode already. This method will encode certain chars that would normally be recognized as special chars for URIs. Note that this meth...
[ "def", "filepath_to_uri", "(", "path", ")", ":", "if", "path", "is", "None", ":", "return", "path", "# I know about `os.sep` and `os.altsep` but I want to leave", "# some flexibility for hardcoding separators.", "return", "urllib", ".", "quote", "(", "path", ".", "replace...
36.9
0.001321
def primaryName(self, value: Optional[str]) -> None: """ Set the value of isPrimary. :param value: the value to set isPrimary to """ if value is not None: self.warned_no_primary = False self.primaryNames[self.viewNo] = value self.compact_primary_names...
[ "def", "primaryName", "(", "self", ",", "value", ":", "Optional", "[", "str", "]", ")", "->", "None", ":", "if", "value", "is", "not", "None", ":", "self", ".", "warned_no_primary", "=", "False", "self", ".", "primaryNames", "[", "self", ".", "viewNo",...
39.619048
0.002347
def get_model(self): """ Gets the mongoengine model for this tool, which serializes parameters that are functions :return: The mongoengine model. TODO: Note that the tool version is currently incorrect (0.0.0) """ return ToolModel( name=self.name, versio...
[ "def", "get_model", "(", "self", ")", ":", "return", "ToolModel", "(", "name", "=", "self", ".", "name", ",", "version", "=", "\"0.0.0\"", ",", "parameters", "=", "self", ".", "parameters_from_dicts", "(", "self", ".", "parameters", ")", ")" ]
33
0.009828
def _get_virtualenv_hash(self, name): """Get the name of the virtualenv adjusted for windows if needed Returns (name, encoded_hash) """ def get_name(name, location): name = self._sanitize(name) hash = hashlib.sha256(location.encode()).digest()[:6] en...
[ "def", "_get_virtualenv_hash", "(", "self", ",", "name", ")", ":", "def", "get_name", "(", "name", ",", "location", ")", ":", "name", "=", "self", ".", "_sanitize", "(", "name", ")", "hash", "=", "hashlib", ".", "sha256", "(", "location", ".", "encode"...
37.65
0.001942
def emails_parse(emails_dict): """ Parse the output of ``SESConnection.list_verified_emails()`` and get a list of emails. """ result = emails_dict['ListVerifiedEmailAddressesResponse'][ 'ListVerifiedEmailAddressesResult'] emails = [email for email in result['VerifiedEmailAddresses']] ...
[ "def", "emails_parse", "(", "emails_dict", ")", ":", "result", "=", "emails_dict", "[", "'ListVerifiedEmailAddressesResponse'", "]", "[", "'ListVerifiedEmailAddressesResult'", "]", "emails", "=", "[", "email", "for", "email", "in", "result", "[", "'VerifiedEmailAddres...
33.4
0.002915
def help_text(cls): """Return a slack-formatted list of commands with their usage.""" docs = [cmd_func.__doc__ for cmd_func in cls.commands.values()] # Don't want to include 'usage: ' or explanation. usage_lines = [doc.partition('\n')[0] for doc in docs] terse_lines = [line[len(...
[ "def", "help_text", "(", "cls", ")", ":", "docs", "=", "[", "cmd_func", ".", "__doc__", "for", "cmd_func", "in", "cls", ".", "commands", ".", "values", "(", ")", "]", "# Don't want to include 'usage: ' or explanation.", "usage_lines", "=", "[", "doc", ".", "...
49.111111
0.004444
def command(state, args): """Watch an anime.""" if len(args) < 2: print(f'Usage: {args[0]} {{ID|aid:AID}} [EPISODE]') return aid = state.results.parse_aid(args[1], default_key='db') anime = query.select.lookup(state.db, aid) if len(args) < 3: episode = anime.watched_episodes ...
[ "def", "command", "(", "state", ",", "args", ")", ":", "if", "len", "(", "args", ")", "<", "2", ":", "print", "(", "f'Usage: {args[0]} {{ID|aid:AID}} [EPISODE]'", ")", "return", "aid", "=", "state", ".", "results", ".", "parse_aid", "(", "args", "[", "1"...
32.296296
0.001114
def _query_once(self, urls): """Perform a single POST request using lookup API. :param urls: a sequence of URLs to put in request body :returns: a response object :raises UnathorizedAPIKeyError: when the API key for this instance is not valid :raises HTTPError: if the HT...
[ "def", "_query_once", "(", "self", ",", "urls", ")", ":", "request_body", "=", "'{}\\n{}'", ".", "format", "(", "len", "(", "urls", ")", ",", "'\\n'", ".", "join", "(", "urls", ")", ")", "response", "=", "post", "(", "self", ".", "_request_address", ...
39.857143
0.002334
def collection_names(self, include_system_collections=True): """Get a list of all the collection names in this database. :Parameters: - `include_system_collections` (optional): if ``False`` list will not include system collections (e.g ``system.indexes``) """ with ...
[ "def", "collection_names", "(", "self", ",", "include_system_collections", "=", "True", ")", ":", "with", "self", ".", "__client", ".", "_socket_for_reads", "(", "ReadPreference", ".", "PRIMARY", ")", "as", "(", "sock_info", ",", "slave_okay", ")", ":", "wire_...
46.538462
0.001619
def _wrap_parse(code, filename): """ async wrapper is required to avoid await calls raising a SyntaxError """ code = 'async def wrapper():\n' + indent(code, ' ') return ast.parse(code, filename=filename).body[0].body[0].value
[ "def", "_wrap_parse", "(", "code", ",", "filename", ")", ":", "code", "=", "'async def wrapper():\\n'", "+", "indent", "(", "code", ",", "' '", ")", "return", "ast", ".", "parse", "(", "code", ",", "filename", "=", "filename", ")", ".", "body", "[", "0...
43.333333
0.007547
def intel_extractor(url, response): """Extract intel from the response body.""" for rintel in rintels: res = re.sub(r'<(script).*?</\1>(?s)', '', response) res = re.sub(r'<[^<]+?>', '', res) matches = rintel[0].findall(res) if matches: for match in matches: ...
[ "def", "intel_extractor", "(", "url", ",", "response", ")", ":", "for", "rintel", "in", "rintels", ":", "res", "=", "re", ".", "sub", "(", "r'<(script).*?</\\1>(?s)'", ",", "''", ",", "response", ")", "res", "=", "re", ".", "sub", "(", "r'<[^<]+?>'", "...
40.1
0.002439
def query(self, *, samples=False, any_samples=False, time=False, primitives=False) -> 'Query': ''' Create a :py:class:`Query` object. Keyword Args: samples (bool): Query ``GL_SAMPLES_PASSED`` or not. any_samples (bool): Query ``GL_ANY_SAMPLES_PASSED`` or ...
[ "def", "query", "(", "self", ",", "*", ",", "samples", "=", "False", ",", "any_samples", "=", "False", ",", "time", "=", "False", ",", "primitives", "=", "False", ")", "->", "'Query'", ":", "res", "=", "Query", ".", "__new__", "(", "Query", ")", "r...
36.727273
0.003619
def load_tool_info(tool_name): """ Load the tool-info class. @param tool_name: The name of the tool-info module. Either a full Python package name or a name within the benchexec.tools package. @return: A tuple of the full name of the used tool-info module and an instance of the tool-info class. ...
[ "def", "load_tool_info", "(", "tool_name", ")", ":", "tool_module", "=", "tool_name", "if", "'.'", "in", "tool_name", "else", "(", "\"benchexec.tools.\"", "+", "tool_name", ")", "try", ":", "tool", "=", "__import__", "(", "tool_module", ",", "fromlist", "=", ...
51
0.008424
def Push(cls, connection, datafile, filename, st_mode=DEFAULT_PUSH_MODE, mtime=0, progress_callback=None): """Push a file-like object to the device. Args: connection: ADB connection datafile: File-like object for reading from filename: Filename to push to ...
[ "def", "Push", "(", "cls", ",", "connection", ",", "datafile", ",", "filename", ",", "st_mode", "=", "DEFAULT_PUSH_MODE", ",", "mtime", "=", "0", ",", "progress_callback", "=", "None", ")", ":", "fileinfo", "=", "(", "'{},{}'", ".", "format", "(", "filen...
35.133333
0.003692
def get_cache_returns(self, jid): ''' Execute a single pass to gather the contents of the job cache ''' ret = {} try: data = self.returners['{0}.get_jid'.format(self.opts['master_job_cache'])](jid) except Exception as exc: raise SaltClientError('C...
[ "def", "get_cache_returns", "(", "self", ",", "jid", ")", ":", "ret", "=", "{", "}", "try", ":", "data", "=", "self", ".", "returners", "[", "'{0}.get_jid'", ".", "format", "(", "self", ".", "opts", "[", "'master_job_cache'", "]", ")", "]", "(", "jid...
38.333333
0.00377
def deliver_hook(instance, target, payload_override=None): """ Deliver the payload to the target URL. By default it serializes to JSON and POSTs. """ payload = payload_override or serialize_hook(instance) if hasattr(settings, 'HOOK_DELIVERER'): deliverer = get_module(settings.HOOK_DELIV...
[ "def", "deliver_hook", "(", "instance", ",", "target", ",", "payload_override", "=", "None", ")", ":", "payload", "=", "payload_override", "or", "serialize_hook", "(", "instance", ")", "if", "hasattr", "(", "settings", ",", "'HOOK_DELIVERER'", ")", ":", "deliv...
32.166667
0.001678
def generate_pseudo(strain_states, order=3): """ Generates the pseudoinverse for a given set of strains. Args: strain_states (6xN array like): a list of voigt-notation "strain-states", i. e. perturbed indices of the strain as a function of the smallest strain e. g. (0, 1, 0,...
[ "def", "generate_pseudo", "(", "strain_states", ",", "order", "=", "3", ")", ":", "s", "=", "sp", ".", "Symbol", "(", "'s'", ")", "nstates", "=", "len", "(", "strain_states", ")", "ni", "=", "np", ".", "array", "(", "strain_states", ")", "*", "s", ...
39.512821
0.000633
def check_docstring(cls): """ Asserts that the class has a docstring, returning it if successful. """ docstring = inspect.getdoc(cls) if not docstring: breadcrumbs = " -> ".join(t.__name__ for t in inspect.getmro(cls)[:-1][::-1]) msg = "docstring required ...
[ "def", "check_docstring", "(", "cls", ")", ":", "docstring", "=", "inspect", ".", "getdoc", "(", "cls", ")", "if", "not", "docstring", ":", "breadcrumbs", "=", "\" -> \"", ".", "join", "(", "t", ".", "__name__", "for", "t", "in", "inspect", ".", "getmr...
44.45
0.004405
def scaled_tile(self, tile): '''return a scaled tile''' width = int(TILES_WIDTH / tile.scale) height = int(TILES_HEIGHT / tile.scale) full_tile = self.load_tile(tile) scaled_tile = cv2.resize(full_tile, (height, width)) return scaled_tile
[ "def", "scaled_tile", "(", "self", ",", "tile", ")", ":", "width", "=", "int", "(", "TILES_WIDTH", "/", "tile", ".", "scale", ")", "height", "=", "int", "(", "TILES_HEIGHT", "/", "tile", ".", "scale", ")", "full_tile", "=", "self", ".", "load_tile", ...
40
0.006993
def largest_sphere(target, fixed_diameter='pore.fixed_diameter', iters=5): r""" Finds the maximum diameter pore that can be placed in each location without overlapping any neighbors. This method iteratively expands pores by increasing their diameter to encompass half of the distance to the nearest ...
[ "def", "largest_sphere", "(", "target", ",", "fixed_diameter", "=", "'pore.fixed_diameter'", ",", "iters", "=", "5", ")", ":", "network", "=", "target", ".", "project", ".", "network", "P12", "=", "network", "[", "'throat.conns'", "]", "C1", "=", "network", ...
43.728571
0.000319
def build_options_str(self, options): '''Returns a string concatenation of the MeCab options. Args: options: dictionary of options to use when instantiating the MeCab instance. Returns: A string concatenation of the options used when instantiatin...
[ "def", "build_options_str", "(", "self", ",", "options", ")", ":", "opts", "=", "[", "]", "for", "name", "in", "iter", "(", "list", "(", "self", ".", "_SUPPORTED_OPTS", ".", "values", "(", ")", ")", ")", ":", "if", "name", "in", "options", ":", "ke...
36.954545
0.002398
def subscribe(self, event, hook): """ Subscribe a callback to an event Parameters ---------- event : str Available events are 'precall', 'postcall', and 'capacity'. precall is called with: (connection, command, query_kwargs) postcall is called...
[ "def", "subscribe", "(", "self", ",", "event", ",", "hook", ")", ":", "if", "hook", "not", "in", "self", ".", "_hooks", "[", "event", "]", ":", "self", ".", "_hooks", "[", "event", "]", ".", "append", "(", "hook", ")" ]
35.875
0.006791
def _get_MRIO_system(path): """ Extract system information (ixi, pxp) from file path. Returns 'ixi' or 'pxp', None in undetermined """ ispxp = True if re.search('pxp', path, flags=re.IGNORECASE) else False isixi = True if re.search('ixi', path, flags=re.IGNORECASE) else False if ispxp == isixi...
[ "def", "_get_MRIO_system", "(", "path", ")", ":", "ispxp", "=", "True", "if", "re", ".", "search", "(", "'pxp'", ",", "path", ",", "flags", "=", "re", ".", "IGNORECASE", ")", "else", "False", "isixi", "=", "True", "if", "re", ".", "search", "(", "'...
30.923077
0.002415
def _make_style_str(styledict): """ Make an SVG style string from the dictionary. See also _parse_style_str also. """ s = '' for key in list(styledict.keys()): s += "%s:%s;" % (key, styledict[key]) return s
[ "def", "_make_style_str", "(", "styledict", ")", ":", "s", "=", "''", "for", "key", "in", "list", "(", "styledict", ".", "keys", "(", ")", ")", ":", "s", "+=", "\"%s:%s;\"", "%", "(", "key", ",", "styledict", "[", "key", "]", ")", "return", "s" ]
28.875
0.008403
def numparser(strict=False): """Return a function that will attempt to parse the value as a number, trying :func:`int`, :func:`long`, :func:`float` and :func:`complex` in that order. If all fail, return the value as-is, unless ``strict=True``, in which case raise the underlying exception. """ ...
[ "def", "numparser", "(", "strict", "=", "False", ")", ":", "def", "f", "(", "v", ")", ":", "try", ":", "return", "int", "(", "v", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "pass", "try", ":", "return", "long", "(", "v", ")", ...
26.137931
0.001272
def load(cls, directory): """Load a Digest from a `.digest` file adjacent to the given directory. :return: A Digest, or None if the Digest did not exist. """ read_file = maybe_read_file(cls._path(directory)) if read_file: fingerprint, length = read_file.split(':') return Digest(fingerpr...
[ "def", "load", "(", "cls", ",", "directory", ")", ":", "read_file", "=", "maybe_read_file", "(", "cls", ".", "_path", "(", "directory", ")", ")", "if", "read_file", ":", "fingerprint", ",", "length", "=", "read_file", ".", "split", "(", "':'", ")", "re...
32.272727
0.010959
def publish(self, topic=None, msg=None, modname=None, pre_fire_hook=None, **kw): """ Send a message over the publishing zeromq socket. >>> import fedmsg >>> fedmsg.publish(topic='testing', modname='test', msg={ ... 'test': "Hello World", ...
[ "def", "publish", "(", "self", ",", "topic", "=", "None", ",", "msg", "=", "None", ",", "modname", "=", "None", ",", "pre_fire_hook", "=", "None", ",", "*", "*", "kw", ")", ":", "topic", "=", "topic", "or", "'unspecified'", "msg", "=", "msg", "or",...
41.546053
0.000619
def _get_all_run_infos(self): """Find the RunInfos for all runs since the last clean-all.""" info_dir = self._settings.info_dir if not os.path.isdir(info_dir): return [] paths = [os.path.join(info_dir, x) for x in os.listdir(info_dir)] # We copy the RunInfo as a dict, so we can add stuff to i...
[ "def", "_get_all_run_infos", "(", "self", ")", ":", "info_dir", "=", "self", ".", "_settings", ".", "info_dir", "if", "not", "os", ".", "path", ".", "isdir", "(", "info_dir", ")", ":", "return", "[", "]", "paths", "=", "[", "os", ".", "path", ".", ...
45.071429
0.006211
def window_size(self, window_size): """ set the render window size """ BasePlotter.window_size.fset(self, window_size) self.app_window.setBaseSize(*window_size)
[ "def", "window_size", "(", "self", ",", "window_size", ")", ":", "BasePlotter", ".", "window_size", ".", "fset", "(", "self", ",", "window_size", ")", "self", ".", "app_window", ".", "setBaseSize", "(", "*", "window_size", ")" ]
45.25
0.01087
def getCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): """Creates a generator to perform SNMP GET query. When iterator gets advanced by :py:mod:`asyncio` main loop, SNMP GET request is send (:RFC:`1905#section-4.2.1`). The iterator yields :py:class:`asyncio.Fut...
[ "def", "getCmd", "(", "snmpEngine", ",", "authData", ",", "transportTarget", ",", "contextData", ",", "*", "varBinds", ",", "*", "*", "options", ")", ":", "def", "__cbFun", "(", "snmpEngine", ",", "sendRequestHandle", ",", "errorIndication", ",", "errorStatus"...
33.757009
0.00269
def delete_package_version_from_recycle_bin(self, feed_id, package_name, package_version): """DeletePackageVersionFromRecycleBin. [Preview API] Delete a package version from the feed, moving it to the recycle bin. :param str feed_id: Name or ID of the feed. :param str package_name: Name ...
[ "def", "delete_package_version_from_recycle_bin", "(", "self", ",", "feed_id", ",", "package_name", ",", "package_version", ")", ":", "route_values", "=", "{", "}", "if", "feed_id", "is", "not", "None", ":", "route_values", "[", "'feedId'", "]", "=", "self", "...
56.555556
0.006763
def session(self): """Get the DB session associated with the task (open a new one if necessary) Returns: sqlalchemy.orm.session.Session: DB session """ if self._session is None: self._session = self.client.create_session() return self._session
[ "def", "session", "(", "self", ")", ":", "if", "self", ".", "_session", "is", "None", ":", "self", ".", "_session", "=", "self", ".", "client", ".", "create_session", "(", ")", "return", "self", ".", "_session" ]
30
0.009709
def substitute_all(sp_object, pairs): """ Performs multiple substitutions in an expression :param expr: a sympy matrix or expression :param pairs: a list of pairs (a,b) where each a_i is to be substituted with b_i :return: the substituted expression """ if not isinstance(pairs, dict): ...
[ "def", "substitute_all", "(", "sp_object", ",", "pairs", ")", ":", "if", "not", "isinstance", "(", "pairs", ",", "dict", ")", ":", "dict_pairs", "=", "dict", "(", "pairs", ")", "else", ":", "dict_pairs", "=", "pairs", "# we recurse if the object was a matrix s...
33.038462
0.005656
def save_ip_ranges(profile_name, prefixes, force_write, debug, output_format = 'json'): """ Creates/Modifies an ip-range-XXX.json file :param profile_name: :param prefixes: :param force_write: :param debug: :return: """ filename = 'ip-ranges-%s.json' % profile_name ip_ranges = ...
[ "def", "save_ip_ranges", "(", "profile_name", ",", "prefixes", ",", "force_write", ",", "debug", ",", "output_format", "=", "'json'", ")", ":", "filename", "=", "'ip-ranges-%s.json'", "%", "profile_name", "ip_ranges", "=", "{", "}", "ip_ranges", "[", "'createDat...
37.375
0.00489
def to_yaml(cls, dumper, vividict): """Implementation for the abstract method of the base class YAMLObject """ dictionary = cls.vividict_to_dict(vividict) node = dumper.represent_mapping(cls.yaml_tag, dictionary) return node
[ "def", "to_yaml", "(", "cls", ",", "dumper", ",", "vividict", ")", ":", "dictionary", "=", "cls", ".", "vividict_to_dict", "(", "vividict", ")", "node", "=", "dumper", ".", "represent_mapping", "(", "cls", ".", "yaml_tag", ",", "dictionary", ")", "return",...
43.166667
0.007576
def formatBitData(self, pos, width1, width2=0): """Show formatted bit data: Bytes are separated by commas whole bytes are displayed in hex >>> Layout(olleke).formatBitData(6, 2, 16) '|00h|2Eh,|00' >>> Layout(olleke).formatBitData(4, 1, 0) '1' """ r...
[ "def", "formatBitData", "(", "self", ",", "pos", ",", "width1", ",", "width2", "=", "0", ")", ":", "result", "=", "[", "]", "#make empty prefix code explicit", "if", "width1", "==", "0", ":", "result", "=", "[", "'()'", ",", "','", "]", "for", "width",...
43.342105
0.014846
def commands(self): """ :rtype: twilio.rest.wireless.v1.command.CommandList """ if self._commands is None: self._commands = CommandList(self) return self._commands
[ "def", "commands", "(", "self", ")", ":", "if", "self", ".", "_commands", "is", "None", ":", "self", ".", "_commands", "=", "CommandList", "(", "self", ")", "return", "self", ".", "_commands" ]
29.857143
0.009302
def find_case_control(items): """Find case/control items in a population of multiple samples. """ cases = [] controls = [] for data in items: if population.get_affected_status(data) == 1: controls.append(data) else: cases.append(data) return cases, control...
[ "def", "find_case_control", "(", "items", ")", ":", "cases", "=", "[", "]", "controls", "=", "[", "]", "for", "data", "in", "items", ":", "if", "population", ".", "get_affected_status", "(", "data", ")", "==", "1", ":", "controls", ".", "append", "(", ...
28.272727
0.003115
def patch_certificate_signing_request(self, name, body, **kwargs): """ partially update the specified CertificateSigningRequest This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_certifi...
[ "def", "patch_certificate_signing_request", "(", "self", ",", "name", ",", "body", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", "...
78.8
0.004012
def lifecycle_lock(self): """An identity-keyed inter-process lock for safeguarding lifecycle and other operations.""" safe_mkdir(self._metadata_base_dir) return OwnerPrintingInterProcessFileLock( # N.B. This lock can't key into the actual named metadata dir (e.g. `.pids/pantsd/lock` # via `Proce...
[ "def", "lifecycle_lock", "(", "self", ")", ":", "safe_mkdir", "(", "self", ".", "_metadata_base_dir", ")", "return", "OwnerPrintingInterProcessFileLock", "(", "# N.B. This lock can't key into the actual named metadata dir (e.g. `.pids/pantsd/lock`", "# via `ProcessMetadataManager._ge...
60
0.007299
def get_plugin_classes(modules): """Get plugin classes for given modules.""" classes = (_ConnectionPlugin, _ContentPlugin, _ParserPlugin) return loader.get_plugins(modules, classes)
[ "def", "get_plugin_classes", "(", "modules", ")", ":", "classes", "=", "(", "_ConnectionPlugin", ",", "_ContentPlugin", ",", "_ParserPlugin", ")", "return", "loader", ".", "get_plugins", "(", "modules", ",", "classes", ")" ]
47.5
0.005181
def get_config_parameter_loglevel(config: ConfigParser, section: str, param: str, default: int) -> int: """ Get ``loglevel`` parameter from ``configparser`` ``.INI`` file, e.g. mapping ``'debug'`` to ``logg...
[ "def", "get_config_parameter_loglevel", "(", "config", ":", "ConfigParser", ",", "section", ":", "str", ",", "param", ":", "str", ",", "default", ":", "int", ")", "->", "int", ":", "try", ":", "value", "=", "config", ".", "get", "(", "section", ",", "p...
35.742857
0.000778
def of_think(self, think): """ Simulate the worker processing the task for the specified amount of time. The worker is not released and the task is not paused. """ return self._compute( duration=think.duration, after=self.continuation)
[ "def", "of_think", "(", "self", ",", "think", ")", ":", "return", "self", ".", "_compute", "(", "duration", "=", "think", ".", "duration", ",", "after", "=", "self", ".", "continuation", ")" ]
36.5
0.010033
def hadamard_product(self, other): """Overload of numpy.ndarray.__mult__(): element-wise multiplication. Tries to speedup by checking for scalars of diagonal matrices on either side of operator Parameters ---------- other : scalar,numpy.ndarray,Matrix object ...
[ "def", "hadamard_product", "(", "self", ",", "other", ")", ":", "if", "np", ".", "isscalar", "(", "other", ")", ":", "return", "type", "(", "self", ")", "(", "x", "=", "self", ".", "x", "*", "other", ")", "if", "isinstance", "(", "other", ",", "p...
45.184211
0.00285
def persist_compilestats(run, session, stats): """ Persist the run results in the database. Args: run: The run we attach the compilestats to. session: The db transaction we belong to. stats: The stats we want to store in the database. """ for stat in stats: stat.run_...
[ "def", "persist_compilestats", "(", "run", ",", "session", ",", "stats", ")", ":", "for", "stat", "in", "stats", ":", "stat", ".", "run_id", "=", "run", ".", "id", "session", ".", "add", "(", "stat", ")" ]
28.833333
0.002801
def create( self, overwrite=False): """ Create the local database (including indexing) if it's not already set up. If `overwrite` is True, always re-create the database from scratch. Returns a connection to the database. """ logger.info("C...
[ "def", "create", "(", "self", ",", "overwrite", "=", "False", ")", ":", "logger", ".", "info", "(", "\"Creating database: %s\"", ",", "self", ".", "local_db_path", ")", "df", "=", "self", ".", "_load_gtf_as_dataframe", "(", "usecols", "=", "self", ".", "re...
36.784314
0.001038
def load_mo(self, state, page_idx): """ Loads a memory object from memory. :param page_idx: the index into the page :returns: a tuple of the object """ mo = self._storage[page_idx - self._page_addr] #print filter(lambda x: x != None, self._storage) if mo i...
[ "def", "load_mo", "(", "self", ",", "state", ",", "page_idx", ")", ":", "mo", "=", "self", ".", "_storage", "[", "page_idx", "-", "self", ".", "_page_addr", "]", "#print filter(lambda x: x != None, self._storage)", "if", "mo", "is", "None", "and", "hasattr", ...
42.153846
0.005357
def _number_of_line(member_tuple): """Try to return the number of the first line of the definition of a member of a module.""" member = member_tuple[1] try: return member.__code__.co_firstlineno except AttributeError: pass try: return inspect.findsource(member)[1] exc...
[ "def", "_number_of_line", "(", "member_tuple", ")", ":", "member", "=", "member_tuple", "[", "1", "]", "try", ":", "return", "member", ".", "__code__", ".", "co_firstlineno", "except", "AttributeError", ":", "pass", "try", ":", "return", "inspect", ".", "fin...
27.611111
0.001946
def open_pspsfile(self, ecut=20, pawecutdg=None): """ Calls Abinit to compute the internal tables for the application of the pseudopotential part. Returns :class:`PspsFile` object providing methods to plot and analyze the data or None if file is not found or it's not readable. A...
[ "def", "open_pspsfile", "(", "self", ",", "ecut", "=", "20", ",", "pawecutdg", "=", "None", ")", ":", "from", "pymatgen", ".", "io", ".", "abinit", ".", "tasks", "import", "AbinitTask", "from", "abipy", ".", "core", ".", "structure", "import", "Structure...
41.175
0.004745
def RemoveClientLabels(self, client, labels_names): """Removes labels with given names from a given client object.""" affected_owners = set() for label in client.GetLabels(): if label.name in labels_names and label.owner != "GRR": affected_owners.add(label.owner) for owner in affected_ow...
[ "def", "RemoveClientLabels", "(", "self", ",", "client", ",", "labels_names", ")", ":", "affected_owners", "=", "set", "(", ")", "for", "label", "in", "client", ".", "GetLabels", "(", ")", ":", "if", "label", ".", "name", "in", "labels_names", "and", "la...
36.9
0.007937
def validate_access_permission(self, valid_permissions): """ :param valid_permissions: List of permissions that access is allowed. :type valid_permissions: |list|/|tuple| :raises ValueError: If the |attr_mode| is invalid. :raises IOError: If the |attr_mode...
[ "def", "validate_access_permission", "(", "self", ",", "valid_permissions", ")", ":", "self", ".", "check_connection", "(", ")", "if", "typepy", ".", "is_null_string", "(", "self", ".", "mode", ")", ":", "raise", "ValueError", "(", "\"mode is not set\"", ")", ...
35.608696
0.002378
def after_update_oai_set(mapper, connection, target): """Update records on OAISet update.""" _delete_percolator(spec=target.spec, search_pattern=target.search_pattern) _new_percolator(spec=target.spec, search_pattern=target.search_pattern) sleep(2) update_affected_records.delay( spec=target....
[ "def", "after_update_oai_set", "(", "mapper", ",", "connection", ",", "target", ")", ":", "_delete_percolator", "(", "spec", "=", "target", ".", "spec", ",", "search_pattern", "=", "target", ".", "search_pattern", ")", "_new_percolator", "(", "spec", "=", "tar...
45.125
0.002717
def stopObserver(self): """ Stops this region's observer loop. If this is running in a subprocess, the subprocess will end automatically. """ self._observer.isStopped = True self._observer.isRunning = False
[ "def", "stopObserver", "(", "self", ")", ":", "self", ".", "_observer", ".", "isStopped", "=", "True", "self", ".", "_observer", ".", "isRunning", "=", "False" ]
34.428571
0.012146
def _set_option(self, name, value, allow_clear=False): """Set value for an option.""" if not allow_clear: # Prevent clears if value was set try: current_value = self._get_option(name) if value is None and current_value is not None: ...
[ "def", "_set_option", "(", "self", ",", "name", ",", "value", ",", "allow_clear", "=", "False", ")", ":", "if", "not", "allow_clear", ":", "# Prevent clears if value was set", "try", ":", "current_value", "=", "self", ".", "_get_option", "(", "name", ")", "i...
34
0.004773
def example_2_load_data(self): """ 加载数据 """ # 权重向量, w1代表神经网络的第一层,w2代表神经网络的第二层 self.w1 = Variable(random_normal([2, 3], stddev=1, seed=1)) self.w2 = Variable(random_normal([3, 1], stddev=1, seed=1)) # 特征向量, 区别是,这里不会在计算图中生成节点 #self.x = placeholder(float32, s...
[ "def", "example_2_load_data", "(", "self", ")", ":", "# 权重向量, w1代表神经网络的第一层,w2代表神经网络的第二层", "self", ".", "w1", "=", "Variable", "(", "random_normal", "(", "[", "2", ",", "3", "]", ",", "stddev", "=", "1", ",", "seed", "=", "1", ")", ")", "self", ".", "w2...
40.3
0.007282
def to_app(app): """Serializes app to id string :param app: object to serialize :return: string id """ from sevenbridges.models.app import App if not app: raise SbgError('App is required!') elif isinstance(app, App): return app.id e...
[ "def", "to_app", "(", "app", ")", ":", "from", "sevenbridges", ".", "models", ".", "app", "import", "App", "if", "not", "app", ":", "raise", "SbgError", "(", "'App is required!'", ")", "elif", "isinstance", "(", "app", ",", "App", ")", ":", "return", "...
31.071429
0.004464
def bootstrap(force=False): ''' Download and install the latest version of the Chocolatey package manager via the official bootstrap. Chocolatey requires Windows PowerShell and the .NET v4.0 runtime. Depending on the host's version of Windows, chocolatey.bootstrap will attempt to ensure these p...
[ "def", "bootstrap", "(", "force", "=", "False", ")", ":", "# Check if Chocolatey is already present in the path", "try", ":", "choc_path", "=", "_find_chocolatey", "(", "__context__", ",", "__salt__", ")", "except", "CommandExecutionError", ":", "choc_path", "=", "Non...
43.531915
0.001673
def make_any_items_node(rawtext, app, prefixed_name, obj, parent, modname, options): """Render a Python sequence as a comma-separated list, with an "or" for the final item. :param rawtext: Text being replaced with link node. :param app: Sphinx application context :param prefixed_name: The dotted Python...
[ "def", "make_any_items_node", "(", "rawtext", ",", "app", ",", "prefixed_name", ",", "obj", ",", "parent", ",", "modname", ",", "options", ")", ":", "text", "=", "list_conjunction", "(", "obj", ",", "\"or\"", ")", "node", "=", "nodes", ".", "Text", "(", ...
47.071429
0.004464
def debug_async(self, conn_id, cmd_name, cmd_args, progress_callback, callback): """Asynchronously complete a named debug command. The command name and arguments are passed to the underlying device adapter and interpreted there. If the command is long running, progress_callback may be ...
[ "def", "debug_async", "(", "self", ",", "conn_id", ",", "cmd_name", ",", "cmd_args", ",", "progress_callback", ",", "callback", ")", ":", "def", "monitor_callback", "(", "_conn_string", ",", "_conn_id", ",", "_event_name", ",", "event", ")", ":", "if", "even...
45.115385
0.007509
def build_core_type(s_cdt): ''' Build an xsd simpleType out of a S_CDT. ''' s_dt = nav_one(s_cdt).S_DT[17]() if s_dt.name == 'void': type_name = None elif s_dt.name == 'boolean': type_name = 'xs:boolean' elif s_dt.name == 'integer': type_name = 'xs:inte...
[ "def", "build_core_type", "(", "s_cdt", ")", ":", "s_dt", "=", "nav_one", "(", "s_cdt", ")", ".", "S_DT", "[", "17", "]", "(", ")", "if", "s_dt", ".", "name", "==", "'void'", ":", "type_name", "=", "None", "elif", "s_dt", ".", "name", "==", "'boole...
23.516129
0.011858
def _Open(self, path_spec, mode='rb'): """Opens the file system defined by path specification. Args: path_spec (PathSpec): a path specification. mode (Optional[str]): file access mode. The default is 'rb' which represents read-only binary. Raises: AccessError: if the access to ...
[ "def", "_Open", "(", "self", ",", "path_spec", ",", "mode", "=", "'rb'", ")", ":", "if", "not", "path_spec", ".", "HasParent", "(", ")", ":", "raise", "errors", ".", "PathSpecError", "(", "'Unsupported path specification without parent.'", ")", "range_offset", ...
35.9
0.003617
def check_manifest (): """Snatched from roundup.sf.net. Check that the files listed in the MANIFEST are present when the source is unpacked.""" try: f = open('MANIFEST') except Exception: print('\n*** SOURCE WARNING: The MANIFEST file is missing!') return try: man...
[ "def", "check_manifest", "(", ")", ":", "try", ":", "f", "=", "open", "(", "'MANIFEST'", ")", "except", "Exception", ":", "print", "(", "'\\n*** SOURCE WARNING: The MANIFEST file is missing!'", ")", "return", "try", ":", "manifest", "=", "[", "l", ".", "strip"...
34.368421
0.005961
def public(self, username=None): """ Returns all public repositories from an user. If username is not defined, tries to return own public repos. """ username = username or self.bitbucket.username or '' url = self.bitbucket.url('GET_USER', username=username) response =...
[ "def", "public", "(", "self", ",", "username", "=", "None", ")", ":", "username", "=", "username", "or", "self", ".", "bitbucket", ".", "username", "or", "''", "url", "=", "self", ".", "bitbucket", ".", "url", "(", "'GET_USER'", ",", "username", "=", ...
40.583333
0.004016
def to_tikz(self, line, circuit, end=None): """ Generate the TikZ code for one line of the circuit up to a certain gate. It modifies the circuit to include only the gates which have not been drawn. It automatically switches to other lines if the gates on those lines have...
[ "def", "to_tikz", "(", "self", ",", "line", ",", "circuit", ",", "end", "=", "None", ")", ":", "if", "end", "is", "None", ":", "end", "=", "len", "(", "circuit", "[", "line", "]", ")", "tikz_code", "=", "[", "]", "cmds", "=", "circuit", "[", "l...
50.010309
0.003436
def getItemXML(): ''' Build an XML string that contains some randomly positioned goal items''' xml="" for item in range(NUM_GOALS): x = str(random.randint(old_div(-ARENA_WIDTH,2),old_div(ARENA_WIDTH,2))) z = str(random.randint(old_div(-ARENA_BREADTH,2),old_div(ARENA_BREADTH,2))) xml ...
[ "def", "getItemXML", "(", ")", ":", "xml", "=", "\"\"", "for", "item", "in", "range", "(", "NUM_GOALS", ")", ":", "x", "=", "str", "(", "random", ".", "randint", "(", "old_div", "(", "-", "ARENA_WIDTH", ",", "2", ")", ",", "old_div", "(", "ARENA_WI...
52.625
0.025701
def _eval_wrapper(self, fit_key, q, chiA, chiB, **kwargs): """ Evaluates the surfinBH3dq8 model. """ chiA = np.array(chiA) chiB = np.array(chiB) # Warn/Exit if extrapolating allow_extrap = kwargs.pop('allow_extrap', False) self._check_param_limits(q, chiA, chiB, ...
[ "def", "_eval_wrapper", "(", "self", ",", "fit_key", ",", "q", ",", "chiA", ",", "chiB", ",", "*", "*", "kwargs", ")", ":", "chiA", "=", "np", ".", "array", "(", "chiA", ")", "chiB", "=", "np", ".", "array", "(", "chiB", ")", "# Warn/Exit if extrap...
38.5
0.004751
def ReadResponsesForRequestId(self, session_id, request_id, timestamp=None): """Reads responses for one request. Args: session_id: The session id to use. request_id: The id of the request. timestamp: A timestamp as used in the data store. Yields: fetched responses for the request ...
[ "def", "ReadResponsesForRequestId", "(", "self", ",", "session_id", ",", "request_id", ",", "timestamp", "=", "None", ")", ":", "request", "=", "rdf_flow_runner", ".", "RequestState", "(", "id", "=", "request_id", ",", "session_id", "=", "session_id", ")", "fo...
35.214286
0.005929
def sanitize_for_archive(url, headers, payload): """Sanitize payload of a HTTP request by removing the login and password information before storing/retrieving archived items :param: url: HTTP url request :param: headers: HTTP headers request :param: payload: HTTP payload reques...
[ "def", "sanitize_for_archive", "(", "url", ",", "headers", ",", "payload", ")", ":", "if", "BugzillaClient", ".", "PBUGZILLA_LOGIN", "in", "payload", ":", "payload", ".", "pop", "(", "BugzillaClient", ".", "PBUGZILLA_LOGIN", ")", "if", "BugzillaClient", ".", "...
36.45
0.004011
def match_template(tree, template, args=None): """Check if match string matches Tree structure Args: tree (Tree): Parsed Tree structure of a sentence template (str): String template to match. Example: "( S ( NP ) )" Returns: bool: If they match or not """ tokens = get_to...
[ "def", "match_template", "(", "tree", ",", "template", ",", "args", "=", "None", ")", ":", "tokens", "=", "get_tokens", "(", "template", ".", "split", "(", ")", ")", "cur_args", "=", "{", "}", "if", "match_tokens", "(", "tree", ",", "tokens", ",", "c...
31.105263
0.003284
def get(self): """ Get a new chunk if available. Returns: Chunk or list: If enough frames are available a chunk is returned. Otherwise None. If ``self.num_buffer >= 1`` a list instead of single chunk is returned. """ chunk_size = self._smal...
[ "def", "get", "(", "self", ")", ":", "chunk_size", "=", "self", ".", "_smallest_buffer", "(", ")", "all_full", "=", "self", ".", "_all_full", "(", ")", "if", "all_full", ":", "right_context", "=", "0", "num_frames", "=", "chunk_size", "-", "self", ".", ...
35
0.003971
def assert_any_call(self, *args, **kwargs): """assert the mock has been called with the specified arguments. The assert passes if the mock has *ever* been called, unlike `assert_called_with` and `assert_called_once_with` that only pass if the call is the most recent one.""" kall...
[ "def", "assert_any_call", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kall", "=", "call", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "kall", "not", "in", "self", ".", "call_args_list", ":", "expected_string", "=", ...
46.333333
0.003527
def truncate_array(array1, array2, position): """Truncate array1 by finding the overlap with array2 when the array1 center is located at the given position in array2.""" slices = [] for i in range(array1.ndim): xmin = 0 xmax = array1.shape[i] dxlo = array1.shape[i] // 2 ...
[ "def", "truncate_array", "(", "array1", ",", "array2", ",", "position", ")", ":", "slices", "=", "[", "]", "for", "i", "in", "range", "(", "array1", ".", "ndim", ")", ":", "xmin", "=", "0", "xmax", "=", "array1", ".", "shape", "[", "i", "]", "dxl...
33.421053
0.001531
def get_bits(block_representation, coin_symbol='btc', api_key=None): ''' Takes a block_representation and returns the number of bits ''' return get_block_overview(block_representation=block_representation, coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['bits']
[ "def", "get_bits", "(", "block_representation", ",", "coin_symbol", "=", "'btc'", ",", "api_key", "=", "None", ")", ":", "return", "get_block_overview", "(", "block_representation", "=", "block_representation", ",", "coin_symbol", "=", "coin_symbol", ",", "txn_limit...
48.5
0.006757
def getBinaries(self): ''' Return a dictionary of binaries to compile: {"dirname":"exename"}, this is used when automatically generating CMakeLists Note that currently modules may define only a single executable binary or library to be built by the automatic build system, by...
[ "def", "getBinaries", "(", "self", ")", ":", "# the module.json syntax is a subset of the package.json syntax: a", "# single string that defines the source directory to use to build an", "# executable with the same name as the component. This may be extended", "# to include the rest of the npm syn...
56.384615
0.001341
def send_music(self, user_id, url, hq_url, thumb_media_id, title=None, description=None, account=None): """ 发送音乐消息 详情请参考 http://mp.weixin.qq.com/wiki/7/12a5a320ae96fecdf0e15cb06123de9f.html :param user_id: 用户 ID 。 就是你收到的 `Message` 的 source :param url:...
[ "def", "send_music", "(", "self", ",", "user_id", ",", "url", ",", "hq_url", ",", "thumb_media_id", ",", "title", "=", "None", ",", "description", "=", "None", ",", "account", "=", "None", ")", ":", "music_data", "=", "{", "'musicurl'", ":", "url", ","...
30.575758
0.002882
def calculate_fraction_of_sn_discovered( log, surveyCadenceSettings, snSurveyDiscoveryTimes, redshifts, peakAppMagList, snCampaignLengthList, extraSurveyConstraints, zmin, zmax): """ *Given a list of the snSurveyDiscoveryTimes calculate the...
[ "def", "calculate_fraction_of_sn_discovered", "(", "log", ",", "surveyCadenceSettings", ",", "snSurveyDiscoveryTimes", ",", "redshifts", ",", "peakAppMagList", ",", "snCampaignLengthList", ",", "extraSurveyConstraints", ",", "zmin", ",", "zmax", ")", ":", "###############...
46.587302
0.002836
def podcasts_iter(self, *, device_id=None, page_size=250): """Get a paged iterator of subscribed podcast series. Parameters: device_id (str, Optional): A mobile device ID. Default: Use ``device_id`` of the :class:`MobileClient` instance. page_size (int, Optional): The maximum number of results per return...
[ "def", "podcasts_iter", "(", "self", ",", "*", ",", "device_id", "=", "None", ",", "page_size", "=", "250", ")", ":", "if", "device_id", "is", "None", ":", "device_id", "=", "self", ".", "device_id", "start_token", "=", "None", "prev_items", "=", "None",...
22.434783
0.035283
def Magic(self): #self.view.setFixedSize(self.width(), self.width()) self.WholeData = [] self.x_scale = self.width_plot / self.width_load self.y_scale = self.height_plot / self.height_load self.z_scale = self.depth_plot / self.depth_load # print(self.x_scale,' and ...
[ "def", "Magic", "(", "self", ")", ":", "#self.view.setFixedSize(self.width(), self.width())", "self", ".", "WholeData", "=", "[", "]", "self", ".", "x_scale", "=", "self", ".", "width_plot", "/", "self", ".", "width_load", "self", ".", "y_scale", "=", "self", ...
29.117647
0.007513
def inv_mix_columns(state): """ Transformation in the Inverse Cipher that is the inverse of MixColumns(). """ state = state.reshape(4, 4, 8) return fcat( multiply(IMA, state[0]), multiply(IMA, state[1]), multiply(IMA, state[2]), multiply(IMA, state[3]), )
[ "def", "inv_mix_columns", "(", "state", ")", ":", "state", "=", "state", ".", "reshape", "(", "4", ",", "4", ",", "8", ")", "return", "fcat", "(", "multiply", "(", "IMA", ",", "state", "[", "0", "]", ")", ",", "multiply", "(", "IMA", ",", "state"...
27.363636
0.003215
def aggr(self, group, *attributes, keep_all_rows=False, **named_attributes): """ Aggregation/projection operator :param group: an entity set whose entities will be grouped per entity of `self` :param attributes: attributes of self to include in the result :param keep_all_rows: T...
[ "def", "aggr", "(", "self", ",", "group", ",", "*", "attributes", ",", "keep_all_rows", "=", "False", ",", "*", "*", "named_attributes", ")", ":", "return", "GroupBy", ".", "create", "(", "self", ",", "group", ",", "keep_all_rows", "=", "keep_all_rows", ...
67.083333
0.008578
def set_rcParams_scvelo(fontsize=8, color_map=None, frameon=None): """Set matplotlib.rcParams to scvelo defaults.""" # dpi options (mpl default: 100, 100) rcParams['figure.dpi'] = 100 rcParams['savefig.dpi'] = 150 # figure (mpl default: 0.125, 0.96, 0.15, 0.91) rcParams['figure.figsize'] = (7,...
[ "def", "set_rcParams_scvelo", "(", "fontsize", "=", "8", ",", "color_map", "=", "None", ",", "frameon", "=", "None", ")", ":", "# dpi options (mpl default: 100, 100)", "rcParams", "[", "'figure.dpi'", "]", "=", "100", "rcParams", "[", "'savefig.dpi'", "]", "=", ...
31.0625
0.000488
def requestOptionsMenu(self): """ Emits the options request signal. """ point = QtCore.QPoint(0, self._optionsButton.height()) point = self._optionsButton.mapToGlobal(point) self.optionsRequested.emit(point)
[ "def", "requestOptionsMenu", "(", "self", ")", ":", "point", "=", "QtCore", ".", "QPoint", "(", "0", ",", "self", ".", "_optionsButton", ".", "height", "(", ")", ")", "point", "=", "self", ".", "_optionsButton", ".", "mapToGlobal", "(", "point", ")", "...
35.571429
0.007843
def get_example_runner(document): """Get or create the :class:`ExampleRunner` instance associated with a document. """ runner = getattr(document, "click_example_runner", None) if runner is None: runner = document.click_example_runner = ExampleRunner() return runner
[ "def", "get_example_runner", "(", "document", ")", ":", "runner", "=", "getattr", "(", "document", ",", "\"click_example_runner\"", ",", "None", ")", "if", "runner", "is", "None", ":", "runner", "=", "document", ".", "click_example_runner", "=", "ExampleRunner",...
36.25
0.003367
def _create_save_scenario_action(self): """Create action for save scenario dialog.""" icon = resources_path('img', 'icons', 'save-as-scenario.svg') self.action_save_scenario = QAction( QIcon(icon), self.tr('Save Current Scenario'), self.iface.mainWindow()) message...
[ "def", "_create_save_scenario_action", "(", "self", ")", ":", "icon", "=", "resources_path", "(", "'img'", ",", "'icons'", ",", "'save-as-scenario.svg'", ")", "self", ".", "action_save_scenario", "=", "QAction", "(", "QIcon", "(", "icon", ")", ",", "self", "."...
52.615385
0.002874
def zpipe(ctx): """build inproc pipe for talking to threads mimic pipe used in czmq zthread_fork. Returns a pair of PAIRs connected via inproc """ a = ctx.socket(zmq.PAIR) a.linger = 0 b = ctx.socket(zmq.PAIR) b.linger = 0 socket_set_hwm(a, 1) socket_set_hwm(b, 1) iface = "...
[ "def", "zpipe", "(", "ctx", ")", ":", "a", "=", "ctx", ".", "socket", "(", "zmq", ".", "PAIR", ")", "a", ".", "linger", "=", "0", "b", "=", "ctx", ".", "socket", "(", "zmq", ".", "PAIR", ")", "b", ".", "linger", "=", "0", "socket_set_hwm", "(...
23.823529
0.002375
def logical_raid_levels(self): """Gets the raid level for each logical volume :returns the set of list of raid levels configured. """ lg_raid_lvls = set() for member in self.get_members(): lg_raid_lvls.add(mappings.RAID_LEVEL_MAP_REV.get(member.raid)) return ...
[ "def", "logical_raid_levels", "(", "self", ")", ":", "lg_raid_lvls", "=", "set", "(", ")", "for", "member", "in", "self", ".", "get_members", "(", ")", ":", "lg_raid_lvls", ".", "add", "(", "mappings", ".", "RAID_LEVEL_MAP_REV", ".", "get", "(", "member", ...
36
0.006024
def CreateDialectActions(dialect): """Create dialect specific actions.""" CompAction = SCons.Action.Action('$%sCOM ' % dialect, '$%sCOMSTR' % dialect) CompPPAction = SCons.Action.Action('$%sPPCOM ' % dialect, '$%sPPCOMSTR' % dialect) ShCompAction = SCons.Action.Action('$SH%sCOM ' % dialect, '$SH%sCOMSTR...
[ "def", "CreateDialectActions", "(", "dialect", ")", ":", "CompAction", "=", "SCons", ".", "Action", ".", "Action", "(", "'$%sCOM '", "%", "dialect", ",", "'$%sCOMSTR'", "%", "dialect", ")", "CompPPAction", "=", "SCons", ".", "Action", ".", "Action", "(", "...
60.625
0.010163
def stop(self, wait=True): """ Stop the thread. More precisely, sends the stopping signal to the thread. It is then up to the run method to correctly responds. """ if self.started: self._running.clear() self._resume.set() # We cannot wait for oursel...
[ "def", "stop", "(", "self", ",", "wait", "=", "True", ")", ":", "if", "self", ".", "started", ":", "self", ".", "_running", ".", "clear", "(", ")", "self", ".", "_resume", ".", "set", "(", ")", "# We cannot wait for ourself", "if", "wait", "and", "("...
32.631579
0.004702
def interleaved2of5(self, txt, x, y, w=1.0, h=10.0): "Barcode I2of5 (numeric), adds a 0 if odd lenght" narrow = w / 3.0 wide = w # wide/narrow codes for the digits bar_char={'0': 'nnwwn', '1': 'wnnnw', '2': 'nwnnw', '3': 'wwnnn', '4': 'nnwnw', '5': 'wnwnn', '6'...
[ "def", "interleaved2of5", "(", "self", ",", "txt", ",", "x", ",", "y", ",", "w", "=", "1.0", ",", "h", "=", "10.0", ")", ":", "narrow", "=", "w", "/", "3.0", "wide", "=", "w", "# wide/narrow codes for the digits", "bar_char", "=", "{", "'0'", ":", ...
37.369565
0.003968
def get_indices(self, fit=None, tmin=None, tmax=None, specimen=None): """ Finds the appropriate indices in self.Data[self.s]['zijdplot_steps'] given a set of upper/lower bounds. This is to resolve duplicate steps using the convention that the first good step of that name is the i...
[ "def", "get_indices", "(", "self", ",", "fit", "=", "None", ",", "tmin", "=", "None", ",", "tmax", "=", "None", ",", "specimen", "=", "None", ")", ":", "if", "specimen", "==", "None", ":", "specimen", "=", "self", ".", "s", "if", "fit", "and", "n...
48.821429
0.003943
def _fonts2pys(self): """Writes fonts to pys file""" # Get mapping from fonts to fontfiles system_fonts = font_manager.findSystemFonts() font_name2font_file = {} for sys_font in system_fonts: font_name = font_manager.FontProperties(fname=sys_font).get_name() ...
[ "def", "_fonts2pys", "(", "self", ")", ":", "# Get mapping from fonts to fontfiles", "system_fonts", "=", "font_manager", ".", "findSystemFonts", "(", ")", "font_name2font_file", "=", "{", "}", "for", "sys_font", "in", "system_fonts", ":", "font_name", "=", "font_ma...
38
0.002232
def get_files(self): """ :inheritdoc """ assert self.bundle, 'Cannot fetch file name with empty bundle' abs_path, rel_path = self.get_abs_and_rel_paths(self.bundle.path, self.file_path, self.bundle.input_dir) file_cls = self.bundle.get_file_cls() return [file_cls(...
[ "def", "get_files", "(", "self", ")", ":", "assert", "self", ".", "bundle", ",", "'Cannot fetch file name with empty bundle'", "abs_path", ",", "rel_path", "=", "self", ".", "get_abs_and_rel_paths", "(", "self", ".", "bundle", ".", "path", ",", "self", ".", "f...
41.625
0.008824
def triangle_center(tri, uv=False): """ Computes the center of mass of the input triangle. :param tri: triangle object :type tri: elements.Triangle :param uv: if True, then finds parametric position of the center of mass :type uv: bool :return: center of mass of the triangle :rtype: tuple ...
[ "def", "triangle_center", "(", "tri", ",", "uv", "=", "False", ")", ":", "if", "uv", ":", "data", "=", "[", "t", ".", "uv", "for", "t", "in", "tri", "]", "mid", "=", "[", "0.0", ",", "0.0", "]", "else", ":", "data", "=", "tri", ".", "vertices...
28.95
0.001672
def NewTagClass(class_name: str, tag: str = None, bases: Union[type, Iterable] = (Tag, ), **kwargs: Any) -> type: """Generate and return new ``Tag`` class. If ``tag`` is empty, lower case of ``class_name`` is used for a tag name of the new class. ``bases`` should be a tuple ...
[ "def", "NewTagClass", "(", "class_name", ":", "str", ",", "tag", ":", "str", "=", "None", ",", "bases", ":", "Union", "[", "type", ",", "Iterable", "]", "=", "(", "Tag", ",", ")", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "type", ":", "if...
37.735294
0.00076
def content_ratings(self, **kwargs): """ Get the content ratings for a TV Series. Args: language: (optional) ISO 639 code. append_to_response: (optional) Comma separated, any collection method. Returns: A dict resprese...
[ "def", "content_ratings", "(", "self", ",", "*", "*", "kwargs", ")", ":", "path", "=", "self", ".", "_get_id_path", "(", "'content_ratings'", ")", "response", "=", "self", ".", "_GET", "(", "path", ",", "kwargs", ")", "self", ".", "_set_attrs_to_values", ...
30.705882
0.003717
def aggregate_events(aggregations, start_date=None, end_date=None, update_bookmark=True): """Aggregate indexed events.""" start_date = dateutil_parse(start_date) if start_date else None end_date = dateutil_parse(end_date) if end_date else None results = [] for a in aggregations:...
[ "def", "aggregate_events", "(", "aggregations", ",", "start_date", "=", "None", ",", "end_date", "=", "None", ",", "update_bookmark", "=", "True", ")", ":", "start_date", "=", "dateutil_parse", "(", "start_date", ")", "if", "start_date", "else", "None", "end_d...
47.083333
0.001736
def extensions(self): """ Access the extensions :returns: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionList :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.Assign...
[ "def", "extensions", "(", "self", ")", ":", "if", "self", ".", "_extensions", "is", "None", ":", "self", ".", "_extensions", "=", "AssignedAddOnExtensionList", "(", "self", ".", "_version", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_si...
46
0.005682
def form_valid(self, form): """After the form is valid lets let people know""" ret = super(ProjectCopy, self).form_valid(form) self.copy_relations() # Good to make note of that messages.add_message(self.request, messages.SUCCESS, 'Project %s copied' % self.object.name) ...
[ "def", "form_valid", "(", "self", ",", "form", ")", ":", "ret", "=", "super", "(", "ProjectCopy", ",", "self", ")", ".", "form_valid", "(", "form", ")", "self", ".", "copy_relations", "(", ")", "# Good to make note of that", "messages", ".", "add_message", ...
32.2
0.009063
def mounts(): """Get a list of all mounted volumes as [[mountpoint,device],[...]]""" with open('/proc/mounts') as f: # [['/mount/point','/dev/path'],[...]] system_mounts = [m[1::-1] for m in [l.strip().split() for l in f.readlines()]] return system...
[ "def", "mounts", "(", ")", ":", "with", "open", "(", "'/proc/mounts'", ")", "as", "f", ":", "# [['/mount/point','/dev/path'],[...]]", "system_mounts", "=", "[", "m", "[", "1", ":", ":", "-", "1", "]", "for", "m", "in", "[", "l", ".", "strip", "(", ")...
45.857143
0.006116