text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def libvlc_media_player_get_chapter_count_for_title(p_mi, i_title): '''Get title chapter count. @param p_mi: the Media Player. @param i_title: title. @return: number of chapters in title, or -1. ''' f = _Cfunctions.get('libvlc_media_player_get_chapter_count_for_title', None) or \ _Cfunct...
[ "def", "libvlc_media_player_get_chapter_count_for_title", "(", "p_mi", ",", "i_title", ")", ":", "f", "=", "_Cfunctions", ".", "get", "(", "'libvlc_media_player_get_chapter_count_for_title'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_media_player_get_chapter_count...
47.5
22.5
def _attach_dim_scales(self): """Attach dimension scales to all variables.""" for name, var in self.variables.items(): if name not in self.dimensions: for n, dim in enumerate(var.dimensions): var._h5ds.dims[n].attach_scale(self._all_h5groups[dim]) ...
[ "def", "_attach_dim_scales", "(", "self", ")", ":", "for", "name", ",", "var", "in", "self", ".", "variables", ".", "items", "(", ")", ":", "if", "name", "not", "in", "self", ".", "dimensions", ":", "for", "n", ",", "dim", "in", "enumerate", "(", "...
43.555556
13.222222
def create(self, update_request): """ Create a new BulkCountryUpdateInstance :param unicode update_request: URL encoded JSON array of update objects :returns: Newly created BulkCountryUpdateInstance :rtype: twilio.rest.voice.v1.dialing_permissions.bulk_country_update.BulkCountr...
[ "def", "create", "(", "self", ",", "update_request", ")", ":", "data", "=", "values", ".", "of", "(", "{", "'UpdateRequest'", ":", "update_request", ",", "}", ")", "payload", "=", "self", ".", "_version", ".", "create", "(", "'POST'", ",", "self", ".",...
32.055556
23.722222
def field_for(self, field_id): """Fetches the field for the given Field ID. :param field_id: ID for Field to fetch. :return: :class:`ContentTypeField <ContentTypeField>` object. :rtype: contentful.ContentTypeField """ for field in self.fields: if field.id ==...
[ "def", "field_for", "(", "self", ",", "field_id", ")", ":", "for", "field", "in", "self", ".", "fields", ":", "if", "field", ".", "id", "==", "field_id", ":", "return", "field", "return", "None" ]
30.666667
14.416667
def get_style_bits(match=False, comment=False, selected=False, data=False, diff=False, user=0): """ Return an int value that contains the specified style bits set. Available styles for each byte are: match: part of the currently matched search comment: user commented area selected: selected region...
[ "def", "get_style_bits", "(", "match", "=", "False", ",", "comment", "=", "False", ",", "selected", "=", "False", ",", "data", "=", "False", ",", "diff", "=", "False", ",", "user", "=", "0", ")", ":", "style_bits", "=", "0", "if", "user", ":", "sty...
31.625
17.791667
def calculate_etag(file_path): """ Calculate an etag value Args: a_file (pathlib.Path): The filepath to the Returns: String of the etag value to be sent back in header """ stat = file_path.stat() etag = "%x-%x" % (stat.st_mtime_ns, stat.s...
[ "def", "calculate_etag", "(", "file_path", ")", ":", "stat", "=", "file_path", ".", "stat", "(", ")", "etag", "=", "\"%x-%x\"", "%", "(", "stat", ".", "st_mtime_ns", ",", "stat", ".", "st_size", ")", "return", "etag" ]
25.769231
17.923077
def omim(self, omimid=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False): """Method to query :class:`.models.OMIM` objects in database :param omimid: Online Mendelian Inheritance in Man (OMIM) ID(s) :type omimid: str or tuple(str) or None :param hgnc_symbol: HGNC sy...
[ "def", "omim", "(", "self", ",", "omimid", "=", "None", ",", "hgnc_symbol", "=", "None", ",", "hgnc_identifier", "=", "None", ",", "limit", "=", "None", ",", "as_df", "=", "False", ")", ":", "q", "=", "self", ".", "session", ".", "query", "(", "mod...
38.15
23.925
def AddEvent(self, event): """Adds an event. Args: event (EventObject): event. Raises: IOError: when the storage writer is closed or if the event data identifier type is not supported. OSError: when the storage writer is closed or if the event data identifier type is ...
[ "def", "AddEvent", "(", "self", ",", "event", ")", ":", "self", ".", "_RaiseIfNotWritable", "(", ")", "# TODO: change to no longer allow event_data_identifier is None", "# after refactoring every parser to generate event data.", "event_data_identifier", "=", "event", ".", "GetE...
33.769231
20.538462
def skip_item_key(self, item, key): """Add the key to the item's "skip" list """ if "skip" in item: item["skip"].append(key) else: item["skip"] = [key] return item
[ "def", "skip_item_key", "(", "self", ",", "item", ",", "key", ")", ":", "if", "\"skip\"", "in", "item", ":", "item", "[", "\"skip\"", "]", ".", "append", "(", "key", ")", "else", ":", "item", "[", "\"skip\"", "]", "=", "[", "key", "]", "return", ...
27.5
9.875
def _enable_autopx(self): """Enable %autopx mode by saving the original run_cell and installing pxrun_cell. """ # override run_cell self._original_run_cell = self.shell.run_cell self.shell.run_cell = self.pxrun_cell self._autopx = True print "%autopx enab...
[ "def", "_enable_autopx", "(", "self", ")", ":", "# override run_cell", "self", ".", "_original_run_cell", "=", "self", ".", "shell", ".", "run_cell", "self", ".", "shell", ".", "run_cell", "=", "self", ".", "pxrun_cell", "self", ".", "_autopx", "=", "True", ...
31.5
12.9
def register(self, models=None, wrapper_cls=None): """Registers with app_label.modelname, wrapper_cls. """ self.loaded = True for model in models: model = model.lower() if model not in self.registry: self.registry.update({model: wrapper_cls or self...
[ "def", "register", "(", "self", ",", "models", "=", "None", ",", "wrapper_cls", "=", "None", ")", ":", "self", ".", "loaded", "=", "True", "for", "model", "in", "models", ":", "model", "=", "model", ".", "lower", "(", ")", "if", "model", "not", "in...
45.666667
16.333333
def from_dict(d): """ Builds a new instance of FileRecordSearch from a dict :param Object d: the dict to parse :return: a new FileRecordSearch based on the supplied dict """ obstory_ids = _value_from_dict(d, 'obstory_ids') lat_min = _value_from_dict(d, 'lat_min')...
[ "def", "from_dict", "(", "d", ")", ":", "obstory_ids", "=", "_value_from_dict", "(", "d", ",", "'obstory_ids'", ")", "lat_min", "=", "_value_from_dict", "(", "d", ",", "'lat_min'", ")", "lat_max", "=", "_value_from_dict", "(", "d", ",", "'lat_max'", ")", "...
54.857143
23.028571
def _inject_patched_examples(self, existing_item, patched_item): """Injects patched examples into original examples.""" for key, _ in patched_item.examples.items(): patched_example = patched_item.examples[key] existing_examples = existing_item.examples if key in exist...
[ "def", "_inject_patched_examples", "(", "self", ",", "existing_item", ",", "patched_item", ")", ":", "for", "key", ",", "_", "in", "patched_item", ".", "examples", ".", "items", "(", ")", ":", "patched_example", "=", "patched_item", ".", "examples", "[", "ke...
60.363636
22.545455
def add(self, item, header_flag=False, align=None): """Add a Cell to the row :param item: An element to add to the Cells can be list or Cell object. :type item: basestring, QString, list, Cell :param header_flag: Flag indicating it the item is a header or not. :type header_flag...
[ "def", "add", "(", "self", ",", "item", ",", "header_flag", "=", "False", ",", "align", "=", "None", ")", ":", "if", "self", ".", "_is_stringable", "(", "item", ")", "or", "self", ".", "_is_qstring", "(", "item", ")", ":", "self", ".", "cells", "."...
37.44
20.92
def iter_monitors(self): """Iterate over all defined (conn_string, event, monitor) tuples.""" for conn_string, events in self._monitors.items(): for event, handlers in events.items(): for handler in handlers: yield (conn_string, event, handler)
[ "def", "iter_monitors", "(", "self", ")", ":", "for", "conn_string", ",", "events", "in", "self", ".", "_monitors", ".", "items", "(", ")", ":", "for", "event", ",", "handlers", "in", "events", ".", "items", "(", ")", ":", "for", "handler", "in", "ha...
43.285714
14.142857
def weighted_choice(lst): """ Makes weighted choices. Accepts a list of tuples with the item and probability as a pair like: >>> x = [('one', 0.25), ('two', 0.25), ('three', 0.5)] >>> y=windex(x) """ n = random.uniform(0, 1) for item, weight in lst: if n < weight: break ...
[ "def", "weighted_choice", "(", "lst", ")", ":", "n", "=", "random", ".", "uniform", "(", "0", ",", "1", ")", "for", "item", ",", "weight", "in", "lst", ":", "if", "n", "<", "weight", ":", "break", "n", "=", "n", "-", "weight", "return", "item" ]
31.272727
13.636364
def on_destination(self, *args): """Make sure to redraw whenever the destination moves.""" if self.destination is None: Clock.schedule_once(self.on_destination, 0) return self.destination.bind( pos=self._trigger_repoint, size=self._trigger_repoint ...
[ "def", "on_destination", "(", "self", ",", "*", "args", ")", ":", "if", "self", ".", "destination", "is", "None", ":", "Clock", ".", "schedule_once", "(", "self", ".", "on_destination", ",", "0", ")", "return", "self", ".", "destination", ".", "bind", ...
35.666667
10.444444
def _varargs_to_iterable_method(func): """decorator to convert a *args method to one taking a iterable""" def wrapped(self, iterable, **kwargs): return func(self, *iterable, **kwargs) return wrapped
[ "def", "_varargs_to_iterable_method", "(", "func", ")", ":", "def", "wrapped", "(", "self", ",", "iterable", ",", "*", "*", "kwargs", ")", ":", "return", "func", "(", "self", ",", "*", "iterable", ",", "*", "*", "kwargs", ")", "return", "wrapped" ]
42.8
6.4
def set_neighbor_attribute_map(neigh_ip_address, at_maps, route_dist=None, route_family=VRF_RF_IPV4): """set attribute_maps to the neighbor.""" core = CORE_MANAGER.get_core_service() peer = core.peer_manager.get_by_addr(neigh_ip_address) at_maps_key = const.ATTR_MAPS_LABE...
[ "def", "set_neighbor_attribute_map", "(", "neigh_ip_address", ",", "at_maps", ",", "route_dist", "=", "None", ",", "route_family", "=", "VRF_RF_IPV4", ")", ":", "core", "=", "CORE_MANAGER", ".", "get_core_service", "(", ")", "peer", "=", "core", ".", "peer_manag...
36.521739
21
def parent(self, key): """when given a key of the form X.Y.Z, this method will return the parent DotDict of the 'Z' key.""" parent_key = '.'.join(key.split('.')[:-1]) if not parent_key: return None else: return self[parent_key]
[ "def", "parent", "(", "self", ",", "key", ")", ":", "parent_key", "=", "'.'", ".", "join", "(", "key", ".", "split", "(", "'.'", ")", "[", ":", "-", "1", "]", ")", "if", "not", "parent_key", ":", "return", "None", "else", ":", "return", "self", ...
35.5
11.375
def collide(self, s2): """ 判断图形是否碰到了另外一个图形 """ s1 = self s1.update_points() s2.update_points() if not (s1.points and s2.points): return False t1 = s1.transform t2 = s2.transform t1.update_points(s1.points) t2.update_points(s...
[ "def", "collide", "(", "self", ",", "s2", ")", ":", "s1", "=", "self", "s1", ".", "update_points", "(", ")", "s2", ".", "update_points", "(", ")", "if", "not", "(", "s1", ".", "points", "and", "s2", ".", "points", ")", ":", "return", "False", "t1...
25
18.607143
def binary_operation_logical(self, rule, left, right, **kwargs): """ Callback method for rule tree traversing. Will be called at proper time from :py:class:`pynspect.rules.LogicalBinOpRule.traverse` method. :param pynspect.rules.Rule rule: Reference to rule. :param left: Left op...
[ "def", "binary_operation_logical", "(", "self", ",", "rule", ",", "left", ",", "right", ",", "*", "*", "kwargs", ")", ":", "return", "'<div class=\"pynspect-rule-operation pynspect-rule-operation-logical\"><h3 class=\"pynspect-rule-operation-name\">{}</h3><ul class=\"pynspect-rule-...
72.090909
44.636364
def freeze(dest_dir, opt): """Iterates over the Secretfile looking for secrets to freeze""" tmp_dir = ensure_tmpdir() dest_prefix = "%s/dest" % tmp_dir ensure_dir(dest_dir) ensure_dir(dest_prefix) config = get_secretfile(opt) Context.load(config, opt) \ .freeze(dest_prefix) zi...
[ "def", "freeze", "(", "dest_dir", ",", "opt", ")", ":", "tmp_dir", "=", "ensure_tmpdir", "(", ")", "dest_prefix", "=", "\"%s/dest\"", "%", "tmp_dir", "ensure_dir", "(", "dest_dir", ")", "ensure_dir", "(", "dest_prefix", ")", "config", "=", "get_secretfile", ...
38.384615
11.153846
def over_under(self): """ Returns the over/under for the game as a float, or np.nan if not available. """ doc = self.get_doc() table = doc('table#game_info') giTable = sportsref.utils.parse_info_table(table) if 'over_under' in giTable: ou = giT...
[ "def", "over_under", "(", "self", ")", ":", "doc", "=", "self", ".", "get_doc", "(", ")", "table", "=", "doc", "(", "'table#game_info'", ")", "giTable", "=", "sportsref", ".", "utils", ".", "parse_info_table", "(", "table", ")", "if", "'over_under'", "in...
31.076923
12
def getenvar(self, envar): from os import getenv """Retrieves the value of an environment variable if it exists.""" if getenv(envar) is not None: self._vardict[envar] = getenv(envar)
[ "def", "getenvar", "(", "self", ",", "envar", ")", ":", "from", "os", "import", "getenv", "if", "getenv", "(", "envar", ")", "is", "not", "None", ":", "self", ".", "_vardict", "[", "envar", "]", "=", "getenv", "(", "envar", ")" ]
42.8
7.2
def pdhg(x, f, g, L, niter, tau=None, sigma=None, **kwargs): r"""Primal-dual hybrid gradient algorithm for convex optimization. First order primal-dual hybrid-gradient method for non-smooth convex optimization problems with known saddle-point structure. The primal formulation of the general problem is ...
[ "def", "pdhg", "(", "x", ",", "f", ",", "g", ",", "L", ",", "niter", ",", "tau", "=", "None", ",", "sigma", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Forward operator", "if", "not", "isinstance", "(", "L", ",", "Operator", ")", ":", "r...
37.684588
21.458781
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document_retrieval_strategy' ) and self.document_retrieval_strategy is not None: _dict[ 'document_retrieval_strategy'] = self.document_retrieval_...
[ "def", "_to_dict", "(", "self", ")", ":", "_dict", "=", "{", "}", "if", "hasattr", "(", "self", ",", "'document_retrieval_strategy'", ")", "and", "self", ".", "document_retrieval_strategy", "is", "not", "None", ":", "_dict", "[", "'document_retrieval_strategy'",...
42.75
21.125
def value(self): """gets the value as a dictionary""" return { "type" : self._type, "name" : self._name, "range" : [self._rangeMin, self._rangeMax] }
[ "def", "value", "(", "self", ")", ":", "return", "{", "\"type\"", ":", "self", ".", "_type", ",", "\"name\"", ":", "self", ".", "_name", ",", "\"range\"", ":", "[", "self", ".", "_rangeMin", ",", "self", ".", "_rangeMax", "]", "}" ]
29
15.571429
def save_diskspace(fname, reason, config): """Overwrite a file in place with a short message to save disk. This keeps files as a sanity check on processes working, but saves disk by replacing them with a short message. """ if config["algorithm"].get("save_diskspace", False): with open(fname...
[ "def", "save_diskspace", "(", "fname", ",", "reason", ",", "config", ")", ":", "if", "config", "[", "\"algorithm\"", "]", ".", "get", "(", "\"save_diskspace\"", ",", "False", ")", ":", "with", "open", "(", "fname", ",", "\"w\"", ")", "as", "out_handle", ...
45.555556
15.111111
def _process_flat_kwargs(source, kwargs): """Apply a flat namespace transformation to recreate (in some respects) a rich structure. This applies several transformations, which may be nested: `foo` (singular): define a simple value named `foo` `foo` (repeated): define a simple value for placement in an arr...
[ "def", "_process_flat_kwargs", "(", "source", ",", "kwargs", ")", ":", "ordered_arrays", "=", "[", "]", "# Process arguments one at a time and apply them to the kwargs passed in.", "for", "name", ",", "value", "in", "source", ".", "items", "(", ")", ":", "container", ...
34.121212
24.727273
def set_basic_params(self, no_expire=None, expire_scan_interval=None, report_freed=None): """ :param bool no_expire: Disable auto sweep of expired items. Since uWSGI 1.2, cache item expiration is managed by a thread in the master process, to reduce the risk of deadlock. This thre...
[ "def", "set_basic_params", "(", "self", ",", "no_expire", "=", "None", ",", "expire_scan_interval", "=", "None", ",", "report_freed", "=", "None", ")", ":", "self", ".", "_set", "(", "'cache-no-expire'", ",", "no_expire", ",", "cast", "=", "bool", ")", "se...
45.368421
30.736842
def setM0Coast(self, device=DEFAULT_DEVICE_ID): """ Set motor 0 to coast. :Keywords: device : `int` The device is the integer number of the hardware devices ID and is only used with the Pololu Protocol. Defaults to the hardware's default value. ...
[ "def", "setM0Coast", "(", "self", ",", "device", "=", "DEFAULT_DEVICE_ID", ")", ":", "cmd", "=", "self", ".", "_COMMAND", ".", "get", "(", "'m0-coast'", ")", "self", ".", "_writeData", "(", "cmd", ",", "device", ")" ]
32.388889
15.833333
def current_size(self): """The size of the current line minus the indentation.""" size = 0 for item in reversed(self._lines): size += item.size if isinstance(item, self._LineBreak): break return size
[ "def", "current_size", "(", "self", ")", ":", "size", "=", "0", "for", "item", "in", "reversed", "(", "self", ".", "_lines", ")", ":", "size", "+=", "item", ".", "size", "if", "isinstance", "(", "item", ",", "self", ".", "_LineBreak", ")", ":", "br...
29.333333
15.888889
def tangent_approx(f: SYM, x: SYM, a: SYM = None, assert_linear: bool = False) -> Dict[str, SYM]: """ Create a tangent approximation of a non-linear function f(x) about point a using a block lower triangular solver 0 = f(x) = f(a) + J*x # taylor series about a (if f(x) linear in x, then globally vali...
[ "def", "tangent_approx", "(", "f", ":", "SYM", ",", "x", ":", "SYM", ",", "a", ":", "SYM", "=", "None", ",", "assert_linear", ":", "bool", "=", "False", ")", "->", "Dict", "[", "str", ",", "SYM", "]", ":", "# find f(a)", "if", "a", "is", "None", ...
40
18.105263
def configure(self, width, height): """See :meth:`set_window_size`.""" self._imgwin_set = True self.set_window_size(width, height)
[ "def", "configure", "(", "self", ",", "width", ",", "height", ")", ":", "self", ".", "_imgwin_set", "=", "True", "self", ".", "set_window_size", "(", "width", ",", "height", ")" ]
37.75
4.25
def create_environment(self, environment): """ Method to create environment """ uri = 'api/v3/environment/' data = dict() data['environments'] = list() data['environments'].append(environment) return super(ApiEnvironment, self).post(uri, data)
[ "def", "create_environment", "(", "self", ",", "environment", ")", ":", "uri", "=", "'api/v3/environment/'", "data", "=", "dict", "(", ")", "data", "[", "'environments'", "]", "=", "list", "(", ")", "data", "[", "'environments'", "]", ".", "append", "(", ...
24.916667
14.916667
def set_tlsext_use_srtp(self, profiles): """ Enable support for negotiating SRTP keying material. :param bytes profiles: A colon delimited list of protection profile names, like ``b'SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32'``. :return: None """ if not is...
[ "def", "set_tlsext_use_srtp", "(", "self", ",", "profiles", ")", ":", "if", "not", "isinstance", "(", "profiles", ",", "bytes", ")", ":", "raise", "TypeError", "(", "\"profiles must be a byte string.\"", ")", "_openssl_assert", "(", "_lib", ".", "SSL_CTX_set_tlsex...
36.214286
21.214286
def return_socket(self, sock_info): """Return the socket to the pool, or if it's closed discard it.""" if self.pid != os.getpid(): self.reset() else: if sock_info.pool_id != self.pool_id: sock_info.close() elif not sock_info.closed: ...
[ "def", "return_socket", "(", "self", ",", "sock_info", ")", ":", "if", "self", ".", "pid", "!=", "os", ".", "getpid", "(", ")", ":", "self", ".", "reset", "(", ")", "else", ":", "if", "sock_info", ".", "pool_id", "!=", "self", ".", "pool_id", ":", ...
35.066667
10.4
def _evaluate(self,R,z,phi=0.,t=0.): """ NAME: _evaluate PURPOSE: evaluate the potential at R,z INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: Phi(R,z) ...
[ "def", "_evaluate", "(", "self", ",", "R", ",", "z", ",", "phi", "=", "0.", ",", "t", "=", "0.", ")", ":", "r2", "=", "R", "**", "2.", "+", "z", "**", "2.", "r", "=", "nu", ".", "sqrt", "(", "r2", ")", "return", "(", "0.5", "*", "nu", "...
26.2
14.4
def postprocess(self, content): """ Perform final processing of the resulting data structure as follows: - Mixed values (children and text) will have a result of the I{content.node}. - Simi-simple values (attributes, no-children and text) will have a result of a property...
[ "def", "postprocess", "(", "self", ",", "content", ")", ":", "node", "=", "content", ".", "node", "if", "len", "(", "node", ".", "children", ")", "and", "node", ".", "hasText", "(", ")", ":", "return", "node", "attributes", "=", "AttrList", "(", "nod...
41.027778
14.916667
def _remove_summary(self): """Removed packge size summary """ if self.size > 0: print("\nRemoved summary") print("=" * 79) print("{0}Size of removed packages {1} {2}.{3}".format( self.meta.color["GREY"], round(self.size, 2), self.unit, ...
[ "def", "_remove_summary", "(", "self", ")", ":", "if", "self", ".", "size", ">", "0", ":", "print", "(", "\"\\nRemoved summary\"", ")", "print", "(", "\"=\"", "*", "79", ")", "print", "(", "\"{0}Size of removed packages {1} {2}.{3}\"", ".", "format", "(", "s...
38.333333
11.555556
def _resolve(self, path, migration_file): """ Resolve a migration instance from a file. :param migration_file: The migration file :type migration_file: str :rtype: eloquent.migrations.migration.Migration """ variables = {} name = '_'.join(migration_file...
[ "def", "_resolve", "(", "self", ",", "path", ",", "migration_file", ")", ":", "variables", "=", "{", "}", "name", "=", "'_'", ".", "join", "(", "migration_file", ".", "split", "(", "'_'", ")", "[", "4", ":", "]", ")", "migration_file", "=", "os", "...
29.26087
21
def get_all_chains(self): """Assemble and return a list of all chains for all leaf nodes to the merkle root. """ return [self.get_chain(i) for i in range(len(self.leaves))]
[ "def", "get_all_chains", "(", "self", ")", ":", "return", "[", "self", ".", "get_chain", "(", "i", ")", "for", "i", "in", "range", "(", "len", "(", "self", ".", "leaves", ")", ")", "]" ]
48.25
10.5
def _parse(data, obj_name, attr_map): """parse xml data into a python map""" parsed_xml = minidom.parseString(data) parsed_objects = [] for obj in parsed_xml.getElementsByTagName(obj_name): parsed_obj = {} for (py_name, xml_name) in attr_map.items(): parsed_obj[py_name] = _ge...
[ "def", "_parse", "(", "data", ",", "obj_name", ",", "attr_map", ")", ":", "parsed_xml", "=", "minidom", ".", "parseString", "(", "data", ")", "parsed_objects", "=", "[", "]", "for", "obj", "in", "parsed_xml", ".", "getElementsByTagName", "(", "obj_name", "...
41.3
11.5
def _replace_booleans(tok): """Replace ``&`` with ``and`` and ``|`` with ``or`` so that bitwise precedence is changed to boolean precedence. Parameters ---------- tok : tuple of int, str ints correspond to the all caps constants in the tokenize module Returns ------- t : tuple ...
[ "def", "_replace_booleans", "(", "tok", ")", ":", "toknum", ",", "tokval", "=", "tok", "if", "toknum", "==", "tokenize", ".", "OP", ":", "if", "tokval", "==", "'&'", ":", "return", "tokenize", ".", "NAME", ",", "'and'", "elif", "tokval", "==", "'|'", ...
28.272727
17
def connect_to_host(cls, host='localhost', port=8000, is_secure=False, session=None, access_key=None, secret_key=None, **kwargs): """ Connect to a specific host. This method has been deprecated in favor of :meth:`~.connect` Parameters ...
[ "def", "connect_to_host", "(", "cls", ",", "host", "=", "'localhost'", ",", "port", "=", "8000", ",", "is_secure", "=", "False", ",", "session", "=", "None", ",", "access_key", "=", "None", ",", "secret_key", "=", "None", ",", "*", "*", "kwargs", ")", ...
42.305556
17.972222
def create_user(self, email, name, password, username, **kwargs): """ Create user :param email: E-mail :param name: Full name :param password: Password :param username: Username :param kwargs: active: roles: join_default_channels: r...
[ "def", "create_user", "(", "self", ",", "email", ",", "name", ",", "password", ",", "username", ",", "*", "*", "kwargs", ")", ":", "return", "CreateUser", "(", "settings", "=", "self", ".", "settings", ",", "*", "*", "kwargs", ")", ".", "call", "(", ...
26.041667
15.708333
def set_resolved_name(self, ref: dict, type_name2solve: TypeName, type_name_ref: TypeName): """ Warning!!! Need to rethink it when global poly type """ if self.resolution[type_name2solve.value] is None: self.resolution[type_name2solve.value] = ref[ty...
[ "def", "set_resolved_name", "(", "self", ",", "ref", ":", "dict", ",", "type_name2solve", ":", "TypeName", ",", "type_name_ref", ":", "TypeName", ")", ":", "if", "self", ".", "resolution", "[", "type_name2solve", ".", "value", "]", "is", "None", ":", "self...
47.428571
15.714286
def findbeam_slices(data, orig_initial, mask=None, maxiter=0, epsfcn=0.001, dmin=0, dmax=np.inf, sector_width=np.pi / 9.0, extent=10, callback=None): """Find beam center with the "slices" method Inputs: data: scattering matrix orig_initial: estimated value for x (row) and y ...
[ "def", "findbeam_slices", "(", "data", ",", "orig_initial", ",", "mask", "=", "None", ",", "maxiter", "=", "0", ",", "epsfcn", "=", "0.001", ",", "dmin", "=", "0", ",", "dmax", "=", "np", ".", "inf", ",", "sector_width", "=", "np", ".", "pi", "/", ...
50.66
24.6
def _registerPickleType(name, typedef): ''' Register a type with the specified name. After registration, NamedStruct with this type (and any sub-types) can be successfully pickled and transfered. ''' NamedStruct._pickleNames[typedef] = name NamedStruct._pickleTypes[name] ...
[ "def", "_registerPickleType", "(", "name", ",", "typedef", ")", ":", "NamedStruct", ".", "_pickleNames", "[", "typedef", "]", "=", "name", "NamedStruct", ".", "_pickleTypes", "[", "name", "]", "=", "typedef" ]
46.142857
23
def _CreateShapesFolder(self, schedule, doc): """Create a KML Folder containing all the shapes in a schedule. The folder contains a placemark for each shape. If there are no shapes in the schedule then the folder is not created and None is returned. Args: schedule: The transitfeed.Schedule insta...
[ "def", "_CreateShapesFolder", "(", "self", ",", "schedule", ",", "doc", ")", ":", "if", "not", "schedule", ".", "GetShapeList", "(", ")", ":", "return", "None", "shapes_folder", "=", "self", ".", "_CreateFolder", "(", "doc", ",", "'Shapes'", ")", "shapes",...
37.166667
18.416667
def query_status(self): '''Query the hub for the status of this command''' try: data = self.api_iface._api_get(self.link) self._update_details(data) except APIError as e: print("API error: ") for key,value in e.data.iteritems: print...
[ "def", "query_status", "(", "self", ")", ":", "try", ":", "data", "=", "self", ".", "api_iface", ".", "_api_get", "(", "self", ".", "link", ")", "self", ".", "_update_details", "(", "data", ")", "except", "APIError", "as", "e", ":", "print", "(", "\"...
38
12.666667
def from_semiaxes(cls,axes): """ Get axis-aligned elliptical conic from axis lenths This can be converted into a hyperbola by getting the dual conic """ ax = list(1/N.array(axes)**2) #ax[-1] *= -1 # Not sure what is going on here... arr = N.diag(ax + [-1]) ...
[ "def", "from_semiaxes", "(", "cls", ",", "axes", ")", ":", "ax", "=", "list", "(", "1", "/", "N", ".", "array", "(", "axes", ")", "**", "2", ")", "#ax[-1] *= -1 # Not sure what is going on here...", "arr", "=", "N", ".", "diag", "(", "ax", "+", "[", ...
37.111111
11.555556
def prepare_for_translation(localization_bundle_path): """ Prepares the localization bundle for translation. This means, after creating the strings files using genstrings.sh, this will produce '.pending' files, that contain the files that are yet to be translated. Args: localization_bundle_pat...
[ "def", "prepare_for_translation", "(", "localization_bundle_path", ")", ":", "logging", ".", "info", "(", "\"Preparing for translation..\"", ")", "for", "strings_file", "in", "os", ".", "listdir", "(", "os", ".", "path", ".", "join", "(", "localization_bundle_path",...
45.566667
31.9
def phasedlc_features(times, mags, errs, period, nbrtimes=None, nbrmags=None, nbrerrs=None): '''This calculates various phased LC features for the object. Some of the features cal...
[ "def", "phasedlc_features", "(", "times", ",", "mags", ",", "errs", ",", "period", ",", "nbrtimes", "=", "None", ",", "nbrmags", "=", "None", ",", "nbrerrs", "=", "None", ")", ":", "# get the finite values", "finind", "=", "np", ".", "isfinite", "(", "ti...
40.285714
23.849624
def setup_markers(seqs): """ setup unique marker for every orf annotation - change size if necessary """ family2marker = {} # family2marker[family] = [marker, size] markers = cycle(['^', 'p', '*', '+', 'x', 'd', '|', 'v', '>', '<', '8']) size = 60 families = [] for seq in list(seqs.v...
[ "def", "setup_markers", "(", "seqs", ")", ":", "family2marker", "=", "{", "}", "# family2marker[family] = [marker, size]", "markers", "=", "cycle", "(", "[", "'^'", ",", "'p'", ",", "'*'", ",", "'+'", ",", "'x'", ",", "'d'", ",", "'|'", ",", "'v'", ",", ...
33.7
12.3
def closeEvent(self, event): """ Saves dirty editors on close and cancel the event if the user choosed to continue to work. :param event: close event """ dirty_widgets = [] for w in self.widgets(include_clones=False): if w.dirty: dirty...
[ "def", "closeEvent", "(", "self", ",", "event", ")", ":", "dirty_widgets", "=", "[", "]", "for", "w", "in", "self", ".", "widgets", "(", "include_clones", "=", "False", ")", ":", "if", "w", ".", "dirty", ":", "dirty_widgets", ".", "append", "(", "w",...
35.861111
12.527778
def findNextFile(folder='.', prefix=None, suffix=None, fnameGen=None, base=0, maxattempts=10): """Finds the next available file-name in a sequence. This function will create a file of zero size and will return the path to ...
[ "def", "findNextFile", "(", "folder", "=", "'.'", ",", "prefix", "=", "None", ",", "suffix", "=", "None", ",", "fnameGen", "=", "None", ",", "base", "=", "0", ",", "maxattempts", "=", "10", ")", ":", "expFolder", "=", "_os", ".", "path", ".", "expa...
46.795918
25.918367
def simulate(self): """ Section 7 - uwg main section self.N # Total hours in simulation self.ph # per hour self.dayType # 3=Sun, 2=Sat, 1=Weekday self.ceil_time_step # simulation timestep (dt) fitted to weathe...
[ "def", "simulate", "(", "self", ")", ":", "self", ".", "N", "=", "int", "(", "self", ".", "simTime", ".", "days", "*", "24", ")", "# total number of hours in simulation\r", "n", "=", "0", "# weather time step counter\r", "self", ".", "ph", "=", "self", "."...
58.835106
33.244681
def comic_archive_uncompress(filename, image_format): """ Uncompress comic archives. Return the name of the working directory we uncompressed into. """ if not Settings.comics: report = ['Skipping archive file: {}'.format(filename)] return None, ReportStats(filename, report=report) ...
[ "def", "comic_archive_uncompress", "(", "filename", ",", "image_format", ")", ":", "if", "not", "Settings", ".", "comics", ":", "report", "=", "[", "'Skipping archive file: {}'", ".", "format", "(", "filename", ")", "]", "return", "None", ",", "ReportStats", "...
31.628571
18.314286
def find_vext_files(self): """ :return: Absolute paths to any provided vext files """ packages = self.depends_on("vext") vext_files = [] for location in [package.get("location") for package in packages]: if not location: continue v...
[ "def", "find_vext_files", "(", "self", ")", ":", "packages", "=", "self", ".", "depends_on", "(", "\"vext\"", ")", "vext_files", "=", "[", "]", "for", "location", "in", "[", "package", ".", "get", "(", "\"location\"", ")", "for", "package", "in", "packag...
34.909091
13.636364
def delete_asset_content(self, asset_content_id): """Deletes content from an ``Asset``. arg: asset_content_id (osid.id.Id): the ``Id`` of the ``AssetContent`` raise: NotFound - ``asset_content_id`` is not found raise: NullArgument - ``asset_content_id`` is ``null`` ...
[ "def", "delete_asset_content", "(", "self", ",", "asset_content_id", ")", ":", "# Implemented from template for", "# osid.repository.AssetAdminSession.delete_asset_content_template", "from", "dlkit", ".", "abstract_osid", ".", "id", ".", "primitives", "import", "Id", "as", ...
44.135135
18.783784
def update_migration_issue_groups(self, id, group_id, workflow_state, content_migration_id): """ Update a migration issue. Update the workflow_state of a migration issue """ path = {} data = {} params = {} # REQUIRED - PATH - group_id ...
[ "def", "update_migration_issue_groups", "(", "self", ",", "id", ",", "group_id", ",", "workflow_state", ",", "content_migration_id", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - group_id\r", "\"\"\"ID\"\"\...
40.241379
27.62069
def _copy(self): """Creates a deep copy of this request.""" copied_uri = Uri(self.uri.scheme, self.uri.host, self.uri.port, self.uri.path, self.uri.query.copy()) new_request = HttpRequest(uri=copied_uri, method=self.method, headers=self.headers.copy()) ...
[ "def", "_copy", "(", "self", ")", ":", "copied_uri", "=", "Uri", "(", "self", ".", "uri", ".", "scheme", ",", "self", ".", "uri", ".", "host", ",", "self", ".", "uri", ".", "port", ",", "self", ".", "uri", ".", "path", ",", "self", ".", "uri", ...
47.625
17.375
def instance_provisioned(device_id): """Returns true if any ports exist for an instance.""" session = db.get_reader_session() with session.begin(): port_model = models_v2.Port res = bool(session.query(port_model) .filter(port_model.device_id == device_id).count()) retu...
[ "def", "instance_provisioned", "(", "device_id", ")", ":", "session", "=", "db", ".", "get_reader_session", "(", ")", "with", "session", ".", "begin", "(", ")", ":", "port_model", "=", "models_v2", ".", "Port", "res", "=", "bool", "(", "session", ".", "q...
39.875
10.875
def _is_svc(svc_path): ''' Return ``True`` if directory <svc_path> is really a service: file <svc_path>/run exists and is executable svc_path the (absolute) directory to check for compatibility ''' run_file = os.path.join(svc_path, 'run') if (os.path.exists(svc_path) and os...
[ "def", "_is_svc", "(", "svc_path", ")", ":", "run_file", "=", "os", ".", "path", ".", "join", "(", "svc_path", ",", "'run'", ")", "if", "(", "os", ".", "path", ".", "exists", "(", "svc_path", ")", "and", "os", ".", "path", ".", "exists", "(", "ru...
29.285714
19
def remove_father(self, father): """ Remove the father node. Do nothing if the node is not a father Args: fathers: list of fathers to add """ self._fathers = [x for x in self._fathers if x.node_id != father.node_id]
[ "def", "remove_father", "(", "self", ",", "father", ")", ":", "self", ".", "_fathers", "=", "[", "x", "for", "x", "in", "self", ".", "_fathers", "if", "x", ".", "node_id", "!=", "father", ".", "node_id", "]" ]
36.285714
17
def _sign_button_press(self, *args): """Validate input from ent_id, then sign in to the Timesheet.""" user_id = self.ent_id.get().strip() try: status = controller.sign(user_id) # ERROR: User type is unknown (!student and !tutor) except ValueError as e: l...
[ "def", "_sign_button_press", "(", "self", ",", "*", "args", ")", ":", "user_id", "=", "self", ".", "ent_id", ".", "get", "(", ")", ".", "strip", "(", ")", "try", ":", "status", "=", "controller", ".", "sign", "(", "user_id", ")", "# ERROR: User type is...
36.355932
16.898305
def draw_qubit_graph(G, layout, linear_biases={}, quadratic_biases={}, nodelist=None, edgelist=None, cmap=None, edge_cmap=None, vmin=None, vmax=None, edge_vmin=None, edge_vmax=None, **kwargs): """Draws graph G according to layout. If `linear_biases...
[ "def", "draw_qubit_graph", "(", "G", ",", "layout", ",", "linear_biases", "=", "{", "}", ",", "quadratic_biases", "=", "{", "}", ",", "nodelist", "=", "None", ",", "edgelist", "=", "None", ",", "cmap", "=", "None", ",", "edge_cmap", "=", "None", ",", ...
36.314286
22.12381
def _register_hid_notification(self): """Register HID notification events on any window (passed by window handler), returns a notification handler""" # create structure, self initialized notify_obj = DevBroadcastDevInterface() h_notify = RegisterDeviceNotification(self.__hid...
[ "def", "_register_hid_notification", "(", "self", ")", ":", "# create structure, self initialized\r", "notify_obj", "=", "DevBroadcastDevInterface", "(", ")", "h_notify", "=", "RegisterDeviceNotification", "(", "self", ".", "__hid_hwnd", ",", "ctypes", ".", "byref", "("...
47.888889
12.333333
def mock_cmd(self, release, *cmd, **kwargs): """Run a mock command in the chroot for a given release""" fmt = '{mock_cmd}' if kwargs.get('new_chroot') is True: fmt +=' --new-chroot' fmt += ' --configdir={mock_dir}' return self.call(fmt.format(**release).split() ...
[ "def", "mock_cmd", "(", "self", ",", "release", ",", "*", "cmd", ",", "*", "*", "kwargs", ")", ":", "fmt", "=", "'{mock_cmd}'", "if", "kwargs", ".", "get", "(", "'new_chroot'", ")", "is", "True", ":", "fmt", "+=", "' --new-chroot'", "fmt", "+=", "' -...
43
5.75
def init_layout(self): """ Add all child widgets to the view """ super(AndroidTextureView, self).init_layout() # Force layout using the default params if not self.layout_params: self.set_layout({})
[ "def", "init_layout", "(", "self", ")", ":", "super", "(", "AndroidTextureView", ",", "self", ")", ".", "init_layout", "(", ")", "# Force layout using the default params", "if", "not", "self", ".", "layout_params", ":", "self", ".", "set_layout", "(", "{", "}"...
30.375
11.625
def hasLock(self): ''' hasLock - Property, returns True if we have the lock, or False if we do not. @return <bool> - True/False if we have the lock or not. ''' # If we don't hold it currently, return False if self.held is False: return False ...
[ "def", "hasLock", "(", "self", ")", ":", "# If we don't hold it currently, return False", "if", "self", ".", "held", "is", "False", ":", "return", "False", "# Otherwise if we think we hold it, but it is not held, we have lost it.", "if", "not", "self", ".", "isHeld", ":",...
28.75
22.833333
def email_addresses2marc(self, key, value): """Populate the 595 MARCXML field. Also populates the 371 field as a side effect. """ m_or_o = 'm' if value.get('current') else 'o' element = { m_or_o: value.get('value') } if value.get('hidden'): return element else: ...
[ "def", "email_addresses2marc", "(", "self", ",", "key", ",", "value", ")", ":", "m_or_o", "=", "'m'", "if", "value", ".", "get", "(", "'current'", ")", "else", "'o'", "element", "=", "{", "m_or_o", ":", "value", ".", "get", "(", "'value'", ")", "}", ...
24.533333
17.4
def label_by_time(self,time_signals,label_names=[],time_units='ms',time_dimension=0,copy=True,backup_original_spike_times_to=None,**kwargs): """ creates a labeled spike data structure `time_signals` is list of lists (or matrix), containing a timestamp in the first c...
[ "def", "label_by_time", "(", "self", ",", "time_signals", ",", "label_names", "=", "[", "]", ",", "time_units", "=", "'ms'", ",", "time_dimension", "=", "0", ",", "copy", "=", "True", ",", "backup_original_spike_times_to", "=", "None", ",", "*", "*", "kwar...
60.072464
31.608696
def column_print(fmt, rows, print_func): """Prints a formatted list, adjusting the width so everything fits. fmt contains a single character for each column. < indicates that the column should be left justified, > indicates that the column should be right justified. The last column may be a space which ...
[ "def", "column_print", "(", "fmt", ",", "rows", ",", "print_func", ")", ":", "# Figure out the max width of each column", "num_cols", "=", "len", "(", "fmt", ")", "width", "=", "[", "max", "(", "0", "if", "isinstance", "(", "row", ",", "str", ")", "else", ...
45
18.263158
def ne(self, other, ranks=None): """ Compares the card against another card, ``other``, and checks whether the card is not equal to ``other``, based on the given rank dict. :arg Card other: The second Card to compare. :arg dict ranks: The ranks to refer t...
[ "def", "ne", "(", "self", ",", "other", ",", "ranks", "=", "None", ")", ":", "ranks", "=", "ranks", "or", "DEFAULT_RANKS", "if", "isinstance", "(", "other", ",", "Card", ")", ":", "if", "ranks", ".", "get", "(", "\"suits\"", ")", ":", "return", "("...
31.518519
16.481481
def change_vartype(self, vartype, energy_offset=0.0, inplace=True): """Return the :class:`SampleSet` with the given vartype. Args: vartype (:class:`.Vartype`/str/set): Variable type to use for the new :class:`SampleSet`. Accepted input values: * :class:`.Var...
[ "def", "change_vartype", "(", "self", ",", "vartype", ",", "energy_offset", "=", "0.0", ",", "inplace", "=", "True", ")", ":", "if", "not", "inplace", ":", "return", "self", ".", "copy", "(", ")", ".", "change_vartype", "(", "vartype", ",", "energy_offse...
43.368421
30.157895
def decode_offset_commit_response(cls, data): """ Decode bytes to an OffsetCommitResponse :param bytes data: bytes to decode """ ((correlation_id,), cur) = relative_unpack('>i', data, 0) ((num_topics,), cur) = relative_unpack('>i', data, cur) for _i in range(num...
[ "def", "decode_offset_commit_response", "(", "cls", ",", "data", ")", ":", "(", "(", "correlation_id", ",", ")", ",", "cur", ")", "=", "relative_unpack", "(", "'>i'", ",", "data", ",", "0", ")", "(", "(", "num_topics", ",", ")", ",", "cur", ")", "=",...
39.5625
18.6875
def ParseOptions(cls, options, output_module): """Parses and validates options. Args: options (argparse.Namespace): parser options. output_module (OutputModule): output module to configure. Raises: BadConfigObject: when the output module object does not have the SetServerInform...
[ "def", "ParseOptions", "(", "cls", ",", "options", ",", "output_module", ")", ":", "if", "not", "hasattr", "(", "output_module", ",", "'SetServerInformation'", ")", ":", "raise", "errors", ".", "BadConfigObject", "(", "'Unable to set server information.'", ")", "s...
35.05
20
def create_file_in_fs(file_data, file_name, file_system, static_dir): """ Writes file in specific file system. Arguments: file_data (str): Data to store into the file. file_name (str): File name of the file to be created. file_system (OSFS): Import file system. static_dir (s...
[ "def", "create_file_in_fs", "(", "file_data", ",", "file_name", ",", "file_system", ",", "static_dir", ")", ":", "with", "file_system", ".", "open", "(", "combine", "(", "static_dir", ",", "file_name", ")", ",", "'wb'", ")", "as", "f", ":", "f", ".", "wr...
39.75
16.25
def _wait_for_completion(conn, wait_timeout, server_id): ''' Poll request status until resource is provisioned. ''' wait_timeout = time.time() + wait_timeout while wait_timeout > time.time(): time.sleep(5) server = conn.get_server(server_id) server_state = server['status']['...
[ "def", "_wait_for_completion", "(", "conn", ",", "wait_timeout", ",", "server_id", ")", ":", "wait_timeout", "=", "time", ".", "time", "(", ")", "+", "wait_timeout", "while", "wait_timeout", ">", "time", ".", "time", "(", ")", ":", "time", ".", "sleep", ...
34.576923
18.192308
def _adaptSegment(self, segUpdate): """ This function applies segment update information to a segment in a cell. Synapses on the active list get their permanence counts incremented by permanenceInc. All other synapses get their permanence counts decremented by permanenceDec. We also increm...
[ "def", "_adaptSegment", "(", "self", ",", "segUpdate", ")", ":", "# This will be set to True if detect that any syapses were decremented to", "# 0", "trimSegment", "=", "False", "# segUpdate.segment is None when creating a new segment", "c", ",", "i", ",", "segment", "=", "s...
40.031915
23.56383
def color_xy(self): """ XY colour value: [float, float] or None :rtype: list float """ color_x = self._last_reading.get('color_x') color_y = self._last_reading.get('color_y') if color_x is not None and color_y is not None: return [float(color_x), float...
[ "def", "color_xy", "(", "self", ")", ":", "color_x", "=", "self", ".", "_last_reading", ".", "get", "(", "'color_x'", ")", "color_y", "=", "self", ".", "_last_reading", ".", "get", "(", "'color_y'", ")", "if", "color_x", "is", "not", "None", "and", "co...
34.1
11.1
async def update(query): """Perform UPDATE query asynchronously. Returns number of rows updated. """ assert isinstance(query, peewee.Update),\ ("Error, trying to run update coroutine" "with wrong query class %s" % str(query)) cursor = await _execute_query_async(query) rowcount = cu...
[ "async", "def", "update", "(", "query", ")", ":", "assert", "isinstance", "(", "query", ",", "peewee", ".", "Update", ")", ",", "(", "\"Error, trying to run update coroutine\"", "\"with wrong query class %s\"", "%", "str", "(", "query", ")", ")", "cursor", "=", ...
30.833333
14.166667
def _is_typing_namedtuple(node: astroid.ClassDef) -> bool: """Check if a class node is a typing.NamedTuple class""" for base in node.ancestors(): if base.qname() == TYPING_NAMEDTUPLE: return True return False
[ "def", "_is_typing_namedtuple", "(", "node", ":", "astroid", ".", "ClassDef", ")", "->", "bool", ":", "for", "base", "in", "node", ".", "ancestors", "(", ")", ":", "if", "base", ".", "qname", "(", ")", "==", "TYPING_NAMEDTUPLE", ":", "return", "True", ...
39.166667
11.833333
def _buildvgrid(self,R,phi,nsigma,t,sigmaR1,sigmaT1,meanvR,meanvT, gridpoints,print_progress,integrate_method,deriv): """Internal function to grid the vDF at a given location""" out= evolveddiskdfGrid() out.sigmaR1= sigmaR1 out.sigmaT1= sigmaT1 out.meanvR= mea...
[ "def", "_buildvgrid", "(", "self", ",", "R", ",", "phi", ",", "nsigma", ",", "t", ",", "sigmaR1", ",", "sigmaT1", ",", "meanvR", ",", "meanvT", ",", "gridpoints", ",", "print_progress", ",", "integrate_method", ",", "deriv", ")", ":", "out", "=", "evol...
57.857143
23.261905
def from_xarray(cls, arr: "xarray.Dataset") -> "Histogram1D": """Convert form xarray.Dataset Parameters ---------- arr: The data in xarray representation """ kwargs = {'frequencies': arr["frequencies"], 'binning': arr["bins"], 'errors2...
[ "def", "from_xarray", "(", "cls", ",", "arr", ":", "\"xarray.Dataset\"", ")", "->", "\"Histogram1D\"", ":", "kwargs", "=", "{", "'frequencies'", ":", "arr", "[", "\"frequencies\"", "]", ",", "'binning'", ":", "arr", "[", "\"bins\"", "]", ",", "'errors2'", ...
36.4
13.266667
def adapter_remove_nio_binding(self, adapter_number): """ Removes a port NIO binding. :param adapter_number: adapter number :returns: NIO instance """ try: adapter = self._ethernet_adapters[adapter_number] except IndexError: raise QemuEr...
[ "def", "adapter_remove_nio_binding", "(", "self", ",", "adapter_number", ")", ":", "try", ":", "adapter", "=", "self", ".", "_ethernet_adapters", "[", "adapter_number", "]", "except", "IndexError", ":", "raise", "QemuError", "(", "'Adapter {adapter_number} does not ex...
47.107143
34.464286
def _nonzero(self): """ Equivalent numpy's nonzero but returns a tuple of Varibles. """ # TODO we should replace dask's native nonzero # after https://github.com/dask/dask/issues/1076 is implemented. nonzeros = np.nonzero(self.data) return tuple(Variable((dim), nz) for nz, dim ...
[ "def", "_nonzero", "(", "self", ")", ":", "# TODO we should replace dask's native nonzero", "# after https://github.com/dask/dask/issues/1076 is implemented.", "nonzeros", "=", "np", ".", "nonzero", "(", "self", ".", "data", ")", "return", "tuple", "(", "Variable", "(", ...
51.571429
12.571429
def caesar_app(parser, cmd, args): # pragma: no cover """ Caesar crypt a value with a key. """ parser.add_argument('shift', type=int, help='the shift to apply') parser.add_argument('value', help='the value to caesar crypt, read from stdin if omitted', nargs='?') parser.add_argument( '-...
[ "def", "caesar_app", "(", "parser", ",", "cmd", ",", "args", ")", ":", "# pragma: no cover", "parser", ".", "add_argument", "(", "'shift'", ",", "type", "=", "int", ",", "help", "=", "'the shift to apply'", ")", "parser", ".", "add_argument", "(", "'value'",...
34.789474
22.473684
def create_event_permission(self, lambda_name, principal, source_arn): """ Create permissions to link to an event. Related: http://docs.aws.amazon.com/lambda/latest/dg/with-s3-example-configure-event-source.html """ logger.debug('Adding new permission to invoke Lambda function: ...
[ "def", "create_event_permission", "(", "self", ",", "lambda_name", ",", "principal", ",", "source_arn", ")", ":", "logger", ".", "debug", "(", "'Adding new permission to invoke Lambda function: {}'", ".", "format", "(", "lambda_name", ")", ")", "permission_response", ...
44.15
24.75
def setChecked(self, state): """ Sets whether or not this button is in its locked state. :param state | <bool> """ super(XLockButton, self).setChecked(state) self.updateState()
[ "def", "setChecked", "(", "self", ",", "state", ")", ":", "super", "(", "XLockButton", ",", "self", ")", ".", "setChecked", "(", "state", ")", "self", ".", "updateState", "(", ")" ]
29.75
12
def _discover_thread(callback, timeout, include_invisible, interface_addr): """ Discover Sonos zones on the local network. """ def create_socket(interface_addr=None): """ A helper function for creating a socket for discover purposes. ...
[ "def", "_discover_thread", "(", "callback", ",", "timeout", ",", "include_invisible", ",", "interface_addr", ")", ":", "def", "create_socket", "(", "interface_addr", "=", "None", ")", ":", "\"\"\" A helper function for creating a socket for discover purposes.\n\n Creat...
39.041667
17.808333
async def async_get_current_program(channel, no_cache=False): ''' Get the current program info ''' chan = await async_determine_channel(channel) guide = await async_get_program_guide(chan, no_cache) if not guide: _LOGGER.warning('Could not retrieve TV program for %s', channel) re...
[ "async", "def", "async_get_current_program", "(", "channel", ",", "no_cache", "=", "False", ")", ":", "chan", "=", "await", "async_determine_channel", "(", "channel", ")", "guide", "=", "await", "async_get_program_guide", "(", "chan", ",", "no_cache", ")", "if",...
33.533333
17
async def disconnect(self): """ Disconnect from target. """ if not self.connected: return self.writer.close() self.reader = None self.writer = None
[ "async", "def", "disconnect", "(", "self", ")", ":", "if", "not", "self", ".", "connected", ":", "return", "self", ".", "writer", ".", "close", "(", ")", "self", ".", "reader", "=", "None", "self", ".", "writer", "=", "None" ]
24.125
15.75
def get_list(cache_length=24, map_vendor_oids=True, cert_callback=None): """ Retrieves (and caches in memory) the list of CA certs from the OS. Includes trust information from the OS - purposes the certificate should be trusted or rejected for. Trust information is encoded via object identifiers (O...
[ "def", "get_list", "(", "cache_length", "=", "24", ",", "map_vendor_oids", "=", "True", ",", "cert_callback", "=", "None", ")", ":", "if", "not", "_in_memory_up_to_date", "(", "cache_length", ")", ":", "with", "memory_lock", ":", "if", "not", "_in_memory_up_to...
53.552239
31.074627
def plot_prep_methods(df, prep, prepi, out_file_base, outtype, title=None, size=None): """Plot comparison between BAM preparation methods. """ samples = df[(df["bamprep"] == prep)]["sample"].unique() assert len(samples) >= 1, samples out_file = "%s-%s.%s" % (out_file_base, samp...
[ "def", "plot_prep_methods", "(", "df", ",", "prep", ",", "prepi", ",", "out_file_base", ",", "outtype", ",", "title", "=", "None", ",", "size", "=", "None", ")", ":", "samples", "=", "df", "[", "(", "df", "[", "\"bamprep\"", "]", "==", "prep", ")", ...
44.5
12.5
def save_as(self): """Dialog for getting name, location of data export file.""" filename = splitext( self.parent.notes.annot.xml_file)[0] + '_data' filename, _ = QFileDialog.getSaveFileName(self, 'Export analysis data', filename, ...
[ "def", "save_as", "(", "self", ")", ":", "filename", "=", "splitext", "(", "self", ".", "parent", ".", "notes", ".", "annot", ".", "xml_file", ")", "[", "0", "]", "+", "'_data'", "filename", ",", "_", "=", "QFileDialog", ".", "getSaveFileName", "(", ...
43.538462
19.538462
def __find(self, name): """ Find a I{port} by name (string) or index (integer). @param name: The name (or index) of a port. @type name: (int|str) @return: A L{MethodSelector} for the found port. @rtype: L{MethodSelector}. """ port = None if not len...
[ "def", "__find", "(", "self", ",", "name", ")", ":", "port", "=", "None", "if", "not", "len", "(", "self", ".", "__ports", ")", ":", "raise", "Exception", "(", "'No ports defined: %s'", "%", "self", ".", "__qn", ")", "if", "isinstance", "(", "name", ...
34.62963
11.074074