text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def delete_collection(self, collection_name, database_name=None): """ Deletes an existing collection in the CosmosDB database. """ if collection_name is None: raise AirflowBadRequest("Collection name cannot be None.") self.get_conn().DeleteContainer( get_...
[ "def", "delete_collection", "(", "self", ",", "collection_name", ",", "database_name", "=", "None", ")", ":", "if", "collection_name", "is", "None", ":", "raise", "AirflowBadRequest", "(", "\"Collection name cannot be None.\"", ")", "self", ".", "get_conn", "(", "...
42.888889
19.333333
def getLatency(self, instId: int) -> float: """ Return a dict with client identifier as a key and calculated latency as a value """ if len(self.clientAvgReqLatencies) == 0: return 0.0 return self.clientAvgReqLatencies[instId].get_avg_latency()
[ "def", "getLatency", "(", "self", ",", "instId", ":", "int", ")", "->", "float", ":", "if", "len", "(", "self", ".", "clientAvgReqLatencies", ")", "==", "0", ":", "return", "0.0", "return", "self", ".", "clientAvgReqLatencies", "[", "instId", "]", ".", ...
41.285714
14.714286
def parse_reports(self): """ Find RSeQC junction_saturation frequency reports and parse their data """ # Set up vars self.junction_saturation_all = dict() self.junction_saturation_known = dict() self.junction_saturation_novel = dict() # Go through files and parse data for f in self.find_lo...
[ "def", "parse_reports", "(", "self", ")", ":", "# Set up vars", "self", ".", "junction_saturation_all", "=", "dict", "(", ")", "self", ".", "junction_saturation_known", "=", "dict", "(", ")", "self", ".", "junction_saturation_novel", "=", "dict", "(", ")", "# ...
47.973684
23.197368
def dotplot(args): """ %prog dotplot map.csv ref.fasta Make dotplot between chromosomes and linkage maps. The input map is csv formatted, for example: ScaffoldID,ScaffoldPosition,LinkageGroup,GeneticPosition scaffold_2707,11508,1,0 scaffold_2707,11525,1,1.2 """ from jcvi.assembly.a...
[ "def", "dotplot", "(", "args", ")", ":", "from", "jcvi", ".", "assembly", ".", "allmaps", "import", "CSVMapLine", "from", "jcvi", ".", "formats", ".", "sizes", "import", "Sizes", "from", "jcvi", ".", "utils", ".", "natsort", "import", "natsorted", "from", ...
32.37931
17.758621
def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check if a dhcp option exists. Returns True if the dhcp option exists; Returns False otherwise. CLI Example: .. code-block:: ba...
[ "def", "dhcp_options_exists", "(", "dhcp_options_id", "=", "None", ",", "name", "=", "None", ",", "dhcp_options_name", "=", "None", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", ...
34.083333
29.75
def create_model(model_folder, model_type, topology, override): """ Create a model if it doesn't exist already. Parameters ---------- model_folder : The path to the folder where the model is described with an `info.yml` model_type : MLP topology : Something like 160:...
[ "def", "create_model", "(", "model_folder", ",", "model_type", ",", "topology", ",", "override", ")", ":", "latest_model", "=", "utils", ".", "get_latest_in_folder", "(", "model_folder", ",", "\".json\"", ")", "if", "(", "latest_model", "==", "\"\"", ")", "or"...
36.689655
19.103448
def headloss_manifold(FlowRate, Diam, Length, KMinor, Nu, PipeRough, NumOutlets): """Return the total head loss through the manifold.""" #Checking input validity - inputs not checked here are checked by #functions this function calls. ut.check_range([NumOutlets, ">0, int", 'Number of outlets']) retu...
[ "def", "headloss_manifold", "(", "FlowRate", ",", "Diam", ",", "Length", ",", "KMinor", ",", "Nu", ",", "PipeRough", ",", "NumOutlets", ")", ":", "#Checking input validity - inputs not checked here are checked by", "#functions this function calls.", "ut", ".", "check_rang...
46.454545
19
def locale(self): ''' Do a lookup for the locale code that is set for this layout. NOTE: USB HID specifies only 35 different locales. If your layout does not fit, it should be set to Undefined/0 @return: Tuple (<USB HID locale code>, <name>) ''' name = self.json_data['h...
[ "def", "locale", "(", "self", ")", ":", "name", "=", "self", ".", "json_data", "[", "'hid_locale'", "]", "# Set to Undefined/0 if not set", "if", "name", "is", "None", ":", "name", "=", "\"Undefined\"", "return", "(", "int", "(", "self", ".", "json_data", ...
32.2
27.933333
def delete_priority_rule(db, rule_id: int) -> None: """Delete a file priority rule.""" with db: cur = db.cursor() cur.execute('DELETE FROM file_priority WHERE id=?', (rule_id,))
[ "def", "delete_priority_rule", "(", "db", ",", "rule_id", ":", "int", ")", "->", "None", ":", "with", "db", ":", "cur", "=", "db", ".", "cursor", "(", ")", "cur", ".", "execute", "(", "'DELETE FROM file_priority WHERE id=?'", ",", "(", "rule_id", ",", ")...
39.4
17
def rename(self, new_name, session=None, **kwargs): """Rename this collection. If operating in auth mode, client must be authorized as an admin to perform this operation. Raises :class:`TypeError` if `new_name` is not an instance of :class:`basestring` (:class:`str` in python 3)...
[ "def", "rename", "(", "self", ",", "new_name", ",", "session", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "new_name", ",", "string_type", ")", ":", "raise", "TypeError", "(", "\"new_name must be an \"", "\"instance of %s\...
44.615385
22.25
def _handle_result(self, test, status, exception=None, message=None): """Create a :class:`~.TestResult` and add it to this :class:`~ResultCollector`. Parameters ---------- test : unittest.TestCase The test that this result will represent. status : haas.result...
[ "def", "_handle_result", "(", "self", ",", "test", ",", "status", ",", "exception", "=", "None", ",", "message", "=", "None", ")", ":", "if", "self", ".", "buffer", ":", "stderr", "=", "self", ".", "_stderr_buffer", ".", "getvalue", "(", ")", "stdout",...
33.568182
17.363636
def parse(self, filenames): """ Read and parse a filename or a list of filenames. Files that cannot be opened are ignored. A single filename may also be given. Return: list of successfully read files. """ filenames = list_strings(filenames) read_ok = [] ...
[ "def", "parse", "(", "self", ",", "filenames", ")", ":", "filenames", "=", "list_strings", "(", "filenames", ")", "read_ok", "=", "[", "]", "for", "fname", "in", "filenames", ":", "try", ":", "fh", "=", "open", "(", "fname", ")", "except", "IOError", ...
29.096774
19.806452
def _is_domain_match(domain: str, hostname: str) -> bool: """Implements domain matching adhering to RFC 6265.""" if hostname == domain: return True if not hostname.endswith(domain): return False non_matching = hostname[:-len(domain)] if not non_matching...
[ "def", "_is_domain_match", "(", "domain", ":", "str", ",", "hostname", ":", "str", ")", "->", "bool", ":", "if", "hostname", "==", "domain", ":", "return", "True", "if", "not", "hostname", ".", "endswith", "(", "domain", ")", ":", "return", "False", "n...
27.928571
17.642857
def delete_member(self, user): """Returns a response after attempting to remove a member from the list. """ if not self.email_enabled: raise EmailNotEnabledError("See settings.EMAIL_ENABLED") return requests.delete( f"{self.api_url}/{self.address}/members/...
[ "def", "delete_member", "(", "self", ",", "user", ")", ":", "if", "not", "self", ".", "email_enabled", ":", "raise", "EmailNotEnabledError", "(", "\"See settings.EMAIL_ENABLED\"", ")", "return", "requests", ".", "delete", "(", "f\"{self.api_url}/{self.address}/members...
37.5
12
def p_exprlt(p): """ expr : expr LT expr """ a = int(p[1]) if p[1].isdigit() else 0 b = int(p[3]) if p[3].isdigit() else 0 p[0] = '1' if a < b else '0'
[ "def", "p_exprlt", "(", "p", ")", ":", "a", "=", "int", "(", "p", "[", "1", "]", ")", "if", "p", "[", "1", "]", ".", "isdigit", "(", ")", "else", "0", "b", "=", "int", "(", "p", "[", "3", "]", ")", "if", "p", "[", "3", "]", ".", "isdi...
23.714286
10.857143
def getPayloadStruct(self, attributes, objType): """ Function getPayloadStruct Get the payload structure to do a creation or a modification @param attribute: The data @param objType: SubItem type (e.g: hostgroup for hostgroup_class) @return RETURN: the payload """ ...
[ "def", "getPayloadStruct", "(", "self", ",", "attributes", ",", "objType", ")", ":", "payload", "=", "{", "self", ".", "payloadObj", ":", "attributes", ",", "objType", "+", "\"_class\"", ":", "{", "self", ".", "payloadObj", ":", "attributes", "}", "}", "...
38.833333
13.333333
def getActiveJobsForClientInfo(self, clientInfo, fields=[]): """ Fetch jobIDs for jobs in the table with optional fields given a specific clientInfo """ # Form the sequence of field name strings that will go into the # request dbFields = [self._jobs.pubToDBNameDict[x] for x in fields] dbFields...
[ "def", "getActiveJobsForClientInfo", "(", "self", ",", "clientInfo", ",", "fields", "=", "[", "]", ")", ":", "# Form the sequence of field name strings that will go into the", "# request", "dbFields", "=", "[", "self", ".", "_jobs", ".", "pubToDBNameDict", "[", "x", ...
38.705882
18.823529
def range(self, name): """Returns a list of :class:`Cell` objects from a specified range. :param name: A string with range value in A1 notation, e.g. 'A1:A5'. :type name: str Alternatively, you may specify numeric boundaries. All values index from 1 (one): :param first...
[ "def", "range", "(", "self", ",", "name", ")", ":", "range_label", "=", "'%s!%s'", "%", "(", "self", ".", "title", ",", "name", ")", "data", "=", "self", ".", "spreadsheet", ".", "values_get", "(", "range_label", ")", "start", ",", "end", "=", "name"...
28.058824
19.098039
def user_line(self, frame, breakpoint_hits=None): """This function is called when we stop or break at this line.""" if not breakpoint_hits: self.interaction(frame, None) else: commands_result = self.bp_commands(frame, breakpoint_hits) if not commands_result: ...
[ "def", "user_line", "(", "self", ",", "frame", ",", "breakpoint_hits", "=", "None", ")", ":", "if", "not", "breakpoint_hits", ":", "self", ".", "interaction", "(", "frame", ",", "None", ")", "else", ":", "commands_result", "=", "self", ".", "bp_commands", ...
41
12.4
def belanno(keyword: str, file: TextIO): """Write as a BEL annotation.""" directory = get_data_dir(keyword) obo_url = f'http://purl.obolibrary.org/obo/{keyword}.obo' obo_path = os.path.join(directory, f'{keyword}.obo') obo_cache_path = os.path.join(directory, f'{keyword}.obo.pickle') obo_getter...
[ "def", "belanno", "(", "keyword", ":", "str", ",", "file", ":", "TextIO", ")", ":", "directory", "=", "get_data_dir", "(", "keyword", ")", "obo_url", "=", "f'http://purl.obolibrary.org/obo/{keyword}.obo'", "obo_path", "=", "os", ".", "path", ".", "join", "(", ...
36.538462
19.769231
def attach_volume(self, volume, device="/dev/sdp"): """ Attach an EBS volume to this server :param volume: EBS Volume to attach :type volume: boto.ec2.volume.Volume :param device: Device to attach to (default to /dev/sdp) :type device: string """ if hasa...
[ "def", "attach_volume", "(", "self", ",", "volume", ",", "device", "=", "\"/dev/sdp\"", ")", ":", "if", "hasattr", "(", "volume", ",", "\"id\"", ")", ":", "volume_id", "=", "volume", ".", "id", "else", ":", "volume_id", "=", "volume", "return", "self", ...
33.8
16.733333
def create_license_helper(self, lic): """ Handle single(no conjunction/disjunction) licenses. Return the created node. """ if isinstance(lic, document.ExtractedLicense): return self.create_extracted_license(lic) if lic.identifier.rstrip('+') in config.LICENSE_...
[ "def", "create_license_helper", "(", "self", ",", "lic", ")", ":", "if", "isinstance", "(", "lic", ",", "document", ".", "ExtractedLicense", ")", ":", "return", "self", ".", "create_extracted_license", "(", "lic", ")", "if", "lic", ".", "identifier", ".", ...
45.2
18.933333
def _add_catch(self, catch_block): """Add a catch block (exception variable declaration and block) to this try block structure. """ assert isinstance(catch_block, self.CodeCatchBlock) self.catches.append(catch_block)
[ "def", "_add_catch", "(", "self", ",", "catch_block", ")", ":", "assert", "isinstance", "(", "catch_block", ",", "self", ".", "CodeCatchBlock", ")", "self", ".", "catches", ".", "append", "(", "catch_block", ")" ]
42.5
4.166667
def exception_handler(exc, context): """ Returns the response that should be used for any given exception. By default we handle the REST framework `APIException`, and also Django's built-in `Http404` and `PermissionDenied` exceptions. Any unhandled exceptions may return `None`, which will cause a ...
[ "def", "exception_handler", "(", "exc", ",", "context", ")", ":", "if", "isinstance", "(", "exc", ",", "exceptions", ".", "APIException", ")", ":", "headers", "=", "{", "}", "if", "getattr", "(", "exc", ",", "'auth_header'", ",", "None", ")", ":", "hea...
31.853659
20.097561
def get_impala_queries(self, start_time, end_time, filter_str="", limit=100, offset=0): """ Returns a list of queries that satisfy the filter @type start_time: datetime.datetime. Note that the datetime must either be time zone aware or specified in the server time zone. See ...
[ "def", "get_impala_queries", "(", "self", ",", "start_time", ",", "end_time", ",", "filter_str", "=", "\"\"", ",", "limit", "=", "100", ",", "offset", "=", "0", ")", ":", "params", "=", "{", "'from'", ":", "start_time", ".", "isoformat", "(", ")", ",",...
45.433333
21.166667
def export_sbml(model, y0=None, volume=1.0, is_valid=True): """ Export a model as a SBMLDocument. Parameters ---------- model : NetworkModel y0 : dict Initial condition. volume : Real or Real3, optional A size of the simulation volume. 1 as a default. is_valid : bool, op...
[ "def", "export_sbml", "(", "model", ",", "y0", "=", "None", ",", "volume", "=", "1.0", ",", "is_valid", "=", "True", ")", ":", "y0", "=", "y0", "or", "{", "}", "import", "libsbml", "document", "=", "libsbml", ".", "SBMLDocument", "(", "3", ",", "1"...
38.18617
20.654255
def url_for(self, *subgroups, **groups): """Build URL.""" parsed = re.sre_parse.parse(self._pattern.pattern) subgroups = {n:str(v) for n, v in enumerate(subgroups, 1)} groups_ = dict(parsed.pattern.groupdict) subgroups.update({ groups_[k0]: str(v0) for k0,...
[ "def", "url_for", "(", "self", ",", "*", "subgroups", ",", "*", "*", "groups", ")", ":", "parsed", "=", "re", ".", "sre_parse", ".", "parse", "(", "self", ".", "_pattern", ".", "pattern", ")", "subgroups", "=", "{", "n", ":", "str", "(", "v", ")"...
41.083333
13.083333
def get_args(self, state, all_params, remainder, argspec, im_self): ''' Determines the arguments for a controller based upon parameters passed the argument specification for the controller. ''' args = [] varargs = [] kwargs = dict() valid_args = argspec.ar...
[ "def", "get_args", "(", "self", ",", "state", ",", "all_params", ",", "remainder", ",", "argspec", ",", "im_self", ")", ":", "args", "=", "[", "]", "varargs", "=", "[", "]", "kwargs", "=", "dict", "(", ")", "valid_args", "=", "argspec", ".", "args", ...
32.684211
16.54386
def add_postfix(file_path, postfix): # type: (AnyStr, AnyStr) -> AnyStr """Add postfix for a full file path. Examples: >>> FileClass.add_postfix('/home/zhulj/dem.tif', 'filled') '/home/zhulj/dem_filled.tif' >>> FileClass.add_postfix('dem.tif', 'filled') ...
[ "def", "add_postfix", "(", "file_path", ",", "postfix", ")", ":", "# type: (AnyStr, AnyStr) -> AnyStr", "cur_sep", "=", "''", "for", "sep", "in", "[", "'\\\\'", ",", "'/'", ",", "os", ".", "sep", "]", ":", "if", "sep", "in", "file_path", ":", "cur_sep", ...
36.307692
14.423077
def get_proficiency_objective_bank_assignment_session(self, proxy): """Gets the ``OsidSession`` associated with assigning proficiencies to objective banks. :param proxy: a proxy :type proxy: ``osid.proxy.Proxy`` :return: a ``ProficiencyObjectiveBankAssignmentSession`` :rtype: ``...
[ "def", "get_proficiency_objective_bank_assignment_session", "(", "self", ",", "proxy", ")", ":", "if", "not", "self", ".", "supports_proficiency_objective_bank_assignment", "(", ")", ":", "raise", "Unimplemented", "(", ")", "try", ":", "from", ".", "import", "sessio...
46.115385
24.423077
def apply_nsigma_separation(fitind,fluxes,separation,niter=10): """ Remove sources which are within nsigma*fwhm/2 pixels of each other, leaving only a single valid source in that region. This algorithm only works for sources which end up sequentially next to each other based on Y position and remov...
[ "def", "apply_nsigma_separation", "(", "fitind", ",", "fluxes", ",", "separation", ",", "niter", "=", "10", ")", ":", "for", "n", "in", "range", "(", "niter", ")", ":", "if", "len", "(", "fitind", ")", "<", "1", ":", "break", "fitarr", "=", "np", "...
39
15
def InferUserAndSubjectFromUrn(self): """Infers user name and subject urn from self.urn.""" _, client_id, user, _ = self.urn.Split(4) return (user, rdf_client.ClientURN(client_id))
[ "def", "InferUserAndSubjectFromUrn", "(", "self", ")", ":", "_", ",", "client_id", ",", "user", ",", "_", "=", "self", ".", "urn", ".", "Split", "(", "4", ")", "return", "(", "user", ",", "rdf_client", ".", "ClientURN", "(", "client_id", ")", ")" ]
47.25
4.5
def evalRanges(self, datetimeString, sourceTime=None): """ Evaluate the C{datetimeString} text and determine if it represents a date or time range. @type datetimeString: string @param datetimeString: datetime text to evaluate @type sourceTime: struct_time @...
[ "def", "evalRanges", "(", "self", ",", "datetimeString", ",", "sourceTime", "=", "None", ")", ":", "rangeFlag", "=", "retFlag", "=", "0", "startStr", "=", "endStr", "=", "''", "s", "=", "datetimeString", ".", "strip", "(", ")", ".", "lower", "(", ")", ...
34.212121
18.530303
def p_iteration_statement_6(self, p): """ iteration_statement \ : FOR LPAREN VAR identifier initializer_noin IN expr RPAREN statement """ p[0] = ast.ForIn(item=ast.VarDecl(identifier=p[4], initializer=p[5]), iterable=p[7], statement=p[9])
[ "def", "p_iteration_statement_6", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "ast", ".", "ForIn", "(", "item", "=", "ast", ".", "VarDecl", "(", "identifier", "=", "p", "[", "4", "]", ",", "initializer", "=", "p", "[", "5", "]", "...
42.714286
15
def destroy_local_fw_db(self): """Delete the FW dict and its attributes. """ del self.fw_dict del self.in_dcnm_net_dict del self.in_dcnm_subnet_dict del self.out_dcnm_net_dict del self.out_dcnm_subnet_dict
[ "def", "destroy_local_fw_db", "(", "self", ")", ":", "del", "self", ".", "fw_dict", "del", "self", ".", "in_dcnm_net_dict", "del", "self", ".", "in_dcnm_subnet_dict", "del", "self", ".", "out_dcnm_net_dict", "del", "self", ".", "out_dcnm_subnet_dict" ]
35.285714
6.571429
def add_select(self, *column): """ Add a new select column to query :param column: The column to add :type column: str :return: The current QueryBuilder instance :rtype: QueryBuilder """ if not column: column = [] self.columns += lis...
[ "def", "add_select", "(", "self", ",", "*", "column", ")", ":", "if", "not", "column", ":", "column", "=", "[", "]", "self", ".", "columns", "+=", "list", "(", "column", ")", "return", "self" ]
20.9375
16.6875
def delete(context, id, etag): """delete(context, id, etag) Delete a Feeder. >>> dcictl feeder-delete [OPTIONS] :param string id: ID of the feeder to delete [required] :param string etag: Entity tag of the feeder resource [required] """ result = feeder.delete(context, id=id, etag=etag) ...
[ "def", "delete", "(", "context", ",", "id", ",", "etag", ")", ":", "result", "=", "feeder", ".", "delete", "(", "context", ",", "id", "=", "id", ",", "etag", "=", "etag", ")", "if", "result", ".", "status_code", "==", "204", ":", "utils", ".", "p...
29.125
20.4375
def append_from_list(self, content, fill_title=False): """ Appends rows created from the data contained in the provided list of tuples of strings. The first tuple of the list can be set as table title. Args: content (list): list of tuples of strings. Each tuple is a ...
[ "def", "append_from_list", "(", "self", ",", "content", ",", "fill_title", "=", "False", ")", ":", "row_index", "=", "0", "for", "row", "in", "content", ":", "tr", "=", "TableRow", "(", ")", "column_index", "=", "0", "for", "item", "in", "row", ":", ...
37.041667
14.375
def mro(*bases): """Calculate the Method Resolution Order of bases using the C3 algorithm. Suppose you intended creating a class K with the given base classes. This function returns the MRO which K would have, *excluding* K itself (since it doesn't yet exist), as if you had actually created the class. ...
[ "def", "mro", "(", "*", "bases", ")", ":", "seqs", "=", "[", "list", "(", "C", ".", "__mro__", ")", "for", "C", "in", "bases", "]", "+", "[", "list", "(", "bases", ")", "]", "res", "=", "[", "]", "while", "True", ":", "non_empty", "=", "list"...
38.285714
20.571429
def _check_index(self, index): """Verify that the given index is consistent with the degree of the node. """ if self.degree is None: raise UnknownDegreeError( 'Cannot access child DataNode on a parent with degree of None. '\ 'Set the degree on the pare...
[ "def", "_check_index", "(", "self", ",", "index", ")", ":", "if", "self", ".", "degree", "is", "None", ":", "raise", "UnknownDegreeError", "(", "'Cannot access child DataNode on a parent with degree of None. '", "'Set the degree on the parent first.'", ")", "if", "index",...
49.833333
12.666667
def super(self): """Super the block.""" if self._depth + 1 >= len(self._stack): return self._context.environment. \ undefined('there is no parent block called %r.' % self.name, name='super') return BlockReference(self.name, self._context, sel...
[ "def", "super", "(", "self", ")", ":", "if", "self", ".", "_depth", "+", "1", ">=", "len", "(", "self", ".", "_stack", ")", ":", "return", "self", ".", "_context", ".", "environment", ".", "undefined", "(", "'there is no parent block called %r.'", "%", "...
46.125
13.375
def get_request_headers(self): """ Determine the headers to send along with the request. These are pretty much the same for every request, with Route53. """ date_header = time.asctime(time.gmtime()) # We sign the time string above with the user's AWS secret access key ...
[ "def", "get_request_headers", "(", "self", ")", ":", "date_header", "=", "time", ".", "asctime", "(", "time", ".", "gmtime", "(", ")", ")", "# We sign the time string above with the user's AWS secret access key", "# in order to authenticate our request.", "signing_key", "="...
35.409091
19.318182
def filter_recordings(recordings): """Remove all recordings which have points without time. Parameters ---------- recordings : list of dicts Each dictionary has the keys 'data' and 'segmentation' Returns ------- list of dicts : Only recordings where all points have time valu...
[ "def", "filter_recordings", "(", "recordings", ")", ":", "new_recordings", "=", "[", "]", "for", "recording", "in", "recordings", ":", "recording", "[", "'data'", "]", "=", "json", ".", "loads", "(", "recording", "[", "'data'", "]", ")", "tmp", "=", "jso...
31.65625
15.875
def get(self, key, default=None): """ :return: the value behind :paramref:`key` in the specification. If no value was found, :paramref:`default` is returned. :param key: a :ref:`specification key <prototype-key>` """ for base in self.__specification: if key ...
[ "def", "get", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "for", "base", "in", "self", ".", "__specification", ":", "if", "key", "in", "base", ":", "return", "base", "[", "key", "]", "return", "default" ]
37.5
12.5
def ancestor(self): """This browse node's immediate ancestor in the browse node tree. :return: The ancestor as an :class:`~.AmazonBrowseNode`, or None. """ ancestors = getattr(self.element, 'Ancestors', None) if hasattr(ancestors, 'BrowseNode'): return Am...
[ "def", "ancestor", "(", "self", ")", ":", "ancestors", "=", "getattr", "(", "self", ".", "element", ",", "'Ancestors'", ",", "None", ")", "if", "hasattr", "(", "ancestors", ",", "'BrowseNode'", ")", ":", "return", "AmazonBrowseNode", "(", "ancestors", "[",...
37
17.8
def _set_global_metric_type(self, v, load=False): """ Setter method for global_metric_type, mapped from YANG variable /routing_system/ipv6/router/ospf/global_metric_type (ospf:metric-type) If this variable is read-only (config: false) in the source YANG file, then _set_global_metric_type is considered a...
[ "def", "_set_global_metric_type", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ","...
91.583333
45
def tag(self, tokens): """Return a list of (token, tag) tuples for a given list of tokens.""" tags = [] for token in tokens: normalized = self.lexicon[token].normalized for regex, tag in self.regexes: if regex.match(normalized): tags.ap...
[ "def", "tag", "(", "self", ",", "tokens", ")", ":", "tags", "=", "[", "]", "for", "token", "in", "tokens", ":", "normalized", "=", "self", ".", "lexicon", "[", "token", "]", ".", "normalized", "for", "regex", ",", "tag", "in", "self", ".", "regexes...
36.166667
11.666667
def get_time_slide_id(xmldoc, time_slide, create_new = None, superset_ok = False, nonunique_ok = False): """ Return the time_slide_id corresponding to the offset vector described by time_slide, a dictionary of instrument/offset pairs. Example: >>> get_time_slide_id(xmldoc, {"H1": 0, "L1": 0}) 'time_slide:time_s...
[ "def", "get_time_slide_id", "(", "xmldoc", ",", "time_slide", ",", "create_new", "=", "None", ",", "superset_ok", "=", "False", ",", "nonunique_ok", "=", "False", ")", ":", "try", ":", "tisitable", "=", "lsctables", ".", "TimeSlideTable", ".", "get_table", "...
40.529412
24.294118
def local_accuracy(X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model): """ The how well do the features plus a constant base rate sum up to the model output. """ X_train, X_test = to_array(X_train, X_test) # how many features to mask assert X_train.shape[1] == X_t...
[ "def", "local_accuracy", "(", "X_train", ",", "y_train", ",", "X_test", ",", "y_test", ",", "attr_test", ",", "model_generator", ",", "metric", ",", "trained_model", ")", ":", "X_train", ",", "X_test", "=", "to_array", "(", "X_train", ",", "X_test", ")", "...
38.615385
23.307692
def find_covalent_bonds(ampal, max_range=2.2, threshold=1.1, tag=True): """Finds all covalent bonds in the AMPAL object. Parameters ---------- ampal : AMPAL Object Any AMPAL object with a `get_atoms` method. max_range : float, optional Used to define the sector size, so interactions...
[ "def", "find_covalent_bonds", "(", "ampal", ",", "max_range", "=", "2.2", ",", "threshold", "=", "1.1", ",", "tag", "=", "True", ")", ":", "sectors", "=", "gen_sectors", "(", "ampal", ".", "get_atoms", "(", ")", ",", "max_range", "*", "1.1", ")", "bond...
38.459459
17.621622
def _caps_add_machine(machines, node): ''' Parse the <machine> element of the host capabilities and add it to the machines list. ''' maxcpus = node.get('maxCpus') canonical = node.get('canonical') name = node.text alternate_name = "" if canonical: alternate_name = name ...
[ "def", "_caps_add_machine", "(", "machines", ",", "node", ")", ":", "maxcpus", "=", "node", ".", "get", "(", "'maxCpus'", ")", "canonical", "=", "node", ".", "get", "(", "'canonical'", ")", "name", "=", "node", ".", "text", "alternate_name", "=", "\"\"",...
27
17.545455
def _parse_tree(self, node): """ Parse a <checksum> object """ if 'filename' in node.attrib: self.filename = node.attrib['filename'] if 'type' in node.attrib: self.kind = node.attrib['type'] if 'target' in node.attrib: self.target = node.attrib['target...
[ "def", "_parse_tree", "(", "self", ",", "node", ")", ":", "if", "'filename'", "in", "node", ".", "attrib", ":", "self", ".", "filename", "=", "node", ".", "attrib", "[", "'filename'", "]", "if", "'type'", "in", "node", ".", "attrib", ":", "self", "."...
38.333333
6.444444
def update(self, payload): """Updates the queried record with `payload` and returns the updated record after validating the response :param payload: Payload to update the record with :raise: :NoResults: if query returned no results :MultipleResults: if query returned mor...
[ "def", "update", "(", "self", ",", "payload", ")", ":", "try", ":", "result", "=", "self", ".", "get_one", "(", ")", "if", "'sys_id'", "not", "in", "result", ":", "raise", "NoResults", "(", ")", "except", "MultipleResults", ":", "raise", "MultipleResults...
40.48
20.72
def decode(self, covertext): """Given an input string ``unrank(X[:n]) || X[n:]`` returns ``X``. """ if not isinstance(covertext, str): raise InvalidInputException('Input must be of type string.') insufficient = (len(covertext) < self._fixed_slice) if insufficient: ...
[ "def", "decode", "(", "self", ",", "covertext", ")", ":", "if", "not", "isinstance", "(", "covertext", ",", "str", ")", ":", "raise", "InvalidInputException", "(", "'Input must be of type string.'", ")", "insufficient", "=", "(", "len", "(", "covertext", ")", ...
39.53125
19.5625
def symlink_to(self, target, target_is_directory=False): """ Make this path a symlink pointing to the given path. Note the order of arguments (self, target) is the reverse of os.symlink's. """ if self._closed: self._raise_closed() self._accessor.symlin...
[ "def", "symlink_to", "(", "self", ",", "target", ",", "target_is_directory", "=", "False", ")", ":", "if", "self", ".", "_closed", ":", "self", ".", "_raise_closed", "(", ")", "self", ".", "_accessor", ".", "symlink", "(", "target", ",", "self", ",", "...
38.666667
14.666667
def create(model_config, epochs, optimizer, model, source, storage, scheduler=None, callbacks=None, max_grad_norm=None): """ Vel factory function """ return SimpleTrainCommand( epochs=epochs, model_config=model_config, model_factory=model, optimizer_factory=optimizer, sch...
[ "def", "create", "(", "model_config", ",", "epochs", ",", "optimizer", ",", "model", ",", "source", ",", "storage", ",", "scheduler", "=", "None", ",", "callbacks", "=", "None", ",", "max_grad_norm", "=", "None", ")", ":", "return", "SimpleTrainCommand", "...
34.769231
16.923077
def download_data(dataset_name=None, prompt=prompt_stdin): """Check with the user that the are happy with terms and conditions for the data set, then download it.""" dr = data_resources[dataset_name] if not authorize_download(dataset_name, prompt=prompt): raise Exception("Permission to down...
[ "def", "download_data", "(", "dataset_name", "=", "None", ",", "prompt", "=", "prompt_stdin", ")", ":", "dr", "=", "data_resources", "[", "dataset_name", "]", "if", "not", "authorize_download", "(", "dataset_name", ",", "prompt", "=", "prompt", ")", ":", "ra...
43.21875
15.96875
def _query_string_params(flask_request): """ Constructs an APIGW equivalent query string dictionary Parameters ---------- flask_request request Request from Flask Returns dict (str: str) ------- Empty dict if no query params where in the ...
[ "def", "_query_string_params", "(", "flask_request", ")", ":", "query_string_dict", "=", "{", "}", "# Flask returns an ImmutableMultiDict so convert to a dictionary that becomes", "# a dict(str: list) then iterate over", "for", "query_string_key", ",", "query_string_list", "in", "f...
36.482759
24.689655
def _getConfigData(self, all_dependencies, component, builddir, build_info_header_path): ''' returns (path_to_config_header, cmake_set_definitions) ''' # ordered_json, , read/write ordered json, internal from yotta.lib import ordered_json add_defs_header = '' set_definitions = ''...
[ "def", "_getConfigData", "(", "self", ",", "all_dependencies", ",", "component", ",", "builddir", ",", "build_info_header_path", ")", ":", "# ordered_json, , read/write ordered json, internal", "from", "yotta", ".", "lib", "import", "ordered_json", "add_defs_header", "=",...
52.197183
30.507042
def write_metadata(self, symbol, metadata, prune_previous_version=True, **kwargs): """ Write 'metadata' under the specified 'symbol' name to this library. The data will remain unchanged. A new version will be created. If the symbol is missing, it causes a write with empty data (None, pic...
[ "def", "write_metadata", "(", "self", ",", "symbol", ",", "metadata", ",", "prune_previous_version", "=", "True", ",", "*", "*", "kwargs", ")", ":", "# Make a normal write with empty data and supplied metadata if symbol does not exist", "try", ":", "previous_version", "="...
52.434783
31.869565
def parse_tables(self): """ Parse and return all tables from the DOM. Returns ------- list of parsed (header, body, footer) tuples from tables. """ tables = self._parse_tables(self._build_doc(), self.match, self.attrs) return (self._parse_thead_tbody_tfoo...
[ "def", "parse_tables", "(", "self", ")", ":", "tables", "=", "self", ".", "_parse_tables", "(", "self", ".", "_build_doc", "(", ")", ",", "self", ".", "match", ",", "self", ".", "attrs", ")", "return", "(", "self", ".", "_parse_thead_tbody_tfoot", "(", ...
34
21.2
def has_main_target (self, name): """Tells if a main target with the specified name exists.""" assert isinstance(name, basestring) if not self.built_main_targets_: self.build_main_targets() return name in self.main_target_
[ "def", "has_main_target", "(", "self", ",", "name", ")", ":", "assert", "isinstance", "(", "name", ",", "basestring", ")", "if", "not", "self", ".", "built_main_targets_", ":", "self", ".", "build_main_targets", "(", ")", "return", "name", "in", "self", "....
37.285714
7.571429
def get_mcu_definition(self, project_file): """ Parse project file to get mcu definition """ # TODO: check the extension here if it's valid IAR project or we # should at least check if syntax is correct check something IAR defines and return error if not project_file = join(getcwd(), pro...
[ "def", "get_mcu_definition", "(", "self", ",", "project_file", ")", ":", "# TODO: check the extension here if it's valid IAR project or we", "# should at least check if syntax is correct check something IAR defines and return error if not", "project_file", "=", "join", "(", "getcwd", "...
55.828571
36.257143
def set_channel_created(self, channel_link, channel_id): """ set_channel_created: records progress after creating channel on Kolibri Studio Args: channel_link (str): link to uploaded channel channel_id (str): id of channel that has been uploaded Returns: N...
[ "def", "set_channel_created", "(", "self", ",", "channel_link", ",", "channel_id", ")", ":", "self", ".", "channel_link", "=", "channel_link", "self", ".", "channel_id", "=", "channel_id", "self", ".", "__record_progress", "(", "Status", ".", "PUBLISH_CHANNEL", ...
49.4
15.7
def _prt_line_detail(self, prt, values, lnum=""): """Print header and field values in a readable format.""" #### data = zip(self.req_str, self.ntgafobj._fields, values) data = zip(self.req_str, self.flds, values) txt = ["{:2}) {:3} {:20} {}".format(i, req, hdr, val) for i, (req, hdr, val...
[ "def", "_prt_line_detail", "(", "self", ",", "prt", ",", "values", ",", "lnum", "=", "\"\"", ")", ":", "#### data = zip(self.req_str, self.ntgafobj._fields, values)", "data", "=", "zip", "(", "self", ".", "req_str", ",", "self", ".", "flds", ",", "values", ")"...
68.5
24.333333
def resizeEvent(self, evt=None): w = self.width() h = self.height() ''' if h<=360: h=360 self.resize(w,h) if w<=640: w = 640 self.resize(w, h) ''' step = (w * 94 / 100) / 5 foot = h * 3 / 48
[ "def", "resizeEvent", "(", "self", ",", "evt", "=", "None", ")", ":", "w", "=", "self", ".", "width", "(", ")", "h", "=", "self", ".", "height", "(", ")", "step", "=", "(", "w", "*", "94", "/", "100", ")", "/", "5", "foot", "=", "h", "*", ...
19.333333
20.666667
def propose_value(self, value, assume_leader=False): """ Proposes a value to the network. """ if value is None: raise ValueError("Not allowed to propose value None") paxos = self.paxos_instance paxos.leader = assume_leader msg = paxos.propose_value(val...
[ "def", "propose_value", "(", "self", ",", "value", ",", "assume_leader", "=", "False", ")", ":", "if", "value", "is", "None", ":", "raise", "ValueError", "(", "\"Not allowed to propose value None\"", ")", "paxos", "=", "self", ".", "paxos_instance", "paxos", "...
32.428571
8.714286
def highPassFilter(self, threshold): ''' remove all low frequencies by setting a square in the middle of the Fourier transformation of the size (2*threshold)^2 to zero threshold = 0...1 ''' if not threshold: return rows, cols = self.img.shape ...
[ "def", "highPassFilter", "(", "self", ",", "threshold", ")", ":", "if", "not", "threshold", ":", "return", "rows", ",", "cols", "=", "self", ".", "img", ".", "shape", "tx", "=", "int", "(", "cols", "*", "threshold", ")", "ty", "=", "int", "(", "row...
36.333333
15.666667
def _convert_seconds(self, packed_seconds): """Unpack the internal representation.""" seconds = struct.unpack("!H", packed_seconds[:2])[0] seconds += struct.unpack("!I", packed_seconds[2:])[0] return seconds
[ "def", "_convert_seconds", "(", "self", ",", "packed_seconds", ")", ":", "seconds", "=", "struct", ".", "unpack", "(", "\"!H\"", ",", "packed_seconds", "[", ":", "2", "]", ")", "[", "0", "]", "seconds", "+=", "struct", ".", "unpack", "(", "\"!I\"", ","...
47
12.4
def scale(arr, mn=0, mx=1): """ Apply min-max scaling (normalize) then scale to (mn,mx) """ amn = arr.min() amx = arr.max() # normalize: arr = (arr - amn) / (amx - amn) # scale: if amn != mn or amx != mx: arr *= mx - mn arr += mn return arr
[ "def", "scale", "(", "arr", ",", "mn", "=", "0", ",", "mx", "=", "1", ")", ":", "amn", "=", "arr", ".", "min", "(", ")", "amx", "=", "arr", ".", "max", "(", ")", "# normalize:", "arr", "=", "(", "arr", "-", "amn", ")", "/", "(", "amx", "-...
20.5
14.785714
def _list_iter(host=None, path=None): ''' Return a generator iterating over hosts path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 ''' tgt = host or '*' client = salt.client.get_local_client(__opts__['conf_file']) f...
[ "def", "_list_iter", "(", "host", "=", "None", ",", "path", "=", "None", ")", ":", "tgt", "=", "host", "or", "'*'", "client", "=", "salt", ".", "client", ".", "get_local_client", "(", "__opts__", "[", "'conf_file'", "]", ")", "for", "container_info", "...
29.516129
16.935484
def write_configs(self, project_root): """Wrapper method that writes all configuration files to the pipeline directory """ # Write resources config with open(join(project_root, "resources.config"), "w") as fh: fh.write(self.resources) # Write containers conf...
[ "def", "write_configs", "(", "self", ",", "project_root", ")", ":", "# Write resources config", "with", "open", "(", "join", "(", "project_root", ",", "\"resources.config\"", ")", ",", "\"w\"", ")", "as", "fh", ":", "fh", ".", "write", "(", "self", ".", "r...
36.277778
17.611111
def do_dock6_flexible(self, ligand_path, force_rerun=False): """Dock a ligand to the protein. Args: ligand_path (str): Path to ligand (mol2 format) to dock to protein force_rerun (bool): If method should be rerun even if output file exists """ log.debug('{}: run...
[ "def", "do_dock6_flexible", "(", "self", ",", "ligand_path", ",", "force_rerun", "=", "False", ")", ":", "log", ".", "debug", "(", "'{}: running DOCK6...'", ".", "format", "(", "self", ".", "id", ")", ")", "ligand_name", "=", "os", ".", "path", ".", "bas...
59.990741
26.527778
def three_hours_forecast_at_id(self, id): """ Queries the OWM Weather API for three hours weather forecast for the specified city ID (eg: 5128581). A *Forecaster* object is returned, containing a *Forecast* instance covering a global streak of five days: this instance encapsulate...
[ "def", "three_hours_forecast_at_id", "(", "self", ",", "id", ")", ":", "assert", "type", "(", "id", ")", "is", "int", ",", "\"'id' must be an int\"", "if", "id", "<", "0", ":", "raise", "ValueError", "(", "\"'id' value must be greater than 0\"", ")", "params", ...
48.645161
20.516129
def full_dict(ldict, keys): """Return Comparison Dictionaries from list dict on keys keys: a list of keys that when combined make the row in the list unique """ if type(keys) == str: keys = [keys] else: keys = keys cmp_dict = {} for line in ldict: in...
[ "def", "full_dict", "(", "ldict", ",", "keys", ")", ":", "if", "type", "(", "keys", ")", "==", "str", ":", "keys", "=", "[", "keys", "]", "else", ":", "keys", "=", "keys", "cmp_dict", "=", "{", "}", "for", "line", "in", "ldict", ":", "index", "...
23.35
16.35
def attempt_connection(self): """ Try connecting to the (host, port) tuples specified at construction time. """ self.connection_error = False sleep_exp = 1 connect_count = 0 while self.running and self.socket is None and ( connect_count < self.__recon...
[ "def", "attempt_connection", "(", "self", ")", ":", "self", ".", "connection_error", "=", "False", "sleep_exp", "=", "1", "connect_count", "=", "0", "while", "self", ".", "running", "and", "self", ".", "socket", "is", "None", "and", "(", "connect_count", "...
51.818182
25.181818
def parse_qc(self, qc_file): """ Parse phantompeakqualtools (spp) QC table and return quality metrics. :param str qc_file: Path to phantompeakqualtools output file, which contains sample quality measurements. """ import pandas as pd series = pd.Series() ...
[ "def", "parse_qc", "(", "self", ",", "qc_file", ")", ":", "import", "pandas", "as", "pd", "series", "=", "pd", ".", "Series", "(", ")", "try", ":", "with", "open", "(", "qc_file", ")", "as", "handle", ":", "line", "=", "handle", ".", "readlines", "...
34.333333
17.666667
def winsorize(row, min_percentile, max_percentile): """ This implementation is based on scipy.stats.mstats.winsorize """ a = row.copy() nan_count = isnan(row).sum() nonnan_count = a.size - nan_count # NOTE: argsort() sorts nans to the end of the array. idx = a.argsort() # Set value...
[ "def", "winsorize", "(", "row", ",", "min_percentile", ",", "max_percentile", ")", ":", "a", "=", "row", ".", "copy", "(", ")", "nan_count", "=", "isnan", "(", "row", ")", ".", "sum", "(", ")", "nonnan_count", "=", "a", ".", "size", "-", "nan_count",...
35.678571
20.964286
def run(**kwargs): """ This function was necessary to separate from main() to accommodate for server startup path on system 3.0, which is server.main. In the case where the api is on system 3.0, server.main will redirect to this function with an additional argument of 'patch_old_init'. kwargs are he...
[ "def", "run", "(", "*", "*", "kwargs", ")", ":", "log_init", "(", ")", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "log", ".", "info", "(", "\"API server version: {}\"", ".", "format", "(", "__version__", ")", ")", "if", "not", "os", ".",...
40.83871
18.451613
def paginate_data(searched_data, request_data): """ Paginates the searched_data as per the request_data Source: Himanshu Shankar (https://github.com/iamhssingh) Parameters ---------- searched_data: Serializer.data It is the data received from queryset. It uses ...
[ "def", "paginate_data", "(", "searched_data", ",", "request_data", ")", ":", "from", "django", ".", "core", ".", "paginator", "import", "Paginator", ",", "EmptyPage", ",", "PageNotAnInteger", "if", "int", "(", "request_data", ".", "data", "[", "'paginator'", "...
34.555556
19.266667
def color(self, key): """ Returns the color value for the given key for this console. :param key | <unicode> :return <QtGui.QColor> """ if type(key) == int: key = self.LoggingMap.get(key, ('NotSet', ''))[0] name = n...
[ "def", "color", "(", "self", ",", "key", ")", ":", "if", "type", "(", "key", ")", "==", "int", ":", "key", "=", "self", ".", "LoggingMap", ".", "get", "(", "key", ",", "(", "'NotSet'", ",", "''", ")", ")", "[", "0", "]", "name", "=", "natives...
31.75
13.083333
def corr(dataset, column, method="pearson"): """ Compute the correlation matrix with specified method using dataset. :param dataset: A Dataset or a DataFrame. :param column: The name of the column of vectors for which the correlation coefficient needs to be...
[ "def", "corr", "(", "dataset", ",", "column", ",", "method", "=", "\"pearson\"", ")", ":", "sc", "=", "SparkContext", ".", "_active_spark_context", "javaCorrObj", "=", "_jvm", "(", ")", ".", "org", ".", "apache", ".", "spark", ".", "ml", ".", "stat", "...
54.142857
24.285714
def location(self, filetype, base_dir=None, **kwargs): """Return the location of the relative sas path of a given type of file. Parameters ---------- filetype : str File type parameter. Returns ------- full : str The relative sas path to ...
[ "def", "location", "(", "self", ",", "filetype", ",", "base_dir", "=", "None", ",", "*", "*", "kwargs", ")", ":", "full", "=", "kwargs", ".", "get", "(", "'full'", ",", "None", ")", "if", "not", "full", ":", "full", "=", "self", ".", "full", "(",...
27.64
20.8
def get_postadres_by_huisnummer(self, huisnummer): ''' Get the `postadres` for a :class:`Huisnummer`. :param huisnummer: The :class:`Huisnummer` for which the \ `postadres` is wanted. OR A huisnummer id. :rtype: A :class:`str`. ''' try: id = huisn...
[ "def", "get_postadres_by_huisnummer", "(", "self", ",", "huisnummer", ")", ":", "try", ":", "id", "=", "huisnummer", ".", "id", "except", "AttributeError", ":", "id", "=", "huisnummer", "def", "creator", "(", ")", ":", "res", "=", "crab_gateway_request", "("...
34.84
17.64
def copy(self): """Create a shallow copy of self. This runs in O(len(self.num_unique_elements())) """ out = self._from_iterable(None) out._dict = self._dict.copy() out._size = self._size return out
[ "def", "copy", "(", "self", ")", ":", "out", "=", "self", ".", "_from_iterable", "(", "None", ")", "out", ".", "_dict", "=", "self", ".", "_dict", ".", "copy", "(", ")", "out", ".", "_size", "=", "self", ".", "_size", "return", "out" ]
22.666667
14.888889
def match(A, S, trueS): """Rearranges columns of S to best fit the components they likely represent (maximizes sum of correlations)""" cov = np.cov(trueS, S) k = S.shape[0] corr = np.zeros([k,k]) for i in range(k): for j in range(k): corr[i][j] = cov[i + k][j]/np.sqrt(cov[...
[ "def", "match", "(", "A", ",", "S", ",", "trueS", ")", ":", "cov", "=", "np", ".", "cov", "(", "trueS", ",", "S", ")", "k", "=", "S", ".", "shape", "[", "0", "]", "corr", "=", "np", ".", "zeros", "(", "[", "k", ",", "k", "]", ")", "for"...
40.266667
14.866667
def fixcode(**kwargs): """ auto pep8 format all python file in ``source code`` and ``tests`` dir. """ # repository direcotry repo_dir = Path(__file__).parent.absolute() # source code directory source_dir = Path(repo_dir, package.__name__) if source_dir.exists(): print("Source c...
[ "def", "fixcode", "(", "*", "*", "kwargs", ")", ":", "# repository direcotry", "repo_dir", "=", "Path", "(", "__file__", ")", ".", "parent", ".", "absolute", "(", ")", "# source code directory", "source_dir", "=", "Path", "(", "repo_dir", ",", "package", "."...
30.148148
16.592593
def StoreCSRFCookie(user, response): """Decorator for WSGI handler that inserts CSRF cookie into response.""" csrf_token = GenerateCSRFToken(user, None) response.set_cookie( "csrftoken", csrf_token, max_age=CSRF_TOKEN_DURATION.seconds)
[ "def", "StoreCSRFCookie", "(", "user", ",", "response", ")", ":", "csrf_token", "=", "GenerateCSRFToken", "(", "user", ",", "None", ")", "response", ".", "set_cookie", "(", "\"csrftoken\"", ",", "csrf_token", ",", "max_age", "=", "CSRF_TOKEN_DURATION", ".", "s...
40.5
15.5
def docs_init_to_class(self): """If found a __init__ method's docstring and the class without any docstring, so set the class docstring with __init__one, and let __init__ without docstring. :returns: True if done :rtype: boolean """ result = False if not...
[ "def", "docs_init_to_class", "(", "self", ")", ":", "result", "=", "False", "if", "not", "self", ".", "parsed", ":", "self", ".", "_parse", "(", ")", "einit", "=", "[", "]", "eclass", "=", "[", "]", "for", "e", "in", "self", ".", "docs_list", ":", ...
36.848485
14.545455
def _check_error(response): """Raises an exception if the Spark Cloud returned an error.""" if (not response.ok) or (response.status_code != 200): raise Exception( response.json()['error'] + ': ' + response.json()['error_description'] )
[ "def", "_check_error", "(", "response", ")", ":", "if", "(", "not", "response", ".", "ok", ")", "or", "(", "response", ".", "status_code", "!=", "200", ")", ":", "raise", "Exception", "(", "response", ".", "json", "(", ")", "[", "'error'", "]", "+", ...
43.142857
13.571429
def get_subjects_with_equal_or_higher_perm(self, perm_str): """ Args: perm_str : str Permission, ``read``, ``write`` or ``changePermission``. Returns: set of str : Subj that have perm equal or higher than ``perm_str``. Since the lowest permission a subject can have is ``read`...
[ "def", "get_subjects_with_equal_or_higher_perm", "(", "self", ",", "perm_str", ")", ":", "self", ".", "_assert_valid_permission", "(", "perm_str", ")", "return", "{", "s", "for", "p", "in", "self", ".", "_equal_or_higher_perm", "(", "perm_str", ")", "for", "s", ...
31.111111
22.333333
def pupv_to_vRvz(pu,pv,u,v,delta=1.,oblate=False): """ NAME: pupv_to_vRvz PURPOSE: calculate cylindrical vR and vz from momenta in prolate or oblate confocal u and v coordinates for a given focal length delta INPUT: pu - u momentum pv - v momentum u - u coordina...
[ "def", "pupv_to_vRvz", "(", "pu", ",", "pv", ",", "u", ",", "v", ",", "delta", "=", "1.", ",", "oblate", "=", "False", ")", ":", "if", "oblate", ":", "denom", "=", "delta", "*", "(", "sc", ".", "sinh", "(", "u", ")", "**", "2.", "+", "sc", ...
21.627907
29.813953
def start(cls, ev): """ Read all data from Views and send them to the backend. """ ev.preventDefault() ev.stopPropagation() ViewController.log_view.add("Beginning MARCGenerator request..") if not ViewController.validate(): ViewController.urlbox_error...
[ "def", "start", "(", "cls", ",", "ev", ")", ":", "ev", ".", "preventDefault", "(", ")", "ev", ".", "stopPropagation", "(", ")", "ViewController", ".", "log_view", ".", "add", "(", "\"Beginning MARCGenerator request..\"", ")", "if", "not", "ViewController", "...
33.575
20.525
def recv_exactly(self, n, timeout='default'): """ Recieve exactly n bytes Aliases: read_exactly, readexactly, recvexactly """ self._print_recv_header( '======== Receiving until exactly {0}B{timeout_text} ========', timeout, n) return self._recv_predicate(la...
[ "def", "recv_exactly", "(", "self", ",", "n", ",", "timeout", "=", "'default'", ")", ":", "self", ".", "_print_recv_header", "(", "'======== Receiving until exactly {0}B{timeout_text} ========'", ",", "timeout", ",", "n", ")", "return", "self", ".", "_recv_predicate...
31.909091
22.090909
def can_attack_air(self) -> bool: """ Does not include upgrades """ if self._weapons: weapon = next( (weapon for weapon in self._weapons if weapon.type in {TargetType.Air.value, TargetType.Any.value}), None, ) return weapon is not None ...
[ "def", "can_attack_air", "(", "self", ")", "->", "bool", ":", "if", "self", ".", "_weapons", ":", "weapon", "=", "next", "(", "(", "weapon", "for", "weapon", "in", "self", ".", "_weapons", "if", "weapon", ".", "type", "in", "{", "TargetType", ".", "A...
36.888889
20.111111
def source(self, source): """When the source gets updated, update the pane object""" BaseView.source.fset(self, source) if self.main_pane: self.main_pane.object = self.contents self.label_pane.object = self.label
[ "def", "source", "(", "self", ",", "source", ")", ":", "BaseView", ".", "source", ".", "fset", "(", "self", ",", "source", ")", "if", "self", ".", "main_pane", ":", "self", ".", "main_pane", ".", "object", "=", "self", ".", "contents", "self", ".", ...
42.5
7.833333
def is_archive(filename): '''returns boolean of whether this filename looks like an archive''' for archive in archive_formats: if filename.endswith(archive_formats[archive]['suffix']): return True return False
[ "def", "is_archive", "(", "filename", ")", ":", "for", "archive", "in", "archive_formats", ":", "if", "filename", ".", "endswith", "(", "archive_formats", "[", "archive", "]", "[", "'suffix'", "]", ")", ":", "return", "True", "return", "False" ]
39.333333
19.666667
def run_functor(functor, *args, **kwargs): """ Given a functor, run it and return its result. We can use this with multiprocessing.map and map it over a list of job functors to do them. Handles getting more than multiprocessing's pitiful exception output This function was derived from: http://...
[ "def", "run_functor", "(", "functor", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "# This is where you do your actual work", "return", "functor", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", ":", "# Put all exce...
39.210526
21.315789
def _resolve_metric(self, original_metric_name, metrics_to_collect, prefix=""): """ Return the submit method and the metric name to use. The metric name is defined as follow: * If available, the normalized metric name alias * (Or) the normalized original metric name """ ...
[ "def", "_resolve_metric", "(", "self", ",", "original_metric_name", ",", "metrics_to_collect", ",", "prefix", "=", "\"\"", ")", ":", "submit_method", "=", "(", "metrics_to_collect", "[", "original_metric_name", "]", "[", "0", "]", "if", "isinstance", "(", "metri...
38.619048
22.047619
def download(self, size=SIZE_LARGE, thumbnail=False, wait=60, asynchronous=False): """ Downloads this image to cache. Calling the download() method instantiates an asynchronous URLAccumulator. Once it is done downloading, this image will have its path property set to an...
[ "def", "download", "(", "self", ",", "size", "=", "SIZE_LARGE", ",", "thumbnail", "=", "False", ",", "wait", "=", "60", ",", "asynchronous", "=", "False", ")", ":", "if", "thumbnail", "==", "True", ":", "size", "=", "SIZE_THUMBNAIL", "# backwards compatibi...
36.913043
21.478261