text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def auth_required(self, view): """Decorator which checks if user is authenticated Decorator for Flask's view which blocks not authenticated requests :param view: Flask's view function """ @functools.wraps(view) def decorated(*args, **kwargs): log.in...
[ "def", "auth_required", "(", "self", ",", "view", ")", ":", "@", "functools", ".", "wraps", "(", "view", ")", "def", "decorated", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "log", ".", "info", "(", "\"Trying to get access to protected resource: '...
37.782609
22.782609
def getaddrspec(self): """Parse an RFC 2822 addr-spec.""" aslist = [] self.gotonext() while self.pos < len(self.field): preserve_ws = True if self.field[self.pos] == '.': if aslist and not aslist[-1].strip(): aslist.pop() ...
[ "def", "getaddrspec", "(", "self", ")", ":", "aslist", "=", "[", "]", "self", ".", "gotonext", "(", ")", "while", "self", ".", "pos", "<", "len", "(", "self", ".", "field", ")", ":", "preserve_ws", "=", "True", "if", "self", ".", "field", "[", "s...
33.53125
14.53125
def _euler_to_q(self, euler): """ Create q array from euler angles :param euler: array [roll, pitch, yaw] in rad :returns: array q which represents a quaternion [w, x, y, z] """ assert(len(euler) == 3) phi = euler[0] theta = euler[1] psi = euler[2]...
[ "def", "_euler_to_q", "(", "self", ",", "euler", ")", ":", "assert", "(", "len", "(", "euler", ")", "==", "3", ")", "phi", "=", "euler", "[", "0", "]", "theta", "=", "euler", "[", "1", "]", "psi", "=", "euler", "[", "2", "]", "c_phi_2", "=", ...
35.692308
9.230769
def _product(*args, **kwds): """ Generates cartesian product of lists given as arguments From itertools.product documentation """ pools = map(tuple, args) * kwds.get('repeat', 1) result = [[]] for pool in pools: result = [x+[y] for x in result for y in pool] return result
[ "def", "_product", "(", "*", "args", ",", "*", "*", "kwds", ")", ":", "pools", "=", "map", "(", "tuple", ",", "args", ")", "*", "kwds", ".", "get", "(", "'repeat'", ",", "1", ")", "result", "=", "[", "[", "]", "]", "for", "pool", "in", "pools...
25.25
16.75
def predict_fixation_duration( durations, angles, length_diffs, dataset=None, params=None): """ Fits a non-linear piecewise regression to fixtaion durations for a fixmat. Returns corrected fixation durations. """ if dataset is None: dataset = np.ones(durations.shape) corrected_d...
[ "def", "predict_fixation_duration", "(", "durations", ",", "angles", ",", "length_diffs", ",", "dataset", "=", "None", ",", "params", "=", "None", ")", ":", "if", "dataset", "is", "None", ":", "dataset", "=", "np", ".", "ones", "(", "durations", ".", "sh...
38.866667
13.8
def update_config_mode(self, prompt): # pylint: disable=no-self-use """Update config mode based on the prompt analysis.""" mode = 'global' if prompt: if 'config' in prompt: mode = 'config' elif 'admin' in prompt: mode = 'admin' se...
[ "def", "update_config_mode", "(", "self", ",", "prompt", ")", ":", "# pylint: disable=no-self-use", "mode", "=", "'global'", "if", "prompt", ":", "if", "'config'", "in", "prompt", ":", "mode", "=", "'config'", "elif", "'admin'", "in", "prompt", ":", "mode", ...
32.818182
14.454545
def reply(self): """ Reply to the selected item. This is a utility method and should not be bound to a key directly. Item type: Submission - add a top level comment Comment - add a comment reply Message - reply to a private message """ ...
[ "def", "reply", "(", "self", ")", ":", "data", "=", "self", ".", "get_selected_item", "(", ")", "if", "data", "[", "'type'", "]", "==", "'Submission'", ":", "body", "=", "data", "[", "'text'", "]", "description", "=", "'submission'", "reply", "=", "dat...
34.27451
15.058824
def _collect_parameters(parameter_names, args, kwargs, defaults): """Creates a dictionary mapping parameters names to their values in the method call. :param parameter_names: The method's parameter names :type parameter_names: list[string] :param args: *args passed into the method ...
[ "def", "_collect_parameters", "(", "parameter_names", ",", "args", ",", "kwargs", ",", "defaults", ")", ":", "parameters", "=", "{", "}", "if", "defaults", "is", "not", "None", ":", "zipped_defaults", "=", "zip", "(", "reversed", "(", "parameter_names", ")",...
43.833333
11.541667
def det_dataset(eb, passband, dataid, comp, time): """ Since RV datasets can have values related to each component in phoebe2, but are component specific in phoebe1 , it is important to determine which dataset to add parameters to. This function will do that. eb - bundle rvpt - relevant phoebe 1 pa...
[ "def", "det_dataset", "(", "eb", ",", "passband", ",", "dataid", ",", "comp", ",", "time", ")", ":", "rvs", "=", "eb", ".", "get_dataset", "(", "kind", "=", "'rv'", ")", ".", "datasets", "#first check to see if there are currently in RV datasets", "if", "datai...
36.741935
28.387097
def word_tokenize(text): """ Split string `text` into word tokens using the Penn Treebank rules """ for (regexp, replacement) in RULES1: text = sub(regexp, replacement, text) # add extra space to make things easier text = " " + text + " " for (regexp, replacement) in RULES2: ...
[ "def", "word_tokenize", "(", "text", ")", ":", "for", "(", "regexp", ",", "replacement", ")", "in", "RULES1", ":", "text", "=", "sub", "(", "regexp", ",", "replacement", ",", "text", ")", "# add extra space to make things easier", "text", "=", "\" \"", "+", ...
33.357143
8.5
def _expectation(p, mean, none, kern, feat, nghp=None): """ Compute the expectation: expectation[n] = <x_n K_{x_n, Z}>_p(x_n) - K_{.,} :: Linear kernel or the equivalent for MarkovGaussian :return: NxDxM """ return tf.matrix_transpose(expectation(p, (kern, feat), mean))
[ "def", "_expectation", "(", "p", ",", "mean", ",", "none", ",", "kern", ",", "feat", ",", "nghp", "=", "None", ")", ":", "return", "tf", ".", "matrix_transpose", "(", "expectation", "(", "p", ",", "(", "kern", ",", "feat", ")", ",", "mean", ")", ...
29.8
12.6
def set_frequencies(self, freq, rg=None, setMaxfeq=True, setMinfreq=True, setSpeed=True): ''' Set cores frequencies freq: int frequency in KHz rg: list of range of cores setMaxfeq: set the maximum frequency, default to true setMinfreq: set the minimum frequency, default ...
[ "def", "set_frequencies", "(", "self", ",", "freq", ",", "rg", "=", "None", ",", "setMaxfeq", "=", "True", ",", "setMinfreq", "=", "True", ",", "setSpeed", "=", "True", ")", ":", "to_change", "=", "self", ".", "__get_ranges", "(", "\"online\"", ")", "i...
44.625
22.125
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: AssetContext for this AssetInstance :rtype: twilio.rest.serverless.v1.service.asset.AssetContext ...
[ "def", "_proxy", "(", "self", ")", ":", "if", "self", ".", "_context", "is", "None", ":", "self", ".", "_context", "=", "AssetContext", "(", "self", ".", "_version", ",", "service_sid", "=", "self", ".", "_solution", "[", "'service_sid'", "]", ",", "si...
37.933333
17.666667
def append_stream(self, streamid, stream, encoding=None): """append a file to search for similarities""" if encoding is None: readlines = stream.readlines else: readlines = decoding_stream(stream, encoding).readlines try: self.linesets.append( ...
[ "def", "append_stream", "(", "self", ",", "streamid", ",", "stream", ",", "encoding", "=", "None", ")", ":", "if", "encoding", "is", "None", ":", "readlines", "=", "stream", ".", "readlines", "else", ":", "readlines", "=", "decoding_stream", "(", "stream",...
32.944444
13.166667
def a_torispherical(D, f, k): r'''Calculates depth of a torispherical head according to [1]_. .. math:: a = a_1 + a_2 .. math:: \alpha = \sin^{-1}\frac{1-2k}{2(f-k)} .. math:: a_1 = fD(1-\cos\alpha) .. math:: a_2 = kD\cos\alpha Parameters ---------- D...
[ "def", "a_torispherical", "(", "D", ",", "f", ",", "k", ")", ":", "alpha", "=", "asin", "(", "(", "1", "-", "2", "*", "k", ")", "/", "(", "2", "*", "(", "f", "-", "k", ")", ")", ")", "a1", "=", "f", "*", "D", "*", "(", "1", "-", "cos"...
21.5
24.863636
def update_job(self, job_id, build=None, custom_data=None, name=None, passed=None, public=None, tags=None): """Edit an existing job.""" method = 'PUT' endpoint = '/rest/v1/{}/jobs/{}'.format(self.client.sauce_username, job_id) ...
[ "def", "update_job", "(", "self", ",", "job_id", ",", "build", "=", "None", ",", "custom_data", "=", "None", ",", "name", "=", "None", ",", "passed", "=", "None", ",", "public", "=", "None", ",", "tags", "=", "None", ")", ":", "method", "=", "'PUT'...
38.714286
12.761905
def from_message(cls, message): """ Create a public blob from a network `.Message`. Specifically, a cert-bearing pubkey auth packet, because by definition OpenSSH-style certificates 'are' their own network representation." """ type_ = message.get_text() return cl...
[ "def", "from_message", "(", "cls", ",", "message", ")", ":", "type_", "=", "message", ".", "get_text", "(", ")", "return", "cls", "(", "type_", "=", "type_", ",", "blob", "=", "message", ".", "asbytes", "(", ")", ")" ]
38.888889
17.555556
def add_requirement( self, install_req, # type: InstallRequirement parent_req_name=None, # type: Optional[str] extras_requested=None # type: Optional[Iterable[str]] ): # type: (...) -> Tuple[List[InstallRequirement], Optional[InstallRequirement]] # noqa: E501 """A...
[ "def", "add_requirement", "(", "self", ",", "install_req", ",", "# type: InstallRequirement", "parent_req_name", "=", "None", ",", "# type: Optional[str]", "extras_requested", "=", "None", "# type: Optional[Iterable[str]]", ")", ":", "# type: (...) -> Tuple[List[InstallRequirem...
42.094828
19.715517
def get_comments_for_reference_on_date(self, reference_id, from_, to): """Pass through to provider CommentLookupSession.get_comments_for_reference_on_date""" # Implemented from azosid template for - # osid.relationship.RelationshipLookupSession.get_relationships_for_source_on_date_template ...
[ "def", "get_comments_for_reference_on_date", "(", "self", ",", "reference_id", ",", "from_", ",", "to", ")", ":", "# Implemented from azosid template for -", "# osid.relationship.RelationshipLookupSession.get_relationships_for_source_on_date_template", "if", "self", ".", "_can", ...
64
21.090909
def handle_basic_container_args(options, parser=None): """Handle the options specified by add_basic_container_args(). @return: a dict that can be used as kwargs for the ContainerExecutor constructor """ dir_modes = {} error_fn = parser.error if parser else sys.exit def handle_dir_mode(path, mod...
[ "def", "handle_basic_container_args", "(", "options", ",", "parser", "=", "None", ")", ":", "dir_modes", "=", "{", "}", "error_fn", "=", "parser", ".", "error", "if", "parser", "else", "sys", ".", "exit", "def", "handle_dir_mode", "(", "path", ",", "mode",...
42.086207
19.241379
def _sounds_re(include_erhua=False): """Sounds are syllables + tones""" tone = '[1-5]' optional_final_erhua = '|r\\b' if include_erhua else '' pattern = '({}{}{})'.format(_joined_syllables_re(), tone, optional_final_erhua) return re.compile(pattern, re.IGNORECASE)
[ "def", "_sounds_re", "(", "include_erhua", "=", "False", ")", ":", "tone", "=", "'[1-5]'", "optional_final_erhua", "=", "'|r\\\\b'", "if", "include_erhua", "else", "''", "pattern", "=", "'({}{}{})'", ".", "format", "(", "_joined_syllables_re", "(", ")", ",", "...
39.857143
19
def run(items): """Perform detection of structural variations with Manta. """ paired = vcfutils.get_paired(items) data = paired.tumor_data if paired else items[0] work_dir = _sv_workdir(data) variant_file = _get_out_file(work_dir, paired) if not utils.file_exists(variant_file): with ...
[ "def", "run", "(", "items", ")", ":", "paired", "=", "vcfutils", ".", "get_paired", "(", "items", ")", "data", "=", "paired", ".", "tumor_data", "if", "paired", "else", "items", "[", "0", "]", "work_dir", "=", "_sv_workdir", "(", "data", ")", "variant_...
47.30303
18.69697
def transform(self, y): """Transform labels to normalized encoding. Parameters ---------- y : array-like of shape [n_samples] Target values. Returns ------- y : array-like of shape [n_samples] """ check_is_fitted(self, 'classes_') ...
[ "def", "transform", "(", "self", ",", "y", ")", ":", "check_is_fitted", "(", "self", ",", "'classes_'", ")", "y", "=", "column_or_1d", "(", "y", ",", "warn", "=", "True", ")", "classes", "=", "np", ".", "unique", "(", "y", ")", "_check_numpy_unicode_bu...
31.190476
16.52381
def on_activity_lifecycle_changed(self, change): """ If the app pauses without pausing the barcode scanner the camera can't be reopened. So we must do it here. """ d = self.declaration if d.active: if change['value'] == 'paused': self.widget.pause...
[ "def", "on_activity_lifecycle_changed", "(", "self", ",", "change", ")", ":", "d", "=", "self", ".", "declaration", "if", "d", ".", "active", ":", "if", "change", "[", "'value'", "]", "==", "'paused'", ":", "self", ".", "widget", ".", "pause", "(", "no...
40.5
8.1
def trigger_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/chat/triggers#create-trigger" api_path = "/api/v2/triggers" return self.call(api_path, method="POST", data=data, **kwargs)
[ "def", "trigger_create", "(", "self", ",", "data", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/triggers\"", "return", "self", ".", "call", "(", "api_path", ",", "method", "=", "\"POST\"", ",", "data", "=", "data", ",", "*", "*", "kwa...
57.5
19
def generate(self, signature_data): """Takes data and returns a signature :arg dict signature_data: data to use to generate a signature :returns: ``Result`` instance """ result = Result() for rule in self.pipeline: rule_name = rule.__class__.__name__ ...
[ "def", "generate", "(", "self", ",", "signature_data", ")", ":", "result", "=", "Result", "(", ")", "for", "rule", "in", "self", ".", "pipeline", ":", "rule_name", "=", "rule", ".", "__class__", ".", "__name__", "try", ":", "if", "rule", ".", "predicat...
29.074074
18.037037
def read_key(pysam_alignment_record): ''' Given a `pysam.AlignedSegment` instance, return the attributes identifying the *read* it comes from (not the alignment). There may be more than one alignment for a read, e.g. chimeric and secondary alignments. ''' return ( pysam_alignment_record....
[ "def", "read_key", "(", "pysam_alignment_record", ")", ":", "return", "(", "pysam_alignment_record", ".", "query_name", ",", "pysam_alignment_record", ".", "is_duplicate", ",", "pysam_alignment_record", ".", "is_read1", ",", "pysam_alignment_record", ".", "is_read2", ",...
37.75
19.75
def start_threads (self): """Spawn threads for URL checking and status printing.""" if self.config["status"]: t = status.Status(self, self.config["status_wait_seconds"]) t.start() self.threads.append(t) if self.config["maxrunseconds"]: t = interrup...
[ "def", "start_threads", "(", "self", ")", ":", "if", "self", ".", "config", "[", "\"status\"", "]", ":", "t", "=", "status", ".", "Status", "(", "self", ",", "self", ".", "config", "[", "\"status_wait_seconds\"", "]", ")", "t", ".", "start", "(", ")"...
43.421053
17.368421
def set_properties(self, properties, **kwargs): """ :param properties: Property names and values given as key-value pairs of strings :type properties: dict Given key-value pairs in *properties* for property names and values, the properties are set on the analysis for the given ...
[ "def", "set_properties", "(", "self", ",", "properties", ",", "*", "*", "kwargs", ")", ":", "dxpy", ".", "api", ".", "analysis_set_properties", "(", "self", ".", "_dxid", ",", "{", "\"properties\"", ":", "properties", "}", ",", "*", "*", "kwargs", ")" ]
40
24.875
def convert_saturation(self, saturation): """ Convert the saturation from decimal percent (0.0-1.0) to byte representation for use in commands. :param saturation: The saturation from in decimal percent (0.0-1.0). 1.0 is the maximum saturation where no white leds will be on. 0.0 i...
[ "def", "convert_saturation", "(", "self", ",", "saturation", ")", ":", "saturation_inverted", "=", "1", "-", "saturation", "return", "math", ".", "ceil", "(", "saturation_inverted", "*", "self", ".", "MAX_SATURATION", ")" ]
42.916667
17.916667
def _reduce_logsumexp(input_tensor, axis=None, keepdims=False, name=None): # pylint: disable=unused-argument """Computes `log(sum(exp(input_tensor))) along the specified axis.""" try: return scipy_special.logsumexp( input_tensor, axis=_astuple(axis), keepdims=keepdims) except NotImplementedError: ...
[ "def", "_reduce_logsumexp", "(", "input_tensor", ",", "axis", "=", "None", ",", "keepdims", "=", "False", ",", "name", "=", "None", ")", ":", "# pylint: disable=unused-argument", "try", ":", "return", "scipy_special", ".", "logsumexp", "(", "input_tensor", ",", ...
50.75
22.166667
def output_files(self): """Returns list of output files from this rule, relative to buildroot. In this case it's simple (for now) - the output files are enumerated in the rule definition. """ outs = [os.path.join(self.address.repo, self.address.path, x) for x in ...
[ "def", "output_files", "(", "self", ")", ":", "outs", "=", "[", "os", ".", "path", ".", "join", "(", "self", ".", "address", ".", "repo", ",", "self", ".", "address", ".", "path", ",", "x", ")", "for", "x", "in", "self", ".", "params", "[", "'o...
39.111111
18.111111
def _matchremove_simple_endings(self, word): """Remove the noun, adjective, adverb word endings""" was_stemmed = False # noun, adjective, and adverb word endings sorted by charlen, then alph simple_endings = ['ibus', 'ius', 'ae', ...
[ "def", "_matchremove_simple_endings", "(", "self", ",", "word", ")", ":", "was_stemmed", "=", "False", "# noun, adjective, and adverb word endings sorted by charlen, then alph", "simple_endings", "=", "[", "'ibus'", ",", "'ius'", ",", "'ae'", ",", "'am'", ",", "'as'", ...
32.060606
12.575758
def get_logger(context=None, name=None): """Return a logger for *context*. Return a :class:`ContextLogger` instance. The instance implements the standard library's :class:`logging.Logger` interface. """ # Many class instances have their own logger. Share them to save memory if # possible, i.e. ...
[ "def", "get_logger", "(", "context", "=", "None", ",", "name", "=", "None", ")", ":", "# Many class instances have their own logger. Share them to save memory if", "# possible, i.e. when *context* is not set.", "if", "name", "is", "None", ":", "name", "=", "_logger_name", ...
38.526316
14.210526
def authenticate(self): """ Authenticate against the HP Cloud Identity Service. This is the first step in any hpcloud.com session, although this method is automatically called when accessing higher-level methods/attributes. **Examples of Credentials Configuration** - B...
[ "def", "authenticate", "(", "self", ")", ":", "log", ".", "info", "(", "\"Authenticating to HP Cloud...\"", ")", "creds", "=", "self", ".", "creds", "access_key_id", "=", "creds", ".", "get", "(", "'access_key_id'", ",", "''", ")", "secret_access_key", "=", ...
38.862069
23.172414
def v1_url_associations(tags, url): '''Retrieve associations for a given URL. The associations returned have the exact same structure as defined in the ``v1_tag_associate`` route with one addition: a ``tag`` field contains the full tag name for the association. ''' url = urllib.unquote_plus(url...
[ "def", "v1_url_associations", "(", "tags", ",", "url", ")", ":", "url", "=", "urllib", ".", "unquote_plus", "(", "url", ".", "decode", "(", "'utf-8'", ")", ")", ".", "strip", "(", ")", "return", "{", "'associations'", ":", "tags", ".", "assocs_by_url", ...
43.333333
20.666667
def prune_mechanism_by_data(graph, key: Optional[str] = None) -> None: """Remove all leaves and source nodes that don't have weights. Is a thin wrapper around :func:`remove_unweighted_leaves` and :func:`remove_unweighted_sources` :param graph: A BEL graph :param key: The key in the node data dictiona...
[ "def", "prune_mechanism_by_data", "(", "graph", ",", "key", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "None", ":", "remove_unweighted_leaves", "(", "graph", ",", "key", "=", "key", ")", "remove_unweighted_sources", "(", "graph", ",", "key", ...
37.4375
22.125
def get_natural_key_info(cls): """ Derive natural key from first unique_together definition, noting which fields are related objects vs. regular fields. """ fields = cls.get_natural_key_def() info = [] for name in fields: field = cls._meta.get_field(na...
[ "def", "get_natural_key_info", "(", "cls", ")", ":", "fields", "=", "cls", ".", "get_natural_key_def", "(", ")", "info", "=", "[", "]", "for", "name", "in", "fields", ":", "field", "=", "cls", ".", "_meta", ".", "get_field", "(", "name", ")", "rel_to",...
36.210526
11.263158
def encrypt(self, key, iv="", cek="", **kwargs): """ Produces a JWE as defined in RFC7516 using RSA algorithms :param key: RSA key :param iv: Initialization vector :param cek: Content master key :param kwargs: Extra keyword arguments :return: A signed payload ...
[ "def", "encrypt", "(", "self", ",", "key", ",", "iv", "=", "\"\"", ",", "cek", "=", "\"\"", ",", "*", "*", "kwargs", ")", ":", "_msg", "=", "as_bytes", "(", "self", ".", "msg", ")", "if", "\"zip\"", "in", "self", ":", "if", "self", "[", "\"zip\...
31.627451
18.254902
def merge_subtokens(doc, label="subtok"): """Merge subtokens into a single token. doc (Doc): The Doc object. label (unicode): The subtoken dependency label. RETURNS (Doc): The Doc object with merged subtokens. DOCS: https://spacy.io/api/pipeline-functions#merge_subtokens """ merger = Match...
[ "def", "merge_subtokens", "(", "doc", ",", "label", "=", "\"subtok\"", ")", ":", "merger", "=", "Matcher", "(", "doc", ".", "vocab", ")", "merger", ".", "add", "(", "\"SUBTOK\"", ",", "None", ",", "[", "{", "\"DEP\"", ":", "label", ",", "\"op\"", ":"...
34.529412
15
def pull(self, platform=None): """ Pull the image digest. Args: platform (str): The platform to pull the image for. Default: ``None`` Returns: (:py:class:`Image`): A reference to the pulled image. """ repository, _ = parse_repository_...
[ "def", "pull", "(", "self", ",", "platform", "=", "None", ")", ":", "repository", ",", "_", "=", "parse_repository_tag", "(", "self", ".", "image_name", ")", "return", "self", ".", "collection", ".", "pull", "(", "repository", ",", "tag", "=", "self", ...
31.384615
20.769231
def apply_filters(self, query, filters): """ Apply user specified filters to query """ assert isinstance(query, peewee.Query) assert isinstance(filters, dict)
[ "def", "apply_filters", "(", "self", ",", "query", ",", "filters", ")", ":", "assert", "isinstance", "(", "query", ",", "peewee", ".", "Query", ")", "assert", "isinstance", "(", "filters", ",", "dict", ")" ]
32.166667
1.833333
def set_state(self, state=None, **kwargs): """ Set the view state of the camera Should be a dict (or kwargs) as returned by get_state. It can be an incomlete dict, in which case only the specified properties are set. Parameters ---------- state : dict ...
[ "def", "set_state", "(", "self", ",", "state", "=", "None", ",", "*", "*", "kwargs", ")", ":", "D", "=", "state", "or", "{", "}", "D", ".", "update", "(", "kwargs", ")", "for", "key", ",", "val", "in", "D", ".", "items", "(", ")", ":", "if", ...
31.8
16.25
def routing(routes, request): """Definition for route matching : helper""" # strip trailing slashes from request path path = request.path.strip('/') # iterate through routes to match args = {} for name, route in routes.items(): if route['path'] == '^': # this section exists...
[ "def", "routing", "(", "routes", ",", "request", ")", ":", "# strip trailing slashes from request path", "path", "=", "request", ".", "path", ".", "strip", "(", "'/'", ")", "# iterate through routes to match", "args", "=", "{", "}", "for", "name", ",", "route", ...
38.756098
19.04878
def save_filter(name, filt, full=None, path='filters'): r"""Save DLF-filter and inversion output to plain text files.""" # First we'll save the filter using its internal routine. # This will create the directory ./filters if it doesn't exist already. filt.tofile(path) # If full, we store the inver...
[ "def", "save_filter", "(", "name", ",", "filt", ",", "full", "=", "None", ",", "path", "=", "'filters'", ")", ":", "# First we'll save the filter using its internal routine.", "# This will create the directory ./filters if it doesn't exist already.", "filt", ".", "tofile", ...
39.654545
22.963636
def _cmd_opts_solver(self, cmd_name): """Scan options related to one command and enrich _opt_cmds.""" sections = self.sections_list(cmd_name) cmd_dict = self._opt_cmds[cmd_name] if cmd_name else self._opt_bare for sct in reversed(sections): for opt, opt_meta in self._conf[sct...
[ "def", "_cmd_opts_solver", "(", "self", ",", "cmd_name", ")", ":", "sections", "=", "self", ".", "sections_list", "(", "cmd_name", ")", "cmd_dict", "=", "self", ".", "_opt_cmds", "[", "cmd_name", "]", "if", "cmd_name", "else", "self", ".", "_opt_bare", "fo...
48.4
12.2
def next(self, verifyPad=False): """Manually iterate through the data loaded in Instrument object. Bounds of iteration and iteration type (day/file) are set by `bounds` attribute. Note ---- If there were no previous calls to load then the first...
[ "def", "next", "(", "self", ",", "verifyPad", "=", "False", ")", ":", "if", "self", ".", "_iter_type", "==", "'date'", ":", "if", "self", ".", "date", "is", "not", "None", ":", "idx", ",", "=", "np", ".", "where", "(", "self", ".", "_iter_list", ...
41.72973
20.810811
def get_font_path(self): """Return the current font path as a list of strings.""" r = request.GetFontPath(display = self.display) return r.paths
[ "def", "get_font_path", "(", "self", ")", ":", "r", "=", "request", ".", "GetFontPath", "(", "display", "=", "self", ".", "display", ")", "return", "r", ".", "paths" ]
41.25
12.25
def annotate(abf): """stamp the bottom with file info.""" msg="SWHLab %s "%str(swhlab.VERSION) msg+="ID:%s "%abf.ID msg+="CH:%d "%abf.channel msg+="PROTOCOL:%s "%abf.protoComment msg+="COMMAND: %d%s "%(abf.holding,abf.units) msg+="GENERATED:%s "%'{0:%Y-%m-%d %H:%M:%S}'.format(datetime.dateti...
[ "def", "annotate", "(", "abf", ")", ":", "msg", "=", "\"SWHLab %s \"", "%", "str", "(", "swhlab", ".", "VERSION", ")", "msg", "+=", "\"ID:%s \"", "%", "abf", ".", "ID", "msg", "+=", "\"CH:%d \"", "%", "abf", ".", "channel", "msg", "+=", "\"PROTOCOL:%s ...
46.9375
16.9375
def _get(self, obj): ''' Internal implementation of instance attribute access for the ``BasicPropertyDescriptor`` getter. If the value has not been explicitly set by a user, return that value. Otherwise, return the default. Args: obj (HasProps) : the instance to get...
[ "def", "_get", "(", "self", ",", "obj", ")", ":", "if", "not", "hasattr", "(", "obj", ",", "'_property_values'", ")", ":", "raise", "RuntimeError", "(", "\"Cannot get a property value '%s' from a %s instance before HasProps.__init__\"", "%", "(", "self", ".", "name"...
35.296296
27.148148
def show_external_release_file(root, request): """ Download a release from a download url from its package information. Must be used with :func:`pyshop.helpers.download.renderer_factory` to download the release file. :return: download informations :rtype: dict """ session = DBSession() ...
[ "def", "show_external_release_file", "(", "root", ",", "request", ")", ":", "session", "=", "DBSession", "(", ")", "settings", "=", "request", ".", "registry", ".", "settings", "whlify", "=", "asbool", "(", "settings", ".", "get", "(", "'pyshop.mirror.wheelify...
31
18.333333
def _run_pyroma(setup_file, show_lint_files): """Run pyroma.""" from pyroma import projectdata, ratings from prospector.message import Message, Location _debug_linter_status("pyroma", setup_file, show_lint_files) return_dict = dict() data = projectdata.get_data(os.getcwd()) all_tests = ra...
[ "def", "_run_pyroma", "(", "setup_file", ",", "show_lint_files", ")", ":", "from", "pyroma", "import", "projectdata", ",", "ratings", "from", "prospector", ".", "message", "import", "Message", ",", "Location", "_debug_linter_status", "(", "\"pyroma\"", ",", "setup...
35.652174
15
def fetch_token( self, token_url, code=None, authorization_response=None, body="", auth=None, username=None, password=None, method="POST", force_querystring=False, timeout=None, headers=None, verify=True, pro...
[ "def", "fetch_token", "(", "self", ",", "token_url", ",", "code", "=", "None", ",", "authorization_response", "=", "None", ",", "body", "=", "\"\"", ",", "auth", "=", "None", ",", "username", "=", "None", ",", "password", "=", "None", ",", "method", "=...
43.111111
21.851852
def set_frequency(self, pin, frequency_hz): """Set frequency (in Hz) of PWM output on specified pin.""" if pin not in self.pwm: raise ValueError('Pin {0} is not configured as a PWM. Make sure to first call start for the pin.'.format(pin)) self.pwm[pin].ChangeFrequency(frequency_hz)
[ "def", "set_frequency", "(", "self", ",", "pin", ",", "frequency_hz", ")", ":", "if", "pin", "not", "in", "self", ".", "pwm", ":", "raise", "ValueError", "(", "'Pin {0} is not configured as a PWM. Make sure to first call start for the pin.'", ".", "format", "(", "p...
63
21.2
def read_block(self, address): """Read 32 bytes from the weather station. If the read fails for any reason, :obj:`None` is returned. :param address: address to read from. :type address: int :return: the data from the weather station. :rtype: list(int) """ ...
[ "def", "read_block", "(", "self", ",", "address", ")", ":", "buf", "=", "[", "self", ".", "ReadCommand", ",", "address", "//", "256", ",", "address", "%", "256", ",", "self", ".", "EndMark", ",", "self", ".", "ReadCommand", ",", "address", "//", "256...
23.925926
18.481481
def install(**kwargs): """setup entry point""" if USE_SETUPTOOLS: if "--force-manifest" in sys.argv: sys.argv.remove("--force-manifest") packages = [modname] + get_packages(join(base_dir, "pylint"), modname) if USE_SETUPTOOLS: if install_requires: kwargs["install_...
[ "def", "install", "(", "*", "*", "kwargs", ")", ":", "if", "USE_SETUPTOOLS", ":", "if", "\"--force-manifest\"", "in", "sys", ".", "argv", ":", "sys", ".", "argv", ".", "remove", "(", "\"--force-manifest\"", ")", "packages", "=", "[", "modname", "]", "+",...
35.744186
11.674419
def get_request_body(self): """ Decodes the request body and returns it. :return: the decoded request body as a :class:`dict` instance. :raises: :class:`tornado.web.HTTPError` if the body cannot be decoded (415) or if decoding fails (400) """ if self._reques...
[ "def", "get_request_body", "(", "self", ")", ":", "if", "self", ".", "_request_body", "is", "None", ":", "content_type_str", "=", "self", ".", "request", ".", "headers", ".", "get", "(", "'Content-Type'", ",", "'application/octet-stream'", ")", "LOGGER", ".", ...
44.34375
18.03125
def start_pipeline(url, pipeline_id, auth, verify_ssl, runtime_parameters={}): """Start a running pipeline. The API waits for the pipeline to be fully started. Args: url (str): the host url in the form 'http://host:port/'. pipeline_id (str): the ID of of the exported pip...
[ "def", "start_pipeline", "(", "url", ",", "pipeline_id", ",", "auth", ",", "verify_ssl", ",", "runtime_parameters", "=", "{", "}", ")", ":", "start_result", "=", "requests", ".", "post", "(", "url", "+", "'/'", "+", "pipeline_id", "+", "'/start'", ",", "...
44.909091
26.772727
def set_current_ns( ns_name: str, module: types.ModuleType = None, ns_var_name: str = NS_VAR_NAME, ns_var_ns: str = NS_VAR_NS, ) -> Var: """Set the value of the dynamic variable `*ns*` in the current thread.""" symbol = sym.Symbol(ns_name) ns = Namespace.get_or_create(symbol, module=module) ...
[ "def", "set_current_ns", "(", "ns_name", ":", "str", ",", "module", ":", "types", ".", "ModuleType", "=", "None", ",", "ns_var_name", ":", "str", "=", "NS_VAR_NAME", ",", "ns_var_ns", ":", "str", "=", "NS_VAR_NS", ",", ")", "->", "Var", ":", "symbol", ...
35.444444
16.611111
def _do_ffts(detector, stream, Nc): """ Perform ffts on data, detector and denominator boxcar :type detector: eqcorrscan.core.subspace.Detector :param detector: Detector object for doing detecting :type stream: list of obspy.core.stream.Stream :param stream: List of streams processed according ...
[ "def", "_do_ffts", "(", "detector", ",", "stream", ",", "Nc", ")", ":", "min_fftlen", "=", "int", "(", "stream", "[", "0", "]", "[", "0", "]", ".", "data", ".", "shape", "[", "0", "]", "+", "detector", ".", "data", "[", "0", "]", ".", "shape", ...
39.097561
15.292683
def set_environment_variable(self, key, val): """ Sets a variable if that variable is not already set """ if self.get_environment_variable(key) in [None, val]: self.__dict__['environment_variables'][key] = val else: raise Contradiction("Could not set environment variable ...
[ "def", "set_environment_variable", "(", "self", ",", "key", ",", "val", ")", ":", "if", "self", ".", "get_environment_variable", "(", "key", ")", "in", "[", "None", ",", "val", "]", ":", "self", ".", "__dict__", "[", "'environment_variables'", "]", "[", ...
54.5
19
def checkCursor(self): 'Keep cursor in bounds of data and screen.' # keep cursor within actual available rowset if self.nRows == 0 or self.cursorRowIndex <= 0: self.cursorRowIndex = 0 elif self.cursorRowIndex >= self.nRows: self.cursorRowIndex = self.nRows-1 ...
[ "def", "checkCursor", "(", "self", ")", ":", "# keep cursor within actual available rowset", "if", "self", ".", "nRows", "==", "0", "or", "self", ".", "cursorRowIndex", "<=", "0", ":", "self", ".", "cursorRowIndex", "=", "0", "elif", "self", ".", "cursorRowInd...
44.042553
22.340426
def process_request( self, path: str, request_headers: Headers ) -> Union[Optional[HTTPResponse], Awaitable[Optional[HTTPResponse]]]: """ Intercept the HTTP request and return an HTTP response if needed. ``request_headers`` is a :class:`~websockets.http.Headers` instance. I...
[ "def", "process_request", "(", "self", ",", "path", ":", "str", ",", "request_headers", ":", "Headers", ")", "->", "Union", "[", "Optional", "[", "HTTPResponse", "]", ",", "Awaitable", "[", "Optional", "[", "HTTPResponse", "]", "]", "]", ":", "if", "self...
42.057143
29.428571
def addMeal(self, date, category, name, notes=None, prices=None): """ This is the main helper, it adds a meal to the canteen. The following data are needed: :param datetime.date date: Date for the meal :param str category: Name of the meal category :param str me...
[ "def", "addMeal", "(", "self", ",", "date", ",", "category", ",", "name", ",", "notes", "=", "None", ",", "prices", "=", "None", ")", ":", "# check name:", "if", "not", "len", "(", "name", ")", ":", "raise", "ValueError", "(", "'Meal names must not be em...
44.740741
19.388889
def load_vstr(buf, pos): """Load bytes prefixed by vint length""" slen, pos = load_vint(buf, pos) return load_bytes(buf, slen, pos)
[ "def", "load_vstr", "(", "buf", ",", "pos", ")", ":", "slen", ",", "pos", "=", "load_vint", "(", "buf", ",", "pos", ")", "return", "load_bytes", "(", "buf", ",", "slen", ",", "pos", ")" ]
35
6
def _matrix_grad(q, h, h_dx, t, t_prime): ''' Returns the gradient with respect to a single variable''' N = len(q) W = np.zeros([N, N]) Wprime = np.zeros([N, N]) for i in range(N): W[i, i] = 0.5*(h[min(i+1, N-1)] - h[max(i-1, 0)]) Wprime[i, i] = \ 0.5*(h_dx[min(i+1, N-1)...
[ "def", "_matrix_grad", "(", "q", ",", "h", ",", "h_dx", ",", "t", ",", "t_prime", ")", ":", "N", "=", "len", "(", "q", ")", "W", "=", "np", ".", "zeros", "(", "[", "N", ",", "N", "]", ")", "Wprime", "=", "np", ".", "zeros", "(", "[", "N",...
29.823529
21.823529
def get_target_temperature(self): """ Returns the actual target temperature. Attention: Returns None if the value can't be queried or is unknown. """ value = self.box.homeautoswitch("gethkrtsoll", self.actor_id) self.target_temperature = self.__get_temp(value) ret...
[ "def", "get_target_temperature", "(", "self", ")", ":", "value", "=", "self", ".", "box", ".", "homeautoswitch", "(", "\"gethkrtsoll\"", ",", "self", ".", "actor_id", ")", "self", ".", "target_temperature", "=", "self", ".", "__get_temp", "(", "value", ")", ...
42.5
12
def gettext_lazy(message, domain=DEFAULT_DOMAIN): """Mark a message as translatable, but delay the translation until the message is used. Sometimes, there are some messages that need to be translated, but the translation can't be done at the point the message itself is written. For example, the names of ...
[ "def", "gettext_lazy", "(", "message", ",", "domain", "=", "DEFAULT_DOMAIN", ")", ":", "return", "LazyProxy", "(", "gettext", ",", "message", ",", "domain", "=", "domain", ",", "enable_cache", "=", "False", ")" ]
41.969697
26.515152
def add_child(self, child): """Children are GFFFeatures and are defined when added. This is done to avoid memory overheads that may be incurred by GFF files that have millions of rows. """ child_id = getattr(child, 'id', None) if child_id: if not hasattr(self, 'child...
[ "def", "add_child", "(", "self", ",", "child", ")", ":", "child_id", "=", "getattr", "(", "child", ",", "'id'", ",", "None", ")", "if", "child_id", ":", "if", "not", "hasattr", "(", "self", ",", "'children'", ")", ":", "self", ".", "children", "=", ...
40.454545
11.818182
def log_likelihood(self, ts): """ Returns the log likelihood of the parameters on the given time series. Based on http://www.unc.edu/~jbhill/Bollerslev_GARCH_1986.pdf """ likelihood = self._jmodel.logLikelihood(_py2java(self._ctx, Vectors.dense(ts))) return _java...
[ "def", "log_likelihood", "(", "self", ",", "ts", ")", ":", "likelihood", "=", "self", ".", "_jmodel", ".", "logLikelihood", "(", "_py2java", "(", "self", ".", "_ctx", ",", "Vectors", ".", "dense", "(", "ts", ")", ")", ")", "return", "_java2py", "(", ...
42.375
20.375
def splits(self): """ 将一个DataStruct按code分解为N个DataStruct """ return list(map(lambda x: self.select_code(x), self.code))
[ "def", "splits", "(", "self", ")", ":", "return", "list", "(", "map", "(", "lambda", "x", ":", "self", ".", "select_code", "(", "x", ")", ",", "self", ".", "code", ")", ")" ]
29.2
10
def get_cluster_placement_group(self): """ Return the placement group, create it if it doesn't yet exist. (needed for cluster type instances). """ placement_group_name = 'pg-%s' % (self._name) try: self.ec2.create_placement_group(placement_group_name, ...
[ "def", "get_cluster_placement_group", "(", "self", ")", ":", "placement_group_name", "=", "'pg-%s'", "%", "(", "self", ".", "_name", ")", "try", ":", "self", ".", "ec2", ".", "create_placement_group", "(", "placement_group_name", ",", "strategy", "=", "'cluster'...
33.166667
15.666667
def redirect_ext(to, params_=None, anchor_=None, permanent_=False, args=None, kwargs=None): """ Advanced redirect which can includes GET-parameters and anchor. """ if permanent_: redirect_class = HttpResponsePermanentRedirect else: redirect_class = HttpResponseRedirect return red...
[ "def", "redirect_ext", "(", "to", ",", "params_", "=", "None", ",", "anchor_", "=", "None", ",", "permanent_", "=", "False", ",", "args", "=", "None", ",", "kwargs", "=", "None", ")", ":", "if", "permanent_", ":", "redirect_class", "=", "HttpResponsePerm...
41.777778
20.888889
def supported_operations(self): """ All operations supported by the camera. """ return tuple(op for op in backend.CAM_OPS if self._abilities.operations & op)
[ "def", "supported_operations", "(", "self", ")", ":", "return", "tuple", "(", "op", "for", "op", "in", "backend", ".", "CAM_OPS", "if", "self", ".", "_abilities", ".", "operations", "&", "op", ")" ]
47.75
8.5
def delete(ctx): """Delete build job. Uses [Caching](/references/polyaxon-cli/#caching) Example: \b ```bash $ polyaxon build delete ``` \b ```bash $ polyaxon build -b 2 delete ``` """ user, project_name, _build = get_build_or_local(ctx.obj.get('project'), ctx.obj....
[ "def", "delete", "(", "ctx", ")", ":", "user", ",", "project_name", ",", "_build", "=", "get_build_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'build'", ")", ")", "if", "not", "cli...
29.352941
26.735294
def tokenize(self, text): """Tokenize given string `text`, and return a list of tokens. Raises :class:`~textparser.TokenizeError` on failure. This method should only be called by :func:`~textparser.Parser.parse()`, but may very well be overridden if the default implementation do...
[ "def", "tokenize", "(", "self", ",", "text", ")", ":", "names", ",", "specs", "=", "self", ".", "_unpack_token_specs", "(", ")", "keywords", "=", "self", ".", "keywords", "(", ")", "tokens", ",", "re_token", "=", "tokenize_init", "(", "specs", ")", "fo...
29.294118
18.911765
def load(cls, path, encoding="utf-8", format_=None, fps=None, **kwargs): """ Load subtitle file from given path. Arguments: path (str): Path to subtitle file. encoding (str): Character encoding of input file. Defaults to UTF-8, you may need to change this...
[ "def", "load", "(", "cls", ",", "path", ",", "encoding", "=", "\"utf-8\"", ",", "format_", "=", "None", ",", "fps", "=", "None", ",", "*", "*", "kwargs", ")", ":", "with", "open", "(", "path", ",", "encoding", "=", "encoding", ")", "as", "fp", ":...
39.95122
23.170732
def _repeat_iter(input_iter): """Iterate over the input iter values. Then repeat the last value indefinitely. This is useful to repeat seed values when an insufficient number of seeds are provided. E.g. KISS(1) effectively becomes KISS(1, 1, 1, 1), rather than (if we just used default values) KISS(...
[ "def", "_repeat_iter", "(", "input_iter", ")", ":", "last_value", "=", "None", "for", "value", "in", "input_iter", ":", "last_value", "=", "value", "yield", "value", "if", "last_value", "is", "not", "None", ":", "while", "True", ":", "yield", "last_value" ]
42
22.9
def _update_labels(self, label, crop_box, height, width): """Convert labels according to crop box""" xmin = float(crop_box[0]) / width ymin = float(crop_box[1]) / height w = float(crop_box[2]) / width h = float(crop_box[3]) / height out = label.copy() out[:, (1, 3...
[ "def", "_update_labels", "(", "self", ",", "label", ",", "crop_box", ",", "height", ",", "width", ")", ":", "xmin", "=", "float", "(", "crop_box", "[", "0", "]", ")", "/", "width", "ymin", "=", "float", "(", "crop_box", "[", "1", "]", ")", "/", "...
41.809524
14.190476
def libvlc_media_get_duration(p_md): '''Get duration (in ms) of media descriptor object item. @param p_md: media descriptor object. @return: duration of media item or -1 on error. ''' f = _Cfunctions.get('libvlc_media_get_duration', None) or \ _Cfunction('libvlc_media_get_duration', ((1,),),...
[ "def", "libvlc_media_get_duration", "(", "p_md", ")", ":", "f", "=", "_Cfunctions", ".", "get", "(", "'libvlc_media_get_duration'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_media_get_duration'", ",", "(", "(", "1", ",", ")", ",", ")", ",", "None",...
42.555556
15.666667
def get_webhook(self): """Get the current callback URL if it exists. :return: The currently set webhook """ api = self._get_api(mds.NotificationsApi) return Webhook(api.get_webhook())
[ "def", "get_webhook", "(", "self", ")", ":", "api", "=", "self", ".", "_get_api", "(", "mds", ".", "NotificationsApi", ")", "return", "Webhook", "(", "api", ".", "get_webhook", "(", ")", ")" ]
31.142857
10
def check_data(self, *args, **kwargs): """Check whether the plotter of this plot method can visualize the data """ plotter_cls = self.plotter_cls da_list = self._project_plotter._da.psy.to_interactive_list() return plotter_cls.check_data( da_list.all_names, da_list.al...
[ "def", "check_data", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "plotter_cls", "=", "self", ".", "plotter_cls", "da_list", "=", "self", ".", "_project_plotter", ".", "_da", ".", "psy", ".", "to_interactive_list", "(", ")", "return"...
49.428571
9.714286
def is_identifier(string): """Check if string could be a valid python identifier :param string: string to be tested :returns: True if string can be a python identifier, False otherwise :rtype: bool """ matched = PYTHON_IDENTIFIER_RE.match(string) return bool(matched) and not keyword.iskeywo...
[ "def", "is_identifier", "(", "string", ")", ":", "matched", "=", "PYTHON_IDENTIFIER_RE", ".", "match", "(", "string", ")", "return", "bool", "(", "matched", ")", "and", "not", "keyword", ".", "iskeyword", "(", "string", ")" ]
35.777778
15.333333
def determine_frame_positions(self): """Record the file pointer position of each frame""" self.rewind_file() with ignored(struct.error): while True: pointer_position = self.blob_file.tell() length = struct.unpack('<i', self.blob_file.read(4))[0] ...
[ "def", "determine_frame_positions", "(", "self", ")", ":", "self", ".", "rewind_file", "(", ")", "with", "ignored", "(", "struct", ".", "error", ")", ":", "while", "True", ":", "pointer_position", "=", "self", ".", "blob_file", ".", "tell", "(", ")", "le...
46.818182
14.818182
def to_naf(self): """ Converts a KAF object to NAF (in memory). You will have to use the method dump later to save it as a new NAF file """ if self.type == 'KAF': self.root.tag = self.type = 'NAF' ## Convert the header if self.header is not None: ...
[ "def", "to_naf", "(", "self", ")", ":", "if", "self", ".", "type", "==", "'KAF'", ":", "self", ".", "root", ".", "tag", "=", "self", ".", "type", "=", "'NAF'", "## Convert the header", "if", "self", ".", "header", "is", "not", "None", ":", "self", ...
34.5875
19.0875
def _override_payload(self, payload): """ This function transforms the payload into a new format using the self.override_payload property. """ if self.override_payload: old_payload = payload def get_value(data, key): try: ...
[ "def", "_override_payload", "(", "self", ",", "payload", ")", ":", "if", "self", ".", "override_payload", ":", "old_payload", "=", "payload", "def", "get_value", "(", "data", ",", "key", ")", ":", "try", ":", "parent_key", ",", "nested_key", "=", "key", ...
33.538462
15.461538
def install_language(language): """Install translation service routines into default namespace.""" translator = get_translator(default_domain, default_directory, languages=[get_lang(language)], fallback=True) do_unicode = True translator.install(do_unicode)
[ "def", "install_language", "(", "language", ")", ":", "translator", "=", "get_translator", "(", "default_domain", ",", "default_directory", ",", "languages", "=", "[", "get_lang", "(", "language", ")", "]", ",", "fallback", "=", "True", ")", "do_unicode", "=",...
46
12.333333
def color_ramp(self, size): """Generate a color ramp for the current screen height.""" color = PALETTE.get(self.option.palette, {}) color = color.get(self.term.colors, None) color_ramp = [] if color is not None: ratio = len(color) / float(size) for i in ra...
[ "def", "color_ramp", "(", "self", ",", "size", ")", ":", "color", "=", "PALETTE", ".", "get", "(", "self", ".", "option", ".", "palette", ",", "{", "}", ")", "color", "=", "color", ".", "get", "(", "self", ".", "term", ".", "colors", ",", "None",...
38.727273
14.181818
def tickets(self, extra_params=None): """ A User's tickets across all available spaces """ tickets = [] for space in self.api.spaces(): tickets += filter( lambda ticket: ticket.get('assigned_to_id', None) == self['id'], space.tickets(ex...
[ "def", "tickets", "(", "self", ",", "extra_params", "=", "None", ")", ":", "tickets", "=", "[", "]", "for", "space", "in", "self", ".", "api", ".", "spaces", "(", ")", ":", "tickets", "+=", "filter", "(", "lambda", "ticket", ":", "ticket", ".", "ge...
33.727273
13.363636
def F1(self, thresholds=None, train=False, valid=False, xval=False): """ Get the F1 values for a set of thresholds for the models explored. If all are False (default), then return the training metric value. If more than one options is set to True, then return a dictionary of metrics whe...
[ "def", "F1", "(", "self", ",", "thresholds", "=", "None", ",", "train", "=", "False", ",", "valid", "=", "False", ",", "xval", "=", "False", ")", ":", "return", "{", "model", ".", "model_id", ":", "model", ".", "F1", "(", "thresholds", ",", "train"...
55.9375
31.0625
def clean_worksheet(wks, gfile_id, wks_name, credentials): """DOCS...""" values = wks.get_all_values() if values: df_ = pd.DataFrame(index=range(len(values)), columns=range(len(values[0]))) df_ = df_.fillna('') wks = upload(df_, gfile_id, wks_name=wks_name...
[ "def", "clean_worksheet", "(", "wks", ",", "gfile_id", ",", "wks_name", ",", "credentials", ")", ":", "values", "=", "wks", ".", "get_all_values", "(", ")", "if", "values", ":", "df_", "=", "pd", ".", "DataFrame", "(", "index", "=", "range", "(", "len"...
36.583333
17
def compile_for_aexec(source, filename="<aexec>", mode="single", dont_imply_dedent=False, local={}): """Return a list of (coroutine object, abstract base tree).""" flags = ast.PyCF_ONLY_AST if dont_imply_dedent: flags |= codeop.PyCF_DONT_IMPLY_DEDENT if compat.PY35: ...
[ "def", "compile_for_aexec", "(", "source", ",", "filename", "=", "\"<aexec>\"", ",", "mode", "=", "\"single\"", ",", "dont_imply_dedent", "=", "False", ",", "local", "=", "{", "}", ")", ":", "flags", "=", "ast", ".", "PyCF_ONLY_AST", "if", "dont_imply_dedent...
44.045455
16.045455
def delete(sql, *args, **kwargs): """Deletes and commits with an insert sql statement""" assert "delete" in sql.lower(), 'This function requires a delete statement, provided: {}'.format(sql) CoyoteDb.execute_and_commit(sql, *args, **kwargs)
[ "def", "delete", "(", "sql", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "assert", "\"delete\"", "in", "sql", ".", "lower", "(", ")", ",", "'This function requires a delete statement, provided: {}'", ".", "format", "(", "sql", ")", "CoyoteDb", ".", ...
65.25
23.25
def accuracy(self, outputs): '''Build a Theano expression for computing the accuracy of graph output. Parameters ---------- outputs : dict of Theano expressions A dictionary mapping network output names to Theano expressions representing the outputs of a computat...
[ "def", "accuracy", "(", "self", ",", "outputs", ")", ":", "output", "=", "outputs", "[", "self", ".", "output_name", "]", "predict", "=", "TT", ".", "argmax", "(", "output", ",", "axis", "=", "-", "1", ")", "correct", "=", "TT", ".", "eq", "(", "...
36
20.545455
def make_codon_list(protein_seq, template_dna=None, include_stop=True): """ Return a list of codons that would be translated to the given protein sequence. Codons are picked first to minimize the mutations relative to a template DNA sequence and second to prefer "optimal" codons. """ codon_l...
[ "def", "make_codon_list", "(", "protein_seq", ",", "template_dna", "=", "None", ",", "include_stop", "=", "True", ")", ":", "codon_list", "=", "[", "]", "if", "template_dna", "is", "None", ":", "template_dna", "=", "[", "]", "# Reverse translate each codon, pref...
33.868421
21.763158
def visit(self, node, abort=abort_visit): """Visit a node.""" method = 'visit_' + node.__class__.__name__ visitor = getattr(self, method, abort) return visitor(node)
[ "def", "visit", "(", "self", ",", "node", ",", "abort", "=", "abort_visit", ")", ":", "method", "=", "'visit_'", "+", "node", ".", "__class__", ".", "__name__", "visitor", "=", "getattr", "(", "self", ",", "method", ",", "abort", ")", "return", "visito...
38.6
6
def _next_lexem(self, lexem_type, source_code, source_code_size): """Return next readable lexem of given type in source_code. If no value can be found, the neutral_value will be used""" # define reader as a lexem extractor def reader(seq, block_size): identificator = '' ...
[ "def", "_next_lexem", "(", "self", ",", "lexem_type", ",", "source_code", ",", "source_code_size", ")", ":", "# define reader as a lexem extractor", "def", "reader", "(", "seq", ",", "block_size", ")", ":", "identificator", "=", "''", "for", "char", "in", "sourc...
44.842105
12.947368
def update_check(package_name, package_version, bypass_cache=False, url=None, **extra_data): """Convenience method that outputs to stdout if an update is available.""" checker = UpdateChecker(url) checker.bypass_cache = bypass_cache result = checker.check(package_name, package_version, ...
[ "def", "update_check", "(", "package_name", ",", "package_version", ",", "bypass_cache", "=", "False", ",", "url", "=", "None", ",", "*", "*", "extra_data", ")", ":", "checker", "=", "UpdateChecker", "(", "url", ")", "checker", ".", "bypass_cache", "=", "b...
45.375
16.375
def attribute_map_get(self, address, route_dist=None, route_family=RF_VPN_V4): """This method gets in-bound filters of the specified neighbor. ``address`` specifies the IP address of the neighbor. ``route_dist`` specifies route distinguisher that has attribute_maps. ...
[ "def", "attribute_map_get", "(", "self", ",", "address", ",", "route_dist", "=", "None", ",", "route_family", "=", "RF_VPN_V4", ")", ":", "if", "route_family", "not", "in", "SUPPORTED_VRF_RF", ":", "raise", "ValueError", "(", "'Unsupported route_family: %s'", "%",...
34.172414
20.655172
def liste_campagnes(self, campagne=None): """ Liste des campagnes de mesure et des stations associées Paramètres: campagne: Si définie, liste des stations que pour cette campagne """ condition = "" if campagne: condition = "WHERE NOM_COURT_CM='%s' "...
[ "def", "liste_campagnes", "(", "self", ",", "campagne", "=", "None", ")", ":", "condition", "=", "\"\"", "if", "campagne", ":", "condition", "=", "\"WHERE NOM_COURT_CM='%s' \"", "\"\"", "%", "campagne", "_sql", "=", "\"\"\"SELECT\n NOM_COURT_CM AS CAMPAGNE,\n ...
30.521739
14.869565