text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def lbest_idx(state, idx): """ lbest Neighbourhood topology function. Neighbourhood size is determined by state.params['n_s']. Args: state: cipy.algorithms.pso.State: The state of the PSO algorithm. idx: int: index of the particle in the swarm. Returns: int: The index of the l...
[ "def", "lbest_idx", "(", "state", ",", "idx", ")", ":", "swarm", "=", "state", ".", "swarm", "n_s", "=", "state", ".", "params", "[", "'n_s'", "]", "cmp", "=", "comparator", "(", "swarm", "[", "0", "]", ".", "best_fitness", ")", "indices", "=", "__...
30
20.809524
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the GetUsageAllocation request payload and decode it into its constituent parts. Args: input_stream (stream): A data stream containing encoded object data, suppo...
[ "def", "read", "(", "self", ",", "input_stream", ",", "kmip_version", "=", "enums", ".", "KMIPVersion", ".", "KMIP_1_0", ")", ":", "super", "(", "GetUsageAllocationRequestPayload", ",", "self", ")", ".", "read", "(", "input_stream", ",", "kmip_version", "=", ...
38.463415
20.365854
def domains(request): """ A page with number of services and layers faceted on domains. """ url = '' query = '*:*&facet=true&facet.limit=-1&facet.pivot=domain_name,service_id&wt=json&indent=true&rows=0' if settings.SEARCH_TYPE == 'elasticsearch': url = '%s/select?q=%s' % (settings.SEARCH...
[ "def", "domains", "(", "request", ")", ":", "url", "=", "''", "query", "=", "'*:*&facet=true&facet.limit=-1&facet.pivot=domain_name,service_id&wt=json&indent=true&rows=0'", "if", "settings", ".", "SEARCH_TYPE", "==", "'elasticsearch'", ":", "url", "=", "'%s/select?q=%s'", ...
39
15.695652
def encode_file_header(boundary, paramname, filesize, filename=None, filetype=None): """Returns the leading data for a multipart/form-data field that contains file data. ``boundary`` is the boundary string used throughout a single request to separate variables. ``paramname``...
[ "def", "encode_file_header", "(", "boundary", ",", "paramname", ",", "filesize", ",", "filename", "=", "None", ",", "filetype", "=", "None", ")", ":", "return", "MultipartParam", "(", "paramname", ",", "filesize", "=", "filesize", ",", "filename", "=", "file...
37.818182
27.181818
def _CheckCacheFileForMatch(self, cache_filename, scopes): """Checks the cache file to see if it matches the given credentials. Args: cache_filename: Cache filename to check. scopes: Scopes for the desired credentials. Returns: List of scopes (if cache matches) or...
[ "def", "_CheckCacheFileForMatch", "(", "self", ",", "cache_filename", ",", "scopes", ")", ":", "creds", "=", "{", "# Credentials metadata dict.", "'scopes'", ":", "sorted", "(", "list", "(", "scopes", ")", ")", "if", "scopes", "else", "None", ",", "'svc_acct_n...
39.142857
17.535714
def kunc_p(v, v0, k0, k0p, order=5): """ calculate Kunc EOS see Dorogokupets 2015 for detail :param v: unit-cell volume in A^3 :param v0: unit-cell volume in A^3 at 1 bar :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at reference conditions ...
[ "def", "kunc_p", "(", "v", ",", "v0", ",", "k0", ",", "k0p", ",", "order", "=", "5", ")", ":", "return", "cal_p_kunc", "(", "v", ",", "[", "v0", ",", "k0", ",", "k0p", "]", ",", "order", "=", "order", ",", "uncertainties", "=", "isuncertainties",...
36.642857
12.928571
def save(self, project): ''' Saves an AnswerFactory Project Args: project (dict): Dictionary specifying an AnswerFactory Project. Returns: AnswerFactory Project id ''' # test if this is a create vs. an update if 'id' in project and proje...
[ "def", "save", "(", "self", ",", "project", ")", ":", "# test if this is a create vs. an update", "if", "'id'", "in", "project", "and", "project", "[", "'id'", "]", "is", "not", "None", ":", "# update -> use put op", "self", ".", "logger", ".", "debug", "(", ...
35.128205
20.717949
def plot(self,xdata,ydata=[],logScale=False,disp=True,**kwargs): '''Graphs a line plot. xdata: list of independent variable data. Can optionally include a header, see testGraph.py in https://github.com/Dfenestrator/GooPyCharts for an example. ydata: list of dependent variable data. Can ...
[ "def", "plot", "(", "self", ",", "xdata", ",", "ydata", "=", "[", "]", ",", "logScale", "=", "False", ",", "disp", "=", "True", ",", "*", "*", "kwargs", ")", ":", "#combine data into proper format", "#check if only 1 vector was sent, then plot against a count", ...
43.4
26.822222
def mps_device_memory_limit(): """ Returns the memory size in bytes that can be effectively allocated on the MPS device that will be used, or None if no suitable device is available. """ lib = _load_tcmps_lib() if lib is None: return None c_size = _ctypes.c_uint64() ret = lib.TC...
[ "def", "mps_device_memory_limit", "(", ")", ":", "lib", "=", "_load_tcmps_lib", "(", ")", "if", "lib", "is", "None", ":", "return", "None", "c_size", "=", "_ctypes", ".", "c_uint64", "(", ")", "ret", "=", "lib", ".", "TCMPSMetalDeviceMemoryLimit", "(", "_c...
33.583333
18.083333
def render_error_debug(request, exception, is_html): '''Render the ``exception`` traceback ''' error = Html('div', cn='well well-lg') if is_html else [] for trace in format_traceback(exception): counter = 0 for line in trace.split('\n'): if line.startswith(' '): ...
[ "def", "render_error_debug", "(", "request", ",", "exception", ",", "is_html", ")", ":", "error", "=", "Html", "(", "'div'", ",", "cn", "=", "'well well-lg'", ")", "if", "is_html", "else", "[", "]", "for", "trace", "in", "format_traceback", "(", "exception...
37.526316
16.157895
def get_signature(self, signature): """Retrieve one signature, discriminated by name or id. Note that signature name is not case sensitive. :param: a zobjects.Signature describing the signature like "Signature(name='my-sig')" :returns: a zobjects.Signature object, fille...
[ "def", "get_signature", "(", "self", ",", "signature", ")", ":", "resp", "=", "self", ".", "request_list", "(", "'GetSignatures'", ")", "# GetSignature does not allow to filter the results, so we do it by", "# hand...", "if", "resp", "and", "(", "len", "(", "resp", ...
38.928571
19.142857
def augment_send(self, send_func): """ :param send_func: a function that sends messages, such as :meth:`.Bot.send\*` :return: a function that wraps around ``send_func`` and examines whether the sent message contains an inline keyboard with callback data. If s...
[ "def", "augment_send", "(", "self", ",", "send_func", ")", ":", "def", "augmented", "(", "*", "aa", ",", "*", "*", "kw", ")", ":", "sent", "=", "send_func", "(", "*", "aa", ",", "*", "*", "kw", ")", "if", "self", ".", "_enable_chat", "and", "self...
36.722222
22.833333
def set_last_position(self, last_position): """ Called from the manager, it is in charge of updating the last position of data commited by the writer, in order to have resume support """ if last_position: if isinstance(last_position, six.string_types): ...
[ "def", "set_last_position", "(", "self", ",", "last_position", ")", ":", "if", "last_position", ":", "if", "isinstance", "(", "last_position", ",", "six", ".", "string_types", ")", ":", "last_key", "=", "last_position", "else", ":", "last_key", "=", "last_posi...
41.357143
15.5
def set(self, value): """Set a GValue. The value is converted to the type of the GValue, if possible, and assigned. """ # logger.debug('GValue.set: value = %s', value) gtype = self.gvalue.g_type fundamental = gobject_lib.g_type_fundamental(gtype) if g...
[ "def", "set", "(", "self", ",", "value", ")", ":", "# logger.debug('GValue.set: value = %s', value)", "gtype", "=", "self", ".", "gvalue", ".", "g_type", "fundamental", "=", "gobject_lib", ".", "g_type_fundamental", "(", "gtype", ")", "if", "gtype", "==", "GValu...
44.733333
20.455556
def find_related_modules(package, related_name_re='.+', ignore_exceptions=False): """Find matching modules using a package and a module name pattern.""" warnings.warn('find_related_modules has been deprecated.', DeprecationWarning) package_elements = package.rsplit...
[ "def", "find_related_modules", "(", "package", ",", "related_name_re", "=", "'.+'", ",", "ignore_exceptions", "=", "False", ")", ":", "warnings", ".", "warn", "(", "'find_related_modules has been deprecated.'", ",", "DeprecationWarning", ")", "package_elements", "=", ...
37.4
17.866667
def handle(cls, value, **kwargs): """Use a value from the environment or fall back to a default if the environment doesn't contain the variable. Format of value: <env_var>::<default value> For example: Groups: ${default app_security_groups::sg-12345,sg-6789...
[ "def", "handle", "(", "cls", ",", "value", ",", "*", "*", "kwargs", ")", ":", "try", ":", "env_var_name", ",", "default_val", "=", "value", ".", "split", "(", "\"::\"", ",", "1", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "\"Invalid ...
33.310345
24.862069
def cli(env, identifier, path, name): """Adds an attachment to an existing ticket.""" mgr = SoftLayer.TicketManager(env.client) ticket_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'ticket') if path is None: raise exceptions.ArgumentError("Missing argument --path") if not os.path.e...
[ "def", "cli", "(", "env", ",", "identifier", ",", "path", ",", "name", ")", ":", "mgr", "=", "SoftLayer", ".", "TicketManager", "(", "env", ".", "client", ")", "ticket_id", "=", "helpers", ".", "resolve_id", "(", "mgr", ".", "resolve_ids", ",", "identi...
35.157895
21.315789
def js_on_change(self, event, *callbacks): ''' Attach a ``CustomJS`` callback to an arbitrary BokehJS model event. On the BokehJS side, change events for model properties have the form ``"change:property_name"``. As a convenience, if the event name passed to this method is also the name...
[ "def", "js_on_change", "(", "self", ",", "event", ",", "*", "callbacks", ")", ":", "if", "len", "(", "callbacks", ")", "==", "0", ":", "raise", "ValueError", "(", "\"js_on_change takes an event name and one or more callbacks, got only one parameter\"", ")", "# handle ...
40.780488
25.02439
def get( self, uri, host=None, strict_slashes=None, version=None, name=None ): """ Add an API URL under the **GET** *HTTP* method :param uri: URL to be tagged to **GET** method of *HTTP* :param host: Host IP or FQDN for the service to use :param strict_slashes: Instr...
[ "def", "get", "(", "self", ",", "uri", ",", "host", "=", "None", ",", "strict_slashes", "=", "None", ",", "version", "=", "None", ",", "name", "=", "None", ")", ":", "return", "self", ".", "route", "(", "uri", ",", "methods", "=", "frozenset", "(",...
35.863636
19.318182
def is_connected(self): r"""Check if the graph is connected (cached). A graph is connected if and only if there exists a (directed) path between any two vertices. Returns ------- connected : bool True if the graph is connected, False otherwise. Note...
[ "def", "is_connected", "(", "self", ")", ":", "if", "self", ".", "_connected", "is", "not", "None", ":", "return", "self", ".", "_connected", "adjacencies", "=", "[", "self", ".", "W", "]", "if", "self", ".", "is_directed", "(", ")", ":", "adjacencies"...
24.657534
20.191781
def confindr_reporter(self, analysistype='confindr'): """ Creates a final report of all the ConFindr results """ # Initialise the data strings data = 'Strain,Genus,NumContamSNVs,ContamStatus,PercentContam,PercentContamSTD\n' with open(os.path.join(self.reportpath, analysi...
[ "def", "confindr_reporter", "(", "self", ",", "analysistype", "=", "'confindr'", ")", ":", "# Initialise the data strings", "data", "=", "'Strain,Genus,NumContamSNVs,ContamStatus,PercentContam,PercentContamSTD\\n'", "with", "open", "(", "os", ".", "path", ".", "join", "("...
49.526316
16.789474
def layer_mapproxy(request, catalog_slug, layer_uuid, path_info): """ Get Layer with matching catalog and uuid """ layer = get_object_or_404(Layer, uuid=layer_uuid, catalog__slug=catalog_slug) # for WorldMap layers we need to use the url o...
[ "def", "layer_mapproxy", "(", "request", ",", "catalog_slug", ",", "layer_uuid", ",", "path_info", ")", ":", "layer", "=", "get_object_or_404", "(", "Layer", ",", "uuid", "=", "layer_uuid", ",", "catalog__slug", "=", "catalog_slug", ")", "# for WorldMap layers we ...
34.04878
20.926829
def _normalized(self, data): """ Does a normalization of sorts on image type data so that values that should be integers are converted from strings """ int_keys = ('frames', 'width', 'height', 'size') for key in int_keys: if key not in data: c...
[ "def", "_normalized", "(", "self", ",", "data", ")", ":", "int_keys", "=", "(", "'frames'", ",", "'width'", ",", "'height'", ",", "'size'", ")", "for", "key", "in", "int_keys", ":", "if", "key", "not", "in", "data", ":", "continue", "try", ":", "data...
26.823529
17.647059
def _spintaylor_aligned_prec_swapper(**p): """ SpinTaylorF2 is only single spin, it also struggles with anti-aligned spin waveforms. This construct chooses between the aligned-twospin TaylorF2 model and the precessing singlespin SpinTaylorF2 models. If aligned spins are given, use TaylorF2, if nonal...
[ "def", "_spintaylor_aligned_prec_swapper", "(", "*", "*", "p", ")", ":", "orig_approximant", "=", "p", "[", "'approximant'", "]", "if", "p", "[", "'spin2x'", "]", "==", "0", "and", "p", "[", "'spin2y'", "]", "==", "0", "and", "p", "[", "'spin1x'", "]",...
46.277778
18.055556
def QA_util_datetime_to_strdate(dt): """ :param dt: pythone datetime.datetime :return: 1999-02-01 string type """ strdate = "%04d-%02d-%02d" % (dt.year, dt.month, dt.day) return strdate
[ "def", "QA_util_datetime_to_strdate", "(", "dt", ")", ":", "strdate", "=", "\"%04d-%02d-%02d\"", "%", "(", "dt", ".", "year", ",", "dt", ".", "month", ",", "dt", ".", "day", ")", "return", "strdate" ]
29.285714
7.285714
def GetAmi(ec2, ami_spec): """ Get the boto ami object given a AmiSpecification object. """ images = ec2.get_all_images(owners=[ami_spec.owner_id] ) requested_image = None for image in images: if image.name == ami_spec.ami_name: requested_image = image break return requested_i...
[ "def", "GetAmi", "(", "ec2", ",", "ami_spec", ")", ":", "images", "=", "ec2", ".", "get_all_images", "(", "owners", "=", "[", "ami_spec", ".", "owner_id", "]", ")", "requested_image", "=", "None", "for", "image", "in", "images", ":", "if", "image", "."...
35.111111
12.777778
def _update_config_sets(self,directory,files=None): """ Loads set information from file and updates on flickr, only reads first line. Format is comma separated eg. travel, 2010, South Africa, Pretoria If files is None, will update all files in DB, otherwise will only upd...
[ "def", "_update_config_sets", "(", "self", ",", "directory", ",", "files", "=", "None", ")", ":", "if", "not", "self", ".", "_connectToFlickr", "(", ")", ":", "print", "(", "\"%s - Couldn't connect to flickr\"", "%", "(", "directory", ")", ")", "return", "Fa...
41.861111
21.111111
def _conn_string_odbc(self, db_key, instance=None, conn_key=None, db_name=None): ''' Return a connection string to use with odbc ''' if instance: dsn, host, username, password, database, driver = self._get_access_info(instance, db_key, db_name) elif conn_key: dsn,...
[ "def", "_conn_string_odbc", "(", "self", ",", "db_key", ",", "instance", "=", "None", ",", "conn_key", "=", "None", ",", "db_name", "=", "None", ")", ":", "if", "instance", ":", "dsn", ",", "host", ",", "username", ",", "password", ",", "database", ","...
36.48
24.8
def write(self, path, data, offset=0, timeout=0): """write data at path path is a string, data binary; it is responsability of the caller ensure proper encoding. """ # fixme: check of path type delayed to str2bytez if not isinstance(data, (bytes, bytearray, )): ...
[ "def", "write", "(", "self", ",", "path", ",", "data", ",", "offset", "=", "0", ",", "timeout", "=", "0", ")", ":", "# fixme: check of path type delayed to str2bytez", "if", "not", "isinstance", "(", "data", ",", "(", "bytes", ",", "bytearray", ",", ")", ...
39.176471
19.411765
def render_revalidation_failure(self, failed_step, form, **kwargs): """ When a step fails, we have to redirect the user to the first failing step. """ self.storage.current_step = failed_step return redirect(self.url_name, step=failed_step)
[ "def", "render_revalidation_failure", "(", "self", ",", "failed_step", ",", "form", ",", "*", "*", "kwargs", ")", ":", "self", ".", "storage", ".", "current_step", "=", "failed_step", "return", "redirect", "(", "self", ".", "url_name", ",", "step", "=", "f...
40.142857
16.142857
def find_disulfide_bridges(self, representatives_only=True): """Run Biopython's disulfide bridge finder and store found bridges. Annotations are stored in the protein structure's chain sequence at: ``<chain_prop>.seq_record.annotations['SSBOND-biopython']`` Args: representa...
[ "def", "find_disulfide_bridges", "(", "self", ",", "representatives_only", "=", "True", ")", ":", "for", "g", "in", "tqdm", "(", "self", ".", "genes", ")", ":", "g", ".", "protein", ".", "find_disulfide_bridges", "(", "representative_only", "=", "representativ...
43.666667
28.666667
def _is_collinear(self, x, y): """ Checks if first three points are collinear """ pts = np.column_stack([x[:3], y[:3], np.ones(3)]) return np.linalg.det(pts) == 0.0
[ "def", "_is_collinear", "(", "self", ",", "x", ",", "y", ")", ":", "pts", "=", "np", ".", "column_stack", "(", "[", "x", "[", ":", "3", "]", ",", "y", "[", ":", "3", "]", ",", "np", ".", "ones", "(", "3", ")", "]", ")", "return", "np", "....
33.166667
6.166667
def to_nullable_boolean(value): """ Converts value into boolean or returns None when conversion is not possible. :param value: the value to convert. :return: boolean value or None when convertion is not supported. """ # Shortcuts if value == None: re...
[ "def", "to_nullable_boolean", "(", "value", ")", ":", "# Shortcuts", "if", "value", "==", "None", ":", "return", "None", "if", "type", "(", "value", ")", "==", "type", "(", "True", ")", ":", "return", "value", "str_value", "=", "str", "(", "value", ")"...
27.916667
18.666667
def set_option(self, name, value): """ Sets an option from an SConscript file. """ if not name in self.settable: raise SCons.Errors.UserError("This option is not settable from a SConscript file: %s"%name) if name == 'num_jobs': try: value ...
[ "def", "set_option", "(", "self", ",", "name", ",", "value", ")", ":", "if", "not", "name", "in", "self", ".", "settable", ":", "raise", "SCons", ".", "Errors", ".", "UserError", "(", "\"This option is not settable from a SConscript file: %s\"", "%", "name", "...
43.178571
18.5
def commit(self, message=None): """Executes the command :params message: The message to use as a comment for this action. """ flags = filters.Items() if self._status: flags.add_flags(self._status) if self._code_review is not None: ...
[ "def", "commit", "(", "self", ",", "message", "=", "None", ")", ":", "flags", "=", "filters", ".", "Items", "(", ")", "if", "self", ".", "_status", ":", "flags", ".", "add_flags", "(", "self", ".", "_status", ")", "if", "self", ".", "_code_review", ...
25.411765
19.882353
def dependencies(self, sort=False): """ Return all dependencies required to use this object. The last item in the list is *self*. """ alldeps = [] if sort: def key(obj): # sort deps such that we get functions, variables, self. if not i...
[ "def", "dependencies", "(", "self", ",", "sort", "=", "False", ")", ":", "alldeps", "=", "[", "]", "if", "sort", ":", "def", "key", "(", "obj", ")", ":", "# sort deps such that we get functions, variables, self.", "if", "not", "isinstance", "(", "obj", ",", ...
31.857143
14.619048
def ignore_cxx(self) -> bool: """Consume comments and whitespace characters.""" self._stream.save_context() while not self.read_eof(): idxref = self._stream.index if self._stream.peek_char in " \t\v\f\r\n": while (not self.read_eof() and self._stream.peek_char...
[ "def", "ignore_cxx", "(", "self", ")", "->", "bool", ":", "self", ".", "_stream", ".", "save_context", "(", ")", "while", "not", "self", ".", "read_eof", "(", ")", ":", "idxref", "=", "self", ".", "_stream", ".", "index", "if", "self", ".", "_stream"...
43.954545
11.090909
def snapshots(self, space_id, environment_id, resource_id, resource_kind='entries'): """ Provides access to snapshot management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots :return: :class:`SnapshotsProxy <co...
[ "def", "snapshots", "(", "self", ",", "space_id", ",", "environment_id", ",", "resource_id", ",", "resource_kind", "=", "'entries'", ")", ":", "return", "SnapshotsProxy", "(", "self", ",", "space_id", ",", "environment_id", ",", "resource_id", ",", "resource_kin...
51.631579
42.684211
def get_proxy_session(self): """Gets a ``ProxySession`` which is responsible for acquiring authentication credentials on behalf of a service client. :return: a proxy session for this service :rtype: ``osid.proxy.ProxySession`` :raise: ``OperationFailed`` -- unable to complete request ...
[ "def", "get_proxy_session", "(", "self", ")", ":", "if", "not", "self", ".", "supports_proxy", "(", ")", ":", "raise", "Unimplemented", "(", ")", "try", ":", "from", ".", "import", "sessions", "except", "ImportError", ":", "raise", "# OperationFailed()", "tr...
37.409091
17.409091
def datetime_to_ns(then): """Transform a :any:`datetime.datetime` into a NationStates-style string. For example "6 days ago", "105 minutes ago", etc. """ if then == datetime(1970, 1, 1, 0, 0): return 'Antiquity' now = datetime.utcnow() delta = now - then seconds = delta.total_s...
[ "def", "datetime_to_ns", "(", "then", ")", ":", "if", "then", "==", "datetime", "(", "1970", ",", "1", ",", "1", ",", "0", ",", "0", ")", ":", "return", "'Antiquity'", "now", "=", "datetime", ".", "utcnow", "(", ")", "delta", "=", "now", "-", "th...
26.809524
16.111111
def query_versions(self, version=None): """Check specified version and resolve special values.""" if version not in RELEASE_AND_CANDIDATE_LATEST_VERSIONS: return [version] url = urljoin(self.base_url, 'releases/') parser = self._create_directory_parser(url) if versio...
[ "def", "query_versions", "(", "self", ",", "version", "=", "None", ")", ":", "if", "version", "not", "in", "RELEASE_AND_CANDIDATE_LATEST_VERSIONS", ":", "return", "[", "version", "]", "url", "=", "urljoin", "(", "self", ".", "base_url", ",", "'releases/'", "...
41.071429
15.714286
def cmd_build(conf: Config, run_tests: bool=False): """Build requested targets, and their dependencies.""" build_context = BuildContext(conf) populate_targets_graph(build_context, conf) build_context.build_graph(run_tests=run_tests) build_context.write_artifacts_metadata()
[ "def", "cmd_build", "(", "conf", ":", "Config", ",", "run_tests", ":", "bool", "=", "False", ")", ":", "build_context", "=", "BuildContext", "(", "conf", ")", "populate_targets_graph", "(", "build_context", ",", "conf", ")", "build_context", ".", "build_graph"...
48
5.666667
def close_connection(self, connection, force=False): """overriding the baseclass function, this routine will decline to close a connection at the end of a transaction context. This allows for reuse of connections.""" if force: try: connection.close() ...
[ "def", "close_connection", "(", "self", ",", "connection", ",", "force", "=", "False", ")", ":", "if", "force", ":", "try", ":", "connection", ".", "close", "(", ")", "except", "self", ".", "operational_exceptions", ":", "self", ".", "config", ".", "logg...
40.333333
15.666667
def sep(s): """Find the path separator used in this string, or os.sep if none.""" sep_match = re.search(r"[\\/]", s) if sep_match: the_sep = sep_match.group(0) else: the_sep = os.sep return the_sep
[ "def", "sep", "(", "s", ")", ":", "sep_match", "=", "re", ".", "search", "(", "r\"[\\\\/]\"", ",", "s", ")", "if", "sep_match", ":", "the_sep", "=", "sep_match", ".", "group", "(", "0", ")", "else", ":", "the_sep", "=", "os", ".", "sep", "return", ...
28.25
15.875
def list_project(self, offset=0, size=100): """ list the project Unsuccessful opertaion will cause an LogException. :type offset: int :param offset: the offset of all the matched names :type size: int :param size: the max return names count, -1 means return all ...
[ "def", "list_project", "(", "self", ",", "offset", "=", "0", ",", "size", "=", "100", ")", ":", "# need to use extended method to get more\r", "if", "int", "(", "size", ")", "==", "-", "1", "or", "int", "(", "size", ")", ">", "MAX_LIST_PAGING_SIZE", ":", ...
33.653846
21.307692
def residmap(self, prefix='', **kwargs): """Generate 2-D spatial residual maps using the current ROI model and the convolution kernel defined with the `model` argument. Parameters ---------- prefix : str String that will be prefixed to the output residual map...
[ "def", "residmap", "(", "self", ",", "prefix", "=", "''", ",", "*", "*", "kwargs", ")", ":", "timer", "=", "Timer", ".", "create", "(", "start", "=", "True", ")", "self", ".", "logger", ".", "info", "(", "'Generating residual maps'", ")", "schema", "...
34.018182
24.236364
def baltree(ntips, treeheight=1.0): """ Returns a balanced tree topology. """ # require even number of tips if ntips % 2: raise ToytreeError("balanced trees must have even number of tips.") # make first cherry rtree = toytree.tree() rtree.tree...
[ "def", "baltree", "(", "ntips", ",", "treeheight", "=", "1.0", ")", ":", "# require even number of tips", "if", "ntips", "%", "2", ":", "raise", "ToytreeError", "(", "\"balanced trees must have even number of tips.\"", ")", "# make first cherry", "rtree", "=", "toytre...
29.74359
14.666667
def read_namespaced_network_policy(self, name, namespace, **kwargs): """ read the specified NetworkPolicy This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_network_policy(name...
[ "def", "read_namespaced_network_policy", "(", "self", ",", "name", ",", "namespace", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ...
58.666667
30.25
def __unLock(self): """Unlock sending requests to projector.""" self._operation = False self._timer = 0 self._isLocked = False
[ "def", "__unLock", "(", "self", ")", ":", "self", ".", "_operation", "=", "False", "self", ".", "_timer", "=", "0", "self", ".", "_isLocked", "=", "False" ]
30.8
11.4
def plot_validate(self, figure_list): """ plots the data contained in self.data, which should be a dictionary or a deque of dictionaries for the latter use the last entry """ axes_list = self.get_axes_layout_validate(figure_list) self._plot_validate(axes_list)
[ "def", "plot_validate", "(", "self", ",", "figure_list", ")", ":", "axes_list", "=", "self", ".", "get_axes_layout_validate", "(", "figure_list", ")", "self", ".", "_plot_validate", "(", "axes_list", ")" ]
37.75
16.25
def _merge_extra_filerefs(*args): ''' Takes a list of filerefs and returns a merged list ''' ret = [] for arg in args: if isinstance(arg, six.string_types): if arg: ret.extend(arg.split(',')) elif isinstance(arg, list): if arg: ...
[ "def", "_merge_extra_filerefs", "(", "*", "args", ")", ":", "ret", "=", "[", "]", "for", "arg", "in", "args", ":", "if", "isinstance", "(", "arg", ",", "six", ".", "string_types", ")", ":", "if", "arg", ":", "ret", ".", "extend", "(", "arg", ".", ...
26.769231
16.461538
def _decode_embedded_dict(src): ''' Convert enbedded bytes to strings if possible. Dict helper. ''' output = {} for key, val in six.iteritems(src): if isinstance(val, dict): val = _decode_embedded_dict(val) elif isinstance(val, list): val = _decode_embedde...
[ "def", "_decode_embedded_dict", "(", "src", ")", ":", "output", "=", "{", "}", "for", "key", ",", "val", "in", "six", ".", "iteritems", "(", "src", ")", ":", "if", "isinstance", "(", "val", ",", "dict", ")", ":", "val", "=", "_decode_embedded_dict", ...
29.565217
15.73913
def pre_delete(cls, sender, instance, *args, **kwargs): """Deletes the CC email marketing campaign associated with me. """ cc = ConstantContact() response = cc.delete_email_marketing_campaign(instance) response.raise_for_status()
[ "def", "pre_delete", "(", "cls", ",", "sender", ",", "instance", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "cc", "=", "ConstantContact", "(", ")", "response", "=", "cc", ".", "delete_email_marketing_campaign", "(", "instance", ")", "response", ...
44
8.833333
def get_provider(self, name): """Allows for lazy instantiation of providers (Jinja2 templating is heavy, so only instantiate it if necessary).""" if name not in self.providers: cls = self.provider_classes[name] # instantiate the provider self.providers[name] =...
[ "def", "get_provider", "(", "self", ",", "name", ")", ":", "if", "name", "not", "in", "self", ".", "providers", ":", "cls", "=", "self", ".", "provider_classes", "[", "name", "]", "# instantiate the provider", "self", ".", "providers", "[", "name", "]", ...
44.875
3.625
def run_json(self): """ Run checks on self.files, printing json object containing information relavent to the CS50 IDE plugin at the end. """ checks = {} for file in self.files: try: results = self._check(file) except Error as e: ...
[ "def", "run_json", "(", "self", ")", ":", "checks", "=", "{", "}", "for", "file", "in", "self", ".", "files", ":", "try", ":", "results", "=", "self", ".", "_check", "(", "file", ")", "except", "Error", "as", "e", ":", "checks", "[", "file", "]",...
34.136364
18.681818
def from_raw(self, file_names=None, **kwargs): """Load a raw data-file. Args: file_names (list of raw-file names): uses CellpyData.file_names if None. If the list contains more than one file name, then the runs will be merged together. """ # T...
[ "def", "from_raw", "(", "self", ",", "file_names", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# This function only loads one test at a time (but could contain several", "# files). The function from_res() also implements loading several", "# datasets (using list of lists as inpu...
42.363636
20.792208
def get_attachments_by_name(self, name, check_regex, find_first=False): """ Gets all attachments by name for the mail. :param name: The name of the attachment to look for. :type name: str :param check_regex: Checks the name for a regular expression. :type check_regex: bo...
[ "def", "get_attachments_by_name", "(", "self", ",", "name", ",", "check_regex", ",", "find_first", "=", "False", ")", ":", "attachments", "=", "[", "]", "for", "part", "in", "self", ".", "mail", ".", "walk", "(", ")", ":", "mail_part", "=", "MailPart", ...
42.103448
19.482759
def search_anime(self, query): """Fuzzy searches the Anime Database for the query. :param str query: The text to fuzzy search. :returns: List of Anime Objects. This list can be empty. """ r = self._query_('/search/anime', 'GET', params={'query': query})...
[ "def", "search_anime", "(", "self", ",", "query", ")", ":", "r", "=", "self", ".", "_query_", "(", "'/search/anime'", ",", "'GET'", ",", "params", "=", "{", "'query'", ":", "query", "}", ")", "results", "=", "[", "Anime", "(", "item", ")", "for", "...
32.166667
17.666667
def filter_google_songs(songs, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False): """Match a Google Music song dict against a set of metadata filters. Parameters: songs (list): Google Music song dicts to filter. include_filters (list): A list of ``(field, pattern)`` tuples. ...
[ "def", "filter_google_songs", "(", "songs", ",", "include_filters", "=", "None", ",", "exclude_filters", "=", "None", ",", "all_includes", "=", "False", ",", "all_excludes", "=", "False", ")", ":", "matched_songs", "=", "[", "]", "filtered_songs", "=", "[", ...
37
29.813953
def generate_random_nhs_number() -> int: """ Returns a random valid NHS number, as an ``int``. """ check_digit = 10 # NHS numbers with this check digit are all invalid while check_digit == 10: digits = [random.randint(1, 9)] # don't start with a zero digits.extend([random.randint(0...
[ "def", "generate_random_nhs_number", "(", ")", "->", "int", ":", "check_digit", "=", "10", "# NHS numbers with this check digit are all invalid", "while", "check_digit", "==", "10", ":", "digits", "=", "[", "random", ".", "randint", "(", "1", ",", "9", ")", "]",...
40.615385
11.230769
def parse_text(text: str, schema: dict) -> Any: """ Validate and parse the BMA answer from websocket :param text: the bma answer :param schema: dict for jsonschema :return: the json data """ try: data = json.loads(text) jsonschema.validate(data, schema) except (TypeError...
[ "def", "parse_text", "(", "text", ":", "str", ",", "schema", ":", "dict", ")", "->", "Any", ":", "try", ":", "data", "=", "json", ".", "loads", "(", "text", ")", "jsonschema", ".", "validate", "(", "data", ",", "schema", ")", "except", "(", "TypeEr...
28
15.2
def filter_publisher_references(root, head, update): """Remove references from ``update`` if there are any in ``head``. This is useful when merging a record from a publisher with an update form arXiv, as arXiv should never overwrite references from the publisher. """ if 'references' in head: ...
[ "def", "filter_publisher_references", "(", "root", ",", "head", ",", "update", ")", ":", "if", "'references'", "in", "head", ":", "root", "=", "_remove_if_present", "(", "root", ",", "'references'", ")", "update", "=", "_remove_if_present", "(", "update", ",",...
40.545455
19.545455
def parse(representation): """Attempts to parse an ISO8601 formatted ``representation`` string, which could be of any valid ISO8601 format (date, time, duration, interval). Return value is specific to ``representation``. """ representation = str(representation).upper().strip() if '/' in repres...
[ "def", "parse", "(", "representation", ")", ":", "representation", "=", "str", "(", "representation", ")", ".", "upper", "(", ")", ".", "strip", "(", ")", "if", "'/'", "in", "representation", ":", "return", "parse_interval", "(", "representation", ")", "if...
32
18.2
def _synoname_strip_punct(self, word): """Return a word with punctuation stripped out. Parameters ---------- word : str A word to strip punctuation from Returns ------- str The word stripped of punctuation Examples ------...
[ "def", "_synoname_strip_punct", "(", "self", ",", "word", ")", ":", "stripped", "=", "''", "for", "char", "in", "word", ":", "if", "char", "not", "in", "set", "(", "',-./:;\"&\\'()!{|}?$%*+<=>[\\\\]^_`~'", ")", ":", "stripped", "+=", "char", "return", "strip...
23.88
19.48
def element_text_should_be(self, locator, expected, message=''): """Verifies element identified by ``locator`` exactly contains text ``expected``. In contrast to `Element Should Contain Text`, this keyword does not try a substring match but an exact match on the element identified by ``loca...
[ "def", "element_text_should_be", "(", "self", ",", "locator", ",", "expected", ",", "message", "=", "''", ")", ":", "self", ".", "_info", "(", "\"Verifying element '%s' contains exactly text '%s'.\"", "%", "(", "locator", ",", "expected", ")", ")", "element", "=...
47.631579
22.684211
def calc_coverage(ref, start, end, length, nucs): """ calculate coverage for positions in range start -> end """ ref = ref[start - 1:end] bases = 0 for pos in ref: for base, count in list(pos.items()): if base in nucs: bases += count return float(bases)/fl...
[ "def", "calc_coverage", "(", "ref", ",", "start", ",", "end", ",", "length", ",", "nucs", ")", ":", "ref", "=", "ref", "[", "start", "-", "1", ":", "end", "]", "bases", "=", "0", "for", "pos", "in", "ref", ":", "for", "base", ",", "count", "in"...
29.181818
10.636364
def find_value_in_object(attr, obj): """Return values for any key coincidence with attr in obj or any other nested dict. """ # Carry on inspecting inside the list or tuple if isinstance(obj, (collections.Iterator, list)): for item in obj: yield from find_value_in_object(attr, it...
[ "def", "find_value_in_object", "(", "attr", ",", "obj", ")", ":", "# Carry on inspecting inside the list or tuple", "if", "isinstance", "(", "obj", ",", "(", "collections", ".", "Iterator", ",", "list", ")", ")", ":", "for", "item", "in", "obj", ":", "yield", ...
32.9
19
async def _on_report_notification(self, event): """Callback function called when a report event is received. Args: event (dict): The report_event """ conn_string = event.get('connection_string') report = self._report_parser.deserialize_report(event.get('serialized_r...
[ "async", "def", "_on_report_notification", "(", "self", ",", "event", ")", ":", "conn_string", "=", "event", ".", "get", "(", "'connection_string'", ")", "report", "=", "self", ".", "_report_parser", ".", "deserialize_report", "(", "event", ".", "get", "(", ...
34.181818
21
def has_source_contents(self, src_id): """Checks if some sources exist.""" return bool(rustcall(_lib.lsm_view_has_source_contents, self._get_ptr(), src_id))
[ "def", "has_source_contents", "(", "self", ",", "src_id", ")", ":", "return", "bool", "(", "rustcall", "(", "_lib", ".", "lsm_view_has_source_contents", ",", "self", ".", "_get_ptr", "(", ")", ",", "src_id", ")", ")" ]
49.5
9.75
def get_needs_provenance(parameters): """Get the provenance of minimum needs. :param parameters: A dictionary of impact function parameters. :type parameters: dict :returns: A parameter of provenance :rtype: TextParameter """ if 'minimum needs' not in parameters: return None ne...
[ "def", "get_needs_provenance", "(", "parameters", ")", ":", "if", "'minimum needs'", "not", "in", "parameters", ":", "return", "None", "needs", "=", "parameters", "[", "'minimum needs'", "]", "provenance", "=", "[", "p", "for", "p", "in", "needs", "if", "p",...
29.25
15.375
def compute_memory_contents_under_schedule(self, schedule): """The in-memory tensors present when executing each operation in schedule. Simulates running operations in the order given by a schedule. Keeps track of the tensors in memory at every point in time, and outputs a list (one entry for each poin...
[ "def", "compute_memory_contents_under_schedule", "(", "self", ",", "schedule", ")", ":", "out_degree", "=", "self", ".", "_compute_initial_out_degree", "(", ")", "curr_memory_contents", "=", "set", "(", ")", "memory_contents_for_each_operation", "=", "[", "]", "for", ...
42.926829
22.97561
def publishFeatureCollections(self, configs): """Publishes feature collections to a feature service. Args: configs (list): A list of JSON configuration feature service details to publish. Returns: dict: A dictionary of results objects. """ if sel...
[ "def", "publishFeatureCollections", "(", "self", ",", "configs", ")", ":", "if", "self", ".", "securityhandler", "is", "None", ":", "print", "(", "\"Security handler required\"", ")", "return", "config", "=", "None", "res", "=", "None", "resItm", "=", "None", ...
29.517241
21.465517
def _calculate_distance(latlon1, latlon2): """Calculates the distance between two points on earth. """ lat1, lon1 = latlon1 lat2, lon2 = latlon2 dlon = lon2 - lon1 dlat = lat2 - lat1 R = 6371 # radius of the earth in kilometers a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np...
[ "def", "_calculate_distance", "(", "latlon1", ",", "latlon2", ")", ":", "lat1", ",", "lon1", "=", "latlon1", "lat2", ",", "lon2", "=", "latlon2", "dlon", "=", "lon2", "-", "lon1", "dlat", "=", "lat2", "-", "lat1", "R", "=", "6371", "# radius of the earth...
37.272727
16
def _update_dest_ip(self): '''如果未指定DEST_IP,默认与RTSP使用相同IP''' global DEST_IP if not DEST_IP: DEST_IP = self._sock.getsockname()[0] PRINT('DEST_IP: %s\n'%DEST_IP, CYAN)
[ "def", "_update_dest_ip", "(", "self", ")", ":", "global", "DEST_IP", "if", "not", "DEST_IP", ":", "DEST_IP", "=", "self", ".", "_sock", ".", "getsockname", "(", ")", "[", "0", "]", "PRINT", "(", "'DEST_IP: %s\\n'", "%", "DEST_IP", ",", "CYAN", ")" ]
34.666667
11
def decode(string, encoding=None, errors=None): """Decode from specified encoding. ``encoding`` defaults to the preferred encoding. ``errors`` defaults to the preferred error handler. """ if encoding is None: encoding = getpreferredencoding() if errors is None: errors = getprefe...
[ "def", "decode", "(", "string", ",", "encoding", "=", "None", ",", "errors", "=", "None", ")", ":", "if", "encoding", "is", "None", ":", "encoding", "=", "getpreferredencoding", "(", ")", "if", "errors", "is", "None", ":", "errors", "=", "getpreferrederr...
33.181818
10.363636
def _get_stddevs(self, C, stddev_types, num_sites, mag, c1_rrup, log_phi_ss, mean_phi_ss): """ Return standard deviations """ phi_ss = _compute_phi_ss(C, mag, c1_rrup, log_phi_ss, mean_phi_ss) stddevs = [] for stddev_type in stddev_types: ...
[ "def", "_get_stddevs", "(", "self", ",", "C", ",", "stddev_types", ",", "num_sites", ",", "mag", ",", "c1_rrup", ",", "log_phi_ss", ",", "mean_phi_ss", ")", ":", "phi_ss", "=", "_compute_phi_ss", "(", "C", ",", "mag", ",", "c1_rrup", ",", "log_phi_ss", "...
37.956522
18.304348
def unpack_reply(cls, header, payload): """Take already unpacked header and binary payload of received request reply and creates message instance :param header: a namedtuple header object providing header information :param payload: payload (BytesIO instance) of message """ reply...
[ "def", "unpack_reply", "(", "cls", ",", "header", ",", "payload", ")", ":", "reply", "=", "cls", "(", "header", ".", "session_id", ",", "header", ".", "packet_count", ",", "segments", "=", "tuple", "(", "ReplySegment", ".", "unpack_from", "(", "payload", ...
45.666667
19.833333
def reset(self): """Resets the iterator to the beginning of the data.""" self.curr_idx = 0 #shuffle data in each bucket random.shuffle(self.idx) for i, buck in enumerate(self.sentences): self.indices[i], self.sentences[i], self.characters[i], self.label[i] = shuffle(s...
[ "def", "reset", "(", "self", ")", ":", "self", ".", "curr_idx", "=", "0", "#shuffle data in each bucket", "random", ".", "shuffle", "(", "self", ".", "idx", ")", "for", "i", ",", "buck", "in", "enumerate", "(", "self", ".", "sentences", ")", ":", "self...
52.304348
28.782609
def convolve_image(self, image_array, blurring_array): """For a given 1D regular array and blurring array, convolve the two using this convolver. Parameters ----------- image_array : ndarray 1D array of the regular values which are to be blurred with the convolver's PSF. ...
[ "def", "convolve_image", "(", "self", ",", "image_array", ",", "blurring_array", ")", ":", "return", "self", ".", "convolve_jit", "(", "image_array", ",", "self", ".", "image_frame_indexes", ",", "self", ".", "image_frame_psfs", ",", "self", ".", "image_frame_le...
57.307692
30.769231
def _read_requirements(filename, extra_packages): """Returns a list of package requirements read from the file.""" requirements_file = open(filename).read() hard_requirements = [] for line in requirements_file.splitlines(): if _is_requirement(line): if line.find(';') > -1: ...
[ "def", "_read_requirements", "(", "filename", ",", "extra_packages", ")", ":", "requirements_file", "=", "open", "(", "filename", ")", ".", "read", "(", ")", "hard_requirements", "=", "[", "]", "for", "line", "in", "requirements_file", ".", "splitlines", "(", ...
41.692308
13.230769
def assert_create_update_delete_permission(f): """Access only by subjects with Create/Update/Delete permission and by trusted infrastructure (CNs).""" @functools.wraps(f) def wrapper(request, *args, **kwargs): d1_gmn.app.auth.assert_create_update_delete_permission(request) return f(requ...
[ "def", "assert_create_update_delete_permission", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "wrapper", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "d1_gmn", ".", "app", ".", "auth", ".", "assert_c...
35.2
16
def normalize_rgb(r, g, b, a): """Transform a rgb[a] color to #hex[a]. """ r = int(r, 10) g = int(g, 10) b = int(b, 10) if a: a = float(a) * 256 if r > 255 or g > 255 or b > 255 or (a and a > 255): return None color = '#%02x%02x%02x' % (r, g, b) if a: color +=...
[ "def", "normalize_rgb", "(", "r", ",", "g", ",", "b", ",", "a", ")", ":", "r", "=", "int", "(", "r", ",", "10", ")", "g", "=", "int", "(", "g", ",", "10", ")", "b", "=", "int", "(", "b", ",", "10", ")", "if", "a", ":", "a", "=", "floa...
24.285714
15.857143
def get_net(req): """Get the net of any 'next' and 'prev' querystrings.""" try: nxt, prev = map( int, (req.GET.get('cal_next', 0), req.GET.get('cal_prev', 0)) ) net = nxt - prev except Exception: net = 0 return net
[ "def", "get_net", "(", "req", ")", ":", "try", ":", "nxt", ",", "prev", "=", "map", "(", "int", ",", "(", "req", ".", "GET", ".", "get", "(", "'cal_next'", ",", "0", ")", ",", "req", ".", "GET", ".", "get", "(", "'cal_prev'", ",", "0", ")", ...
26.5
22.1
def set_extension(self, name, value): """ Sets the value for an extension using a fully constructed asn1crypto.core.Asn1Value object. Normally this should not be needed, and the convenience attributes should be sufficient. See the definition of asn1crypto.ocsp.SingleResponseExte...
[ "def", "set_extension", "(", "self", ",", "name", ",", "value", ")", ":", "if", "isinstance", "(", "name", ",", "str_cls", ")", ":", "response_data_extension_oids", "=", "set", "(", "[", "'nonce'", ",", "'extended_revoke'", ",", "'1.3.6.1.5.5.7.48.1.2'", ",", ...
35.192
19.896
def get_splits_in_period(self, start: Datum, end: Datum) -> List[Split]: """ returns splits only up to the given date """ # from gnucash_portfolio.lib import generic query = ( self.book.session.query(Split) .join(Transaction) .filter(Split.account == self.acc...
[ "def", "get_splits_in_period", "(", "self", ",", "start", ":", "Datum", ",", "end", ":", "Datum", ")", "->", "List", "[", "Split", "]", ":", "# from gnucash_portfolio.lib import generic", "query", "=", "(", "self", ".", "book", ".", "session", ".", "query", ...
38.357143
17.071429
def findSensor(self, sensors, sensor_name, device_type = None): """ Find a sensor in the provided list of sensors @param sensors (list) - List of sensors to search in @param sensor_name (string) - Name of sensor to find @param device_type (strin...
[ "def", "findSensor", "(", "self", ",", "sensors", ",", "sensor_name", ",", "device_type", "=", "None", ")", ":", "if", "device_type", "==", "None", ":", "for", "sensor", "in", "sensors", ":", "if", "sensor", "[", "'name'", "]", "==", "sensor_name", ":", ...
38.904762
20.333333
def send_group_file(self, sender, receiver, media_id): """ 发送群聊文件消息 :param sender: 发送人 :param receiver: 会话 ID :param media_id: 文件id,可以调用上传素材文件接口获取, 文件须大于4字节 :return: 返回的 JSON 数据包 """ return self.send_file(sender, 'group', receiver, media_id)
[ "def", "send_group_file", "(", "self", ",", "sender", ",", "receiver", ",", "media_id", ")", ":", "return", "self", ".", "send_file", "(", "sender", ",", "'group'", ",", "receiver", ",", "media_id", ")" ]
29.7
15.3
def _get_roles_for_request(request, application): """ Check the authentication of the current user. """ roles = application.get_roles_for_person(request.user) if common.is_admin(request): roles.add("is_admin") roles.add('is_authorised') return roles
[ "def", "_get_roles_for_request", "(", "request", ",", "application", ")", ":", "roles", "=", "application", ".", "get_roles_for_person", "(", "request", ".", "user", ")", "if", "common", ".", "is_admin", "(", "request", ")", ":", "roles", ".", "add", "(", ...
33.222222
16
def clear_socket(self): ''' delete socket if you have it ''' if hasattr(self, '_socket'): if isinstance(self.poller.sockets, dict): sockets = list(self.poller.sockets.keys()) for socket in sockets: log.trace('Unregistering s...
[ "def", "clear_socket", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'_socket'", ")", ":", "if", "isinstance", "(", "self", ".", "poller", ".", "sockets", ",", "dict", ")", ":", "sockets", "=", "list", "(", "self", ".", "poller", ".", ...
39.6
15.6
def listen_tta(self, target, timeout): """Listen *timeout* seconds for a Type A activation at 106 kbps. The ``sens_res``, ``sdd_res``, and ``sel_res`` response data must be provided and ``sdd_res`` must be a 4 byte UID that starts with ``08h``. Depending on ``sel_res`` an activation may ...
[ "def", "listen_tta", "(", "self", ",", "target", ",", "timeout", ")", ":", "return", "super", "(", "Device", ",", "self", ")", ".", "listen_tta", "(", "target", ",", "timeout", ")" ]
53.545455
20.545455
def update_routing_table_from(self, *routers): """ Try to update routing tables with the given routers. :return: True if the routing table is successfully updated, otherwise False """ for router in routers: new_routing_table = self.fetch_routing_table(router) if ...
[ "def", "update_routing_table_from", "(", "self", ",", "*", "routers", ")", ":", "for", "router", "in", "routers", ":", "new_routing_table", "=", "self", ".", "fetch_routing_table", "(", "router", ")", "if", "new_routing_table", "is", "not", "None", ":", "self"...
40.909091
16.454545
def _validate_type(self): # type: () -> None """Validation to ensure value is the correct type""" if not isinstance(self._value, self._type): title = '{} has an invalid type'.format(self._key_name()) description = '{} must be a {}'.format(self._key_name(), self._type.__name__) ...
[ "def", "_validate_type", "(", "self", ")", ":", "# type: () -> None", "if", "not", "isinstance", "(", "self", ".", "_value", ",", "self", ".", "_type", ")", ":", "title", "=", "'{} has an invalid type'", ".", "format", "(", "self", ".", "_key_name", "(", "...
54.142857
22.714286
def add_dockwidget(self, child): """Add QDockWidget and toggleViewAction""" dockwidget, location = child.create_dockwidget() if CONF.get('main', 'vertical_dockwidget_titlebars'): dockwidget.setFeatures(dockwidget.features()| QDockWidget.DockWid...
[ "def", "add_dockwidget", "(", "self", ",", "child", ")", ":", "dockwidget", ",", "location", "=", "child", ".", "create_dockwidget", "(", ")", "if", "CONF", ".", "get", "(", "'main'", ",", "'vertical_dockwidget_titlebars'", ")", ":", "dockwidget", ".", "setF...
52.75
13.875
def get_bad_rows_and_cols(df, validation_names, type_col_names, value_col_names, verbose=False): """ Input: validated DataFrame, all validation names, names of the type columns, names of the value columns, verbose (True or False). Output: list of rows with bad values, list of c...
[ "def", "get_bad_rows_and_cols", "(", "df", ",", "validation_names", ",", "type_col_names", ",", "value_col_names", ",", "verbose", "=", "False", ")", ":", "df", "[", "\"num\"", "]", "=", "list", "(", "range", "(", "len", "(", "df", ")", ")", ")", "proble...
44.14
19.66
def _read_result(self): """Parse read a response from the AGI and parse it. :return dict: The AGI response parsed into a dict. """ response = yield from self.reader.readline() return parse_agi_result(response.decode(self.encoding)[:-1])
[ "def", "_read_result", "(", "self", ")", ":", "response", "=", "yield", "from", "self", ".", "reader", ".", "readline", "(", ")", "return", "parse_agi_result", "(", "response", ".", "decode", "(", "self", ".", "encoding", ")", "[", ":", "-", "1", "]", ...
38.714286
16.428571
def options(self, context, module_options): ''' LHOST IP hosting the handler LPORT Handler port PAYLOAD Payload to inject: reverse_http or reverse_https (default: reverse_https) PROCID Process ID to inject into (default: current powershell process) ...
[ "def", "options", "(", "self", ",", "context", ",", "module_options", ")", ":", "self", ".", "met_payload", "=", "'reverse_https'", "self", ".", "procid", "=", "None", "if", "not", "'LHOST'", "in", "module_options", "or", "not", "'LPORT'", "in", "module_opti...
36.4
23.84
def _em_conversion(orig_units, conv_data, to_units=None, unit_system=None): """Convert between E&M & MKS base units. If orig_units is a CGS (or MKS) E&M unit, conv_data contains the corresponding MKS (or CGS) unit and scale factor converting between them. This must be done by replacing the expression o...
[ "def", "_em_conversion", "(", "orig_units", ",", "conv_data", ",", "to_units", "=", "None", ",", "unit_system", "=", "None", ")", ":", "conv_unit", ",", "canonical_unit", ",", "scale", "=", "conv_data", "if", "conv_unit", "is", "None", ":", "conv_unit", "=",...
44.85
19.8
def pre_dissect(self, s): """ Decrypt, verify and decompress the message. """ if len(s) < 5: raise Exception("Invalid record: header is too short.") if isinstance(self.tls_session.rcs.cipher, Cipher_NULL): self.deciphered_len = None return s ...
[ "def", "pre_dissect", "(", "self", ",", "s", ")", ":", "if", "len", "(", "s", ")", "<", "5", ":", "raise", "Exception", "(", "\"Invalid record: header is too short.\"", ")", "if", "isinstance", "(", "self", ".", "tls_session", ".", "rcs", ".", "cipher", ...
36.5
15.375
def get_checksum_by_target(self, target): """ returns a checksum of a specific kind """ for csum in self.checksums: if csum.target == target: return csum return None
[ "def", "get_checksum_by_target", "(", "self", ",", "target", ")", ":", "for", "csum", "in", "self", ".", "checksums", ":", "if", "csum", ".", "target", "==", "target", ":", "return", "csum", "return", "None" ]
35.333333
7.166667
def calculateOptionPrice(self, reqId, contract, volatility, underPrice): """calculateOptionPrice(EClient self, TickerId reqId, Contract contract, double volatility, double underPrice)""" return _swigibpy.EClient_calculateOptionPrice(self, reqId, contract, volatility, underPrice)
[ "def", "calculateOptionPrice", "(", "self", ",", "reqId", ",", "contract", ",", "volatility", ",", "underPrice", ")", ":", "return", "_swigibpy", ".", "EClient_calculateOptionPrice", "(", "self", ",", "reqId", ",", "contract", ",", "volatility", ",", "underPrice...
97.666667
30.666667