text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def _set_scan_parameters(self, interval=2100, window=2100, active=False): """ Set the scan interval and window in units of ms and set whether active scanning is performed """ active_num = 0 if bool(active): active_num = 1 interval_num = int(interval*1000/625...
[ "def", "_set_scan_parameters", "(", "self", ",", "interval", "=", "2100", ",", "window", "=", "2100", ",", "active", "=", "False", ")", ":", "active_num", "=", "0", "if", "bool", "(", "active", ")", ":", "active_num", "=", "1", "interval_num", "=", "in...
35.090909
24.545455
def sample(self, X, y, quantity='y', sample_at_X=None, weights=None, n_draws=100, n_bootstraps=5, objective='auto'): """Simulate from the posterior of the coefficients and smoothing params. Samples are drawn from the posterior of the coefficients and smoothing parameters given th...
[ "def", "sample", "(", "self", ",", "X", ",", "y", ",", "quantity", "=", "'y'", ",", "sample_at_X", "=", "None", ",", "weights", "=", "None", ",", "n_draws", "=", "100", ",", "n_bootstraps", "=", "5", ",", "objective", "=", "'auto'", ")", ":", "if",...
45.017241
26.87069
def reset(self): """ Clear all cell and segment activity. """ super(ApicalTiebreakSequenceMemory, self).reset() self.prevApicalInput = np.empty(0, dtype="uint32") self.prevApicalGrowthCandidates = np.empty(0, dtype="uint32") self.prevPredictedCells = np.empty(0, dtype="uint32")
[ "def", "reset", "(", "self", ")", ":", "super", "(", "ApicalTiebreakSequenceMemory", ",", "self", ")", ".", "reset", "(", ")", "self", ".", "prevApicalInput", "=", "np", ".", "empty", "(", "0", ",", "dtype", "=", "\"uint32\"", ")", "self", ".", "prevAp...
33.222222
14.777778
def nacm_enable_external_groups(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") nacm = ET.SubElement(config, "nacm", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-acm") enable_external_groups = ET.SubElement(nacm, "enable-external-groups") enab...
[ "def", "nacm_enable_external_groups", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "nacm", "=", "ET", ".", "SubElement", "(", "config", ",", "\"nacm\"", ",", "xmlns", "=", "\"urn:ietf:params:x...
46.4
20.7
def multiply(self, other): """Return the operator self + other. Args: other (complex): a complex number. Returns: Operator: the operator other * self. Raises: QiskitError: if other is not a valid complex number. """ if not isinstance...
[ "def", "multiply", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "Number", ")", ":", "raise", "QiskitError", "(", "\"other is not a number\"", ")", "return", "Operator", "(", "other", "*", "self", ".", "data", ",", "s...
30.125
17.9375
def get_template_vars(self, slides): """ Computes template vars from slides html source code. """ try: head_title = slides[0]['title'] except (IndexError, TypeError): head_title = "Untitled Presentation" for slide_index, slide_vars in enumerate(slides): ...
[ "def", "get_template_vars", "(", "self", ",", "slides", ")", ":", "try", ":", "head_title", "=", "slides", "[", "0", "]", "[", "'title'", "]", "except", "(", "IndexError", ",", "TypeError", ")", ":", "head_title", "=", "\"Untitled Presentation\"", "for", "...
45.6
19.4
def __make_points_for_label(self, ts, data, label, prefix, gun_stats): """x Make a set of points for `this` label overall_quantiles, overall_meta, net_codes, proto_codes, histograms """ label_points = list() label_points.extend( ( # overall q...
[ "def", "__make_points_for_label", "(", "self", ",", "ts", ",", "data", ",", "label", ",", "prefix", ",", "gun_stats", ")", ":", "label_points", "=", "list", "(", ")", "label_points", ".", "extend", "(", "(", "# overall quantiles for label", "self", ".", "__m...
35.075472
13.773585
def icmp(a, b): "Like cmp(), but for any iterator." for xa in a: try: xb = next(b) d = cmp(xa, xb) if d: return d except StopIteration: return 1 try: next(b) return -1 except StopIteration: return 0
[ "def", "icmp", "(", "a", ",", "b", ")", ":", "for", "xa", "in", "a", ":", "try", ":", "xb", "=", "next", "(", "b", ")", "d", "=", "cmp", "(", "xa", ",", "xb", ")", "if", "d", ":", "return", "d", "except", "StopIteration", ":", "return", "1"...
20.642857
19.357143
def format_time(x): """Formats date values This function formats :class:`datetime.datetime` and :class:`datetime.timedelta` objects (and the corresponding numpy objects) using the :func:`xarray.core.formatting.format_timestamp` and the :func:`xarray.core.formatting.format_timedelta` functions. ...
[ "def", "format_time", "(", "x", ")", ":", "if", "isinstance", "(", "x", ",", "(", "datetime64", ",", "datetime", ")", ")", ":", "return", "format_timestamp", "(", "x", ")", "elif", "isinstance", "(", "x", ",", "(", "timedelta64", ",", "timedelta", ")",...
32.041667
21.041667
def apply(self, func, axis='major', **kwargs): """ Apply function along axis (or axes) of the Panel. Parameters ---------- func : function Function to apply to each combination of 'other' axes e.g. if axis = 'items', the combination of major_axis/minor_ax...
[ "def", "apply", "(", "self", ",", "func", ",", "axis", "=", "'major'", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", "and", "not", "isinstance", "(", "func", ",", "np", ".", "ufunc", ")", ":", "f", "=", "lambda", "x", ":", "func", "(", "x"...
30.59375
23.96875
def toLily(self): ''' Method which converts the object instance, its attributes and children to a string of lilypond code :return: str of lilypond code ''' lilystring = "" if self.item is not None: if not isinstance(self.GetChild(0), NoteNode): ...
[ "def", "toLily", "(", "self", ")", ":", "lilystring", "=", "\"\"", "if", "self", ".", "item", "is", "not", "None", ":", "if", "not", "isinstance", "(", "self", ".", "GetChild", "(", "0", ")", ",", "NoteNode", ")", ":", "if", "hasattr", "(", "self",...
42.848485
18.484848
def encrypt(base_field, key=None, ttl=None): """ A decorator for creating encrypted model fields. :type base_field: models.Field[T] :param bytes key: This is an optional argument. Allows for specifying an instance specific encryption key. :param int ttl: This is an optional argument. ...
[ "def", "encrypt", "(", "base_field", ",", "key", "=", "None", ",", "ttl", "=", "None", ")", ":", "if", "not", "isinstance", "(", "base_field", ",", "models", ".", "Field", ")", ":", "assert", "key", "is", "None", "assert", "ttl", "is", "None", "retur...
38.304348
17.782609
def upload_file(filename, session): """ Uploads a file """ print('Uploading file %s' % filename) outfilesource = os.path.join(os.getcwd(), filename) outfiletarget = 'sftp://' + ADDRESS + WORKING_DIR out = saga.filesystem.File(outfilesource, session=session, flags=OVERWRITE) out.copy(outfiletarge...
[ "def", "upload_file", "(", "filename", ",", "session", ")", ":", "print", "(", "'Uploading file %s'", "%", "filename", ")", "outfilesource", "=", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "filename", ")", "outfiletarget", "...
49
15.25
def _remove_observation(self, x_to_remove, y_to_remove): """Remove observation from window, updating means/variance efficiently.""" self._remove_observation_from_variances(x_to_remove, y_to_remove) self._remove_observation_from_means(x_to_remove, y_to_remove) self.window_size -= 1
[ "def", "_remove_observation", "(", "self", ",", "x_to_remove", ",", "y_to_remove", ")", ":", "self", ".", "_remove_observation_from_variances", "(", "x_to_remove", ",", "y_to_remove", ")", "self", ".", "_remove_observation_from_means", "(", "x_to_remove", ",", "y_to_r...
61.8
17.8
def relativeAreaSTE(self): ''' return STE area - relative to image area ''' s = self.noSTE.shape return np.sum(self.mask_STE) / (s[0] * s[1])
[ "def", "relativeAreaSTE", "(", "self", ")", ":", "s", "=", "self", ".", "noSTE", ".", "shape", "return", "np", ".", "sum", "(", "self", ".", "mask_STE", ")", "/", "(", "s", "[", "0", "]", "*", "s", "[", "1", "]", ")" ]
30.166667
16.833333
def _set_fill_word(self, v, load=False): """ Setter method for fill_word, mapped from YANG variable /interface/fc_port/fill_word (fc-fillword-cfg-type) If this variable is read-only (config: false) in the source YANG file, then _set_fill_word is considered as a private method. Backends looking to po...
[ "def", "_set_fill_word", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base...
103
49.136364
def get_attachment_model(): """ Returns the Attachment model that is active in this project. """ try: from .models import AbstractAttachment klass = apps.get_model(config["attachment_model"]) if not issubclass(klass, AbstractAttachment): raise ImproperlyConfigured( ...
[ "def", "get_attachment_model", "(", ")", ":", "try", ":", "from", ".", "models", "import", "AbstractAttachment", "klass", "=", "apps", ".", "get_model", "(", "config", "[", "\"attachment_model\"", "]", ")", "if", "not", "issubclass", "(", "klass", ",", "Abst...
43.7
27.4
def _Open(self, path_spec, mode='rb'): """Opens the file system defined by path specification. Args: path_spec (PathSpec): a path specification. mode (Optional[str]): file access mode. The default is 'rb' which represents read-only binary. Raises: AccessError: if the access to ...
[ "def", "_Open", "(", "self", ",", "path_spec", ",", "mode", "=", "'rb'", ")", ":", "if", "not", "path_spec", ".", "HasParent", "(", ")", ":", "raise", "errors", ".", "PathSpecError", "(", "'Unsupported path specification without parent.'", ")", "resolver", "."...
36.846154
20.153846
def main (args): """Usage: create_sedml2 output-filename """ if (len(args) != 2): print(main.__doc__) sys.exit(1); # create the document doc = libsedml.SedDocument(); doc.setLevel(1); doc.setVersion(3); # create a data description ddesc = doc.createDataDescription() ddesc.setId('data1')...
[ "def", "main", "(", "args", ")", ":", "if", "(", "len", "(", "args", ")", "!=", "2", ")", ":", "print", "(", "main", ".", "__doc__", ")", "sys", ".", "exit", "(", "1", ")", "# create the document", "doc", "=", "libsedml", ".", "SedDocument", "(", ...
24.0625
17.270833
def admin(self): """points to the adminstrative side of ArcGIS Server""" if self._securityHandler is None: raise Exception("Cannot connect to adminstrative server without authentication") from ..manageags import AGSAdministration return AGSAdministration(url=self._adminUrl, ...
[ "def", "admin", "(", "self", ")", ":", "if", "self", ".", "_securityHandler", "is", "None", ":", "raise", "Exception", "(", "\"Cannot connect to adminstrative server without authentication\"", ")", "from", ".", ".", "manageags", "import", "AGSAdministration", "return"...
55.4
17.9
def delete_blacklist_entry(self, blacklist_entry_id): """Delete an existing blacklist entry. Keyword arguments: blacklist_entry_id -- The unique identifier of the blacklist entry to delete. """ delete_blacklist_endpoint = Template("${rest_root}/blacklist/${public_key}/${...
[ "def", "delete_blacklist_entry", "(", "self", ",", "blacklist_entry_id", ")", ":", "delete_blacklist_endpoint", "=", "Template", "(", "\"${rest_root}/blacklist/${public_key}/${blacklist_entry_id}/delete\"", ")", "url", "=", "delete_blacklist_endpoint", ".", "substitute", "(", ...
53.1
31.8
def find_vpid(self, url, res=None): """ Find the Video Packet ID in the HTML for the provided URL :param url: URL to download, if res is not provided. :param res: Provide a cached version of the HTTP response to search :type url: string :type res: requests.Response ...
[ "def", "find_vpid", "(", "self", ",", "url", ",", "res", "=", "None", ")", ":", "log", ".", "debug", "(", "\"Looking for vpid on {0}\"", ",", "url", ")", "# Use pre-fetched page if available", "res", "=", "res", "or", "self", ".", "session", ".", "http", "...
39.647059
15.176471
def create_raw(self, create_missing=None): """Create an entity. Possibly call :meth:`create_missing`. Then make an HTTP POST call to ``self.path('base')``. The request payload consists of whatever is returned by :meth:`create_payload`. Return the response. :param create_missing...
[ "def", "create_raw", "(", "self", ",", "create_missing", "=", "None", ")", ":", "if", "create_missing", "is", "None", ":", "create_missing", "=", "CREATE_MISSING", "if", "create_missing", "is", "True", ":", "self", ".", "create_missing", "(", ")", "return", ...
39.181818
19.136364
def parse_xml_string(self, xml, id_generator=None): """Parse a string of XML, returning a usage id.""" if id_generator is not None: warnings.warn( "Passing an id_generator directly is deprecated " "in favor of constructing the Runtime with the id_generator", ...
[ "def", "parse_xml_string", "(", "self", ",", "xml", ",", "id_generator", "=", "None", ")", ":", "if", "id_generator", "is", "not", "None", ":", "warnings", ".", "warn", "(", "\"Passing an id_generator directly is deprecated \"", "\"in favor of constructing the Runtime w...
39
16.5
def casefold_parts(self, parts): """Return the lower-case version of parts for a Windows filesystem.""" if self.filesystem.is_windows_fs: return [p.lower() for p in parts] return parts
[ "def", "casefold_parts", "(", "self", ",", "parts", ")", ":", "if", "self", ".", "filesystem", ".", "is_windows_fs", ":", "return", "[", "p", ".", "lower", "(", ")", "for", "p", "in", "parts", "]", "return", "parts" ]
43.2
6.8
def resend_presence(self): """ Re-send the currently configured presence. :return: Stanza token of the presence stanza or :data:`None` if the stream is not established. :rtype: :class:`~.stream.StanzaToken` .. note:: :meth:`set_presence` automatical...
[ "def", "resend_presence", "(", "self", ")", ":", "if", "self", ".", "client", ".", "established", ":", "return", "self", ".", "client", ".", "enqueue", "(", "self", ".", "make_stanza", "(", ")", ")" ]
30.5
19.375
def get_extra_imts(self, imts): """ Returns the extra IMTs in the risk functions, i.e. the ones not in the `imts` set (the set of IMTs for which there is hazard). """ extra_imts = set() for taxonomy in self.taxonomies: for (lt, kind), rf in self[taxonomy].risk...
[ "def", "get_extra_imts", "(", "self", ",", "imts", ")", ":", "extra_imts", "=", "set", "(", ")", "for", "taxonomy", "in", "self", ".", "taxonomies", ":", "for", "(", "lt", ",", "kind", ")", ",", "rf", "in", "self", "[", "taxonomy", "]", ".", "risk_...
39.727273
12.272727
def yview(self, *args): """Update inplace widgets position when doing vertical scroll""" self.after_idle(self.__updateWnds) ttk.Treeview.yview(self, *args)
[ "def", "yview", "(", "self", ",", "*", "args", ")", ":", "self", ".", "after_idle", "(", "self", ".", "__updateWnds", ")", "ttk", ".", "Treeview", ".", "yview", "(", "self", ",", "*", "args", ")" ]
44
5
def concat(self, tailvec): '''Returns the result of concatenating tailvec to the implicit parameter''' newvec = ImmutableVector() vallist = [(i + self._length, tailvec[i]) \ for i in range(0, tailvec._length)] newvec.tree = self.tree.multi_assoc(vallist) n...
[ "def", "concat", "(", "self", ",", "tailvec", ")", ":", "newvec", "=", "ImmutableVector", "(", ")", "vallist", "=", "[", "(", "i", "+", "self", ".", "_length", ",", "tailvec", "[", "i", "]", ")", "for", "i", "in", "range", "(", "0", ",", "tailvec...
42.222222
15.333333
def _enumerator(opener, entry_cls, format_code=None, filter_code=None): """Return an archive enumerator from a user-defined source, using a user- defined entry type. """ archive_res = _archive_read_new() try: r = _set_read_context(archive_res, format_code, filter_code) opener(archi...
[ "def", "_enumerator", "(", "opener", ",", "entry_cls", ",", "format_code", "=", "None", ",", "filter_code", "=", "None", ")", ":", "archive_res", "=", "_archive_read_new", "(", ")", "try", ":", "r", "=", "_set_read_context", "(", "archive_res", ",", "format_...
31.541667
19.958333
def load_secret(self, secret): """ Ask YubiHSM to load a pre-existing YubiKey secret. The data is stored internally in the YubiHSM in temporary memory - this operation would typically be followed by one or more L{generate_aead} commands to actually retreive the generated secret ...
[ "def", "load_secret", "(", "self", ",", "secret", ")", ":", "if", "isinstance", "(", "secret", ",", "pyhsm", ".", "aead_cmd", ".", "YHSM_YubiKeySecret", ")", ":", "secret", "=", "secret", ".", "pack", "(", ")", "return", "pyhsm", ".", "buffer_cmd", ".", ...
41.421053
24.789474
def _replay_index(replay_dir): """Output information for a directory of replays.""" run_config = run_configs.get() replay_dir = run_config.abs_replay_path(replay_dir) print("Checking: ", replay_dir) with run_config.start(want_rgb=False) as controller: print("-" * 60) print(",".join(( "filenam...
[ "def", "_replay_index", "(", "replay_dir", ")", ":", "run_config", "=", "run_configs", ".", "get", "(", ")", "replay_dir", "=", "run_config", ".", "abs_replay_path", "(", "replay_dir", ")", "print", "(", "\"Checking: \"", ",", "replay_dir", ")", "with", "run_c...
31.241379
17.931034
def has_membership(self, user, role): """ checks if user is member of a group""" targetRecord = AuthMembership.objects(creator=self.client, user=user).first() if targetRecord: return role in [i.role for i in targetRecord.groups] return False
[ "def", "has_membership", "(", "self", ",", "user", ",", "role", ")", ":", "targetRecord", "=", "AuthMembership", ".", "objects", "(", "creator", "=", "self", ".", "client", ",", "user", "=", "user", ")", ".", "first", "(", ")", "if", "targetRecord", ":...
46.666667
18
def parse_tstv_by_qual(self): """ Create the HTML for the TsTv by quality linegraph plot. """ self.vcftools_tstv_by_qual = dict() for f in self.find_log_files('vcftools/tstv_by_qual', filehandles=True): d = {} for line in f['f'].readlines()[1:]: # don't add the header li...
[ "def", "parse_tstv_by_qual", "(", "self", ")", ":", "self", ".", "vcftools_tstv_by_qual", "=", "dict", "(", ")", "for", "f", "in", "self", ".", "find_log_files", "(", "'vcftools/tstv_by_qual'", ",", "filehandles", "=", "True", ")", ":", "d", "=", "{", "}",...
45.229167
27.458333
def rolling_performances(self, timestamp='one_month'): ''' Filters self.perfs ''' # TODO Study the impact of month choice # TODO Check timestamp in an enumeration # TODO Implement other benchmarks for perf computation # (zipline issue, maybe expected) if self.metrics: ...
[ "def", "rolling_performances", "(", "self", ",", "timestamp", "=", "'one_month'", ")", ":", "# TODO Study the impact of month choice", "# TODO Check timestamp in an enumeration", "# TODO Implement other benchmarks for perf computation", "# (zipline issue, maybe expected)", "if", "self"...
39.608696
16.652174
def _dump_multipolygon(obj, big_endian, meta): """ Dump a GeoJSON-like `dict` to a multipolygon WKB string. Input parameters and output are similar to :funct:`_dump_point`. """ coords = obj['coordinates'] vertex = coords[0][0][0] num_dims = len(vertex) wkb_string, byte_fmt, byte_order ...
[ "def", "_dump_multipolygon", "(", "obj", ",", "big_endian", ",", "meta", ")", ":", "coords", "=", "obj", "[", "'coordinates'", "]", "vertex", "=", "coords", "[", "0", "]", "[", "0", "]", "[", "0", "]", "num_dims", "=", "len", "(", "vertex", ")", "w...
32.685714
19.771429
def monthly_cooling_design_days_020(self): """A list of 12 objects representing monthly 2.0% cooling design days.""" if self.monthly_found is False or self._monthly_db_20 == [] \ or self._monthly_wb_20 == []: return [] else: db_conds = [DryBulbCond...
[ "def", "monthly_cooling_design_days_020", "(", "self", ")", ":", "if", "self", ".", "monthly_found", "is", "False", "or", "self", ".", "_monthly_db_20", "==", "[", "]", "or", "self", ".", "_monthly_wb_20", "==", "[", "]", ":", "return", "[", "]", "else", ...
53
16.235294
def filter_nremoved(self, filt=True, quiet=False): """ Report how many data are removed by the active filters. """ rminfo = {} for n in self.subsets['All_Samples']: s = self.data[n] rminfo[n] = s.filt_nremoved(filt) if not quiet: maxL =...
[ "def", "filter_nremoved", "(", "self", ",", "filt", "=", "True", ",", "quiet", "=", "False", ")", ":", "rminfo", "=", "{", "}", "for", "n", "in", "self", ".", "subsets", "[", "'All_Samples'", "]", ":", "s", "=", "self", ".", "data", "[", "n", "]"...
44.190476
17.52381
def dec(data, **kwargs): ''' Alias to `{box_type}_decrypt` box_type: secretbox, sealedbox(default) ''' kwargs['opts'] = __opts__ return salt.utils.nacl.dec(data, **kwargs)
[ "def", "dec", "(", "data", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'opts'", "]", "=", "__opts__", "return", "salt", ".", "utils", ".", "nacl", ".", "dec", "(", "data", ",", "*", "*", "kwargs", ")" ]
23.625
18.625
def decode_timeseries(self, resp, tsobj, convert_timestamp=False): """ Fills an TsObject with the appropriate data and metadata from a TsGetResp / TsQueryResp. :param resp: the protobuf message from which to process data :type resp: riak.pb.riak_ts_pb2....
[ "def", "decode_timeseries", "(", "self", ",", "resp", ",", "tsobj", ",", "convert_timestamp", "=", "False", ")", ":", "if", "resp", ".", "columns", "is", "not", "None", ":", "col_names", "=", "[", "]", "col_types", "=", "[", "]", "for", "col", "in", ...
38.896552
13.586207
def DbImportEvent(self, argin): """ Get event channel info from database :param argin: name of event channel or factory :type: tango.DevString :return: export information e.g. IOR :rtype: tango.DevVarLongStringArray """ self._log.debug("In DbImportEvent()") argin...
[ "def", "DbImportEvent", "(", "self", ",", "argin", ")", ":", "self", ".", "_log", ".", "debug", "(", "\"In DbImportEvent()\"", ")", "argin", "=", "replace_wildcard", "(", "argin", ".", "lower", "(", ")", ")", "return", "self", ".", "db", ".", "import_eve...
38.8
9.1
def _renderResource(resource, request): """ Render a given resource. See `IResource.render <twisted:twisted.web.resource.IResource.render>`. """ meth = getattr(resource, 'render_' + nativeString(request.method), None) if meth is None: try: allowedMethods = resource.allowedMe...
[ "def", "_renderResource", "(", "resource", ",", "request", ")", ":", "meth", "=", "getattr", "(", "resource", ",", "'render_'", "+", "nativeString", "(", "request", ".", "method", ")", ",", "None", ")", "if", "meth", "is", "None", ":", "try", ":", "all...
34.142857
17
def seqToKV(seq, strict=False): """Represent a sequence of pairs of strings as newline-terminated key:value pairs. The pairs are generated in the order given. @param seq: The pairs @type seq: [(str, (unicode|str))] @return: A string representation of the sequence @rtype: str """ def er...
[ "def", "seqToKV", "(", "seq", ",", "strict", "=", "False", ")", ":", "def", "err", "(", "msg", ")", ":", "formatted", "=", "'seqToKV warning: %s: %r'", "%", "(", "msg", ",", "seq", ")", "if", "strict", ":", "raise", "KVFormError", "(", "formatted", ")"...
30.173077
20.365385
def autocomplete(self): """ Output completion suggestions for BASH. The output of this function is passed to BASH's `COMREPLY` variable and treated as completion suggestions. `COMREPLY` expects a space separated string as the result. The `COMP_WORDS` and `COMP_CWORD` BA...
[ "def", "autocomplete", "(", "self", ")", ":", "# Don't complete if user hasn't sourced bash_completion file.", "if", "'DJANGO_AUTO_COMPLETE'", "not", "in", "os", ".", "environ", ":", "return", "cwords", "=", "os", ".", "environ", "[", "'COMP_WORDS'", "]", ".", "spli...
46.278481
23.392405
async def home_z(self, mount: top_types.Mount = None): """ Home the two z-axes """ if not mount: axes = [Axis.Z, Axis.A] else: axes = [Axis.by_mount(mount)] await self.home(axes)
[ "async", "def", "home_z", "(", "self", ",", "mount", ":", "top_types", ".", "Mount", "=", "None", ")", ":", "if", "not", "mount", ":", "axes", "=", "[", "Axis", ".", "Z", ",", "Axis", ".", "A", "]", "else", ":", "axes", "=", "[", "Axis", ".", ...
32.571429
11
def snapshot(opts): """snapshot a seqrepo data directory by hardlinking sequence files, copying sqlite databases, and remove write permissions from directories """ seqrepo_dir = os.path.join(opts.root_directory, opts.instance_name) dst_dir = opts.destination_name if not dst_dir.startswith("/")...
[ "def", "snapshot", "(", "opts", ")", ":", "seqrepo_dir", "=", "os", ".", "path", ".", "join", "(", "opts", ".", "root_directory", ",", "opts", ".", "instance_name", ")", "dst_dir", "=", "opts", ".", "destination_name", "if", "not", "dst_dir", ".", "start...
34.265625
21.390625
def run_query(ont, aset, args): """ Basic querying by positive/negative class lists """ subjects = aset.query(args.query, args.negative) for s in subjects: print("{} {}".format(s, str(aset.label(s)))) if args.plot: import plotly.plotly as py import plotly.graph_objs as g...
[ "def", "run_query", "(", "ont", ",", "aset", ",", "args", ")", ":", "subjects", "=", "aset", ".", "query", "(", "args", ".", "query", ",", "args", ".", "negative", ")", "for", "s", "in", "subjects", ":", "print", "(", "\"{} {}\"", ".", "format", "(...
36.045455
13.045455
def _create_dictionary_of_ned_d( self): """create a list of dictionaries containing all the rows in the ned_d catalogue **Return:** - ``dictList`` - a list of dictionaries containing all the rows in the ned_d catalogue .. todo :: - update key arguments valu...
[ "def", "_create_dictionary_of_ned_d", "(", "self", ")", ":", "self", ".", "log", ".", "debug", "(", "'starting the ``_create_dictionary_of_ned_d`` method'", ")", "count", "=", "0", "with", "open", "(", "self", ".", "pathToDataFile", ",", "'rb'", ")", "as", "csvF...
42.428571
16.306122
def signed_session(self, session=None): # type: (Optional[requests.Session]) -> requests.Session """Create requests session with any required auth headers applied. If a session object is provided, configure it directly. Otherwise, create a new session and return it. :param sess...
[ "def", "signed_session", "(", "self", ",", "session", "=", "None", ")", ":", "# type: (Optional[requests.Session]) -> requests.Session", "session", "=", "session", "or", "requests", ".", "Session", "(", ")", "# Don't call super on purpose, let's \"auth\" manage the headers.",...
45.642857
20.714286
def call(self, args, devnull=False): """Call other processes. args - list of command args devnull - whether to pipe stdout to /dev/null (or equivalent) """ if self.debug: click.echo(subprocess.list2cmdline(args)) click.confirm('Continue?', default=True, ab...
[ "def", "call", "(", "self", ",", "args", ",", "devnull", "=", "False", ")", ":", "if", "self", ".", "debug", ":", "click", ".", "echo", "(", "subprocess", ".", "list2cmdline", "(", "args", ")", ")", "click", ".", "confirm", "(", "'Continue?'", ",", ...
37.5
13.111111
def get_tripIs_within_range_by_dsut(self, start_time_ut, end_time_ut): """ Obtain a list of trip_Is that take place during a time interval. The trip needs to be only partially overlapping with the given time interval...
[ "def", "get_tripIs_within_range_by_dsut", "(", "self", ",", "start_time_ut", ",", "end_time_ut", ")", ":", "cur", "=", "self", ".", "conn", ".", "cursor", "(", ")", "assert", "start_time_ut", "<=", "end_time_ut", "dst_ut", ",", "st_ds", ",", "et_ds", "=", "s...
38.916667
14.25
def start_session(self): """Start the underlying APIs sessions Calling this is not required, it will be called automatically if a method that needs a session is called @return bool """ self._android_api.start_session() self._manga_api.cr_start_session() ...
[ "def", "start_session", "(", "self", ")", ":", "self", ".", "_android_api", ".", "start_session", "(", ")", "self", ".", "_manga_api", ".", "cr_start_session", "(", ")", "return", "self", ".", "session_started" ]
30.636364
14.818182
def _handle_special_yaml_cases(v): """Handle values that pass integer, boolean, list or dictionary values. """ if "::" in v: out = {} for part in v.split("::"): k_part, v_part = part.split(":") out[k_part] = v_part.split(";") v = out elif ";" in v: ...
[ "def", "_handle_special_yaml_cases", "(", "v", ")", ":", "if", "\"::\"", "in", "v", ":", "out", "=", "{", "}", "for", "part", "in", "v", ".", "split", "(", "\"::\"", ")", ":", "k_part", ",", "v_part", "=", "part", ".", "split", "(", "\":\"", ")", ...
28.521739
14.26087
def plot_returns(perf_attrib_data, cost=None, ax=None): """ Plot total, specific, and common returns. Parameters ---------- perf_attrib_data : pd.DataFrame df with factors, common returns, and specific returns as columns, and datetimes as index. Assumes the `total_returns` column is...
[ "def", "plot_returns", "(", "perf_attrib_data", ",", "cost", "=", "None", ",", "ax", "=", "None", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "returns", "=", "perf_attrib_data", "[", "'total_returns'", "]", "total_r...
30.213115
22.508197
def id(self): """获取用户id,就是网址最后那一部分. :return: 用户id :rtype: str """ return re.match(r'^.*/([^/]+)/$', self.url).group(1) \ if self.url is not None else ''
[ "def", "id", "(", "self", ")", ":", "return", "re", ".", "match", "(", "r'^.*/([^/]+)/$'", ",", "self", ".", "url", ")", ".", "group", "(", "1", ")", "if", "self", ".", "url", "is", "not", "None", "else", "''" ]
24.75
16.5
def flat_data(self): """ Pass all the data from modified_data to original_data """ def flat_field(value): """ Flat field data """ try: value.flat_data() return value except AttributeError: ...
[ "def", "flat_data", "(", "self", ")", ":", "def", "flat_field", "(", "value", ")", ":", "\"\"\"\n Flat field data\n \"\"\"", "try", ":", "value", ".", "flat_data", "(", ")", "return", "value", "except", "AttributeError", ":", "return", "value...
29.454545
15.272727
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_3): """ Read the data encoding the CapabilityInformation structure and decode it into its constituent parts. Args: input_buffer (stream): A data stream containing encoded object data, supporti...
[ "def", "read", "(", "self", ",", "input_buffer", ",", "kmip_version", "=", "enums", ".", "KMIPVersion", ".", "KMIP_1_3", ")", ":", "if", "kmip_version", "<", "enums", ".", "KMIPVersion", ".", "KMIP_1_3", ":", "raise", "exceptions", ".", "VersionNotSupported", ...
39.550847
20.228814
def histogram2d(self, counts, x_edges, y_edges, type='bw', style=None, bitmap=False, colormap=None): """Plot a two-dimensional histogram. The user needs to supply the histogram. This method only plots the results. You can use NumPy's histogram2d function. :param c...
[ "def", "histogram2d", "(", "self", ",", "counts", ",", "x_edges", ",", "y_edges", ",", "type", "=", "'bw'", ",", "style", "=", "None", ",", "bitmap", "=", "False", ",", "colormap", "=", "None", ")", ":", "if", "counts", ".", "shape", "!=", "(", "le...
47.530435
20.2
def bss_eval_images(reference_sources, estimated_sources, compute_permutation=True): """ BSS Eval v3 bss_eval_images Wrapper to ``bss_eval`` with the right parameters. """ return bss_eval( reference_sources, estimated_sources, window=np.inf, hop=np.inf, ...
[ "def", "bss_eval_images", "(", "reference_sources", ",", "estimated_sources", ",", "compute_permutation", "=", "True", ")", ":", "return", "bss_eval", "(", "reference_sources", ",", "estimated_sources", ",", "window", "=", "np", ".", "inf", ",", "hop", "=", "np"...
31.071429
13.785714
def get_data_iters_and_vocabs(args: argparse.Namespace, model_folder: Optional[str]) -> Tuple['data_io.BaseParallelSampleIter', List[vocab.Vocab], vocab.Vocab, model.ModelConfig]: """ Loads the data iterators and v...
[ "def", "get_data_iters_and_vocabs", "(", "args", ":", "argparse", ".", "Namespace", ",", "model_folder", ":", "Optional", "[", "str", "]", ")", "->", "Tuple", "[", "'data_io.BaseParallelSampleIter'", ",", "List", "[", "vocab", ".", "Vocab", "]", ",", "vocab", ...
42.769231
24.512821
def write(self, proto): """ Writes serialized data to proto object :param proto: (DynamicStructBuilder) Proto object """ proto.filterDim = self.filterDim proto.outputDim = self.outputDim proto.batchSize = self.batchSize lossHistoryProto = proto.init("losses", len(self.losses)) i = ...
[ "def", "write", "(", "self", ",", "proto", ")", ":", "proto", ".", "filterDim", "=", "self", ".", "filterDim", "proto", ".", "outputDim", "=", "self", ".", "outputDim", "proto", ".", "batchSize", "=", "self", ".", "batchSize", "lossHistoryProto", "=", "p...
29.4
16.4
def get(self, tag, default=None): """Get a metadata value. Each metadata value is referenced by a ``tag`` -- a short string such as ``'xlen'`` or ``'audit'``. In the sidecar file these tag names are prepended with ``'Xmp.pyctools.'``, which corresponds to a custom namespace in t...
[ "def", "get", "(", "self", ",", "tag", ",", "default", "=", "None", ")", ":", "full_tag", "=", "'Xmp.pyctools.'", "+", "tag", "if", "full_tag", "in", "self", ".", "data", ":", "return", "self", ".", "data", "[", "full_tag", "]", "return", "default" ]
31.526316
19.368421
def delete(self, id): """Deletes a grant. Args: id (str): The id of the custom domain to delete See: https://auth0.com/docs/api/management/v2#!/Custom_Domains/delete_custom_domains_by_id """ url = self._url('%s' % (id)) return self.client.delete(url)
[ "def", "delete", "(", "self", ",", "id", ")", ":", "url", "=", "self", ".", "_url", "(", "'%s'", "%", "(", "id", ")", ")", "return", "self", ".", "client", ".", "delete", "(", "url", ")" ]
27.454545
22.545455
def invoke(self, script_hash, params, **kwargs): """ Invokes a contract with given parameters and returns the result. It should be noted that the name of the function invoked in the contract should be part of paramaters. :param script_hash: contract script hash :param params: l...
[ "def", "invoke", "(", "self", ",", "script_hash", ",", "params", ",", "*", "*", "kwargs", ")", ":", "contract_params", "=", "encode_invocation_params", "(", "params", ")", "raw_result", "=", "self", ".", "_call", "(", "JSONRPCMethods", ".", "INVOKE", ".", ...
40.388889
20.777778
def keywords2marc(self, key, values): """Populate the ``695`` MARC field. Also populates the ``084`` and ``6531`` MARC fields through side effects. """ result_695 = self.get('695', []) result_084 = self.get('084', []) result_6531 = self.get('6531', []) for value in values: schema =...
[ "def", "keywords2marc", "(", "self", ",", "key", ",", "values", ")", ":", "result_695", "=", "self", ".", "get", "(", "'695'", ",", "[", "]", ")", "result_084", "=", "self", ".", "get", "(", "'084'", ",", "[", "]", ")", "result_6531", "=", "self", ...
27.276596
13.87234
def can_mark_block_complete_on_view(self, block): """ Returns True if the xblock can be marked complete on view. This is true of any non-customized, non-scorable, completable block. """ return ( XBlockCompletionMode.get_mode(block) == XBlockCompletionMode.COMPLETABLE ...
[ "def", "can_mark_block_complete_on_view", "(", "self", ",", "block", ")", ":", "return", "(", "XBlockCompletionMode", ".", "get_mode", "(", "block", ")", "==", "XBlockCompletionMode", ".", "COMPLETABLE", "and", "not", "getattr", "(", "block", ",", "'has_custom_com...
44.2
21
def set(self): """Set the color as current OpenGL color """ glColor4f(self.r, self.g, self.b, self.a)
[ "def", "set", "(", "self", ")", ":", "glColor4f", "(", "self", ".", "r", ",", "self", ".", "g", ",", "self", ".", "b", ",", "self", ".", "a", ")" ]
30.5
8.75
def getDistinctPairs(self): """ Return a set consisting of unique feature/location pairs across all objects """ distinctPairs = set() for pairs in self.objects.itervalues(): distinctPairs = distinctPairs.union(set(pairs)) return distinctPairs
[ "def", "getDistinctPairs", "(", "self", ")", ":", "distinctPairs", "=", "set", "(", ")", "for", "pairs", "in", "self", ".", "objects", ".", "itervalues", "(", ")", ":", "distinctPairs", "=", "distinctPairs", ".", "union", "(", "set", "(", "pairs", ")", ...
29.777778
13.333333
def macro_body(self, node, frame, children=None): """Dump the function def of a macro or call block.""" frame = self.function_scoping(node, frame, children) # macros are delayed, they never require output checks frame.require_output_check = False args = frame.arguments # ...
[ "def", "macro_body", "(", "self", ",", "node", ",", "frame", ",", "children", "=", "None", ")", ":", "frame", "=", "self", ".", "function_scoping", "(", "node", ",", "frame", ",", "children", ")", "# macros are delayed, they never require output checks", "frame"...
48.130435
16.521739
def SlotSentinel(*args): """Provides exception handling for all slots""" # (NOTE) davidlatwe # Thanks to this answer # https://stackoverflow.com/questions/18740884 if len(args) == 0 or isinstance(args[0], types.FunctionType): args = [] @QtCore.pyqtSlot(*args) def slotdecorator(fun...
[ "def", "SlotSentinel", "(", "*", "args", ")", ":", "# (NOTE) davidlatwe", "# Thanks to this answer", "# https://stackoverflow.com/questions/18740884", "if", "len", "(", "args", ")", "==", "0", "or", "isinstance", "(", "args", "[", "0", "]", ",", "types", ".", "F...
24.952381
18.904762
def filter_rows_as_dict(fname, filter_, **kw): """Rewrite a dsv file, filtering the rows. :param fname: Path to dsv file :param filter_: callable which accepts a `dict` with a row's data as single argument\ returning a `Boolean` indicating whether to keep the row (`True`) or to discard it \ `False`...
[ "def", "filter_rows_as_dict", "(", "fname", ",", "filter_", ",", "*", "*", "kw", ")", ":", "filter_", "=", "DictFilter", "(", "filter_", ")", "rewrite", "(", "fname", ",", "filter_", ",", "*", "*", "kw", ")", "return", "filter_", ".", "removed" ]
42.384615
20.153846
def make_flow_labels(graph, flow, capac): """Generate arc labels for a flow in a graph with capacities. :param graph: adjacency list or adjacency dictionary :param flow: flow matrix or adjacency dictionary :param capac: capacity matrix or adjacency dictionary :returns: listdic graph representation...
[ "def", "make_flow_labels", "(", "graph", ",", "flow", ",", "capac", ")", ":", "V", "=", "range", "(", "len", "(", "graph", ")", ")", "arc_label", "=", "[", "{", "v", ":", "\"\"", "for", "v", "in", "graph", "[", "u", "]", "}", "for", "u", "in", ...
39.882353
17.529412
def publish_queue(self): """ Publish all messages that have been added to the queue for configured protocol :return: None """ self.last_send_time = time.time() try: self._tx_queue_lock.acquire() start_length = len(self._rx_queue) publis...
[ "def", "publish_queue", "(", "self", ")", ":", "self", ".", "last_send_time", "=", "time", ".", "time", "(", ")", "try", ":", "self", ".", "_tx_queue_lock", ".", "acquire", "(", ")", "start_length", "=", "len", "(", "self", ".", "_rx_queue", ")", "publ...
37.958333
16.208333
def connection_with_anon(credentials, anon=True): """ Connect to S3 with automatic handling for anonymous access. Parameters ---------- credentials : dict AWS access key ('access') and secret access key ('secret') anon : boolean, optional, default = True Whether to make an anon...
[ "def", "connection_with_anon", "(", "credentials", ",", "anon", "=", "True", ")", ":", "from", "boto", ".", "s3", ".", "connection", "import", "S3Connection", "from", "boto", ".", "exception", "import", "NoAuthHandlerFound", "try", ":", "conn", "=", "S3Connect...
29.730769
21.807692
def ValidateRequiredFieldsAreNotEmpty(gtfs_object, required_field_names, problems=None): """ Validates whether all required fields of an object have a value: - if value empty adds MissingValue errors (if problems accumulator is provided) """ no_missing_value = Tru...
[ "def", "ValidateRequiredFieldsAreNotEmpty", "(", "gtfs_object", ",", "required_field_names", ",", "problems", "=", "None", ")", ":", "no_missing_value", "=", "True", "for", "name", "in", "required_field_names", ":", "if", "IsEmpty", "(", "getattr", "(", "gtfs_object...
36.142857
15
def _connect(self, config): """Establish a connection with a MySQL database.""" if 'connection_timeout' not in self._config: self._config['connection_timeout'] = 480 try: self._cnx = connect(**config) self._cursor = self._cnx.cursor() self._printer...
[ "def", "_connect", "(", "self", ",", "config", ")", ":", "if", "'connection_timeout'", "not", "in", "self", ".", "_config", ":", "self", ".", "_config", "[", "'connection_timeout'", "]", "=", "480", "try", ":", "self", ".", "_cnx", "=", "connect", "(", ...
47.642857
16.571429
def plantloopfields(data, commdct): """get plantloop fields to diagram it""" fieldlists = plantloopfieldlists(data) objkey = 'plantloop'.upper() return extractfields(data, commdct, objkey, fieldlists)
[ "def", "plantloopfields", "(", "data", ",", "commdct", ")", ":", "fieldlists", "=", "plantloopfieldlists", "(", "data", ")", "objkey", "=", "'plantloop'", ".", "upper", "(", ")", "return", "extractfields", "(", "data", ",", "commdct", ",", "objkey", ",", "...
42.4
6.8
def periodic_callback(self): """Periodic cleanup tasks to maintain this adapter, should be called every second. """ if self.stopped: return # Check if we should start scanning again if not self.scanning and len(self.connections.get_connections()) == 0: self._log...
[ "def", "periodic_callback", "(", "self", ")", ":", "if", "self", ".", "stopped", ":", "return", "# Check if we should start scanning again", "if", "not", "self", ".", "scanning", "and", "len", "(", "self", ".", "connections", ".", "get_connections", "(", ")", ...
42.363636
21.090909
def cross_lists(*sets): """Return the cross product of the arguments""" wheels = [iter(_) for _ in sets] digits = [next(it) for it in wheels] while True: yield digits[:] for i in range(len(digits)-1, -1, -1): try: digits[i] = next(wheels[i]) br...
[ "def", "cross_lists", "(", "*", "sets", ")", ":", "wheels", "=", "[", "iter", "(", "_", ")", "for", "_", "in", "sets", "]", "digits", "=", "[", "next", "(", "it", ")", "for", "it", "in", "wheels", "]", "while", "True", ":", "yield", "digits", "...
30.733333
11.733333
def satisfiable(self, extra_constraints=(), exact=None): """ This function does a constraint check and checks if the solver is in a sat state. :param extra_constraints: Extra constraints (as ASTs) to add to s for this solve :param exact: If False, return approximate solu...
[ "def", "satisfiable", "(", "self", ",", "extra_constraints", "=", "(", ")", ",", "exact", "=", "None", ")", ":", "if", "exact", "is", "False", "and", "o", ".", "VALIDATE_APPROXIMATIONS", "in", "self", ".", "state", ".", "options", ":", "er", "=", "self...
56.375
35
def _write(self, string): """Helper function to call write_data on the provided FTDI device and verify it succeeds. """ # Get modem status. Useful to enable for debugging. #ret, status = ftdi.poll_modem_status(self._ctx) #if ret == 0: # logger.debug('Modem status ...
[ "def", "_write", "(", "self", ",", "string", ")", ":", "# Get modem status. Useful to enable for debugging.", "#ret, status = ftdi.poll_modem_status(self._ctx)", "#if ret == 0:", "#\tlogger.debug('Modem status {0:02X}'.format(status))", "#else:", "#\tlogger.debug('Modem status error {0}'.f...
51.909091
26.454545
def float_field_data(field, **kwargs): """ Return random value for FloatField >>> result = any_form_field(forms.FloatField(max_value=200, min_value=100)) >>> type(result) <type 'str'> >>> float(result) >=100, float(result) <=200 (True, True) """ min_value = 0 max_value = 100 ...
[ "def", "float_field_data", "(", "field", ",", "*", "*", "kwargs", ")", ":", "min_value", "=", "0", "max_value", "=", "100", "from", "django", ".", "core", ".", "validators", "import", "MinValueValidator", ",", "MaxValueValidator", "for", "elem", "in", "field...
34.291667
17.291667
def urlencode_params(params): """URL encodes the parameters. :param params: The parameters :type params: list of key/value tuples. :rtype: string """ # urlencode does not handle unicode strings in Python 2. # Firstly, normalize the values so they get encoded correctly. params = [(key, ...
[ "def", "urlencode_params", "(", "params", ")", ":", "# urlencode does not handle unicode strings in Python 2.", "# Firstly, normalize the values so they get encoded correctly.", "params", "=", "[", "(", "key", ",", "normalize_for_urlencode", "(", "val", ")", ")", "for", "key"...
39
20.266667
def _set_below(self, v, load=False): """ Setter method for below, mapped from YANG variable /rbridge_id/threshold_monitor/interface/policy/area/alert/below (container) If this variable is read-only (config: false) in the source YANG file, then _set_below is considered as a private method. Backends l...
[ "def", "_set_below", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base", ...
74.636364
35.636364
def score(self, X, y, compute=True): """Returns the score on the given data. Parameters ---------- X : array-like, shape = [n_samples, n_features] Input data, where n_samples is the number of samples and n_features is the number of features. y : array-li...
[ "def", "score", "(", "self", ",", "X", ",", "y", ",", "compute", "=", "True", ")", ":", "scoring", "=", "self", ".", "scoring", "X", "=", "self", ".", "_check_array", "(", "X", ")", "y", "=", "self", ".", "_check_array", "(", "y", ")", "if", "n...
33.780488
20.121951
def info(self): """ Prints out information for the loaded database, namely the available tables and the number of entries for each. """ t = self.query("SELECT * FROM sqlite_master WHERE type='table'", fmt='table') all_tables = t['name'].tolist() print('\nDatabase path: {}...
[ "def", "info", "(", "self", ")", ":", "t", "=", "self", ".", "query", "(", "\"SELECT * FROM sqlite_master WHERE type='table'\"", ",", "fmt", "=", "'table'", ")", "all_tables", "=", "t", "[", "'name'", "]", ".", "tolist", "(", ")", "print", "(", "'\\nDataba...
53.928571
24.071429
def list_events(self, cond, cols, fields): """ Return the list of events, with a specific order and filtered by a condition. An element of the list is a tuple with three component. The first is the main attribute (first field). The second the second field/label, usually a string ...
[ "def", "list_events", "(", "self", ",", "cond", ",", "cols", ",", "fields", ")", ":", "def", "insert_row", "(", ")", ":", "\"\"\"\r\n Internal function to flush results for a single tabkey to result list.\r\n \"\"\"", "row", "=", "list", "(", "row_te...
36.54878
18.670732
def close_client_stream(client_stream, unix_path): """ Closes provided client stream """ try: client_stream.shutdown(socket.SHUT_RDWR) if unix_path: logger.debug('%s: Connection closed', unix_path) else: peer = client_stream.getpeername() logger.debug(...
[ "def", "close_client_stream", "(", "client_stream", ",", "unix_path", ")", ":", "try", ":", "client_stream", ".", "shutdown", "(", "socket", ".", "SHUT_RDWR", ")", "if", "unix_path", ":", "logger", ".", "debug", "(", "'%s: Connection closed'", ",", "unix_path", ...
41.083333
16.5
def all_network_files(): """All network files""" # TODO: list explicitly since some are missing? network_types = [ 'AND-circle', 'MAJ-specialized', 'MAJ-complete', 'iit-3.0-modular' ] network_sizes = range(5, 8) network_files = [] for n in network_sizes: ...
[ "def", "all_network_files", "(", ")", ":", "# TODO: list explicitly since some are missing?", "network_types", "=", "[", "'AND-circle'", ",", "'MAJ-specialized'", ",", "'MAJ-complete'", ",", "'iit-3.0-modular'", "]", "network_sizes", "=", "range", "(", "5", ",", "8", ...
27.466667
15
def get_pmap_from_nrml(oqparam, fname): """ :param oqparam: an :class:`openquake.commonlib.oqvalidation.OqParam` instance :param fname: an XML file containing hazard curves :returns: site mesh, curve array """ hcurves_by_imt = {} oqparam.hazard_imtls = imtls = {} ...
[ "def", "get_pmap_from_nrml", "(", "oqparam", ",", "fname", ")", ":", "hcurves_by_imt", "=", "{", "}", "oqparam", ".", "hazard_imtls", "=", "imtls", "=", "{", "}", "for", "hcurves", "in", "nrml", ".", "read", "(", "fname", ")", ":", "imt", "=", "hcurves...
37.066667
14.066667
def get_queue(name='default', default_timeout=None, is_async=None, autocommit=None, connection=None, queue_class=None, job_class=None, **kwargs): """ Returns an rq Queue using parameters defined in ``RQ_QUEUES`` """ from .settings import QUEUES if kwargs.get('async') is not None: ...
[ "def", "get_queue", "(", "name", "=", "'default'", ",", "default_timeout", "=", "None", ",", "is_async", "=", "None", ",", "autocommit", "=", "None", ",", "connection", "=", "None", ",", "queue_class", "=", "None", ",", "job_class", "=", "None", ",", "*"...
43.24
21.08
def one_to_many(df, unitcol, manycol): """ Assert that a many-to-one relationship is preserved between two columns. For example, a retail store will have have distinct departments, each with several employees. If each employee may only work in a single department, then the relationship of the de...
[ "def", "one_to_many", "(", "df", ",", "unitcol", ",", "manycol", ")", ":", "subset", "=", "df", "[", "[", "manycol", ",", "unitcol", "]", "]", ".", "drop_duplicates", "(", ")", "for", "many", "in", "subset", "[", "manycol", "]", ".", "unique", "(", ...
32.275862
21.586207
def update_firmware(filename, host=None, admin_username=None, admin_password=None): ''' Updates firmware using local firmware file .. code-block:: bash salt dell dracr.update_firmware firmware.exe This executes the following command...
[ "def", "update_firmware", "(", "filename", ",", "host", "=", "None", ",", "admin_username", "=", "None", ",", "admin_password", "=", "None", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "return", "_update_firmware", "(", "...
31.148148
20.62963
def related_records_78708(self, key, value): """Populate the ``related_records`` key.""" record = get_record_ref(maybe_int(value.get('w')), 'literature') if record: return { 'curated_relation': record is not None, 'record': record, 'relation_freetext': value.get('...
[ "def", "related_records_78708", "(", "self", ",", "key", ",", "value", ")", ":", "record", "=", "get_record_ref", "(", "maybe_int", "(", "value", ".", "get", "(", "'w'", ")", ")", ",", "'literature'", ")", "if", "record", ":", "return", "{", "'curated_re...
36.222222
15.888889
def basic_distance(trig_pin, echo_pin, celsius=20): '''Return an unformatted distance in cm's as read directly from RPi.GPIO.''' speed_of_sound = 331.3 * math.sqrt(1+(celsius / 273.15)) GPIO.setup(trig_pin, GPIO.OUT) GPIO.setup(echo_pin, GPIO.IN) GPIO.output(trig_pin, GPIO.LOW) time.sleep(0...
[ "def", "basic_distance", "(", "trig_pin", ",", "echo_pin", ",", "celsius", "=", "20", ")", ":", "speed_of_sound", "=", "331.3", "*", "math", ".", "sqrt", "(", "1", "+", "(", "celsius", "/", "273.15", ")", ")", "GPIO", ".", "setup", "(", "trig_pin", "...
34.625
14.125
def find(self, name, menu=None): """ Finds a menu item by name and returns it. :param name: The menu item name. """ menu = menu or self.menu for i in menu: if i.name == name: return i else: i...
[ "def", "find", "(", "self", ",", "name", ",", "menu", "=", "None", ")", ":", "menu", "=", "menu", "or", "self", ".", "menu", "for", "i", "in", "menu", ":", "if", "i", ".", "name", "==", "name", ":", "return", "i", "else", ":", "if", "i", ".",...
28.1875
12.4375
def emails_parse(emails_dict): """ Parse the output of ``SESConnection.list_verified_emails()`` and get a list of emails. """ result = emails_dict['ListVerifiedEmailAddressesResponse'][ 'ListVerifiedEmailAddressesResult'] emails = [email for email in result['VerifiedEmailAddresses']] ...
[ "def", "emails_parse", "(", "emails_dict", ")", ":", "result", "=", "emails_dict", "[", "'ListVerifiedEmailAddressesResponse'", "]", "[", "'ListVerifiedEmailAddressesResult'", "]", "emails", "=", "[", "email", "for", "email", "in", "result", "[", "'VerifiedEmailAddres...
33.4
16.8
def generate_validation_function(self, uri, name): """ Generate validation function for given uri with given name """ self._validation_functions_done.add(uri) self.l('') with self._resolver.resolving(uri) as definition: with self.l('def {}(data):', name): ...
[ "def", "generate_validation_function", "(", "self", ",", "uri", ",", "name", ")", ":", "self", ".", "_validation_functions_done", ".", "add", "(", "uri", ")", "self", ".", "l", "(", "''", ")", "with", "self", ".", "_resolver", ".", "resolving", "(", "uri...
44
14.8
def apply_trapping(self, outlets): """ Apply trapping based on algorithm described by Y. Masson [1]. It is applied as a post-process and runs the percolation algorithm in reverse assessing the occupancy of pore neighbors. Consider the following scenario when running standard IP w...
[ "def", "apply_trapping", "(", "self", ",", "outlets", ")", ":", "# First see if network is fully invaded", "net", "=", "self", ".", "project", ".", "network", "invaded_ps", "=", "self", "[", "'pore.invasion_sequence'", "]", ">", "-", "1", "if", "~", "np", ".",...
49.014815
19.888889
def write(self, filename=None): """Save template to xml. Before saving template will update date, start position, well positions, and counts. Parameters ---------- filename : str If not set, XML will be written to self.filename. """ if not filename: ...
[ "def", "write", "(", "self", ",", "filename", "=", "None", ")", ":", "if", "not", "filename", ":", "filename", "=", "self", ".", "filename", "# update time", "self", ".", "properties", ".", "CurrentDate", "=", "_current_time", "(", ")", "# set rubber band to...
30.586957
18.152174