text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def expect(self): ''' Add an expectation to this stub. Return the expectation. ''' exp = Expectation(self) self._expectations.append(exp) return exp
[ "def", "expect", "(", "self", ")", ":", "exp", "=", "Expectation", "(", "self", ")", "self", ".", "_expectations", ".", "append", "(", "exp", ")", "return", "exp" ]
27.142857
0.010204
def trigger_to_dict(trigger): """Converts a trigger to an OrderedDict.""" data = OrderedDict() if isinstance(trigger, DateTrigger): data['trigger'] = 'date' data['run_date'] = trigger.run_date elif isinstance(trigger, IntervalTrigger): data['trigger'] = 'interval' data[...
[ "def", "trigger_to_dict", "(", "trigger", ")", ":", "data", "=", "OrderedDict", "(", ")", "if", "isinstance", "(", "trigger", ",", "DateTrigger", ")", ":", "data", "[", "'trigger'", "]", "=", "'date'", "data", "[", "'run_date'", "]", "=", "trigger", ".",...
26.255814
0.000854
def _print_console_link(region, application_id): """ Print link for the application in AWS Serverless Application Repository console. Parameters ---------- region : str AWS region name application_id : str The Amazon Resource Name (ARN) of the application """ if not reg...
[ "def", "_print_console_link", "(", "region", ",", "application_id", ")", ":", "if", "not", "region", ":", "region", "=", "boto3", ".", "Session", "(", ")", ".", "region_name", "console_link", "=", "SERVERLESSREPO_CONSOLE_URL", ".", "format", "(", "region", ","...
32.277778
0.006689
def dispatch(self, *args, **kwargs): """This decorator sets this view to have restricted permissions.""" return super(StrainDelete, self).dispatch(*args, **kwargs)
[ "def", "dispatch", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "StrainDelete", ",", "self", ")", ".", "dispatch", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
59
0.011173
def getTokensEndLoc(): """Method to be called from within a parse action to determine the end location of the parsed tokens.""" import inspect fstack = inspect.stack() try: # search up the stack (through intervening argument normalizers) for correct calling routine for f in...
[ "def", "getTokensEndLoc", "(", ")", ":", "import", "inspect", "fstack", "=", "inspect", ".", "stack", "(", ")", "try", ":", "# search up the stack (through intervening argument normalizers) for correct calling routine\r", "for", "f", "in", "fstack", "[", "2", ":", "]"...
40.733333
0.0048
def verify_editor(self): """Verify if the software used in the changeset is a powerfull_editor. """ powerful_editors = [ 'josm', 'level0', 'merkaartor', 'qgis', 'arcgis', 'upload.py', 'osmapi', 'Services_OpenStreetMap' ] if self.editor is not None: ...
[ "def", "verify_editor", "(", "self", ")", ":", "powerful_editors", "=", "[", "'josm'", ",", "'level0'", ",", "'merkaartor'", ",", "'qgis'", ",", "'arcgis'", ",", "'upload.py'", ",", "'osmapi'", ",", "'Services_OpenStreetMap'", "]", "if", "self", ".", "editor",...
41.290323
0.001527
def with_options(self, component): """Apply options component options to this configuration.""" options = component.get_required_config() component_name = _get_component_name(component) return BoundConfig(self._get_base_config(), component_name, options)
[ "def", "with_options", "(", "self", ",", "component", ")", ":", "options", "=", "component", ".", "get_required_config", "(", ")", "component_name", "=", "_get_component_name", "(", "component", ")", "return", "BoundConfig", "(", "self", ".", "_get_base_config", ...
56.4
0.006993
def reset(self): """ Factory reset all of Vent's user data, containers, and images """ status = (True, None) error_message = '' # remove containers try: c_list = set(self.d_client.containers.list( filters={'label': 'vent'}, all=True)) for ...
[ "def", "reset", "(", "self", ")", ":", "status", "=", "(", "True", ",", "None", ")", "error_message", "=", "''", "# remove containers", "try", ":", "c_list", "=", "set", "(", "self", ".", "d_client", ".", "containers", ".", "list", "(", "filters", "=",...
38.825
0.001256
def consolidateBy(requestContext, seriesList, consolidationFunc): """ Takes one metric or a wildcard seriesList and a consolidation function name. Valid function names are 'sum', 'average', 'min', and 'max'. When a graph is drawn where width of the graph size in pixels is smaller than the numb...
[ "def", "consolidateBy", "(", "requestContext", ",", "seriesList", ",", "consolidationFunc", ")", ":", "for", "series", "in", "seriesList", ":", "# datalib will throw an exception, so it's not necessary to validate", "# here", "series", ".", "consolidationFunc", "=", "consol...
41.344828
0.000815
def getinfo(ee_obj, n=4): """Make an exponential back off getInfo call on an Earth Engine object""" output = None for i in range(1, n): try: output = ee_obj.getInfo() except ee.ee_exception.EEException as e: if 'Earth Engine memory capacity exceeded' in str(e): ...
[ "def", "getinfo", "(", "ee_obj", ",", "n", "=", "4", ")", ":", "output", "=", "None", "for", "i", "in", "range", "(", "1", ",", "n", ")", ":", "try", ":", "output", "=", "ee_obj", ".", "getInfo", "(", ")", "except", "ee", ".", "ee_exception", "...
30.315789
0.001684
def delete_item(self, token, item_id): """ Delete the item with the passed in item_id. :param token: A valid token for the user in question. :type token: string :param item_id: The id of the item to be deleted. :type item_id: int | long :returns: None. :r...
[ "def", "delete_item", "(", "self", ",", "token", ",", "item_id", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'token'", "]", "=", "token", "parameters", "[", "'id'", "]", "=", "item_id", "response", "=", "self", ".", "request", "(...
32.1875
0.003774
def download_pac(candidate_urls, timeout=1, allowed_content_types=None): """ Try to download a PAC file from one of the given candidate URLs. :param list[str] candidate_urls: URLs that are expected to return a PAC file. Requests are made in order, one by one. :param timeout: Time to wait ...
[ "def", "download_pac", "(", "candidate_urls", ",", "timeout", "=", "1", ",", "allowed_content_types", "=", "None", ")", ":", "if", "not", "allowed_content_types", ":", "allowed_content_types", "=", "{", "'application/x-ns-proxy-autoconfig'", ",", "'application/x-javascr...
52.9
0.005569
def clear(self): """ Clears the tables and the message list """ QtWidgets.QTableWidget.clear(self) self.setRowCount(0) self.setColumnCount(4) self.setHorizontalHeaderLabels( ["Type", "File name", "Line", "Description"])
[ "def", "clear", "(", "self", ")", ":", "QtWidgets", ".", "QTableWidget", ".", "clear", "(", "self", ")", "self", ".", "setRowCount", "(", "0", ")", "self", ".", "setColumnCount", "(", "4", ")", "self", ".", "setHorizontalHeaderLabels", "(", "[", "\"Type\...
31
0.006969
def show(context, log, results_file, verbose, item): """ Print test results info from provided results json file. If no results file is supplied echo results from most recent test in history if it exists. If verbose option selected, echo all test cases. If ...
[ "def", "show", "(", "context", ",", "log", ",", "results_file", ",", "verbose", ",", "item", ")", ":", "history_log", "=", "context", ".", "obj", "[", "'history_log'", "]", "no_color", "=", "context", ".", "obj", "[", "'no_color'", "]", "if", "not", "r...
28.017857
0.000616
def RGB_to_HSL(cobj, *args, **kwargs): """ Converts from RGB to HSL. H values are in degrees and are 0 to 360. S values are a percentage, 0.0 to 1.0. L values are a percentage, 0.0 to 1.0. """ var_R = cobj.rgb_r var_G = cobj.rgb_g var_B = cobj.rgb_b var_max = max(var_R, var_G, ...
[ "def", "RGB_to_HSL", "(", "cobj", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "var_R", "=", "cobj", ".", "rgb_r", "var_G", "=", "cobj", ".", "rgb_g", "var_B", "=", "cobj", ".", "rgb_b", "var_max", "=", "max", "(", "var_R", ",", "var_G", ...
25.333333
0.001408
def extend_node_list(acc, new): """Extend accumulator with Node(s) from new""" if new is None: new = [] elif not isinstance(new, list): new = [new] return acc + new
[ "def", "extend_node_list", "(", "acc", ",", "new", ")", ":", "if", "new", "is", "None", ":", "new", "=", "[", "]", "elif", "not", "isinstance", "(", "new", ",", "list", ")", ":", "new", "=", "[", "new", "]", "return", "acc", "+", "new" ]
30.571429
0.009091
def extract_value(self, data): """Extract the id key and validate the request structure.""" errors = [] if 'id' not in data: errors.append('Must have an `id` field') if 'type' not in data: errors.append('Must have a `type` field') elif data['type'] != self...
[ "def", "extract_value", "(", "self", ",", "data", ")", ":", "errors", "=", "[", "]", "if", "'id'", "not", "in", "data", ":", "errors", ".", "append", "(", "'Must have an `id` field'", ")", "if", "'type'", "not", "in", "data", ":", "errors", ".", "appen...
38.576923
0.002918
def tmppath(root=TEMPS_DIR, prefix=TEMPS_PREFIX, suffix=TEMPS_SUFFIX): ''' Returns a path directly under root that is guaranteed to be unique by using the uuid module. ''' return os.path.join(root, prefix + uuid.uuid4().hex + suffix)
[ "def", "tmppath", "(", "root", "=", "TEMPS_DIR", ",", "prefix", "=", "TEMPS_PREFIX", ",", "suffix", "=", "TEMPS_SUFFIX", ")", ":", "return", "os", ".", "path", ".", "join", "(", "root", ",", "prefix", "+", "uuid", ".", "uuid4", "(", ")", ".", "hex", ...
41.333333
0.003953
def coalesce_headers(cls, header_lines): """Collects headers that are spread across multiple lines into a single row""" header_lines = [list(hl) for hl in header_lines if bool(hl)] if len(header_lines) == 0: return [] if len(header_lines) == 1: return header_li...
[ "def", "coalesce_headers", "(", "cls", ",", "header_lines", ")", ":", "header_lines", "=", "[", "list", "(", "hl", ")", "for", "hl", "in", "header_lines", "if", "bool", "(", "hl", ")", "]", "if", "len", "(", "header_lines", ")", "==", "0", ":", "retu...
32.535714
0.00533
def delete(self): """delete the file from the filesystem.""" if self.isfile: os.remove(self.fn) elif self.isdir: shutil.rmtree(self.fn)
[ "def", "delete", "(", "self", ")", ":", "if", "self", ".", "isfile", ":", "os", ".", "remove", "(", "self", ".", "fn", ")", "elif", "self", ".", "isdir", ":", "shutil", ".", "rmtree", "(", "self", ".", "fn", ")" ]
29.666667
0.010929
def namespaced_function(function, global_dict, defaults=None, preserve_context=False): ''' Redefine (clone) a function under a different globals() namespace scope preserve_context: Allow keeping the context taken from orignal namespace, and extend it with globals() taken from ...
[ "def", "namespaced_function", "(", "function", ",", "global_dict", ",", "defaults", "=", "None", ",", "preserve_context", "=", "False", ")", ":", "if", "defaults", "is", "None", ":", "defaults", "=", "function", ".", "__defaults__", "if", "preserve_context", "...
34.16
0.002278
def search_issues(self, query, sort=None, order=None, per_page=None, text_match=False, number=-1, etag=None): """Find issues by state and keyword The query can contain any combination of the following supported qualifers: - ``type`` With this qualifier you can res...
[ "def", "search_issues", "(", "self", ",", "query", ",", "sort", "=", "None", ",", "order", "=", "None", ",", "per_page", "=", "None", ",", "text_match", "=", "False", ",", "number", "=", "-", "1", ",", "etag", "=", "None", ")", ":", "params", "=", ...
46.40625
0.000989
def is_time(self): """Determine if a data record is of type TIME.""" dt = DATA_TYPES['time'] if type(self.data) is dt['type'] and ':' in str(self.data) and str(self.data).count(':') == 2: # Separate hour, month, second date_split = str(self.data).split(':') h,...
[ "def", "is_time", "(", "self", ")", ":", "dt", "=", "DATA_TYPES", "[", "'time'", "]", "if", "type", "(", "self", ".", "data", ")", "is", "dt", "[", "'type'", "]", "and", "':'", "in", "str", "(", "self", ".", "data", ")", "and", "str", "(", "sel...
45
0.005806
def _get_template_from_string(self, ostmpl): ''' Get a jinja2 template object from a string. :param ostmpl: OSConfigTemplate to use as a data source. ''' self._get_tmpl_env() template = self._tmpl_env.from_string(ostmpl.config_template) log('Loaded a template from...
[ "def", "_get_template_from_string", "(", "self", ",", "ostmpl", ")", ":", "self", ".", "_get_tmpl_env", "(", ")", "template", "=", "self", ".", "_tmpl_env", ".", "from_string", "(", "ostmpl", ".", "config_template", ")", "log", "(", "'Loaded a template from a st...
37.818182
0.004695
def get_student_activity_for_sis_course_id_and_sis_user_id( self, sis_user_id, sis_course_id): """ Returns student activity data for the given user_id and course_id. https://canvas.instructure.com/doc/api/analytics.html#method.analytics_api.student_in_course_participation ""...
[ "def", "get_student_activity_for_sis_course_id_and_sis_user_id", "(", "self", ",", "sis_user_id", ",", "sis_course_id", ")", ":", "url", "=", "(", "\"/api/v1/courses/%s/analytics/users/\"", "\"sis_user_id:%s/activity.json\"", ")", "%", "(", "self", ".", "_sis_id", "(", "s...
48
0.003717
def _cho_solve_AATI(A, rho, b, c, lwr, check_finite=True): """Patched version of :func:`sporco.linalg.cho_solve_AATI`.""" N, M = A.shape if N >= M: x = (b - _cho_solve((c, lwr), b.dot(A).T, check_finite=check_finite).T.dot(A.T)) / rho else: x = _cho_solve((c, lwr), b.T, chec...
[ "def", "_cho_solve_AATI", "(", "A", ",", "rho", ",", "b", ",", "c", ",", "lwr", ",", "check_finite", "=", "True", ")", ":", "N", ",", "M", "=", "A", ".", "shape", "if", "N", ">=", "M", ":", "x", "=", "(", "b", "-", "_cho_solve", "(", "(", "...
34.8
0.005602
def _transformBy(self, matrix, **kwargs): """ Subclasses may override this method. """ anchor = self.anchor bcpIn = absoluteBCPIn(anchor, self.bcpIn) bcpOut = absoluteBCPOut(anchor, self.bcpOut) points = [bcpIn, anchor, bcpOut] t = transform.Transform(*mat...
[ "def", "_transformBy", "(", "self", ",", "matrix", ",", "*", "*", "kwargs", ")", ":", "anchor", "=", "self", ".", "anchor", "bcpIn", "=", "absoluteBCPIn", "(", "anchor", ",", "self", ".", "bcpIn", ")", "bcpOut", "=", "absoluteBCPOut", "(", "anchor", ",...
36.333333
0.003578
def dataset_format_to_extension(ds_format): """ Get the preferred Dataset format extension :param str ds_format: Format of the Dataset (expected to be one of `csv` or `xml`) :rtype: str """ try: return DATASET_FORMATS[ds_format] except KeyError: raise ValueError( ...
[ "def", "dataset_format_to_extension", "(", "ds_format", ")", ":", "try", ":", "return", "DATASET_FORMATS", "[", "ds_format", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "\"dataset_format is expected to be one of %s. '%s' is not valid\"", "%", "(", "\", \""...
31.571429
0.004396
def instantiate_with_credentials(credentials, **config): ''' Initialize the client against an HSv8 instance with full read/write access. :param credentials: A credentials object, see separate class PIDClientCredentials. :param \**config: More key-value pairs may be p...
[ "def", "instantiate_with_credentials", "(", "credentials", ",", "*", "*", "config", ")", ":", "key_value_pairs", "=", "credentials", ".", "get_all_args", "(", ")", "if", "config", "is", "not", "None", ":", "key_value_pairs", ".", "update", "(", "*", "*", "co...
43
0.006826
def get_current_session(request, hproPk): """Get the current session value""" retour = {} base_key = 'plugit_' + str(hproPk) + '_' for key, value in request.session.iteritems(): if key.startswith(base_key): retour[key[len(base_key):]] = value return retour
[ "def", "get_current_session", "(", "request", ",", "hproPk", ")", ":", "retour", "=", "{", "}", "base_key", "=", "'plugit_'", "+", "str", "(", "hproPk", ")", "+", "'_'", "for", "key", ",", "value", "in", "request", ".", "session", ".", "iteritems", "("...
24.083333
0.003333
def _get_class_lib(self): ''' If the range is from a to b, we try a few numbers around the arrows a b +-------------------------------------------+ ^ ^ ^ ^ ^ ''' lib = [] num_sec...
[ "def", "_get_class_lib", "(", "self", ")", ":", "lib", "=", "[", "]", "num_sections", "=", "4", "for", "i", "in", "range", "(", "3", ")", ":", "lib", ".", "append", "(", "(", "(", "lambda", "x", ",", "i", "=", "i", ":", "x", ".", "_min_value", ...
44.387097
0.00569
def python_version_matchers(): """Return set of string representations of current python version""" version = sys.version_info patterns = [ "{0}", "{0}{1}", "{0}.{1}", ] matchers = [ pattern.format(*version) for pattern in patterns ] + [None] return se...
[ "def", "python_version_matchers", "(", ")", ":", "version", "=", "sys", ".", "version_info", "patterns", "=", "[", "\"{0}\"", ",", "\"{0}{1}\"", ",", "\"{0}.{1}\"", ",", "]", "matchers", "=", "[", "pattern", ".", "format", "(", "*", "version", ")", "for", ...
24.538462
0.003021
def putcolslice(self, columnname, value, blc, trc, inc=[], startrow=0, nrow=-1, rowincr=1): """Put into a slice in a table column holding arrays. Its arguments are the same as for getcolslice and putcellslice. """ self._putcolslice(columnname, value, blc, trc, inc, ...
[ "def", "putcolslice", "(", "self", ",", "columnname", ",", "value", ",", "blc", ",", "trc", ",", "inc", "=", "[", "]", ",", "startrow", "=", "0", ",", "nrow", "=", "-", "1", ",", "rowincr", "=", "1", ")", ":", "self", ".", "_putcolslice", "(", ...
40.222222
0.008108
def _lvarx(ins): """ Defines a local variable. 1st param is offset of the local variable. 2nd param is the type a list of bytes in hexadecimal. """ output = [] l = eval(ins.quad[3]) # List of bytes to push label = tmp_label() offset = int(ins.quad[1]) tmp = list(ins.quad) tmp[1] = ...
[ "def", "_lvarx", "(", "ins", ")", ":", "output", "=", "[", "]", "l", "=", "eval", "(", "ins", ".", "quad", "[", "3", "]", ")", "# List of bytes to push", "label", "=", "tmp_label", "(", ")", "offset", "=", "int", "(", "ins", ".", "quad", "[", "1"...
27.625
0.002915
def encodeSentence(self, *words): """ Encode given sentence in API format. :param words: Words to endoce. :returns: Encoded sentence. """ encoded = map(self.encodeWord, words) encoded = b''.join(encoded) # append EOS (end of sentence) byte encoded...
[ "def", "encodeSentence", "(", "self", ",", "*", "words", ")", ":", "encoded", "=", "map", "(", "self", ".", "encodeWord", ",", "words", ")", "encoded", "=", "b''", ".", "join", "(", "encoded", ")", "# append EOS (end of sentence) byte", "encoded", "+=", "b...
28.583333
0.00565
def _calc_keys(self, config, name, timestamp): ''' Calculate keys given a stat name and timestamp. ''' i_bucket = config['i_calc'].to_bucket( timestamp ) r_bucket = config['r_calc'].to_bucket( timestamp ) i_key = '%s%s:%s:%s'%(self._prefix, name, config['interval'], i_bucket) r_key = '%s:%s...
[ "def", "_calc_keys", "(", "self", ",", "config", ",", "name", ",", "timestamp", ")", ":", "i_bucket", "=", "config", "[", "'i_calc'", "]", ".", "to_bucket", "(", "timestamp", ")", "r_bucket", "=", "config", "[", "'r_calc'", "]", ".", "to_bucket", "(", ...
34
0.018229
def encode_bytes(obj, nsprefix=None): """ Encodes an OpenMath element into a string. :param obj: Object to encode as string. :type obj: OMAny :rtype: bytes """ node = encode_xml(obj, nsprefix) return etree.tostring(node)
[ "def", "encode_bytes", "(", "obj", ",", "nsprefix", "=", "None", ")", ":", "node", "=", "encode_xml", "(", "obj", ",", "nsprefix", ")", "return", "etree", ".", "tostring", "(", "node", ")" ]
21.909091
0.003984
def _get_SEQRES_sequences(self): '''Creates the SEQRES Sequences and stores the chains in order of their appearance in the SEQRES records. This order of chains in the SEQRES sequences does not always agree with the order in the ATOM records.''' pdb_id = self.get_pdb_id() SEQRES_lines...
[ "def", "_get_SEQRES_sequences", "(", "self", ")", ":", "pdb_id", "=", "self", ".", "get_pdb_id", "(", ")", "SEQRES_lines", "=", "self", ".", "parsed_lines", "[", "\"SEQRES\"", "]", "modified_residue_mapping_3", "=", "self", ".", "modified_residue_mapping_3", "# I ...
53.291971
0.004034
def main(self): """Main satellite function. Do init and then mainloop :return: None """ try: # Start the daemon mode if not self.do_daemon_init_and_start(): self.exit_on_error(message="Daemon initialization error", exit_code=3) self.d...
[ "def", "main", "(", "self", ")", ":", "try", ":", "# Start the daemon mode", "if", "not", "self", ".", "do_daemon_init_and_start", "(", ")", ":", "self", ".", "exit_on_error", "(", "message", "=", "\"Daemon initialization error\"", ",", "exit_code", "=", "3", ...
31.931034
0.004193
def _get_evanno_table(self, kpops, max_var_multiple, quiet): """ Calculates Evanno method K value scores for a series of permuted clumpp results. """ ## iterate across k-vals kpops = sorted(kpops) replnliks = [] for kpop in kpops: ## concat results for k=x reps, exclud...
[ "def", "_get_evanno_table", "(", "self", ",", "kpops", ",", "max_var_multiple", ",", "quiet", ")", ":", "## iterate across k-vals", "kpops", "=", "sorted", "(", "kpops", ")", "replnliks", "=", "[", "]", "for", "kpop", "in", "kpops", ":", "## concat results for...
31.176471
0.008688
def pages_dynamic_tree_menu(context, page, url='/'): """ Render a "dynamic" tree menu, with all nodes expanded which are either ancestors or the current page itself. Override ``pages/dynamic_tree_menu.html`` if you want to change the design. :param page: the current page :param url: not us...
[ "def", "pages_dynamic_tree_menu", "(", "context", ",", "page", ",", "url", "=", "'/'", ")", ":", "lang", "=", "context", ".", "get", "(", "'lang'", ",", "pages_settings", ".", "PAGE_DEFAULT_LANGUAGE", ")", "page", "=", "get_page_from_string_or_id", "(", "page"...
38.038462
0.000986
def delete_quick(self, get_count=False): """ Deletes the table without cascading and without user prompt. If this table has populated dependent tables, this will fail. """ query = 'DELETE FROM ' + self.full_table_name + self.where_clause self.connection.query(query) ...
[ "def", "delete_quick", "(", "self", ",", "get_count", "=", "False", ")", ":", "query", "=", "'DELETE FROM '", "+", "self", ".", "full_table_name", "+", "self", ".", "where_clause", "self", ".", "connection", ".", "query", "(", "query", ")", "count", "=", ...
45.4
0.006479
def calcOffset(self, x, y): """Calculate offset into data array. Only uses to test correctness of the formula.""" # Datalayout # X = longitude # Y = latitude # Sample for size 1201x1201 # ( 0/1200) ( 1/1200) ... (1199/1200) (1200/1200) ...
[ "def", "calcOffset", "(", "self", ",", "x", ",", "y", ")", ":", "# Datalayout", "# X = longitude", "# Y = latitude", "# Sample for size 1201x1201", "# ( 0/1200) ( 1/1200) ... (1199/1200) (1200/1200)", "# ( 0/1199) ( 1/1199) ... (1199/1199) (1200/1199)", ...
42.2
0.002317
def clean(self, value): """ Convert the value's type and run validation. Validation errors from to_python and validate are propagated. The correct value is returned if no error is raised. """ value = self.to_python(value) self.validate(value) return value
[ "def", "clean", "(", "self", ",", "value", ")", ":", "value", "=", "self", ".", "to_python", "(", "value", ")", "self", ".", "validate", "(", "value", ")", "return", "value" ]
34.555556
0.00627
def can_solve(cls, filter_): """Tells if the solver is able to resolve the given filter. Arguments --------- filter_ : subclass of dataql.resources.BaseFilter The subclass or ``BaseFilter`` to check if it is solvable by the current solver class. Returns ----...
[ "def", "can_solve", "(", "cls", ",", "filter_", ")", ":", "for", "solvable_filter", "in", "cls", ".", "solvable_filters", ":", "if", "isinstance", "(", "filter_", ",", "solvable_filter", ")", ":", "return", "True", "return", "False" ]
28.793103
0.004635
def Write(self): """Write out the updated configuration to the fd.""" if self.writeback: self.writeback.SaveData(self.writeback_data) else: raise RuntimeError("Attempting to write a configuration without a " "writeback location.")
[ "def", "Write", "(", "self", ")", ":", "if", "self", ".", "writeback", ":", "self", ".", "writeback", ".", "SaveData", "(", "self", ".", "writeback_data", ")", "else", ":", "raise", "RuntimeError", "(", "\"Attempting to write a configuration without a \"", "\"wr...
39
0.010753
def version(): """Return version string.""" with io.open('pgmagick/_version.py') as input_file: for line in input_file: if line.startswith('__version__'): return ast.parse(line).body[0].value.s
[ "def", "version", "(", ")", ":", "with", "io", ".", "open", "(", "'pgmagick/_version.py'", ")", "as", "input_file", ":", "for", "line", "in", "input_file", ":", "if", "line", ".", "startswith", "(", "'__version__'", ")", ":", "return", "ast", ".", "parse...
38.666667
0.004219
def toTFExample(image, label): """Serializes an image/label as a TFExample byte string""" example = tf.train.Example( features=tf.train.Features( feature={ 'label': tf.train.Feature(int64_list=tf.train.Int64List(value=label.astype("int64"))), 'image': tf.train.Feature(int64_list=tf.train.I...
[ "def", "toTFExample", "(", "image", ",", "label", ")", ":", "example", "=", "tf", ".", "train", ".", "Example", "(", "features", "=", "tf", ".", "train", ".", "Features", "(", "feature", "=", "{", "'label'", ":", "tf", ".", "train", ".", "Feature", ...
36.636364
0.014528
def unique(self): """ Get all unique values in the current SArray. Raises a TypeError if the SArray is of dictionary type. Will not necessarily preserve the order of the given SArray in the new SArray. Returns ------- out : SArray A new SArray that ...
[ "def", "unique", "(", "self", ")", ":", "from", ".", "sframe", "import", "SFrame", "as", "_SFrame", "tmp_sf", "=", "_SFrame", "(", ")", "tmp_sf", ".", "add_column", "(", "self", ",", "'X1'", ",", "inplace", "=", "True", ")", "res", "=", "tmp_sf", "."...
25.2
0.004587
def remove_pid_file(self): """Remove the pid file. This should be called at shutdown by registering a callback with :func:`reactor.addSystemEventTrigger`. This needs to return ``None``. """ pid_file = os.path.join(self.profile_dir.pid_dir, self.name + u'.pid') if...
[ "def", "remove_pid_file", "(", "self", ")", ":", "pid_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "profile_dir", ".", "pid_dir", ",", "self", ".", "name", "+", "u'.pid'", ")", "if", "os", ".", "path", ".", "isfile", "(", "pid_file",...
39.142857
0.005348
def addPointVectors(self, vectors, name): """ Add a point vector field to the actor's polydata assigning it a name. """ poly = self.polydata(False) if len(vectors) != poly.GetNumberOfPoints(): colors.printc('~times addPointVectors Error: Number of vectors != nr. of po...
[ "def", "addPointVectors", "(", "self", ",", "vectors", ",", "name", ")", ":", "poly", "=", "self", ".", "polydata", "(", "False", ")", "if", "len", "(", "vectors", ")", "!=", "poly", ".", "GetNumberOfPoints", "(", ")", ":", "colors", ".", "printc", "...
39.529412
0.00436
def get_df_payload(self, query_obj, **kwargs): """Handles caching around the df paylod retrieval""" cache_key = query_obj.cache_key( datasource=self.datasource.uid, **kwargs) if query_obj else None logging.info('Cache key: {}'.format(cache_key)) is_loaded = False stac...
[ "def", "get_df_payload", "(", "self", ",", "query_obj", ",", "*", "*", "kwargs", ")", ":", "cache_key", "=", "query_obj", ".", "cache_key", "(", "datasource", "=", "self", ".", "datasource", ".", "uid", ",", "*", "*", "kwargs", ")", "if", "query_obj", ...
40.918605
0.000832
def k_in_row(self, board, move, player, (delta_x, delta_y)): "Return true if there is a line through move on board for player." x, y = move n = 0 # n is number of moves in row while board.get((x, y)) == player: n += 1 x, y = x + delta_x, y + delta_y x, y =...
[ "def", "k_in_row", "(", "self", ",", "board", ",", "move", ",", "player", ",", "(", "delta_x", ",", "delta_y", ")", ")", ":", "x", ",", "y", "=", "move", "n", "=", "0", "# n is number of moves in row", "while", "board", ".", "get", "(", "(", "x", "...
38.461538
0.007813
def list_instances(self, filter_="", page_size=None, page_token=None): """List instances for the client's project. See https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.InstanceAdmin.ListInstances :type filter_: string ...
[ "def", "list_instances", "(", "self", ",", "filter_", "=", "\"\"", ",", "page_size", "=", "None", ",", "page_token", "=", "None", ")", ":", "metadata", "=", "_metadata_with_prefix", "(", "self", ".", "project_name", ")", "path", "=", "\"projects/%s\"", "%", ...
44.810811
0.001181
async def sendAudio(self, chat_id, audio, caption=None, parse_mode=None, duration=None, performer=None, title=None, disable_notification=None, reply_to_...
[ "async", "def", "sendAudio", "(", "self", ",", "chat_id", ",", "audio", ",", "caption", "=", "None", ",", "parse_mode", "=", "None", ",", "duration", "=", "None", ",", "performer", "=", "None", ",", "title", "=", "None", ",", "disable_notification", "=",...
41.3125
0.016272
def _create_and_add_parameters(params): ''' Parses the configuration and creates Parameter instances. ''' global _current_parameter if _is_simple_type(params): _current_parameter = SimpleParameter(params) _current_option.add_parameter(_current_parameter) else: # must be a...
[ "def", "_create_and_add_parameters", "(", "params", ")", ":", "global", "_current_parameter", "if", "_is_simple_type", "(", "params", ")", ":", "_current_parameter", "=", "SimpleParameter", "(", "params", ")", "_current_option", ".", "add_parameter", "(", "_current_pa...
35.352941
0.001621
def data(self, *args): '''Add or retrieve data values for this :class:`Html`.''' data = self._data if not args: return data or {} result, adding = self._attrdata('data', *args) if adding: if data is None: self._extra['data'] = {} ...
[ "def", "data", "(", "self", ",", "*", "args", ")", ":", "data", "=", "self", ".", "_data", "if", "not", "args", ":", "return", "data", "or", "{", "}", "result", ",", "adding", "=", "self", ".", "_attrdata", "(", "'data'", ",", "*", "args", ")", ...
32.266667
0.004016
def _validate_message(self, message): """Validate XML response from iLO. This function validates the XML response to see if the exit status is 0 or not in the response. If the status is non-zero it raises exception. """ if message.tag != 'RIBCL': # the true c...
[ "def", "_validate_message", "(", "self", ",", "message", ")", ":", "if", "message", ".", "tag", "!=", "'RIBCL'", ":", "# the true case shall be unreachable for response", "# XML from Ilo as all messages are tagged with RIBCL", "# but still raise an exception if any invalid", "# X...
49.45098
0.000778
def __setup(local_download_dir_warc, log_level): """ Setup :return: """ if not os.path.exists(local_download_dir_warc): os.makedirs(local_download_dir_warc) # make loggers quite configure_logging({"LOG_LEVEL": "ERROR"}) logging.getLogger('requests').setLevel(logging.CRITICAL) ...
[ "def", "__setup", "(", "local_download_dir_warc", ",", "log_level", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "local_download_dir_warc", ")", ":", "os", ".", "makedirs", "(", "local_download_dir_warc", ")", "# make loggers quite", "configure_lo...
35.285714
0.001314
def merge_units(self, unit_ids): '''This function merges two roots from the curation tree according to the given unit_ids. It creates a new unit_id and root that has the merged roots as children. Parameters ---------- unit_ids: list The unit ids to be merged ...
[ "def", "merge_units", "(", "self", ",", "unit_ids", ")", ":", "root_ids", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "self", ".", "_roots", ")", ")", ":", "root_id", "=", "self", ".", "_roots", "[", "i", "]", ".", "unit_id", "root...
48.381818
0.005157
def friends(self): """ :return: Iterator of :class:`stravalib.model.Athlete` friend objects for this athlete. """ if self._friends is None: self.assert_bind_client() if self.friend_count > 0: self._friends = self.bind_client.get_athlete_friends(sel...
[ "def", "friends", "(", "self", ")", ":", "if", "self", ".", "_friends", "is", "None", ":", "self", ".", "assert_bind_client", "(", ")", "if", "self", ".", "friend_count", ">", "0", ":", "self", ".", "_friends", "=", "self", ".", "bind_client", ".", "...
37.583333
0.006494
def _keep_positive(self): '''Internal method to strip elements with a negative or zero count''' nonpositive = [elem for elem, count in self.items() if not count > 0] for elem in nonpositive: del self[elem] return self
[ "def", "_keep_positive", "(", "self", ")", ":", "nonpositive", "=", "[", "elem", "for", "elem", ",", "count", "in", "self", ".", "items", "(", ")", "if", "not", "count", ">", "0", "]", "for", "elem", "in", "nonpositive", ":", "del", "self", "[", "e...
42.666667
0.007663
def add_summary(self, summary, global_step=None): """Adds a `Summary` protocol buffer to the event file. This method wraps the provided summary in an `Event` protocol buffer and adds it to the event file. Parameters ---------- summary : A `Summary` protocol buffer ...
[ "def", "add_summary", "(", "self", ",", "summary", ",", "global_step", "=", "None", ")", ":", "if", "isinstance", "(", "summary", ",", "bytes", ")", ":", "summ", "=", "summary_pb2", ".", "Summary", "(", ")", "summ", ".", "ParseFromString", "(", "summary"...
39.388889
0.004129
def get_publisher_doc(self): """Return a publish safe version of the frame's document""" with self.draft_context(): # Select the draft document from the database draft = self.one(Q._uid == self._uid) publisher_doc = draft._document # Remove any keys from ...
[ "def", "get_publisher_doc", "(", "self", ")", ":", "with", "self", ".", "draft_context", "(", ")", ":", "# Select the draft document from the database", "draft", "=", "self", ".", "one", "(", "Q", ".", "_uid", "==", "self", ".", "_uid", ")", "publisher_doc", ...
40.333333
0.00404
def add_resource(self, data): """Add binary resource :param string data: Binary Data """ data = gntp.shim.b(data) identifier = hashlib.md5(data).hexdigest() self.resources[identifier] = data return 'x-growl-resource://%s' % identifier
[ "def", "add_resource", "(", "self", ",", "data", ")", ":", "data", "=", "gntp", ".", "shim", ".", "b", "(", "data", ")", "identifier", "=", "hashlib", ".", "md5", "(", "data", ")", ".", "hexdigest", "(", ")", "self", ".", "resources", "[", "identif...
26.777778
0.036145
def sendrawtransaction(cls, rawtxn: str) -> str: '''sendrawtransaction remote API''' if cls.is_testnet: url = 'https://testnet-explorer.peercoin.net/api/sendrawtransaction?hex={0}'.format(rawtxn) else: url = 'https://explorer.peercoin.net/api/sendrawtransaction?hex={0}'....
[ "def", "sendrawtransaction", "(", "cls", ",", "rawtxn", ":", "str", ")", "->", "str", ":", "if", "cls", ".", "is_testnet", ":", "url", "=", "'https://testnet-explorer.peercoin.net/api/sendrawtransaction?hex={0}'", ".", "format", "(", "rawtxn", ")", "else", ":", ...
41.2
0.009501
def f0Morph(fromWavFN, pitchPath, stepList, outputName, doPlotPitchSteps, fromPitchData, toPitchData, outputMinPitch, outputMaxPitch, praatEXE, keepPitchRange=False, keepAveragePitch=False, sourcePitchDataList=None, minIntervalLength=0.3): ''' Resynthesizes the pi...
[ "def", "f0Morph", "(", "fromWavFN", ",", "pitchPath", ",", "stepList", ",", "outputName", ",", "doPlotPitchSteps", ",", "fromPitchData", ",", "toPitchData", ",", "outputMinPitch", ",", "outputMaxPitch", ",", "praatEXE", ",", "keepPitchRange", "=", "False", ",", ...
42.972973
0.002254
def user(self, user_id): """Get the information of the given user. :param user_id: user identifier """ resource = urijoin(self.RUSERS, str(user_id) + self.CJSON) params = {} response = self._call(resource, params) return response
[ "def", "user", "(", "self", ",", "user_id", ")", ":", "resource", "=", "urijoin", "(", "self", ".", "RUSERS", ",", "str", "(", "user_id", ")", "+", "self", ".", "CJSON", ")", "params", "=", "{", "}", "response", "=", "self", ".", "_call", "(", "r...
23.166667
0.00692
def thirteen_oscillator_three_stimulated_ensembles_list(): "Good example of three synchronous ensembels" "Not accurate due to false skipes are observed" parameters = legion_parameters(); parameters.Wt = 4.0; parameters.fi = 10.0; template_dynamic_legion(15, 1000, 1000, conn_type = conn_typ...
[ "def", "thirteen_oscillator_three_stimulated_ensembles_list", "(", ")", ":", "\"Not accurate due to false skipes are observed\"", "parameters", "=", "legion_parameters", "(", ")", "parameters", ".", "Wt", "=", "4.0", "parameters", ".", "fi", "=", "10.0", "template_dynamic_l...
69.285714
0.032587
def _make_flow(request, scopes, return_url=None): """Creates a Web Server Flow Args: request: A Django request object. scopes: the request oauth2 scopes. return_url: The URL to return to after the flow is complete. Defaults to the path of the current request. Returns: ...
[ "def", "_make_flow", "(", "request", ",", "scopes", ",", "return_url", "=", "None", ")", ":", "# Generate a CSRF token to prevent malicious requests.", "csrf_token", "=", "hashlib", ".", "sha256", "(", "os", ".", "urandom", "(", "1024", ")", ")", ".", "hexdigest...
32.090909
0.000917
def _lderiv(self,l,n): """ NAME: _lderiv PURPOSE: evaluate the derivative w.r.t. lambda for this potential INPUT: l - prolate spheroidal coordinate lambda n - prolate spheroidal coordinate nu OUTPUT: derivative w.r.t. la...
[ "def", "_lderiv", "(", "self", ",", "l", ",", "n", ")", ":", "return", "0.5", "/", "nu", ".", "sqrt", "(", "l", ")", "/", "(", "nu", ".", "sqrt", "(", "l", ")", "+", "nu", ".", "sqrt", "(", "n", ")", ")", "**", "2" ]
29.6
0.010917
def defer_entity_syncing(wrapped, instance, args, kwargs): """ A decorator that can be used to defer the syncing of entities until after the method has been run This is being introduced to help avoid deadlocks in the meantime as we attempt to better understand why they are happening """ # Defer...
[ "def", "defer_entity_syncing", "(", "wrapped", ",", "instance", ",", "args", ",", "kwargs", ")", ":", "# Defer entity syncing while we run our method", "sync_entities", ".", "defer", "=", "True", "# Run the method", "try", ":", "return", "wrapped", "(", "*", "args",...
32.757576
0.002695
def get_bitcoind( new_bitcoind_opts=None, reset=False, new=False ): """ Get or instantiate our bitcoind client. Optionally re-set the bitcoind options. """ global bitcoind if reset: bitcoind = None elif not new and bitcoind is not None: return bitcoind if new or bitcoind is None:...
[ "def", "get_bitcoind", "(", "new_bitcoind_opts", "=", "None", ",", "reset", "=", "False", ",", "new", "=", "False", ")", ":", "global", "bitcoind", "if", "reset", ":", "bitcoind", "=", "None", "elif", "not", "new", "and", "bitcoind", "is", "not", "None",...
24.102564
0.03681
def _get_hover_data(self, data, element): """ Initializes hover data based on Element dimension values. If empty initializes with no data. """ if 'hover' not in self.handles or self.static_source: return npath = len([vs for vs in data.values()][0]) fo...
[ "def", "_get_hover_data", "(", "self", ",", "data", ",", "element", ")", ":", "if", "'hover'", "not", "in", "self", ".", "handles", "or", "self", ".", "static_source", ":", "return", "npath", "=", "len", "(", "[", "vs", "for", "vs", "in", "data", "."...
44.76
0.0035
def get_api_link(self): """ Adds a query string to the api url. At minimum adds the type=choices argument so that the return format is json. Any other filtering arguments calculated by the `get_qs` method are then added to the url. It is up to the destination url to respect them ...
[ "def", "get_api_link", "(", "self", ")", ":", "url", "=", "self", ".", "_api_link", "if", "url", ":", "qs", "=", "self", ".", "get_qs", "(", ")", "url", "=", "\"%s?type=choices\"", "%", "url", "if", "qs", ":", "url", "=", "\"%s&%s\"", "%", "(", ...
49.117647
0.007051
def format_string(self, s, args, kwargs): """If a format call is detected, then this is routed through this method so that our safety sandbox can be used for it. """ if isinstance(s, Markup): formatter = SandboxedEscapeFormatter(self, s.escape) else: forma...
[ "def", "format_string", "(", "self", ",", "s", ",", "args", ",", "kwargs", ")", ":", "if", "isinstance", "(", "s", ",", "Markup", ")", ":", "formatter", "=", "SandboxedEscapeFormatter", "(", "self", ",", "s", ".", "escape", ")", "else", ":", "formatter...
42.454545
0.004193
def get_texts_and_labels(sentence_chunk): """Given a sentence chunk, extract original texts and labels.""" words = sentence_chunk.split('\n') texts = [] labels = [] for word in words: word = word.strip() if len(word) > 0: toks = word.split('\t') texts.append(t...
[ "def", "get_texts_and_labels", "(", "sentence_chunk", ")", ":", "words", "=", "sentence_chunk", ".", "split", "(", "'\\n'", ")", "texts", "=", "[", "]", "labels", "=", "[", "]", "for", "word", "in", "words", ":", "word", "=", "word", ".", "strip", "(",...
32.75
0.002475
def optional_str(deco): """ string 1개만 deco 인자로 오거나 없거나. :param deco: :return: """ @wraps(deco) def dispatcher(*args, **kwargs): # when only function arg if not kwargs and len(args) == 1 and not isinstance(args[0], str) \ and args[0] is not None: ...
[ "def", "optional_str", "(", "deco", ")", ":", "@", "wraps", "(", "deco", ")", "def", "dispatcher", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# when only function arg", "if", "not", "kwargs", "and", "len", "(", "args", ")", "==", "1", "and...
23.952381
0.001912
async def set_pause(self, pause: bool): """ Sets the player's paused state. """ await self._lavalink.ws.send(op='pause', guildId=self.guild_id, pause=pause) self.paused = pause
[ "async", "def", "set_pause", "(", "self", ",", "pause", ":", "bool", ")", ":", "await", "self", ".", "_lavalink", ".", "ws", ".", "send", "(", "op", "=", "'pause'", ",", "guildId", "=", "self", ".", "guild_id", ",", "pause", "=", "pause", ")", "sel...
50
0.014778
def get_catalogs(self): """Gets the catalog list resulting from the search. return: (osid.cataloging.CatalogList) - the catalogs list raise: IllegalState - list has already been retrieved *compliance: mandatory -- This method must be implemented.* """ if self.retrieved...
[ "def", "get_catalogs", "(", "self", ")", ":", "if", "self", ".", "retrieved", ":", "raise", "errors", ".", "IllegalState", "(", "'List has already been retrieved.'", ")", "self", ".", "retrieved", "=", "True", "return", "objects", ".", "CatalogList", "(", "sel...
40.583333
0.004016
def addFilteringOptions(parser, samfileIsPositionalArg=False): """ Add options to an argument parser for filtering SAM/BAM. @param samfileIsPositionalArg: If C{True} the SAM/BAM file must be given as the final argument on the command line (without being preceded by --sam...
[ "def", "addFilteringOptions", "(", "parser", ",", "samfileIsPositionalArg", "=", "False", ")", ":", "parser", ".", "add_argument", "(", "'%ssamfile'", "%", "(", "''", "if", "samfileIsPositionalArg", "else", "'--'", ")", ",", "required", "=", "True", ",", "help...
44.40678
0.000747
def _blkid(fs_type=None): ''' Return available media devices. :param fs_type: Filter only devices that are formatted by that file system. ''' flt = lambda data: [el for el in data if el.strip()] data = dict() for dev_meta in flt(os.popen("blkid -o full").read().split(os.linesep)): # No __s...
[ "def", "_blkid", "(", "fs_type", "=", "None", ")", ":", "flt", "=", "lambda", "data", ":", "[", "el", "for", "el", "in", "data", "if", "el", ".", "strip", "(", ")", "]", "data", "=", "dict", "(", ")", "for", "dev_meta", "in", "flt", "(", "os", ...
33.884615
0.004415
def read(filename, encoding='utf-8'): """ Read text from file ('filename') Return text and encoding """ text, encoding = decode( open(filename, 'rb').read() ) return text, encoding
[ "def", "read", "(", "filename", ",", "encoding", "=", "'utf-8'", ")", ":", "text", ",", "encoding", "=", "decode", "(", "open", "(", "filename", ",", "'rb'", ")", ".", "read", "(", ")", ")", "return", "text", ",", "encoding" ]
29.142857
0.014286
def remove_all(self, token): """Removes all occurrences of token :param token: string to remove :return: input without token """ out = self.string.replace(" ", token) # replace tokens while out.find(token + token) >= 0: # while there are tokens out = out.r...
[ "def", "remove_all", "(", "self", ",", "token", ")", ":", "out", "=", "self", ".", "string", ".", "replace", "(", "\" \"", ",", "token", ")", "# replace tokens", "while", "out", ".", "find", "(", "token", "+", "token", ")", ">=", "0", ":", "# while t...
32.454545
0.00545
def default_cell_formatter(table, column, row, value, **_): """ :type column: tri.table.Column """ formatter = _cell_formatters.get(type(value)) if formatter: value = formatter(table=table, column=column, row=row, value=value) if value is None: return '' return conditional_...
[ "def", "default_cell_formatter", "(", "table", ",", "column", ",", "row", ",", "value", ",", "*", "*", "_", ")", ":", "formatter", "=", "_cell_formatters", ".", "get", "(", "type", "(", "value", ")", ")", "if", "formatter", ":", "value", "=", "formatte...
26.833333
0.003003
def ready(self): '''Whether or not enough time has passed since the last failure''' if self._last_failed: delta = time.time() - self._last_failed return delta >= self.backoff() return True
[ "def", "ready", "(", "self", ")", ":", "if", "self", ".", "_last_failed", ":", "delta", "=", "time", ".", "time", "(", ")", "-", "self", ".", "_last_failed", "return", "delta", ">=", "self", ".", "backoff", "(", ")", "return", "True" ]
38.5
0.008475
def class_param_names(cls, hidden=True): """ Return the names of all class parameters. :param hidden: if ``False``, excludes parameters with a ``_`` prefix. :type hidden: :class:`bool` :return: set of parameter names :rtype: :class:`set` """ param_names =...
[ "def", "class_param_names", "(", "cls", ",", "hidden", "=", "True", ")", ":", "param_names", "=", "set", "(", "k", "for", "(", "k", ",", "v", ")", "in", "cls", ".", "__dict__", ".", "items", "(", ")", "if", "isinstance", "(", "v", ",", "Parameter",...
34.8
0.002797
def download(self, filename=None, as_type='zip'): """ Download the IPList. List format can be either zip, text or json. For large lists, it is recommended to use zip encoding. Filename is required for zip downloads. :param str filename: Name of file to save to (required for zip)...
[ "def", "download", "(", "self", ",", "filename", "=", "None", ",", "as_type", "=", "'zip'", ")", ":", "headers", "=", "None", "if", "as_type", "in", "[", "'zip'", ",", "'txt'", ",", "'json'", "]", ":", "if", "as_type", "==", "'zip'", ":", "if", "fi...
42.580645
0.005185
def get_variation_for_rollout(self, rollout, user_id, attributes=None): """ Determine which experiment/variation the user is in for a given rollout. Returns the variation of the first experiment the user qualifies for. Args: rollout: Rollout for which we are getting the variation. user_id: ID f...
[ "def", "get_variation_for_rollout", "(", "self", ",", "rollout", ",", "user_id", ",", "attributes", "=", "None", ")", ":", "# Go through each experiment in order and try to get the variation for the user", "if", "rollout", "and", "len", "(", "rollout", ".", "experiments",...
48.894737
0.009497
def alter_field(self, model, old_field, new_field, strict=False): """Ran when the configuration on a field changed.""" is_old_field_hstore = isinstance(old_field, HStoreField) is_new_field_hstore = isinstance(new_field, HStoreField) if not is_old_field_hstore and not is_new_field_hstor...
[ "def", "alter_field", "(", "self", ",", "model", ",", "old_field", ",", "new_field", ",", "strict", "=", "False", ")", ":", "is_old_field_hstore", "=", "isinstance", "(", "old_field", ",", "HStoreField", ")", "is_new_field_hstore", "=", "isinstance", "(", "new...
35.75
0.001361
def _need_check_tokens(self): """Check if we need to switch GitHub API tokens""" if self.n_tokens <= 1 or self.rate_limit is None: return False elif self.last_rate_limit_checked is None: self.last_rate_limit_checked = self.rate_limit return True # If...
[ "def", "_need_check_tokens", "(", "self", ")", ":", "if", "self", ".", "n_tokens", "<=", "1", "or", "self", ".", "rate_limit", "is", "None", ":", "return", "False", "elif", "self", ".", "last_rate_limit_checked", "is", "None", ":", "self", ".", "last_rate_...
41.16
0.003799
def compile_fetch(self, raw, doi_id): """ Loop over Raw and add selected items to Fetch with proper formatting :param dict raw: JSON data from doi.org :param str doi_id: :return dict: """ fetch_dict = OrderedDict() order = {'author': 'author', 'type': 'typ...
[ "def", "compile_fetch", "(", "self", ",", "raw", ",", "doi_id", ")", ":", "fetch_dict", "=", "OrderedDict", "(", ")", "order", "=", "{", "'author'", ":", "'author'", ",", "'type'", ":", "'type'", ",", "'identifier'", ":", "''", ",", "'title'", ":", "'t...
48.88
0.008026
def differential(poly, diffvar): """ Polynomial differential operator. Args: poly (Poly) : Polynomial to be differentiated. diffvar (Poly) : Polynomial to differentiate by. Must be decomposed. If polynomial array, the output is the Jacobian matrix. Examples: >>>...
[ "def", "differential", "(", "poly", ",", "diffvar", ")", ":", "poly", "=", "Poly", "(", "poly", ")", "diffvar", "=", "Poly", "(", "diffvar", ")", "if", "not", "chaospy", ".", "poly", ".", "caller", ".", "is_decomposed", "(", "diffvar", ")", ":", "sum...
29.104167
0.000693
def detect(self): """ Detect the WAN IP of the current process through DNS. Depending on the 'family' option, either ipv4 or ipv6 resolution is carried out. :return: ip address """ theip = find_ip(family=self.opts_family) self.set_current_value(theip) ...
[ "def", "detect", "(", "self", ")", ":", "theip", "=", "find_ip", "(", "family", "=", "self", ".", "opts_family", ")", "self", ".", "set_current_value", "(", "theip", ")", "return", "theip" ]
27.25
0.005917
def add_priorfactor(self,**kwargs): """Adds given values to priorfactors If given keyword exists already, error will be raised to use :func:`EclipsePopulation.change_prior` instead. """ for kw in kwargs: if kw in self.priorfactors: logging.error('%s a...
[ "def", "add_priorfactor", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "kw", "in", "kwargs", ":", "if", "kw", "in", "self", ".", "priorfactors", ":", "logging", ".", "error", "(", "'%s already in prior factors for %s. use change_prior function instead.'...
44
0.011986
def get_none_packages(self): """ Get packages with None (not founded), recursively """ not_found = set() for package_name, package in self.packages.items(): if package is None: not_found.add(package_name) else: if package.pa...
[ "def", "get_none_packages", "(", "self", ")", ":", "not_found", "=", "set", "(", ")", "for", "package_name", ",", "package", "in", "self", ".", "packages", ".", "items", "(", ")", ":", "if", "package", "is", "None", ":", "not_found", ".", "add", "(", ...
34.416667
0.004717
def biopax_process_pc_neighborhood(): """Process PathwayCommons neighborhood, return INDRA Statements.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) genes = body.get('genes') bp = biopax.process_pc_neighborhood(gen...
[ "def", "biopax_process_pc_neighborhood", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ...
38.555556
0.002817
def switch_to_window(driver, window, timeout=settings.SMALL_TIMEOUT): """ Wait for a window to appear, and switch to it. This should be usable as a drop-in replacement for driver.switch_to.window(). @Params driver - the webdriver object (required) window - the window index or window handle t...
[ "def", "switch_to_window", "(", "driver", ",", "window", ",", "timeout", "=", "settings", ".", "SMALL_TIMEOUT", ")", ":", "start_ms", "=", "time", ".", "time", "(", ")", "*", "1000.0", "stop_ms", "=", "start_ms", "+", "(", "timeout", "*", "1000.0", ")", ...
37.75
0.000717
def firmware_download_input_protocol_type_scp_protocol_scp_user(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") firmware_download = ET.Element("firmware_download") config = firmware_download input = ET.SubElement(firmware_download, "input") ...
[ "def", "firmware_download_input_protocol_type_scp_protocol_scp_user", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "firmware_download", "=", "ET", ".", "Element", "(", "\"firmware_download\"", ")", "c...
43.4
0.004511
async def create(source_id: str, name: str, requested_attrs: list, revocation_interval: dict, requested_predicates: list = []): """ Builds a generic proof object :param source_id: Tag associated by user of sdk :param name: Name of the Proof :param requested_attrs: Attributes ass...
[ "async", "def", "create", "(", "source_id", ":", "str", ",", "name", ":", "str", ",", "requested_attrs", ":", "list", ",", "revocation_interval", ":", "dict", ",", "requested_predicates", ":", "list", "=", "[", "]", ")", ":", "constructor_params", "=", "("...
95.192308
0.0032