text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def fundb(self, fields=None, min_volume=0, min_discount=0, forever=False): """以字典形式返回分级B数据 :param fields:利率范围,形如['+3.0%', '6.0%'] :param min_volume:最小交易量,单位万元 :param min_discount:最小折价率, 单位% :param forever: 是否选择永续品种,默认 False """ if fields is None: field...
[ "def", "fundb", "(", "self", ",", "fields", "=", "None", ",", "min_volume", "=", "0", ",", "min_discount", "=", "0", ",", "forever", "=", "False", ")", ":", "if", "fields", "is", "None", ":", "fields", "=", "[", "]", "# 添加当前的ctime", "self", ".", "_...
31.318182
16.090909
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
21.055556
def validate_task_schema(context, schema_key='schema_file'): """Validate the task definition. Args: context (scriptworker.context.Context): the scriptworker context. It must contain a task and the config pointing to the schema file schema_key: the key in `context.config` where the p...
[ "def", "validate_task_schema", "(", "context", ",", "schema_key", "=", "'schema_file'", ")", ":", "schema_path", "=", "context", ".", "config", "schema_keys", "=", "schema_key", ".", "split", "(", "'.'", ")", "for", "key", "in", "schema_keys", ":", "schema_pat...
39.84
26.6
def annotateTree(bT, fn): """ annotate a tree in an external array using the given function """ l = [None]*bT.traversalID.midEnd def fn2(bT): l[bT.traversalID.mid] = fn(bT) if bT.internal: fn2(bT.left) fn2(bT.right) fn2(bT) return l
[ "def", "annotateTree", "(", "bT", ",", "fn", ")", ":", "l", "=", "[", "None", "]", "*", "bT", ".", "traversalID", ".", "midEnd", "def", "fn2", "(", "bT", ")", ":", "l", "[", "bT", ".", "traversalID", ".", "mid", "]", "=", "fn", "(", "bT", ")"...
24.083333
14.583333
def _terminate_service(self): """Force termination of running service. Disconnect queues, end queue feeder threads. Wait for service process to clear, drop all references.""" with self.__lock: if self._service: self._service.terminate() if self._pi...
[ "def", "_terminate_service", "(", "self", ")", ":", "with", "self", ".", "__lock", ":", "if", "self", ".", "_service", ":", "self", ".", "_service", ".", "terminate", "(", ")", "if", "self", ".", "_pipe_commands", ":", "self", ".", "_pipe_commands", ".",...
45.15
10.95
def publish(self, message_type, message_payload): """ Publish the specified object that the function automatically converts into a JSON string representation. This function use the lowered class name of the service as the AMQP routing key. For instance, if the class ``ExampleSe...
[ "def", "publish", "(", "self", ",", "message_type", ",", "message_payload", ")", ":", "payload", "=", "json", ".", "dumps", "(", "jsonpickle", ".", "Pickler", "(", "unpicklable", "=", "False", ")", ".", "flatten", "(", "message_payload", ")", ")", "message...
51.518519
29.518519
def get_unit_by_id(self, unit_id: str) -> typing.Optional['BaseUnit']: """ Gets a unit from its ID Args: unit_id: unit id Returns: Unit """ VALID_POSITIVE_INT.validate(unit_id, 'get_unit_by_id') for unit in self.units: if unit.unit_id ==...
[ "def", "get_unit_by_id", "(", "self", ",", "unit_id", ":", "str", ")", "->", "typing", ".", "Optional", "[", "'BaseUnit'", "]", ":", "VALID_POSITIVE_INT", ".", "validate", "(", "unit_id", ",", "'get_unit_by_id'", ")", "for", "unit", "in", "self", ".", "uni...
24.2
18.866667
def _updateB(oldB, B, W, degrees, damping, inds, backinds): # pragma: no cover '''belief update function.''' for j,d in enumerate(degrees): kk = inds[j] bk = backinds[j] if d == 0: B[kk,bk] = -np.inf continue belief = W[kk,bk] + W[j] oldBj = oldB[j] if d == oldBj.s...
[ "def", "_updateB", "(", "oldB", ",", "B", ",", "W", ",", "degrees", ",", "damping", ",", "inds", ",", "backinds", ")", ":", "# pragma: no cover\r", "for", "j", ",", "d", "in", "enumerate", "(", "degrees", ")", ":", "kk", "=", "inds", "[", "j", "]",...
27.65
21.45
def print_network(self): # pragma: no cover """ Generate a graphviz compatible graph. """ edges = set() def gen_edges(node): nonlocal edges name = str(id(node)) yield '{name} [label="{cls_name}"];'.format( name=name, ...
[ "def", "print_network", "(", "self", ")", ":", "# pragma: no cover", "edges", "=", "set", "(", ")", "def", "gen_edges", "(", "node", ")", ":", "nonlocal", "edges", "name", "=", "str", "(", "id", "(", "node", ")", ")", "yield", "'{name} [label=\"{cls_name}\...
32.407407
15.148148
def _AddStopTimeObjectUnordered(self, stoptime, schedule): """Add StopTime object to this trip. The trip isn't checked for duplicate sequence numbers so it must be validated later.""" stop_time_class = self.GetGtfsFactory().StopTime cursor = schedule._connection.cursor() insert_query = "INSERT ...
[ "def", "_AddStopTimeObjectUnordered", "(", "self", ",", "stoptime", ",", "schedule", ")", ":", "stop_time_class", "=", "self", ".", "GetGtfsFactory", "(", ")", ".", "StopTime", "cursor", "=", "schedule", ".", "_connection", ".", "cursor", "(", ")", "insert_que...
45.230769
15.923077
def update_elbs(self): """Update list of ELBs for the account / region Returns: `None` """ self.log.debug('Updating ELBs for {}/{}'.format( self.account.account_name, self.region )) # ELBs known to CINQ elbs_from_db = ELB.get_...
[ "def", "update_elbs", "(", "self", ")", ":", "self", ".", "log", ".", "debug", "(", "'Updating ELBs for {}/{}'", ".", "format", "(", "self", ".", "account", ".", "account_name", ",", "self", ".", "region", ")", ")", "# ELBs known to CINQ", "elbs_from_db", "=...
40.821429
19.982143
async def update_version(self): """Retrieve version and protocol version from API.""" get_version = GetVersion(pyvlx=self) await get_version.do_api_call() if not get_version.success: raise PyVLXException("Unable to retrieve version") self.version = get_version.version...
[ "async", "def", "update_version", "(", "self", ")", ":", "get_version", "=", "GetVersion", "(", "pyvlx", "=", "self", ")", "await", "get_version", ".", "do_api_call", "(", ")", "if", "not", "get_version", ".", "success", ":", "raise", "PyVLXException", "(", ...
48.266667
10.866667
def column_widths(self, size, focus=False): """ Return a list of column widths. 0 values in the list mean hide corresponding column completely """ maxcol = size[0] self._cache_maxcol = maxcol widths = [width for i, (w, (t, width, b)) in enumerate(self.contents)] ...
[ "def", "column_widths", "(", "self", ",", "size", ",", "focus", "=", "False", ")", ":", "maxcol", "=", "size", "[", "0", "]", "self", ".", "_cache_maxcol", "=", "maxcol", "widths", "=", "[", "width", "for", "i", ",", "(", "w", ",", "(", "t", ",",...
31.166667
16.166667
def to_underscore(string): """Converts a given string from CamelCase to under_score. >>> to_underscore('FooBar') 'foo_bar' """ new_string = re.sub(r'([A-Z]+)([A-Z][a-z])', r'\1_\2', string) new_string = re.sub(r'([a-z\d])([A-Z])', r'\1_\2', new_string) return new_string.lower()
[ "def", "to_underscore", "(", "string", ")", ":", "new_string", "=", "re", ".", "sub", "(", "r'([A-Z]+)([A-Z][a-z])'", ",", "r'\\1_\\2'", ",", "string", ")", "new_string", "=", "re", ".", "sub", "(", "r'([a-z\\d])([A-Z])'", ",", "r'\\1_\\2'", ",", "new_string",...
33.222222
17
def branchings(image, mask=None): '''Count the number of branches eminating from each pixel image - a binary image mask - optional mask of pixels not to consider This is the count of the number of branches that eminate from a pixel. A pixel with neighbors fore and aft has branches fore and...
[ "def", "branchings", "(", "image", ",", "mask", "=", "None", ")", ":", "global", "branchings_table", "if", "mask", "is", "None", ":", "masked_image", "=", "image", "else", ":", "masked_image", "=", "image", ".", "astype", "(", "bool", ")", ".", "copy", ...
32.03125
18.28125
def load_env_from_file(filename): """ Read an env file into a collection of (name, value) tuples. """ if not os.path.exists(filename): raise FileNotFoundError("Environment file {} does not exist.".format(filename)) with open(filename) as f: for lineno, line in enumerate(f): ...
[ "def", "load_env_from_file", "(", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "raise", "FileNotFoundError", "(", "\"Environment file {} does not exist.\"", ".", "format", "(", "filename", ")", ")", "with", "o...
34.555556
19
def update_build_configuration_set(id, **kwargs): """ Update a BuildConfigurationSet """ data = update_build_configuration_set_raw(id, **kwargs) if data: return utils.format_json(data)
[ "def", "update_build_configuration_set", "(", "id", ",", "*", "*", "kwargs", ")", ":", "data", "=", "update_build_configuration_set_raw", "(", "id", ",", "*", "*", "kwargs", ")", "if", "data", ":", "return", "utils", ".", "format_json", "(", "data", ")" ]
29.428571
9.142857
def get_jids_filter(count, filter_find_job=True): ''' Return a list of all job ids :param int count: show not more than the count of most recent jobs :param bool filter_find_jobs: filter out 'saltutil.find_job' jobs ''' with _get_serv(ret=None, commit=True) as cur: sql = '''SELECT * FRO...
[ "def", "get_jids_filter", "(", "count", ",", "filter_find_job", "=", "True", ")", ":", "with", "_get_serv", "(", "ret", "=", "None", ",", "commit", "=", "True", ")", "as", "cur", ":", "sql", "=", "'''SELECT * FROM (\n SELECT DISTINCT `jid` ,`lo...
36.666667
20.416667
def freeze_bn(self): '''Freeze BatchNorm layers.''' for layer in self.modules(): if isinstance(layer, nn.BatchNorm2d): layer.eval()
[ "def", "freeze_bn", "(", "self", ")", ":", "for", "layer", "in", "self", ".", "modules", "(", ")", ":", "if", "isinstance", "(", "layer", ",", "nn", ".", "BatchNorm2d", ")", ":", "layer", ".", "eval", "(", ")" ]
34.2
9.4
def _ConvertDateTimeToOffset(self, date_time_value): """Converts the PQL formatted response for a dateTime object. Output conforms to ISO 8061 format, e.g. 'YYYY-MM-DDTHH:MM:SSz.' Args: date_time_value: dict The date time value from the PQL response. Returns: str: A string representation ...
[ "def", "_ConvertDateTimeToOffset", "(", "self", ",", "date_time_value", ")", ":", "date_time_obj", "=", "datetime", ".", "datetime", "(", "int", "(", "date_time_value", "[", "'date'", "]", "[", "'year'", "]", ")", ",", "int", "(", "date_time_value", "[", "'d...
39.9
22.9
def get_interpolated_value(self, energy, integrated=False): """ Returns the COHP for a particular energy. Args: energy: Energy to return the COHP value for. """ inter = {} for spin in self.cohp: if not integrated: inter[spin] = get...
[ "def", "get_interpolated_value", "(", "self", ",", "energy", ",", "integrated", "=", "False", ")", ":", "inter", "=", "{", "}", "for", "spin", "in", "self", ".", "cohp", ":", "if", "not", "integrated", ":", "inter", "[", "spin", "]", "=", "get_linear_i...
42
20.1
def filter_host_by_name(name): """Filter for host Filter on name :param name: name to filter :type name: str :return: Filter :rtype: bool """ def inner_filter(items): """Inner filter for host. Accept if host_name == name""" host = items["host"] if host is None: ...
[ "def", "filter_host_by_name", "(", "name", ")", ":", "def", "inner_filter", "(", "items", ")", ":", "\"\"\"Inner filter for host. Accept if host_name == name\"\"\"", "host", "=", "items", "[", "\"host\"", "]", "if", "host", "is", "None", ":", "return", "False", "r...
21.666667
16.833333
def dec(self, byts): ''' Decode an envelope dict and decrypt the given bytes. Args: byts (bytes): Bytes to decrypt. Returns: bytes: Decrypted message. ''' envl = s_msgpack.un(byts) iv = envl.get('iv', b'') asscd = envl.get('asscd'...
[ "def", "dec", "(", "self", ",", "byts", ")", ":", "envl", "=", "s_msgpack", ".", "un", "(", "byts", ")", "iv", "=", "envl", ".", "get", "(", "'iv'", ",", "b''", ")", "asscd", "=", "envl", ".", "get", "(", "'asscd'", ",", "b''", ")", "data", "...
24.869565
19.391304
def dump(obj, file, protocol=None): """Serialize obj as bytes streamed into file protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to pickle.HIGHEST_PROTOCOL. This setting favors maximum communication speed between processes running the same Python version. Set protocol=pickle.DE...
[ "def", "dump", "(", "obj", ",", "file", ",", "protocol", "=", "None", ")", ":", "CloudPickler", "(", "file", ",", "protocol", "=", "protocol", ")", ".", "dump", "(", "obj", ")" ]
42.090909
19.818182
def get_crime_category(self, id, date=None): """ Get a particular crime category by ID, valid at a particular date. Uses the crime-categories_ API call. :rtype: CrimeCategory :param str id: The ID of the crime category to get. :param date: The date that the given crime c...
[ "def", "get_crime_category", "(", "self", ",", "id", ",", "date", "=", "None", ")", ":", "try", ":", "return", "self", ".", "_get_crime_categories", "(", "date", "=", "date", ")", "[", "id", "]", "except", "KeyError", ":", "raise", "InvalidCategoryExceptio...
40.842105
19.157895
def _implementation(): """Return a dict with the Python implementation and version. Provide both the name and the version of the Python implementation currently running. For example, on CPython 2.7.5 it will return {'name': 'CPython', 'version': '2.7.5'}. This function works best on CPython and Py...
[ "def", "_implementation", "(", ")", ":", "implementation", "=", "platform", ".", "python_implementation", "(", ")", "if", "implementation", "==", "'CPython'", ":", "implementation_version", "=", "platform", ".", "python_version", "(", ")", "elif", "implementation", ...
46.419355
22.83871
def parse_genotype(variant, ind, pos): """Get the genotype information in the proper format Sv specific format fields: ##FORMAT=<ID=DV,Number=1,Type=Integer, Description="Number of paired-ends that support the event"> ##FORMAT=<ID=PE,Number=1,Type=Integer, Description="Number of paired-ends t...
[ "def", "parse_genotype", "(", "variant", ",", "ind", ",", "pos", ")", ":", "gt_call", "=", "{", "}", "ind_id", "=", "ind", "[", "'individual_id'", "]", "gt_call", "[", "'individual_id'", "]", "=", "ind_id", "gt_call", "[", "'display_name'", "]", "=", "in...
30.659218
16.932961
def groups_set_topic(self, room_id, topic, **kwargs): """Sets the topic for the private group.""" return self.__call_api_post('groups.setTopic', roomId=room_id, topic=topic, kwargs=kwargs)
[ "def", "groups_set_topic", "(", "self", ",", "room_id", ",", "topic", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "__call_api_post", "(", "'groups.setTopic'", ",", "roomId", "=", "room_id", ",", "topic", "=", "topic", ",", "kwargs", "=", "k...
67.333333
23.666667
def _remove_zeros(votes, fpl, cl, ranking): """Remove zeros in IRV voting. """ for v in votes: for r in v: if r not in fpl: v.remove(r) for c in cl: if c not in fpl: if c not in ranking: ranking.append((c, 0))
[ "def", "_remove_zeros", "(", "votes", ",", "fpl", ",", "cl", ",", "ranking", ")", ":", "for", "v", "in", "votes", ":", "for", "r", "in", "v", ":", "if", "r", "not", "in", "fpl", ":", "v", ".", "remove", "(", "r", ")", "for", "c", "in", "cl", ...
26.090909
10.909091
def _get_matching_segments(self, zf, name): """ Return a generator yielding each of the segments who's names match name. """ for n in zf.namelist(): if n.startswith(name): yield zf.read(n)
[ "def", "_get_matching_segments", "(", "self", ",", "zf", ",", "name", ")", ":", "for", "n", "in", "zf", ".", "namelist", "(", ")", ":", "if", "n", ".", "startswith", "(", "name", ")", ":", "yield", "zf", ".", "read", "(", "n", ")" ]
24.75
12.75
def set_source_ip_for_interface(source_ip_address, desired_source_ip_address, device_num=0): """Configures the source IP address for a Linux interface :param source_ip_address: (str) Source IP address to change :param desired_source_ip_address: (str) IP address to configure as the source in outgoing packet...
[ "def", "set_source_ip_for_interface", "(", "source_ip_address", ",", "desired_source_ip_address", ",", "device_num", "=", "0", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "mod_logger", "+", "'.set_source_ip_for_interface'", ")", "if", "not", "isinstance", ...
47.095238
26.714286
def add_peer(self, peerAddr, networks=None): """Add a peer and optionally provide a list of the reachable networks.""" if _debug: BTR._debug("add_peer %r networks=%r", peerAddr, networks) # see if this is already a peer if peerAddr in self.peers: # add the (new?) reachable n...
[ "def", "add_peer", "(", "self", ",", "peerAddr", ",", "networks", "=", "None", ")", ":", "if", "_debug", ":", "BTR", ".", "_debug", "(", "\"add_peer %r networks=%r\"", ",", "peerAddr", ",", "networks", ")", "# see if this is already a peer", "if", "peerAddr", ...
34.823529
15
def FindPotentialURIs(self, file_obj): """Given a file, this will return all potenial APT source URIs.""" rfc822_format = "" # will contain all lines not in legacy format uris_to_parse = [] for line in utils.ReadFileBytesAsUnicode(file_obj).splitlines(True): # check if legacy style line - if it ...
[ "def", "FindPotentialURIs", "(", "self", ",", "file_obj", ")", ":", "rfc822_format", "=", "\"\"", "# will contain all lines not in legacy format", "uris_to_parse", "=", "[", "]", "for", "line", "in", "utils", ".", "ReadFileBytesAsUnicode", "(", "file_obj", ")", ".",...
40.466667
23.133333
def getWmState(self, win, str=False): """ Get the list of states of the given window (property _NET_WM_STATE). :param win: the window object :param str: True to get a list of string states instead of int :return: list of (int|str) """ states = self._getProperty('...
[ "def", "getWmState", "(", "self", ",", "win", ",", "str", "=", "False", ")", ":", "states", "=", "self", ".", "_getProperty", "(", "'_NET_WM_STATE'", ",", "win", ")", "or", "[", "]", "if", "not", "str", ":", "return", "states", "return", "[", "self",...
36.25
15.75
def _must_be_deleted(local_path, r_st): """Return True if the remote correspondent of local_path has to be deleted. i.e. if it doesn't exists locally or if it has a different type from the remote one.""" # if the file doesn't exists if not os.path.lexists(local_path): return...
[ "def", "_must_be_deleted", "(", "local_path", ",", "r_st", ")", ":", "# if the file doesn't exists", "if", "not", "os", ".", "path", ".", "lexists", "(", "local_path", ")", ":", "return", "True", "# or if the file type is different", "l_st", "=", "os", ".", "lst...
35.357143
14.642857
def get_name(self): """ Tries to get WF name from 'process' or 'collobration' or 'pariticipant' Returns: str. WF name. """ ns = {'ns': '{%s}' % BPMN_MODEL_NS} for path in ('.//{ns}process', './/{ns}collaboration', './...
[ "def", "get_name", "(", "self", ")", ":", "ns", "=", "{", "'ns'", ":", "'{%s}'", "%", "BPMN_MODEL_NS", "}", "for", "path", "in", "(", "'.//{ns}process'", ",", "'.//{ns}collaboration'", ",", "'.//{ns}collaboration/{ns}participant/'", ")", ":", "tag", "=", "self...
31.882353
14.117647
def airplane(self, model_mask: str = '###') -> str: """Generate a dummy airplane model. :param model_mask: Mask of truck model. Here '@' is a placeholder of characters and '#' is a placeholder of digits. :return: Airplane model. :Example: Boeing 727. """...
[ "def", "airplane", "(", "self", ",", "model_mask", ":", "str", "=", "'###'", ")", "->", "str", ":", "model", "=", "self", ".", "random", ".", "custom_code", "(", "mask", "=", "model_mask", ")", "plane", "=", "self", ".", "random", ".", "choice", "(",...
35
16.692308
def load_url(url, token, shape=(8, 256, 256)): """ Loads a geotiff url inside a thread and returns as an ndarray """ _, ext = os.path.splitext(urlparse(url).path) success = False for i in xrange(MAX_RETRIES): thread_id = threading.current_thread().ident _curl = _curl_pool[thread_id] ...
[ "def", "load_url", "(", "url", ",", "token", ",", "shape", "=", "(", "8", ",", "256", ",", "256", ")", ")", ":", "_", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "urlparse", "(", "url", ")", ".", "path", ")", "success", "=", "Fa...
41.972222
16.555556
def get_conn(self): """Return the FileService object.""" conn = self.get_connection(self.conn_id) service_options = conn.extra_dejson return FileService(account_name=conn.login, account_key=conn.password, **service_options)
[ "def", "get_conn", "(", "self", ")", ":", "conn", "=", "self", ".", "get_connection", "(", "self", ".", "conn_id", ")", "service_options", "=", "conn", ".", "extra_dejson", "return", "FileService", "(", "account_name", "=", "conn", ".", "login", ",", "acco...
46.166667
12.5
async def uv_protection_window( self, low: float = 3.5, high: float = 3.5) -> dict: """Get data on when a UV protection window is.""" return await self.request( 'get', 'protection', params={ 'from': str(low), 'to': str(high) })
[ "async", "def", "uv_protection_window", "(", "self", ",", "low", ":", "float", "=", "3.5", ",", "high", ":", "float", "=", "3.5", ")", "->", "dict", ":", "return", "await", "self", ".", "request", "(", "'get'", ",", "'protection'", ",", "params", "=", ...
38
10.125
def kill(restriction=None, connection=None): # pragma: no cover """ view and kill database connections. :param restriction: restriction to be applied to processlist :param connection: a datajoint.Connection object. Default calls datajoint.conn() Restrictions are specified as strings and can involv...
[ "def", "kill", "(", "restriction", "=", "None", ",", "connection", "=", "None", ")", ":", "# pragma: no cover", "if", "connection", "is", "None", ":", "connection", "=", "conn", "(", ")", "query", "=", "'SELECT * FROM information_schema.processlist WHERE id <> CONNE...
38.952381
23.190476
def get_ordering_for_column(self, column, direction): """ Returns a tuple of lookups to order by for the given column and direction. Direction is an integer, either -1, 0 or 1. """ if direction == 0: return () if column in self.orderings: ordering ...
[ "def", "get_ordering_for_column", "(", "self", ",", "column", ",", "direction", ")", ":", "if", "direction", "==", "0", ":", "return", "(", ")", "if", "column", "in", "self", ".", "orderings", ":", "ordering", "=", "self", ".", "orderings", "[", "column"...
35.7
12.2
def reduceByKeyAndWindow(self, func, invFunc, windowDuration, slideDuration=None, numPartitions=None, filterFunc=None): """ Return a new DStream by applying incremental `reduceByKey` over a sliding window. The reduced value of over a new window is calculated using t...
[ "def", "reduceByKeyAndWindow", "(", "self", ",", "func", ",", "invFunc", ",", "windowDuration", ",", "slideDuration", "=", "None", ",", "numPartitions", "=", "None", ",", "filterFunc", "=", "None", ")", ":", "self", ".", "_validate_window_param", "(", "windowD...
53.517857
28.089286
def make_sentence(list_words): """ Return a sentence from list of words. :param list list_words: list of words :returns: sentence :rtype: str """ lw_len = len(list_words) if lw_len > 6: list_words.insert(lw_len // 2 + random.choice(range(-2, ...
[ "def", "make_sentence", "(", "list_words", ")", ":", "lw_len", "=", "len", "(", "list_words", ")", "if", "lw_len", ">", "6", ":", "list_words", ".", "insert", "(", "lw_len", "//", "2", "+", "random", ".", "choice", "(", "range", "(", "-", "2", ",", ...
26.125
18.625
def cmd_graph(self, args): '''graph command''' if len(args) == 0: # list current graphs for i in range(len(self.graphs)): print("Graph %u: %s" % (i, self.graphs[i].fields)) return elif args[0] == "help": print("graph <timespan|tick...
[ "def", "cmd_graph", "(", "self", ",", "args", ")", ":", "if", "len", "(", "args", ")", "==", "0", ":", "# list current graphs", "for", "i", "in", "range", "(", "len", "(", "self", ".", "graphs", ")", ")", ":", "print", "(", "\"Graph %u: %s\"", "%", ...
35.782609
14.565217
def shutdown_waits_for(coro, loop=None): """Prevent coro from being cancelled during the shutdown sequence. The trick here is that we add this coro to the global "DO_NOT_CANCEL" collection, and then later during the shutdown sequence we make sure that the task that wraps this coro will NOT be cance...
[ "def", "shutdown_waits_for", "(", "coro", ",", "loop", "=", "None", ")", ":", "loop", "=", "loop", "or", "get_event_loop", "(", ")", "fut", "=", "loop", ".", "create_future", "(", ")", "# This future will connect coro and the caller.", "async", "def", "coro_prox...
42.333333
24.6
def _adjust_rowcol(self, insertion_point, no_to_insert, axis, tab=None): """Adjusts row and column sizes on insertion/deletion""" if axis == 2: self._shift_rowcol(insertion_point, no_to_insert) return assert axis in (0, 1) cell_sizes = self.col_widths if axis e...
[ "def", "_adjust_rowcol", "(", "self", ",", "insertion_point", ",", "no_to_insert", ",", "axis", ",", "tab", "=", "None", ")", ":", "if", "axis", "==", "2", ":", "self", ".", "_shift_rowcol", "(", "insertion_point", ",", "no_to_insert", ")", "return", "asse...
35.785714
22
def minimum(self): """ Finds the minimum reaction energy E_min and corresponding mixing ratio x_min. Returns: Tuple (x_min, E_min). """ return min([(x, energy) for _, x, energy, _, _ in self.get_kinks()], key=lambda i: i[1])
[ "def", "minimum", "(", "self", ")", ":", "return", "min", "(", "[", "(", "x", ",", "energy", ")", "for", "_", ",", "x", ",", "energy", ",", "_", ",", "_", "in", "self", ".", "get_kinks", "(", ")", "]", ",", "key", "=", "lambda", "i", ":", "...
29.5
16.9
def get_iss_info(self): """ Get information about the USB-ISS Querying will return three bytes; - the module ID (7), - firmware version (currently 2), - the current operating mode. """ self.write_data([self.ISS_CMD, self.ISS_VERSION]) response = s...
[ "def", "get_iss_info", "(", "self", ")", ":", "self", ".", "write_data", "(", "[", "self", ".", "ISS_CMD", ",", "self", ".", "ISS_VERSION", "]", ")", "response", "=", "self", ".", "read_data", "(", "3", ")", "if", "len", "(", "response", ")", "==", ...
32.611111
9.277778
def fix_e502(self, result): """Remove extraneous escape of newline.""" (line_index, _, target) = get_index_offset_contents(result, self.source) self.source[line_index] = target.rstrip('\n\r \t\\') + '\n'
[ "def", "fix_e502", "(", "self", ",", "result", ")", ":", "(", "line_index", ",", "_", ",", "target", ")", "=", "get_index_offset_contents", "(", "result", ",", "self", ".", "source", ")", "self", ".", "source", "[", "line_index", "]", "=", "target", "....
56.6
19.8
def delete(self, name, action, seqno): """Deletes the routemap from the node Note: This method will attempt to delete the routemap from the nodes operational config. If the routemap does not exist then this method will not perform any changes but still return True ...
[ "def", "delete", "(", "self", ",", "name", ",", "action", ",", "seqno", ")", ":", "return", "self", ".", "configure", "(", "'no route-map %s %s %s'", "%", "(", "name", ",", "action", ",", "seqno", ")", ")" ]
39.388889
27.388889
def mkdir_p(self, path): """Python implementation of `mkdir -p <path>` :param path: ``str`` """ try: if not os.path.isdir(path): os.makedirs(path) self.log.info('Created Directory [ %s ]', path) except OSError as exc: if ex...
[ "def", "mkdir_p", "(", "self", ",", "path", ")", ":", "try", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "os", ".", "makedirs", "(", "path", ")", "self", ".", "log", ".", "info", "(", "'Created Directory [ %s ]'", ",",...
32.375
17.125
def AddItem(self, item, f=lambda x: x): """Add an item to the ReservoirBucket, replacing an old item if necessary. The new item is guaranteed to be added to the bucket, and to be the last element in the bucket. If the bucket has reached capacity, then an old item will be replaced. With probability (_ma...
[ "def", "AddItem", "(", "self", ",", "item", ",", "f", "=", "lambda", "x", ":", "x", ")", ":", "with", "self", ".", "_mutex", ":", "if", "len", "(", "self", ".", "items", ")", "<", "self", ".", "_max_size", "or", "self", ".", "_max_size", "==", ...
40.724138
19.655172
def split(args): """ %prog split pairs.fastq Split shuffled pairs into `.1.fastq` and `.2.fastq`, using `sed`. Can work on gzipped file. <http://seqanswers.com/forums/showthread.php?t=13776> """ from jcvi.apps.grid import Jobs p = OptionParser(split.__doc__) opts, args = p.parse_a...
[ "def", "split", "(", "args", ")", ":", "from", "jcvi", ".", "apps", ".", "grid", "import", "Jobs", "p", "=", "OptionParser", "(", "split", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", ...
23.756098
21.073171
def pip_install(self, reqs): """Install dependencies into this env by calling pip in a subprocess""" if not reqs: return log.info('Calling pip to install %s', reqs) check_call([ sys.executable, '-m', 'pip', 'install', '--ignore-installed', '--prefix', ...
[ "def", "pip_install", "(", "self", ",", "reqs", ")", ":", "if", "not", "reqs", ":", "return", "log", ".", "info", "(", "'Calling pip to install %s'", ",", "reqs", ")", "check_call", "(", "[", "sys", ".", "executable", ",", "'-m'", ",", "'pip'", ",", "'...
42.125
15.75
def attach(self, filt, view=None): """Attach a Filter to this visual Each filter modifies the appearance or behavior of the visual. Parameters ---------- filt : object The filter to attach. view : instance of VisualView | None The view to use. ...
[ "def", "attach", "(", "self", ",", "filt", ",", "view", "=", "None", ")", ":", "if", "view", "is", "None", ":", "self", ".", "_vshare", ".", "filters", ".", "append", "(", "filt", ")", "for", "view", "in", "self", ".", "_vshare", ".", "views", "....
29.052632
14.631579
def validate(self, value): """ Applies the validation criteria. Returns value, new value, or None if invalid. Overload this in derived classes. """ try: v = int(value) if v not in self.allowed: return None return value ...
[ "def", "validate", "(", "self", ",", "value", ")", ":", "try", ":", "v", "=", "int", "(", "value", ")", "if", "v", "not", "in", "self", ".", "allowed", ":", "return", "None", "return", "value", "except", "ValueError", ":", "return", "None" ]
25.5
12.357143
def _expand(self, str, local_vars={}): """Expand $vars in a string.""" return ninja_syntax.expand(str, self.vars, local_vars)
[ "def", "_expand", "(", "self", ",", "str", ",", "local_vars", "=", "{", "}", ")", ":", "return", "ninja_syntax", ".", "expand", "(", "str", ",", "self", ".", "vars", ",", "local_vars", ")" ]
46.333333
8
def deepcopy(self, line_strings=None, shape=None): """ Create a deep copy of the LineStringsOnImage object. Parameters ---------- line_strings : None \ or list of imgaug.augmentables.lines.LineString, optional List of line strings on the image....
[ "def", "deepcopy", "(", "self", ",", "line_strings", "=", "None", ",", "shape", "=", "None", ")", ":", "lss", "=", "self", ".", "line_strings", "if", "line_strings", "is", "None", "else", "line_strings", "shape", "=", "self", ".", "shape", "if", "shape",...
38.033333
20.5
def exists(self, share_name, directory_name=None, file_name=None, timeout=None, snapshot=None): ''' Returns a boolean indicating whether the share exists if only share name is given. If directory_name is specificed a boolean will be returned indicating if the directory exists. If file_na...
[ "def", "exists", "(", "self", ",", "share_name", ",", "directory_name", "=", "None", ",", "file_name", "=", "None", ",", "timeout", "=", "None", ",", "snapshot", "=", "None", ")", ":", "_validate_not_none", "(", "'share_name'", ",", "share_name", ")", "try...
45.8125
24.1875
def put(self, item, block=True, timeout=None): """Put item into underlying queue.""" return self._queue.put(item, block, timeout)
[ "def", "put", "(", "self", ",", "item", ",", "block", "=", "True", ",", "timeout", "=", "None", ")", ":", "return", "self", ".", "_queue", ".", "put", "(", "item", ",", "block", ",", "timeout", ")" ]
47.666667
6
def acquire(cls, name=None, lifetime=None, mechs=None, usage='both', store=None): """Acquire GSSAPI credentials This method acquires credentials. If the `store` argument is used, the credentials will be acquired from the given credential store (if supported). Otherwise...
[ "def", "acquire", "(", "cls", ",", "name", "=", "None", ",", "lifetime", "=", "None", ",", "mechs", "=", "None", ",", "usage", "=", "'both'", ",", "store", "=", "None", ")", ":", "if", "store", "is", "None", ":", "res", "=", "rcreds", ".", "acqui...
40.810345
23.948276
def _convert_date(self, date): """Convert '106/05/01' to '2017/05/01'""" return '/'.join([str(int(date.split('/')[0]) + 1911)] + date.split('/')[1:])
[ "def", "_convert_date", "(", "self", ",", "date", ")", ":", "return", "'/'", ".", "join", "(", "[", "str", "(", "int", "(", "date", ".", "split", "(", "'/'", ")", "[", "0", "]", ")", "+", "1911", ")", "]", "+", "date", ".", "split", "(", "'/'...
54.333333
18
def format(args): """ %prog format oldagpfile newagpfile Reformat AGP file. --switch will replace the ids in the AGP file. """ from jcvi.formats.base import DictFile p = OptionParser(format.__doc__) p.add_option("--switchcomponent", help="Switch component id based on") ...
[ "def", "format", "(", "args", ")", ":", "from", "jcvi", ".", "formats", ".", "base", "import", "DictFile", "p", "=", "OptionParser", "(", "format", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--switchcomponent\"", ",", "help", "=", "\"Switch compo...
30.257143
16.2
def reset_failed(self, pk): """ reset failed counter :param pk: :return: """ TriggerService.objects.filter(consumer__name__id=pk).update(consumer_failed=0, provider_failed=0) TriggerService.objects.filter(provider__name__id=pk).update(consumer_failed=0, provid...
[ "def", "reset_failed", "(", "self", ",", "pk", ")", ":", "TriggerService", ".", "objects", ".", "filter", "(", "consumer__name__id", "=", "pk", ")", ".", "update", "(", "consumer_failed", "=", "0", ",", "provider_failed", "=", "0", ")", "TriggerService", "...
40.625
24.625
def _get_schema(self, argmap, req): """Return a `marshmallow.Schema` for the given argmap and request. :param argmap: Either a `marshmallow.Schema`, `dict` of argname -> `marshmallow.fields.Field` pairs, or a callable that returns a `marshmallow.Schema` instance. :param ...
[ "def", "_get_schema", "(", "self", ",", "argmap", ",", "req", ")", ":", "if", "isinstance", "(", "argmap", ",", "ma", ".", "Schema", ")", ":", "schema", "=", "argmap", "elif", "isinstance", "(", "argmap", ",", "type", ")", "and", "issubclass", "(", "...
42.541667
18.333333
def not_empty(message=None) -> Filter_T: """ Validate any object to ensure it's not empty (is None or has no elements). """ def validate(value): if value is None: _raise_failure(message) if hasattr(value, '__len__') and value.__len__() == 0: _raise_failure(messag...
[ "def", "not_empty", "(", "message", "=", "None", ")", "->", "Filter_T", ":", "def", "validate", "(", "value", ")", ":", "if", "value", "is", "None", ":", "_raise_failure", "(", "message", ")", "if", "hasattr", "(", "value", ",", "'__len__'", ")", "and"...
27.076923
17.076923
def define_component(self, body, type_token, def_name, param_defs): """ Given component definition, recurse to another ComponentVisitor to define a new component """ for subclass in ComponentVisitor.__subclasses__(): if subclass.comp_type == self._CompType_Map[type_to...
[ "def", "define_component", "(", "self", ",", "body", ",", "type_token", ",", "def_name", ",", "param_defs", ")", ":", "for", "subclass", "in", "ComponentVisitor", ".", "__subclasses__", "(", ")", ":", "if", "subclass", ".", "comp_type", "==", "self", ".", ...
46.3
16.3
def group_create(self, group, **kwargs): # noqa: E501 """Create a group # noqa: E501 Create a group # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.group_create(group, a...
[ "def", "group_create", "(", "self", ",", "group", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'asynchronous'", ")", ":", "return", "self", ".", "group_cre...
41.238095
17.619048
def load(cls, name, rc_file='~/.odoorpcrc'): """Return a connected :class:`ODOO` session identified by `name`: .. doctest:: :options: +SKIP >>> import odoorpc >>> odoo = odoorpc.ODOO.load('foo') Such sessions are stored with the :func:`save <odoorpc...
[ "def", "load", "(", "cls", ",", "name", ",", "rc_file", "=", "'~/.odoorpcrc'", ")", ":", "data", "=", "session", ".", "get", "(", "name", ",", "rc_file", ")", "if", "data", ".", "get", "(", "'type'", ")", "!=", "cls", ".", "__name__", ":", "raise",...
30.111111
17.055556
def do_scheduled_update(self, action, **kwargs): """ Do the actual update. action: if provided it will be looked up on the implementing class and called with **kwargs. If action is not provided each k/v pair in kwargs will be set on self and then self is saved. ...
[ "def", "do_scheduled_update", "(", "self", ",", "action", ",", "*", "*", "kwargs", ")", ":", "action", "=", "getattr", "(", "self", ",", "action", ",", "None", ")", "if", "callable", "(", "action", ")", ":", "return", "action", "(", "*", "*", "kwargs...
29.909091
14.545455
def isValid(folder, epoch=0): """ Check if the given folder is a valid preprocessed dataset """ # Validate by checking for the training 'silence.pkl' on the given epoch # This file is unique to our pre-processed dataset generated by 'process_dataset.py' return os.path.exists(os.path.join(folder,...
[ "def", "isValid", "(", "folder", ",", "epoch", "=", "0", ")", ":", "# Validate by checking for the training 'silence.pkl' on the given epoch", "# This file is unique to our pre-processed dataset generated by 'process_dataset.py'", "return", "os", ".", "path", ".", "exists", "(", ...
50.142857
22.714286
def build_scala(app): """build scala for scala docs, java docs, and clojure docs to use""" if any(v in _BUILD_VER for v in ['1.2.', '1.3.', '1.4.']): _run_cmd("cd %s/.. && make scalapkg" % app.builder.srcdir) _run_cmd("cd %s/.. && make scalainstall" % app.builder.srcdir) else: _run_c...
[ "def", "build_scala", "(", "app", ")", ":", "if", "any", "(", "v", "in", "_BUILD_VER", "for", "v", "in", "[", "'1.2.'", ",", "'1.3.'", ",", "'1.4.'", "]", ")", ":", "_run_cmd", "(", "\"cd %s/.. && make scalapkg\"", "%", "app", ".", "builder", ".", "src...
56.142857
25.857143
def postprocess_keyevent(self, event): """Post-process keypress event: in InternalShell, this is method is called when shell is ready""" event, text, key, ctrl, shift = restore_keyevent(event) # Is cursor on the last line? and after prompt? if len(text): ...
[ "def", "postprocess_keyevent", "(", "self", ",", "event", ")", ":", "event", ",", "text", ",", "key", ",", "ctrl", ",", "shift", "=", "restore_keyevent", "(", "event", ")", "# Is cursor on the last line? and after prompt?\r", "if", "len", "(", "text", ")", ":"...
37.804688
16.351563
def save(self, *args, **kwargs): """ The save method should create a new OrganizationUser linking the User matching the provided email address. If not matching User is found it should kick off the registration process. It needs to create a User in order to link it to the Organiza...
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "user", "=", "get_user_model", "(", ")", ".", "objects", ".", "get", "(", "email__iexact", "=", "self", ".", "cleaned_data", "[", "\"email\"", "]", ")", "e...
39.461538
17.153846
def get_relationship_lookup_session_for_family(self, family_id=None, proxy=None, *args, **kwargs): """Gets the ``OsidSession`` associated with the relationship lookup service for the given family. arg: family_id (osid.id.Id): the ``Id`` of the family arg: proxy (osid.proxy.Proxy): a proxy...
[ "def", "get_relationship_lookup_session_for_family", "(", "self", ",", "family_id", "=", "None", ",", "proxy", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "family_id", ":", "raise", "NullArgument", "if", "not", "self", "....
46.575758
22.757576
def blob_counter(self): """Create a blob counter.""" import aa # pylint: disablF0401 # noqa from ROOT import EventFile # pylint: disable F0401 try: event_file = EventFile(self.filename) except Exception: raise SystemExit("Could not open file"...
[ "def", "blob_counter", "(", "self", ")", ":", "import", "aa", "# pylint: disablF0401 # noqa", "from", "ROOT", "import", "EventFile", "# pylint: disable F0401", "try", ":", "event_file", "=", "EventFile", "(", "self", ".", "filename", ")", "except", "Exception...
27.733333
19.6
def members(self): """ -> #set of all members in the set """ if self.serialized: return set(map( self._loads, self._client.smembers(self.key_prefix))) else: return set(map( self._decode, self._client.smembers(self.key_prefix)))
[ "def", "members", "(", "self", ")", ":", "if", "self", ".", "serialized", ":", "return", "set", "(", "map", "(", "self", ".", "_loads", ",", "self", ".", "_client", ".", "smembers", "(", "self", ".", "key_prefix", ")", ")", ")", "else", ":", "retur...
37.5
18.375
def find_unique_metabolites(model): """Return set of metabolite IDs without duplicates from compartments.""" unique = set() for met in model.metabolites: is_missing = True for comp in model.compartments: if met.id.endswith("_{}".format(comp)): unique.add(met.id[:-...
[ "def", "find_unique_metabolites", "(", "model", ")", ":", "unique", "=", "set", "(", ")", "for", "met", "in", "model", ".", "metabolites", ":", "is_missing", "=", "True", "for", "comp", "in", "model", ".", "compartments", ":", "if", "met", ".", "id", "...
34.923077
11.538462
def __groupchat_message(self,stanza): """Process a groupchat message from a MUC room. :Parameters: - `stanza`: the stanza received. :Types: - `stanza`: `Message` :return: `True` if the message was properly recognized as directed to one of the managed...
[ "def", "__groupchat_message", "(", "self", ",", "stanza", ")", ":", "fr", "=", "stanza", ".", "get_from", "(", ")", "key", "=", "fr", ".", "bare", "(", ")", ".", "as_unicode", "(", ")", "rs", "=", "self", ".", "rooms", ".", "get", "(", "key", ")"...
33.473684
16.578947
def get_ip(): """Return machine's origin IP address. """ try: r = requests.get(HTTPBIN_URL) ip, _ = r.json()['origin'].split(',') return ip if r.status_code == 200 else None except requests.exceptions.ConnectionError: return None
[ "def", "get_ip", "(", ")", ":", "try", ":", "r", "=", "requests", ".", "get", "(", "HTTPBIN_URL", ")", "ip", ",", "_", "=", "r", ".", "json", "(", ")", "[", "'origin'", "]", ".", "split", "(", "','", ")", "return", "ip", "if", "r", ".", "stat...
29.888889
11.777778
def convert_Text_to_mrf( text ): ''' Converts from Text object into pre-syntactic mrf format, given as a list of lines, as in the output of etmrf. *) If the input Text has already been morphologically analysed, uses the existing analysis; *) If the input has not been analysed, p...
[ "def", "convert_Text_to_mrf", "(", "text", ")", ":", "from", "estnltk", ".", "text", "import", "Text", "if", "not", "isinstance", "(", "text", ",", "Text", ")", ":", "raise", "Exception", "(", "' Expected estnltk\\'s Text as an input argument! '", ")", "if", "no...
45.163265
15
def summary(app): """Print a summary of a deployed app's status.""" r = requests.get('https://{}.herokuapp.com/summary'.format(app)) summary = r.json()['summary'] click.echo("\nstatus \t| count") click.echo("----------------") for s in summary: click.echo("{}\t| {}".format(s[0], s[1])) ...
[ "def", "summary", "(", "app", ")", ":", "r", "=", "requests", ".", "get", "(", "'https://{}.herokuapp.com/summary'", ".", "format", "(", "app", ")", ")", "summary", "=", "r", ".", "json", "(", ")", "[", "'summary'", "]", "click", ".", "echo", "(", "\...
43.166667
15.25
def _split_line(self, line_str): """Split line and check number of columns""" arr = line_str.rstrip().split("\t") if len(arr) != self.expected_fields: raise exceptions.InvalidRecordException( ( "The line contains an invalid number of fields. Was " ...
[ "def", "_split_line", "(", "self", ",", "line_str", ")", ":", "arr", "=", "line_str", ".", "rstrip", "(", ")", ".", "split", "(", "\"\\t\"", ")", "if", "len", "(", "arr", ")", "!=", "self", ".", "expected_fields", ":", "raise", "exceptions", ".", "In...
41.909091
19.545455
def unwrap(s, node_indent): """Group lines of a docstring to blocks. For now, only groups markdown list sections. A block designates a list of consequtive lines that all start at the same indentation level. The lines of the docstring are iterated top to bottom. Each line is added to `block_li...
[ "def", "unwrap", "(", "s", ",", "node_indent", ")", ":", "def", "get_indent", "(", ")", ":", "if", "line_str", ".", "startswith", "(", "'\"\"\"'", ")", ":", "return", "node_indent", "return", "len", "(", "re", ".", "match", "(", "r\"^( *)\"", ",", "lin...
32.929412
25.788235
def send_request(self, path, data, method): """ All outbound requests go through this method. It defers to the transport's various HTTP method-specific methods. :param str path: The path to tack on to the endpoint URL for the query. :param data: The params to send al...
[ "def", "send_request", "(", "self", ",", "path", ",", "data", ",", "method", ")", ":", "headers", "=", "self", ".", "get_request_headers", "(", ")", "if", "method", "==", "'GET'", ":", "return", "self", ".", "_send_get_request", "(", "path", ",", "data",...
37.64
20.52
def draw_time_marker(self): """Draw the time marker on the TimeLine Canvas""" self._time_marker_image = self._canvas_ticks.create_image((2, 16), image=self._time_marker) self._time_marker_line = self._timeline.create_line( (2, 0, 2, self._timeline.winfo_height()), fill="#016dc9", wid...
[ "def", "draw_time_marker", "(", "self", ")", ":", "self", ".", "_time_marker_image", "=", "self", ".", "_canvas_ticks", ".", "create_image", "(", "(", "2", ",", "16", ")", ",", "image", "=", "self", ".", "_time_marker", ")", "self", ".", "_time_marker_line...
59.142857
20.428571
def tag(self, text): """Retrieves list of regex_matches in text. Parameters ---------- text: Text The estnltk text object to search for events. Returns ------- list of matches """ matches = self._match(text.text) matches = sel...
[ "def", "tag", "(", "self", ",", "text", ")", ":", "matches", "=", "self", ".", "_match", "(", "text", ".", "text", ")", "matches", "=", "self", ".", "_resolve_conflicts", "(", "matches", ")", "if", "self", ".", "return_layer", ":", "return", "matches",...
23.526316
18.684211
def nla_put_msecs(msg, attrtype, msecs): """Add msecs Netlink attribute to Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L737 Positional arguments: msg -- Netlink message (nl_msg class instance). attrtype -- attribute type (integer). msecs -- number of msecs (in...
[ "def", "nla_put_msecs", "(", "msg", ",", "attrtype", ",", "msecs", ")", ":", "if", "isinstance", "(", "msecs", ",", "c_uint64", ")", ":", "pass", "elif", "isinstance", "(", "msecs", ",", "c_ulong", ")", ":", "msecs", "=", "c_uint64", "(", "msecs", ".",...
30.4
15.65
def resolved_task(cls, task): """Task instance representing 'task', if any""" for t in cls.tasks: if t is task or t.execute is task: return t
[ "def", "resolved_task", "(", "cls", ",", "task", ")", ":", "for", "t", "in", "cls", ".", "tasks", ":", "if", "t", "is", "task", "or", "t", ".", "execute", "is", "task", ":", "return", "t" ]
36.2
9.2
def block_perm_and_perms_within_blocks(permutation, block_structure): """Decompose a permutation into a block permutation and into permutations acting within each block. :param permutation: The overall permutation to be factored. :type permutation: tuple :param block_structure: The channel dimensio...
[ "def", "block_perm_and_perms_within_blocks", "(", "permutation", ",", "block_structure", ")", ":", "nblocks", "=", "len", "(", "block_structure", ")", "offsets", "=", "[", "sum", "(", "block_structure", "[", ":", "k", "]", ")", "for", "k", "in", "range", "("...
42.795455
25.704545
def add_next(self, requester: int, track: dict): """ Adds a track to beginning of the queue """ self.queue.insert(0, AudioTrack().build(track, requester))
[ "def", "add_next", "(", "self", ",", "requester", ":", "int", ",", "track", ":", "dict", ")", ":", "self", ".", "queue", ".", "insert", "(", "0", ",", "AudioTrack", "(", ")", ".", "build", "(", "track", ",", "requester", ")", ")" ]
56.666667
11.666667
def stop_other_daemons(self): """ Stop services already provided by main samba daemon """ if self.smbd.running: self.smbd.stop() if self.nmbd.running: self.nmbd.stop()
[ "def", "stop_other_daemons", "(", "self", ")", ":", "if", "self", ".", "smbd", ".", "running", ":", "self", ".", "smbd", ".", "stop", "(", ")", "if", "self", ".", "nmbd", ".", "running", ":", "self", ".", "nmbd", ".", "stop", "(", ")" ]
24.888889
12.888889
def zadd(self, name, members, score=1, nx=False, xx=False, ch=False, incr=False): """ Add members in the set and assign them the score. :param name: str the name of the redis key :param members: a list of item or a single item :param score: the score the assign ...
[ "def", "zadd", "(", "self", ",", "name", ",", "members", ",", "score", "=", "1", ",", "nx", "=", "False", ",", "xx", "=", "False", ",", "ch", "=", "False", ",", "incr", "=", "False", ")", ":", "if", "nx", ":", "_args", "=", "[", "'NX'", "]", ...
28.368421
20.947368
def xinfo_stream(self, stream): """Retrieve information about the given stream.""" fut = self.execute(b'XINFO', b'STREAM', stream) return wait_make_dict(fut)
[ "def", "xinfo_stream", "(", "self", ",", "stream", ")", ":", "fut", "=", "self", ".", "execute", "(", "b'XINFO'", ",", "b'STREAM'", ",", "stream", ")", "return", "wait_make_dict", "(", "fut", ")" ]
44.5
7.5
def write_cache_decorator(self, node_or_pagetag, name, args, buffered, identifiers, inline=False, toplevel=False): """write a post-function decorator to replace a rendering callable with a cached version of itself.""" s...
[ "def", "write_cache_decorator", "(", "self", ",", "node_or_pagetag", ",", "name", ",", "args", ",", "buffered", ",", "identifiers", ",", "inline", "=", "False", ",", "toplevel", "=", "False", ")", ":", "self", ".", "printer", ".", "writeline", "(", "\"__M_...
41.3
19.028571
def profile_form_factory(): """Create a profile form.""" if current_app.config['USERPROFILES_EMAIL_ENABLED']: return EmailProfileForm( formdata=None, username=current_userprofile.username, full_name=current_userprofile.full_name, email=current_user.email, ...
[ "def", "profile_form_factory", "(", ")", ":", "if", "current_app", ".", "config", "[", "'USERPROFILES_EMAIL_ENABLED'", "]", ":", "return", "EmailProfileForm", "(", "formdata", "=", "None", ",", "username", "=", "current_userprofile", ".", "username", ",", "full_na...
34.4
10.666667
def parse_plugin_metadata(content): """Parse summary metadata to a Python object. Arguments: content: The `content` field of a `SummaryMetadata` proto corresponding to the pr_curves plugin. Returns: A `PrCurvesPlugin` protobuf object. """ if not isinstance(content, bytes): raise TypeError(...
[ "def", "parse_plugin_metadata", "(", "content", ")", ":", "if", "not", "isinstance", "(", "content", ",", "bytes", ")", ":", "raise", "TypeError", "(", "'Content type must be bytes'", ")", "result", "=", "plugin_data_pb2", ".", "PrCurvePluginData", ".", "FromStrin...
32
18.666667
def fit_from_cfg(cls, choosers, chosen_fname, alternatives, cfgname, outcfgname=None): """ Parameters ---------- choosers : DataFrame A dataframe in which rows represent choosers. chosen_fname : string A string indicating the column in the choosers datafra...
[ "def", "fit_from_cfg", "(", "cls", ",", "choosers", ",", "chosen_fname", ",", "alternatives", ",", "cfgname", ",", "outcfgname", "=", "None", ")", ":", "logger", ".", "debug", "(", "'start: fit from configuration {}'", ".", "format", "(", "cfgname", ")", ")", ...
44.78125
21.21875
def age(self, minimum: int = 16, maximum: int = 66) -> int: """Get a random integer value. :param maximum: Maximum value of age. :param minimum: Minimum value of age. :return: Random integer. :Example: 23. """ age = self.random.randint(minimum, maxim...
[ "def", "age", "(", "self", ",", "minimum", ":", "int", "=", "16", ",", "maximum", ":", "int", "=", "66", ")", "->", "int", ":", "age", "=", "self", ".", "random", ".", "randint", "(", "minimum", ",", "maximum", ")", "self", ".", "_store", "[", ...
27.923077
15.846154