text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def measureSize(self, diff, chunkSize): """ Spend some time to get an accurate size. """ self._fileSystemSync() sendContext = self.butter.send( self.getSendPath(diff.toVol), self.getSendPath(diff.fromVol), diff, showProgress=self.showProgress is n...
[ "def", "measureSize", "(", "self", ",", "diff", ",", "chunkSize", ")", ":", "self", ".", "_fileSystemSync", "(", ")", "sendContext", "=", "self", ".", "butter", ".", "send", "(", "self", ".", "getSendPath", "(", "diff", ".", "toVol", ")", ",", "self", ...
34.346939
20.020408
def purge_queues(self, queues): """ Purge all messages from one or more queues. :param list queues: A list of ('qname', 'vhost') tuples. :returns: True on success """ for name, vhost in queues: vhost = quote(vhost, '') name = quote(name, '') ...
[ "def", "purge_queues", "(", "self", ",", "queues", ")", ":", "for", "name", ",", "vhost", "in", "queues", ":", "vhost", "=", "quote", "(", "vhost", ",", "''", ")", "name", "=", "quote", "(", "name", ",", "''", ")", "path", "=", "Client", ".", "ur...
30.214286
13.642857
def align_and_update_state_dicts(model_state_dict, loaded_state_dict): """ Strategy: suppose that the models that we will create will have prefixes appended to each of its keys, for example due to an extra level of nesting that the original pre-trained weights from ImageNet won't contain. For example, m...
[ "def", "align_and_update_state_dicts", "(", "model_state_dict", ",", "loaded_state_dict", ")", ":", "current_keys", "=", "sorted", "(", "list", "(", "model_state_dict", ".", "keys", "(", ")", ")", ")", "loaded_keys", "=", "sorted", "(", "list", "(", "loaded_stat...
48.183673
23.367347
def read_manifest(self, encrypted=None): """ Read an existing manifest. """ with open(self.manifest_path, 'r') as input_file: self.manifest = yaml.safe_load(input_file) if 'env' not in self.manifest: self.manifest['env'] = {} if 'servic...
[ "def", "read_manifest", "(", "self", ",", "encrypted", "=", "None", ")", ":", "with", "open", "(", "self", ".", "manifest_path", ",", "'r'", ")", "as", "input_file", ":", "self", ".", "manifest", "=", "yaml", ".", "safe_load", "(", "input_file", ")", "...
37.178571
18.392857
def get_links(html, outformat): """Return a list of reference links from the html. Parameters ---------- html : str outformat : int the output format of the citations Returns ------- List[str] the links to the references """ if outformat == FORMAT_BIBTEX: ...
[ "def", "get_links", "(", "html", ",", "outformat", ")", ":", "if", "outformat", "==", "FORMAT_BIBTEX", ":", "refre", "=", "re", ".", "compile", "(", "r'<a href=\"https://scholar.googleusercontent.com(/scholar\\.bib\\?[^\"]*)'", ")", "elif", "outformat", "==", "FORMAT_...
36.857143
24.25
def scheduleMeasurement(self, measurementId, duration, start): """ Schedules the requested measurement session with all INITIALISED devices. :param measurementId: :param duration: :param start: :return: a dict of device vs status. """ # TODO subtract 1s fr...
[ "def", "scheduleMeasurement", "(", "self", ",", "measurementId", ",", "duration", ",", "start", ")", ":", "# TODO subtract 1s from start and format", "results", "=", "{", "}", "for", "device", "in", "self", ".", "getDevices", "(", "RecordingDeviceStatus", ".", "IN...
50.227273
23.954545
def delete_customer(self, handle): """Delete a customer.""" self.request(E.deleteCustomerRequest(E.handle(handle))) return True
[ "def", "delete_customer", "(", "self", ",", "handle", ")", ":", "self", ".", "request", "(", "E", ".", "deleteCustomerRequest", "(", "E", ".", "handle", "(", "handle", ")", ")", ")", "return", "True" ]
24.666667
21.666667
def commit(self): """ Put the document into the new state. """ if self.after is None: # If this is the first 'commit' call then do not make # any changes but store the current document state. self.after = self.qteWidget.toHtml() else: ...
[ "def", "commit", "(", "self", ")", ":", "if", "self", ".", "after", "is", "None", ":", "# If this is the first 'commit' call then do not make", "# any changes but store the current document state.", "self", ".", "after", "=", "self", ".", "qteWidget", ".", "toHtml", "...
37.692308
12.461538
def _escape(s): """ Helper method that escapes parameters to a SQL query. """ e = s e = e.replace('\\', '\\\\') e = e.replace('\n', '\\n') e = e.replace('\r', '\\r') e = e.replace("'", "\\'") e = e.replace('"', '\\"') return e
[ "def", "_escape", "(", "s", ")", ":", "e", "=", "s", "e", "=", "e", ".", "replace", "(", "'\\\\'", ",", "'\\\\\\\\'", ")", "e", "=", "e", ".", "replace", "(", "'\\n'", ",", "'\\\\n'", ")", "e", "=", "e", ".", "replace", "(", "'\\r'", ",", "'\...
27.777778
15
def ConfigureRequest(self, upload_config, http_request, url_builder): """Configure the request and url for this upload.""" # Validate total_size vs. max_size if (self.total_size and upload_config.max_size and self.total_size > upload_config.max_size): raise exceptions...
[ "def", "ConfigureRequest", "(", "self", ",", "upload_config", ",", "http_request", ",", "url_builder", ")", ":", "# Validate total_size vs. max_size", "if", "(", "self", ".", "total_size", "and", "upload_config", ".", "max_size", "and", "self", ".", "total_size", ...
57.113636
22.795455
def output_kernels(gandi, flavor, name_list, justify=14): """ Helper to output kernel flavor versions.""" output_line(gandi, 'flavor', flavor, justify) for name in name_list: output_line(gandi, 'version', name, justify)
[ "def", "output_kernels", "(", "gandi", ",", "flavor", ",", "name_list", ",", "justify", "=", "14", ")", ":", "output_line", "(", "gandi", ",", "'flavor'", ",", "flavor", ",", "justify", ")", "for", "name", "in", "name_list", ":", "output_line", "(", "gan...
47
10.4
def generate_metimage_file(platform_name): """Retrieve original RSR data and convert to internal hdf5 format. """ import h5py bandnames = METIMAGE_BAND_NAMES instr = MetImageRSR(bandnames[0], platform_name) instr_name = instr.instrument.replace('/', '') filename = os.path.join(instr.output_...
[ "def", "generate_metimage_file", "(", "platform_name", ")", ":", "import", "h5py", "bandnames", "=", "METIMAGE_BAND_NAMES", "instr", "=", "MetImageRSR", "(", "bandnames", "[", "0", "]", ",", "platform_name", ")", "instr_name", "=", "instr", ".", "instrument", "....
43.609375
15.75
def query_search_api(min_lat, max_lat, min_lon, max_lon, max_results): ''' Send query to the search API and get dict with image data. ''' # Create URL params = urllib.urlencode(zip( ['client_id', 'bbox', 'per_page'], [CLIENT_ID, ','.join([str(min_lon), str(min_lat), str( ...
[ "def", "query_search_api", "(", "min_lat", ",", "max_lat", ",", "min_lon", ",", "max_lon", ",", "max_results", ")", ":", "# Create URL", "params", "=", "urllib", ".", "urlencode", "(", "zip", "(", "[", "'client_id'", ",", "'bbox'", ",", "'per_page'", "]", ...
33.631579
22.473684
def logfbank(signal,samplerate=16000,winlen=0.025,winstep=0.01, nfilt=26,nfft=512,lowfreq=0,highfreq=None,preemph=0.97, winfunc=lambda x:numpy.ones((x,))): """Compute log Mel-filterbank energy features from an audio signal. :param signal: the audio signal from which to compute feature...
[ "def", "logfbank", "(", "signal", ",", "samplerate", "=", "16000", ",", "winlen", "=", "0.025", ",", "winstep", "=", "0.01", ",", "nfilt", "=", "26", ",", "nfft", "=", "512", ",", "lowfreq", "=", "0", ",", "highfreq", "=", "None", ",", "preemph", "...
74.157895
39.947368
def init_from_files( vocab_file, files, target_vocab_size, threshold, min_count=None, file_byte_limit=1e6, reserved_tokens=None): """Create subtoken vocabulary based on files, and save vocab to file. Args: vocab_file: String name of vocab file to store subtoken vocabulary. files: List o...
[ "def", "init_from_files", "(", "vocab_file", ",", "files", ",", "target_vocab_size", ",", "threshold", ",", "min_count", "=", "None", ",", "file_byte_limit", "=", "1e6", ",", "reserved_tokens", "=", "None", ")", ":", "if", "reserved_tokens", "is", "None", ":",...
47.325
21.575
def getKwdArgs(self, flatten = False): """ Return a dict of all normal dict parameters - that is, all parameters NOT marked with "pos=N" in the .cfgspc file. This will also exclude all hidden parameters (metadata, rules, etc). """ # Start with a full deep-copy. What complicate...
[ "def", "getKwdArgs", "(", "self", ",", "flatten", "=", "False", ")", ":", "# Start with a full deep-copy. What complicates this method is the", "# idea of sub-sections. This dict can have dicts as values, and so on.", "dcopy", "=", "self", ".", "dict", "(", ")", "# ConfigObj ...
46.137931
22.827586
def getRloc(self): """get router locator unicast IPv6 address""" print '%s call getRloc' % self.port prefix = self.__stripValue(self.__sendCommand(WPANCTL_CMD + 'getprop -v IPv6:MeshLocalPrefix')[0]) mlprefix = prefix.split('/')[0] rloc16 = self.__sendCommand(WPANCTL_CMD + 'getpr...
[ "def", "getRloc", "(", "self", ")", ":", "print", "'%s call getRloc'", "%", "self", ".", "port", "prefix", "=", "self", ".", "__stripValue", "(", "self", ".", "__sendCommand", "(", "WPANCTL_CMD", "+", "'getprop -v IPv6:MeshLocalPrefix'", ")", "[", "0", "]", ...
43.769231
20
def on_change(self, value): '''Calles modifier on instance with passed value''' self._modifier(self.inst, self.prop, value)
[ "def", "on_change", "(", "self", ",", "value", ")", ":", "self", ".", "_modifier", "(", "self", ".", "inst", ",", "self", ".", "prop", ",", "value", ")" ]
45.666667
14.333333
def d2logpdf_dlink2(self, inv_link_f, y, Y_metadata=None): """ Hessian at y, given link(f), w.r.t link(f) i.e. second derivative logpdf at y given link(f_i) and link(f_j) w.r.t link(f_i) and link(f_j) The hessian will be 0 unless i == j .. math:: \\frac{d^{2} \\ln p...
[ "def", "d2logpdf_dlink2", "(", "self", ",", "inv_link_f", ",", "y", ",", "Y_metadata", "=", "None", ")", ":", "e", "=", "y", "-", "inv_link_f", "hess", "=", "(", "(", "self", ".", "v", "+", "1", ")", "*", "(", "e", "**", "2", "-", "self", ".", ...
48.833333
32.333333
def parse_compound(s, global_compartment=None): """Parse a compound specification. If no compartment is specified in the string, the global compartment will be used. """ m = re.match(r'^\|(.*)\|$', s) if m: s = m.group(1) m = re.match(r'^(.+)\[(\S+)\]$', s) if m: compou...
[ "def", "parse_compound", "(", "s", ",", "global_compartment", "=", "None", ")", ":", "m", "=", "re", ".", "match", "(", "r'^\\|(.*)\\|$'", ",", "s", ")", "if", "m", ":", "s", "=", "m", ".", "group", "(", "1", ")", "m", "=", "re", ".", "match", ...
25.631579
18.421053
def m_b(mbmb, scale, f, alphasMZ=0.1185, loop=3): r"""Get running b quark mass in the MSbar scheme at the scale `scale` in the theory with `f` dynamical quark flavours starting from $m_b(m_b)$""" if scale == mbmb and f == 5: return mbmb # nothing to do _sane(scale, f) alphas_mb = alpha_s(mb...
[ "def", "m_b", "(", "mbmb", ",", "scale", ",", "f", ",", "alphasMZ", "=", "0.1185", ",", "loop", "=", "3", ")", ":", "if", "scale", "==", "mbmb", "and", "f", "==", "5", ":", "return", "mbmb", "# nothing to do", "_sane", "(", "scale", ",", "f", ")"...
39.117647
18.529412
def load_data_with_word2vec(word2vec_list): """Loads and preprocessed data for the MR dataset. Returns input vectors, labels, vocabulary, and inverse vocabulary. """ # Load and preprocess data sentences, labels = load_data_and_labels() sentences_padded = pad_sentences(sentences) # vocabulary...
[ "def", "load_data_with_word2vec", "(", "word2vec_list", ")", ":", "# Load and preprocess data", "sentences", ",", "labels", "=", "load_data_and_labels", "(", ")", "sentences_padded", "=", "pad_sentences", "(", "sentences", ")", "# vocabulary, vocabulary_inv = build_vocab(sent...
49.222222
13.555556
def p_string_expr_lp(p): """ string : LP expr RP substr """ if p[2].type_ != TYPE.string: syntax_error(p.lexer.lineno, "Expected a string type expression. " "Got %s type instead" % TYPE.to_string(p[2].type_)) p[0] = None else: p[0] = make...
[ "def", "p_string_expr_lp", "(", "p", ")", ":", "if", "p", "[", "2", "]", ".", "type_", "!=", "TYPE", ".", "string", ":", "syntax_error", "(", "p", ".", "lexer", ".", "lineno", ",", "\"Expected a string type expression. \"", "\"Got %s type instead\"", "%", "T...
36
15.7
def store_archiver_index(config, archiver, index): """ Store an archiver's index record for faster search. :param config: The configuration :type config: :class:`wily.config.WilyConfig` :param archiver: The name of the archiver type (e.g. 'git') :type archiver: ``str`` :param index:...
[ "def", "store_archiver_index", "(", "config", ",", "archiver", ",", "index", ")", ":", "root", "=", "pathlib", ".", "Path", "(", "config", ".", "cache_path", ")", "/", "archiver", ".", "name", "if", "not", "root", ".", "exists", "(", ")", ":", "root", ...
28.142857
18.071429
def get_trans(self, out_vec=None): """Return the translation portion of the matrix as a vector. If out_vec is provided, store in out_vec instead of creating a new Vec3. """ if out_vec: return out_vec.set(*self.data[3][:3]) return Vec3(*self.data[3][:3])
[ "def", "get_trans", "(", "self", ",", "out_vec", "=", "None", ")", ":", "if", "out_vec", ":", "return", "out_vec", ".", "set", "(", "*", "self", ".", "data", "[", "3", "]", "[", ":", "3", "]", ")", "return", "Vec3", "(", "*", "self", ".", "data...
29.9
19.8
def savestate(self, state, chain=-1): """Store a dictionnary containing the state of the Model and its StepMethods.""" cur_chain = self._chains[chain] if hasattr(cur_chain, '_state_'): cur_chain._state_[0] = state else: s = self._h5file.create_vlarray( ...
[ "def", "savestate", "(", "self", ",", "state", ",", "chain", "=", "-", "1", ")", ":", "cur_chain", "=", "self", ".", "_chains", "[", "chain", "]", "if", "hasattr", "(", "cur_chain", ",", "'_state_'", ")", ":", "cur_chain", ".", "_state_", "[", "0", ...
36.2
7.466667
def print_results(results): """Print `results` (the results of validation) to stdout. Args: results: A list of FileValidationResults or ObjectValidationResults instances. """ if not isinstance(results, list): results = [results] for r in results: try: ...
[ "def", "print_results", "(", "results", ")", ":", "if", "not", "isinstance", "(", "results", ",", "list", ")", ":", "results", "=", "[", "results", "]", "for", "r", "in", "results", ":", "try", ":", "r", ".", "log", "(", ")", "except", "AttributeErro...
30
22.588235
def patch_get_deferred_fields(model): """ Django >= 1.8: patch detecting deferred fields. Crucial for only/defer to work. """ if not hasattr(model, 'get_deferred_fields'): return old_get_deferred_fields = model.get_deferred_fields def new_get_deferred_fields(self): sup = old_get...
[ "def", "patch_get_deferred_fields", "(", "model", ")", ":", "if", "not", "hasattr", "(", "model", ",", "'get_deferred_fields'", ")", ":", "return", "old_get_deferred_fields", "=", "model", ".", "get_deferred_fields", "def", "new_get_deferred_fields", "(", "self", ")...
36.142857
14.142857
def atomic(self, func): """A decorator that wraps a function in an atomic block. Example:: db = CustomSQLAlchemy() @db.atomic def f(): write_to_db('a message') return 'OK' assert f() == 'OK' This code defines the function `...
[ "def", "atomic", "(", "self", ",", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "session", "=", "self", ".", "session", "session_info", "=", "session", ".", "info", "if", ...
33.052632
20.438596
def convert_to_shape(self, origin_x=0, origin_y=0): """Return new freeform shape positioned relative to specified offset. *origin_x* and *origin_y* locate the origin of the local coordinate system in slide coordinates (EMU), perhaps most conveniently by use of a |Length| object. ...
[ "def", "convert_to_shape", "(", "self", ",", "origin_x", "=", "0", ",", "origin_y", "=", "0", ")", ":", "sp", "=", "self", ".", "_add_freeform_sp", "(", "origin_x", ",", "origin_y", ")", "path", "=", "self", ".", "_start_path", "(", "sp", ")", "for", ...
46.066667
18.6
def import_image_tags(self, name, tags, repository, insecure=False): """Import image tags from specified container repository. :param name: str, name of ImageStream object :param tags: iterable, tags to be imported :param repository: str, remote location of container image ...
[ "def", "import_image_tags", "(", "self", ",", "name", ",", "tags", ",", "repository", ",", "insecure", "=", "False", ")", ":", "stream_import_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "os_conf", ".", "get_build_json_store", "(", ")", ...
50.411765
20.058824
def unregister_controllers(self): """Destroy controller objects and clear internal registry. This will be called after each test class. """ # TODO(xpconanfan): actually record these errors instead of just # logging them. for name, module in self._controller_modules.items...
[ "def", "unregister_controllers", "(", "self", ")", ":", "# TODO(xpconanfan): actually record these errors instead of just", "# logging them.", "for", "name", ",", "module", "in", "self", ".", "_controller_modules", ".", "items", "(", ")", ":", "logging", ".", "debug", ...
45
14.785714
def init_app(self, app, env_file=None, verbose_mode=False): """Imports .env file.""" if self.app is None: self.app = app self.verbose_mode = verbose_mode if env_file is None: env_file = os.path.join(os.getcwd(), ".env") if not os.path.exists(env_file): ...
[ "def", "init_app", "(", "self", ",", "app", ",", "env_file", "=", "None", ",", "verbose_mode", "=", "False", ")", ":", "if", "self", ".", "app", "is", "None", ":", "self", ".", "app", "=", "app", "self", ".", "verbose_mode", "=", "verbose_mode", "if"...
36.75
14.916667
def mark_rewrite(self, *names): """Mark import names as needing to be re-written. The named module or package as well as any nested modules will be re-written on import. """ already_imported = set(names).intersection(set(sys.modules)) if already_imported: for...
[ "def", "mark_rewrite", "(", "self", ",", "*", "names", ")", ":", "already_imported", "=", "set", "(", "names", ")", ".", "intersection", "(", "set", "(", "sys", ".", "modules", ")", ")", "if", "already_imported", ":", "for", "name", "in", "already_import...
40.333333
12.833333
def get_field_list(fields, schema): """ Convert a field list spec into a real list of field names. For tables, we return only the top-level non-RECORD fields as Google charts can't handle nested data. """ # If the fields weren't supplied get them from the schema. if schema: all_fields = [f['nam...
[ "def", "get_field_list", "(", "fields", ",", "schema", ")", ":", "# If the fields weren't supplied get them from the schema.", "if", "schema", ":", "all_fields", "=", "[", "f", "[", "'name'", "]", "for", "f", "in", "schema", ".", "_bq_schema", "if", "f", "[", ...
32.888889
19.518519
def GetUnreachableHosts(hostnames, ssh_key): """ Returns list of hosts unreachable via ssh. """ ssh_status = AreHostsReachable(hostnames, ssh_key) assert(len(hostnames) == len(ssh_status)) nonresponsive_hostnames = [host for (host, ssh_ok) in zip(hostnames, ssh_status) if not ssh_ok...
[ "def", "GetUnreachableHosts", "(", "hostnames", ",", "ssh_key", ")", ":", "ssh_status", "=", "AreHostsReachable", "(", "hostnames", ",", "ssh_key", ")", "assert", "(", "len", "(", "hostnames", ")", "==", "len", "(", "ssh_status", ")", ")", "nonresponsive_hostn...
49.714286
10.285714
def init_app(self, app, **kwargs): """ Initializes the Flask-Bouncer extension for the specified application. :param app: The application. """ self.app = app self._init_extension() self.app.before_request(self.check_implicit_rules) if kwargs.get('ensure_author...
[ "def", "init_app", "(", "self", ",", "app", ",", "*", "*", "kwargs", ")", ":", "self", ".", "app", "=", "app", "self", ".", "_init_extension", "(", ")", "self", ".", "app", ".", "before_request", "(", "self", ".", "check_implicit_rules", ")", "if", "...
29.692308
19.153846
def get_logs(self): """ print logs from pod :return: str or None """ try: api_response = self.core_api.read_namespaced_pod_log(self.name, self.namespace) logger.debug("Logs from pod: %s in namespace: %s", self.name, self.namespace) for line in ...
[ "def", "get_logs", "(", "self", ")", ":", "try", ":", "api_response", "=", "self", ".", "core_api", ".", "read_namespaced_pod_log", "(", "self", ".", "name", ",", "self", ".", "namespace", ")", "logger", ".", "debug", "(", "\"Logs from pod: %s in namespace: %s...
39.647059
21.529412
def postinit(self, exc=None, cause=None): """Do some setup after initialisation. :param exc: What is being raised. :type exc: NodeNG or None :param cause: The exception being used to raise this one. :type cause: NodeNG or None """ self.exc = exc self.cau...
[ "def", "postinit", "(", "self", ",", "exc", "=", "None", ",", "cause", "=", "None", ")", ":", "self", ".", "exc", "=", "exc", "self", ".", "cause", "=", "cause" ]
29.090909
13.727273
def matchmaker_matches(institute_id, case_name): """Show all MatchMaker matches for a given case""" # check that only authorized users can access MME patients matches user_obj = store.user(current_user.email) if 'mme_submitter' not in user_obj['roles']: flash('unauthorized request', 'warning') ...
[ "def", "matchmaker_matches", "(", "institute_id", ",", "case_name", ")", ":", "# check that only authorized users can access MME patients matches", "user_obj", "=", "store", ".", "user", "(", "current_user", ".", "email", ")", "if", "'mme_submitter'", "not", "in", "user...
48.958333
17.791667
def _is_robot(): """ Return `True` if the current visitor is a robot or spider, or `False` otherwise. This function works by comparing the request's user agent with a regular expression. The regular expression can be configured with the ``SPLIT_ROBOT_REGEX`` setting. """ robot_regex = ...
[ "def", "_is_robot", "(", ")", ":", "robot_regex", "=", "current_app", ".", "config", "[", "'SPLIT_ROBOT_REGEX'", "]", "user_agent", "=", "request", ".", "headers", ".", "get", "(", "'User-Agent'", ",", "''", ")", "return", "re", ".", "search", "(", "robot_...
38.916667
19.083333
def delete_db_entry(self, release): """Delete the db entries for releasefile and comment of the given release :param release: the release with the releasefile and comment db entries :type release: :class:`Release` :returns: an action status :rtype: :class:`ActionStatus` ...
[ "def", "delete_db_entry", "(", "self", ",", "release", ")", ":", "log", ".", "info", "(", "\"Delete database entry for file.\"", ")", "release", ".", "_releasedbentry", ".", "delete", "(", ")", "log", ".", "info", "(", "\"Delete database entry for comment.\"", ")"...
43.866667
12.933333
def log_stats(self): """Output the stats to the LOGGER.""" if not self.stats.get('counts'): if self.consumers: LOGGER.info('Did not receive any stats data from children') return if self.poll_data['processes']: LOGGER.warning('%i process(es) di...
[ "def", "log_stats", "(", "self", ")", ":", "if", "not", "self", ".", "stats", ".", "get", "(", "'counts'", ")", ":", "if", "self", ".", "consumers", ":", "LOGGER", ".", "info", "(", "'Did not receive any stats data from children'", ")", "return", "if", "se...
47.958333
22.166667
def normaliseWV(wV, normFac=1.0): """ make char probs divisible by one """ f = sum(wV) / normFac return [ i/f for i in wV ]
[ "def", "normaliseWV", "(", "wV", ",", "normFac", "=", "1.0", ")", ":", "f", "=", "sum", "(", "wV", ")", "/", "normFac", "return", "[", "i", "/", "f", "for", "i", "in", "wV", "]" ]
23
6
def dn(self, fraction, n=None): r'''Computes the diameter at which a specified `fraction` of the distribution falls under. Utilizes a bounded solver to search for the desired diameter. Parameters ---------- fraction : float Fraction of the distribution which...
[ "def", "dn", "(", "self", ",", "fraction", ",", "n", "=", "None", ")", ":", "if", "fraction", "==", "1.0", ":", "# Avoid returning the maximum value of the search interval", "fraction", "=", "1.0", "-", "epsilon", "if", "fraction", "<", "0", ":", "raise", "V...
37.448276
20.931034
def to_tuple(param, low=None, bias=None): """Convert input argument to min-max tuple Args: param (scalar, tuple or list of 2+ elements): Input value. If value is scalar, return value would be (offset - value, offset + value). If value is tuple, return value would be value + offse...
[ "def", "to_tuple", "(", "param", ",", "low", "=", "None", ",", "bias", "=", "None", ")", ":", "if", "low", "is", "not", "None", "and", "bias", "is", "not", "None", ":", "raise", "ValueError", "(", "'Arguments low and bias are mutually exclusive'", ")", "if...
36.344828
21.758621
def _submit(self, client, config, osutil, request_executor, io_executor, transfer_future, bandwidth_limiter=None): """ :param client: The client associated with the transfer manager :type config: s3transfer.manager.TransferConfig :param config: The transfer config associ...
[ "def", "_submit", "(", "self", ",", "client", ",", "config", ",", "osutil", ",", "request_executor", ",", "io_executor", ",", "transfer_future", ",", "bandwidth_limiter", "=", "None", ")", ":", "if", "transfer_future", ".", "meta", ".", "size", "is", "None",...
45.226415
23.264151
def write_sources_file(): """Write a sources.yaml file to current working dir.""" file_content = ( 'schemes: ' 'https://github.com/chriskempson/base16-schemes-source.git\n' 'templates: ' 'https://github.com/chriskempson/base16-templates-source.git' ) file_path = rel_to_cw...
[ "def", "write_sources_file", "(", ")", ":", "file_content", "=", "(", "'schemes: '", "'https://github.com/chriskempson/base16-schemes-source.git\\n'", "'templates: '", "'https://github.com/chriskempson/base16-templates-source.git'", ")", "file_path", "=", "rel_to_cwd", "(", "'sourc...
36.454545
16.181818
def get_new_document(self, cursor_pos=None): """ Create a `Document` instance that contains the resulting text. """ lines = [] # Original text, before cursor. if self.original_document.text_before_cursor: lines.append(self.original_document.text_before_cursor...
[ "def", "get_new_document", "(", "self", ",", "cursor_pos", "=", "None", ")", ":", "lines", "=", "[", "]", "# Original text, before cursor.", "if", "self", ".", "original_document", ".", "text_before_cursor", ":", "lines", ".", "append", "(", "self", ".", "orig...
36.782609
16.695652
def instruction_ASR_memory(self, opcode, ea, m): """ Arithmetic shift memory right """ r = self.ASR(m) # log.debug("$%x ASR memory value $%x >> 1 | Carry = $%x and write it to $%x \t| %s" % ( # self.program_counter, # m, r, ea, # self.cfg.mem_info.get_shortest(ea)...
[ "def", "instruction_ASR_memory", "(", "self", ",", "opcode", ",", "ea", ",", "m", ")", ":", "r", "=", "self", ".", "ASR", "(", "m", ")", "# log.debug(\"$%x ASR memory value $%x >> 1 | Carry = $%x and write it to $%x \\t| %s\" % (", "# self.program_counter,...
39.111111
17
def bytes2human(n, format="%(value).1f%(symbol)s"): """ >>> bytes2human(10000) '9K' >>> bytes2human(100001221) '95M' """ symbols = ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') prefix = {} for i, s in enumerate(symbols[1:]): prefix[s] = 1 << (i + 1) * 10 for symbol in rev...
[ "def", "bytes2human", "(", "n", ",", "format", "=", "\"%(value).1f%(symbol)s\"", ")", ":", "symbols", "=", "(", "'B'", ",", "'K'", ",", "'M'", ",", "'G'", ",", "'T'", ",", "'P'", ",", "'E'", ",", "'Z'", ",", "'Y'", ")", "prefix", "=", "{", "}", "...
30.75
11
def analyze(self): """Return a list giving the parameters required by a query.""" class MockBindings(dict): def __contains__(self, key): self[key] = None return True bindings = MockBindings() used = {} ancestor = self.ancestor if isinstance(ancestor, ParameterizedThing): ...
[ "def", "analyze", "(", "self", ")", ":", "class", "MockBindings", "(", "dict", ")", ":", "def", "__contains__", "(", "self", ",", "key", ")", ":", "self", "[", "key", "]", "=", "None", "return", "True", "bindings", "=", "MockBindings", "(", ")", "use...
30
14.625
def apparent_temp(temp, rh, wind): """Compute apparent temperature (real feel), using formula from http://www.bom.gov.au/info/thermal_stress/ """ if temp is None or rh is None or wind is None: return None vap_press = (float(rh) / 100.0) * 6.105 * math.exp( 17.27 * temp / (237.7 + te...
[ "def", "apparent_temp", "(", "temp", ",", "rh", ",", "wind", ")", ":", "if", "temp", "is", "None", "or", "rh", "is", "None", "or", "wind", "is", "None", ":", "return", "None", "vap_press", "=", "(", "float", "(", "rh", ")", "/", "100.0", ")", "*"...
37.5
11.9
def addClass(self, alias, klass): """ Creates a reference to C{class_def}. @param alias: C{ClassDefinition} instance. """ ref = self.class_idx self.class_ref[ref] = alias cd = self.classes[klass] = alias cd.reference = ref self.class_idx += 1 ...
[ "def", "addClass", "(", "self", ",", "alias", ",", "klass", ")", ":", "ref", "=", "self", ".", "class_idx", "self", ".", "class_ref", "[", "ref", "]", "=", "alias", "cd", "=", "self", ".", "classes", "[", "klass", "]", "=", "alias", "cd", ".", "r...
20.1875
17.9375
def insert_before(self, parent, sibling, row=None): """insert_before(parent, sibling, row=None) :param parent: A valid :obj:`Gtk.TreeIter`, or :obj:`None` :type parent: :obj:`Gtk.TreeIter` or :obj:`None` :param sibling: A valid :obj:`Gtk.TreeIter`, or :obj:`None` :type sibling:...
[ "def", "insert_before", "(", "self", ",", "parent", ",", "sibling", ",", "row", "=", "None", ")", ":", "treeiter", "=", "Gtk", ".", "TreeStore", ".", "insert_before", "(", "self", ",", "parent", ",", "sibling", ")", "if", "row", "is", "not", "None", ...
40.621622
26.513514
def list_releases(): """ Lists all releases published on pypi. """ response = requests.get(PYPI_URL.format(package=PYPI_PACKAGE_NAME)) if response: data = response.json() releases_dict = data.get('releases', {}) if releases_dict: for version, release in releases_dict.it...
[ "def", "list_releases", "(", ")", ":", "response", "=", "requests", ".", "get", "(", "PYPI_URL", ".", "format", "(", "package", "=", "PYPI_PACKAGE_NAME", ")", ")", "if", "response", ":", "data", "=", "response", ".", "json", "(", ")", "releases_dict", "=...
40.090909
22.954545
def register_code_edit(cls, code_edit_class): """ Register an additional code edit **class** .. warning: This method expect a class, not an instance! :param code_edit_class: code edit class to register. """ if not inspect.isclass(code_edit_class): raise Type...
[ "def", "register_code_edit", "(", "cls", ",", "code_edit_class", ")", ":", "if", "not", "inspect", ".", "isclass", "(", "code_edit_class", ")", ":", "raise", "TypeError", "(", "'must be a class, not an instance.'", ")", "for", "mimetype", "in", "code_edit_class", ...
41.9375
15.6875
def tenengrad(img, ksize=3): ''''TENG' algorithm (Krotkov86)''' Gx = cv2.Sobel(img, ddepth=cv2.CV_64F, dx=1, dy=0, ksize=ksize) Gy = cv2.Sobel(img, ddepth=cv2.CV_64F, dx=0, dy=1, ksize=ksize) FM = Gx*Gx + Gy*Gy mn = cv2.mean(FM)[0] if np.isnan(mn): return np.nanmean(FM) retur...
[ "def", "tenengrad", "(", "img", ",", "ksize", "=", "3", ")", ":", "Gx", "=", "cv2", ".", "Sobel", "(", "img", ",", "ddepth", "=", "cv2", ".", "CV_64F", ",", "dx", "=", "1", ",", "dy", "=", "0", ",", "ksize", "=", "ksize", ")", "Gy", "=", "c...
35.111111
17.333333
def erase_hardware_breakpoint(self, dwThreadId, address): """ Erases the hardware breakpoint at the given address. @see: L{define_hardware_breakpoint}, L{has_hardware_breakpoint}, L{get_hardware_breakpoint}, L{enable_hardware_breakpoint}, ...
[ "def", "erase_hardware_breakpoint", "(", "self", ",", "dwThreadId", ",", "address", ")", ":", "bp", "=", "self", ".", "get_hardware_breakpoint", "(", "dwThreadId", ",", "address", ")", "if", "not", "bp", ".", "is_disabled", "(", ")", ":", "self", ".", "dis...
34.2
13.72
async def get_all_tracks(self) -> List[PlaylistTrack]: """Get all playlist tracks from the playlist. Returns ------- tracks : List[PlaylistTrack] The playlists tracks. """ if isinstance(self._tracks, PartialTracks): return await self._tracks.build...
[ "async", "def", "get_all_tracks", "(", "self", ")", "->", "List", "[", "PlaylistTrack", "]", ":", "if", "isinstance", "(", "self", ".", "_tracks", ",", "PartialTracks", ")", ":", "return", "await", "self", ".", "_tracks", ".", "build", "(", ")", "_tracks...
33.380952
21.380952
def layer(self, layer_name): """Get QGIS layer. :param layer_name: The name of the layer to fetch. :type layer_name: str :return: The QGIS layer. :rtype: QgsMapLayer .. versionadded:: 4.0 """ uri = self.layer_uri(layer_name) layer = QgsVectorLay...
[ "def", "layer", "(", "self", ",", "layer_name", ")", ":", "uri", "=", "self", ".", "layer_uri", "(", "layer_name", ")", "layer", "=", "QgsVectorLayer", "(", "uri", ",", "layer_name", ",", "'ogr'", ")", "if", "not", "layer", ".", "isValid", "(", ")", ...
25.47619
16.571429
def get_default_config(self): """ Returns the default collector settings """ config = super(OpenVPNCollector, self).get_default_config() config.update({ 'path': 'openvpn', 'instances': 'file:///var/log/openvpn/status.log', 'timeout': '10...
[ "def", "get_default_config", "(", "self", ")", ":", "config", "=", "super", "(", "OpenVPNCollector", ",", "self", ")", ".", "get_default_config", "(", ")", "config", ".", "update", "(", "{", "'path'", ":", "'openvpn'", ",", "'instances'", ":", "'file:///var/...
31.363636
13.363636
def get_available_networks(self, **kwargs): """ Retrieves the list of Ethernet networks, Fiber Channel networks, and network sets that are available to a server profile, along with their respective ports. Args: enclosureGroupUri (str): The URI of the enclosure group associate...
[ "def", "get_available_networks", "(", "self", ",", "*", "*", "kwargs", ")", ":", "uri", "=", "self", ".", "_helper", ".", "build_uri_with_query_string", "(", "kwargs", ",", "'/available-networks'", ")", "return", "self", ".", "_helper", ".", "do_get", "(", "...
58.896552
35.724138
def _configure_users(self, site=None, full=0, only_data=0): """ Installs and configures RabbitMQ. """ site = site or ALL full = int(full) if full and not only_data: packager = self.get_satchel('packager') packager.install_required(type=SYSTEM, s...
[ "def", "_configure_users", "(", "self", ",", "site", "=", "None", ",", "full", "=", "0", ",", "only_data", "=", "0", ")", ":", "site", "=", "site", "or", "ALL", "full", "=", "int", "(", "full", ")", "if", "full", "and", "not", "only_data", ":", "...
35.454545
22.121212
def throw_random_intervals( lengths, regions, save_interval_func=None, allow_overlap=False ): """ Generates a set of non-overlapping random intervals from a length distribution. `lengths`: list containing the length of each interval to be generated. We expect this to be sorted by de...
[ "def", "throw_random_intervals", "(", "lengths", ",", "regions", ",", "save_interval_func", "=", "None", ",", "allow_overlap", "=", "False", ")", ":", "# Copy regions", "regions", "=", "[", "(", "x", "[", "1", "]", "-", "x", "[", "0", "]", ",", "x", "[...
50.147059
27.264706
def from_filename(file_name): """ Look up the BioPython file type corresponding to an input file name. """ base, extension = os.path.splitext(file_name) if extension in COMPRESS_EXT: # Compressed file extension = os.path.splitext(base)[1] return from_extension(extension)
[ "def", "from_filename", "(", "file_name", ")", ":", "base", ",", "extension", "=", "os", ".", "path", ".", "splitext", "(", "file_name", ")", "if", "extension", "in", "COMPRESS_EXT", ":", "# Compressed file", "extension", "=", "os", ".", "path", ".", "spli...
33.666667
9.222222
def http_post(url, data=None, opt=opt_default): """ Shortcut for urlopen (POST) + read. We'll probably want to add a nice timeout here later too. """ return _http_request(url, method='POST', data=_marshalled(data), opt=opt)
[ "def", "http_post", "(", "url", ",", "data", "=", "None", ",", "opt", "=", "opt_default", ")", ":", "return", "_http_request", "(", "url", ",", "method", "=", "'POST'", ",", "data", "=", "_marshalled", "(", "data", ")", ",", "opt", "=", "opt", ")" ]
39.666667
13.333333
def e161(number, alphabet=PHONE_E161_ALPHABET): ''' Printable a 26 Latin letters (A to Z) phone number to the 12-key telephone keypad number. :param number: string :param alphabet: dict >>> print(e161('0800-PIZZA123')) 080074992123 >>> e161('0800^PIZZA123') Traceback (most recent c...
[ "def", "e161", "(", "number", ",", "alphabet", "=", "PHONE_E161_ALPHABET", ")", ":", "digits", "=", "[", "]", "for", "char", "in", "strip", "(", "number", ",", "'+-. ()'", ")", ".", "lower", "(", ")", ":", "length", "=", "len", "(", "digits", ")", ...
26.903226
20.709677
def run(self): """Starts the blotter Connects to the TWS/GW, processes and logs market data, and broadcast it over TCP via ZeroMQ (which algo subscribe to) """ self._check_unique_blotter() # connect to mysql self.mysql_connect() self.context = zmq.Cont...
[ "def", "run", "(", "self", ")", ":", "self", ".", "_check_unique_blotter", "(", ")", "# connect to mysql", "self", ".", "mysql_connect", "(", ")", "self", ".", "context", "=", "zmq", ".", "Context", "(", "zmq", ".", "REP", ")", "self", ".", "socket", "...
42.15942
21.782609
def _save_group(self, group_id, result): """Store the result of an executed group.""" self.TaskSetModel._default_manager.store_result(group_id, result) return result
[ "def", "_save_group", "(", "self", ",", "group_id", ",", "result", ")", ":", "self", ".", "TaskSetModel", ".", "_default_manager", ".", "store_result", "(", "group_id", ",", "result", ")", "return", "result" ]
46.5
13
def where_cross(data,threshold): """return a list of Is where the data first crosses above threshold.""" Is=np.where(data>threshold)[0] Is=np.concatenate(([0],Is)) Ds=Is[:-1]-Is[1:]+1 return Is[np.where(Ds)[0]+1]
[ "def", "where_cross", "(", "data", ",", "threshold", ")", ":", "Is", "=", "np", ".", "where", "(", "data", ">", "threshold", ")", "[", "0", "]", "Is", "=", "np", ".", "concatenate", "(", "(", "[", "0", "]", ",", "Is", ")", ")", "Ds", "=", "Is...
37.833333
8
def process_raw_data(cls, raw_data): """Create a new model using raw API response.""" properties = raw_data["properties"] ip_configurations = [] for raw_content in properties.get("ipConfigurations", []): resource = Resource.from_raw_data(raw_content) ip_configura...
[ "def", "process_raw_data", "(", "cls", ",", "raw_data", ")", ":", "properties", "=", "raw_data", "[", "\"properties\"", "]", "ip_configurations", "=", "[", "]", "for", "raw_content", "in", "properties", ".", "get", "(", "\"ipConfigurations\"", ",", "[", "]", ...
40.909091
19.090909
def quote_single_identifier(self, string): """ Quotes a single identifier (no dot chain separation). :param string: The identifier name to be quoted. :type string: str :return: The quoted identifier string. :rtype: str """ c = self.get_identifier_quote_c...
[ "def", "quote_single_identifier", "(", "self", ",", "string", ")", ":", "c", "=", "self", ".", "get_identifier_quote_character", "(", ")", "return", "\"%s%s%s\"", "%", "(", "c", ",", "string", ".", "replace", "(", "c", ",", "c", "+", "c", ")", ",", "c"...
29.076923
17.538462
def parse_dom(self): """Parse xml information in :attr:`data` and return. Returns: dict: Parsed xml data. An empty dictionary when content is blank. """ if self.dom is None: return {} else: domain = {} for child in self.dom: ...
[ "def", "parse_dom", "(", "self", ")", ":", "if", "self", ".", "dom", "is", "None", ":", "return", "{", "}", "else", ":", "domain", "=", "{", "}", "for", "child", "in", "self", ".", "dom", ":", "if", "len", "(", "child", ")", "==", "0", ":", "...
29.411765
18.647059
def DeleteOldCronJobRuns(self, cutoff_timestamp, cursor=None): """Deletes cron job runs that are older then the given timestamp.""" query = "DELETE FROM cron_job_runs WHERE write_time < FROM_UNIXTIME(%s)" cursor.execute(query, [mysql_utils.RDFDatetimeToTimestamp(cutoff_timestamp)])
[ "def", "DeleteOldCronJobRuns", "(", "self", ",", "cutoff_timestamp", ",", "cursor", "=", "None", ")", ":", "query", "=", "\"DELETE FROM cron_job_runs WHERE write_time < FROM_UNIXTIME(%s)\"", "cursor", ".", "execute", "(", "query", ",", "[", "mysql_utils", ".", "RDFDat...
61.8
21.4
def get_shared_files_from_shake(self, shake_id=None, before=None, after=None): """ Returns a list of SharedFile objects from a particular shake. Args: shake_id (int): Shake fr...
[ "def", "get_shared_files_from_shake", "(", "self", ",", "shake_id", "=", "None", ",", "before", "=", "None", ",", "after", "=", "None", ")", ":", "if", "before", "and", "after", ":", "raise", "Exception", "(", "\"You cannot specify both before and after keys\"", ...
36.9375
22.375
def save(self, block_id, consensus_hash, ops_hash, accepted_ops, virtualchain_ops_hints, backup=False): """ Write out all state to the working directory. Calls the implementation's 'db_save' method to store any state for this block. Calls the implementation's 'db_continue' method at the ...
[ "def", "save", "(", "self", ",", "block_id", ",", "consensus_hash", ",", "ops_hash", ",", "accepted_ops", ",", "virtualchain_ops_hints", ",", "backup", "=", "False", ")", ":", "assert", "self", ".", "setup", ",", "\"Not set up yet. Call .db_setup() first!\"", "as...
39.704082
21.357143
def get_history(self): """Return history parameters carried by the stanza. :returntype: `HistoryParameters`""" for child in xml_element_iter(self.xmlnode.children): if get_node_ns_uri(child) == MUC_NS and child.name == "history": maxchars = from_utf8(child.prop("maxc...
[ "def", "get_history", "(", "self", ")", ":", "for", "child", "in", "xml_element_iter", "(", "self", ".", "xmlnode", ".", "children", ")", ":", "if", "get_node_ns_uri", "(", "child", ")", "==", "MUC_NS", "and", "child", ".", "name", "==", "\"history\"", "...
49.888889
16.444444
def _insert_breaklines(self): """Inserts a breakline instead of a trailing space if the chunk is in CJK. """ target_chunks = ChunkList() for chunk in self: if chunk.word[-1] == ' ' and chunk.has_cjk(): chunk.word = chunk.word[:-1] target_chunks.append(chunk) target_chunks.a...
[ "def", "_insert_breaklines", "(", "self", ")", ":", "target_chunks", "=", "ChunkList", "(", ")", "for", "chunk", "in", "self", ":", "if", "chunk", ".", "word", "[", "-", "1", "]", "==", "' '", "and", "chunk", ".", "has_cjk", "(", ")", ":", "chunk", ...
34.25
9.166667
def _read_text(self, filename): """ Helper that reads the UTF-8 content of the specified file, or None if the file doesn't exist. This returns a unicode string. """ with io.open(filename, 'rt', encoding='utf-8') as f: return f.read()
[ "def", "_read_text", "(", "self", ",", "filename", ")", ":", "with", "io", ".", "open", "(", "filename", ",", "'rt'", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")" ]
39.857143
14.428571
def restrict_bond_dict(self, bond_dict): """Restrict a bond dictionary to self. Args: bond_dict (dict): Look into :meth:`~chemcoord.Cartesian.get_bonds`, to see examples for a bond_dict. Returns: bond dictionary """ return {j: bond_dict[j...
[ "def", "restrict_bond_dict", "(", "self", ",", "bond_dict", ")", ":", "return", "{", "j", ":", "bond_dict", "[", "j", "]", "&", "set", "(", "self", ".", "index", ")", "for", "j", "in", "self", ".", "index", "}" ]
31.818182
20.090909
def config(): ''' Display fault manager configuration CLI Example: .. code-block:: bash salt '*' fmadm.config ''' ret = {} fmadm = _check_fmadm() cmd = '{cmd} config'.format( cmd=fmadm ) res = __salt__['cmd.run_all'](cmd) retcode = res['retcode'] result...
[ "def", "config", "(", ")", ":", "ret", "=", "{", "}", "fmadm", "=", "_check_fmadm", "(", ")", "cmd", "=", "'{cmd} config'", ".", "format", "(", "cmd", "=", "fmadm", ")", "res", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "cmd", ")", "retcode", ...
19.208333
23.041667
def create_group(self, title, parent=None, icon=1, expires=None): """ This method creates a new group. A group title is needed or no group will be created. If a parent is given, the group will be created as a sub-group. title must be a string, image an unsigned int >0 and pare...
[ "def", "create_group", "(", "self", ",", "title", ",", "parent", "=", "None", ",", "icon", "=", "1", ",", "expires", "=", "None", ")", ":", "if", "parent", "and", "not", "isinstance", "(", "parent", ",", "Group", ")", ":", "raise", "TypeError", "(", ...
35.6
19.2
def print_maps(map_type=None, number=None): """ Print maps by type and/or number of defined colors. Parameters ---------- map_type : {'Sequential', 'Diverging', 'Qualitative'}, optional Filter output by map type. By default all maps are printed. number : int, optional Filter out...
[ "def", "print_maps", "(", "map_type", "=", "None", ",", "number", "=", "None", ")", ":", "if", "not", "map_type", "and", "not", "number", ":", "print_all_maps", "(", ")", "elif", "map_type", ":", "print_maps_by_type", "(", "map_type", ",", "number", ")", ...
28.652174
19.695652
def token(self): '''Attempt to return the auth header token. :return: token related to request ''' auth_header = self.headers.get('Authorization', '') if 'Token ' in auth_header: return auth_header.partition('Token ')[-1] else: return auth_header
[ "def", "token", "(", "self", ")", ":", "auth_header", "=", "self", ".", "headers", ".", "get", "(", "'Authorization'", ",", "''", ")", "if", "'Token '", "in", "auth_header", ":", "return", "auth_header", ".", "partition", "(", "'Token '", ")", "[", "-", ...
31
18
def clean_list_of_twitter_list(list_of_twitter_lists, sent_tokenize, _treebank_word_tokenize, tagger, lemmatizer, lemmatize, stopset, first_cap_re, all_cap_re, digits_punctuation_whitespace_re, po...
[ "def", "clean_list_of_twitter_list", "(", "list_of_twitter_lists", ",", "sent_tokenize", ",", "_treebank_word_tokenize", ",", "tagger", ",", "lemmatizer", ",", "lemmatize", ",", "stopset", ",", "first_cap_re", ",", "all_cap_re", ",", "digits_punctuation_whitespace_re", ",...
56.46875
31.46875
def read(self): """ Read a given file path and return its content. :return: The content of the given file path. :rtype: str """ try: with open(self.file, "r", encoding="utf-8") as file: # We open and read a file. # We get the...
[ "def", "read", "(", "self", ")", ":", "try", ":", "with", "open", "(", "self", ".", "file", ",", "\"r\"", ",", "encoding", "=", "\"utf-8\"", ")", "as", "file", ":", "# We open and read a file.", "# We get the file content.", "funilrys", "=", "file", ".", "...
27.913043
16.347826
def get_absorbing_atom_symbol_index(absorbing_atom, structure): """ Return the absorbing atom symboll and site index in the given structure. Args: absorbing_atom (str/int): symbol or site index structure (Structure) Returns: str, int: symbol and site index """ if isinst...
[ "def", "get_absorbing_atom_symbol_index", "(", "absorbing_atom", ",", "structure", ")", ":", "if", "isinstance", "(", "absorbing_atom", ",", "str", ")", ":", "return", "absorbing_atom", ",", "structure", ".", "indices_from_symbol", "(", "absorbing_atom", ")", "[", ...
36.294118
21.705882
def dump(self): """Dump the cache (for debugging)""" for key in self._store.keys(): print(key, ':', self.get(key))
[ "def", "dump", "(", "self", ")", ":", "for", "key", "in", "self", ".", "_store", ".", "keys", "(", ")", ":", "print", "(", "key", ",", "':'", ",", "self", ".", "get", "(", "key", ")", ")" ]
34.75
7.25
def get_app_n_model(settings_entry_name): """Returns tuple with application and tree[item] model class names. :param str|unicode settings_entry_name: :rtype: tuple """ try: app_name, model_name = getattr(settings, settings_entry_name).split('.') except ValueError: raise Improper...
[ "def", "get_app_n_model", "(", "settings_entry_name", ")", ":", "try", ":", "app_name", ",", "model_name", "=", "getattr", "(", "settings", ",", "settings_entry_name", ")", ".", "split", "(", "'.'", ")", "except", "ValueError", ":", "raise", "ImproperlyConfigure...
38.333333
19.666667
def private_encrypt(key, message): ''' Generate an M2Crypto-compatible signature :param Crypto.PublicKey.RSA._RSAobj key: The RSA key object :param str message: The message to sign :rtype: str :return: The signature, or an empty string if the signature operation failed ''' if HAS_M2: ...
[ "def", "private_encrypt", "(", "key", ",", "message", ")", ":", "if", "HAS_M2", ":", "return", "key", ".", "private_encrypt", "(", "message", ",", "salt", ".", "utils", ".", "rsax931", ".", "RSA_X931_PADDING", ")", "else", ":", "signer", "=", "salt", "."...
35.928571
24.357143
def p_file_chk_sum(self, f_term, predicate): """Sets file checksum. Assumes SHA1 algorithm without checking.""" try: for _s, _p, checksum in self.graph.triples((f_term, predicate, None)): for _, _, value in self.graph.triples((checksum, self.spdx_namespace['checksumValue'], N...
[ "def", "p_file_chk_sum", "(", "self", ",", "f_term", ",", "predicate", ")", ":", "try", ":", "for", "_s", ",", "_p", ",", "checksum", "in", "self", ".", "graph", ".", "triples", "(", "(", "f_term", ",", "predicate", ",", "None", ")", ")", ":", "for...
60.875
25.625
def update(self, id): """PUT /layertemplates/id: Update an existing item.""" # url('LayerTemplates', id=ID) lt = meta.Session.query(LayerTemplate).get(id) # use following query for getting a layertemplate owned by current user #lt = self._get_lt_from_user_by_id(c.user, id) ...
[ "def", "update", "(", "self", ",", "id", ")", ":", "# url('LayerTemplates', id=ID)", "lt", "=", "meta", ".", "Session", ".", "query", "(", "LayerTemplate", ")", ".", "get", "(", "id", ")", "# use following query for getting a layertemplate owned by current user", "#...
43.625
14
def factor_cmap(field_name, palette, factors, start=0, end=None, nan_color="gray"): ''' Create a ``DataSpec`` dict that applies a client-side ``CategoricalColorMapper`` transformation to a ``ColumnDataSource`` column. Args: field_name (str) : a field name to configure ``DataSpec`` with ...
[ "def", "factor_cmap", "(", "field_name", ",", "palette", ",", "factors", ",", "start", "=", "0", ",", "end", "=", "None", ",", "nan_color", "=", "\"gray\"", ")", ":", "return", "field", "(", "field_name", ",", "CategoricalColorMapper", "(", "palette", "=",...
40.451613
31.806452
def train_batch(self, batch_info: BatchInfo): """ Single, most atomic 'step' of learning this reinforcer can perform """ batch_info['sub_batch_data'] = [] self.on_policy_train_batch(batch_info) if self.settings.experience_replay > 0 and self.env_roller.is_ready_for_sampling(): ...
[ "def", "train_batch", "(", "self", ",", "batch_info", ":", "BatchInfo", ")", ":", "batch_info", "[", "'sub_batch_data'", "]", "=", "[", "]", "self", ".", "on_policy_train_batch", "(", "batch_info", ")", "if", "self", ".", "settings", ".", "experience_replay", ...
46.705882
25.764706
def make_legacy_input_and_empty_witness(outpoint, stack_script, redeem_script, sequence): ''' Outpoint, byte-like, byte-like, int -> (TxIn, InputWitness) ''' return (make_legacy_input(outpoint=outpoint, stack_script=stack_script, ...
[ "def", "make_legacy_input_and_empty_witness", "(", "outpoint", ",", "stack_script", ",", "redeem_script", ",", "sequence", ")", ":", "return", "(", "make_legacy_input", "(", "outpoint", "=", "outpoint", ",", "stack_script", "=", "stack_script", ",", "redeem_script", ...
44.9
19.5
def estimate_hz(self,R,z,dz=10.**-8.,**kwargs): """ NAME: estimate_hz PURPOSE: estimate the exponential scale height at R INPUT: R - Galactocentric radius (can be Quantity) dz - z range to use (can be Quantity) density kwargs ...
[ "def", "estimate_hz", "(", "self", ",", "R", ",", "z", ",", "dz", "=", "10.", "**", "-", "8.", ",", "*", "*", "kwargs", ")", ":", "if", "z", "==", "0.", ":", "zs", "=", "[", "z", ",", "z", "+", "dz", "]", "else", ":", "zs", "=", "[", "z...
19.621622
23.72973
def save_driver_script(driver, script_save=None): # noqa: E501 """Save a script Save a script # noqa: E501 :param driver: The driver to use for the request. ie. github :type driver: str :param script_save: The data needed to save this script :type script_save: dict | bytes :rtype: Respon...
[ "def", "save_driver_script", "(", "driver", ",", "script_save", "=", "None", ")", ":", "# noqa: E501", "if", "connexion", ".", "request", ".", "is_json", ":", "script_save", "=", "ScriptSave", ".", "from_dict", "(", "connexion", ".", "request", ".", "get_json"...
30.76
23.12
def replicate_methods(srcObj, dstObj): """Replicate callable methods from a `srcObj` to `dstObj` (generally a wrapper object). @param srcObj: source object @param dstObj: destination object of the same type. @return : none Implementer notes: 1. Once the methods are mapped from the `s...
[ "def", "replicate_methods", "(", "srcObj", ",", "dstObj", ")", ":", "# prevent methods that we intend to specialize from being mapped. The specialized ", "# (overridden) methods are methods with the same name as the corresponding method in ", "# the source ZOS API COM object written for each ZOS...
52.529412
28.029412
async def handle_websocket_exception(self, error: Exception) -> Optional[Response]: """Handle an uncaught exception. By default this logs the exception and then re-raises it. """ await got_websocket_exception.send(self, exception=error) self.log_exception(sys.exc_info()) ...
[ "async", "def", "handle_websocket_exception", "(", "self", ",", "error", ":", "Exception", ")", "->", "Optional", "[", "Response", "]", ":", "await", "got_websocket_exception", ".", "send", "(", "self", ",", "exception", "=", "error", ")", "self", ".", "log_...
38.9375
25.75