text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def query(self, model): '''Return a query for ``model`` when it needs to be indexed. ''' session = self.router.session() fields = tuple((f.name for f in model._meta.scalarfields if f.type == 'text')) qs = session.query(model).load_only(*fields) ...
[ "def", "query", "(", "self", ",", "model", ")", ":", "session", "=", "self", ".", "router", ".", "session", "(", ")", "fields", "=", "tuple", "(", "(", "f", ".", "name", "for", "f", "in", "model", ".", "_meta", ".", "scalarfields", "if", "f", "."...
42.3
15.7
def handle_cable(cable, handler, standalone=True): """\ Emits event from the provided `cable` to the handler. `cable` A cable object. `handler` A ICableHandler instance. `standalone` Indicates if a `start` and `end` event should be issued (default: ``True``). ...
[ "def", "handle_cable", "(", "cable", ",", "handler", ",", "standalone", "=", "True", ")", ":", "def", "datetime", "(", "dt", ")", ":", "date", ",", "time", "=", "dt", ".", "split", "(", "u' '", ")", "if", "len", "(", "time", ")", "==", "5", ":", ...
35.564516
12.516129
def getElementsByAttr(self, attrName, attrValue): ''' getElementsByAttr - Search children of this tag for tags with an attribute name/value pair @param attrName - Attribute name (lowercase) @param attrValue - Attribute value @return - TagCollection of matching e...
[ "def", "getElementsByAttr", "(", "self", ",", "attrName", ",", "attrValue", ")", ":", "elements", "=", "[", "]", "for", "child", "in", "self", ".", "children", ":", "if", "child", ".", "getAttribute", "(", "attrName", ")", "==", "attrValue", ":", "elemen...
39.2
21.333333
def use_args( self, argmap, req=None, locations=core.Parser.DEFAULT_LOCATIONS, as_kwargs=False, validate=None, error_status_code=None, error_headers=None, ): """Decorator that injects parsed arguments into a view callable. Supports the ...
[ "def", "use_args", "(", "self", ",", "argmap", ",", "req", "=", "None", ",", "locations", "=", "core", ".", "Parser", ".", "DEFAULT_LOCATIONS", ",", "as_kwargs", "=", "False", ",", "validate", "=", "None", ",", "error_status_code", "=", "None", ",", "err...
43.311475
19.52459
def process_memory_map(attrs=None, where=None): ''' Return process_memory_map information from osquery CLI Example: .. code-block:: bash salt '*' osquery.process_memory_map ''' if __grains__['os_family'] in ['RedHat', 'Debian']: return _osquery_cmd(table='process_memory_map', ...
[ "def", "process_memory_map", "(", "attrs", "=", "None", ",", "where", "=", "None", ")", ":", "if", "__grains__", "[", "'os_family'", "]", "in", "[", "'RedHat'", ",", "'Debian'", "]", ":", "return", "_osquery_cmd", "(", "table", "=", "'process_memory_map'", ...
32.846154
27.615385
def delete_project(self, project): """ Deletes all versions of a project. First class, maps to Scrapyd's delete project endpoint. """ url = self._build_url(constants.DELETE_PROJECT_ENDPOINT) data = { 'project': project, } self.client.post(url, ...
[ "def", "delete_project", "(", "self", ",", "project", ")", ":", "url", "=", "self", ".", "_build_url", "(", "constants", ".", "DELETE_PROJECT_ENDPOINT", ")", "data", "=", "{", "'project'", ":", "project", ",", "}", "self", ".", "client", ".", "post", "("...
32.909091
16.181818
def transition(self, duration, brightness=None): """ Transition wrapper. Short-circuit transition if necessary. :param duration: Duration of transition. :param brightness: Transition to this brightness. """ if duration == 0: if brightness is not None: ...
[ "def", "transition", "(", "self", ",", "duration", ",", "brightness", "=", "None", ")", ":", "if", "duration", "==", "0", ":", "if", "brightness", "is", "not", "None", ":", "self", ".", "brightness", "=", "brightness", "return", "if", "brightness", "!=",...
32.642857
12.357143
def initinfo(self) -> Tuple[Union[float, int, bool], bool]: """The actual initial value of the given parameter. Some |Parameter| subclasses define another value for class attribute `INIT` than |None| to provide a default value. Let's define a parameter test class and prepare a function...
[ "def", "initinfo", "(", "self", ")", "->", "Tuple", "[", "Union", "[", "float", ",", "int", ",", "bool", "]", ",", "bool", "]", ":", "init", "=", "self", ".", "INIT", "if", "(", "init", "is", "not", "None", ")", "and", "hydpy", ".", "pub", ".",...
32.0625
20.40625
def dump_to_stream(self, cnf, stream, **kwargs): """ Dump config 'cnf' to a file or file-like object 'stream'. :param cnf: Shell variables data to dump :param stream: Shell script file or file like object :param kwargs: backend-specific optional keyword parameters :: dict ...
[ "def", "dump_to_stream", "(", "self", ",", "cnf", ",", "stream", ",", "*", "*", "kwargs", ")", ":", "for", "key", ",", "val", "in", "anyconfig", ".", "compat", ".", "iteritems", "(", "cnf", ")", ":", "stream", ".", "write", "(", "\"%s='%s'%s\"", "%",...
43.6
17.4
def getInfo(self): """ Returns a DevInfo instance, a named tuple with the following items: - bustype: one of BUS_USB, BUS_HIL, BUS_BLUETOOTH or BUS_VIRTUAL - vendor: device's vendor number - product: device's product number """ devinfo = _hidraw_devinfo() ...
[ "def", "getInfo", "(", "self", ")", ":", "devinfo", "=", "_hidraw_devinfo", "(", ")", "self", ".", "_ioctl", "(", "_HIDIOCGRAWINFO", ",", "devinfo", ",", "True", ")", "return", "DevInfo", "(", "devinfo", ".", "bustype", ",", "devinfo", ".", "vendor", ","...
42.7
13.9
def update(self, roomId, title=None, **request_parameters): """Update details for a room, by ID. Args: roomId(basestring): The room ID. title(basestring): A user-friendly name for the room. **request_parameters: Additional request parameters (provides ...
[ "def", "update", "(", "self", ",", "roomId", ",", "title", "=", "None", ",", "*", "*", "request_parameters", ")", ":", "check_type", "(", "roomId", ",", "basestring", ",", "may_be_none", "=", "False", ")", "check_type", "(", "roomId", ",", "basestring", ...
34.83871
23.580645
def hpx_to_axes(h, npix): """ Generate a sequence of bin edge vectors corresponding to the axes of a HPX object.""" x = h.ebins z = np.arange(npix[-1] + 1) return x, z
[ "def", "hpx_to_axes", "(", "h", ",", "npix", ")", ":", "x", "=", "h", ".", "ebins", "z", "=", "np", ".", "arange", "(", "npix", "[", "-", "1", "]", "+", "1", ")", "return", "x", ",", "z" ]
26
16.285714
def solve_one(self, expr, constrain=False): """ Concretize a symbolic :class:`~manticore.core.smtlib.expression.Expression` into one solution. :param manticore.core.smtlib.Expression expr: Symbolic value to concretize :param bool constrain: If True, constrain expr to concretized...
[ "def", "solve_one", "(", "self", ",", "expr", ",", "constrain", "=", "False", ")", ":", "expr", "=", "self", ".", "migrate_expression", "(", "expr", ")", "value", "=", "self", ".", "_solver", ".", "get_value", "(", "self", ".", "_constraints", ",", "ex...
37.5
16.611111
def show_network(self): """! @brief Shows structure of the network: neurons and connections between them. """ dimension = len(self.__location[0]) if (dimension != 3) and (dimension != 2): raise NameError('Network that is located in different ...
[ "def", "show_network", "(", "self", ")", ":", "dimension", "=", "len", "(", "self", ".", "__location", "[", "0", "]", ")", "if", "(", "dimension", "!=", "3", ")", "and", "(", "dimension", "!=", "2", ")", ":", "raise", "NameError", "(", "'Network that...
53.392857
35.357143
def auto_data_specs(self): """ Data specs in the sub-study class that are not explicitly provided in the name map """ for spec in self.study_class.data_specs(): if spec.name not in self._name_map: yield spec
[ "def", "auto_data_specs", "(", "self", ")", ":", "for", "spec", "in", "self", ".", "study_class", ".", "data_specs", "(", ")", ":", "if", "spec", ".", "name", "not", "in", "self", ".", "_name_map", ":", "yield", "spec" ]
33.5
12
def clearFilter(self): """ Clear all filters. """ if self._dataFrameOriginal is not None: self.layoutAboutToBeChanged.emit() self._dataFrame = self._dataFrameOriginal self._dataFrameOriginal = None self.layoutChanged.emit()
[ "def", "clearFilter", "(", "self", ")", ":", "if", "self", ".", "_dataFrameOriginal", "is", "not", "None", ":", "self", ".", "layoutAboutToBeChanged", ".", "emit", "(", ")", "self", ".", "_dataFrame", "=", "self", ".", "_dataFrameOriginal", "self", ".", "_...
32.777778
7
def _draw_number(screen, x_offset, y_offset, number, style='class:clock', transparent=False): " Write number at position. " fg = Char(' ', 'class:clock') bg = Char(' ', '') for y, row in enumerate(_numbers[number]): screen_row = screen.data_buffer[y + y_offset] for x, n...
[ "def", "_draw_number", "(", "screen", ",", "x_offset", ",", "y_offset", ",", "number", ",", "style", "=", "'class:clock'", ",", "transparent", "=", "False", ")", ":", "fg", "=", "Char", "(", "' '", ",", "'class:clock'", ")", "bg", "=", "Char", "(", "' ...
36.769231
12.769231
def _set_int(self, commands, name): """ set integer value from commands """ if name in commands: try: value = int(commands[name]) setattr(self, name, value) except ValueError: pass
[ "def", "_set_int", "(", "self", ",", "commands", ",", "name", ")", ":", "if", "name", "in", "commands", ":", "try", ":", "value", "=", "int", "(", "commands", "[", "name", "]", ")", "setattr", "(", "self", ",", "name", ",", "value", ")", "except", ...
27.5
7.7
def deleted(self): 'Return datetime.datetime or None if the file isnt deleted' _d = self.folder.attrib.get('deleted', None) if _d is None: return None return dateutil.parser.parse(str(_d))
[ "def", "deleted", "(", "self", ")", ":", "_d", "=", "self", ".", "folder", ".", "attrib", ".", "get", "(", "'deleted'", ",", "None", ")", "if", "_d", "is", "None", ":", "return", "None", "return", "dateutil", ".", "parser", ".", "parse", "(", "str"...
43.2
14.4
def provide_label(self): """The name and shape of label provided by this iterator""" return [(k, tuple([self.batch_size] + list(v.shape[1:]))) for k, v in self.label]
[ "def", "provide_label", "(", "self", ")", ":", "return", "[", "(", "k", ",", "tuple", "(", "[", "self", ".", "batch_size", "]", "+", "list", "(", "v", ".", "shape", "[", "1", ":", "]", ")", ")", ")", "for", "k", ",", "v", "in", "self", ".", ...
60
21.666667
def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args): ''' Delete endpoints of an Openstack service CLI Examples: .. code-block:: bash salt 'v2' keystone.endpoint_delete nova [region=RegionOne] salt 'v3' keystone.endpoint_delete nova interface=adm...
[ "def", "endpoint_delete", "(", "service", ",", "region", "=", "None", ",", "profile", "=", "None", ",", "interface", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kstone", "=", "auth", "(", "profile", ",", "*", "*", "connection_args", ")", ...
38.45
27.05
def _link_rels(obj, fields=None, save=False, overwrite=False): """Populate any database related fields (ForeignKeyField, OneToOneField) that have `_get`ters to populate them with""" if not fields: meta = obj._meta fields = [f.name for f in meta.fields if hasattr(f, 'do_related_class') and not f....
[ "def", "_link_rels", "(", "obj", ",", "fields", "=", "None", ",", "save", "=", "False", ",", "overwrite", "=", "False", ")", ":", "if", "not", "fields", ":", "meta", "=", "obj", ".", "_meta", "fields", "=", "[", "f", ".", "name", "for", "f", "in"...
56.466667
32.2
def ex6_2(n): """ Generate a triangle pulse as described in Example 6-2 of Chapter 6. You need to supply an index array n that covers at least [-2, 5]. The function returns the hard-coded signal of the example. Parameters ---------- n : time index ndarray covering at least -2 ...
[ "def", "ex6_2", "(", "n", ")", ":", "x", "=", "np", ".", "zeros", "(", "len", "(", "n", ")", ")", "for", "k", ",", "nn", "in", "enumerate", "(", "n", ")", ":", "if", "nn", ">=", "-", "2", "and", "nn", "<=", "5", ":", "x", "[", "k", "]",...
25
19.466667
def get_function(rule, domain, normalize, **parameters): """ Create a quadrature function and set default parameter values. Args: rule (str): Name of quadrature rule defined in ``QUAD_FUNCTIONS``. domain (Dist, numpy.ndarray): Defines ``lower`` and ``upper`` that is ...
[ "def", "get_function", "(", "rule", ",", "domain", ",", "normalize", ",", "*", "*", "parameters", ")", ":", "from", ".", ".", ".", "distributions", ".", "baseclass", "import", "Dist", "if", "isinstance", "(", "domain", ",", "Dist", ")", ":", "lower", "...
37.616667
17.65
def veoh_download(url, output_dir = '.', merge = False, info_only = False, **kwargs): '''Get item_id''' if re.match(r'http://www.veoh.com/watch/\w+', url): item_id = match1(url, r'http://www.veoh.com/watch/(\w+)') elif re.match(r'http://www.veoh.com/m/watch.php\?v=\.*', url): item_id = match...
[ "def", "veoh_download", "(", "url", ",", "output_dir", "=", "'.'", ",", "merge", "=", "False", ",", "info_only", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "re", ".", "match", "(", "r'http://www.veoh.com/watch/\\w+'", ",", "url", ")", ":", ...
58.777778
29.888889
def make_association(self, record): """ contstruct the association :param record: :return: modeled association of genotype to mammalian phenotype """ model = Model(self.graph) record['relation']['id'] = self.resolve("has phenotype") # define the triple ...
[ "def", "make_association", "(", "self", ",", "record", ")", ":", "model", "=", "Model", "(", "self", ".", "graph", ")", "record", "[", "'relation'", "]", "[", "'id'", "]", "=", "self", ".", "resolve", "(", "\"has phenotype\"", ")", "# define the triple", ...
37.777778
19.2
def _openssl_key_iv(passphrase, salt): """ Returns a (key, iv) tuple that can be used in AES symmetric encryption from a *passphrase* (a byte or unicode string) and *salt* (a byte array). """ def _openssl_kdf(req): if hasattr(passphrase, 'encode'): passwd = passphrase.encode('asc...
[ "def", "_openssl_key_iv", "(", "passphrase", ",", "salt", ")", ":", "def", "_openssl_kdf", "(", "req", ")", ":", "if", "hasattr", "(", "passphrase", ",", "'encode'", ")", ":", "passwd", "=", "passphrase", ".", "encode", "(", "'ascii'", ",", "'ignore'", "...
37.772727
13.954545
def _set_suffix_links(self): ''' Sets all suffix links in all nodes in this trie. ''' self._suffix_links_set = True for current, parent in self.bfs(): # skip the root node if parent is None: continue current.longest_prefix = par...
[ "def", "_set_suffix_links", "(", "self", ")", ":", "self", ".", "_suffix_links_set", "=", "True", "for", "current", ",", "parent", "in", "self", ".", "bfs", "(", ")", ":", "# skip the root node", "if", "parent", "is", "None", ":", "continue", "current", "....
37.676471
11.264706
def get_client_parameters(username: str, ip_address: str, user_agent: str) -> dict: """ Get query parameters for filtering AccessAttempt queryset. This method returns a dict that guarantees iteration order for keys and values, and can so be used in e.g. the generation of hash keys or other deterministi...
[ "def", "get_client_parameters", "(", "username", ":", "str", ",", "ip_address", ":", "str", ",", "user_agent", ":", "str", ")", "->", "dict", ":", "filter_kwargs", "=", "dict", "(", ")", "if", "settings", ".", "AXES_ONLY_USER_FAILURES", ":", "# 1. Only individ...
41.259259
25.037037
def convert_vectored_io_slice_to_final_path_name(local_path, ase): # type: (pathlib.Path, # blobxfer.models.azure.StorageEntity) -> pathlib.Path """Convert vectored io slice to final path name :param pathlib.Path local_path: local path :param blobxfer.models.azure.StorageE...
[ "def", "convert_vectored_io_slice_to_final_path_name", "(", "local_path", ",", "ase", ")", ":", "# type: (pathlib.Path,", "# blobxfer.models.azure.StorageEntity) -> pathlib.Path", "name", "=", "blobxfer", ".", "models", ".", "metadata", ".", "remove_vectored_io_slice_suffi...
44.666667
11.733333
def return_max_phrase(run, idx, dictionary): """ Finds the maximal phrase in the run starting from the given index. It uses the dictionary to find sequences of ids that can be merged into a phrase. :param run: a run of ids :param idx: the position in the run to start looking fo...
[ "def", "return_max_phrase", "(", "run", ",", "idx", ",", "dictionary", ")", ":", "if", "idx", "<", "len", "(", "run", ")", "and", "run", "[", "idx", "]", "in", "dictionary", ":", "id", "=", "run", "[", "idx", "]", "rv", ",", "rv_idx", "=", "Phras...
53.857143
28.809524
def compensate_system_time_change(self, difference): # pragma: no cover, # not with unit tests """If a system time change occurs we have to update properties time related to reflect change :param difference: difference between new time and old time :type difference: :re...
[ "def", "compensate_system_time_change", "(", "self", ",", "difference", ")", ":", "# pragma: no cover,", "# not with unit tests", "# We only need to change some value", "for", "prop", "in", "(", "'last_notification'", ",", "'last_state_change'", ",", "'last_hard_state_change'",...
43.933333
16.866667
def reset_index(self, level=None, drop=False, name=None, inplace=False): """ Generate a new DataFrame or Series with the index reset. This is useful when the index needs to be treated as a column, or when the index is meaningless and needs to be reset to the default before anoth...
[ "def", "reset_index", "(", "self", ",", "level", "=", "None", ",", "drop", "=", "False", ",", "name", "=", "None", ",", "inplace", "=", "False", ")", ":", "inplace", "=", "validate_bool_kwarg", "(", "inplace", ",", "'inplace'", ")", "if", "drop", ":", ...
33.152672
22.78626
def parse_tuple(self, simplified=False, with_condexpr=True, extra_end_rules=None, explicit_parentheses=False): """Works like `parse_expression` but if multiple expressions are delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created. This method could also return a...
[ "def", "parse_tuple", "(", "self", ",", "simplified", "=", "False", ",", "with_condexpr", "=", "True", ",", "extra_end_rules", "=", "None", ",", "explicit_parentheses", "=", "False", ")", ":", "lineno", "=", "self", ".", "stream", ".", "current", ".", "lin...
41.888889
21.537037
def limit_x( self, limit_lower = None, # float limit_upper = None # float ): """ get or set x limits of the current axes x_min, x_max = limit_x() # return the current limit_x limit_x(x_min, x_max) # set the limit_x to x_min, x_max """ ...
[ "def", "limit_x", "(", "self", ",", "limit_lower", "=", "None", ",", "# float", "limit_upper", "=", "None", "# float", ")", ":", "if", "limit_lower", "is", "None", "and", "limit_upper", "is", "None", ":", "return", "self", ".", "_limit_x", "elif", "hasattr...
30.478261
15.695652
def get_cell_shift(flow_model): """Get flow direction induced cell shift dict. Args: flow_model: Currently, "TauDEM", "ArcGIS", and "Whitebox" are supported. """ assert flow_model.lower() in FlowModelConst.d8_deltas return FlowModelConst.d8_deltas.get(flow_model.lower...
[ "def", "get_cell_shift", "(", "flow_model", ")", ":", "assert", "flow_model", ".", "lower", "(", ")", "in", "FlowModelConst", ".", "d8_deltas", "return", "FlowModelConst", ".", "d8_deltas", ".", "get", "(", "flow_model", ".", "lower", "(", ")", ")" ]
45.285714
17.714286
def computeMatchProbabilityOmega(k, bMax, theta, nTrials=100): """ The Omega match probability estimates the probability of matching when both vectors have exactly b components in common. This function computes this probability for b=1 to bMax. For each value of b this function: 1) Creates nTrials instan...
[ "def", "computeMatchProbabilityOmega", "(", "k", ",", "bMax", ",", "theta", ",", "nTrials", "=", "100", ")", ":", "omegaProb", "=", "np", ".", "zeros", "(", "bMax", "+", "1", ")", "for", "b", "in", "range", "(", "1", ",", "bMax", "+", "1", ")", "...
32.714286
24.657143
def validate_enum_attribute(self, attribute: str, candidates: Set[Union[str, int, float]]) -> None: """ Validates that the attribute value is among the candidates """ self.add_errors( validate_enum_attribute(self.fully_qualified_name, self._spec, attribute, ca...
[ "def", "validate_enum_attribute", "(", "self", ",", "attribute", ":", "str", ",", "candidates", ":", "Set", "[", "Union", "[", "str", ",", "int", ",", "float", "]", "]", ")", "->", "None", ":", "self", ".", "add_errors", "(", "validate_enum_attribute", "...
65.2
24.8
def _prepare_b_jkl_mn(readout_povm, pauli_basis, pre_channel_ops, post_channel_ops, rho0): """ Prepare the coefficient matrix for process tomography. This function uses sparse matrices for much greater efficiency. The coefficient matrix is defined as: .. math:: B_{(jkl)(mn)}=\sum_{r,q}\pi_...
[ "def", "_prepare_b_jkl_mn", "(", "readout_povm", ",", "pauli_basis", ",", "pre_channel_ops", ",", "post_channel_ops", ",", "rho0", ")", ":", "c_jk_m", "=", "state_tomography", ".", "_prepare_c_jk_m", "(", "readout_povm", ",", "pauli_basis", ",", "post_channel_ops", ...
57.560976
34.97561
def from_rotation_matrix(rot, nonorthogonal=True): """Convert input 3x3 rotation matrix to unit quaternion By default, if scipy.linalg is available, this function uses Bar-Itzhack's algorithm to allow for non-orthogonal matrices. [J. Guidance, Vol. 23, No. 6, p. 1085 <http://dx.doi.org/10.2514/2.4654>]...
[ "def", "from_rotation_matrix", "(", "rot", ",", "nonorthogonal", "=", "True", ")", ":", "try", ":", "from", "scipy", "import", "linalg", "except", "ImportError", ":", "linalg", "=", "False", "rot", "=", "np", ".", "array", "(", "rot", ",", "copy", "=", ...
42.934307
20.014599
def get_hwclock(): ''' Get current hardware clock setting (UTC or localtime) CLI Example: .. code-block:: bash salt '*' timezone.get_hwclock ''' if salt.utils.path.which('timedatectl'): ret = _timedatectl() for line in (x.strip() for x in ret['stdout'].splitlines()): ...
[ "def", "get_hwclock", "(", ")", ":", "if", "salt", ".", "utils", ".", "path", ".", "which", "(", "'timedatectl'", ")", ":", "ret", "=", "_timedatectl", "(", ")", "for", "line", "in", "(", "x", ".", "strip", "(", ")", "for", "x", "in", "ret", "[",...
40.288288
15.945946
def tool_classpath_from_products(products, key, scope): """Get a classpath for the tool previously registered under key in the given scope. :param products: The products of the current pants run. :type products: :class:`pants.goal.products.Products` :param string key: The key the tool configuration was...
[ "def", "tool_classpath_from_products", "(", "products", ",", "key", ",", "scope", ")", ":", "callback_product_map", "=", "products", ".", "get_data", "(", "'jvm_build_tools_classpath_callbacks'", ")", "or", "{", "}", "callback", "=", "callback_product_map", ".", "ge...
48.9375
22.1875
def footprints_from_address(address, distance, footprint_type='building', retain_invalid=False): """ Get footprints within some distance north, south, east, and west of an address. Parameters ---------- address : string the address to geocode to a lat-long point distance : numeric ...
[ "def", "footprints_from_address", "(", "address", ",", "distance", ",", "footprint_type", "=", "'building'", ",", "retain_invalid", "=", "False", ")", ":", "# geocode the address string to a (lat, lon) point", "point", "=", "geocode", "(", "query", "=", "address", ")"...
32.407407
24.851852
def timeout_at(clock, coro=None, *args): '''Execute the specified coroutine and return its result. However, issue a cancellation request to the calling task after seconds have elapsed. When this happens, a TaskTimeout exception is raised. If coro is None, the result of this function serves as an a...
[ "def", "timeout_at", "(", "clock", ",", "coro", "=", "None", ",", "*", "args", ")", ":", "if", "coro", ":", "return", "_timeout_after_func", "(", "clock", ",", "True", ",", "coro", ",", "args", ")", "return", "TimeoutAfter", "(", "clock", ",", "absolut...
42.45
24.95
def build(templates=None, schemes=None, base_output_dir=None): """Main build function to initiate building process.""" template_dirs = templates or get_template_dirs() scheme_files = get_scheme_files(schemes) base_output_dir = base_output_dir or rel_to_cwd('output') # raise LookupError if there is ...
[ "def", "build", "(", "templates", "=", "None", ",", "schemes", "=", "None", ",", "base_output_dir", "=", "None", ")", ":", "template_dirs", "=", "templates", "or", "get_template_dirs", "(", ")", "scheme_files", "=", "get_scheme_files", "(", "schemes", ")", "...
34.916667
21.291667
def run_plasmid_extractor(self): """ Create and run the plasmid extractor system call """ logging.info('Extracting plasmids') # Define the system call extract_command = 'PlasmidExtractor.py -i {inf} -o {outf} -p {plasdb} -d {db} -t {cpus} -nc' \ .format(inf=se...
[ "def", "run_plasmid_extractor", "(", "self", ")", ":", "logging", ".", "info", "(", "'Extracting plasmids'", ")", "# Define the system call", "extract_command", "=", "'PlasmidExtractor.py -i {inf} -o {outf} -p {plasdb} -d {db} -t {cpus} -nc'", ".", "format", "(", "inf", "=", ...
47.47619
14.047619
def start(self): """ Start process. :returns: itself :rtype: OutputExecutor .. note:: Process will be considered started, when defined banner will appear in process output. """ super(OutputExecutor, self).start() # get a polling...
[ "def", "start", "(", "self", ")", ":", "super", "(", "OutputExecutor", ",", "self", ")", ".", "start", "(", ")", "# get a polling object", "self", ".", "poll_obj", "=", "select", ".", "poll", "(", ")", "# register a file descriptor", "# POLLIN because we will wa...
25.827586
21.068966
def get(datasets_identifiers, identifier_type='hid', history_id=None): """ Given the history_id that is displayed to the user, this function will download the file[s] from the history and stores them under /import/ Return value[s] are the path[s] to the dataset[s] stored under /import/ "...
[ "def", "get", "(", "datasets_identifiers", ",", "identifier_type", "=", "'hid'", ",", "history_id", "=", "None", ")", ":", "history_id", "=", "history_id", "or", "os", ".", "environ", "[", "'HISTORY_ID'", "]", "# The object version of bioblend is to slow in retrieving...
54.107143
23.75
def add_or_replace_filter(self, new_filter): """Replaces null or blank filter or adds filter to existing list.""" if self.filter.lower() in self._FILTERS_TO_REPLACE: self.filter = new_filter elif new_filter not in self.filter.split(";"): self.filter = ";".join([self.filte...
[ "def", "add_or_replace_filter", "(", "self", ",", "new_filter", ")", ":", "if", "self", ".", "filter", ".", "lower", "(", ")", "in", "self", ".", "_FILTERS_TO_REPLACE", ":", "self", ".", "filter", "=", "new_filter", "elif", "new_filter", "not", "in", "self...
52.142857
8.142857
def traverse(fn, expr, type=ir.Expr, container=Stack): """Utility for generic expression tree traversal Parameters ---------- fn : Callable[[ir.Expr], Tuple[Union[Boolean, Iterable], Any]] This function will be applied on each expressions, it must return a tuple. The first element of th...
[ "def", "traverse", "(", "fn", ",", "expr", ",", "type", "=", "ir", ".", "Expr", ",", "container", "=", "Stack", ")", ":", "args", "=", "expr", "if", "isinstance", "(", "expr", ",", "collections", ".", "abc", ".", "Iterable", ")", "else", "[", "expr...
32.826087
20.413043
def js_reverse_inline(context): """ Outputs a string of javascript that can generate URLs via the use of the names given to those URLs. """ if 'request' in context: default_urlresolver = get_resolver(getattr(context['request'], 'urlconf', None)) else: default_urlresolver = get_re...
[ "def", "js_reverse_inline", "(", "context", ")", ":", "if", "'request'", "in", "context", ":", "default_urlresolver", "=", "get_resolver", "(", "getattr", "(", "context", "[", "'request'", "]", ",", "'urlconf'", ",", "None", ")", ")", "else", ":", "default_u...
37.8
15.4
def hincrby(self, hashkey, attribute, increment=1): """Emulate hincrby.""" return self._hincrby(hashkey, attribute, 'HINCRBY', long, increment)
[ "def", "hincrby", "(", "self", ",", "hashkey", ",", "attribute", ",", "increment", "=", "1", ")", ":", "return", "self", ".", "_hincrby", "(", "hashkey", ",", "attribute", ",", "'HINCRBY'", ",", "long", ",", "increment", ")" ]
39.25
21.75
def _parse_config(self): """Parses the mlag global configuration Returns: dict: A dict object that is intended to be merged into the resource dict """ config = self.get_block('mlag configuration') cfg = dict() cfg.update(self._parse_domain_id(...
[ "def", "_parse_config", "(", "self", ")", ":", "config", "=", "self", ".", "get_block", "(", "'mlag configuration'", ")", "cfg", "=", "dict", "(", ")", "cfg", ".", "update", "(", "self", ".", "_parse_domain_id", "(", "config", ")", ")", "cfg", ".", "up...
36.933333
14.4
def mode(self): """ Reading returns the currently selected mode. Writing sets the mode. Generally speaking when the mode changes any sensor or motor devices associated with the port will be removed new ones loaded, however this this will depend on the individual driver implementi...
[ "def", "mode", "(", "self", ")", ":", "self", ".", "_mode", ",", "value", "=", "self", ".", "get_attr_string", "(", "self", ".", "_mode", ",", "'mode'", ")", "return", "value" ]
47.555556
24
def quote_value(value): """ convert values to mysql code for the same mostly delegate directly to the mysql lib, but some exceptions exist """ try: if value == None: return SQL_NULL elif isinstance(value, SQL): return quote_sql(value.template, value.param) ...
[ "def", "quote_value", "(", "value", ")", ":", "try", ":", "if", "value", "==", "None", ":", "return", "SQL_NULL", "elif", "isinstance", "(", "value", ",", "SQL", ")", ":", "return", "quote_sql", "(", "value", ".", "template", ",", "value", ".", "param"...
42.153846
16.923077
def _compute_term3(self, C, rrup): """ This computes the term f3 in equation 34, page 1021 but corrected according to the erratum. """ f3 = np.zeros_like(rrup) idx_between_70_130 = (rrup > 70) & (rrup <= 130) idx_greater_130 = rrup > 130 f3[idx_between_7...
[ "def", "_compute_term3", "(", "self", ",", "C", ",", "rrup", ")", ":", "f3", "=", "np", ".", "zeros_like", "(", "rrup", ")", "idx_between_70_130", "=", "(", "rrup", ">", "70", ")", "&", "(", "rrup", "<=", "130", ")", "idx_greater_130", "=", "rrup", ...
29.55
20.95
def ls_packages(self): """ List packages in this store. """ packages = [] pkgdir = os.path.join(self._path, self.PKG_DIR) if not os.path.isdir(pkgdir): return [] for team in sub_dirs(pkgdir): for user in sub_dirs(self.team_path(team)): ...
[ "def", "ls_packages", "(", "self", ")", ":", "packages", "=", "[", "]", "pkgdir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_path", ",", "self", ".", "PKG_DIR", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "pkgdir", ")", ...
53.857143
24.714286
def new(cls, freeform_builder, x, y): """Return a new _LineSegment object ending at point *(x, y)*. Both *x* and *y* are rounded to the nearest integer before use. """ return cls(freeform_builder, int(round(x)), int(round(y)))
[ "def", "new", "(", "cls", ",", "freeform_builder", ",", "x", ",", "y", ")", ":", "return", "cls", "(", "freeform_builder", ",", "int", "(", "round", "(", "x", ")", ")", ",", "int", "(", "round", "(", "y", ")", ")", ")" ]
42.333333
16.666667
def _credssp_processor(self, context): """ Implements a state machine :return: """ http_response = (yield) credssp_context = self._get_credssp_header(http_response) if credssp_context is None: raise Exception('The remote host did not respond with a \'...
[ "def", "_credssp_processor", "(", "self", ",", "context", ")", ":", "http_response", "=", "(", "yield", ")", "credssp_context", "=", "self", ".", "_get_credssp_header", "(", "http_response", ")", "if", "credssp_context", "is", "None", ":", "raise", "Exception", ...
48.699115
26.557522
def sortDictList(dictList,**kwargs): ''' students = [ {'name':'john','class':'A', 'year':15}, {'name':'jane','class':'B', 'year':12}, {'name':'dave','class':'B', 'year':10} ] rslt = sortDictList(students,cond_keys=['name','class','year']) ...
[ "def", "sortDictList", "(", "dictList", ",", "*", "*", "kwargs", ")", ":", "def", "default_eq_func", "(", "value1", ",", "value2", ")", ":", "cond", "=", "(", "value1", "==", "value2", ")", "return", "(", "cond", ")", "def", "default_gt_func", "(", "va...
30.257576
17.621212
def find(self, signature = None, order = 0, since = None, until = None, offset = None, limit = None): """ Retrieve all crash dumps in the database, optionally filtering them by signature and timestamp, and/or sorting them by timestamp. Resul...
[ "def", "find", "(", "self", ",", "signature", "=", "None", ",", "order", "=", "0", ",", "since", "=", "None", ",", "until", "=", "None", ",", "offset", "=", "None", ",", "limit", "=", "None", ")", ":", "# Validate the parameters.", "if", "since", "an...
37.164557
20.734177
def execute(filename, formatted_name): """Renames a file based on the name generated using metadata. :param str filename: absolute path and filename of original file :param str formatted_name: absolute path and new filename """ if os.path.isfile(formatted_name): # If the destination exists...
[ "def", "execute", "(", "filename", ",", "formatted_name", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "formatted_name", ")", ":", "# If the destination exists, skip rename unless overwrite enabled", "if", "not", "cfg", ".", "CONF", ".", "overwrite_file_en...
39.235294
18.411765
def transform_data(function, input_data): ''' a function to apply a function to each value in a nested dictionary :param function: callable function with a single input of any datatype :param input_data: dictionary or list with nested data to transform :return: dictionary or list with data transformed...
[ "def", "transform_data", "(", "function", ",", "input_data", ")", ":", "# construct copy", "try", ":", "from", "copy", "import", "deepcopy", "output_data", "=", "deepcopy", "(", "input_data", ")", "except", ":", "raise", "ValueError", "(", "'transform_data() input...
34.382353
21.205882
def remove_actor(self, actor, reset_camera=False): """ Removes an actor from the Plotter. Parameters ---------- actor : vtk.vtkActor Actor that has previously added to the Renderer. reset_camera : bool, optional Resets camera so all actors can be...
[ "def", "remove_actor", "(", "self", ",", "actor", ",", "reset_camera", "=", "False", ")", ":", "for", "renderer", "in", "self", ".", "renderers", ":", "renderer", ".", "remove_actor", "(", "actor", ",", "reset_camera", ")", "return", "True" ]
27.52381
17.809524
def momentum(data, period): """ Momentum. Formula: DATA[i] - DATA[i - period] """ catch_errors.check_for_period_error(data, period) momentum = [data[idx] - data[idx+1-period] for idx in range(period-1, len(data))] momentum = fill_for_noncomputable_vals(data, momentum) return moment...
[ "def", "momentum", "(", "data", ",", "period", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "period", ")", "momentum", "=", "[", "data", "[", "idx", "]", "-", "data", "[", "idx", "+", "1", "-", "period", "]", "for", "idx...
25.916667
21.25
def binary(self, new_binary): """Sets location of the browser binary, either by string or ``FirefoxBinary`` instance. """ if not isinstance(new_binary, FirefoxBinary): new_binary = FirefoxBinary(new_binary) self._binary = new_binary
[ "def", "binary", "(", "self", ",", "new_binary", ")", ":", "if", "not", "isinstance", "(", "new_binary", ",", "FirefoxBinary", ")", ":", "new_binary", "=", "FirefoxBinary", "(", "new_binary", ")", "self", ".", "_binary", "=", "new_binary" ]
34.75
10.75
def _main(self, client, copy_source, bucket, key, upload_id, part_number, extra_args, callbacks, size): """ :param client: The client to use when calling PutObject :param copy_source: The CopySource parameter to use :param bucket: The name of the bucket to upload to ...
[ "def", "_main", "(", "self", ",", "client", ",", "copy_source", ",", "bucket", ",", "key", ",", "upload_id", ",", "part_number", ",", "extra_args", ",", "callbacks", ",", "size", ")", ":", "response", "=", "client", ".", "upload_part_copy", "(", "CopySourc...
44.16129
18.870968
def validate_public_key(value): """ Check that the given value is a valid RSA Public key in either PEM or OpenSSH format. If it is invalid, raises ``django.core.exceptions.ValidationError``. """ is_valid = False exc = None for load in (load_pem_public_key, load_ssh_public_key): if n...
[ "def", "validate_public_key", "(", "value", ")", ":", "is_valid", "=", "False", "exc", "=", "None", "for", "load", "in", "(", "load_pem_public_key", ",", "load_ssh_public_key", ")", ":", "if", "not", "is_valid", ":", "try", ":", "load", "(", "value", ".", ...
31.833333
20.722222
def accepted(self): """Successfully close the widget and return the loaded model. This method is also a `SLOT`. The dialog will be closed, when the `ok` button is pressed. If a `DataFrame` was loaded, it will be emitted by the signal `load`. """ model = self._previewTab...
[ "def", "accepted", "(", "self", ")", ":", "model", "=", "self", ".", "_previewTableView", ".", "model", "(", ")", "if", "model", "is", "not", "None", ":", "df", "=", "model", ".", "dataFrame", "(", ")", ".", "copy", "(", ")", "dfModel", "=", "DataF...
37.625
15.875
def send_animation( self, chat_id: Union[int, str], animation: str, caption: str = "", parse_mode: str = "", duration: int = 0, width: int = 0, height: int = 0, thumb: str = None, disable_notification: bool = None, reply_to_message_...
[ "def", "send_animation", "(", "self", ",", "chat_id", ":", "Union", "[", "int", ",", "str", "]", ",", "animation", ":", "str", ",", "caption", ":", "str", "=", "\"\"", ",", "parse_mode", ":", "str", "=", "\"\"", ",", "duration", ":", "int", "=", "0...
44.913793
24.074713
def overlaps(self, other): """Tell if self is partly contained in other.""" return self.network_address in other or ( self.broadcast_address in other or ( other.network_address in self or ( other.broadcast_address in self)))
[ "def", "overlaps", "(", "self", ",", "other", ")", ":", "return", "self", ".", "network_address", "in", "other", "or", "(", "self", ".", "broadcast_address", "in", "other", "or", "(", "other", ".", "network_address", "in", "self", "or", "(", "other", "."...
47.166667
9.166667
def updateflags(self, flags): """ Thin wrapper around build_update(flags=X). This only handles simple status changes, anything like needinfo requestee needs to call build_update + update_bugs directly :param flags: Dictionary of the form {"flagname": "status"}, example ...
[ "def", "updateflags", "(", "self", ",", "flags", ")", ":", "flaglist", "=", "[", "]", "for", "key", ",", "value", "in", "flags", ".", "items", "(", ")", ":", "flaglist", ".", "append", "(", "{", "\"name\"", ":", "key", ",", "\"status\"", ":", "valu...
42.285714
16.428571
def apply_changes(self, event): """ applies the changes in the various attribute boxes of this object to all highlighted fit objects in the logger, these changes are reflected both in this object and in the Zeq_GUI parent object. @param: event -> the wx.ButtonEvent that triggered this function ...
[ "def", "apply_changes", "(", "self", ",", "event", ")", ":", "new_name", "=", "self", ".", "name_box", ".", "GetLineText", "(", "0", ")", "new_color", "=", "self", ".", "color_box", ".", "GetValue", "(", ")", "new_tmin", "=", "self", ".", "tmin_box", "...
47.938776
26.591837
def vignetting(xy, f=100, alpha=0, rot=0, tilt=0, cx=50, cy=50): ''' Vignetting equation using the KANG-WEISS-MODEL see http://research.microsoft.com/en-us/um/people/sbkang/publications/eccv00.pdf f - focal length alpha - coefficient in the geometric vignetting factor tilt - tilt angl...
[ "def", "vignetting", "(", "xy", ",", "f", "=", "100", ",", "alpha", "=", "0", ",", "rot", "=", "0", ",", "tilt", "=", "0", ",", "cx", "=", "50", ",", "cy", "=", "50", ")", ":", "x", ",", "y", "=", "xy", "# distance to image center:\r", "dist", ...
28.689655
19.931034
def pkginfo_to_metadata(egg_info_path, pkginfo_path): """ Convert .egg-info directory with PKG-INFO to the Metadata 1.3 aka old-draft Metadata 2.0 format. """ pkg_info = read_pkg_info(pkginfo_path) pkg_info.replace_header('Metadata-Version', '2.0') requires_path = os.path.join(egg_info_path,...
[ "def", "pkginfo_to_metadata", "(", "egg_info_path", ",", "pkginfo_path", ")", ":", "pkg_info", "=", "read_pkg_info", "(", "pkginfo_path", ")", "pkg_info", ".", "replace_header", "(", "'Metadata-Version'", ",", "'2.0'", ")", "requires_path", "=", "os", ".", "path",...
39.5
14.7
def _get_policy_set(self, policy_set_id): """ Get a specific policy set by id. """ uri = self._get_policy_set_uri(guid=policy_set_id) return self.service._get(uri)
[ "def", "_get_policy_set", "(", "self", ",", "policy_set_id", ")", ":", "uri", "=", "self", ".", "_get_policy_set_uri", "(", "guid", "=", "policy_set_id", ")", "return", "self", ".", "service", ".", "_get", "(", "uri", ")" ]
33
3.666667
def pix2sky_vec(self, pixel, r, theta): """ Given and input position and vector in pixel coordinates, calculate the equivalent position and vector in sky coordinates. Parameters ---------- pixel : (int,int) origin of vector in pixel coordinates r : fl...
[ "def", "pix2sky_vec", "(", "self", ",", "pixel", ",", "r", ",", "theta", ")", ":", "ra1", ",", "dec1", "=", "self", ".", "pix2sky", "(", "pixel", ")", "x", ",", "y", "=", "pixel", "a", "=", "[", "x", "+", "r", "*", "np", ".", "cos", "(", "n...
31.6
14.866667
def _send_event_to_all(self, action, event): """ Send an event to all the client listening for notifications on all projects :param action: Action name :param event: Event to send """ for project_listeners in self._listeners.values(): for listener in ...
[ "def", "_send_event_to_all", "(", "self", ",", "action", ",", "event", ")", ":", "for", "project_listeners", "in", "self", ".", "_listeners", ".", "values", "(", ")", ":", "for", "listener", "in", "project_listeners", ":", "listener", ".", "put_nowait", "(",...
35
13.909091
def convert_numpy_str_to_uint16(data): """ Converts a numpy.unicode\_ to UTF-16 in numpy.uint16 form. Convert a ``numpy.unicode_`` or an array of them (they are UTF-32 strings) to UTF-16 in the equivalent array of ``numpy.uint16``. The conversion will throw an exception if any characters cannot be ...
[ "def", "convert_numpy_str_to_uint16", "(", "data", ")", ":", "# An empty string should be an empty uint16", "if", "data", ".", "nbytes", "==", "0", ":", "return", "np", ".", "uint16", "(", "[", "]", ")", "# We need to use the UTF-16 codec for our endianness. Using the", ...
34.924528
21.886792
def basic_auth_header(username, password): '''generate a base64 encoded header to ask for a token. This means base64 encoding a username and password and adding to the Authorization header to identify the client. Parameters ========== username: the username password:...
[ "def", "basic_auth_header", "(", "username", ",", "password", ")", ":", "s", "=", "\"%s:%s\"", "%", "(", "username", ",", "password", ")", "if", "sys", ".", "version_info", "[", "0", "]", ">=", "3", ":", "s", "=", "bytes", "(", "s", ",", "'utf-8'", ...
32.105263
20.210526
def union(self, *others): r"""Return a new multiset with all elements from the multiset and the others with maximal multiplicities. >>> ms = Multiset('aab') >>> sorted(ms.union('bc')) ['a', 'a', 'b', 'c'] You can also use the ``|`` operator for the same effect. However, the ope...
[ "def", "union", "(", "self", ",", "*", "others", ")", ":", "result", "=", "self", ".", "__copy__", "(", ")", "_elements", "=", "result", ".", "_elements", "_total", "=", "result", ".", "_total", "for", "other", "in", "map", "(", "self", ".", "_as_map...
40.342857
22.742857
def extend(self, *args, **kwargs): """Extend current MultiDict with more values. This method must be used instead of update. """ self._extend(args, kwargs, 'extend', self._extend_items)
[ "def", "extend", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_extend", "(", "args", ",", "kwargs", ",", "'extend'", ",", "self", ".", "_extend_items", ")" ]
35.5
13.5
def handleHeader(self, key, value): """Handle header values.""" if key == 'CIMError': self.CIMError = urllib.parse.unquote(value) if key == 'PGErrorDetail': self.PGErrorDetail = urllib.parse.unquote(value)
[ "def", "handleHeader", "(", "self", ",", "key", ",", "value", ")", ":", "if", "key", "==", "'CIMError'", ":", "self", ".", "CIMError", "=", "urllib", ".", "parse", ".", "unquote", "(", "value", ")", "if", "key", "==", "'PGErrorDetail'", ":", "self", ...
35.428571
13.857143
def fix_for_specific_versions(self, rdf_data, to_replace): """ Fixes of the RDF before loading the graph. All of these are workaround to circuvent known issues of the SPM and FSL exporters. """ # Load the graph as is so that we can query g = self.parse(rdf_data) ...
[ "def", "fix_for_specific_versions", "(", "self", ",", "rdf_data", ",", "to_replace", ")", ":", "# Load the graph as is so that we can query", "g", "=", "self", ".", "parse", "(", "rdf_data", ")", "# Retreive the exporter name and version", "query", "=", "\"\"\"\nprefix ni...
42.833333
22.1
def embeddedFileDel(self, name): """Delete embedded file by name.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_embeddedFileDel(self, name)
[ "def", "embeddedFileDel", "(", "self", ",", "name", ")", ":", "if", "self", ".", "isClosed", "or", "self", ".", "isEncrypted", ":", "raise", "ValueError", "(", "\"operation illegal for closed / encrypted doc\"", ")", "return", "_fitz", ".", "Document_embeddedFileDel...
42.166667
17.666667
def parse_xml_node(self, node): '''Parse an xml.dom Node object representing a message sending object into this object. ''' self._targets = [] for c in node.getElementsByTagNameNS(RTS_NS, 'targets'): if c.getElementsByTagNameNS(RTS_NS, 'WaitTime'): ne...
[ "def", "parse_xml_node", "(", "self", ",", "node", ")", ":", "self", ".", "_targets", "=", "[", "]", "for", "c", "in", "node", ".", "getElementsByTagNameNS", "(", "RTS_NS", ",", "'targets'", ")", ":", "if", "c", ".", "getElementsByTagNameNS", "(", "RTS_N...
37.25
16.25
def get_policy(self): """ Returns an instance of :attr:`~policy_class`. :return: An instance of the current policy class. :rtype: dockermap.map.policy.base.BasePolicy """ if not self._policy: self._policy = self.policy_class(self._maps, self._clients) ...
[ "def", "get_policy", "(", "self", ")", ":", "if", "not", "self", ".", "_policy", ":", "self", ".", "_policy", "=", "self", ".", "policy_class", "(", "self", ".", "_maps", ",", "self", ".", "_clients", ")", "return", "self", ".", "_policy" ]
33.1
15.7
def from_tsv(cls, line, field_names, timezone_in_use=pytz.utc, database=None): ''' Create a model instance from a tab-separated line. The line may or may not include a newline. The `field_names` list must match the fields defined in the model, but does not have to include all of them. -...
[ "def", "from_tsv", "(", "cls", ",", "line", ",", "field_names", ",", "timezone_in_use", "=", "pytz", ".", "utc", ",", "database", "=", "None", ")", ":", "from", "six", "import", "next", "values", "=", "iter", "(", "parse_tsv", "(", "line", ")", ")", ...
42.090909
26.454545
def span(self): """Return a contiguous range that is a superset of this range. Returns: A VersionRange object representing the span of this range. For example, the span of "2+<4|6+<8" would be "2+<8". """ other = VersionRange(None) bound = _Bound(self.bou...
[ "def", "span", "(", "self", ")", ":", "other", "=", "VersionRange", "(", "None", ")", "bound", "=", "_Bound", "(", "self", ".", "bounds", "[", "0", "]", ".", "lower", ",", "self", ".", "bounds", "[", "-", "1", "]", ".", "upper", ")", "other", "...
36.181818
18.818182
def make_app(root, **kw): ''' Utility for creating the Pecan application object. This function should generally be called from the ``setup_app`` function in your project's ``app.py`` file. :param root: A string representing a root controller object (e.g., "myapp.controller.root.Ro...
[ "def", "make_app", "(", "root", ",", "*", "*", "kw", ")", ":", "# Pass logging configuration (if it exists) on to the Python logging module", "logging", "=", "kw", ".", "get", "(", "'logging'", ",", "{", "}", ")", "debug", "=", "kw", ".", "get", "(", "'debug'"...
39.019608
23.568627
def marshal_dict( obj, types, method=None, fields=None, **m_kwargs ): """ Recursively marshal a Python object to a dict that can be passed to json.{dump,dumps}, a web client, or a web server, document database, etc... Args: obj: object, It's members can be neste...
[ "def", "marshal_dict", "(", "obj", ",", "types", ",", "method", "=", "None", ",", "fields", "=", "None", ",", "*", "*", "m_kwargs", ")", ":", "has_slots", ",", "d", "=", "_get_dict", "(", "obj", ")", "if", "fields", ":", "for", "field", "in", "fiel...
29.537313
21.80597
def dp990(self, value=None): """ Corresponds to IDD Field `dp990` Dew-point temperature corresponding to 90.0% annual cumulative frequency of occurrence (cold conditions) Args: value (float): value for IDD Field `dp990` Unit: C if `value` is ...
[ "def", "dp990", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type float '"...
35.090909
20.090909
def withSize(cls, minimum, maximum): """Creates a subclass with value size constraint. """ class X(cls): subtypeSpec = cls.subtypeSpec + constraint.ValueSizeConstraint( minimum, maximum) X.__name__ = cls.__name__ return X
[ "def", "withSize", "(", "cls", ",", "minimum", ",", "maximum", ")", ":", "class", "X", "(", "cls", ")", ":", "subtypeSpec", "=", "cls", ".", "subtypeSpec", "+", "constraint", ".", "ValueSizeConstraint", "(", "minimum", ",", "maximum", ")", "X", ".", "_...
28.2
17.6
def notify(self, message): """ TODO: Add code to lpush to redis stack rpop when stack hits size 'X' """ data = dict( payload=self.payload, attempt=self.attempt, success=self.success, response_message=...
[ "def", "notify", "(", "self", ",", "message", ")", ":", "data", "=", "dict", "(", "payload", "=", "self", ".", "payload", ",", "attempt", "=", "self", ".", "attempt", ",", "success", "=", "self", ".", "success", ",", "response_message", "=", "self", ...
37.888889
10.444444
def new_driver(browser_name, *args, **kwargs): """Instantiates a new WebDriver instance, determining class by environment variables """ if browser_name == FIREFOX: return webdriver.Firefox(*args, **kwargs) # elif options['local'] and options['browser_name'] == CHROME: ...
[ "def", "new_driver", "(", "browser_name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "browser_name", "==", "FIREFOX", ":", "return", "webdriver", ".", "Firefox", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# elif options['local'] and o...
44.25
22.875
def handle(self, key, value): ''' Processes a vaild action info request @param key: The key that matched the request @param value: The value associated with the key ''' # very similar to stop # break down key elements = key.split(":") spiderid = e...
[ "def", "handle", "(", "self", ",", "key", ",", "value", ")", ":", "# very similar to stop", "# break down key", "elements", "=", "key", ".", "split", "(", "\":\"", ")", "spiderid", "=", "elements", "[", "1", "]", "appid", "=", "elements", "[", "2", "]", ...
35.288889
16.4
def main(): """ NAME download_magic.py DESCRIPTION unpacks a magic formatted smartbook .txt file from the MagIC database into the tab delimited MagIC format txt files for use with the MagIC-Py programs. SYNTAX download_magic.py command line options] INPUT ta...
[ "def", "main", "(", ")", ":", "if", "'-h'", "in", "sys", ".", "argv", ":", "print", "(", "main", ".", "__doc__", ")", "sys", ".", "exit", "(", ")", "if", "'-WD'", "in", "sys", ".", "argv", ":", "ind", "=", "sys", ".", "argv", ".", "index", "(...
37
22.555556
def vel_disp(self, kwargs_mass, kwargs_light, kwargs_anisotropy, kwargs_apertur): """ computes the averaged LOS velocity dispersion in the slit (convolved) :param kwargs_mass: mass model parameters (following lenstronomy lens model conventions) :param kwargs_light: deflector light param...
[ "def", "vel_disp", "(", "self", ",", "kwargs_mass", ",", "kwargs_light", ",", "kwargs_anisotropy", ",", "kwargs_apertur", ")", ":", "sigma2_R_sum", "=", "0", "for", "i", "in", "range", "(", "0", ",", "self", ".", "_num_sampling", ")", ":", "sigma2_R", "=",...
67.2
36.1
def query_by_account(self, account_id, end_time=None, start_time=None): """ Query by account. List authentication events for a given account. """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ID""" path["ac...
[ "def", "query_by_account", "(", "self", ",", "account_id", ",", "end_time", "=", "None", ",", "start_time", "=", "None", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - account_id\r", "\"\"\"ID\"\"\"", ...
39.269231
23.307692
def assign_region_to_channels(channels, anat, parc_type='aparc', max_approx=3, exclude_regions=None): """Assign a brain region based on the channel location. Parameters ---------- channels : instance of wonambi.attr.chan.Channels channels to assign regions to a...
[ "def", "assign_region_to_channels", "(", "channels", ",", "anat", ",", "parc_type", "=", "'aparc'", ",", "max_approx", "=", "3", ",", "exclude_regions", "=", "None", ")", ":", "for", "one_chan", "in", "channels", ".", "chan", ":", "one_region", ",", "approx"...
43.147059
20.676471