text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def get_key(bytes_, encoding, keynames='curtsies', full=False): """Return key pressed from bytes_ or None Return a key name or None meaning it's an incomplete sequence of bytes (more bytes needed to determine the key pressed) encoding is how the bytes should be translated to unicode - it should ma...
[ "def", "get_key", "(", "bytes_", ",", "encoding", ",", "keynames", "=", "'curtsies'", ",", "full", "=", "False", ")", ":", "if", "not", "all", "(", "isinstance", "(", "c", ",", "type", "(", "b''", ")", ")", "for", "c", "in", "bytes_", ")", ":", "...
46.805195
27.844156
def creep_kill(self, target, timestamp): """ A creep was tragically killed. Need to split this into radiant/dire and neutrals """ self.creep_kill_types[target] += 1 matched = False for k, v in self.creep_types.iteritems(): if target.startswith(k): ...
[ "def", "creep_kill", "(", "self", ",", "target", ",", "timestamp", ")", ":", "self", ".", "creep_kill_types", "[", "target", "]", "+=", "1", "matched", "=", "False", "for", "k", ",", "v", "in", "self", ".", "creep_types", ".", "iteritems", "(", ")", ...
30.8125
15.3125
def embed(contents='', width='100%', height=512, *args, **kwargs): """ Embed geojson.io in an iframe in Jupyter/IPython notebook. Parameters ---------- contents - see make_url() width - string, default '100%' - width of the iframe height - string / int, default 512 - height of the iframe ...
[ "def", "embed", "(", "contents", "=", "''", ",", "width", "=", "'100%'", ",", "height", "=", "512", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "IPython", ".", "display", "import", "HTML", "url", "=", "make_url", "(", "contents", "...
33.333333
19.888889
def create_constant(self, expression, *, verbose=True): """Append a constant to the stored list. Parameters ---------- expression : str Expression for the new constant. verbose : boolean (optional) Toggle talkback. Default is True See...
[ "def", "create_constant", "(", "self", ",", "expression", ",", "*", ",", "verbose", "=", "True", ")", ":", "if", "expression", "in", "self", ".", "constant_expressions", ":", "wt_exceptions", ".", "ObjectExistsWarning", ".", "warn", "(", "expression", ")", "...
34.689655
15
def parse(self, obj): """ Parse the object's properties according to its default types. """ for k, default in obj.__class__.defaults.items(): typ = type(default) if typ is str: continue v = getattr(obj, k) if typ is int: ...
[ "def", "parse", "(", "self", ",", "obj", ")", ":", "for", "k", ",", "default", "in", "obj", ".", "__class__", ".", "defaults", ".", "items", "(", ")", ":", "typ", "=", "type", "(", "default", ")", "if", "typ", "is", "str", ":", "continue", "v", ...
34.933333
12.4
def attempt_squash_merge(pr: PullRequestDetails ) -> Union[bool, CannotAutomergeError]: """ References: https://developer.github.com/v3/pulls/#merge-a-pull-request-merge-button """ url = ("https://api.github.com/repos/{}/{}/pulls/{}/merge" "?access_token={}".f...
[ "def", "attempt_squash_merge", "(", "pr", ":", "PullRequestDetails", ")", "->", "Union", "[", "bool", ",", "CannotAutomergeError", "]", ":", "url", "=", "(", "\"https://api.github.com/repos/{}/{}/pulls/{}/merge\"", "\"?access_token={}\"", ".", "format", "(", "pr", "."...
33.777778
18.222222
def exists(*nictag, **kwargs): ''' Check if nictags exists nictag : string one or more nictags to check verbose : boolean return list of nictags CLI Example: .. code-block:: bash salt '*' nictagadm.exists admin ''' ret = {} if not nictag: return {'...
[ "def", "exists", "(", "*", "nictag", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "}", "if", "not", "nictag", ":", "return", "{", "'Error'", ":", "'Please provide at least one nictag to check.'", "}", "cmd", "=", "'nictagadm exists -l {0}'", ".", "for...
22
21.733333
def t_php_CLOSE_TAG(t): r'[?%]>\r?\n?' t.lexer.lineno += t.value.count("\n") t.lexer.begin('INITIAL') return t
[ "def", "t_php_CLOSE_TAG", "(", "t", ")", ":", "t", ".", "lexer", ".", "lineno", "+=", "t", ".", "value", ".", "count", "(", "\"\\n\"", ")", "t", ".", "lexer", ".", "begin", "(", "'INITIAL'", ")", "return", "t" ]
24.4
16
def validate_pair(ob: Any) -> bool: """ Does the object have length 2? """ try: if len(ob) != 2: log.warning("Unexpected result: {!r}", ob) raise ValueError() except ValueError: return False return True
[ "def", "validate_pair", "(", "ob", ":", "Any", ")", "->", "bool", ":", "try", ":", "if", "len", "(", "ob", ")", "!=", "2", ":", "log", ".", "warning", "(", "\"Unexpected result: {!r}\"", ",", "ob", ")", "raise", "ValueError", "(", ")", "except", "Val...
23.272727
13.272727
def no_crop(im, min_sz=None, interpolation=cv2.INTER_AREA): """ Return a squared resized image """ r,c,*_ = im.shape if min_sz is None: min_sz = min(r,c) return cv2.resize(im, (min_sz, min_sz), interpolation=interpolation)
[ "def", "no_crop", "(", "im", ",", "min_sz", "=", "None", ",", "interpolation", "=", "cv2", ".", "INTER_AREA", ")", ":", "r", ",", "c", ",", "", "*", "_", "=", "im", ".", "shape", "if", "min_sz", "is", "None", ":", "min_sz", "=", "min", "(", "r"...
46.8
14
def filter(self, query: Query): """Return a new filtered query. Use the tree to filter the query and return a new query "filtered". This query can be filtered again using another tree or even a manual filter. To manually filter query see : - https://docs.sqlalch...
[ "def", "filter", "(", "self", ",", "query", ":", "Query", ")", ":", "entity", "=", "query", ".", "column_descriptions", "[", "0", "]", "[", "'type'", "]", "new_query", ",", "filters", "=", "self", ".", "_root", ".", "filter", "(", "query", ",", "enti...
46.833333
20.666667
def shell_comment(c): 'Do not shell-escape raw strings in comments, but do handle line breaks.' return ShellQuoted('# {c}').format(c=ShellQuoted( (raw_shell(c) if isinstance(c, ShellQuoted) else c) .replace('\n', '\n# ') ))
[ "def", "shell_comment", "(", "c", ")", ":", "return", "ShellQuoted", "(", "'# {c}'", ")", ".", "format", "(", "c", "=", "ShellQuoted", "(", "(", "raw_shell", "(", "c", ")", "if", "isinstance", "(", "c", ",", "ShellQuoted", ")", "else", "c", ")", ".",...
41.666667
21.333333
def _ewp_flags_set(self, ewp_dic_subset, project_dic, flag_type, flag_dic): """ Flags from misc to set to ewp project """ try: if flag_type in project_dic['misc'].keys(): # enable commands index_option = self._get_option(ewp_dic_subset, flag_dic['enable']) ...
[ "def", "_ewp_flags_set", "(", "self", ",", "ewp_dic_subset", ",", "project_dic", ",", "flag_type", ",", "flag_dic", ")", ":", "try", ":", "if", "flag_type", "in", "project_dic", "[", "'misc'", "]", ".", "keys", "(", ")", ":", "# enable commands", "index_opti...
50.947368
26.368421
def is_back_tracking(neurite): ''' Check if a neurite process backtracks to a previous node. Back-tracking takes place when a daughter of a branching process goes back and either overlaps with a previous point, or lies inside the cylindrical volume of the latter. Args: neurite(Neurite): neurite...
[ "def", "is_back_tracking", "(", "neurite", ")", ":", "def", "pair", "(", "segs", ")", ":", "''' Pairs the input list into triplets'''", "return", "zip", "(", "segs", ",", "segs", "[", "1", ":", "]", ")", "def", "coords", "(", "node", ")", ":", "''' Returns...
41.113402
25.237113
def set_temperature(self, zone, temperature, until=None): """Sets the temperature of the given zone.""" if until is None: data = {"Value": temperature, "Status": "Hold", "NextTime": None} else: data = {"Value": temperature, "Status": "Temporary", ...
[ "def", "set_temperature", "(", "self", ",", "zone", ",", "temperature", ",", "until", "=", "None", ")", ":", "if", "until", "is", "None", ":", "data", "=", "{", "\"Value\"", ":", "temperature", ",", "\"Status\"", ":", "\"Hold\"", ",", "\"NextTime\"", ":"...
42
17.1
def get_stream_when_active(stream_name, region=None, key=None, keyid=None, profile=None): ''' Get complete stream info from AWS, returning only when the stream is in the ACTIVE state. Continues to retry when stream is updating or creating. If the stream is deleted during retries, the loop will catch the...
[ "def", "get_stream_when_active", "(", "stream_name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ...
42.9
29.033333
def bf(items, targets, **kwargs): """Best-Fit Complexity O(n^2) """ bins = [(target, []) for target in targets] skip = [] for item in items: containers = [] capacities = [] for target, content in bins: capacity = target - sum(content) if item <= ...
[ "def", "bf", "(", "items", ",", "targets", ",", "*", "*", "kwargs", ")", ":", "bins", "=", "[", "(", "target", ",", "[", "]", ")", "for", "target", "in", "targets", "]", "skip", "=", "[", "]", "for", "item", "in", "items", ":", "containers", "=...
27.666667
16.333333
def analyze(self, text): """Return the sentiment as a tuple of the form: ``(polarity, subjectivity)`` :param str text: A string. .. todo:: Figure out best format to be passed to the analyzer. There might be a better format than a string of space separated ...
[ "def", "analyze", "(", "self", ",", "text", ")", ":", "if", "self", ".", "lemmatize", ":", "text", "=", "self", ".", "_lemmatize", "(", "text", ")", "return", "self", ".", "RETURN_TYPE", "(", "*", "pattern_sentiment", "(", "text", ")", ")" ]
37.157895
21.368421
def _parse_source_sections(self, diff_str): """ Given the output of `git diff`, return a dictionary with keys that are source file paths. Each value is a list of lines from the `git diff` output related to the source file. Raises a `GitDiffError` if `diff_str` is in an ...
[ "def", "_parse_source_sections", "(", "self", ",", "diff_str", ")", ":", "# Create a dict to map source files to lines in the diff output", "source_dict", "=", "dict", "(", ")", "# Keep track of the current source file", "src_path", "=", "None", "# Signal that we've found a hunk ...
36.557377
22.229508
def _cmd_create(self): """Create a migration in the current or new revision folder """ assert self._message, "need to supply a message for the \"create\" command" if not self._revisions: self._revisions.append("1") # get the migration folder rev_folder = self...
[ "def", "_cmd_create", "(", "self", ")", ":", "assert", "self", ".", "_message", ",", "\"need to supply a message for the \\\"create\\\" command\"", "if", "not", "self", ".", "_revisions", ":", "self", ".", "_revisions", ".", "append", "(", "\"1\"", ")", "# get the...
44.710526
17.078947
def get_template_substitution_values(self, value): """ Return value-related substitutions. """ return { 'initial': os.path.basename(conditional_escape(value)), 'initial_url': conditional_escape(value.url), }
[ "def", "get_template_substitution_values", "(", "self", ",", "value", ")", ":", "return", "{", "'initial'", ":", "os", ".", "path", ".", "basename", "(", "conditional_escape", "(", "value", ")", ")", ",", "'initial_url'", ":", "conditional_escape", "(", "value...
33
14
def focus_loss(labels, probs, loss, gamma): """ Calculate the alpha balanced focal loss. See the focal loss paper: "Focal Loss for Dense Object Detection" [by Facebook AI Research] :param labels: A float tensor of shape [batch_size, ..., num_classes] representing the label class probabilities. :pa...
[ "def", "focus_loss", "(", "labels", ",", "probs", ",", "loss", ",", "gamma", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"focus_loss\"", ")", ":", "# Compute p_t that is used in paper.", "# FIXME is it possible that the 1-p term does not make any sense?", "p_t",...
55.315789
31.631579
def store_env(path=None): '''Encode current environment as yaml and store in path or a temporary file. Return the path to the stored environment. ''' path = path or get_store_env_tmp() env_dict = yaml.safe_dump(os.environ.data, default_flow_style=False) with open(path, 'w') as f: f.wr...
[ "def", "store_env", "(", "path", "=", "None", ")", ":", "path", "=", "path", "or", "get_store_env_tmp", "(", ")", "env_dict", "=", "yaml", ".", "safe_dump", "(", "os", ".", "environ", ".", "data", ",", "default_flow_style", "=", "False", ")", "with", "...
26
26
def init_loopback(self, data): """Just initialize the object for our Pseudo Loopback""" self.name = data["name"] self.description = data['description'] self.win_index = data['win_index'] self.mac = data["mac"] self.guid = data["guid"] self.ip = "127.0.0.1"
[ "def", "init_loopback", "(", "self", ",", "data", ")", ":", "self", ".", "name", "=", "data", "[", "\"name\"", "]", "self", ".", "description", "=", "data", "[", "'description'", "]", "self", ".", "win_index", "=", "data", "[", "'win_index'", "]", "sel...
38.125
6.875
def get_next(self, tag="<"): """ This function is tricky and took me a while to figure out. The tag specifies the direction where the current edge came from. tag ntag ---> V >----> U cur next This means the next vertex should follow the outs sinc...
[ "def", "get_next", "(", "self", ",", "tag", "=", "\"<\"", ")", ":", "next", ",", "ntag", "=", "None", ",", "None", "L", "=", "self", ".", "outs", "if", "tag", "==", "\"<\"", "else", "self", ".", "ins", "if", "len", "(", "L", ")", "==", "1", "...
30.757576
21.545455
def decode(self, code, terminator='\0'): r"""Return a word decoded from BWT form. Parameters ---------- code : str The word to transform from BWT form terminator : str A character added to signal the end of the string Returns ------- ...
[ "def", "decode", "(", "self", ",", "code", ",", "terminator", "=", "'\\0'", ")", ":", "if", "code", ":", "if", "terminator", "not", "in", "code", ":", "raise", "ValueError", "(", "'Specified terminator, {}, absent from code.'", ".", "format", "(", "terminator"...
27.3125
19.333333
def new_logger(name): '''Return new logger which will log both to logstash and to file in JSON format. Log files are stored in <logdir>/name.json ''' log = get_task_logger(name) handler = logstash.LogstashHandler( config.logstash.host, config.logstash.port) log.addHandler(handler)...
[ "def", "new_logger", "(", "name", ")", ":", "log", "=", "get_task_logger", "(", "name", ")", "handler", "=", "logstash", ".", "LogstashHandler", "(", "config", ".", "logstash", ".", "host", ",", "config", ".", "logstash", ".", "port", ")", "log", ".", ...
24.956522
20.26087
def leaves(self, prefix=None): """ LIKE items() BUT RECURSIVE, AND ONLY FOR THE LEAVES (non dict) VALUES """ prefix = coalesce(prefix, "") output = [] for k, v in self.items(): if _get(v, CLASS) in data_types: output.extend(wrap(v).leaves(prefi...
[ "def", "leaves", "(", "self", ",", "prefix", "=", "None", ")", ":", "prefix", "=", "coalesce", "(", "prefix", ",", "\"\"", ")", "output", "=", "[", "]", "for", "k", ",", "v", "in", "self", ".", "items", "(", ")", ":", "if", "_get", "(", "v", ...
37.166667
15.833333
def update_counter(self, key, value, **kwargs): """ Updates the value of a counter stored in this bucket. Positive values increment the counter, negative values decrement. See :meth:`RiakClient.update_counter() <riak.client.RiakClient.update_counter>` for options. .. dep...
[ "def", "update_counter", "(", "self", ",", "key", ",", "value", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_client", ".", "update_counter", "(", "self", ",", "key", ",", "value", ",", "*", "*", "kwargs", ")" ]
40.647059
19
def create_ambiente(self): """Get an instance of ambiente services facade.""" return Ambiente( self.networkapi_url, self.user, self.password, self.user_ldap)
[ "def", "create_ambiente", "(", "self", ")", ":", "return", "Ambiente", "(", "self", ".", "networkapi_url", ",", "self", ".", "user", ",", "self", ".", "password", ",", "self", ".", "user_ldap", ")" ]
30.714286
11.857143
def strike(channel, nick, rest): "Strike last <n> statements from the record" yield NoLog rest = rest.strip() if not rest: count = 1 else: if not rest.isdigit(): yield "Strike how many? Argument must be a positive integer." raise StopIteration count = int(rest) try: struck = Logger.store.strike(cha...
[ "def", "strike", "(", "channel", ",", "nick", ",", "rest", ")", ":", "yield", "NoLog", "rest", "=", "rest", ".", "strip", "(", ")", "if", "not", "rest", ":", "count", "=", "1", "else", ":", "if", "not", "rest", ".", "isdigit", "(", ")", ":", "y...
27.571429
20.142857
def raw_cap(self, refresh=False): """ Raw xml(cap) of the the feed. If a valid cache is available it is used, else a new copy of the feed is grabbed Note: you can force refresh here, if you do, don't also manually call refresh """ if refresh is True: self._raw...
[ "def", "raw_cap", "(", "self", ",", "refresh", "=", "False", ")", ":", "if", "refresh", "is", "True", ":", "self", ".", "_raw", "=", "self", ".", "refresh", "(", ")", "if", "self", ".", "_raw", "is", "None", ":", "self", ".", "_raw", "=", "self",...
38.153846
12.153846
def event_transition(self, event_cls, event_type, ion_type, value): """Returns an ion event event_transition that yields to another co-routine.""" annotations = self.annotations or () depth = self.depth whence = self.whence if ion_type is IonType.SYMBOL: if not annot...
[ "def", "event_transition", "(", "self", ",", "event_cls", ",", "event_type", ",", "ion_type", ",", "value", ")", ":", "annotations", "=", "self", ".", "annotations", "or", "(", ")", "depth", "=", "self", ".", "depth", "whence", "=", "self", ".", "whence"...
42.666667
20.333333
def generate_make_string(out_f, max_step): """Generate the make_string template""" steps = [2 ** n for n in xrange(int(math.log(max_step, 2)), -1, -1)] with Namespace( out_f, ['boost', 'metaparse', 'v{0}'.format(VERSION), 'impl'] ) as nsp: generate_take(out_f, steps, nsp.prefix(...
[ "def", "generate_make_string", "(", "out_f", ",", "max_step", ")", ":", "steps", "=", "[", "2", "**", "n", "for", "n", "in", "xrange", "(", "int", "(", "math", ".", "log", "(", "max_step", ",", "2", ")", ")", ",", "-", "1", ",", "-", "1", ")", ...
36.75
18.525
def _tf_squared_euclidean(X, Y): """Squared Euclidean distance between the rows of `X` and `Y`. """ return tf.reduce_sum(tf.pow(tf.subtract(X, Y), 2), axis=1)
[ "def", "_tf_squared_euclidean", "(", "X", ",", "Y", ")", ":", "return", "tf", ".", "reduce_sum", "(", "tf", ".", "pow", "(", "tf", ".", "subtract", "(", "X", ",", "Y", ")", ",", "2", ")", ",", "axis", "=", "1", ")" ]
44.75
8.5
def service_group_exists(name, groupname=None, vsys=1, members=None, description=None, commit=False): ''' Ensures that a service group object exists in the configured state. If it does no...
[ "def", "service_group_exists", "(", "name", ",", "groupname", "=", "None", ",", "vsys", "=", "1", ",", "members", "=", "None", ",", "description", "=", "None", ",", "commit", "=", "False", ")", ":", "ret", "=", "_default_ret", "(", "name", ")", "if", ...
34.567308
28.759615
def phenotypes(institute_id, case_name, phenotype_id=None): """Handle phenotypes.""" institute_obj, case_obj = institute_and_case(store, institute_id, case_name) case_url = url_for('.case', institute_id=institute_id, case_name=case_name) is_group = request.args.get('is_group') == 'yes' user_obj = st...
[ "def", "phenotypes", "(", "institute_id", ",", "case_name", ",", "phenotype_id", "=", "None", ")", ":", "institute_obj", ",", "case_obj", "=", "institute_and_case", "(", "store", ",", "institute_id", ",", "case_name", ")", "case_url", "=", "url_for", "(", "'.c...
49.961538
23.884615
def use_model(self, model_name): """ Decide whether to use a model, based on the model name and the lists of models to exclude and include. """ # Check against exclude list. if self.exclude_models: for model_pattern in self.exclude_models: mode...
[ "def", "use_model", "(", "self", ",", "model_name", ")", ":", "# Check against exclude list.", "if", "self", ".", "exclude_models", ":", "for", "model_pattern", "in", "self", ".", "exclude_models", ":", "model_pattern", "=", "'^%s$'", "%", "model_pattern", ".", ...
44.947368
13.368421
def scenario_risk(riskinputs, riskmodel, param, monitor): """ Core function for a scenario computation. :param riskinput: a of :class:`openquake.risklib.riskinput.RiskInput` object :param riskmodel: a :class:`openquake.risklib.riskinput.CompositeRiskModel` instance :param param: ...
[ "def", "scenario_risk", "(", "riskinputs", ",", "riskmodel", ",", "param", ",", "monitor", ")", ":", "E", "=", "param", "[", "'E'", "]", "L", "=", "len", "(", "riskmodel", ".", "loss_types", ")", "result", "=", "dict", "(", "agg", "=", "numpy", ".", ...
44.911111
19.533333
def add_context(self, context, label=None): """Append `context` to model Arguments: context (dict): Serialised to add Schema: context.json """ assert isinstance(context, dict) item = defaults["common"].copy() item.update(defaults["inst...
[ "def", "add_context", "(", "self", ",", "context", ",", "label", "=", "None", ")", ":", "assert", "isinstance", "(", "context", ",", "dict", ")", "item", "=", "defaults", "[", "\"common\"", "]", ".", "copy", "(", ")", "item", ".", "update", "(", "def...
25.115385
17.153846
def dict(cls): """ Return a dict containing all of the configuration properties :returns: (dict) containing all configuration properties. """ if cls._properties is None: cls._readStdConfigFiles() # Make a copy so we can update any current values obtained from environment # variables ...
[ "def", "dict", "(", "cls", ")", ":", "if", "cls", ".", "_properties", "is", "None", ":", "cls", ".", "_readStdConfigFiles", "(", ")", "# Make a copy so we can update any current values obtained from environment", "# variables", "result", "=", "dict", "(", "cls", "....
29.857143
18.47619
def bp_to_aap (bp): """Converts a basepol into a tuple of (ant1, ant2, pol).""" ap1, ap2 = bp if ap1 < 0: raise ValueError ('first antpol %d is negative' % ap1) if ap2 < 0: raise ValueError ('second antpol %d is negative' % ap2) pol = _fpol_to_pol[((ap1 & 0x7) << 4) + (ap2 & 0x7)] ...
[ "def", "bp_to_aap", "(", "bp", ")", ":", "ap1", ",", "ap2", "=", "bp", "if", "ap1", "<", "0", ":", "raise", "ValueError", "(", "'first antpol %d is negative'", "%", "ap1", ")", "if", "ap2", "<", "0", ":", "raise", "ValueError", "(", "'second antpol %d is...
34.25
22.9375
def prepare_refresh_token_request(self, token_url, refresh_token=None, body='', scope=None, **kwargs): """Prepare an access token refresh request. Expired access tokens can be replaced by new access tokens without going through the OAuth dance if the client...
[ "def", "prepare_refresh_token_request", "(", "self", ",", "token_url", ",", "refresh_token", "=", "None", ",", "body", "=", "''", ",", "scope", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "is_secure_transport", "(", "token_url", ")", ":", ...
44.322581
27.225806
def make_repository_component(self): """Return an XML string representing this BMI in a workflow. This description is required by EMELI to discover and load models. Returns ------- xml : str String serialized XML representation of the component in the mo...
[ "def", "make_repository_component", "(", "self", ")", ":", "component", "=", "etree", ".", "Element", "(", "'component'", ")", "comp_name", "=", "etree", ".", "Element", "(", "'comp_name'", ")", "comp_name", ".", "text", "=", "self", ".", "model", ".", "na...
30.982143
16.964286
def create_new_folder(self, current_path, title, subtitle, is_package): """Create new folder""" if current_path is None: current_path = '' if osp.isfile(current_path): current_path = osp.dirname(current_path) name, valid = QInputDialog.getText(self, title, s...
[ "def", "create_new_folder", "(", "self", ",", "current_path", ",", "title", ",", "subtitle", ",", "is_package", ")", ":", "if", "current_path", "is", "None", ":", "current_path", "=", "''", "if", "osp", ".", "isfile", "(", "current_path", ")", ":", "curren...
51.3125
18.75
def uci(self, move: Move, *, chess960: Optional[bool] = None) -> str: """ Gets the UCI notation of the move. *chess960* defaults to the mode of the board. Pass ``True`` to force Chess960 mode. """ if chess960 is None: chess960 = self.chess960 move = ...
[ "def", "uci", "(", "self", ",", "move", ":", "Move", ",", "*", ",", "chess960", ":", "Optional", "[", "bool", "]", "=", "None", ")", "->", "str", ":", "if", "chess960", "is", "None", ":", "chess960", "=", "self", ".", "chess960", "move", "=", "se...
35.615385
20.230769
def _get_timethresh_heuristics(self): """ resonably decent hueristics for how much time to wait before updating progress. """ if self.length > 1E5: time_thresh = 2.5 elif self.length > 1E4: time_thresh = 2.0 elif self.length > 1E3: ...
[ "def", "_get_timethresh_heuristics", "(", "self", ")", ":", "if", "self", ".", "length", ">", "1E5", ":", "time_thresh", "=", "2.5", "elif", "self", ".", "length", ">", "1E4", ":", "time_thresh", "=", "2.0", "elif", "self", ".", "length", ">", "1E3", "...
28.5
11.357143
def precompute(self, cache_dir=None, swath_usage=0, **kwargs): """Generate row and column arrays and store it for later use.""" if kwargs.get('mask') is not None: LOG.warning("'mask' parameter has no affect during EWA " "resampling") del kwargs source...
[ "def", "precompute", "(", "self", ",", "cache_dir", "=", "None", ",", "swath_usage", "=", "0", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ".", "get", "(", "'mask'", ")", "is", "not", "None", ":", "LOG", ".", "warning", "(", "\"'mask' paramete...
36.305556
19.194444
def key_exists_in_list_or_dict(key, lst_or_dct): """True if `lst_or_dct[key]` does not raise an Exception""" if isinstance(lst_or_dct, dict) and key in lst_or_dct: return True elif isinstance(lst_or_dct, list): min_i, max_i = 0, len(lst_or_dct) if min_i <= key < max_i: re...
[ "def", "key_exists_in_list_or_dict", "(", "key", ",", "lst_or_dct", ")", ":", "if", "isinstance", "(", "lst_or_dct", ",", "dict", ")", "and", "key", "in", "lst_or_dct", ":", "return", "True", "elif", "isinstance", "(", "lst_or_dct", ",", "list", ")", ":", ...
37.555556
11
def sum_layout_dimensions(dimensions): """ Sum a list of :class:`.LayoutDimension` instances. """ min = sum([d.min for d in dimensions if d.min is not None]) max = sum([d.max for d in dimensions if d.max is not None]) preferred = sum([d.preferred for d in dimensions]) return LayoutDimension...
[ "def", "sum_layout_dimensions", "(", "dimensions", ")", ":", "min", "=", "sum", "(", "[", "d", ".", "min", "for", "d", "in", "dimensions", "if", "d", ".", "min", "is", "not", "None", "]", ")", "max", "=", "sum", "(", "[", "d", ".", "max", "for", ...
39
15.666667
def read(fname, encoding='utf8', strip_comments=False, **kw): """ Load a list of trees from a Newick formatted file. :param fname: file path. :param strip_comments: Flag signaling whether to strip comments enclosed in square \ brackets. :param kw: Keyword arguments are passed through to `Node.c...
[ "def", "read", "(", "fname", ",", "encoding", "=", "'utf8'", ",", "strip_comments", "=", "False", ",", "*", "*", "kw", ")", ":", "kw", "[", "'strip_comments'", "]", "=", "strip_comments", "with", "io", ".", "open", "(", "fname", ",", "encoding", "=", ...
36.923077
16.769231
def get_conversation_between(self, um_from_user, um_to_user): """ Returns a conversation between two users """ messages = self.filter(Q(sender=um_from_user, recipients=um_to_user, sender_deleted_at__isnull=True) | Q(sender=um_to_user, recip...
[ "def", "get_conversation_between", "(", "self", ",", "um_from_user", ",", "um_to_user", ")", ":", "messages", "=", "self", ".", "filter", "(", "Q", "(", "sender", "=", "um_from_user", ",", "recipients", "=", "um_to_user", ",", "sender_deleted_at__isnull", "=", ...
62
24.571429
def alphabetical_formula(self): """ Returns a reduced formula string with appended charge """ alph_formula = super().alphabetical_formula chg_str = "" if self.charge > 0: chg_str = " +" + formula_double_format(self.charge, False) elif self.charge < 0: ...
[ "def", "alphabetical_formula", "(", "self", ")", ":", "alph_formula", "=", "super", "(", ")", ".", "alphabetical_formula", "chg_str", "=", "\"\"", "if", "self", ".", "charge", ">", "0", ":", "chg_str", "=", "\" +\"", "+", "formula_double_format", "(", "self"...
37.909091
13.363636
def _inhibitColumnsWithLateral(self, overlaps, lateralConnections): """ Performs an experimentatl local inhibition. Local inhibition is iteratively performed on a column by column basis. """ n,m = self.shape y = np.zeros(n) s = self.sparsity L = lateralConnections desiredWeigh...
[ "def", "_inhibitColumnsWithLateral", "(", "self", ",", "overlaps", ",", "lateralConnections", ")", ":", "n", ",", "m", "=", "self", ".", "shape", "y", "=", "np", ".", "zeros", "(", "n", ")", "s", "=", "self", ".", "sparsity", "L", "=", "lateralConnecti...
26.25
19.9375
def siblings(self, **kwargs): # type: (Any) -> Any """Retrieve the siblings of this `Part` as `Partset`. Siblings are other Parts sharing the same parent of this `Part`, including the part itself. :param kwargs: Additional search arguments to search for, check :class:`pykechain.Client....
[ "def", "siblings", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# type: (Any) -> Any", "if", "self", ".", "parent_id", ":", "return", "self", ".", "_client", ".", "parts", "(", "parent", "=", "self", ".", "parent_id", ",", "category", "=", "self", ...
44.529412
24.058824
def reduce_lists(d): """Replace single item lists in a dictionary with the single item.""" for field in d: old_data = d[field] if len(old_data) == 1: d[field] = old_data[0]
[ "def", "reduce_lists", "(", "d", ")", ":", "for", "field", "in", "d", ":", "old_data", "=", "d", "[", "field", "]", "if", "len", "(", "old_data", ")", "==", "1", ":", "d", "[", "field", "]", "=", "old_data", "[", "0", "]" ]
33.833333
11.666667
def _cursor_position(self, data): """ Moves the cursor position. """ column, line = self._get_line_and_col(data) self._move_cursor_to_line(line) self._move_cursor_to_column(column) self._last_cursor_pos = self._cursor.position()
[ "def", "_cursor_position", "(", "self", ",", "data", ")", ":", "column", ",", "line", "=", "self", ".", "_get_line_and_col", "(", "data", ")", "self", ".", "_move_cursor_to_line", "(", "line", ")", "self", ".", "_move_cursor_to_column", "(", "column", ")", ...
34.625
5.375
def _replace_numeric_markers(operation, string_parameters): """ Replaces qname, format, and numeric markers in the given operation, from the string_parameters list. Raises ProgrammingError on wrong number of parameters or bindings when using qmark. There is no error checking on numeric parameters. ...
[ "def", "_replace_numeric_markers", "(", "operation", ",", "string_parameters", ")", ":", "def", "replace_markers", "(", "marker", ",", "op", ",", "parameters", ")", ":", "param_count", "=", "len", "(", "parameters", ")", "marker_index", "=", "0", "start_offset",...
47.204545
22.386364
def _request(self, method, uri_relative, request_bytes, params, custom_headers): """ :type method: str :type uri_relative: str :type request_bytes: bytes :type params: dict[str, str] :type custom_headers: dict[str, str] :return: BunqResponseRaw ...
[ "def", "_request", "(", "self", ",", "method", ",", "uri_relative", ",", "request_bytes", ",", "params", ",", "custom_headers", ")", ":", "uri_relative_with_params", "=", "self", ".", "_append_params_to_uri", "(", "uri_relative", ",", "params", ")", "if", "uri_r...
33.130435
19.217391
def vector_to_rgb(image): """ Convert an Vector ANTsImage to a RGB ANTsImage Arguments --------- image : ANTsImage RGB image to be converted Returns ------- ANTsImage Example ------- >>> import ants >>> img = ants.image_read(ants.get_data('r16'), pixeltype='uns...
[ "def", "vector_to_rgb", "(", "image", ")", ":", "if", "image", ".", "pixeltype", "!=", "'unsigned char'", ":", "image", "=", "image", ".", "clone", "(", "'unsigned char'", ")", "idim", "=", "image", ".", "dimension", "libfn", "=", "utils", ".", "get_lib_fn...
28.275862
19.586207
def mat2euler(rmat, axes="sxyz"): """ Converts given rotation matrix to euler angles in radian. Args: rmat: 3x3 rotation matrix axes: One of 24 axis sequences as string or encoded tuple Returns: converted euler angles in radian vec3 float """ try: firstaxis, par...
[ "def", "mat2euler", "(", "rmat", ",", "axes", "=", "\"sxyz\"", ")", ":", "try", ":", "firstaxis", ",", "parity", ",", "repetition", ",", "frame", "=", "_AXES2TUPLE", "[", "axes", ".", "lower", "(", ")", "]", "except", "(", "AttributeError", ",", "KeyEr...
29.574468
17.404255
def _decrypt_asymmetric( self, decryption_algorithm, decryption_key, cipher_text, padding_method, hashing_algorithm=None): """ Encrypt data using asymmetric decryption. Args: decryption_algorithm (CryptographicA...
[ "def", "_decrypt_asymmetric", "(", "self", ",", "decryption_algorithm", ",", "decryption_key", ",", "cipher_text", ",", "padding_method", ",", "hashing_algorithm", "=", "None", ")", ":", "if", "decryption_algorithm", "==", "enums", ".", "CryptographicAlgorithm", ".", ...
40.05618
19.808989
def custom(self, code, message): """ Specific server side errors use: -32000 to -32099 reserved for implementation-defined server-errors """ if -32000 < code or -32099 > code: code = -32603 message = 'Internal error' return JResponse(jsonrpc={ ...
[ "def", "custom", "(", "self", ",", "code", ",", "message", ")", ":", "if", "-", "32000", "<", "code", "or", "-", "32099", ">", "code", ":", "code", "=", "-", "32603", "message", "=", "'Internal error'", "return", "JResponse", "(", "jsonrpc", "=", "{"...
33.333333
10.5
def main(): """ Do the things! Return: 0 Exceptions: """ description = 'Letter - a commandline interface' parser = argparse.ArgumentParser(description=description) parser.add_argument('--gmail', action='store_true', help='Send via Gmail', ) args = parser.parse_args() to ...
[ "def", "main", "(", ")", ":", "description", "=", "'Letter - a commandline interface'", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "description", ")", "parser", ".", "add_argument", "(", "'--gmail'", ",", "action", "=", "'store_true...
25
21.114286
def level(self, img, level): """Get image level. Parameters ---------- img : `PIL.Image` Input image. level : `int` Level number. Returns ------- `PIL.Image` Converted image. """ if level < self.levels ...
[ "def", "level", "(", "self", ",", "img", ",", "level", ")", ":", "if", "level", "<", "self", ".", "levels", "-", "1", ":", "width", ",", "height", "=", "img", ".", "size", "scale", "=", "reduce", "(", "lambda", "x", ",", "y", ":", "x", "*", "...
26.47619
18.47619
def load(filename, relative_to_module=None, compound=None, coords_only=False, rigid=False, use_parmed=False, smiles=False, **kwargs): """Load a file into an mbuild compound. Files are read using the MDTraj package unless the `use_parmed` argument is specified as True. Please refer to http://mdtraj...
[ "def", "load", "(", "filename", ",", "relative_to_module", "=", "None", ",", "compound", "=", "None", ",", "coords_only", "=", "False", ",", "rigid", "=", "False", ",", "use_parmed", "=", "False", ",", "smiles", "=", "False", ",", "*", "*", "kwargs", "...
42.216981
21.311321
def set_flair_csv(self, subreddit, flair_mapping): """Set flair for a group of users in the given subreddit. flair_mapping should be a list of dictionaries with the following keys: `user`: the user name, `flair_text`: the flair text for the user (optional), `flair_css_clas...
[ "def", "set_flair_csv", "(", "self", ",", "subreddit", ",", "flair_mapping", ")", ":", "if", "not", "flair_mapping", ":", "raise", "errors", ".", "ClientException", "(", "'flair_mapping must be set'", ")", "item_order", "=", "[", "'user'", ",", "'flair_text'", "...
43.129032
18.870968
def __create_map(self, map_size): ''' Create map. References: - https://qiita.com/kusano_t/items/487eec15d42aace7d685 ''' import random import numpy as np from itertools import product news = ['n', 'e', 'w', 's'] m, n = map_s...
[ "def", "__create_map", "(", "self", ",", "map_size", ")", ":", "import", "random", "import", "numpy", "as", "np", "from", "itertools", "import", "product", "news", "=", "[", "'n'", ",", "'e'", ",", "'w'", ",", "'s'", "]", "m", ",", "n", "=", "map_siz...
27.828125
18.671875
def add_optional_parameters(detail_json, detail, rating, rating_n, popularity, current_popularity, time_spent): """ check for optional return parameters and add them to the result json :param detail_json: :param detail: :param rating: :param rating_n: :param popularity: :param current_po...
[ "def", "add_optional_parameters", "(", "detail_json", ",", "detail", ",", "rating", ",", "rating_n", ",", "popularity", ",", "current_popularity", ",", "time_spent", ")", ":", "if", "rating", "is", "not", "None", ":", "detail_json", "[", "\"rating\"", "]", "="...
29.567568
21.351351
def autocomplete_view(self, request): """ Searches in the fields of the given related model and returns the result as a simple string to be used by the jQuery Autocomplete plugin """ query = request.GET.get('q', None) app_label = request.GET.get('app_label', None) ...
[ "def", "autocomplete_view", "(", "self", ",", "request", ")", ":", "query", "=", "request", ".", "GET", ".", "get", "(", "'q'", ",", "None", ")", "app_label", "=", "request", ".", "GET", ".", "get", "(", "'app_label'", ",", "None", ")", "model_name", ...
40.870968
18.483871
def can_access_objective_hierarchy(self): """Tests if this user can perform hierarchy queries. A return of true does not guarantee successful authorization. A return of false indicates that it is known all methods in this session will result in a PermissionDenied. This is intended as a ...
[ "def", "can_access_objective_hierarchy", "(", "self", ")", ":", "url_path", "=", "construct_url", "(", "'authorization'", ",", "bank_id", "=", "self", ".", "_catalog_idstr", ")", "return", "self", ".", "_get_request", "(", "url_path", ")", "[", "'objectiveHierarch...
47.411765
23.235294
def analyze_one_classification_result(storage_client, file_path, adv_batch, dataset_batches, dataset_meta): """Reads and analyzes one classification result. This method reads file with classification result and counts how many images wer...
[ "def", "analyze_one_classification_result", "(", "storage_client", ",", "file_path", ",", "adv_batch", ",", "dataset_batches", ",", "dataset_meta", ")", ":", "class_result", "=", "read_classification_results", "(", "storage_client", ",", "file_path", ")", "if", "class_r...
38.282609
18.869565
def _clean_item(self, item): ''' Cleans the item to be logged ''' item_copy = dict(item) del item_copy['body'] del item_copy['links'] del item_copy['response_headers'] del item_copy['request_headers'] del item_copy['status_code'] del item_c...
[ "def", "_clean_item", "(", "self", ",", "item", ")", ":", "item_copy", "=", "dict", "(", "item", ")", "del", "item_copy", "[", "'body'", "]", "del", "item_copy", "[", "'links'", "]", "del", "item_copy", "[", "'response_headers'", "]", "del", "item_copy", ...
28.0625
12.8125
def _geom_type(self, source): """gets geometry type(s) of specified layer""" if isinstance(source, AbstractLayer): query = source.orig_query else: query = 'SELECT * FROM "{table}"'.format(table=source) resp = self.sql_client.send( utils.minify_sql(( ...
[ "def", "_geom_type", "(", "self", ",", "source", ")", ":", "if", "isinstance", "(", "source", ",", "AbstractLayer", ")", ":", "query", "=", "source", ".", "orig_query", "else", ":", "query", "=", "'SELECT * FROM \"{table}\"'", ".", "format", "(", "table", ...
48.527778
14.75
def kill_child_processes() -> None: """ Kills children of this process that were registered in the :data:`processes` variable. Use with ``@atexit.register``. """ timeout_sec = 5 for p in processes: try: p.wait(timeout_sec) except TimeoutExpired: # fai...
[ "def", "kill_child_processes", "(", ")", "->", "None", ":", "timeout_sec", "=", "5", "for", "p", "in", "processes", ":", "try", ":", "p", ".", "wait", "(", "timeout_sec", ")", "except", "TimeoutExpired", ":", "# failed to close", "p", ".", "kill", "(", "...
24.285714
14.142857
def FilePattern(pattern, settings, **kwargs): """Factory method returns LocalFilePattern or GoogleStorageFilePattern """ url = _urlparse(pattern) if url.scheme == 'gs': return GoogleStorageFilePattern(pattern, settings, **kwargs) else: assert url.scheme == 'file' return Local...
[ "def", "FilePattern", "(", "pattern", ",", "settings", ",", "*", "*", "kwargs", ")", ":", "url", "=", "_urlparse", "(", "pattern", ")", "if", "url", ".", "scheme", "==", "'gs'", ":", "return", "GoogleStorageFilePattern", "(", "pattern", ",", "settings", ...
39.111111
12.777778
def _grains(): ''' Helper function to the grains from the proxied devices. ''' client = _get_client() # This is a collection of the configuration of all running devices under NSO ret = client.get_datastore(DatastoreType.RUNNING) GRAINS_CACHE.update(ret) return GRAINS_CACHE
[ "def", "_grains", "(", ")", ":", "client", "=", "_get_client", "(", ")", "# This is a collection of the configuration of all running devices under NSO", "ret", "=", "client", ".", "get_datastore", "(", "DatastoreType", ".", "RUNNING", ")", "GRAINS_CACHE", ".", "update",...
33
23
def SAR(cpu, dest, src): """ Shift arithmetic right. The shift arithmetic right (SAR) and shift logical right (SHR) instructions shift the bits of the destination operand to the right (toward less significant bit locations). For each shift count, the least significant bit of the destina...
[ "def", "SAR", "(", "cpu", ",", "dest", ",", "src", ")", ":", "OperandSize", "=", "dest", ".", "size", "countMask", "=", "{", "8", ":", "0x1f", ",", "16", ":", "0x1f", ",", "32", ":", "0x1f", ",", "64", ":", "0x3f", "}", "[", "OperandSize", "]",...
53.583333
34.958333
def as_tag(self, tag_func): """ Creates a tag expecting the format: ``{% tag_name as var_name %}`` The decorated func returns the value that is given to ``var_name`` in the template. """ @wraps(tag_func) def tag_wrapper(parser, token): class As...
[ "def", "as_tag", "(", "self", ",", "tag_func", ")", ":", "@", "wraps", "(", "tag_func", ")", "def", "tag_wrapper", "(", "parser", ",", "token", ")", ":", "class", "AsTagNode", "(", "template", ".", "Node", ")", ":", "def", "render", "(", "self", ",",...
41.483871
11.032258
def _fetch(self, endpoint_name, **params): """ Wrapper for making an api request from giphy """ params['api_key'] = self.api_key resp = requests.get(self._endpoint(endpoint_name), params=params) resp.raise_for_status() data = resp.json() self._check_or_r...
[ "def", "_fetch", "(", "self", ",", "endpoint_name", ",", "*", "*", "params", ")", ":", "params", "[", "'api_key'", "]", "=", "self", ".", "api_key", "resp", "=", "requests", ".", "get", "(", "self", ".", "_endpoint", "(", "endpoint_name", ")", ",", "...
27.307692
17
def write_zarr( self, store: Union[MutableMapping, PathLike], chunks: Union[bool, int, Tuple[int, ...]], ): """Write a hierarchical Zarr array store. Parameters ---------- store The filename, a :class:`~typing.MutableMapping`, or a Zarr storage cl...
[ "def", "write_zarr", "(", "self", ",", "store", ":", "Union", "[", "MutableMapping", ",", "PathLike", "]", ",", "chunks", ":", "Union", "[", "bool", ",", "int", ",", "Tuple", "[", "int", ",", "...", "]", "]", ",", ")", ":", "from", ".", "readwrite"...
28.5
19.625
def execute(self, eopatch): """ Execute function which adds new vector layer to the EOPatch :param eopatch: input EOPatch :type eopatch: EOPatch :return: New EOPatch with added vector layer :rtype: EOPatch """ for raster_ft, raster_fn, vector_fn in self.feature_g...
[ "def", "execute", "(", "self", ",", "eopatch", ")", ":", "for", "raster_ft", ",", "raster_fn", ",", "vector_fn", "in", "self", ".", "feature_gen", "(", "eopatch", ")", ":", "vector_ft", "=", "FeatureType", ".", "VECTOR_TIMELESS", "if", "raster_ft", ".", "i...
44.75
30.4375
def from_query_string(cls, schema, qs=None): """ Extract a page from the current query string. :param qs: a query string dictionary (`request.args` will be used if omitted) """ dct = load_query_string_data(schema, qs) return cls.from_dict(dct)
[ "def", "from_query_string", "(", "cls", ",", "schema", ",", "qs", "=", "None", ")", ":", "dct", "=", "load_query_string_data", "(", "schema", ",", "qs", ")", "return", "cls", ".", "from_dict", "(", "dct", ")" ]
31.666667
17.444444
def area_of_polygon(polygon): """ Returns the area of an OpenQuake polygon in square kilometres """ lon0 = np.mean(polygon.lons) lat0 = np.mean(polygon.lats) # Transform to lamber equal area projection x, y = lonlat_to_laea(polygon.lons, polygon.lats, lon0, lat0) # Build shapely polygons...
[ "def", "area_of_polygon", "(", "polygon", ")", ":", "lon0", "=", "np", ".", "mean", "(", "polygon", ".", "lons", ")", "lat0", "=", "np", ".", "mean", "(", "polygon", ".", "lats", ")", "# Transform to lamber equal area projection", "x", ",", "y", "=", "lo...
33.636364
10.727273
def NDLimitExceeded_originator_switch_info_switchVcsId(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") NDLimitExceeded = ET.SubElement(config, "NDLimitExceeded", xmlns="http://brocade.com/ns/brocade-notification-stream") originator_switch_info = ET.SubEl...
[ "def", "NDLimitExceeded_originator_switch_info_switchVcsId", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "NDLimitExceeded", "=", "ET", ".", "SubElement", "(", "config", ",", "\"NDLimitExceeded\"", ...
52.454545
25.454545
def format_pattrs(pattrs: List['api.PrettyAttribute']) -> str: """Generates repr string given a list of pattrs.""" output = [] pattrs.sort( key=lambda x: ( _FORMATTER[x.display_group].display_index, x.display_group, x.name, ) ) for display_group, g...
[ "def", "format_pattrs", "(", "pattrs", ":", "List", "[", "'api.PrettyAttribute'", "]", ")", "->", "str", ":", "output", "=", "[", "]", "pattrs", ".", "sort", "(", "key", "=", "lambda", "x", ":", "(", "_FORMATTER", "[", "x", ".", "display_group", "]", ...
31.6875
24
def path_components(path): """ Return the individual components of a given file path string (for the local operating system). Taken from https://stackoverflow.com/q/21498939/438386 """ components = [] # The loop guarantees that the returned components can be # os.path.joined wi...
[ "def", "path_components", "(", "path", ")", ":", "components", "=", "[", "]", "# The loop guarantees that the returned components can be\r", "# os.path.joined with the path separator and point to the same\r", "# location: \r", "while", "True", ":", "(", "new_path", ",", "tai...
36.4
17.3
def flip_ctrlpts_u(ctrlpts, size_u, size_v): """ Flips a list of 1-dimensional control points from u-row order to v-row order. **u-row order**: each row corresponds to a list of u values **v-row order**: each row corresponds to a list of v values :param ctrlpts: control points in u-row order :typ...
[ "def", "flip_ctrlpts_u", "(", "ctrlpts", ",", "size_u", ",", "size_v", ")", ":", "new_ctrlpts", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "size_u", ")", ":", "for", "j", "in", "range", "(", "0", ",", "size_v", ")", ":", "temp", "="...
31.434783
16.478261
def extract_runscript(self): '''extract the runscript (EntryPoint) as first priority, unless the user has specified to use the CMD. If Entrypoint is not defined, we default to None: 1. IF SREGISTRY_DOCKERHUB_CMD is set, use Cmd 2. If not set, or Cmd is None/blank, try Entrypoint ...
[ "def", "extract_runscript", "(", "self", ")", ":", "use_cmd", "=", "self", ".", "_get_setting", "(", "'SREGISTRY_DOCKER_CMD'", ")", "# Does the user want to use the CMD instead of ENTRYPOINT?", "commands", "=", "[", "\"Entrypoint\"", ",", "\"Cmd\"", "]", "if", "use_cmd"...
31.390244
21.097561
def diskusage(human_readable=False, path=None): ''' .. versionadded:: 2015.8.0 Return the disk usage for this minion human_readable : False If ``True``, usage will be in KB/MB/GB etc. CLI Example: .. code-block:: bash salt '*' status.diskusage path=c:/salt ''' if not...
[ "def", "diskusage", "(", "human_readable", "=", "False", ",", "path", "=", "None", ")", ":", "if", "not", "path", ":", "path", "=", "'c:/'", "disk_stats", "=", "psutil", ".", "disk_usage", "(", "path", ")", "total_val", "=", "disk_stats", ".", "total", ...
22.235294
19.294118
def timebar(t, varname = None, databar = False, delete = False, color = 'black', thick = 1, dash = False): """ This function will add a vertical bar to all time series plots. This is useful if you want to bring attention to a specific time. Parameters: t : flt/list The ti...
[ "def", "timebar", "(", "t", ",", "varname", "=", "None", ",", "databar", "=", "False", ",", "delete", "=", "False", ",", "color", "=", "'black'", ",", "thick", "=", "1", ",", "dash", "=", "False", ")", ":", "# make sure t entered is a list", "if", "not...
36.99
21.73
def wait_for_interrupts(threaded=False, epoll_timeout=1): """ Blocking loop to listen for GPIO interrupts and distribute them to associated callbacks. epoll_timeout is an easy way to shutdown the blocking function. Per default the timeout is set to 1 second; if `_is_waiting_for_interrupts` is set to...
[ "def", "wait_for_interrupts", "(", "threaded", "=", "False", ",", "epoll_timeout", "=", "1", ")", ":", "if", "threaded", ":", "t", "=", "Thread", "(", "target", "=", "_rpio", ".", "wait_for_interrupts", ",", "args", "=", "(", "epoll_timeout", ",", ")", "...
43.863636
22.772727
def auto_create_version(class_name, version, filename="__init__.py"): """ creates a version number in the __init__.py file. it can be accessed with __version__ :param class_name: :param version: :param filename: :return: """ version_filename = Path( "{classname}/{filename...
[ "def", "auto_create_version", "(", "class_name", ",", "version", ",", "filename", "=", "\"__init__.py\"", ")", ":", "version_filename", "=", "Path", "(", "\"{classname}/{filename}\"", ".", "format", "(", "classname", "=", "class_name", ",", "filename", "=", "filen...
37
16.263158
def _walk_factory(self, dep_predicate): """Construct the right context object for managing state during a transitive walk.""" walk = None if dep_predicate: walk = self.DepPredicateWalk(dep_predicate) else: walk = self.NoDepPredicateWalk() return walk
[ "def", "_walk_factory", "(", "self", ",", "dep_predicate", ")", ":", "walk", "=", "None", "if", "dep_predicate", ":", "walk", "=", "self", ".", "DepPredicateWalk", "(", "dep_predicate", ")", "else", ":", "walk", "=", "self", ".", "NoDepPredicateWalk", "(", ...
34.375
14
def write_config(self): """ Write config to file """ if not os.path.exists(os.path.dirname(self.config_file)): os.makedirs(os.path.dirname(self.config_file)) with open(self.config_file, 'w') as f: f.write(json.dumps(self.config)) f.close()
[ "def", "write_config", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "dirname", "(", "self", ".", "config_file", ")", ")", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(...
41.857143
12.714286
def removeforkrelation(self, project_id): """ Remove an existing fork relation. this DO NOT remove the fork,only the relation between them :param project_id: project id :return: true if success """ request = requests.delete( '{0}/{1}/fork'.format(self.project...
[ "def", "removeforkrelation", "(", "self", ",", "project_id", ")", ":", "request", "=", "requests", ".", "delete", "(", "'{0}/{1}/fork'", ".", "format", "(", "self", ".", "projects_url", ",", "project_id", ")", ",", "headers", "=", "self", ".", "headers", "...
33.4375
16.9375
def action_update(self): """Form action enpoint to update the attachments """ order = [] form = self.request.form attachments = form.get("attachments", []) for attachment in attachments: # attachment is a form mapping, not a dictionary -> convert ...
[ "def", "action_update", "(", "self", ")", ":", "order", "=", "[", "]", "form", "=", "self", ".", "request", ".", "form", "attachments", "=", "form", ".", "get", "(", "\"attachments\"", ",", "[", "]", ")", "for", "attachment", "in", "attachments", ":", ...
30.78125
17.9375
def _fix_tagging(value, params): """ Checks if a value is properly tagged based on the spec, and re/untags as necessary :param value: An Asn1Value object :param params: A dict of spec params :return: An Asn1Value that is properly tagged """ _tag_type_to_explic...
[ "def", "_fix_tagging", "(", "value", ",", "params", ")", ":", "_tag_type_to_explicit_implicit", "(", "params", ")", "retag", "=", "False", "if", "'implicit'", "not", "in", "params", ":", "if", "value", ".", "implicit", "is", "not", "False", ":", "retag", "...
23.947368
19.684211
def stop(self): """Gracefully shutdown a server that is serving forever.""" self.ready = False if self._start_time is not None: self._run_time += (time.time() - self._start_time) self._start_time = None sock = getattr(self, 'socket', None) if sock: ...
[ "def", "stop", "(", "self", ")", ":", "self", ".", "ready", "=", "False", "if", "self", ".", "_start_time", "is", "not", "None", ":", "self", ".", "_run_time", "+=", "(", "time", ".", "time", "(", ")", "-", "self", ".", "_start_time", ")", "self", ...
44.826087
16.934783
def parse_date(value): """Attempts to parse `value` into an instance of ``datetime.date``. If `value` is ``None``, this function will return ``None``. Args: value: A timestamp. This can be a string, datetime.date, or datetime.datetime value. """ if not value: return Non...
[ "def", "parse_date", "(", "value", ")", ":", "if", "not", "value", ":", "return", "None", "if", "isinstance", "(", "value", ",", "datetime", ".", "date", ")", ":", "return", "value", "return", "parse_datetime", "(", "value", ")", ".", "date", "(", ")" ...
25.625
20.3125