text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def send_photo(self, chat_id, photo, caption=None, reply_to_message_id=None, reply_markup=None, parse_mode=None, disable_notification=None): """ Use this method to send photos. :param disable_notification: :param chat_id: :param photo: :param caption: ...
[ "def", "send_photo", "(", "self", ",", "chat_id", ",", "photo", ",", "caption", "=", "None", ",", "reply_to_message_id", "=", "None", ",", "reply_markup", "=", "None", ",", "parse_mode", "=", "None", ",", "disable_notification", "=", "None", ")", ":", "ret...
40.3125
17.1875
def total_read_throughput(self): """ Combined read throughput of table and global indexes """ total = self.read_throughput for index in itervalues(self.global_indexes): total += index.read_throughput return total
[ "def", "total_read_throughput", "(", "self", ")", ":", "total", "=", "self", ".", "read_throughput", "for", "index", "in", "itervalues", "(", "self", ".", "global_indexes", ")", ":", "total", "+=", "index", ".", "read_throughput", "return", "total" ]
41.833333
7.833333
def Ravipudi_Godbold(m, x, D, rhol, rhog, Cpl, kl, mug, mu_b, mu_w=None): r'''Calculates the two-phase non-boiling heat transfer coefficient of a liquid and gas flowing inside a tube of any inclination, as in [1]_ and reviewed in [2]_. .. math:: Nu = \frac{h_{TP} D}{k_l} = 0.56 \left(\frac{V_...
[ "def", "Ravipudi_Godbold", "(", "m", ",", "x", ",", "D", ",", "rhol", ",", "rhog", ",", "Cpl", ",", "kl", ",", "mug", ",", "mu_b", ",", "mu_w", "=", "None", ")", ":", "Vgs", "=", "m", "*", "x", "/", "(", "rhog", "*", "pi", "/", "4", "*", ...
35.361111
25.027778
def readGlobalFile(self, fileStoreID, userPath=None, cache=True, mutable=False, symlink=False): """ Downloads a file described by fileStoreID from the file store to the local directory. The function first looks for the file in the cache and if found, it hardlinks to the cached copy inste...
[ "def", "readGlobalFile", "(", "self", ",", "fileStoreID", ",", "userPath", "=", "None", ",", "cache", "=", "True", ",", "mutable", "=", "False", ",", "symlink", "=", "False", ")", ":", "# Check that the file hasn't been deleted by the user", "if", "fileStoreID", ...
66.157895
32.097744
def save_config(self): """Save the config, update the seqnum & default language """ self.__config.set('agent', 'seqnum', self.__client.get_seqnum()) self.__config.set('agent', 'lang', self.__client.default_lang) self.__config.save()
[ "def", "save_config", "(", "self", ")", ":", "self", ".", "__config", ".", "set", "(", "'agent'", ",", "'seqnum'", ",", "self", ".", "__client", ".", "get_seqnum", "(", ")", ")", "self", ".", "__config", ".", "set", "(", "'agent'", ",", "'lang'", ","...
44.5
15.333333
def limits_status_encode(self, limits_state, last_trigger, last_action, last_recovery, last_clear, breach_count, mods_enabled, mods_required, mods_triggered): ''' Status of AP_Limits. Sent in extended status stream when AP_Limits is enabled limits_state ...
[ "def", "limits_status_encode", "(", "self", ",", "limits_state", ",", "last_trigger", ",", "last_action", ",", "last_recovery", ",", "last_clear", ",", "breach_count", ",", "mods_enabled", ",", "mods_required", ",", "mods_triggered", ")", ":", "return", "MAVLink_lim...
88.529412
64.882353
def symlink(source, link_name): """ Method to allow creating symlinks on Windows """ if os.path.islink(link_name) and os.readlink(link_name) == source: return os_symlink = getattr(os, "symlink", None) if callable(os_symlink): os_symlink(source, link_name) else: impor...
[ "def", "symlink", "(", "source", ",", "link_name", ")", ":", "if", "os", ".", "path", ".", "islink", "(", "link_name", ")", "and", "os", ".", "readlink", "(", "link_name", ")", "==", "source", ":", "return", "os_symlink", "=", "getattr", "(", "os", "...
34.166667
14.388889
def wait_for_link_text(self, link_text, timeout=settings.LARGE_TIMEOUT): """ The shorter version of wait_for_link_text_visible() """ if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT: timeout = self.__get_new_timeout(timeout) return self.wait_for_link_text_visible(link...
[ "def", "wait_for_link_text", "(", "self", ",", "link_text", ",", "timeout", "=", "settings", ".", "LARGE_TIMEOUT", ")", ":", "if", "self", ".", "timeout_multiplier", "and", "timeout", "==", "settings", ".", "LARGE_TIMEOUT", ":", "timeout", "=", "self", ".", ...
67.8
22.4
def get_datastream(self, datastream): """ To get Datastream by id """ response = self.http.get('/Datastream/' + str(datastream)) datastream = Schemas.Datastream(datastream=response) return datastream
[ "def", "get_datastream", "(", "self", ",", "datastream", ")", ":", "response", "=", "self", ".", "http", ".", "get", "(", "'/Datastream/'", "+", "str", "(", "datastream", ")", ")", "datastream", "=", "Schemas", ".", "Datastream", "(", "datastream", "=", ...
34.428571
10.428571
def iter_instances(self): """Iterate over the stored objects Yields: wrkey: The two-tuple key used to store the object obj: The instance or function object """ for wrkey in set(self.keys()): obj = self.get(wrkey) if obj is None: ...
[ "def", "iter_instances", "(", "self", ")", ":", "for", "wrkey", "in", "set", "(", "self", ".", "keys", "(", ")", ")", ":", "obj", "=", "self", ".", "get", "(", "wrkey", ")", "if", "obj", "is", "None", ":", "continue", "yield", "wrkey", ",", "obj"...
29.333333
13.25
def get_objectives_by_genus_type(self, objective_genus_type=None): """Gets an ObjectiveList corresponding to the given objective genus Type which does not include objectives of genus types derived from the specified Type. In plenary mode, the returned list contains all known objectives ...
[ "def", "get_objectives_by_genus_type", "(", "self", ",", "objective_genus_type", "=", "None", ")", ":", "if", "objective_genus_type", "is", "None", ":", "raise", "NullArgument", "(", ")", "url_path", "=", "construct_url", "(", "'objectives_by_genus'", ",", "bank_id"...
52.434783
20.521739
def update_looking_for(profile_tree, looking_for): """ Update looking_for attribute of a Profile. """ div = profile_tree.xpath("//div[@id = 'what_i_want']")[0] looking_for['gentation'] = div.xpath(".//li[@id = 'ajax_gentation']/text()")[0].strip() looking_for['ages'] = replace_chars(div.xpath("....
[ "def", "update_looking_for", "(", "profile_tree", ",", "looking_for", ")", ":", "div", "=", "profile_tree", ".", "xpath", "(", "\"//div[@id = 'what_i_want']\"", ")", "[", "0", "]", "looking_for", "[", "'gentation'", "]", "=", "div", ".", "xpath", "(", "\".//li...
49.923077
28.692308
def load_plugin(self, manifest, *args): """ Loads a plugin from the given manifest :param manifest: The manifest to use to load the plugin :param args: Arguments to pass to the plugin """ if self.get_plugin_loaded(manifest["name"]): self._logger.debug("Plugin...
[ "def", "load_plugin", "(", "self", ",", "manifest", ",", "*", "args", ")", ":", "if", "self", ".", "get_plugin_loaded", "(", "manifest", "[", "\"name\"", "]", ")", ":", "self", ".", "_logger", ".", "debug", "(", "\"Plugin {} is already loaded.\"", ".", "fo...
48.912281
27.684211
def before_insert(mapper, conn, target): """event.listen method for Sqlalchemy to set the sequence for this object and create an ObjectNumber value for the id_""" from sqlalchemy import text if not target.id: sql = text('SELECT max(f_id)+1 FROM files WHERE f_d_vid = :did') ...
[ "def", "before_insert", "(", "mapper", ",", "conn", ",", "target", ")", ":", "from", "sqlalchemy", "import", "text", "if", "not", "target", ".", "id", ":", "sql", "=", "text", "(", "'SELECT max(f_id)+1 FROM files WHERE f_d_vid = :did'", ")", "target", ".", "id...
36.705882
21.882353
def smoothEstimate(self, nodeShape, estimatedNodeCount): """ Smooth out fluctuations in the estimate for this node compared to previous runs. Returns an integer. """ weightedEstimate = (1 - self.betaInertia) * estimatedNodeCount + \ self.betaInertia * s...
[ "def", "smoothEstimate", "(", "self", ",", "nodeShape", ",", "estimatedNodeCount", ")", ":", "weightedEstimate", "=", "(", "1", "-", "self", ".", "betaInertia", ")", "*", "estimatedNodeCount", "+", "self", ".", "betaInertia", "*", "self", ".", "previousWeighte...
51.555556
18
def asizeof(self, *objs, **opts): '''Return the combined size of the given objects (with modified options, see method **set**). ''' if opts: self.set(**opts) s, _ = self._sizes(objs, None) return s
[ "def", "asizeof", "(", "self", ",", "*", "objs", ",", "*", "*", "opts", ")", ":", "if", "opts", ":", "self", ".", "set", "(", "*", "*", "opts", ")", "s", ",", "_", "=", "self", ".", "_sizes", "(", "objs", ",", "None", ")", "return", "s" ]
31.625
16.125
def gMagnitudeError(G): """ Calculate the single-field-of-view-transit photometric standard error in the G band as a function of G. A 20% margin is included. Parameters ---------- G - Value(s) of G-band magnitude. Returns ------- The G band photometric standard error in units of magnitude. "...
[ "def", "gMagnitudeError", "(", "G", ")", ":", "z", "=", "calcZ", "(", "G", ")", "return", "1.0e-3", "*", "sqrt", "(", "0.04895", "*", "z", "*", "z", "+", "1.8633", "*", "z", "+", "0.0001985", ")", "*", "_scienceMargin" ]
23.117647
26.176471
def outliers_gesd(data, outliers = 5, report = False, alpha=0.05): """ The generalized (Extreme Studentized Deviate) ESD test is used to detect one or more outliers in a univariate data set that follows an approximately normal distribution [1]_. Parameters ---------- data : array_like or n...
[ "def", "outliers_gesd", "(", "data", ",", "outliers", "=", "5", ",", "report", "=", "False", ",", "alpha", "=", "0.05", ")", ":", "Rs", ",", "ls", "=", "np", ".", "zeros", "(", "outliers", ",", "dtype", "=", "np", ".", "float", ")", ",", "np", ...
37.031746
24.650794
def _save_current_cell(self): """Helper for :meth:`consume_next`.""" row, cell = self._row, self._cell family = row._cells.setdefault(cell.family_name, {}) qualified = family.setdefault(cell.qualifier, []) complete = Cell.from_pb(cell) qualified.append(complete) s...
[ "def", "_save_current_cell", "(", "self", ")", ":", "row", ",", "cell", "=", "self", ".", "_row", ",", "self", ".", "_cell", "family", "=", "row", ".", "_cells", ".", "setdefault", "(", "cell", ".", "family_name", ",", "{", "}", ")", "qualified", "="...
44.5
8.75
def push(jaide, source, destination, progress, multi=False): """ Copy file(s) from the local machine to a junos device. @param jaide: The jaide connection to the device. @type jaide: jaide.Jaide object @param source: The source filepath on the junos device to pull. @type source: str @param dest...
[ "def", "push", "(", "jaide", ",", "source", ",", "destination", ",", "progress", ",", "multi", "=", "False", ")", ":", "output", "=", "color", "(", "'Pushing %s to %s:%s\\n'", "%", "(", "source", ",", "jaide", ".", "host", ",", "destination", ")", ",", ...
45.888889
21.777778
def parse(self, argument): """Parses argument as whitespace-separated list of strings. It also parses argument as comma-separated list of strings if requested. Args: argument: string argument passed in the commandline. Returns: [str], the parsed flag value. """ if isinstance(argum...
[ "def", "parse", "(", "self", ",", "argument", ")", ":", "if", "isinstance", "(", "argument", ",", "list", ")", ":", "return", "argument", "elif", "not", "argument", ":", "return", "[", "]", "else", ":", "if", "self", ".", "_comma_compat", ":", "argumen...
25.736842
19.947368
def check_int_param(self, param, low, high, name): """ Check if the value of the given parameter is in the given range and an int. Designed for testing parameters like `mu` and `eps`. To pass this function the variable `param` must be able to be converted into a float wit...
[ "def", "check_int_param", "(", "self", ",", "param", ",", "low", ",", "high", ",", "name", ")", ":", "try", ":", "param", "=", "int", "(", "param", ")", "except", ":", "raise", "ValueError", "(", "'Parameter {} is not int or similar'", ".", "format", "(", ...
32.647059
22.588235
def Instance(expected, message="Not an instance of {}"): """ Creates a validator that checks if the given value is an instance of ``expected``. A custom message can be specified with ``message``. """ @wraps(Instance) def built(value): if not isinstance(value, expected): ...
[ "def", "Instance", "(", "expected", ",", "message", "=", "\"Not an instance of {}\"", ")", ":", "@", "wraps", "(", "Instance", ")", "def", "built", "(", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "expected", ")", ":", "raise", "Erro...
30.153846
17.692308
def rename_image(self, ami_name, new_ami_name, source_region='us-east-1'): """ Method which renames an ami by copying to a new ami with a new name (only way this is possible in AWS) :param ami_name: :param new_ami_name: :return: """ print "Re-naming/moving AMI to ...
[ "def", "rename_image", "(", "self", ",", "ami_name", ",", "new_ami_name", ",", "source_region", "=", "'us-east-1'", ")", ":", "print", "\"Re-naming/moving AMI to desired name and region\"", "image_id", "=", "self", ".", "get_image_id_by_name", "(", "ami_name", ",", "s...
48.363636
23.090909
def job_status(name=None): ''' Return the current status, enabled or disabled, of the job. :param name: The name of the job to return status for :return: Return true if enabled or false if disabled. CLI Example: .. code-block:: bash salt '*' jenkins.job_status jobname ''' i...
[ "def", "job_status", "(", "name", "=", "None", ")", ":", "if", "not", "name", ":", "raise", "SaltInvocationError", "(", "'Required parameter \\'name\\' is missing'", ")", "server", "=", "_connect", "(", ")", "if", "not", "job_exists", "(", "name", ")", ":", ...
23.833333
28.25
def save_xml(self, doc, element): '''Save this message_sending object into an xml.dom.Element object.''' for cond in self._targets: new_element = doc.createElementNS(RTS_NS, RTS_NS_S + 'targets') new_element.setAttributeNS(XSI_NS, XSI_NS_S + 'type', 'rtsExt:condition_ext') ...
[ "def", "save_xml", "(", "self", ",", "doc", ",", "element", ")", ":", "for", "cond", "in", "self", ".", "_targets", ":", "new_element", "=", "doc", ".", "createElementNS", "(", "RTS_NS", ",", "RTS_NS_S", "+", "'targets'", ")", "new_element", ".", "setAtt...
56.571429
20.285714
def validate(self, data, context=None): """Takes serialized data and returns validation errors or None. :param data: Data to validate. :param context: Context data. :returns: validation errors or None """ try: self.load(data, context) return None ...
[ "def", "validate", "(", "self", ",", "data", ",", "context", "=", "None", ")", ":", "try", ":", "self", ".", "load", "(", "data", ",", "context", ")", "return", "None", "except", "ValidationError", "as", "ve", ":", "return", "ve", ".", "messages" ]
31.416667
9.25
def express_route_cross_connection_peerings(self): """Instance depends on the API version: * 2018-02-01: :class:`ExpressRouteCrossConnectionPeeringsOperations<azure.mgmt.network.v2018_02_01.operations.ExpressRouteCrossConnectionPeeringsOperations>` * 2018-04-01: :class:`ExpressRouteCrossC...
[ "def", "express_route_cross_connection_peerings", "(", "self", ")", ":", "api_version", "=", "self", ".", "_get_api_version", "(", "'express_route_cross_connection_peerings'", ")", "if", "api_version", "==", "'2018-02-01'", ":", "from", ".", "v2018_02_01", ".", "operati...
94.914286
59.428571
def get_protein_targets_only(target_chembl_ids): """Given list of ChEMBL target ids, return dict of SINGLE PROTEIN targets Parameters ---------- target_chembl_ids : list list of chembl_ids as strings Returns ------- protein_targets : dict dictionary keyed to ChEMBL target i...
[ "def", "get_protein_targets_only", "(", "target_chembl_ids", ")", ":", "protein_targets", "=", "{", "}", "for", "target_chembl_id", "in", "target_chembl_ids", ":", "target", "=", "query_target", "(", "target_chembl_id", ")", "if", "'SINGLE PROTEIN'", "in", "target", ...
31.315789
17.315789
def dump_value(key, value, f, indent=0): '''Save a value of any libconfig type This function serializes takes ``key`` and ``value`` and serializes them into ``f``. If ``key`` is ``None``, a list-style output is produced. Otherwise, output has ``key = value`` format. ''' spaces = ' ' * indent ...
[ "def", "dump_value", "(", "key", ",", "value", ",", "f", ",", "indent", "=", "0", ")", ":", "spaces", "=", "' '", "*", "indent", "if", "key", "is", "None", ":", "key_prefix", "=", "''", "key_prefix_nl", "=", "''", "else", ":", "key_prefix", "=", "k...
37.181818
18.272727
def _interp_total_size(interp): """ Compute total load size of interpreter. :param ELFFile interp: interpreter ELF .so :return: total load size of interpreter, not aligned :rtype: int """ load_segs = [x for x in interp.iter_segments() if x.header.p_type == 'PT_LO...
[ "def", "_interp_total_size", "(", "interp", ")", ":", "load_segs", "=", "[", "x", "for", "x", "in", "interp", ".", "iter_segments", "(", ")", "if", "x", ".", "header", ".", "p_type", "==", "'PT_LOAD'", "]", "last", "=", "load_segs", "[", "-", "1", "]...
36.363636
16.545455
def _alternate(u, bigraph, visitU, visitV, matchV): """extend alternating tree from free vertex u. visitU, visitV marks all vertices covered by the tree. """ visitU[u] = True for v in bigraph[u]: if not visitV[v]: visitV[v] = True assert matchV[v] is not None # oth...
[ "def", "_alternate", "(", "u", ",", "bigraph", ",", "visitU", ",", "visitV", ",", "matchV", ")", ":", "visitU", "[", "u", "]", "=", "True", "for", "v", "in", "bigraph", "[", "u", "]", ":", "if", "not", "visitV", "[", "v", "]", ":", "visitV", "[...
40.5
15.4
def _event_monitor_loop(region_name, vpc_id, watcher_plugin, health_plugin, iterations, sleep_time, route_check_time_interval=30): """ Monitor queues to receive updates about new route specs or any detected failed IPs. If any of th...
[ "def", "_event_monitor_loop", "(", "region_name", ",", "vpc_id", ",", "watcher_plugin", ",", "health_plugin", ",", "iterations", ",", "sleep_time", ",", "route_check_time_interval", "=", "30", ")", ":", "q_route_spec", "=", "watcher_plugin", ".", "get_route_spec_queue...
48.038835
25.203883
def get_l2cap_options (sock): """get_l2cap_options (sock, mtu) Gets L2CAP options for the specified L2CAP socket. Options are: omtu, imtu, flush_to, mode, fcs, max_tx, txwin_size. """ # TODO this should be in the C module, because it depends # directly on struct l2cap_options layout. s = so...
[ "def", "get_l2cap_options", "(", "sock", ")", ":", "# TODO this should be in the C module, because it depends", "# directly on struct l2cap_options layout.", "s", "=", "sock", ".", "getsockopt", "(", "SOL_L2CAP", ",", "L2CAP_OPTIONS", ",", "12", ")", "options", "=", "list...
38.454545
15.090909
def install_app(cls, id, raw, api=None, raw_format=None): """ Installs and app. :param id: App identifier. :param raw: Raw cwl data. :param api: Api instance. :param raw_format: Format of raw app data being sent, json by default :return: App object. """ ...
[ "def", "install_app", "(", "cls", ",", "id", ",", "raw", ",", "api", "=", "None", ",", "raw_format", "=", "None", ")", ":", "api", "=", "api", "if", "api", "else", "cls", ".", "_API", "raw_format", "=", "raw_format", ".", "lower", "(", ")", "if", ...
33.457143
15.514286
def run_all(logdir, verbose=False): """Run simulations on a reasonable set of parameters. Arguments: logdir: the directory into which to store all the runs' data verbose: if true, print out each run's name as it begins """ for initial_temperature in [270.0, 310.0, 350.0]: for final_temperature in [...
[ "def", "run_all", "(", "logdir", ",", "verbose", "=", "False", ")", ":", "for", "initial_temperature", "in", "[", "270.0", ",", "310.0", ",", "350.0", "]", ":", "for", "final_temperature", "in", "[", "270.0", ",", "310.0", ",", "350.0", "]", ":", "for"...
41.4375
15.8125
def get_dict(self): """ Get the dict of the instance of this class. :return: """ return { 'authors': self.authors, 'date_download': self.date_download, 'date_modify': self.date_modify, 'date_publish': self.date_publish, ...
[ "def", "get_dict", "(", "self", ")", ":", "return", "{", "'authors'", ":", "self", ".", "authors", ",", "'date_download'", ":", "self", ".", "date_download", ",", "'date_modify'", ":", "self", ".", "date_modify", ",", "'date_publish'", ":", "self", ".", "d...
33
8.272727
def update(self): """todo: Docstring for update :return: :rtype: """ logger.debug("") rd = self.repo_dir logger.debug("pkg path %s", rd) if not rd: print( "unable to find pkg '%s'. %s" % (self.name, did_u_mean(self.name)) ...
[ "def", "update", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"\"", ")", "rd", "=", "self", ".", "repo_dir", "logger", ".", "debug", "(", "\"pkg path %s\"", ",", "rd", ")", "if", "not", "rd", ":", "print", "(", "\"unable to find pkg '%s'. %s\"",...
30.642857
20.404762
def process_quotes(self, text): """Process quotes.""" escaped = False in_quotes = False current = [] quoted = [] i = _util.StringIter(text) iter(i) for t in i: if not escaped and t == "\\": escaped = True elif escap...
[ "def", "process_quotes", "(", "self", ",", "text", ")", ":", "escaped", "=", "False", "in_quotes", "=", "False", "current", "=", "[", "]", "quoted", "=", "[", "]", "i", "=", "_util", ".", "StringIter", "(", "text", ")", "iter", "(", "i", ")", "for"...
28.230769
14.615385
def prepend(self, bs): """Prepend a bitstring to the current bitstring. bs -- The bitstring to prepend. """ bs = self._converttobitstring(bs) self._prepend(bs) self._pos += bs.len
[ "def", "prepend", "(", "self", ",", "bs", ")", ":", "bs", "=", "self", ".", "_converttobitstring", "(", "bs", ")", "self", ".", "_prepend", "(", "bs", ")", "self", ".", "_pos", "+=", "bs", ".", "len" ]
24.555556
14.222222
def PowersOf(logbase, count, lower=0, include_zero=True): """Returns a list of count powers of logbase (from logbase**lower).""" if not include_zero: return [logbase ** i for i in range(lower, count+lower)] else: return [0] + [logbase ** i for i in range(lower, count+lower)]
[ "def", "PowersOf", "(", "logbase", ",", "count", ",", "lower", "=", "0", ",", "include_zero", "=", "True", ")", ":", "if", "not", "include_zero", ":", "return", "[", "logbase", "**", "i", "for", "i", "in", "range", "(", "lower", ",", "count", "+", ...
49.666667
19.666667
def haversine(lon1, lat1, lon2, lat2, radians=False, earth_rad=6371.227): """ Allows to calculate geographical distance using the haversine formula. :param lon1: longitude of the first set of locations :type lon1: numpy.ndarray :param lat1: latitude of the frist set of locations :type lat1:...
[ "def", "haversine", "(", "lon1", ",", "lat1", ",", "lon2", ",", "lat2", ",", "radians", "=", "False", ",", "earth_rad", "=", "6371.227", ")", ":", "if", "not", "radians", ":", "cfact", "=", "np", ".", "pi", "/", "180.", "lon1", "=", "cfact", "*", ...
33.245283
16.075472
def eff_request_host(request): """Return a tuple (request-host, effective request-host name). As defined by RFC 2965, except both are lowercased. """ erhn = req_host = request_host(request) if req_host.find(".") == -1 and not IPV4_RE.search(req_host): erhn = req_host + ".local" return ...
[ "def", "eff_request_host", "(", "request", ")", ":", "erhn", "=", "req_host", "=", "request_host", "(", "request", ")", "if", "req_host", ".", "find", "(", "\".\"", ")", "==", "-", "1", "and", "not", "IPV4_RE", ".", "search", "(", "req_host", ")", ":",...
32.5
15.4
def get_record(self, name): """ Get a record for the registered name, which will be a set of matching desired "module names" for the given path. """ return set().union(self.records.get(name, set()))
[ "def", "get_record", "(", "self", ",", "name", ")", ":", "return", "set", "(", ")", ".", "union", "(", "self", ".", "records", ".", "get", "(", "name", ",", "set", "(", ")", ")", ")" ]
33.285714
16.714286
def validate(self, value, model_instance): """Check value is a valid JSON string, raise ValidationError on error.""" if isinstance(value, six.string_types): super(JSONField, self).validate(value, model_instance) try: json.loads(value) except Ex...
[ "def", "validate", "(", "self", ",", "value", ",", "model_instance", ")", ":", "if", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "super", "(", "JSONField", ",", "self", ")", ".", "validate", "(", "value", ",", "model_instance",...
41.666667
8.555556
def write_graphml(docgraph, output_file): """ takes a document graph, converts it into GraphML format and writes it to a file. """ dg_copy = deepcopy(docgraph) layerset2str(dg_copy) attriblist2str(dg_copy) remove_root_metadata(dg_copy) nx_write_graphml(dg_copy, output_file)
[ "def", "write_graphml", "(", "docgraph", ",", "output_file", ")", ":", "dg_copy", "=", "deepcopy", "(", "docgraph", ")", "layerset2str", "(", "dg_copy", ")", "attriblist2str", "(", "dg_copy", ")", "remove_root_metadata", "(", "dg_copy", ")", "nx_write_graphml", ...
30.1
11.1
def _skySub(imageSet,paramDict,saveFile=False): """ subtract the sky from all the chips in the imagefile that imageSet represents imageSet is a single imageObject reference paramDict should be the subset from an actual config object if saveFile=True, then images that have been sky subtracted are sa...
[ "def", "_skySub", "(", "imageSet", ",", "paramDict", ",", "saveFile", "=", "False", ")", ":", "_skyValue", "=", "0.0", "#this will be the sky value computed for the exposure", "skyKW", "=", "\"MDRIZSKY\"", "#header keyword that contains the sky that's been subtracted", "#just...
43.375
23.803571
def _identify(self, dataframe): """ Returns a list of indexes containing only the points that pass the filter. Parameters ---------- dataframe : DataFrame """ ## # TODO Fix this implementation. (i.e., why not support just 'left') # At the moment t...
[ "def", "_identify", "(", "self", ",", "dataframe", ")", ":", "##", "# TODO Fix this implementation. (i.e., why not support just 'left')", "# At the moment this implementation won't work at all.", "# The logic here can be simplified.", "id1", "=", "dataframe", "[", "self", ".", "c...
28.708333
21.041667
def subscribers(self): """Property returning the subscriber list""" return [s for p, s in sorted(self._subscribers, key=lambda x: x[0])]
[ "def", "subscribers", "(", "self", ")", ":", "return", "[", "s", "for", "p", ",", "s", "in", "sorted", "(", "self", ".", "_subscribers", ",", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ")", "]" ]
50
18
def get_version(): """Get LanguageTool version.""" version = _get_attrib().get('version') if not version: match = re.search(r"LanguageTool-?.*?(\S+)$", get_directory()) if match: version = match.group(1) return version
[ "def", "get_version", "(", ")", ":", "version", "=", "_get_attrib", "(", ")", ".", "get", "(", "'version'", ")", "if", "not", "version", ":", "match", "=", "re", ".", "search", "(", "r\"LanguageTool-?.*?(\\S+)$\"", ",", "get_directory", "(", ")", ")", "i...
31.875
15.5
def expand_alleles(p, tolerance=0): """ Returns expanded allele set given the tolerance. """ _p = set() for x in p: _p |= set(range(x - tolerance, x + tolerance + 1)) return _p
[ "def", "expand_alleles", "(", "p", ",", "tolerance", "=", "0", ")", ":", "_p", "=", "set", "(", ")", "for", "x", "in", "p", ":", "_p", "|=", "set", "(", "range", "(", "x", "-", "tolerance", ",", "x", "+", "tolerance", "+", "1", ")", ")", "ret...
25.125
14.125
def sense_dep(self, target): """Search for a DEP Target in active or passive communication mode. """ # Set timeout for PSL_RES and ATR_RES self.chipset.rf_configuration(0x02, b"\x0B\x0B\x0A") return super(Device, self).sense_dep(target)
[ "def", "sense_dep", "(", "self", ",", "target", ")", ":", "# Set timeout for PSL_RES and ATR_RES", "self", ".", "chipset", ".", "rf_configuration", "(", "0x02", ",", "b\"\\x0B\\x0B\\x0A\"", ")", "return", "super", "(", "Device", ",", "self", ")", ".", "sense_dep...
38.714286
12.714286
def alpha(self): r'''Thermal diffusivity of the chemical at its current temperature, pressure, and phase in units of [m^2/s]. .. math:: \alpha = \frac{k}{\rho Cp} Examples -------- >>> Chemical('furfural').alpha 8.696537158635412e-08 ''' ...
[ "def", "alpha", "(", "self", ")", ":", "return", "phase_select_property", "(", "phase", "=", "self", ".", "phase", ",", "l", "=", "self", ".", "alphal", ",", "g", "=", "self", ".", "alphag", ")" ]
29.846154
23.538462
def unique(seq, key=None): """ Create a unique list or tuple from a provided list or tuple and preserve the order. :param seq: The list or tuple to preserve unique items from. :type seq: list, tuple :param key: If key is provided it will be called during the comparison process. :type key: function, None """ ...
[ "def", "unique", "(", "seq", ",", "key", "=", "None", ")", ":", "if", "key", "is", "None", ":", "key", "=", "lambda", "x", ":", "x", "preserved_type", "=", "type", "(", "seq", ")", "if", "preserved_type", "not", "in", "(", "list", ",", "tuple", "...
26.96
21.28
def set_window_title(self): """Set window title.""" if DEV is not None: title = u"Spyder %s (Python %s.%s)" % (__version__, sys.version_info[0], sys.version_info[1]) else: ...
[ "def", "set_window_title", "(", "self", ")", ":", "if", "DEV", "is", "not", "None", ":", "title", "=", "u\"Spyder %s (Python %s.%s)\"", "%", "(", "__version__", ",", "sys", ".", "version_info", "[", "0", "]", ",", "sys", ".", "version_info", "[", "1", "]...
39.958333
20.708333
def remove_tracks(self, track_indices): """ Remove tracks specified by `track_indices`. Parameters ---------- track_indices : list The indices of the tracks to be removed. """ if isinstance(track_indices, int): track_indices = [track_indi...
[ "def", "remove_tracks", "(", "self", ",", "track_indices", ")", ":", "if", "isinstance", "(", "track_indices", ",", "int", ")", ":", "track_indices", "=", "[", "track_indices", "]", "self", ".", "tracks", "=", "[", "track", "for", "idx", ",", "track", "i...
30.928571
14.642857
def histogram(values, num_bins, bounds, normalized=True, plot=False, color='b'): """Generate a histogram plot. Parameters ---------- values : :obj:`numpy.ndarray` An array of values to put in the histogram. num_bins : int The number equal-width bins in the histogram. bounds : ...
[ "def", "histogram", "(", "values", ",", "num_bins", ",", "bounds", ",", "normalized", "=", "True", ",", "plot", "=", "False", ",", "color", "=", "'b'", ")", ":", "hist", ",", "bins", "=", "np", ".", "histogram", "(", "values", ",", "bins", "=", "nu...
30.615385
21.74359
def get_unique_sample_files(file_samples): """Filter file_sample data frame to only keep one file per sample. Params ------ file_samples : `pandas.DataFrame` A data frame containing a mapping between file IDs and sample barcodes. This type of data frame is returned by :meth:`get_fil...
[ "def", "get_unique_sample_files", "(", "file_samples", ")", ":", "assert", "isinstance", "(", "file_samples", ",", "pd", ".", "DataFrame", ")", "df", "=", "file_samples", "# use shorter variable name", "# sort data frame by file ID", "df", "=", "df", ".", "sort_values...
36.019231
23.115385
def config_factory(ConfigClass=dict, prefix=None, config_file=None ): '''return a class, which implements the compiler_factory API :param ConfigClass: defaults to dict. A simple factory (without parameter) for a dictionary-like object, which implements __setitem__() method. Ad...
[ "def", "config_factory", "(", "ConfigClass", "=", "dict", ",", "prefix", "=", "None", ",", "config_file", "=", "None", ")", ":", "config_factory", "=", "ConfigClass", "class", "ConfigFactory", ":", "def", "__init__", "(", "self", ",", "command", ")", ":", ...
38.252252
23.675676
def model_code_key_prefix(code_location_key_prefix, model_name, image): """Returns the s3 key prefix for uploading code during model deployment The location returned is a potential concatenation of 2 parts 1. code_location_key_prefix if it exists 2. model_name or a name derived from the image ...
[ "def", "model_code_key_prefix", "(", "code_location_key_prefix", ",", "model_name", ",", "image", ")", ":", "training_job_name", "=", "sagemaker", ".", "utils", ".", "name_from_image", "(", "image", ")", "return", "'/'", ".", "join", "(", "filter", "(", "None", ...
44.058824
25
def path_serialize(cls, path): """ Given a list of [{'hash': ..., 'order': ...}], serialize it to a string. """ # make it into a netstring path_parts = ['{}-{}'.format(p['order'], p['hash']) for p in path] path_ns_parts = ['{}:{},'.format(len(pp), pp) for pp in path_parts...
[ "def", "path_serialize", "(", "cls", ",", "path", ")", ":", "# make it into a netstring", "path_parts", "=", "[", "'{}-{}'", ".", "format", "(", "p", "[", "'order'", "]", ",", "p", "[", "'hash'", "]", ")", "for", "p", "in", "path", "]", "path_ns_parts", ...
45.666667
15.666667
def wait_for_up(self, timeout=40): """ Wait until port is up and running, including all parameters (admin state, oper state, license etc.). :param timeout: max time to wait for port up. """ self.wait_for_states(timeout, 'up') connectionStatus = self.get_attribute('connectionSta...
[ "def", "wait_for_up", "(", "self", ",", "timeout", "=", "40", ")", ":", "self", ".", "wait_for_states", "(", "timeout", ",", "'up'", ")", "connectionStatus", "=", "self", ".", "get_attribute", "(", "'connectionStatus'", ")", ".", "strip", "(", ")", "if", ...
52.727273
24.454545
def fastdtw(x, y, radius=1, dist=None): ''' return the approximate distance between 2 time series with O(N) time and memory complexity Parameters ---------- x : array_like input array 1 y : array_like input array 2 radius : int siz...
[ "def", "fastdtw", "(", "x", ",", "y", ",", "radius", "=", "1", ",", "dist", "=", "None", ")", ":", "x", ",", "y", ",", "dist", "=", "__prep_inputs", "(", "x", ",", "y", ",", "dist", ")", "return", "__fastdtw", "(", "x", ",", "y", ",", "radius...
37.205128
21.102564
def add_coalescent_model(self, Tc, **kwargs): """Add a coalescent model to the tree and optionally optimze Parameters ---------- Tc : float,str If this is a float, it will be interpreted as the inverse merger rate in molecular clock units, if its is a """...
[ "def", "add_coalescent_model", "(", "self", ",", "Tc", ",", "*", "*", "kwargs", ")", ":", "from", ".", "merger_models", "import", "Coalescent", "self", ".", "logger", "(", "'TreeTime.run: adding coalescent prior with Tc='", "+", "str", "(", "Tc", ")", ",", "1"...
41.785714
21.178571
def convert2wavenumber(rsr): """ Take rsr data set with all channels and detectors for an instrument each with a set of wavelengths and normalised responses and convert to wavenumbers and responses :rsr: Relative Spectral Response function (all bands) Returns: :retv: Relative Spectral Res...
[ "def", "convert2wavenumber", "(", "rsr", ")", ":", "retv", "=", "{", "}", "for", "chname", "in", "rsr", ".", "keys", "(", ")", ":", "# Go through bands/channels", "retv", "[", "chname", "]", "=", "{", "}", "for", "det", "in", "rsr", "[", "chname", "]...
41.209302
19.674419
def _from_dict(cls, _dict): """Initialize a RuntimeEntity object from a json dictionary.""" args = {} xtra = _dict.copy() if 'entity' in _dict: args['entity'] = _dict.get('entity') del xtra['entity'] else: raise ValueError( 'Req...
[ "def", "_from_dict", "(", "cls", ",", "_dict", ")", ":", "args", "=", "{", "}", "xtra", "=", "_dict", ".", "copy", "(", ")", "if", "'entity'", "in", "_dict", ":", "args", "[", "'entity'", "]", "=", "_dict", ".", "get", "(", "'entity'", ")", "del"...
35.810811
16.324324
def p_debug(self, message): "Format and print debug messages" print("{}{} `{}`".format(self._debug_indent * " ", message, repr(self.p_suffix(10))))
[ "def", "p_debug", "(", "self", ",", "message", ")", ":", "print", "(", "\"{}{} `{}`\"", ".", "format", "(", "self", ".", "_debug_indent", "*", "\" \"", ",", "message", ",", "repr", "(", "self", ".", "p_suffix", "(", "10", ")", ")", ")", ")" ]
48.25
14.75
def enable_aliases_autocomplete(_, **kwargs): """ Enable aliases autocomplete by injecting aliases into Azure CLI tab completion list. """ external_completions = kwargs.get('external_completions', []) prefix = kwargs.get('cword_prefix', []) cur_commands = kwargs.get('comp_words', []) alias_t...
[ "def", "enable_aliases_autocomplete", "(", "_", ",", "*", "*", "kwargs", ")", ":", "external_completions", "=", "kwargs", ".", "get", "(", "'external_completions'", ",", "[", "]", ")", "prefix", "=", "kwargs", ".", "get", "(", "'cword_prefix'", ",", "[", "...
53.545455
25.363636
def run_dssp(pdb, path=True, outfile=None): """Uses DSSP to find helices and extracts helices from a pdb file or string. Parameters ---------- pdb : str Path to pdb file or string. path : bool, optional Indicates if pdb is a path or a string. outfile : str, optional File...
[ "def", "run_dssp", "(", "pdb", ",", "path", "=", "True", ",", "outfile", "=", "None", ")", ":", "if", "not", "path", ":", "if", "type", "(", "pdb", ")", "==", "str", ":", "pdb", "=", "pdb", ".", "encode", "(", ")", "try", ":", "temp_pdb", "=", ...
27.275
17.15
def get_word_id (root): """ lookup/assign a unique identify for each word root """ global UNIQ_WORDS # in practice, this should use a microservice via some robust # distributed cache, e.g., Redis, Cassandra, etc. if root not in UNIQ_WORDS: UNIQ_WORDS[root] = len(UNIQ_WORDS) ret...
[ "def", "get_word_id", "(", "root", ")", ":", "global", "UNIQ_WORDS", "# in practice, this should use a microservice via some robust", "# distributed cache, e.g., Redis, Cassandra, etc.", "if", "root", "not", "in", "UNIQ_WORDS", ":", "UNIQ_WORDS", "[", "root", "]", "=", "len...
27.416667
16.083333
def make_compound_ctype(self, varname): """ Create a ctypes type that corresponds to a compound type in memory. """ # look up the type name compoundname = self.get_var_type(varname) nfields = self.inq_compound(compoundname) # for all the fields look up the type, ...
[ "def", "make_compound_ctype", "(", "self", ",", "varname", ")", ":", "# look up the type name", "compoundname", "=", "self", ".", "get_var_type", "(", "varname", ")", "nfields", "=", "self", ".", "inq_compound", "(", "compoundname", ")", "# for all the fields look u...
36.151515
14.878788
def unique(list1, list2): """ Get unique items in list1 that are not in list2 :return: Unique items only in list 1 """ set2 = set(list2) list1_unique = [x for x in tqdm(list1, desc='Unique', total=len(list1)) if x not in set2] return list1_unique
[ "def", "unique", "(", "list1", ",", "list2", ")", ":", "set2", "=", "set", "(", "list2", ")", "list1_unique", "=", "[", "x", "for", "x", "in", "tqdm", "(", "list1", ",", "desc", "=", "'Unique'", ",", "total", "=", "len", "(", "list1", ")", ")", ...
33.375
14.375
def run(self, job_list): """ Runs a job set which consists of the jobs in an iterable job list. """ if self._closed: raise RuntimeError("master is closed") return self._manager.add_job_set(job_list)
[ "def", "run", "(", "self", ",", "job_list", ")", ":", "if", "self", ".", "_closed", ":", "raise", "RuntimeError", "(", "\"master is closed\"", ")", "return", "self", ".", "_manager", ".", "add_job_set", "(", "job_list", ")" ]
27.111111
18.444444
def _get(self, k, obj=None): 'Return Option object for k in context of obj. Cache result until any set().' opt = self._cache.get((k, obj), None) if opt is None: opt = self._opts._get(k, obj) self._cache[(k, obj or vd.sheet)] = opt return opt
[ "def", "_get", "(", "self", ",", "k", ",", "obj", "=", "None", ")", ":", "opt", "=", "self", ".", "_cache", ".", "get", "(", "(", "k", ",", "obj", ")", ",", "None", ")", "if", "opt", "is", "None", ":", "opt", "=", "self", ".", "_opts", ".",...
41.571429
16.142857
def bar(self, serie, rescale=False): """Draw a bar graph for a serie""" serie_node = self.svg.serie(serie) bars = self.svg.node(serie_node['plot'], class_="histbars") points = serie.points for i, (y, x0, x1) in enumerate(points): if None in (x0, x1, y) or (self.logar...
[ "def", "bar", "(", "self", ",", "serie", ",", "rescale", "=", "False", ")", ":", "serie_node", "=", "self", ".", "svg", ".", "serie", "(", "serie", ")", "bars", "=", "self", ".", "svg", ".", "node", "(", "serie_node", "[", "'plot'", "]", ",", "cl...
35.818182
18.818182
def combine(self, other, name=None): """Combine with another PhaseGroup and return the result.""" return PhaseGroup( setup=self.setup + other.setup, main=self.main + other.main, teardown=self.teardown + other.teardown, name=name)
[ "def", "combine", "(", "self", ",", "other", ",", "name", "=", "None", ")", ":", "return", "PhaseGroup", "(", "setup", "=", "self", ".", "setup", "+", "other", ".", "setup", ",", "main", "=", "self", ".", "main", "+", "other", ".", "main", ",", "...
37.571429
8.142857
def _uniquely_named_callbacks(self): """Make sure that the returned dict of named callbacks is unique w.r.t. to the callback name. User-defined names will not be renamed on conflict, instead an exception will be raised. The same goes for the event where renaming leads to a conflict. ...
[ "def", "_uniquely_named_callbacks", "(", "self", ")", ":", "grouped_cbs", ",", "names_set_by_user", "=", "self", ".", "_callbacks_grouped_by_name", "(", ")", "for", "name", ",", "cbs", "in", "grouped_cbs", ".", "items", "(", ")", ":", "if", "len", "(", "cbs"...
51.695652
18.173913
def get_source(self, environment, template): """Get the template source, filename and reload helper for a template. It's passed the environment and template name and has to return a tuple in the form ``(source, filename, uptodate)`` or raise a `TemplateNotFound` error if it can't locate ...
[ "def", "get_source", "(", "self", ",", "environment", ",", "template", ")", ":", "if", "not", "self", ".", "has_source_access", ":", "raise", "RuntimeError", "(", "'%s cannot provide access to the source'", "%", "self", ".", "__class__", ".", "__name__", ")", "r...
55.409091
22.727273
def _update_limits_from_api(self): """ Query EC2's DescribeAccountAttributes API action, and update limits with the quotas returned. Updates ``self.limits``. """ self.connect() logger.info("Querying EC2 DescribeAccountAttributes for limits") lims = self.conn.descr...
[ "def", "_update_limits_from_api", "(", "self", ")", ":", "self", ".", "connect", "(", ")", "logger", ".", "info", "(", "\"Querying EC2 DescribeAccountAttributes for limits\"", ")", "lims", "=", "self", ".", "conn", ".", "describe_account_limits", "(", ")", "self",...
46
14.833333
def convert_to_cgs(self, equivalence=None, **kwargs): """ Convert the array and in-place to the equivalent cgs units. Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions. Parameters ---------- equi...
[ "def", "convert_to_cgs", "(", "self", ",", "equivalence", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "convert_to_units", "(", "self", ".", "units", ".", "get_cgs_equivalent", "(", ")", ",", "equivalence", "=", "equivalence", ",", "*", "...
33.272727
22.181818
def attach(self, volume_id, instance_id, device_path): """Attach a volume to an instance, exposing it with a device name.""" return self.call("AttachVolume", VolumeId=volume_id, InstanceId=instance_id, Device=device_path)
[ "def", "attach", "(", "self", ",", "volume_id", ",", "instance_id", ",", "device_path", ")", ":", "return", "self", ".", "call", "(", "\"AttachVolume\"", ",", "VolumeId", "=", "volume_id", ",", "InstanceId", "=", "instance_id", ",", "Device", "=", "device_pa...
56.6
9.2
def Reset(self): """Preserves FSM but resets starting state and current record.""" # Current state is Start state. self._cur_state = self.states['Start'] self._cur_state_name = 'Start' # Clear table of results and current record. self._result = [] self._ClearAllRecord()
[ "def", "Reset", "(", "self", ")", ":", "# Current state is Start state.", "self", ".", "_cur_state", "=", "self", ".", "states", "[", "'Start'", "]", "self", ".", "_cur_state_name", "=", "'Start'", "# Clear table of results and current record.", "self", ".", "_resul...
29.1
15.8
def _line_by_type(self, line, header, hgroups, htypes, out, want_type, collapse_quals_fn = None): """Parse out key value pairs for line information based on a group of values. """ for index, htype in ((i, t) for i, t in enumerate(htypes) if t == want_type): col ...
[ "def", "_line_by_type", "(", "self", ",", "line", ",", "header", ",", "hgroups", ",", "htypes", ",", "out", ",", "want_type", ",", "collapse_quals_fn", "=", "None", ")", ":", "for", "index", ",", "htype", "in", "(", "(", "i", ",", "t", ")", "for", ...
45.538462
16.153846
def load(**options): """ Load this driver :param \*\*options: A variadic list of options """ log.msg("Hello!, I am a dummy, so I won't do a thing!") if len(options): log.msg_debug("I have received a bunch of options, here they come ...") for o, v in options.items(): ...
[ "def", "load", "(", "*", "*", "options", ")", ":", "log", ".", "msg", "(", "\"Hello!, I am a dummy, so I won't do a thing!\"", ")", "if", "len", "(", "options", ")", ":", "log", ".", "msg_debug", "(", "\"I have received a bunch of options, here they come ...\"", ")"...
34.25
17.083333
def _glob_to_regexp(pat): """Compile a glob pattern into a regexp. We need to do this because fnmatch allows * to match /, which we don't want. E.g. an MANIFEST.in exclude of 'dirname/*css' should match 'dirname/foo.css' but not 'dirname/subdir/bar.css'. """ pat = fnmatch.translate(pat) # ...
[ "def", "_glob_to_regexp", "(", "pat", ")", ":", "pat", "=", "fnmatch", ".", "translate", "(", "pat", ")", "# Note that distutils in Python 2.6 has a buggy glob_to_re in", "# distutils.filelist -- it converts '*.cfg' to '[^/]*cfg' instead", "# of '[^\\\\]*cfg' on Windows.", "sep", ...
45.538462
18.692308
def mktk03(terms, seed, G2, G3): """ generates a list of gauss coefficients drawn from the TK03 distribution """ # random.seed(n) p = 0 n = seed gh = [] g10, sfact, afact = -18e3, 3.8, 2.4 g20 = G2 * g10 g30 = G3 * g10 alpha = g10/afact s1 = s_l(1, alpha) s10 = sfact * s1...
[ "def", "mktk03", "(", "terms", ",", "seed", ",", "G2", ",", "G3", ")", ":", "# random.seed(n)", "p", "=", "0", "n", "=", "seed", "gh", "=", "[", "]", "g10", ",", "sfact", ",", "afact", "=", "-", "18e3", ",", "3.8", ",", "2.4", "g20", "=", "G2...
25.311111
15.222222
def WriteBuildYaml(self, fd, build_timestamp=True): """Write build spec to fd.""" output = { "Client.build_environment": rdf_client.Uname.FromCurrentSystem().signature(), "Template.build_type": config.CONFIG.Get("ClientBuilder.build_type", context=self.context), "...
[ "def", "WriteBuildYaml", "(", "self", ",", "fd", ",", "build_timestamp", "=", "True", ")", ":", "output", "=", "{", "\"Client.build_environment\"", ":", "rdf_client", ".", "Uname", ".", "FromCurrentSystem", "(", ")", ".", "signature", "(", ")", ",", "\"Templ...
41.029412
20.882353
def dump(self): """Output all recorded metrics""" with self.lock: atexit.unregister(self.dump) self.fh.close()
[ "def", "dump", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "atexit", ".", "unregister", "(", "self", ".", "dump", ")", "self", ".", "fh", ".", "close", "(", ")" ]
29.2
11
def load_from_string(self, content, container, **kwargs): """ Load config from given string 'content'. :param content: Config content string :param container: callble to make a container object later :param kwargs: optional keyword parameters to be sanitized :: dict :re...
[ "def", "load_from_string", "(", "self", ",", "content", ",", "container", ",", "*", "*", "kwargs", ")", ":", "_not_implemented", "(", "self", ",", "content", ",", "container", ",", "*", "*", "kwargs", ")" ]
39.181818
19
def install_upgrade_powerline(): ''' More infos: https://powerline.readthedocs.io/en/latest/installation.html#pip-installation ''' checkup_git_repo_legacy('https://github.com/powerline/powerline.git') path_to_powerline = os.path.expanduser('~/repos/powerline') run(flo('pip install --user -...
[ "def", "install_upgrade_powerline", "(", ")", ":", "checkup_git_repo_legacy", "(", "'https://github.com/powerline/powerline.git'", ")", "path_to_powerline", "=", "os", ".", "path", ".", "expanduser", "(", "'~/repos/powerline'", ")", "run", "(", "flo", "(", "'pip install...
43.923077
21.615385
def update_category(uid, postdata, kwargs): ''' Update the category of the post. ''' catid = kwargs['catid'] if ('catid' in kwargs and MCategory.get_by_uid(kwargs['catid'])) else None post_data = postdata current_infos = MPost2Catalog.query_by_entity_uid(uid, kind='').objects() new_catego...
[ "def", "update_category", "(", "uid", ",", "postdata", ",", "kwargs", ")", ":", "catid", "=", "kwargs", "[", "'catid'", "]", "if", "(", "'catid'", "in", "kwargs", "and", "MCategory", ".", "get_by_uid", "(", "kwargs", "[", "'catid'", "]", ")", ")", "els...
29.555556
22.62963
def dropEvent(self, event): """ Reimplements the :meth:`QTabWidget.dropEvent` method. :param event: QEvent. :type event: QEvent """ LOGGER.debug("> '{0}' widget drop event accepted!".format(self.__class__.__name__)) self.content_dropped.emit(event)
[ "def", "dropEvent", "(", "self", ",", "event", ")", ":", "LOGGER", ".", "debug", "(", "\"> '{0}' widget drop event accepted!\"", ".", "format", "(", "self", ".", "__class__", ".", "__name__", ")", ")", "self", ".", "content_dropped", ".", "emit", "(", "event...
29.7
18.9
def qdict_get_list(qdict, k): """ get list from QueryDict and remove blank date from list. """ pks = qdict.getlist(k) return [e for e in pks if e]
[ "def", "qdict_get_list", "(", "qdict", ",", "k", ")", ":", "pks", "=", "qdict", ".", "getlist", "(", "k", ")", "return", "[", "e", "for", "e", "in", "pks", "if", "e", "]" ]
26.833333
8.833333
def quaternion_to_rotation_matrix(quaternion): """Compute the rotation matrix representated by the quaternion""" c, x, y, z = quaternion return np.array([ [c*c + x*x - y*y - z*z, 2*x*y - 2*c*z, 2*x*z + 2*c*y ], [2*x*y + 2*c*z, c*c - x*x + y*y - z*z, 2*y*z - 2*c*x ...
[ "def", "quaternion_to_rotation_matrix", "(", "quaternion", ")", ":", "c", ",", "x", ",", "y", ",", "z", "=", "quaternion", "return", "np", ".", "array", "(", "[", "[", "c", "*", "c", "+", "x", "*", "x", "-", "y", "*", "y", "-", "z", "*", "z", ...
51.125
22.25
def show_processing(message=""): """ Shows processing behavior. :param message: Operation description. :type message: unicode :return: Object. :rtype: object """ def show_processingDecorator(object): """ Shows processing behavior. :param object: Object to decor...
[ "def", "show_processing", "(", "message", "=", "\"\"", ")", ":", "def", "show_processingDecorator", "(", "object", ")", ":", "\"\"\"\n Shows processing behavior.\n\n :param object: Object to decorate.\n :type object: object\n :return: Object.\n :rtype: ...
24.8
15.6
def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:...
[ "def", "mac2eui64", "(", "mac", ",", "prefix", "=", "None", ")", ":", "# http://tools.ietf.org/html/rfc4291#section-2.5.1", "eui64", "=", "re", ".", "sub", "(", "r'[.:-]'", ",", "''", ",", "mac", ")", ".", "lower", "(", ")", "eui64", "=", "eui64", "[", "...
34.526316
18.526316
def wave_saver(u, x, y, t): """save the wave log""" global u_hist global t_hist t_hist.append(t) u_hist.append(1.0*u)
[ "def", "wave_saver", "(", "u", ",", "x", ",", "y", ",", "t", ")", ":", "global", "u_hist", "global", "t_hist", "t_hist", ".", "append", "(", "t", ")", "u_hist", ".", "append", "(", "1.0", "*", "u", ")" ]
22
15.833333
def add_pending_greenlet(self, greenlet: Greenlet): """ Ensures an error on the passed greenlet crashes self/main greenlet. """ def remove(_): self.greenlets.remove(greenlet) self.greenlets.append(greenlet) greenlet.link_exception(self.on_error) greenlet.link_value(...
[ "def", "add_pending_greenlet", "(", "self", ",", "greenlet", ":", "Greenlet", ")", ":", "def", "remove", "(", "_", ")", ":", "self", ".", "greenlets", ".", "remove", "(", "greenlet", ")", "self", ".", "greenlets", ".", "append", "(", "greenlet", ")", "...
35.444444
13.777778
def _parse_parmlist(self, parmlist): """ Parses a PARMLIST string into a dictionary of name and value pairs. The parsing is complicated by the following: - parameter keynames may or may not include a length specification - delimiter characters (=, &) may a...
[ "def", "_parse_parmlist", "(", "self", ",", "parmlist", ")", ":", "parmlist", "=", "\"&\"", "+", "parmlist", "name_re", "=", "re", ".", "compile", "(", "r'\\&([A-Z0-9_]+)(\\[\\d+\\])?='", ")", "results", "=", "{", "}", "offset", "=", "0", "match", "=", "na...
36.571429
17.142857
def remove_empty_suppxls(suppxls): """Remove empty superpixels. Sometimes there are superpixels(labels), which are empty. To overcome subsequent problems, these empty superpixels should be removed. inputs: suppxls ... image with suppxls labels, ndarray [MxN]-same size as im outputs: new_...
[ "def", "remove_empty_suppxls", "(", "suppxls", ")", ":", "n_suppxls", "=", "np", ".", "int", "(", "suppxls", ".", "max", "(", ")", "+", "1", ")", "new_supps", "=", "np", ".", "zeros", "(", "suppxls", ".", "shape", ",", "dtype", "=", "np", ".", "int...
40.823529
19.058824