text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def set_password(self, password, user='', note=None): """Sets the password for the current user or passed-in user. As a side effect, installs the "password" package. @param user: username to set the password for. Defaults to '' (i.e. current user) @...
[ "def", "set_password", "(", "self", ",", "password", ",", "user", "=", "''", ",", "note", "=", "None", ")", ":", "shutit", "=", "self", ".", "shutit", "shutit", ".", "handle_note", "(", "note", ")", "if", "isinstance", "(", "password", ",", "str", ")...
40.416667
0.039919
def _load_cytoBand(filename): """ Load UCSC cytoBand table. Parameters ---------- filename : str path to cytoBand file Returns ------- df : pandas.DataFrame cytoBand table if loading was successful, else None References -...
[ "def", "_load_cytoBand", "(", "filename", ")", ":", "try", ":", "# adapted from chromosome plotting code (see [1]_)", "df", "=", "pd", ".", "read_table", "(", "filename", ",", "names", "=", "[", "\"chrom\"", ",", "\"start\"", ",", "\"end\"", ",", "\"name\"", ","...
27.857143
0.002478
def word2vec( train, output, size=100, window=5, sample="1e-3", hs=0, negative=5, threads=12, iter_=5, min_count=5, alpha=0.025, debug=2, binary=1, cbow=1, save_vocab=None, read_vocab=None, ...
[ "def", "word2vec", "(", "train", ",", "output", ",", "size", "=", "100", ",", "window", "=", "5", ",", "sample", "=", "\"1e-3\"", ",", "hs", "=", "0", ",", "negative", "=", "5", ",", "threads", "=", "12", ",", "iter_", "=", "5", ",", "min_count",...
26.401869
0.000341
def coderef_to_ecoclass(self, code, reference=None): """ Map a GAF code to an ECO class Arguments --------- code : str GAF evidence code, e.g. ISS, IDA reference: str CURIE for a reference for the evidence instance. E.g. GO_REF:0000001. ...
[ "def", "coderef_to_ecoclass", "(", "self", ",", "code", ",", "reference", "=", "None", ")", ":", "mcls", "=", "None", "for", "(", "this_code", ",", "this_ref", ",", "cls", ")", "in", "self", ".", "mappings", "(", ")", ":", "if", "str", "(", "this_cod...
29.115385
0.01023
def Update(self, data): """Updates a Dirichlet distribution. data: sequence of observations, in order corresponding to params """ m = len(data) self.params[:m] += data
[ "def", "Update", "(", "self", ",", "data", ")", ":", "m", "=", "len", "(", "data", ")", "self", ".", "params", "[", ":", "m", "]", "+=", "data" ]
28.857143
0.009615
def make_model(self): """Assemble text from the set of collected INDRA Statements. Returns ------- stmt_strs : str Return the assembled text as unicode string. By default, the text is a single string consisting of one or more sentences with periods at...
[ "def", "make_model", "(", "self", ")", ":", "stmt_strs", "=", "[", "]", "for", "stmt", "in", "self", ".", "statements", ":", "if", "isinstance", "(", "stmt", ",", "ist", ".", "Modification", ")", ":", "stmt_strs", ".", "append", "(", "_assemble_modificat...
45.47619
0.001025
def line(self, text=''): '''A simple helper to write line with `\n`''' self.out.write(text) self.out.write('\n')
[ "def", "line", "(", "self", ",", "text", "=", "''", ")", ":", "self", ".", "out", ".", "write", "(", "text", ")", "self", ".", "out", ".", "write", "(", "'\\n'", ")" ]
33.25
0.014706
def computeMultipleExpectations(self, A_in, u_n, compute_uncertainty=True, compute_covariance=False, uncertainty_method=None, warning_cutoff=1.0e-10, return_theta=False): """Compute the expectations of multiple observables of phase space functions. Compute the expect...
[ "def", "computeMultipleExpectations", "(", "self", ",", "A_in", ",", "u_n", ",", "compute_uncertainty", "=", "True", ",", "compute_covariance", "=", "False", ",", "uncertainty_method", "=", "None", ",", "warning_cutoff", "=", "1.0e-10", ",", "return_theta", "=", ...
47.82
0.0084
def load_suffixes(self, filename): """ Build the suffix dictionary. The keys will be possible long versions, and the values will be the accepted abbreviations. Everything should be stored using the value version, and you can search all by using building a set of self.suffixes.keys() and ...
[ "def", "load_suffixes", "(", "self", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'r'", ")", "as", "f", ":", "for", "line", "in", "f", ":", "# Make sure we have key and value", "if", "len", "(", "line", ".", "split", "(", "','", ")...
51
0.008889
def dismiss(self): """ Dismisses the alert available. """ if self.driver.w3c: self.driver.execute(Command.W3C_DISMISS_ALERT) else: self.driver.execute(Command.DISMISS_ALERT)
[ "def", "dismiss", "(", "self", ")", ":", "if", "self", ".", "driver", ".", "w3c", ":", "self", ".", "driver", ".", "execute", "(", "Command", ".", "W3C_DISMISS_ALERT", ")", "else", ":", "self", ".", "driver", ".", "execute", "(", "Command", ".", "DIS...
28.75
0.008439
def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the encoding of the LongInteger from the input stream. Args: istream (stream): A buffer containing the encoded bytes of a LongInteger. Usually a BytearrayStream object. Required. k...
[ "def", "read", "(", "self", ",", "istream", ",", "kmip_version", "=", "enums", ".", "KMIPVersion", ".", "KMIP_1_0", ")", ":", "super", "(", "LongInteger", ",", "self", ")", ".", "read", "(", "istream", ",", "kmip_version", "=", "kmip_version", ")", "if",...
41.76
0.001873
def _init_jobs_table(): """Initialise the "jobs" table in the db.""" _jobs_table = sqlalchemy.Table( 'jobs', _METADATA, sqlalchemy.Column('job_id', sqlalchemy.UnicodeText, primary_key=True), sqlalchemy.Column('job_type', sqlalchemy.UnicodeText), sqlalchemy.Column('status', sqlalc...
[ "def", "_init_jobs_table", "(", ")", ":", "_jobs_table", "=", "sqlalchemy", ".", "Table", "(", "'jobs'", ",", "_METADATA", ",", "sqlalchemy", ".", "Column", "(", "'job_id'", ",", "sqlalchemy", ".", "UnicodeText", ",", "primary_key", "=", "True", ")", ",", ...
47.9
0.001024
def write(s = ''): """ Automates the process of typing by converting a string into a set of press() and hold() calls :param s: string to be written :return: None """ for char in s: if char.isupper(): # Handles uppercase hold('shift', char.lower()) elif char == " ":...
[ "def", "write", "(", "s", "=", "''", ")", ":", "for", "char", "in", "s", ":", "if", "char", ".", "isupper", "(", ")", ":", "# Handles uppercase", "hold", "(", "'shift'", ",", "char", ".", "lower", "(", ")", ")", "elif", "char", "==", "\" \"", ":"...
42.954545
0.008282
def get_python_files(self): """Returns all python files available in the project""" return [resource for resource in self.get_files() if self.pycore.is_python_file(resource)]
[ "def", "get_python_files", "(", "self", ")", ":", "return", "[", "resource", "for", "resource", "in", "self", ".", "get_files", "(", ")", "if", "self", ".", "pycore", ".", "is_python_file", "(", "resource", ")", "]" ]
50.75
0.009709
def use_comparative_comment_view(self): """Pass through to provider CommentLookupSession.use_comparative_comment_view""" self._object_views['comment'] = COMPARATIVE # self._get_provider_session('comment_lookup_session') # To make sure the session is tracked for session in self._get_provi...
[ "def", "use_comparative_comment_view", "(", "self", ")", ":", "self", ".", "_object_views", "[", "'comment'", "]", "=", "COMPARATIVE", "# self._get_provider_session('comment_lookup_session') # To make sure the session is tracked", "for", "session", "in", "self", ".", "_get_pr...
50.555556
0.008639
def coalesce(*fields, **kwargs): """ Return a function which accepts a row and returns the first non-missing value from the specified fields. Intended for use with :func:`petl.transform.basics.addfield`. """ missing = kwargs.get('missing', None) default = kwargs.get('default', None) de...
[ "def", "coalesce", "(", "*", "fields", ",", "*", "*", "kwargs", ")", ":", "missing", "=", "kwargs", ".", "get", "(", "'missing'", ",", "None", ")", "default", "=", "kwargs", ".", "get", "(", "'default'", ",", "None", ")", "def", "_coalesce", "(", "...
26.166667
0.002049
def from_path_and_array(cls, path, folder, y, classes=None, val_idxs=None, test_name=None, num_workers=8, tfms=(None,None), bs=64): """ Read in images given a sub-folder and their labels given a numpy array Arguments: path: a root path of the data (used for storing trained model...
[ "def", "from_path_and_array", "(", "cls", ",", "path", ",", "folder", ",", "y", ",", "classes", "=", "None", ",", "val_idxs", "=", "None", ",", "test_name", "=", "None", ",", "num_workers", "=", "8", ",", "tfms", "=", "(", "None", ",", "None", ")", ...
60.478261
0.010616
def task(obj = None, deps = None): """Decorator for creating a task.""" # The decorator is not used as a function if callable(obj): __task(obj.__name__, obj) return obj # The decorator is used as a function def __decorated(func): __task(obj if obj else obj.__name__, deps, func) return func return __deco...
[ "def", "task", "(", "obj", "=", "None", ",", "deps", "=", "None", ")", ":", "# The decorator is not used as a function", "if", "callable", "(", "obj", ")", ":", "__task", "(", "obj", ".", "__name__", ",", "obj", ")", "return", "obj", "# The decorator is used...
24.076923
0.046154
def _rec_filter_to_info(line): """Move a DKFZBias filter to the INFO field, for a record. """ parts = line.rstrip().split("\t") move_filters = {"bSeq": "strand", "bPcr": "damage"} new_filters = [] bias_info = [] for f in parts[6].split(";"): if f in move_filters: bias_inf...
[ "def", "_rec_filter_to_info", "(", "line", ")", ":", "parts", "=", "line", ".", "rstrip", "(", ")", ".", "split", "(", "\"\\t\"", ")", "move_filters", "=", "{", "\"bSeq\"", ":", "\"strand\"", ",", "\"bPcr\"", ":", "\"damage\"", "}", "new_filters", "=", "...
34.5
0.001764
def get_reference_lines(docbody, ref_sect_start_line, ref_sect_end_line, ref_sect_title, ref_line_marker_ptn, title_marker_same_line): """After the reference section of a document has been identif...
[ "def", "get_reference_lines", "(", "docbody", ",", "ref_sect_start_line", ",", "ref_sect_end_line", ",", "ref_sect_title", ",", "ref_line_marker_ptn", ",", "title_marker_same_line", ")", ":", "start_idx", "=", "ref_sect_start_line", "if", "title_marker_same_line", ":", "#...
49.519231
0.000762
def project(X, Z, use_jit=False, debug=False): """ Project tensor Z on the tangent space of tensor X. X is a tensor in the TT format. Z can be a tensor in the TT format or a list of tensors (in this case the function computes projection of the sum off all tensors in the list: project(X, Z) = P_...
[ "def", "project", "(", "X", ",", "Z", ",", "use_jit", "=", "False", ",", "debug", "=", "False", ")", ":", "zArr", "=", "None", "if", "isinstance", "(", "Z", ",", "tt", ".", "vector", ")", ":", "zArr", "=", "[", "Z", "]", "else", ":", "zArr", ...
45.384615
0.001833
def check_assets(self): """ Throws an exception if assets file is not configured or cannot be found. :param assets: path to the assets file """ if not self.assets_file: raise ImproperlyConfigured("You must specify the path to the assets.json file via WEBPACK_ASSETS_FI...
[ "def", "check_assets", "(", "self", ")", ":", "if", "not", "self", ".", "assets_file", ":", "raise", "ImproperlyConfigured", "(", "\"You must specify the path to the assets.json file via WEBPACK_ASSETS_FILE\"", ")", "elif", "not", "os", ".", "path", ".", "exists", "("...
52.363636
0.008532
def compile_create_temporary_table(table_name: str, column_statement: str, primary_key_statement: str) -> str: """Postgresql Create Temporary Table statement formatter.""" statement = """ CREATE TEMPORARY TABLE {table} ({colu...
[ "def", "compile_create_temporary_table", "(", "table_name", ":", "str", ",", "column_statement", ":", "str", ",", "primary_key_statement", ":", "str", ")", "->", "str", ":", "statement", "=", "\"\"\"\n CREATE TEMPORARY TABLE {table} ({columns} {primary_keys});\...
46.636364
0.001912
def _get(self, node, key): """ get value inside a node :param node: node in form of list, or BLANK_NODE :param key: nibble list without terminator :return: BLANK_NODE if does not exist, otherwise value or hash """ node_type = self._get_node_type(node) ...
[ "def", "_get", "(", "self", ",", "node", ",", "key", ")", ":", "node_type", "=", "self", ".", "_get_node_type", "(", "node", ")", "if", "node_type", "==", "NODE_TYPE_BLANK", ":", "return", "BLANK_NODE", "if", "node_type", "==", "NODE_TYPE_BRANCH", ":", "# ...
34.21875
0.001776
def updated_copy(self,flag,deep=True): ''' Returns a sliced (updated) copy of current data object :summary: This has the same effect as `obj.copy();obj.update(flag)` but is much less memory consumming. .. note:: TypeError could arise if some object attributes are ...
[ "def", "updated_copy", "(", "self", ",", "flag", ",", "deep", "=", "True", ")", ":", "emptyObj", "=", "self", ".", "__class__", "(", "[", "]", ")", "if", "deep", ":", "func_copy", "=", "copy", ".", "deepcopy", "else", ":", "func_copy", "=", "copy", ...
45.44186
0.021042
def update_file(filename, result, content, indent): """Updates a Jekyll file to contain the counts form an object This just converts the results to YAML and adds to the Jekyll frontmatter. Args: filename: the Jekyll file to update result: the results object from `wc` content: the c...
[ "def", "update_file", "(", "filename", ",", "result", ",", "content", ",", "indent", ")", ":", "# Split the file into frontmatter and content", "parts", "=", "re", ".", "split", "(", "'---+'", ",", "content", ",", "2", ")", "# Load the frontmatter into an object", ...
35.633333
0.000911
def add_node(self, node, attrs = None): """ Add given node to the graph. @attention: While nodes can be of any type, it's strongly recommended to use only numbers and single-line strings as node identifiers if you intend to use write(). @type node: node @param ...
[ "def", "add_node", "(", "self", ",", "node", ",", "attrs", "=", "None", ")", ":", "if", "attrs", "is", "None", ":", "attrs", "=", "[", "]", "if", "(", "node", "not", "in", "self", ".", "node_neighbors", ")", ":", "self", ".", "node_neighbors", "[",...
36.238095
0.011524
def delete(path, dryrun=False, recursive=True, verbose=None, print_exists=True, ignore_errors=True): """ Removes a file, directory, or symlink """ if verbose is None: verbose = VERBOSE if not QUIET: verbose = 1 if verbose > 0: print('[util_path] Deleting path=%...
[ "def", "delete", "(", "path", ",", "dryrun", "=", "False", ",", "recursive", "=", "True", ",", "verbose", "=", "None", ",", "print_exists", "=", "True", ",", "ignore_errors", "=", "True", ")", ":", "if", "verbose", "is", "None", ":", "verbose", "=", ...
36.757576
0.000803
def tg90p(tas, t90, freq='YS'): r"""Number of days with daily mean temperature over the 90th percentile. Number of days with daily mean temperature over the 90th percentile. Parameters ---------- tas : xarray.DataArray Mean daily temperature [℃] or [K] t90 : xarray.DataArray 90th p...
[ "def", "tg90p", "(", "tas", ",", "t90", ",", "freq", "=", "'YS'", ")", ":", "if", "'dayofyear'", "not", "in", "t90", ".", "coords", ".", "keys", "(", ")", ":", "raise", "AttributeError", "(", "\"t10 should have dayofyear coordinates.\"", ")", "t90", "=", ...
28.844444
0.002235
def state_pop(self): """ Pop the state of all generators """ super(Composite,self).state_pop() for gen in self.generators: gen.state_pop()
[ "def", "state_pop", "(", "self", ")", ":", "super", "(", "Composite", ",", "self", ")", ".", "state_pop", "(", ")", "for", "gen", "in", "self", ".", "generators", ":", "gen", ".", "state_pop", "(", ")" ]
26.285714
0.015789
def seek( self, offset, whence=0 ): """ Move the file pointer to a particular offset. """ # Determine absolute target position if whence == 0: target_pos = offset elif whence == 1: target_pos = self.file_pos + offset elif whence == 2: ...
[ "def", "seek", "(", "self", ",", "offset", ",", "whence", "=", "0", ")", ":", "# Determine absolute target position", "if", "whence", "==", "0", ":", "target_pos", "=", "offset", "elif", "whence", "==", "1", ":", "target_pos", "=", "self", ".", "file_pos",...
36.130435
0.008206
def limits_status_send(self, limits_state, last_trigger, last_action, last_recovery, last_clear, breach_count, mods_enabled, mods_required, mods_triggered, force_mavlink1=False): ''' Status of AP_Limits. Sent in extended status stream when AP_Limits is enabled ...
[ "def", "limits_status_send", "(", "self", ",", "limits_state", ",", "last_trigger", ",", "last_action", ",", "last_recovery", ",", "last_clear", ",", "breach_count", ",", "mods_enabled", ",", "mods_required", ",", "mods_triggered", ",", "force_mavlink1", "=", "False...
91.941176
0.008233
def _setup_progIsTrack(self): """If progIsTrack, the progenitor orbit that was passed to the streamdf initialization is the track at zero angle separation; this routine computes an actual progenitor position that gives the desired track given the parameters of the streamdf""" # ...
[ "def", "_setup_progIsTrack", "(", "self", ")", ":", "# We need to flip the sign of the offset, to go to the progenitor", "self", ".", "_sigMeanSign", "*=", "-", "1.", "# Use _determine_stream_track_single to calculate the track-progenitor", "# offset at zero angle separation", "prog_st...
53.666667
0.010847
def _get_or_create_student_item(student_item_dict): """Gets or creates a Student Item that matches the values specified. Attempts to get the specified Student Item. If it does not exist, the specified parameters are validated, and a new Student Item is created. Args: student_item_dict (dict): ...
[ "def", "_get_or_create_student_item", "(", "student_item_dict", ")", ":", "try", ":", "try", ":", "return", "StudentItem", ".", "objects", ".", "get", "(", "*", "*", "student_item_dict", ")", "except", "StudentItem", ".", "DoesNotExist", ":", "student_item_seriali...
39.153846
0.001917
def fix_residue_numbering(self): """this function renumbers the res ids in order to avoid strange behaviour of Rosetta""" resid_list = self.aa_resids() resid_set = set(resid_list) resid_lst1 = list(resid_set) resid_lst1.sort() map_res_id = {} x = 1 old_...
[ "def", "fix_residue_numbering", "(", "self", ")", ":", "resid_list", "=", "self", ".", "aa_resids", "(", ")", "resid_set", "=", "set", "(", "resid_list", ")", "resid_lst1", "=", "list", "(", "resid_set", ")", "resid_lst1", ".", "sort", "(", ")", "map_res_i...
32
0.010427
def get_chunks(self, new_data_bytes): """Yield chunks generated from received data. The buffer may not be decodable as UTF-8 if there's a split multi-byte character at the end. To handle this, do a "best effort" decode of the buffer to decode as much of it as possible. The leng...
[ "def", "get_chunks", "(", "self", ",", "new_data_bytes", ")", ":", "self", ".", "_buf", "+=", "new_data_bytes", "while", "True", ":", "buf_decoded", "=", "_best_effort_decode", "(", "self", ".", "_buf", ")", "buf_utf16", "=", "buf_decoded", ".", "encode", "(...
45.952381
0.001015
def get_extension_attribute(self, ext_name, key): """ Banana banana """ attributes = self.extension_attributes.get(ext_name) if not attributes: return None return attributes.get(key)
[ "def", "get_extension_attribute", "(", "self", ",", "ext_name", ",", "key", ")", ":", "attributes", "=", "self", ".", "extension_attributes", ".", "get", "(", "ext_name", ")", "if", "not", "attributes", ":", "return", "None", "return", "attributes", ".", "ge...
29.375
0.008264
def camelcase_to_underscores(argument): ''' Converts a camelcase param like theNewAttribute to the equivalent python underscore variable like the_new_attribute''' result = '' prev_char_title = True if not argument: return argument for index, char in enumerate(argument): try: ...
[ "def", "camelcase_to_underscores", "(", "argument", ")", ":", "result", "=", "''", "prev_char_title", "=", "True", "if", "not", "argument", ":", "return", "argument", "for", "index", ",", "char", "in", "enumerate", "(", "argument", ")", ":", "try", ":", "n...
37.25
0.002181
def attachment_to_multidim_measurement(attachment, name=None): """Convert an OpenHTF test record attachment to a multi-dim measurement. This is a best effort attempt to reverse, as some data is lost in converting from a multidim to an attachment. Args: attachment: an `openhtf.test_record.Attachment` from ...
[ "def", "attachment_to_multidim_measurement", "(", "attachment", ",", "name", "=", "None", ")", ":", "data", "=", "json", ".", "loads", "(", "attachment", ".", "data", ")", "name", "=", "name", "or", "data", ".", "get", "(", "'name'", ")", "# attachment_dim...
33.464789
0.01063
def _load_source_object(self): """ Loads related object in a dynamic attribute and returns it. """ if hasattr(self, "source_obj"): self.source_text = getattr(self.source_obj, self.field) return self.source_obj self._load_source_model() self.source_obj = self.source_model.objects.get(id=self.object_id...
[ "def", "_load_source_object", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "\"source_obj\"", ")", ":", "self", ".", "source_text", "=", "getattr", "(", "self", ".", "source_obj", ",", "self", ".", "field", ")", "return", "self", ".", "source...
30.545455
0.031792
def parse_radl(data): """ Parse a RADL document. Args: - data(str): filepath to a RADL content or a string with content. Return: RADL object. """ if data is None: return None elif os.path.isfile(data): f = open(data) data = "".join(f.readlines()) f.clos...
[ "def", "parse_radl", "(", "data", ")", ":", "if", "data", "is", "None", ":", "return", "None", "elif", "os", ".", "path", ".", "isfile", "(", "data", ")", ":", "f", "=", "open", "(", "data", ")", "data", "=", "\"\"", ".", "join", "(", "f", ".",...
20.272727
0.002141
def _platform_patterns(self, platform='generic', compiled=False): """Return all the patterns for specific platform.""" patterns = self._dict_compiled.get(platform, None) if compiled else self._dict_text.get(platform, None) if patterns is None: raise KeyError("Unknown platform: {}".fo...
[ "def", "_platform_patterns", "(", "self", ",", "platform", "=", "'generic'", ",", "compiled", "=", "False", ")", ":", "patterns", "=", "self", ".", "_dict_compiled", ".", "get", "(", "platform", ",", "None", ")", "if", "compiled", "else", "self", ".", "_...
59
0.008357
def addTopLevelItem(self, item): """ Adds the inputed item to the gantt widget. :param item | <XGanttWidgetItem> """ vitem = item.viewItem() self.treeWidget().addTopLevelItem(item) self.viewWidget().scene().addItem(vitem) ...
[ "def", "addTopLevelItem", "(", "self", ",", "item", ")", ":", "vitem", "=", "item", ".", "viewItem", "(", ")", "self", ".", "treeWidget", "(", ")", ".", "addTopLevelItem", "(", "item", ")", "self", ".", "viewWidget", "(", ")", ".", "scene", "(", ")",...
28.388889
0.011364
def findfivo(ol,*args,**kwargs): ''' #findfivo f,i,v,o四元决定 fivo-4-tuple-engine #cond_func diff_func(index,value,*diff_args) ''' args = list(args) lngth = args.__len__() if(lngth==0): diff_funcs_arr = kwargs['cond_funcs'] diff_args_...
[ "def", "findfivo", "(", "ol", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "args", "=", "list", "(", "args", ")", "lngth", "=", "args", ".", "__len__", "(", ")", "if", "(", "lngth", "==", "0", ")", ":", "diff_funcs_arr", "=", "kwargs", ...
29.636364
0.008911
def _CollapseStrings(elided): """Collapses strings and chars on a line to simple "" or '' blocks. We nix strings first so we're not fooled by text like '"http://"' Args: elided: The line being processed. Returns: The line with collapsed strings. """ if _RE_PATTERN_INCLUDE.match(el...
[ "def", "_CollapseStrings", "(", "elided", ")", ":", "if", "_RE_PATTERN_INCLUDE", ".", "match", "(", "elided", ")", ":", "return", "elided", "# Remove escaped characters first to make quote/single quote collapsing", "# basic. Things that look like escaped characters shouldn't occur...
35.846154
0.008354
def thaicheck(word: str) -> bool: """ Check if a word is an "authentic Thai word" :param str word: word :return: True or False """ pattern = re.compile(r"[ก-ฬฮ]", re.U) # สำหรับตรวจสอบพยัญชนะ res = re.findall(pattern, word) # ดึงพยัญชนะทัั้งหมดออกมา if res == []: return False...
[ "def", "thaicheck", "(", "word", ":", "str", ")", "->", "bool", ":", "pattern", "=", "re", ".", "compile", "(", "r\"[ก-ฬฮ]\", re.U", ")", " #", " ", "ส", "ำ", "ับตรวจสอบพยัญชนะ", "res", "=", "re", ".", "findall", "(", "pattern", ",", "word", ")", "# ...
23.66
0.000812
def smooth_magseries_savgol(mags, windowsize, polyorder=2): '''This smooths the magseries with a Savitsky-Golay filter. Parameters ---------- mags : np.array The input mags/flux time-series to smooth. windowsize : int This is a odd integer containing the smoothing window size. ...
[ "def", "smooth_magseries_savgol", "(", "mags", ",", "windowsize", ",", "polyorder", "=", "2", ")", ":", "smoothed", "=", "savgol_filter", "(", "mags", ",", "windowsize", ",", "polyorder", ")", "return", "smoothed" ]
23.538462
0.00157
def plot_4(data, *args): """Scatter plot of score vs each param """ params = nonconstant_parameters(data) scores = np.array([d['mean_test_score'] for d in data]) order = np.argsort(scores) for key in params.keys(): if params[key].dtype == np.dtype('bool'): params[key] = para...
[ "def", "plot_4", "(", "data", ",", "*", "args", ")", ":", "params", "=", "nonconstant_parameters", "(", "data", ")", "scores", "=", "np", ".", "array", "(", "[", "d", "[", "'mean_test_score'", "]", "for", "d", "in", "data", "]", ")", "order", "=", ...
31.76
0.002445
def _generic_mixer(slice1, slice2, mixer_name, **kwargs): """ Generic mixer to process two slices with appropriate mixer and return the composite to be displayed. """ mixer_name = mixer_name.lower() if mixer_name in ['color_mix', 'rgb']: mixed = _mix_color(slice1, slice2, **kwargs) ...
[ "def", "_generic_mixer", "(", "slice1", ",", "slice2", ",", "mixer_name", ",", "*", "*", "kwargs", ")", ":", "mixer_name", "=", "mixer_name", ".", "lower", "(", ")", "if", "mixer_name", "in", "[", "'color_mix'", ",", "'rgb'", "]", ":", "mixed", "=", "_...
36.805556
0.001471
def _upload(self, project_id, updating, file_path, language_code=None, overwrite=False, sync_terms=False, tags=None, fuzzy_trigger=None): """ Internal: updates terms / translations File uploads are limited to one every 30 seconds """ options = [ self....
[ "def", "_upload", "(", "self", ",", "project_id", ",", "updating", ",", "file_path", ",", "language_code", "=", "None", ",", "overwrite", "=", "False", ",", "sync_terms", "=", "False", ",", "tags", "=", "None", ",", "fuzzy_trigger", "=", "None", ")", ":"...
33.25
0.002247
def _build_wsgi_env(event, app_name): """Turn the Lambda/API Gateway request event into a WSGI environment dict. :param dict event: The event parameters passed to the Lambda function entrypoint. :param str app_name: Name of the API application. """ gateway = event['parameters']['gat...
[ "def", "_build_wsgi_env", "(", "event", ",", "app_name", ")", ":", "gateway", "=", "event", "[", "'parameters'", "]", "[", "'gateway'", "]", "request", "=", "event", "[", "'parameters'", "]", "[", "'request'", "]", "ctx", "=", "event", "[", "'rawContext'",...
37.765957
0.000549
def get_config(): """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "pep440-post" cfg.tag_prefix = "" cfg.parentdir_prefix = "None" cfg.v...
[ "def", "get_config", "(", ")", ":", "# these strings are filled in when 'setup.py versioneer' creates", "# _version.py", "cfg", "=", "VersioneerConfig", "(", ")", "cfg", ".", "VCS", "=", "\"git\"", "cfg", ".", "style", "=", "\"pep440-post\"", "cfg", ".", "tag_prefix",...
32.583333
0.002488
def get_properties(self, packet, bt_addr): """Get properties of beacon depending on type.""" if is_one_of(packet, [EddystoneTLMFrame, EddystoneURLFrame, \ EddystoneEncryptedTLMFrame, EddystoneEIDFrame]): # here we retrieve the namespace and instance which corres...
[ "def", "get_properties", "(", "self", ",", "packet", ",", "bt_addr", ")", ":", "if", "is_one_of", "(", "packet", ",", "[", "EddystoneTLMFrame", ",", "EddystoneURLFrame", ",", "EddystoneEncryptedTLMFrame", ",", "EddystoneEIDFrame", "]", ")", ":", "# here we retriev...
53.777778
0.00813
def remove(self, server_id): """remove server and data stuff Args: server_id - server identity """ server = self._storage.pop(server_id) server.stop() server.cleanup()
[ "def", "remove", "(", "self", ",", "server_id", ")", ":", "server", "=", "self", ".", "_storage", ".", "pop", "(", "server_id", ")", "server", ".", "stop", "(", ")", "server", ".", "cleanup", "(", ")" ]
27.5
0.008811
def setDeviceID(self, value, device=DEFAULT_DEVICE_ID, message=True): """ Set the hardware device number. This is only needed if more that one device is on the same serial buss. :Parameters: value : `int` The device ID to set in the range of 0 - 127. :Keyw...
[ "def", "setDeviceID", "(", "self", ",", "value", ",", "device", "=", "DEFAULT_DEVICE_ID", ",", "message", "=", "True", ")", ":", "return", "self", ".", "_setDeviceID", "(", "value", ",", "device", ",", "message", ")" ]
38.068966
0.001767
def update_house(self, complex: str, id: str, **kwargs): """ Update the existing house """ self.check_house(complex, id) self.put('developers/{developer}/complexes/{complex}/houses/{id}'.format( developer=self.developer, complex=complex, id=id,...
[ "def", "update_house", "(", "self", ",", "complex", ":", "str", ",", "id", ":", "str", ",", "*", "*", "kwargs", ")", ":", "self", ".", "check_house", "(", "complex", ",", "id", ")", "self", ".", "put", "(", "'developers/{developer}/complexes/{complex}/hous...
33.5
0.008721
def get_all_zones(self, zones=None, filters=None): """ Get all Availability Zones associated with the current region. :type zones: list :param zones: Optional list of zones. If this list is present, only the Zones associated with these zone names ...
[ "def", "get_all_zones", "(", "self", ",", "zones", "=", "None", ",", "filters", "=", "None", ")", ":", "params", "=", "{", "}", "if", "zones", ":", "self", ".", "build_list_params", "(", "params", ",", "zones", ",", "'ZoneName'", ")", "if", "filters", ...
43.241379
0.00156
def open(self, name, mode="r", pwd=None): """Return file-like object for 'name'.""" if mode not in ("r", "U", "rU"): raise RuntimeError('open() requires mode "r", "U", or "rU"') if 'U' in mode: import warnings warnings.warn("'U' mode is deprecated", ...
[ "def", "open", "(", "self", ",", "name", ",", "mode", "=", "\"r\"", ",", "pwd", "=", "None", ")", ":", "if", "mode", "not", "in", "(", "\"r\"", ",", "\"U\"", ",", "\"rU\"", ")", ":", "raise", "RuntimeError", "(", "'open() requires mode \"r\", \"U\", or \...
34.428571
0.000733
def read_nb(fname): "Read a notebook in `fname` and return its corresponding json" with open(fname,'r') as f: return nbformat.reads(f.read(), as_version=4)
[ "def", "read_nb", "(", "fname", ")", ":", "with", "open", "(", "fname", ",", "'r'", ")", "as", "f", ":", "return", "nbformat", ".", "reads", "(", "f", ".", "read", "(", ")", ",", "as_version", "=", "4", ")" ]
53.666667
0.018405
def ext_pillar(minion_id, pillar, **kwargs): ''' Obtain the Pillar data from **reclass** for the given ``minion_id``. ''' # If reclass is installed, __virtual__ put it onto the search path, so we # don't need to protect against ImportError: # pylint: disable=3rd-party-module-not-gated from ...
[ "def", "ext_pillar", "(", "minion_id", ",", "pillar", ",", "*", "*", "kwargs", ")", ":", "# If reclass is installed, __virtual__ put it onto the search path, so we", "# don't need to protect against ImportError:", "# pylint: disable=3rd-party-module-not-gated", "from", "reclass", "...
39.27907
0.000578
def _build_row(cells, padding, begin, sep, end): "Return a string which represents a row of data cells." pad = " " * padding padded_cells = [pad + cell + pad for cell in cells] # SolveBio: we're only displaying Key-Value tuples (dimension of 2). # enforce that we don't wrap lines by setting a max...
[ "def", "_build_row", "(", "cells", ",", "padding", ",", "begin", ",", "sep", ",", "end", ")", ":", "pad", "=", "\" \"", "*", "padding", "padded_cells", "=", "[", "pad", "+", "cell", "+", "pad", "for", "cell", "in", "cells", "]", "# SolveBio: we're only...
40.3
0.001212
def highlight_edges(graph: BELGraph, edges=None, color: Optional[str]=None) -> None: """Adds a highlight tag to the given edges. :param graph: A BEL graph :param edges: The edges (4-tuples of u, v, k, d) to add a highlight tag on :type edges: iter[tuple] :param str color: The color to highlight (us...
[ "def", "highlight_edges", "(", "graph", ":", "BELGraph", ",", "edges", "=", "None", ",", "color", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "None", ":", "color", "=", "color", "or", "EDGE_HIGHLIGHT_DEFAULT_COLOR", "for", "u", ",", "v", ...
48.727273
0.010989
def truncate_attr_at_path( obj, path ): """ Traverses a set of nested attributes and truncates the value on an object :param mixed obj: The object to set the attribute on :param tuple path: The path to the attribute on the object :rtype None: """ target = obj last_attr = path[-1] m...
[ "def", "truncate_attr_at_path", "(", "obj", ",", "path", ")", ":", "target", "=", "obj", "last_attr", "=", "path", "[", "-", "1", "]", "message", "=", "[", "]", "if", "type", "(", "last_attr", ")", "==", "tuple", ":", "last_attr", "=", "last_attr", "...
36.704545
0.037394
def hicpro_pairing_chart (self): """ Generate Pairing chart """ # Specify the order of the different possible categories keys = OrderedDict() keys['Unique_paired_alignments'] = { 'color': '#005ce6', 'name': 'Uniquely Aligned' } keys['Low_qual_pairs'] = { 'color': '#b97b35', 'nam...
[ "def", "hicpro_pairing_chart", "(", "self", ")", ":", "# Specify the order of the different possible categories", "keys", "=", "OrderedDict", "(", ")", "keys", "[", "'Unique_paired_alignments'", "]", "=", "{", "'color'", ":", "'#005ce6'", ",", "'name'", ":", "'Uniquel...
44.4
0.019846
def init_log(logger, filename=None, loglevel=None): """ Initializes the log file in the proper format. Arguments: filename (str): Path to a file. Or None if logging is to be disabled. loglevel (str): Determines the level of the log output. """ template = '[...
[ "def", "init_log", "(", "logger", ",", "filename", "=", "None", ",", "loglevel", "=", "None", ")", ":", "template", "=", "'[%(asctime)s] %(levelname)-8s: %(name)-25s: %(message)s'", "formatter", "=", "logging", ".", "Formatter", "(", "template", ")", "if", "loglev...
32.264706
0.000885
def query_and_read_frame(frame_type, channels, start_time, end_time, sieve=None, check_integrity=False): """Read time series from frame data. Query for the locatin of physical frames matching the frame type. Return a time series containing the channel between the given start and en...
[ "def", "query_and_read_frame", "(", "frame_type", ",", "channels", ",", "start_time", ",", "end_time", ",", "sieve", "=", "None", ",", "check_integrity", "=", "False", ")", ":", "# Allows compatibility with our standard tools", "# We may want to place this into a higher lev...
41.22
0.000474
def samples(dataset='imagenet', index=0, batchsize=1, shape=(224, 224), data_format='channels_last'): ''' Returns a batch of example images and the corresponding labels Parameters ---------- dataset : string The data set to load (options: imagenet, mnist, cifar10, cifar100, ...
[ "def", "samples", "(", "dataset", "=", "'imagenet'", ",", "index", "=", "0", ",", "batchsize", "=", "1", ",", "shape", "=", "(", "224", ",", "224", ")", ",", "data_format", "=", "'channels_last'", ")", ":", "from", "PIL", "import", "Image", "images", ...
28.633333
0.000563
def delete_agent(self, agent_id): """Delete an agent. :param str agent_id: The id of the agent to delete. It must be an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. :return: agent deleted. :rtype: dict. """ # Raises an error when agent_id is ...
[ "def", "delete_agent", "(", "self", ",", "agent_id", ")", ":", "# Raises an error when agent_id is invalid", "self", ".", "_check_agent_id", "(", "agent_id", ")", "req_url", "=", "\"{}/agents/{}\"", ".", "format", "(", "self", ".", "_base_url", ",", "agent_id", ")...
27.894737
0.001825
def patches_after(self, patch): """ Returns a list of patches after patch from the patches list """ return [line.get_patch() for line in self._patchlines_after(patch) if line.get_patch()]
[ "def", "patches_after", "(", "self", ",", "patch", ")", ":", "return", "[", "line", ".", "get_patch", "(", ")", "for", "line", "in", "self", ".", "_patchlines_after", "(", "patch", ")", "if", "line", ".", "get_patch", "(", ")", "]" ]
54
0.009132
def event_listen(self, timeout=None, raise_on_disconnect=True): '''Does not return until PulseLoopStop gets raised in event callback or timeout passes. timeout should be in seconds (float), 0 for non-blocking poll and None (default) for no timeout. raise_on_disconnect causes PulseDisconnected exceptions...
[ "def", "event_listen", "(", "self", ",", "timeout", "=", "None", ",", "raise_on_disconnect", "=", "True", ")", ":", "assert", "self", ".", "event_callback", "try", ":", "self", ".", "_pulse_poll", "(", "timeout", ")", "except", "c", ".", "pa", ".", "Call...
54.090909
0.026446
def get_tdms_files(directory): """Recursively find projects based on '.tdms' file endings Searches the `directory` recursively and return a sorted list of all found '.tdms' project files, except fluorescence data trace files which end with `_traces.tdms`. """ path = pathlib.Path(directory).reso...
[ "def", "get_tdms_files", "(", "directory", ")", ":", "path", "=", "pathlib", ".", "Path", "(", "directory", ")", ".", "resolve", "(", ")", "# get all tdms files", "tdmslist", "=", "[", "r", "for", "r", "in", "path", ".", "rglob", "(", "\"*.tdms\"", ")", ...
41
0.001835
def read_certificate_signing_request(self, name, **kwargs): # noqa: E501 """read_certificate_signing_request # noqa: E501 read the specified CertificateSigningRequest # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pa...
[ "def", "read_certificate_signing_request", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", "...
55.375
0.001479
def hash64(data: Any, seed: int = 0) -> int: """ Non-cryptographic, deterministic, fast hash. Args: data: data to hash seed: seed Returns: signed 64-bit integer """ # ------------------------------------------------------------------------- # MurmurHash3 # -----...
[ "def", "hash64", "(", "data", ":", "Any", ",", "seed", ":", "int", "=", "0", ")", "->", "int", ":", "# -------------------------------------------------------------------------", "# MurmurHash3", "# -------------------------------------------------------------------------", "c_...
29.619048
0.001558
def _analyze_state(state: GlobalState): """ :param state: the current state :return: returns the issues for that corresponding state """ instruction = state.get_current_instruction() annotations = cast( List[MultipleSendsAnnotation], list(state.get_annotations(MultipleSendsAnnot...
[ "def", "_analyze_state", "(", "state", ":", "GlobalState", ")", ":", "instruction", "=", "state", ".", "get_current_instruction", "(", ")", "annotations", "=", "cast", "(", "List", "[", "MultipleSendsAnnotation", "]", ",", "list", "(", "state", ".", "get_annot...
34.237288
0.002406
def list_keys(self, secret=False): """List the keys currently in the keyring. The GnuPG option '--show-photos', according to the GnuPG manual, "does not work with --with-colons", but since we can't rely on all versions of GnuPG to explicitly handle this correctly, we should probably ...
[ "def", "list_keys", "(", "self", ",", "secret", "=", "False", ")", ":", "which", "=", "'public-keys'", "if", "secret", ":", "which", "=", "'secret-keys'", "args", "=", "[", "]", "args", ".", "append", "(", "\"--fixed-list-mode\"", ")", "args", ".", "appe...
36.837209
0.00123
def hash(self): ''' :rtype: int :return: hash of the field ''' if self._hash is None: self._initialize() self._hash = khash(type(self).__name__, self._default_value, self._fuzzable) return self._hash
[ "def", "hash", "(", "self", ")", ":", "if", "self", ".", "_hash", "is", "None", ":", "self", ".", "_initialize", "(", ")", "self", ".", "_hash", "=", "khash", "(", "type", "(", "self", ")", ".", "__name__", ",", "self", ".", "_default_value", ",", ...
29.222222
0.01107
def clear(self, correlation_id): """ Clears component state. :param correlation_id: (optional) transaction id to trace execution through call chain. """ self._lock.acquire() try: self._cache = {} finally: self._lock.release()
[ "def", "clear", "(", "self", ",", "correlation_id", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "self", ".", "_cache", "=", "{", "}", "finally", ":", "self", ".", "_lock", ".", "release", "(", ")" ]
26.909091
0.009804
def get_epoch_config( block_height ): """ Get the epoch constants for the given block height """ global EPOCHS epoch_number = get_epoch_number( block_height ) if epoch_number < 0 or epoch_number >= len(EPOCHS): log.error("FATAL: invalid epoch %s" % epoch_number) os.abort() ...
[ "def", "get_epoch_config", "(", "block_height", ")", ":", "global", "EPOCHS", "epoch_number", "=", "get_epoch_number", "(", "block_height", ")", "if", "epoch_number", "<", "0", "or", "epoch_number", ">=", "len", "(", "EPOCHS", ")", ":", "log", ".", "error", ...
28
0.014409
def send_message(host, data, timeout=None, properties=None): """ Send message to given `host`. Args: host (str): Specified host: aleph/ftp/whatever available host. data (str): JSON data. timeout (int, default None): How much time wait for connection. """ channel = _get_chann...
[ "def", "send_message", "(", "host", ",", "data", ",", "timeout", "=", "None", ",", "properties", "=", "None", ")", ":", "channel", "=", "_get_channel", "(", "host", ",", "timeout", ")", "if", "not", "properties", ":", "properties", "=", "pika", ".", "B...
28.076923
0.001325
def curve_points(self, beginframe, endframe, framestep, birthframe, startframe, stopframe, deathframe, filternone=True, noiseframe=None): """ returns a list of frames from startframe to stopframe, in steps of framestepj warning: the list of points may include "None" elements...
[ "def", "curve_points", "(", "self", ",", "beginframe", ",", "endframe", ",", "framestep", ",", "birthframe", ",", "startframe", ",", "stopframe", ",", "deathframe", ",", "filternone", "=", "True", ",", "noiseframe", "=", "None", ")", ":", "if", "endframe", ...
59.363636
0.008036
def find_package_data( where='.', package='', exclude=standard_exclude, exclude_directories=standard_exclude_directories, only_in_packages=True, show_ignored=False, ): """ Return a dictionary suitable for use in ``package_data`` in a distutils ``setup.py`` file. The dictionary l...
[ "def", "find_package_data", "(", "where", "=", "'.'", ",", "package", "=", "''", ",", "exclude", "=", "standard_exclude", ",", "exclude_directories", "=", "standard_exclude_directories", ",", "only_in_packages", "=", "True", ",", "show_ignored", "=", "False", ",",...
36.890244
0.001288
def _eig_complex_symmetric(M: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """Diagonalize a complex symmetric matrix. The eigenvalues are complex, and the eigenvectors form an orthogonal matrix. Returns: eigenvalues, eigenvectors """ if not np.allclose(M, M.transpose()): raise np....
[ "def", "_eig_complex_symmetric", "(", "M", ":", "np", ".", "ndarray", ")", "->", "Tuple", "[", "np", ".", "ndarray", ",", "np", ".", "ndarray", "]", ":", "if", "not", "np", ".", "allclose", "(", "M", ",", "M", ".", "transpose", "(", ")", ")", ":"...
42.333333
0.000481
def dump_private_key(private_key, passphrase, encoding='pem', target_ms=200): """ Serializes a private key object into a byte string of the PKCS#8 format :param private_key: An oscrypto.asymmetric.PrivateKey or asn1crypto.keys.PrivateKeyInfo object :param passphrase: A unicode ...
[ "def", "dump_private_key", "(", "private_key", ",", "passphrase", ",", "encoding", "=", "'pem'", ",", "target_ms", "=", "200", ")", ":", "if", "encoding", "not", "in", "set", "(", "[", "'pem'", ",", "'der'", "]", ")", ":", "raise", "ValueError", "(", "...
33.172414
0.000757
def start(lang, session_id, owner, env, mount, tag, resources, cluster_size): ''' Prepare and start a single compute session without executing codes. You may use the created session to execute codes using the "run" command or connect to an application service provided by the session using the "app" ...
[ "def", "start", "(", "lang", ",", "session_id", ",", "owner", ",", "env", ",", "mount", ",", "tag", ",", "resources", ",", "cluster_size", ")", ":", "if", "session_id", "is", "None", ":", "session_id", "=", "token_hex", "(", "5", ")", "else", ":", "s...
35.717391
0.00237
def tune(device, **kwargs): ''' Set attributes for the specified device CLI Example: .. code-block:: bash salt '*' disk.tune /dev/sda1 read-ahead=1024 read-write=True Valid options are: ``read-ahead``, ``filesystem-read-ahead``, ``read-only``, ``read-write``. See the ``blockdev(...
[ "def", "tune", "(", "device", ",", "*", "*", "kwargs", ")", ":", "kwarg_map", "=", "{", "'read-ahead'", ":", "'setra'", ",", "'filesystem-read-ahead'", ":", "'setfra'", ",", "'read-only'", ":", "'setro'", ",", "'read-write'", ":", "'setrw'", "}", "opts", "...
30.567568
0.000857
def new(self, extension_sequence): # type: (int) -> None ''' Create a new Rock Ridge Extension Selector record. Parameters: extension_sequence - The sequence number of this extension. Returns: Nothing. ''' if self._initialized: raise...
[ "def", "new", "(", "self", ",", "extension_sequence", ")", ":", "# type: (int) -> None", "if", "self", ".", "_initialized", ":", "raise", "pycdlibexception", ".", "PyCdlibInternalError", "(", "'ES record already initialized!'", ")", "self", ".", "extension_sequence", ...
31
0.008351
def include_file(filename, lineno, local_first): """ Performs a file inclusion (#include) in the preprocessor. Writes down that "filename" was included at the current file, at line <lineno>. If local_first is True, then it will first search the file in the local path before looking for it in the in...
[ "def", "include_file", "(", "filename", ",", "lineno", ",", "local_first", ")", ":", "global", "CURRENT_DIR", "filename", "=", "search_filename", "(", "filename", ",", "lineno", ",", "local_first", ")", "if", "filename", "not", "in", "INCLUDED", ".", "keys", ...
38.6
0.001264
def _get_fuzzy_tc_matches(text, full_text, options): ''' Get the options that match the full text, then from each option return only the individual words which have not yet been matched which also match the text being tab-completed. ''' print("text: {}, full: {}, options: {}".format(text, full_t...
[ "def", "_get_fuzzy_tc_matches", "(", "text", ",", "full_text", ",", "options", ")", ":", "print", "(", "\"text: {}, full: {}, options: {}\"", ".", "format", "(", "text", ",", "full_text", ",", "options", ")", ")", "# get the options which match the full text", "matchi...
47.311111
0.001841
def set_meta(self, selected_meta): """Sets one axis of the 2D multi-indexed dataframe index to the selected meta data. :param selected_meta: The list of the metadata users want to index with. """ meta_names = list(selected_meta) meta_names.append('sample') m...
[ "def", "set_meta", "(", "self", ",", "selected_meta", ")", ":", "meta_names", "=", "list", "(", "selected_meta", ")", "meta_names", ".", "append", "(", "'sample'", ")", "meta_index", "=", "[", "]", "# To set the index for existing samples in the region dataframe.", ...
51.315789
0.008056
def get_orm_classes_by_table_name_from_base(base: Type) -> Dict[str, Type]: """ Given an SQLAlchemy ORM base class, returns a dictionary whose keys are table names and whose values are ORM classes. If you begin with the proper :class`Base` class, then this should give all tables and ORM classes in ...
[ "def", "get_orm_classes_by_table_name_from_base", "(", "base", ":", "Type", ")", "->", "Dict", "[", "str", ",", "Type", "]", ":", "# noinspection PyUnresolvedReferences", "return", "{", "cls", ".", "__tablename__", ":", "cls", "for", "cls", "in", "gen_orm_classes_...
44.4
0.002208
async def check_result(method_name: str, content_type: str, status_code: int, body: str): """ Checks whether `result` is a valid API response. A result is considered invalid if: - The server returned an HTTP response code other than 200 - The content of the result is invalid JSON. - The method c...
[ "async", "def", "check_result", "(", "method_name", ":", "str", ",", "content_type", ":", "str", ",", "status_code", ":", "int", ",", "body", ":", "str", ")", ":", "log", ".", "debug", "(", "'Response for %s: [%d] \"%r\"'", ",", "method_name", ",", "status_c...
46.58
0.002103
def assign_power_curve(self, wake_losses_model='power_efficiency_curve', smoothing=False, block_width=0.5, standard_deviation_method='turbulence_intensity', smoothing_order='wind_farm_power_curves', turbulence_in...
[ "def", "assign_power_curve", "(", "self", ",", "wake_losses_model", "=", "'power_efficiency_curve'", ",", "smoothing", "=", "False", ",", "block_width", "=", "0.5", ",", "standard_deviation_method", "=", "'turbulence_intensity'", ",", "smoothing_order", "=", "'wind_farm...
48.3
0.001522
def com_daltonmaag_check_required_fields(ufo_font): """Check that required fields are present in the UFO fontinfo. ufo2ft requires these info fields to compile a font binary: unitsPerEm, ascender, descender, xHeight, capHeight and familyName. """ recommended_fields = [] for field in [ "unitsPe...
[ "def", "com_daltonmaag_check_required_fields", "(", "ufo_font", ")", ":", "recommended_fields", "=", "[", "]", "for", "field", "in", "[", "\"unitsPerEm\"", ",", "\"ascender\"", ",", "\"descender\"", ",", "\"xHeight\"", ",", "\"capHeight\"", ",", "\"familyName\"", "]...
32.578947
0.010989
def url_builder(self, latitude, longitude): """ This function is used to build the correct url to make the request to the forecast.io api. Recieves the latitude and the longitude. Return a string with the url. """ try: float(latitude) float...
[ "def", "url_builder", "(", "self", ",", "latitude", ",", "longitude", ")", ":", "try", ":", "float", "(", "latitude", ")", "float", "(", "longitude", ")", "except", "TypeError", ":", "raise", "TypeError", "(", "'Latitude (%s) and Longitude (%s) must be a float num...
43
0.001749
def write (self, data): """Write data to buffer.""" self.tmpbuf.append(data) self.pos += len(data)
[ "def", "write", "(", "self", ",", "data", ")", ":", "self", ".", "tmpbuf", ".", "append", "(", "data", ")", "self", ".", "pos", "+=", "len", "(", "data", ")" ]
29.75
0.02459
def afterglow(self, src=None, event=None, dst=None, **kargs): """Experimental clone attempt of http://sourceforge.net/projects/afterglow each datum is reduced as src -> event -> dst and the data are graphed. by default we have IP.src -> IP.dport -> IP.dst""" if src is None: s...
[ "def", "afterglow", "(", "self", ",", "src", "=", "None", ",", "event", "=", "None", ",", "dst", "=", "None", ",", "*", "*", "kargs", ")", ":", "if", "src", "is", "None", ":", "src", "=", "lambda", "x", ":", "x", "[", "'IP'", "]", ".", "src",...
35.5875
0.020848
def from_query_string(cls, schema, qs=None): """ Extract a page from the current query string. :param qs: a query string dictionary (`request.args` will be used if omitted) """ dct = load_query_string_data(schema, qs) return cls.from_dict(dct)
[ "def", "from_query_string", "(", "cls", ",", "schema", ",", "qs", "=", "None", ")", ":", "dct", "=", "load_query_string_data", "(", "schema", ",", "qs", ")", "return", "cls", ".", "from_dict", "(", "dct", ")" ]
31.666667
0.010239
def get_api_service(self, name=None): """Returns the specific service config definition""" try: svc = self.services_by_name.get(name, None) if svc is None: raise ValueError(f"Couldn't find the API service configuration") return svc except: # N...
[ "def", "get_api_service", "(", "self", ",", "name", "=", "None", ")", ":", "try", ":", "svc", "=", "self", ".", "services_by_name", ".", "get", "(", "name", ",", "None", ")", "if", "svc", "is", "None", ":", "raise", "ValueError", "(", "f\"Couldn't find...
44
0.009901
def gammatone(freq, bandwidth, phase=0, eta=4): """ ``Bellini, D. J. S. "AudioLazy: Processamento digital de sinais expressivo e em tempo real", IME-USP, Mastership Thesis, 2013.`` This implementation have the impulse response (for each sample ``n``, keeping the input parameter names): .. math:: ...
[ "def", "gammatone", "(", "freq", ",", "bandwidth", ",", "phase", "=", "0", ",", "eta", "=", "4", ")", ":", "assert", "eta", ">=", "1", "A", "=", "exp", "(", "-", "bandwidth", ")", "numerator", "=", "cos", "(", "phase", ")", "-", "A", "*", "cos"...
35.16
0.018826
def _orbitNumberBreaks(self): """Determine where orbital breaks in a dataset with orbit numbers occur. Looks for changes in unique values. """ if self.orbit_index is None: raise ValueError('Orbit properties must be defined at ' + 'pysat.Instrum...
[ "def", "_orbitNumberBreaks", "(", "self", ")", ":", "if", "self", ".", "orbit_index", "is", "None", ":", "raise", "ValueError", "(", "'Orbit properties must be defined at '", "+", "'pysat.Instrument object instantiation.'", "+", "'See Instrument docs.'", ")", "else", ":...
36.277778
0.002237