text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def parameter_converter(*convert_types): ''' Decorator that denotes a function as a url parameter converter. ''' def inner(func): for ct in convert_types: ParameterConverter._register_converter(func, ct) return func return inner
[ "def", "parameter_converter", "(", "*", "convert_types", ")", ":", "def", "inner", "(", "func", ")", ":", "for", "ct", "in", "convert_types", ":", "ParameterConverter", ".", "_register_converter", "(", "func", ",", "ct", ")", "return", "func", "return", "inn...
29.777778
20.666667
def maps_get_rules_output_rules_rbridgeid(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") maps_get_rules = ET.Element("maps_get_rules") config = maps_get_rules output = ET.SubElement(maps_get_rules, "output") rules = ET.SubElement(output,...
[ "def", "maps_get_rules_output_rules_rbridgeid", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "maps_get_rules", "=", "ET", ".", "Element", "(", "\"maps_get_rules\"", ")", "config", "=", "maps_get_r...
39.307692
11.692308
def fetch_next_block(self): """Returns a block of results with respecting retry policy. This method only exists for backward compatibility reasons. (Because QueryIterable has exposed fetch_next_block api). :return: List of results. :rtype: list ...
[ "def", "fetch_next_block", "(", "self", ")", ":", "if", "self", ".", "_ex_context", "is", "None", ":", "# initiates execution context for the first time", "self", ".", "_ex_context", "=", "self", ".", "_create_execution_context", "(", ")", "return", "self", ".", "...
32.529412
19.705882
def lti_sde_to_descrete(F,L,Qc,dt,compute_derivatives=False, grad_params_no=None, P_inf=None, dP_inf=None, dF = None, dQc=None): """ Linear Time-Invariant Stochastic Differential Equation (LTI SDE): dx(t) = F x(t) dt + L d \beta ,wher...
[ "def", "lti_sde_to_descrete", "(", "F", ",", "L", ",", "Qc", ",", "dt", ",", "compute_derivatives", "=", "False", ",", "grad_params_no", "=", "None", ",", "P_inf", "=", "None", ",", "dP_inf", "=", "None", ",", "dF", "=", "None", ",", "dQc", "=", "Non...
36.041176
22.017647
def attributes_js(cls, attributes): """ Generates JS code to look up attributes on JS objects from an attributes specification dictionary. If the specification references a plotting particular plotting handle it will also generate JS code to get the ID of the object. Sim...
[ "def", "attributes_js", "(", "cls", ",", "attributes", ")", ":", "assign_template", "=", "'{assign}{{id: {obj_name}[\"id\"], value: {obj_name}{attr_getters}}};\\n'", "conditional_template", "=", "'if (({obj_name} != undefined)) {{ {assign} }}'", "code", "=", "''", "for", "key", ...
41.560976
22.243902
def note_on(self, channel, note, velocity): """Return bytes for a 'note_on' event.""" return self.midi_event(NOTE_ON, channel, note, velocity)
[ "def", "note_on", "(", "self", ",", "channel", ",", "note", ",", "velocity", ")", ":", "return", "self", ".", "midi_event", "(", "NOTE_ON", ",", "channel", ",", "note", ",", "velocity", ")" ]
52
9
def merge_enrollments(db, uuid, organization): """Merge overlapping enrollments. This function merges those enrollments, related to the given 'uuid' and 'organization', that have overlapping dates. Default start and end dates (1900-01-01 and 2100-01-01) are considered range limits and will be remov...
[ "def", "merge_enrollments", "(", "db", ",", "uuid", ",", "organization", ")", ":", "# Merge enrollments", "with", "db", ".", "connect", "(", ")", "as", "session", ":", "uidentity", "=", "find_unique_identity", "(", "session", ",", "uuid", ")", "if", "not", ...
38.333333
21.222222
def lint(): "report pylint results" # report according to file extension report_formats = { ".html": "html", ".log": "parseable", ".txt": "text", } lint_build_dir = easy.path("build/lint") lint_build_dir.exists() or lint_build_dir.makedirs() # pylint: disable=expression...
[ "def", "lint", "(", ")", ":", "# report according to file extension", "report_formats", "=", "{", "\".html\"", ":", "\"html\"", ",", "\".log\"", ":", "\"parseable\"", ",", "\".txt\"", ":", "\"text\"", ",", "}", "lint_build_dir", "=", "easy", ".", "path", "(", ...
37.419355
21.709677
def get_chatlist(chatfile): """Try reading ids of saved chats from file. If we fail, return empty set""" if not chatfile: return set() try: with open(chatfile) as file_contents: return set(int(chat) for chat in file_contents) except (OSError, IOError) as exc: LOGG...
[ "def", "get_chatlist", "(", "chatfile", ")", ":", "if", "not", "chatfile", ":", "return", "set", "(", ")", "try", ":", "with", "open", "(", "chatfile", ")", "as", "file_contents", ":", "return", "set", "(", "int", "(", "chat", ")", "for", "chat", "in...
34.454545
13.818182
def replace(self, nodes): """ Replaces user defined files search pattern occurrences with replacement pattern using given nodes. :param nodes: Nodes. :type nodes: list :return: Method success. :rtype: bool """ files = {} for node in nodes: ...
[ "def", "replace", "(", "self", ",", "nodes", ")", ":", "files", "=", "{", "}", "for", "node", "in", "nodes", ":", "if", "node", ".", "family", "==", "\"SearchFile\"", ":", "files", "[", "node", ".", "file", "]", "=", "node", ".", "children", "elif"...
43.911111
24.133333
def _get_event_id(object_type: str) -> str: """Return an event key for the event on the object type. This must be a unique event id for the object. Args: object_type (str): Type of object Returns: str, event id """ key = _keys.event_counter(object_type) DB.watch(key, pipe...
[ "def", "_get_event_id", "(", "object_type", ":", "str", ")", "->", "str", ":", "key", "=", "_keys", ".", "event_counter", "(", "object_type", ")", "DB", ".", "watch", "(", "key", ",", "pipeline", "=", "True", ")", "count", "=", "DB", ".", "get_value", ...
24.05
18.9
def apply_next_patch(self, force=False, quiet=False): """ Apply next patch in series file """ self._check() top = self.db.top_patch() if not top: patch = self.series.first_patch() else: patch = self.series.patch_after(top) if not patch: ...
[ "def", "apply_next_patch", "(", "self", ",", "force", "=", "False", ",", "quiet", "=", "False", ")", ":", "self", ".", "_check", "(", ")", "top", "=", "self", ".", "db", ".", "top_patch", "(", ")", "if", "not", "top", ":", "patch", "=", "self", "...
25.789474
19.421053
def _export_model(models): """ Switch model tables to index-by-number :param dict models: Metadata :return dict _models: Metadata """ logger_jsons.info("enter export_model") _models = [] try: for name, model in models.items(): if "summaryTable" in model: ...
[ "def", "_export_model", "(", "models", ")", ":", "logger_jsons", ".", "info", "(", "\"enter export_model\"", ")", "_models", "=", "[", "]", "try", ":", "for", "name", ",", "model", "in", "models", ".", "items", "(", ")", ":", "if", "\"summaryTable\"", "i...
31.551724
19.206897
def copy(self, dst, **kwargs): """Copy file to a new destination. Returns JSON Patch with proposed change pointing to new copy. """ _fs, filename = opener.parse(self.uri) _fs_dst, filename_dst = opener.parse(dst) copyfile(_fs, filename, _fs_dst, filename_dst, **kwargs) ...
[ "def", "copy", "(", "self", ",", "dst", ",", "*", "*", "kwargs", ")", ":", "_fs", ",", "filename", "=", "opener", ".", "parse", "(", "self", ".", "uri", ")", "_fs_dst", ",", "filename_dst", "=", "opener", ".", "parse", "(", "dst", ")", "copyfile", ...
42.333333
16.444444
def start(self): """ Starts the IOU process. """ self._check_requirements() if not self.is_running(): yield from self._library_check() try: self._rename_nvram_file() except OSError as e: raise IOUError("Could ...
[ "def", "start", "(", "self", ")", ":", "self", ".", "_check_requirements", "(", ")", "if", "not", "self", ".", "is_running", "(", ")", ":", "yield", "from", "self", ".", "_library_check", "(", ")", "try", ":", "self", ".", "_rename_nvram_file", "(", ")...
44.455882
23.691176
def query_region(self, chrom=None, start=None, stop=None): """Query the table, returning row or rows within the given genomic region. Parameters ---------- chrom : string, optional Chromosome/contig. start : int, optional Region start position (1-...
[ "def", "query_region", "(", "self", ",", "chrom", "=", "None", ",", "start", "=", "None", ",", "stop", "=", "None", ")", ":", "if", "self", ".", "index", "is", "None", ":", "raise", "ValueError", "(", "'no index has been set'", ")", "if", "isinstance", ...
29.5
16.846154
def add_iri_thermal_plasma(inst, glat_label='glat', glong_label='glong', alt_label='alt'): """ Uses IRI (International Reference Ionosphere) model to simulate an ionosphere. Uses pyglow module to run IRI. Configured to use actual solar parameters to run model. ...
[ "def", "add_iri_thermal_plasma", "(", "inst", ",", "glat_label", "=", "'glat'", ",", "glong_label", "=", "'glong'", ",", "alt_label", "=", "'alt'", ")", ":", "import", "pyglow", "from", "pyglow", ".", "pyglow", "import", "Point", "iri_params", "=", "[", "]",...
42.046875
26.59375
def no_use_pep517_callback(option, opt, value, parser): """ Process a value provided for the --no-use-pep517 option. This is an optparse.Option callback for the no_use_pep517 option. """ # Since --no-use-pep517 doesn't accept arguments, the value argument # will be None if --no-use-pep517 is pa...
[ "def", "no_use_pep517_callback", "(", "option", ",", "opt", ",", "value", ",", "parser", ")", ":", "# Since --no-use-pep517 doesn't accept arguments, the value argument", "# will be None if --no-use-pep517 is passed via the command-line.", "# However, the value can be non-None if the opt...
46.904762
20.571429
def determine_end_point(http_request, url): """ returns detail, list or aggregates """ if url.endswith('aggregates') or url.endswith('aggregates/'): return 'aggregates' else: return 'detail' if is_detail_url(http_request, url) else 'list'
[ "def", "determine_end_point", "(", "http_request", ",", "url", ")", ":", "if", "url", ".", "endswith", "(", "'aggregates'", ")", "or", "url", ".", "endswith", "(", "'aggregates/'", ")", ":", "return", "'aggregates'", "else", ":", "return", "'detail'", "if", ...
33.375
13.125
def calculate_leaf_paths(self): """Build map of reverse xrefs then traverse backwards marking path to leaf for all leaves. """ reverse_xref = {} leaves = set() for v in self.value.values(): if v.leaf: leaves.add(v) for xref in v.value_xref:...
[ "def", "calculate_leaf_paths", "(", "self", ")", ":", "reverse_xref", "=", "{", "}", "leaves", "=", "set", "(", ")", "for", "v", "in", "self", ".", "value", ".", "values", "(", ")", ":", "if", "v", ".", "leaf", ":", "leaves", ".", "add", "(", "v"...
38.333333
10.916667
def __parse_organizations(self, stream): """Parse organizations stream""" for aliases in self.__parse_stream(stream): # Parse identity identity = self.__parse_alias(aliases[1]) uuid = identity.email uid = self._identities.get(uuid, None) if ...
[ "def", "__parse_organizations", "(", "self", ",", "stream", ")", ":", "for", "aliases", "in", "self", ".", "__parse_stream", "(", "stream", ")", ":", "# Parse identity", "identity", "=", "self", ".", "__parse_alias", "(", "aliases", "[", "1", "]", ")", "uu...
32.103448
16.241379
def parse_plugin_metadata(content): """Parse summary metadata to a Python object. Arguments: content: The `content` field of a `SummaryMetadata` proto corresponding to the pr_curves plugin. Returns: A `PrCurvesPlugin` protobuf object. """ if not isinstance(content, bytes): raise TypeError(...
[ "def", "parse_plugin_metadata", "(", "content", ")", ":", "if", "not", "isinstance", "(", "content", ",", "bytes", ")", ":", "raise", "TypeError", "(", "'Content type must be bytes'", ")", "result", "=", "plugin_data_pb2", ".", "PrCurvePluginData", ".", "FromStrin...
32
18.666667
def project_gdf(gdf, to_crs=None, to_latlong=False): """ Project a GeoDataFrame to the UTM zone appropriate for its geometries' centroid. The simple calculation in this function works well for most latitudes, but won't work for some far northern locations like Svalbard and parts of far northern...
[ "def", "project_gdf", "(", "gdf", ",", "to_crs", "=", "None", ",", "to_latlong", "=", "False", ")", ":", "assert", "len", "(", "gdf", ")", ">", "0", ",", "'You cannot project an empty GeoDataFrame.'", "start_time", "=", "time", ".", "time", "(", ")", "# if...
37.106061
23.621212
def init_dict(data, index, columns, dtype=None): """ Segregate Series based on type and coerce into matrices. Needs to handle a lot of exceptional cases. """ if columns is not None: from pandas.core.series import Series arrays = Series(data, index=columns, dtype=object) data_...
[ "def", "init_dict", "(", "data", ",", "index", ",", "columns", ",", "dtype", "=", "None", ")", ":", "if", "columns", "is", "not", "None", ":", "from", "pandas", ".", "core", ".", "series", "import", "Series", "arrays", "=", "Series", "(", "data", ","...
38.810811
16.378378
def all(self, page=1, per_page=10): """ Get a single page from the list of all collections. :param page [integer]: Page number to retrieve. (Optional; default: 1) :param per_page [integer]: Number of items per page. (Optional; default: 10) :return: [Array]: A single page of the ...
[ "def", "all", "(", "self", ",", "page", "=", "1", ",", "per_page", "=", "10", ")", ":", "url", "=", "\"/collections\"", "result", "=", "self", ".", "_all", "(", "url", ",", "page", "=", "page", ",", "per_page", "=", "per_page", ")", "return", "Coll...
43.545455
19.181818
def update(self, scaling_group, name=None, cooldown=None, min_entities=None, max_entities=None, metadata=None): """ Updates an existing ScalingGroup. One or more of the attributes can be specified. NOTE: if you specify metadata, it will *replace* any existing metadata. ...
[ "def", "update", "(", "self", ",", "scaling_group", ",", "name", "=", "None", ",", "cooldown", "=", "None", ",", "min_entities", "=", "None", ",", "max_entities", "=", "None", ",", "metadata", "=", "None", ")", ":", "return", "self", ".", "_manager", "...
48.846154
23.769231
def to_fixed(stype): """ Returns the instruction sequence for converting the given type stored in DE,HL to fixed DE,HL. """ output = [] # List of instructions if is_int_type(stype): output = to_word(stype) output.append('ex de, hl') output.append('ld hl, 0') # 'Truncate' t...
[ "def", "to_fixed", "(", "stype", ")", ":", "output", "=", "[", "]", "# List of instructions", "if", "is_int_type", "(", "stype", ")", ":", "output", "=", "to_word", "(", "stype", ")", "output", ".", "append", "(", "'ex de, hl'", ")", "output", ".", "appe...
29.466667
13.2
def stop(self): """Stop the current timer if there is one and cancel the async call.""" if self._timer: self._timer.stop() self._timer.deleteLater()
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "_timer", ":", "self", ".", "_timer", ".", "stop", "(", ")", "self", ".", "_timer", ".", "deleteLater", "(", ")" ]
36.8
11
def logout(): """ Log out the active user """ flogin.logout_user() next = flask.request.args.get('next') return flask.redirect(next or flask.url_for("user"))
[ "def", "logout", "(", ")", ":", "flogin", ".", "logout_user", "(", ")", "next", "=", "flask", ".", "request", ".", "args", ".", "get", "(", "'next'", ")", "return", "flask", ".", "redirect", "(", "next", "or", "flask", ".", "url_for", "(", "\"user\""...
28.666667
10
def get_qutip_module(required_version='3.2'): """ Attempts to return the qutip module, but silently returns ``None`` if it can't be imported, or doesn't have version at least ``required_version``. :param str required_version: Valid input to ``distutils.version.LooseVersion``. :retur...
[ "def", "get_qutip_module", "(", "required_version", "=", "'3.2'", ")", ":", "try", ":", "import", "qutip", "as", "qt", "from", "distutils", ".", "version", "import", "LooseVersion", "_qt_version", "=", "LooseVersion", "(", "qt", ".", "version", ".", "version",...
30
12.909091
def unitary(self, obj, qubits, label=None): """Apply u2 to q.""" if isinstance(qubits, QuantumRegister): qubits = qubits[:] return self.append(UnitaryGate(obj, label=label), qubits, [])
[ "def", "unitary", "(", "self", ",", "obj", ",", "qubits", ",", "label", "=", "None", ")", ":", "if", "isinstance", "(", "qubits", ",", "QuantumRegister", ")", ":", "qubits", "=", "qubits", "[", ":", "]", "return", "self", ".", "append", "(", "Unitary...
40.2
9
def drawQuad(self, quad): """Draw a Quad. """ q = Quad(quad) return self.drawPolyline([q.ul, q.ll, q.lr, q.ur, q.ul])
[ "def", "drawQuad", "(", "self", ",", "quad", ")", ":", "q", "=", "Quad", "(", "quad", ")", "return", "self", ".", "drawPolyline", "(", "[", "q", ".", "ul", ",", "q", ".", "ll", ",", "q", ".", "lr", ",", "q", ".", "ur", ",", "q", ".", "ul", ...
29
11.4
def pulse(self): """ Calls when_rotated callback if detected changes """ new_b_value = self.gpio_b.is_active new_a_value = self.gpio_a.is_active value = self.table_values.value(new_b_value, new_a_value, self.old_b_value, self.old_a_value) self.old_b_value = new_...
[ "def", "pulse", "(", "self", ")", ":", "new_b_value", "=", "self", ".", "gpio_b", ".", "is_active", "new_a_value", "=", "self", ".", "gpio_a", ".", "is_active", "value", "=", "self", ".", "table_values", ".", "value", "(", "new_b_value", ",", "new_a_value"...
29.571429
18
def pickle_load(path, compression=False): """Unpickle a possible compressed pickle. Parameters ---------- path: str path to the output file compression: bool if true assumes that pickle was compressed when created and attempts decompression. Returns ------- obj: object ...
[ "def", "pickle_load", "(", "path", ",", "compression", "=", "False", ")", ":", "if", "compression", ":", "with", "zipfile", ".", "ZipFile", "(", "path", ",", "\"r\"", ",", "compression", "=", "zipfile", ".", "ZIP_DEFLATED", ")", "as", "myzip", ":", "with...
26.043478
21.086957
def safe_mkdir_for_all(paths): """Make directories which would contain all of the passed paths. This avoids attempting to re-make the same directories, which may be noticeably expensive if many paths mostly fall in the same set of directories. :param list of str paths: The paths for which containing directori...
[ "def", "safe_mkdir_for_all", "(", "paths", ")", ":", "created_dirs", "=", "set", "(", ")", "for", "path", "in", "paths", ":", "dir_to_make", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "if", "dir_to_make", "not", "in", "created_dirs", ":", ...
37.428571
18.928571
def draw_boundary_images(glf, glb, v, f, vpe, fpe, camera): """Assumes camera is set up correctly, and that glf has any texmapping on necessary.""" glf.Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glb.Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); # Figure out which edges are on pairs of differ...
[ "def", "draw_boundary_images", "(", "glf", ",", "glb", ",", "v", ",", "f", ",", "vpe", ",", "fpe", ",", "camera", ")", ":", "glf", ".", "Clear", "(", "GL_COLOR_BUFFER_BIT", "|", "GL_DEPTH_BUFFER_BIT", ")", "glb", ".", "Clear", "(", "GL_COLOR_BUFFER_BIT", ...
47.96
18.16
def submit_text(self, sr, title, text, follow=True): """Login required. POSTs a text submission. Returns :class:`things.Link` object if ``follow=True`` (default), or the string permalink of the new submission otherwise. Argument ``follow`` exists because reddit only returns the permalink afte...
[ "def", "submit_text", "(", "self", ",", "sr", ",", "title", ",", "text", ",", "follow", "=", "True", ")", ":", "return", "self", ".", "_submit", "(", "sr", ",", "title", ",", "'self'", ",", "text", "=", "text", ",", "follow", "=", "follow", ")" ]
64.5
35.5625
def get_resource_id(self): """Gets the ``resource _id`` for this authorization. return: (osid.id.Id) - the ``Resource Id`` raise: IllegalState - ``has_resource()`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template ...
[ "def", "get_resource_id", "(", "self", ")", ":", "# Implemented from template for osid.resource.Resource.get_avatar_id_template", "if", "not", "bool", "(", "self", ".", "_my_map", "[", "'resourceId'", "]", ")", ":", "raise", "errors", ".", "IllegalState", "(", "'this ...
42
21.307692
def render_to_terminal(self, array, cursor_pos=(0, 0)): """Renders array to terminal, returns the number of lines scrolled offscreen Returns: Number of times scrolled Args: array (FSArray): Grid of styled characters to be rendered. If array received is of wid...
[ "def", "render_to_terminal", "(", "self", ",", "array", ",", "cursor_pos", "=", "(", "0", ",", "0", ")", ")", ":", "for_stdout", "=", "self", ".", "fmtstr_to_stdout_xform", "(", ")", "# caching of write and tc (avoiding the self. lookups etc) made", "# no significant ...
39.054348
19
def normalized_flux_to_mag(lcdict, columns=('sap.sap_flux', 'sap.sap_flux_err', 'sap.sap_bkg', 'sap.sap_bkg_err', 'pdc.pdcsap_flux', ...
[ "def", "normalized_flux_to_mag", "(", "lcdict", ",", "columns", "=", "(", "'sap.sap_flux'", ",", "'sap.sap_flux_err'", ",", "'sap.sap_bkg'", ",", "'sap.sap_bkg_err'", ",", "'pdc.pdcsap_flux'", ",", "'pdc.pdcsap_flux_err'", ")", ")", ":", "tess_mag", "=", "lcdict", "...
29.716981
27.226415
def health_check(self): """Uses head object to make sure the file exists in S3.""" logger.debug('Health Check on S3 file for: {namespace}'.format( namespace=self.namespace )) try: self.client.head_object(Bucket=self.bucket_name, Key=self.data_file) re...
[ "def", "health_check", "(", "self", ")", ":", "logger", ".", "debug", "(", "'Health Check on S3 file for: {namespace}'", ".", "format", "(", "namespace", "=", "self", ".", "namespace", ")", ")", "try", ":", "self", ".", "client", ".", "head_object", "(", "Bu...
38.636364
22.454545
def create_snapshot(self, name): """ :: POST /:login/machines/:id/snapshots :param name: identifier for snapshot :type name: :py:class:`basestring` :rtype: :py:class:`smartdc.machine.Snapshot` Create a snapshot for this mach...
[ "def", "create_snapshot", "(", "self", ",", "name", ")", ":", "params", "=", "{", "'name'", ":", "name", "}", "j", ",", "_", "=", "self", ".", "datacenter", ".", "request", "(", "'POST'", ",", "self", ".", "path", "+", "'/snapshots'", ",", "data", ...
30.777778
18
def _generate_idx(n, seed, n_train, n_test): """Generate train, test indices for a length-n array. Parameters ---------- n : int The length of the array seed : int Seed for a RandomState n_train, n_test : int, 0 < n_train, n_test < n Number of samples to use for the trai...
[ "def", "_generate_idx", "(", "n", ",", "seed", ",", "n_train", ",", "n_test", ")", ":", "idx", "=", "check_random_state", "(", "seed", ")", ".", "permutation", "(", "n", ")", "ind_test", "=", "idx", "[", ":", "n_test", "]", "ind_train", "=", "idx", "...
24.285714
18.571429
def _get_master_schema(version): # type: (Hashable) -> bytes """ Loads the master schema of given version as bytes. :param version: The version of the master schema whose path we wish to retrieve. :raises SchemaError: When the schema version is unknown. This usually mean...
[ "def", "_get_master_schema", "(", "version", ")", ":", "# type: (Hashable) -> bytes", "try", ":", "file_name", "=", "MASTER_SCHEMA_FILE_NAMES", "[", "version", "]", "except", "(", "TypeError", ",", "KeyError", ")", "as", "e", ":", "msg", "=", "(", "'Schema versi...
40.333333
19.69697
def Cleanup(self): """ Cleanup Timed out connections Loop though all the connections and test if still active. If inactive close socket. @author: Nick Verbeck @since: 2/20/2009 """ self.lock.acquire() try: for bucket in self.connections.values(): try: for conn in bucket: conn.loc...
[ "def", "Cleanup", "(", "self", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "for", "bucket", "in", "self", ".", "connections", ".", "values", "(", ")", ":", "try", ":", "for", "conn", "in", "bucket", ":", "conn", ".", "loc...
23
21.133333
def in_(self, *values): ''' A query to check if this query field is one of the values in ``values``. Produces a MongoDB ``$in`` expression. ''' return QueryExpression({ self : { '$in' : [self.get_type().wrap_value(value) for value in values] } })
[ "def", "in_", "(", "self", ",", "*", "values", ")", ":", "return", "QueryExpression", "(", "{", "self", ":", "{", "'$in'", ":", "[", "self", ".", "get_type", "(", ")", ".", "wrap_value", "(", "value", ")", "for", "value", "in", "values", "]", "}", ...
42.428571
26.428571
def groupByNode(requestContext, seriesList, nodeNum, callback): """ Takes a serieslist and maps a callback to subgroups within as defined by a common node. Example:: &target=groupByNode(ganglia.by-function.*.*.cpu.load5,2,"sumSeries") Would return multiple series which are each the result...
[ "def", "groupByNode", "(", "requestContext", ",", "seriesList", ",", "nodeNum", ",", "callback", ")", ":", "return", "groupByNodes", "(", "requestContext", ",", "seriesList", ",", "callback", ",", "nodeNum", ")" ]
35.444444
27
def prioSort(elements): """Sort a list of elements that have priority attributes""" # Randomize the services before sorting so that equal priority # elements are load-balanced. random.shuffle(elements) sorted_elems = sorted(elements, key=getPriority) return sorted_elems
[ "def", "prioSort", "(", "elements", ")", ":", "# Randomize the services before sorting so that equal priority", "# elements are load-balanced.", "random", ".", "shuffle", "(", "elements", ")", "sorted_elems", "=", "sorted", "(", "elements", ",", "key", "=", "getPriority",...
36
16.375
def _process_list(self, l): """ Processes a list of widget names. If any name is between `` then it is supposed to be a regex. """ if hasattr(self, l): t = getattr(self, l) def proc(inp): w = inp.strip() if w.startswith('...
[ "def", "_process_list", "(", "self", ",", "l", ")", ":", "if", "hasattr", "(", "self", ",", "l", ")", ":", "t", "=", "getattr", "(", "self", ",", "l", ")", "def", "proc", "(", "inp", ")", ":", "w", "=", "inp", ".", "strip", "(", ")", "if", ...
30.380952
22.761905
def append_all_below(destination, source, join_str=None): """ Compared to xml.dom.minidom, lxml's treatment of text as .text and .tail attributes of elements is an oddity. It can even be a little frustrating when one is attempting to copy everything underneath some element to another element; one ha...
[ "def", "append_all_below", "(", "destination", ",", "source", ",", "join_str", "=", "None", ")", ":", "if", "join_str", "is", "None", ":", "join_str", "=", "' '", "if", "source", ".", "text", "is", "not", "None", ":", "# If source has text", "if", "len", ...
50
17.307692
def create(path,archiveList,xFilesFactor=None,aggregationMethod=None,sparse=False,useFallocate=False): """create(path,archiveList,xFilesFactor=0.5,aggregationMethod='average') path is a string archiveList is a list of archives, each of which is of the form (secondsPerPoint,numberOfPoints) xFilesFactor specifies the ...
[ "def", "create", "(", "path", ",", "archiveList", ",", "xFilesFactor", "=", "None", ",", "aggregationMethod", "=", "None", ",", "sparse", "=", "False", ",", "useFallocate", "=", "False", ")", ":", "# Set default params", "if", "xFilesFactor", "is", "None", "...
38.6875
24.015625
def call(self, my_args=None): """ publish the message in the topic :param my_args: dict like {msg: 'msg'} :return: nothing """ LOGGER.debug("zeromq.Publisher.call") if my_args is None: raise exceptions.ArianeConfError("publisher call arguments") ...
[ "def", "call", "(", "self", ",", "my_args", "=", "None", ")", ":", "LOGGER", ".", "debug", "(", "\"zeromq.Publisher.call\"", ")", "if", "my_args", "is", "None", ":", "raise", "exceptions", ".", "ArianeConfError", "(", "\"publisher call arguments\"", ")", "if",...
48.571429
18.428571
def size(self, destination): """ Size of the queue for specified destination. @param destination: The queue destination (e.g. /queue/foo) @type destination: C{str} @return: The number of frames in specified queue. @rtype: C{int} """ if not destination in...
[ "def", "size", "(", "self", ",", "destination", ")", ":", "if", "not", "destination", "in", "self", ".", "queue_metadata", ":", "return", "0", "else", ":", "return", "len", "(", "self", ".", "queue_metadata", "[", "destination", "]", "[", "'frames'", "]"...
30.714286
18.285714
def update(self, item): """ Add a collector item. Args: item (CollectorUpdate): event data like stage, timestampe and status. """ if item.matrix not in self.data: self.data[item.matrix] = [] result = Select(self.data[item.matrix]).where( ...
[ "def", "update", "(", "self", ",", "item", ")", ":", "if", "item", ".", "matrix", "not", "in", "self", ".", "data", ":", "self", ".", "data", "[", "item", ".", "matrix", "]", "=", "[", "]", "result", "=", "Select", "(", "self", ".", "data", "["...
33.238095
17.809524
def scopus_url(self): """URL to the abstract page on Scopus.""" scopus_url = self.coredata.find('link[@rel="scopus"]', ns) try: return scopus_url.get('href') except AttributeError: # scopus_url is None return None
[ "def", "scopus_url", "(", "self", ")", ":", "scopus_url", "=", "self", ".", "coredata", ".", "find", "(", "'link[@rel=\"scopus\"]'", ",", "ns", ")", "try", ":", "return", "scopus_url", ".", "get", "(", "'href'", ")", "except", "AttributeError", ":", "# sco...
37.714286
14.714286
def bind(self, format, *args): """ Bind a socket to a formatted endpoint. For tcp:// endpoints, supports ephemeral ports, if you specify the port number as "*". By default zsock uses the IANA designated range from C000 (49152) to FFFF (65535). To override this range, follow the "*" with "[first-last]". ...
[ "def", "bind", "(", "self", ",", "format", ",", "*", "args", ")", ":", "return", "lib", ".", "zsock_bind", "(", "self", ".", "_as_parameter_", ",", "format", ",", "*", "args", ")" ]
49.458333
25.041667
def _atexit_verify() -> None: """Warns if the libtcod root console is implicitly deleted.""" if lib.TCOD_ctx.root: warnings.warn( "The libtcod root console was implicitly deleted.\n" "Make sure the 'with' statement is used with the root console to" " ensure that it cl...
[ "def", "_atexit_verify", "(", ")", "->", "None", ":", "if", "lib", ".", "TCOD_ctx", ".", "root", ":", "warnings", ".", "warn", "(", "\"The libtcod root console was implicitly deleted.\\n\"", "\"Make sure the 'with' statement is used with the root console to\"", "\" ensure tha...
39.363636
15.545455
def _geolocation_extract(response): """ Mimics the exception handling logic in ``client._get_body``, but for geolocation which uses a different response format. """ body = response.json() if response.status_code in (200, 404): return body try: error = body["error"]["errors"]...
[ "def", "_geolocation_extract", "(", "response", ")", ":", "body", "=", "response", ".", "json", "(", ")", "if", "response", ".", "status_code", "in", "(", "200", ",", "404", ")", ":", "return", "body", "try", ":", "error", "=", "body", "[", "\"error\""...
29.888889
18.888889
def check_throttles(self, request): """ Check if request should be throttled. Raises an appropriate exception if the request is throttled. """ for throttle in self.get_throttles(): if not throttle.allow_request(request, self): self.throttled(request, t...
[ "def", "check_throttles", "(", "self", ",", "request", ")", ":", "for", "throttle", "in", "self", ".", "get_throttles", "(", ")", ":", "if", "not", "throttle", ".", "allow_request", "(", "request", ",", "self", ")", ":", "self", ".", "throttled", "(", ...
41
9.5
def active_network_addresses(hypervisor): """Query libvirt for the already reserved addresses.""" active = [] for network in hypervisor.listNetworks(): try: xml = hypervisor.networkLookupByName(network).XMLDesc(0) except libvirt.libvirtError: # network has been destroyed meanwh...
[ "def", "active_network_addresses", "(", "hypervisor", ")", ":", "active", "=", "[", "]", "for", "network", "in", "hypervisor", ".", "listNetworks", "(", ")", ":", "try", ":", "xml", "=", "hypervisor", ".", "networkLookupByName", "(", "network", ")", ".", "...
36.666667
22.611111
def _jcols(self, *cols): """Return a JVM Seq of Columns from a list of Column or column names If `cols` has only one list in it, cols[0] will be used as the list. """ if len(cols) == 1 and isinstance(cols[0], list): cols = cols[0] return self._jseq(cols, _to_java_col...
[ "def", "_jcols", "(", "self", ",", "*", "cols", ")", ":", "if", "len", "(", "cols", ")", "==", "1", "and", "isinstance", "(", "cols", "[", "0", "]", ",", "list", ")", ":", "cols", "=", "cols", "[", "0", "]", "return", "self", ".", "_jseq", "(...
39.625
16.25
def _cmd_run(cmd, as_json=False): ''' Ensure that the Pki module is loaded, and convert to and extract data from Json as needed. ''' cmd_full = ['Import-Module -Name PKI; '] if as_json: cmd_full.append(r'ConvertTo-Json -Compress -Depth 4 -InputObject ' r'@({0})'....
[ "def", "_cmd_run", "(", "cmd", ",", "as_json", "=", "False", ")", ":", "cmd_full", "=", "[", "'Import-Module -Name PKI; '", "]", "if", "as_json", ":", "cmd_full", ".", "append", "(", "r'ConvertTo-Json -Compress -Depth 4 -InputObject '", "r'@({0})'", ".", "format", ...
31.555556
23.481481
def resolve_job_references(io_hash, job_outputs, should_resolve=True): ''' :param io_hash: an input or output hash in which to resolve any job-based object references possible :type io_hash: dict :param job_outputs: a mapping of finished local jobs to their output hashes :type job_outputs: dict ...
[ "def", "resolve_job_references", "(", "io_hash", ",", "job_outputs", ",", "should_resolve", "=", "True", ")", ":", "q", "=", "[", "]", "for", "field", "in", "io_hash", ":", "if", "is_job_ref", "(", "io_hash", "[", "field", "]", ")", ":", "io_hash", "[", ...
43.848485
25.787879
def sam_parse_reply(line): """parse a reply line into a dict""" parts = line.split(' ') opts = {k: v for (k, v) in split_kv(parts[2:])} return SAMReply(parts[0], opts)
[ "def", "sam_parse_reply", "(", "line", ")", ":", "parts", "=", "line", ".", "split", "(", "' '", ")", "opts", "=", "{", "k", ":", "v", "for", "(", "k", ",", "v", ")", "in", "split_kv", "(", "parts", "[", "2", ":", "]", ")", "}", "return", "SA...
35.8
8.6
def bgmagenta(cls, string, auto=False): """Color-code entire string. :param str string: String to colorize. :param bool auto: Enable auto-color (dark/light terminal). :return: Class instance for colorized string. :rtype: Color """ return cls.colorize('bgmagenta'...
[ "def", "bgmagenta", "(", "cls", ",", "string", ",", "auto", "=", "False", ")", ":", "return", "cls", ".", "colorize", "(", "'bgmagenta'", ",", "string", ",", "auto", "=", "auto", ")" ]
33.1
16.4
def _parse_command_response(response): """Parse an SCI command response into ElementTree XML This is a helper method that takes a Requests Response object of an SCI command response and will parse it into an ElementTree Element representing the root of the XML response. :param response: The reques...
[ "def", "_parse_command_response", "(", "response", ")", ":", "try", ":", "root", "=", "ET", ".", "fromstring", "(", "response", ".", "text", ")", "except", "ET", ".", "ParseError", ":", "raise", "ResponseParseError", "(", "\"Unexpected response format, could not p...
39
22.222222
def schedule(self): """Initiate distribution of the test collection. Initiate scheduling of the items across the nodes. If this gets called again later it behaves the same as calling ``._reschedule()`` on all nodes so that newly added nodes will start to be used. If ``.collect...
[ "def", "schedule", "(", "self", ")", ":", "assert", "self", ".", "collection_is_completed", "# Initial distribution already happened, reschedule on all nodes", "if", "self", ".", "collection", "is", "not", "None", ":", "for", "node", "in", "self", ".", "nodes", ":",...
36.271186
21.542373
def ac3(space): """ AC-3 algorithm. This reduces the domains of the variables by propagating constraints to ensure arc consistency. :param Space space: The space to reduce """ #determine arcs arcs = {} for name in space.variables: arcs[name] = set([]) for const in space.cons...
[ "def", "ac3", "(", "space", ")", ":", "#determine arcs", "arcs", "=", "{", "}", "for", "name", "in", "space", ".", "variables", ":", "arcs", "[", "name", "]", "=", "set", "(", "[", "]", ")", "for", "const", "in", "space", ".", "constraints", ":", ...
31.897436
13.384615
def status(self, status): """Sets the status of this StoreCreditPayment. :param status: The status of this StoreCreditPayment. :type: str """ allowed_values = ["pending", "awaitingRetry", "successful", "failed"] if status is not None and status not in allowed_values: ...
[ "def", "status", "(", "self", ",", "status", ")", ":", "allowed_values", "=", "[", "\"pending\"", ",", "\"awaitingRetry\"", ",", "\"successful\"", ",", "\"failed\"", "]", "if", "status", "is", "not", "None", "and", "status", "not", "in", "allowed_values", ":...
33.133333
21.6
def find_service_references( self, clazz=None, ldap_filter=None, only_one=False ): """ Finds all services references matching the given filter. :param clazz: Class implemented by the service :param ldap_filter: Service filter :param only_one: Return the first matchin...
[ "def", "find_service_references", "(", "self", ",", "clazz", "=", "None", ",", "ldap_filter", "=", "None", ",", "only_one", "=", "False", ")", ":", "with", "self", ".", "__svc_lock", ":", "if", "clazz", "is", "None", "and", "ldap_filter", "is", "None", "...
36.951613
16.532258
def _fix_callback_item(self, item): 'Update component identifier' item.component_id = self._fix_id(item.component_id) return item
[ "def", "_fix_callback_item", "(", "self", ",", "item", ")", ":", "item", ".", "component_id", "=", "self", ".", "_fix_id", "(", "item", ".", "component_id", ")", "return", "item" ]
37.5
12
def set_power_levels(self, room_id, content): """Perform PUT /rooms/$room_id/state/m.room.power_levels Note that any power levels which are not explicitly specified in the content arg are reset to default values. Args: room_id (str): The room ID content (dict): ...
[ "def", "set_power_levels", "(", "self", ",", "room_id", ",", "content", ")", ":", "# Synapse returns M_UNKNOWN if body['events'] is omitted,", "# as of 2016-10-31", "if", "\"events\"", "not", "in", "content", ":", "content", "[", "\"events\"", "]", "=", "{", "}", "...
40.789474
22.184211
def create_git_release(self, tag, name, message, draft=False, prerelease=False, target_commitish=github.GithubObject.NotSet): """ :calls: `POST /repos/:owner/:repo/releases <http://developer.github.com/v3/repos/releases>`_ :param tag: string :param name: string :param message: st...
[ "def", "create_git_release", "(", "self", ",", "tag", ",", "name", ",", "message", ",", "draft", "=", "False", ",", "prerelease", "=", "False", ",", "target_commitish", "=", "github", ".", "GithubObject", ".", "NotSet", ")", ":", "assert", "isinstance", "(...
52.638889
26.638889
def queryset(self): """This function sets the queryset according to the keyword arguments. For the crosstype, the input value is the the display value of CROSS_TYPE. This is done because the spaces in HET vs HET are not recognized. Therefore the queryset must be matched exactly (ie by ...
[ "def", "queryset", "(", "self", ")", ":", "from", "mousedb", ".", "animal", ".", "models", "import", "CROSS_TYPE", "crosstype_reverse", "=", "dict", "(", "(", "v", ",", "k", ")", "for", "k", ",", "v", "in", "CROSS_TYPE", ")", "try", ":", "crosstype", ...
48.736842
26.789474
def get_last_traded_dt(self, asset, dt): """ Get the latest minute on or before ``dt`` in which ``asset`` traded. If there are no trades on or before ``dt``, returns ``pd.NaT``. Parameters ---------- asset : zipline.asset.Asset The asset for which to get the...
[ "def", "get_last_traded_dt", "(", "self", ",", "asset", ",", "dt", ")", ":", "rf", "=", "self", ".", "_roll_finders", "[", "asset", ".", "roll_style", "]", "sid", "=", "(", "rf", ".", "get_contract_center", "(", "asset", ".", "root_symbol", ",", "dt", ...
36.296296
19.037037
def _create_refinement_wrapper(transformation, baseattr, base, target_attrname): """ applies refinement ``transformation`` to ``baseattr`` attribute of ``base``. ``baseattr`` can be any type of callable (function, method, functor) this method handles the differences. docstrings a...
[ "def", "_create_refinement_wrapper", "(", "transformation", ",", "baseattr", ",", "base", ",", "target_attrname", ")", ":", "# first step: extract the original", "special_refinement_type", "=", "None", "instance_refinement", "=", "_is_class_instance", "(", "base", ")", "i...
38.254902
17.196078
def to_lal_ligotimegps(gps): """Convert the given GPS time to a `lal.LIGOTimeGPS` object Parameters ---------- gps : `~gwpy.time.LIGOTimeGPS`, `float`, `str` input GPS time, can be anything parsable by :meth:`~gwpy.time.to_gps` Returns ------- ligotimegps : `lal.LIGOTimeGPS` ...
[ "def", "to_lal_ligotimegps", "(", "gps", ")", ":", "gps", "=", "to_gps", "(", "gps", ")", "return", "lal", ".", "LIGOTimeGPS", "(", "gps", ".", "gpsSeconds", ",", "gps", ".", "gpsNanoSeconds", ")" ]
31.133333
21.933333
async def AddRelation(self, endpoints): ''' endpoints : typing.Sequence[str] Returns -> typing.Mapping[str, ~CharmRelation] ''' # map input types to rpc msg _params = dict() msg = dict(type='Application', request='AddRelation', ...
[ "async", "def", "AddRelation", "(", "self", ",", "endpoints", ")", ":", "# map input types to rpc msg", "_params", "=", "dict", "(", ")", "msg", "=", "dict", "(", "type", "=", "'Application'", ",", "request", "=", "'AddRelation'", ",", "version", "=", "3", ...
32.285714
9.857143
def make_release(self): """Build and distribute the package. """ directory = self.directory infoflags = self.infoflags branch = self.branch develop = self.develop scmtype = self.scm.name tempdir = abspath(tempfile.mkdtemp(prefix='mkrelease-')) try...
[ "def", "make_release", "(", "self", ")", ":", "directory", "=", "self", ".", "directory", "infoflags", "=", "self", ".", "infoflags", "branch", "=", "self", ".", "branch", "develop", "=", "self", ".", "develop", "scmtype", "=", "self", ".", "scm", ".", ...
43.767123
21.671233
def _pop(self, model): """Pop all matching tags off the model and return them.""" tags = [] # collect any exsiting tags with matching prefix for tag in model.tags: if self.is_tag(tag): tags.append(tag) # remove collected tags from model if ta...
[ "def", "_pop", "(", "self", ",", "model", ")", ":", "tags", "=", "[", "]", "# collect any exsiting tags with matching prefix", "for", "tag", "in", "model", ".", "tags", ":", "if", "self", ".", "is_tag", "(", "tag", ")", ":", "tags", ".", "append", "(", ...
26.533333
17.6
def get_api_token(self, agent_key, user_key): """ Send POST request to get an auth token. This method doesn't require auth obviously. :param agent_key: str agent key (who is acting on behalf of the user) :param user_key: str secret user key :return: requests.Response cont...
[ "def", "get_api_token", "(", "self", ",", "agent_key", ",", "user_key", ")", ":", "data", "=", "{", "\"agent_key\"", ":", "agent_key", ",", "\"user_key\"", ":", "user_key", ",", "}", "return", "self", ".", "_post", "(", "\"/software_agents/api_token\"", ",", ...
39
13.769231
def _error_code_to_str(mod, type_, code): """ This method is registered as ofp_error_code_to_str(type_, code) method into ryu.ofproto.ofproto_v1_* modules. And this method returns the error code as a string value for given 'type' and 'code' defined in ofp_error_msg structure. Example:: ...
[ "def", "_error_code_to_str", "(", "mod", ",", "type_", ",", "code", ")", ":", "(", "_", ",", "c_name", ")", "=", "_get_error_names", "(", "mod", ",", "type_", ",", "code", ")", "return", "'%s(%d)'", "%", "(", "c_name", ",", "code", ")" ]
34
16
def ComputeGMST(GPSTime): """ ComputeGMST - function to compute the Greenwich mean sidereal time from the GPS time. GPSTime - GPS time that the GW signal from the source reached the geocenter. Returns GMST - the Greenwich mean sidereal time corresponding to ...
[ "def", "ComputeGMST", "(", "GPSTime", ")", ":", "# Difference in Julian Date between GPSTime and the J2000.0 epoch", "# Subtract half a day as Julian Days start at noon", "D", "=", "np", ".", "round", "(", "(", "GPSTime", "-", "EpochJ2000_0_UTC", ")", "/", "secPerDay", ")",...
31.864865
20.918919
async def msetup(self, text_channel): """Creates the gui Args: text_channel (discord.Channel): The channel for the embed ui to run in """ if self.mready: logger.warning("Attempt to init music when already initialised") return if self.state !...
[ "async", "def", "msetup", "(", "self", ",", "text_channel", ")", ":", "if", "self", ".", "mready", ":", "logger", ".", "warning", "(", "\"Attempt to init music when already initialised\"", ")", "return", "if", "self", ".", "state", "!=", "'starting'", ":", "lo...
27.84
22.28
def _dump_stats_group(self, title, items, normal_formatter=None, verbose_formatter=None): """Dump a statistics group. In verbose mode, do so as a config file so that other processors can load the information if they want to. :param normal_formatter: the callable to apply...
[ "def", "_dump_stats_group", "(", "self", ",", "title", ",", "items", ",", "normal_formatter", "=", "None", ",", "verbose_formatter", "=", "None", ")", ":", "if", "self", ".", "verbose", ":", "self", ".", "outf", ".", "write", "(", "\"[%s]\\n\"", "%", "("...
43.961538
12.884615
def dispatch(self): """Wraps the dispatch method to add session support.""" try: webapp2.RequestHandler.dispatch(self) finally: self.session_store.save_sessions(self.response)
[ "def", "dispatch", "(", "self", ")", ":", "try", ":", "webapp2", ".", "RequestHandler", ".", "dispatch", "(", "self", ")", "finally", ":", "self", ".", "session_store", ".", "save_sessions", "(", "self", ".", "response", ")" ]
32.333333
16.166667
def sample_surface_sphere(count): """ Correctly pick random points on the surface of a unit sphere Uses this method: http://mathworld.wolfram.com/SpherePointPicking.html Parameters ---------- count: int, number of points to return Returns ---------- points: (count,3) float, li...
[ "def", "sample_surface_sphere", "(", "count", ")", ":", "u", ",", "v", "=", "np", ".", "random", ".", "random", "(", "(", "2", ",", "count", ")", ")", "theta", "=", "np", ".", "pi", "*", "2", "*", "u", "phi", "=", "np", ".", "arccos", "(", "(...
23.086957
22.478261
def send_location(self, *args, **kwargs): """See :func:`send_location`""" return send_location(*args, **self._merge_overrides(**kwargs)).run()
[ "def", "send_location", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "send_location", "(", "*", "args", ",", "*", "*", "self", ".", "_merge_overrides", "(", "*", "*", "kwargs", ")", ")", ".", "run", "(", ")" ]
52
12.333333
def heightmap_new(w: int, h: int, order: str = "C") -> np.ndarray: """Return a new numpy.ndarray formatted for use with heightmap functions. `w` and `h` are the width and height of the array. `order` is given to the new NumPy array, it can be 'C' or 'F'. You can pass a NumPy array to any heightmap fu...
[ "def", "heightmap_new", "(", "w", ":", "int", ",", "h", ":", "int", ",", "order", ":", "str", "=", "\"C\"", ")", "->", "np", ".", "ndarray", ":", "if", "order", "==", "\"C\"", ":", "return", "np", ".", "zeros", "(", "(", "h", ",", "w", ")", "...
35.958333
21.541667
def load(self, file_key): """Load the data.""" var = self.sd.select(file_key) data = xr.DataArray(from_sds(var, chunks=CHUNK_SIZE), dims=['y', 'x']).astype(np.float32) data = data.where(data != var._FillValue) try: data = data * np.float32(...
[ "def", "load", "(", "self", ",", "file_key", ")", ":", "var", "=", "self", ".", "sd", ".", "select", "(", "file_key", ")", "data", "=", "xr", ".", "DataArray", "(", "from_sds", "(", "var", ",", "chunks", "=", "CHUNK_SIZE", ")", ",", "dims", "=", ...
35.909091
15.181818
def isordv(array, n): """ Determine whether an array of n items contains the integers 0 through n-1. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/isordv_c.html :param array: Array of integers. :type array: Array of ints :param n: Number of integers in array. :type n: int ...
[ "def", "isordv", "(", "array", ",", "n", ")", ":", "array", "=", "stypes", ".", "toIntVector", "(", "array", ")", "n", "=", "ctypes", ".", "c_int", "(", "n", ")", "return", "bool", "(", "libspice", ".", "isordv_c", "(", "array", ",", "n", ")", ")...
30.052632
17.842105
def pairs(iterable): """ :return: iterator yielding overlapping pairs from iterable :Example: >>> list(pairs([1, 2, 3, 4]) [(1, 2), (2, 3), (3, 4)] """ a, b = itertools.tee(iterable) next(b, None) return zip(a, b)
[ "def", "pairs", "(", "iterable", ")", ":", "a", ",", "b", "=", "itertools", ".", "tee", "(", "iterable", ")", "next", "(", "b", ",", "None", ")", "return", "zip", "(", "a", ",", "b", ")" ]
20
18.166667
async def handle_agent_job_started(self, agent_addr, message: AgentJobStarted): """Handle an AgentJobStarted message. Send the data back to the client""" self._logger.debug("Job %s %s started on agent %s", message.job_id[0], message.job_id[1], agent_addr) await ZMQUtils.send_with_addr(self._clie...
[ "async", "def", "handle_agent_job_started", "(", "self", ",", "agent_addr", ",", "message", ":", "AgentJobStarted", ")", ":", "self", ".", "_logger", ".", "debug", "(", "\"Job %s %s started on agent %s\"", ",", "message", ".", "job_id", "[", "0", "]", ",", "me...
96
45.75
def _tseitin(ex, auxvarname, auxvars=None): """ Convert a factored expression to a literal, and a list of constraints. """ if isinstance(ex, Literal): return ex, list() else: if auxvars is None: auxvars = list() lits = list() constraints = list() ...
[ "def", "_tseitin", "(", "ex", ",", "auxvarname", ",", "auxvars", "=", "None", ")", ":", "if", "isinstance", "(", "ex", ",", "Literal", ")", ":", "return", "ex", ",", "list", "(", ")", "else", ":", "if", "auxvars", "is", "None", ":", "auxvars", "=",...
27.916667
14.75
def get_port_channel_detail_input_last_aggregator_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_port_channel_detail = ET.Element("get_port_channel_detail") config = get_port_channel_detail input = ET.SubElement(get_port_channel_detail, "...
[ "def", "get_port_channel_detail_input_last_aggregator_id", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_port_channel_detail", "=", "ET", ".", "Element", "(", "\"get_port_channel_detail\"", ")", "...
45.5
17.416667
def partial_safe_wraps(wrapped_func, *args, **kwargs): """ A version of `functools.wraps` that is safe to wrap a partial in. """ if isinstance(wrapped_func, functools.partial): return partial_safe_wraps(wrapped_func.func) else: return functools.wraps(wrapped_func)
[ "def", "partial_safe_wraps", "(", "wrapped_func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "wrapped_func", ",", "functools", ".", "partial", ")", ":", "return", "partial_safe_wraps", "(", "wrapped_func", ".", "func", ")",...
36.625
12.625
def _serve_individual_audio(self, request): """Serve encoded audio data.""" tag = request.args.get('tag') run = request.args.get('run') index = int(request.args.get('index')) sample = int(request.args.get('sample', 0)) events = self._filter_by_sample(self._multiplexer.Tensors(run, tag), sample) ...
[ "def", "_serve_individual_audio", "(", "self", ",", "request", ")", ":", "tag", "=", "request", ".", "args", ".", "get", "(", "'tag'", ")", "run", "=", "request", ".", "args", ".", "get", "(", "'run'", ")", "index", "=", "int", "(", "request", ".", ...
48.6
11.9
def _CreateOutputFileHandles(self, output_type): """Creates a new gzipped output tempfile for the output type. We write to JSON data to gzip_filehandle to get compressed data. We hold a reference to the original filehandle (gzip_filehandle_parent) so we can pass the gzip data to bigquery. Args: ...
[ "def", "_CreateOutputFileHandles", "(", "self", ",", "output_type", ")", ":", "gzip_filehandle_parent", "=", "tempfile", ".", "NamedTemporaryFile", "(", "suffix", "=", "output_type", ")", "gzip_filehandle", "=", "gzip", ".", "GzipFile", "(", "gzip_filehandle_parent", ...
41.608696
21.521739
def safe_int(string, default=None): """ Safely parse a string into an int. On error return the ``default`` value. :param string string: string value to be converted :param int default: default value to be used in case of failure :rtype: int """ value = safe_float(string, default) i...
[ "def", "safe_int", "(", "string", ",", "default", "=", "None", ")", ":", "value", "=", "safe_float", "(", "string", ",", "default", ")", "if", "value", "is", "not", "None", ":", "value", "=", "int", "(", "value", ")", "return", "value" ]
26.5
14.928571
def has_creep(self, pos: Union[Point2, Point3, Unit]) -> bool: """ Returns True if there is creep on the grid point. """ assert isinstance(pos, (Point2, Point3, Unit)) pos = pos.position.to2.rounded return self.state.creep[pos] != 0
[ "def", "has_creep", "(", "self", ",", "pos", ":", "Union", "[", "Point2", ",", "Point3", ",", "Unit", "]", ")", "->", "bool", ":", "assert", "isinstance", "(", "pos", ",", "(", "Point2", ",", "Point3", ",", "Unit", ")", ")", "pos", "=", "pos", "....
52
7.8