text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def declare_api_routes(config): """Declaration of routing""" add_route = config.add_route add_route('get-content', '/contents/{ident_hash}') add_route('get-resource', '/resources/{hash}') # User actions API add_route('license-request', '/contents/{uuid}/licensors') add_route('roles-request'...
[ "def", "declare_api_routes", "(", "config", ")", ":", "add_route", "=", "config", ".", "add_route", "add_route", "(", "'get-content'", ",", "'/contents/{ident_hash}'", ")", "add_route", "(", "'get-resource'", ",", "'/resources/{hash}'", ")", "# User actions API", "add...
40.333333
0.000807
def _load_config(): """Searches for config files, reads them and returns a dictionary Looks for a ``check-manifest`` section in ``pyproject.toml``, ``setup.cfg``, and ``tox.ini``, in that order. The first file that exists and has that section will be loaded and returned as a dictionary. """ ...
[ "def", "_load_config", "(", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "\"pyproject.toml\"", ")", ":", "config", "=", "toml", ".", "load", "(", "\"pyproject.toml\"", ")", "if", "CFG_SECTION_CHECK_MANIFEST", "in", "config", ".", "get", "(", "\"t...
37.261905
0.001868
def register_plugin(self): """Register plugin in Spyder's main window""" self.main.add_dockwidget(self) self.focus_changed.connect(self.main.plugin_focus_changed) self.edit_goto.connect(self.main.editor.load) self.edit_goto[str, int, str, bool].connect( ...
[ "def", "register_plugin", "(", "self", ")", ":", "self", ".", "main", ".", "add_dockwidget", "(", "self", ")", "self", ".", "focus_changed", ".", "connect", "(", "self", ".", "main", ".", "plugin_focus_changed", ")", "self", ".", "edit_goto", ".", "connect...
52.526316
0.001969
def setup(self): """ Abinit has the very *bad* habit of changing the file extension by appending the characters in [A,B ..., Z] to the output file, and this breaks a lot of code that relies of the use of a unique file extension. Here we fix this issue by renaming run.abo to run.abo_[numb...
[ "def", "setup", "(", "self", ")", ":", "def", "rename_file", "(", "afile", ")", ":", "\"\"\"Helper function to rename :class:`File` objects. Return string for logging purpose.\"\"\"", "# Find the index of the last file (if any).", "# TODO: Maybe it's better to use run.abo --> run(1).abo"...
53.76
0.008041
def dict_to_element(element_as_dict): """ Converts a Dictionary object to an element. The Dictionary can include any of the following tags, only name is required: - name (required): the name of the element tag - text: the text contained by element - tail: text immediately following t...
[ "def", "dict_to_element", "(", "element_as_dict", ")", ":", "if", "element_as_dict", "is", "None", ":", "return", "None", "elif", "isinstance", "(", "element_as_dict", ",", "ElementTree", ")", ":", "return", "element_as_dict", ".", "getroot", "(", ")", "elif", ...
34.153846
0.00073
def jenkins(self): """Generate jenkins job details.""" job_name = self.format['jenkins_job_name'].format(**self.data) job = {'name': job_name} return job
[ "def", "jenkins", "(", "self", ")", ":", "job_name", "=", "self", ".", "format", "[", "'jenkins_job_name'", "]", ".", "format", "(", "*", "*", "self", ".", "data", ")", "job", "=", "{", "'name'", ":", "job_name", "}", "return", "job" ]
30.166667
0.010753
def delete_service(resource_root, name, cluster_name="default"): """ Delete a service by name @param resource_root: The root Resource object. @param name: Service name @param cluster_name: Cluster name @return: The deleted ApiService object """ return call(resource_root.delete, "%s/%s" % (SERVICES...
[ "def", "delete_service", "(", "resource_root", ",", "name", ",", "cluster_name", "=", "\"default\"", ")", ":", "return", "call", "(", "resource_root", ".", "delete", ",", "\"%s/%s\"", "%", "(", "SERVICES_PATH", "%", "(", "cluster_name", ",", ")", ",", "name"...
32.636364
0.01355
def _generate_destination_for_source(self, local_path): # type: (Uploader, blobxfer.models.upload.LocalSourcePath) -> # Tuple[blobxfer.operations.azure.StorageAccount, # blobxfer.models.azure.StorageEntity) """Generate entities for source path :param Uploader self: ...
[ "def", "_generate_destination_for_source", "(", "self", ",", "local_path", ")", ":", "# type: (Uploader, blobxfer.models.upload.LocalSourcePath) ->", "# Tuple[blobxfer.operations.azure.StorageAccount,", "# blobxfer.models.azure.StorageEntity)", "# construct stripped destination p...
48.693878
0.002054
def update(cwd, rev, force=False, user=None): ''' Update to a given revision cwd The path to the Mercurial repository rev The revision to update to force : False Force an update user : None Run hg as a user other than what the minion runs as CLI Example: ...
[ "def", "update", "(", "cwd", ",", "rev", ",", "force", "=", "False", ",", "user", "=", "None", ")", ":", "cmd", "=", "[", "'hg'", ",", "'update'", ",", "'{0}'", ".", "format", "(", "rev", ")", "]", "if", "force", ":", "cmd", ".", "append", "(",...
22
0.001319
def round_off(idnad: Tuple[List[float], List[float]], dp: int = 2): """ Round off an ideal/nadir estimate e.g. so that it's looks nicer when plotted. This function is careful to round so only ever move the values away from the contained range. """ ideal, nadir = idnad mult = np.power(10, dp)...
[ "def", "round_off", "(", "idnad", ":", "Tuple", "[", "List", "[", "float", "]", ",", "List", "[", "float", "]", "]", ",", "dp", ":", "int", "=", "2", ")", ":", "ideal", ",", "nadir", "=", "idnad", "mult", "=", "np", ".", "power", "(", "10", "...
42.272727
0.002105
def key_from_keybase(username, fingerprint=None): """Look up a public key from a username""" url = keybase_lookup_url(username) resp = requests.get(url) if resp.status_code == 200: j_resp = json.loads(polite_string(resp.content)) if 'them' in j_resp and len(j_resp['them']) == 1: ...
[ "def", "key_from_keybase", "(", "username", ",", "fingerprint", "=", "None", ")", ":", "url", "=", "keybase_lookup_url", "(", "username", ")", "resp", "=", "requests", ".", "get", "(", "url", ")", "if", "resp", ".", "status_code", "==", "200", ":", "j_re...
40.058824
0.001435
def ids(self): """A frozen set of all unique IDs in the file.""" as_list = [seq.description.split()[0] for seq in self] as_set = frozenset(as_list) assert len(as_set) == len(as_list) return as_set
[ "def", "ids", "(", "self", ")", ":", "as_list", "=", "[", "seq", ".", "description", ".", "split", "(", ")", "[", "0", "]", "for", "seq", "in", "self", "]", "as_set", "=", "frozenset", "(", "as_list", ")", "assert", "len", "(", "as_set", ")", "==...
38.5
0.008475
def deploy_dotfiles(self, dotfiles): """Deploy dotfiles using the appropriate method.""" if self.args.server: return self.deploy_remote(dotfiles) else: return self.deploy_local(dotfiles)
[ "def", "deploy_dotfiles", "(", "self", ",", "dotfiles", ")", ":", "if", "self", ".", "args", ".", "server", ":", "return", "self", ".", "deploy_remote", "(", "dotfiles", ")", "else", ":", "return", "self", ".", "deploy_local", "(", "dotfiles", ")" ]
38.166667
0.008547
def get_value(self, variable = None, table = None): """ Get value Parameters ---------- variable : string name of the variable table : string, default None name of the table hosting the variable Returns ------- df...
[ "def", "get_value", "(", "self", ",", "variable", "=", "None", ",", "table", "=", "None", ")", ":", "assert", "variable", "is", "not", "None", ",", "\"A variable is needed\"", "if", "table", "not", "in", "self", ".", "tables", ":", "log", ".", "error", ...
31.45
0.009259
def blocksearch(block, name): """ Recursive search for name in block (inner blocks) Args: name (str): search term Returns: Block OR False """ if hasattr(block, 'tokens'): for b in block.tokens[1]: b = (b if hasattr(b, 'raw') and b.raw() == name else blocksearch( ...
[ "def", "blocksearch", "(", "block", ",", "name", ")", ":", "if", "hasattr", "(", "block", ",", "'tokens'", ")", ":", "for", "b", "in", "block", ".", "tokens", "[", "1", "]", ":", "b", "=", "(", "b", "if", "hasattr", "(", "b", ",", "'raw'", ")",...
27.928571
0.002475
def elekta_xvi_space(shape=(512, 512, 512), **kwargs): """Default reconstruction space for the Elekta XVI CBCT. Parameters ---------- shape : sequence of int, optional Shape of the space, in voxels. kwargs : Keyword arguments to pass to `uniform_discr` to modify the space, e.g. ...
[ "def", "elekta_xvi_space", "(", "shape", "=", "(", "512", ",", "512", ",", "512", ")", ",", "*", "*", "kwargs", ")", ":", "if", "'dtype'", "not", "in", "kwargs", ":", "kwargs", "[", "'dtype'", "]", "=", "'float32'", "return", "odl", ".", "uniform_dis...
28.891892
0.000905
def validate(self) : """validate the document""" self._store.validate() for pField in self.collection.arangoPrivates : self.collection.validatePrivate(pField, getattr(self, pField))
[ "def", "validate", "(", "self", ")", ":", "self", ".", "_store", ".", "validate", "(", ")", "for", "pField", "in", "self", ".", "collection", ".", "arangoPrivates", ":", "self", ".", "collection", ".", "validatePrivate", "(", "pField", ",", "getattr", "(...
42.6
0.018433
def __register_notification(self, prop_name, method, kwargs): """Internal service which associates the given property name to the method, and the (prop_name, method) with the given kwargs dictionary. If needed merges the dictionary, if the given (prop_name, method) pair was already regis...
[ "def", "__register_notification", "(", "self", ",", "prop_name", ",", "method", ",", "kwargs", ")", ":", "key", "=", "(", "prop_name", ",", "method", ")", "if", "key", "in", "self", ".", "__PAT_METH_TO_KWARGS", ":", "raise", "ValueError", "(", "\"In class %s...
45.363636
0.002354
def basename_without_extension(self): """ Get the ``os.path.basename`` of the local file, if any, with extension removed. """ ret = self.basename.rsplit('.', 1)[0] if ret.endswith('.tar'): ret = ret[0:len(ret)-4] return ret
[ "def", "basename_without_extension", "(", "self", ")", ":", "ret", "=", "self", ".", "basename", ".", "rsplit", "(", "'.'", ",", "1", ")", "[", "0", "]", "if", "ret", ".", "endswith", "(", "'.tar'", ")", ":", "ret", "=", "ret", "[", "0", ":", "le...
34.5
0.010601
def get_current_service_state(self, service_id: str): """Get the state of a SDP service.""" state = self._get_service_state(service_id) return state.current_state
[ "def", "get_current_service_state", "(", "self", ",", "service_id", ":", "str", ")", ":", "state", "=", "self", ".", "_get_service_state", "(", "service_id", ")", "return", "state", ".", "current_state" ]
45.75
0.010753
def sync_mptt_tree_fields_from_draft_to_published_post_save( sender, instance, **kwargs): """ Post save trigger to immediately sync MPTT tree structure field changes made to draft copies to their corresponding published copy. """ mptt_opts = getattr(instance, '_mptt_meta', None) publishe...
[ "def", "sync_mptt_tree_fields_from_draft_to_published_post_save", "(", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "mptt_opts", "=", "getattr", "(", "instance", ",", "'_mptt_meta'", ",", "None", ")", "published_copy", "=", "getattr", "(", "instan...
46.5
0.00211
def cov(self, other=None, pairwise=None, bias=False, **kwargs): """ Exponential weighted sample covariance. """ if other is None: other = self._selected_obj # only default unset pairwise = True if pairwise is None else pairwise other = self._sh...
[ "def", "cov", "(", "self", ",", "other", "=", "None", ",", "pairwise", "=", "None", ",", "bias", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "other", "is", "None", ":", "other", "=", "self", ".", "_selected_obj", "# only default unset", "p...
41.285714
0.002255
def make_module_to_builder_dict(datasets=None): """Get all builders organized by module in nested dicts.""" # pylint: disable=g-long-lambda # dict to hold tfds->image->mnist->[builders] module_to_builder = collections.defaultdict( lambda: collections.defaultdict( lambda: collections.defaultdict(...
[ "def", "make_module_to_builder_dict", "(", "datasets", "=", "None", ")", ":", "# pylint: disable=g-long-lambda", "# dict to hold tfds->image->mnist->[builders]", "module_to_builder", "=", "collections", ".", "defaultdict", "(", "lambda", ":", "collections", ".", "defaultdict"...
32.387097
0.012573
def grok_vars(elements): """Returns a list of vars for which the value is being appropriately set This currently includes the default filter, for-based iterators, and the explicit use of set""" default_vars = [] iterbody = None if hasattr(elements, 'body'): iterbody = elements.body e...
[ "def", "grok_vars", "(", "elements", ")", ":", "default_vars", "=", "[", "]", "iterbody", "=", "None", "if", "hasattr", "(", "elements", ",", "'body'", ")", ":", "iterbody", "=", "elements", ".", "body", "elif", "hasattr", "(", "elements", ",", "'nodes'"...
41.413793
0.000814
def load_cyclegan_dataset(filename='summer2winter_yosemite', path='data'): """Load images from CycleGAN's database, see `this link <https://people.eecs.berkeley.edu/~taesung_park/CycleGAN/datasets/>`__. Parameters ------------ filename : str The dataset you want, see `this link <https://people....
[ "def", "load_cyclegan_dataset", "(", "filename", "=", "'summer2winter_yosemite'", ",", "path", "=", "'data'", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'cyclegan'", ")", "url", "=", "'https://people.eecs.berkeley.edu/~taesung_park/C...
43.955556
0.002473
def _transliterate (self, text, outFormat): """ Transliterate the text to Unicode.""" result = [] text = self._preprocess(text) i = 0 while i < len(text): if text[i].isspace(): result.append(text[i]) i = i+1 else: ...
[ "def", "_transliterate", "(", "self", ",", "text", ",", "outFormat", ")", ":", "result", "=", "[", "]", "text", "=", "self", ".", "_preprocess", "(", "text", ")", "i", "=", "0", "while", "i", "<", "len", "(", "text", ")", ":", "if", "text", "[", ...
32.882353
0.008696
def _try_inline_read(self) -> None: """Attempt to complete the current read operation from buffered data. If the read can be completed without blocking, schedules the read callback on the next IOLoop iteration; otherwise starts listening for reads on the socket. """ # Se...
[ "def", "_try_inline_read", "(", "self", ")", "->", "None", ":", "# See if we've already got the data from a previous read", "pos", "=", "self", ".", "_find_read_pos", "(", ")", "if", "pos", "is", "not", "None", ":", "self", ".", "_read_from_buffer", "(", "pos", ...
40.095238
0.00232
def find_suggestions(self, sentence): """ Search all possible suggestions. Suggestions returned always have at least one document matching. Arguments: sentence --- keywords (single strings) for which we want suggestions Return: An array of...
[ "def", "find_suggestions", "(", "self", ",", "sentence", ")", ":", "if", "not", "isinstance", "(", "sentence", ",", "str", ")", ":", "sentence", "=", "str", "(", "sentence", ")", "keywords", "=", "sentence", ".", "split", "(", "\" \"", ")", "query_parser...
38.391304
0.001104
def phoncontent(self, cls='current', correctionhandling=CorrectionHandling.CURRENT): """See :meth:`AbstractElement.phoncontent`""" if cls == 'original': correctionhandling = CorrectionHandling.ORIGINAL #backward compatibility if correctionhandling in (CorrectionHandling.CURRENT, CorrectionHandli...
[ "def", "phoncontent", "(", "self", ",", "cls", "=", "'current'", ",", "correctionhandling", "=", "CorrectionHandling", ".", "CURRENT", ")", ":", "if", "cls", "==", "'original'", ":", "correctionhandling", "=", "CorrectionHandling", ".", "ORIGINAL", "#backward comp...
60.916667
0.012129
def stop(self, unique_id, configs=None): """Stop the service. If the deployer has not started a service with`unique_id` the deployer will raise an Exception There are two configs that will be considered: 'terminate_only': if this config is passed in then this method is the same as terminate(unique_id) (thi...
[ "def", "stop", "(", "self", ",", "unique_id", ",", "configs", "=", "None", ")", ":", "# the following is necessay to set the configs for this function as the combination of the", "# default configurations and the parameter with the parameter superceding the defaults but", "# not modifyin...
43
0.011634
def get_c_sources(folder, include_headers=False): """Find all C/C++ source files in the `folder` directory.""" allowed_extensions = [".c", ".C", ".cc", ".cpp", ".cxx", ".c++"] if include_headers: allowed_extensions += [".h", ".hpp"] sources = [] for root, _, files in os.walk(folder): ...
[ "def", "get_c_sources", "(", "folder", ",", "include_headers", "=", "False", ")", ":", "allowed_extensions", "=", "[", "\".c\"", ",", "\".C\"", ",", "\".cc\"", ",", "\".cpp\"", ",", "\".cxx\"", ",", "\".c++\"", "]", "if", "include_headers", ":", "allowed_exten...
44
0.001391
def autoset_margins(self): """auto-set margins left, bottom, right, top according to the specified margins (in pixels) and axes extent (taking into account labels, title, axis) """ if not self.conf.auto_margins: return # coordinates in px -> [0,1] in ...
[ "def", "autoset_margins", "(", "self", ")", ":", "if", "not", "self", ".", "conf", ".", "auto_margins", ":", "return", "# coordinates in px -> [0,1] in figure coordinates", "trans", "=", "self", ".", "fig", ".", "transFigure", ".", "inverted", "(", ")", ".", "...
35.863636
0.002469
def escalatees(self): """ Gets the task escalatees """ if not self.can_update(): self._tcex.handle_error(910, [self.type]) for e in self.tc_requests.escalatees(self.api_type, self.api_sub_type, self.unique_id): yield e
[ "def", "escalatees", "(", "self", ")", ":", "if", "not", "self", ".", "can_update", "(", ")", ":", "self", ".", "_tcex", ".", "handle_error", "(", "910", ",", "[", "self", ".", "type", "]", ")", "for", "e", "in", "self", ".", "tc_requests", ".", ...
30.555556
0.010601
def batch_indices_iterator(self, batch_size, shuffle=None, **kwargs): """ Create an iterator that generates mini-batch sample indices. The batches will have `batch_size` elements, with the exception of the final batch which will have less if there are insufficient elements left t...
[ "def", "batch_indices_iterator", "(", "self", ",", "batch_size", ",", "shuffle", "=", "None", ",", "*", "*", "kwargs", ")", ":", "shuffle_rng", "=", "self", ".", "_get_shuffle_rng", "(", "shuffle", ")", "if", "shuffle_rng", "is", "not", "None", ":", "retur...
42.047619
0.001107
def _get_cluster_dict(cluster_name, cluster_ref): ''' Returns a cluster dict representation from a vim.ClusterComputeResource object. cluster_name Name of the cluster cluster_ref Reference to the cluster ''' log.trace('Building a dictionary representation of cluster \'%s\'...
[ "def", "_get_cluster_dict", "(", "cluster_name", ",", "cluster_ref", ")", ":", "log", ".", "trace", "(", "'Building a dictionary representation of cluster \\'%s\\''", ",", "cluster_name", ")", "props", "=", "salt", ".", "utils", ".", "vmware", ".", "get_properties_of_...
46.949367
0.00132
def tuple(self, var, cast=None, default=NOTSET): """ :rtype: tuple """ return self.get_value(var, cast=tuple if not cast else (cast,), default=default)
[ "def", "tuple", "(", "self", ",", "var", ",", "cast", "=", "None", ",", "default", "=", "NOTSET", ")", ":", "return", "self", ".", "get_value", "(", "var", ",", "cast", "=", "tuple", "if", "not", "cast", "else", "(", "cast", ",", ")", ",", "defau...
35.8
0.016393
def path_new_using_map( m: tcod.map.Map, dcost: float = 1.41 ) -> tcod.path.AStar: """Return a new AStar using the given Map. Args: m (Map): A Map instance. dcost (float): The path-finding cost of diagonal movement. Can be set to 0 to disable diagonal movement. Re...
[ "def", "path_new_using_map", "(", "m", ":", "tcod", ".", "map", ".", "Map", ",", "dcost", ":", "float", "=", "1.41", ")", "->", "tcod", ".", "path", ".", "AStar", ":", "return", "tcod", ".", "path", ".", "AStar", "(", "m", ",", "dcost", ")" ]
30.461538
0.002451
def make_good_url(url=None, addition="/"): """Appends addition to url, ensuring the right number of slashes exist and the path doesn't get clobbered. >>> make_good_url('http://www.server.com/anywhere', 'else') 'http://www.server.com/anywhere/else' >>> make_good_url('http://test.com/', '/somewhere/o...
[ "def", "make_good_url", "(", "url", "=", "None", ",", "addition", "=", "\"/\"", ")", ":", "if", "url", "is", "None", ":", "return", "None", "if", "isinstance", "(", "url", ",", "str", ")", "and", "isinstance", "(", "addition", ",", "str", ")", ":", ...
31.88
0.001218
def ascii(expr, cache=None, **settings): """Return an ASCII representation of the given object / expression Args: expr: Expression to print cache (dict or None): dictionary to use for caching show_hs_label (bool or str): Whether to a label for the Hilbert space of `expr`. By...
[ "def", "ascii", "(", "expr", ",", "cache", "=", "None", ",", "*", "*", "settings", ")", ":", "try", ":", "if", "cache", "is", "None", "and", "len", "(", "settings", ")", "==", "0", ":", "return", "ascii", ".", "printer", ".", "doprint", "(", "exp...
38.6
0.000561
def plotSuccessRate_varyNumColumns(noiseSigma, noiseEverywhere): """ Run and plot the experiment, varying the number of cortical columns. """ # # Run the experiment # noiseLevels = [x * 0.01 for x in xrange(0, 101, 5)] l2Overrides = {"sampleSizeDistal": 20} columnCounts = [1, 2, 3, 4] results = de...
[ "def", "plotSuccessRate_varyNumColumns", "(", "noiseSigma", ",", "noiseEverywhere", ")", ":", "#", "# Run the experiment", "#", "noiseLevels", "=", "[", "x", "*", "0.01", "for", "x", "in", "xrange", "(", "0", ",", "101", ",", "5", ")", "]", "l2Overrides", ...
34.230769
0.014854
def observe(self, key, callback: Callable[[Any, Any], None]): """Subscribes to key changes""" if key not in self.__dict__ and key not in self._callbacks: raise KeyError('Entity ' + str(self) + 'doesn''t have attribute' + key) super().observe(key, callback)
[ "def", "observe", "(", "self", ",", "key", ",", "callback", ":", "Callable", "[", "[", "Any", ",", "Any", "]", ",", "None", "]", ")", ":", "if", "key", "not", "in", "self", ".", "__dict__", "and", "key", "not", "in", "self", ".", "_callbacks", ":...
57.6
0.010274
def is_valid(self): """ Tests if the dependency is in a valid state """ return super(SimpleDependency, self).is_valid() or ( self.requirement.immediate_rebind and self._pending_ref is not None )
[ "def", "is_valid", "(", "self", ")", ":", "return", "super", "(", "SimpleDependency", ",", "self", ")", ".", "is_valid", "(", ")", "or", "(", "self", ".", "requirement", ".", "immediate_rebind", "and", "self", ".", "_pending_ref", "is", "not", "None", ")...
34.285714
0.00813
def save_to_cache(url, response_json): """ Save an HTTP response json object to the cache. If the request was sent to server via POST instead of GET, then URL should be a GET-style representation of request. Users should always pass OrderedDicts instead of dicts of parameters into request functions...
[ "def", "save_to_cache", "(", "url", ",", "response_json", ")", ":", "if", "settings", ".", "use_cache", ":", "if", "response_json", "is", "None", ":", "log", "(", "'Saved nothing to cache because response_json is None'", ")", "else", ":", "# create the folder on the d...
39.5
0.002353
def mk_privkeys(num): "make privkeys that support coloring, see utils.cstr" privkeys = [] assert num <= num_colors for i in range(num): j = 0 while True: k = sha3(str(j)) a = privtoaddr(k) an = big_endian_to_int(a) if an % num_colors == i: ...
[ "def", "mk_privkeys", "(", "num", ")", ":", "privkeys", "=", "[", "]", "assert", "num", "<=", "num_colors", "for", "i", "in", "range", "(", "num", ")", ":", "j", "=", "0", "while", "True", ":", "k", "=", "sha3", "(", "str", "(", "j", ")", ")", ...
26.2
0.002457
def mtabstr2doestr(st1): """mtabstr2doestr""" seperator = '$ ==============' alist = st1.split(seperator) #this removes all the tabs that excel #puts after the seperator and before the next line for num in range(0, len(alist)): alist[num] = alist[num].lstrip() st2 = '' for num i...
[ "def", "mtabstr2doestr", "(", "st1", ")", ":", "seperator", "=", "'$ =============='", "alist", "=", "st1", ".", "split", "(", "seperator", ")", "#this removes all the tabs that excel", "#puts after the seperator and before the next line", "for", "num", "in", "range", "...
25.826087
0.00974
def _instruction_list(self, filters): """Generates the instructions for a bot and its filters. Note: The guidance for each filter is generated by combining the docstrings of the predicate filter and resulting dispatch function with a single space between. The class's ...
[ "def", "_instruction_list", "(", "self", ",", "filters", ")", ":", "return", "'\\n\\n'", ".", "join", "(", "[", "self", ".", "INSTRUCTIONS", ".", "strip", "(", ")", ",", "'*Supported methods:*'", ",", "'If you send \"@{}: help\" to me I reply with these '", "'instru...
36.730769
0.002041
def chimera_layout(G, scale=1., center=None, dim=2): """Positions the nodes of graph G in a Chimera cross topology. NumPy (http://scipy.org) is required for this function. Parameters ---------- G : NetworkX graph Should be a Chimera graph or a subgraph of a Chimera graph. If every ...
[ "def", "chimera_layout", "(", "G", ",", "scale", "=", "1.", ",", "center", "=", "None", ",", "dim", "=", "2", ")", ":", "if", "not", "isinstance", "(", "G", ",", "nx", ".", "Graph", ")", ":", "empty_graph", "=", "nx", ".", "Graph", "(", ")", "e...
36.157895
0.002125
def get_synset_xml(self,syn_id): """ call cdb_syn with synset identifier -> returns the synset xml; """ http, resp, content = self.connect() params = "" fragment = "" path = "cdb_syn" if self.debug: printf( "cornettodb/views/query_remote_s...
[ "def", "get_synset_xml", "(", "self", ",", "syn_id", ")", ":", "http", ",", "resp", ",", "content", "=", "self", ".", "connect", "(", ")", "params", "=", "\"\"", "fragment", "=", "\"\"", "path", "=", "\"cdb_syn\"", "if", "self", ".", "debug", ":", "p...
34
0.025482
def check_argument_types(cllable = None, call_args = None, clss = None, caller_level = 0): """Can be called from within a function or method to apply typechecking to the arguments that were passed in by the caller. Checking is applied w.r.t. type hints of the function or method hosting the call to check_arg...
[ "def", "check_argument_types", "(", "cllable", "=", "None", ",", "call_args", "=", "None", ",", "clss", "=", "None", ",", "caller_level", "=", "0", ")", ":", "return", "_check_caller_type", "(", "False", ",", "cllable", ",", "call_args", ",", "clss", ",", ...
69
0.026253
def process_block(self, block): """ process block from the block_parser and return a list of processed lines """ ret = [] output = None input_lines = None lineno = self.IP.execution_count input_prompt = self.promptin % lineno output_prompt = self....
[ "def", "process_block", "(", "self", ",", "block", ")", ":", "ret", "=", "[", "]", "output", "=", "None", "input_lines", "=", "None", "lineno", "=", "self", ".", "IP", ".", "execution_count", "input_prompt", "=", "self", ".", "promptin", "%", "lineno", ...
41
0.001381
def dewpoint(e): r"""Calculate the ambient dewpoint given the vapor pressure. Parameters ---------- e : `pint.Quantity` Water vapor partial pressure Returns ------- `pint.Quantity` Dew point temperature See Also -------- dewpoint_rh, saturation_vapor_pressure, ...
[ "def", "dewpoint", "(", "e", ")", ":", "val", "=", "np", ".", "log", "(", "e", "/", "sat_pressure_0c", ")", "return", "0.", "*", "units", ".", "degC", "+", "243.5", "*", "units", ".", "delta_degC", "*", "val", "/", "(", "17.67", "-", "val", ")" ]
25.571429
0.001346
def serve_protected_thumbnail(request, path): """ Serve protected thumbnails to authenticated users. If the user doesn't have read permissions, redirect to a static image. """ source_path = thumbnail_to_original_filename(path) if not source_path: raise Http404('File not found') try: ...
[ "def", "serve_protected_thumbnail", "(", "request", ",", "path", ")", ":", "source_path", "=", "thumbnail_to_original_filename", "(", "path", ")", "if", "not", "source_path", ":", "raise", "Http404", "(", "'File not found'", ")", "try", ":", "file_obj", "=", "Fi...
38.727273
0.002291
def change_password(): """View function which handles a change password request.""" form_class = _security.change_password_form if request.is_json: form = form_class(MultiDict(request.get_json())) else: form = form_class() if form.validate_on_submit(): after_this_request(_...
[ "def", "change_password", "(", ")", ":", "form_class", "=", "_security", ".", "change_password_form", "if", "request", ".", "is_json", ":", "form", "=", "form_class", "(", "MultiDict", "(", "request", ".", "get_json", "(", ")", ")", ")", "else", ":", "form...
31.821429
0.001089
def _calculate_feature_stats(feature_list, prepared, serialization_file): # pylint: disable=R0914 """Calculate min, max and mean for each feature. Store it in object.""" # Create feature only list feats = [x for x, _ in prepared] # Label is not necessary # Calculate all means / mins / maxs means ...
[ "def", "_calculate_feature_stats", "(", "feature_list", ",", "prepared", ",", "serialization_file", ")", ":", "# pylint: disable=R0914", "# Create feature only list", "feats", "=", "[", "x", "for", "x", ",", "_", "in", "prepared", "]", "# Label is not necessary", "# C...
41.575758
0.001425
def _fit_RSA_UV(self, X, Y, X_base, scan_onsets=None, coords=None, inten=None): """ The major utility of fitting Bayesian RSA. Note that there is a naming change of variable. X in fit() is changed to Y here, and design in fit() is changed to X here. This i...
[ "def", "_fit_RSA_UV", "(", "self", ",", "X", ",", "Y", ",", "X_base", ",", "scan_onsets", "=", "None", ",", "coords", "=", "None", ",", "inten", "=", "None", ")", ":", "GP_inten", "=", "self", ".", "GP_inten", "GP_space", "=", "self", ".", "GP_space"...
49.581818
0.00027
def convert_activation(builder, layer, input_names, output_names, keras_layer): """Convert an activation layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ # Get input...
[ "def", "convert_activation", "(", "builder", ",", "layer", ",", "input_names", ",", "output_names", ",", "keras_layer", ")", ":", "# Get input and output names", "input_name", ",", "output_name", "=", "(", "input_names", "[", "0", "]", ",", "output_names", "[", ...
39.767857
0.014023
def parse_header(file_obj): """ Read the ASCII header of a PLY file, and leave the file object at the position of the start of data but past the header. Parameters ----------- file_obj : open file object Positioned at the start of the file Returns ----------- elements : colle...
[ "def", "parse_header", "(", "file_obj", ")", ":", "if", "'ply'", "not", "in", "str", "(", "file_obj", ".", "readline", "(", ")", ")", ":", "raise", "ValueError", "(", "'not a ply file!'", ")", "# collect the encoding: binary or ASCII", "encoding", "=", "file_obj...
32.088608
0.000383
def run(self): """ Run consumer """ if KSER_METRICS_ENABLED == "yes": from prometheus_client import start_http_server logger.info("Metric.Starting...") start_http_server( os.getenv("KSER_METRICS_PORT", 8888), os.getenv("KSER_MET...
[ "def", "run", "(", "self", ")", ":", "if", "KSER_METRICS_ENABLED", "==", "\"yes\"", ":", "from", "prometheus_client", "import", "start_http_server", "logger", ".", "info", "(", "\"Metric.Starting...\"", ")", "start_http_server", "(", "os", ".", "getenv", "(", "\...
36.423077
0.002058
def _query_server_pos(self, conn, file_length): """ Queries server to find out what bytes it currently has. Returns (server_start, server_end), where the values are inclusive. For example, (0, 2) would mean that the server has bytes 0, 1, *and* 2. Raises ResumableUploadExceptio...
[ "def", "_query_server_pos", "(", "self", ",", "conn", ",", "file_length", ")", ":", "resp", "=", "self", ".", "_query_server_state", "(", "conn", ",", "file_length", ")", "if", "resp", ".", "status", "==", "200", ":", "return", "(", "0", ",", "file_lengt...
50.155556
0.002173
def dependencies(self): """ Read the contents of the rpm itself :return: """ cpio = self.rpm.gzip_file.read() content = cpio.read() return []
[ "def", "dependencies", "(", "self", ")", ":", "cpio", "=", "self", ".", "rpm", ".", "gzip_file", ".", "read", "(", ")", "content", "=", "cpio", ".", "read", "(", ")", "return", "[", "]" ]
23.75
0.010152
def get_alias(self, alias): """ RETURN REFERENCE TO ALIAS (MANY INDEXES) USER MUST BE SURE NOT TO SEND UPDATES """ aliases = self.get_aliases() if alias in aliases.alias: settings = self.settings.copy() settings.alias = alias settings.i...
[ "def", "get_alias", "(", "self", ",", "alias", ")", ":", "aliases", "=", "self", ".", "get_aliases", "(", ")", "if", "alias", "in", "aliases", ".", "alias", ":", "settings", "=", "self", ".", "settings", ".", "copy", "(", ")", "settings", ".", "alias...
40.25
0.008097
def _add_to_stack(self, item, value): """ Add a parameter-value pair to the stack of parameters that have been set. :param item: :param value: :return: """ p_value = (item, value) if p_value not in self.stack: self.stack.append(p_value)
[ "def", "_add_to_stack", "(", "self", ",", "item", ",", "value", ")", ":", "p_value", "=", "(", "item", ",", "value", ")", "if", "p_value", "not", "in", "self", ".", "stack", ":", "self", ".", "stack", ".", "append", "(", "p_value", ")" ]
30.3
0.009615
def canonical(request, uploaded_at, file_id): """ Redirect to the current url of a public file """ filer_file = get_object_or_404(File, pk=file_id, is_public=True) if (uploaded_at != filer_file.uploaded_at.strftime('%s') or not filer_file.file): raise Http404('No %s matches the g...
[ "def", "canonical", "(", "request", ",", "uploaded_at", ",", "file_id", ")", ":", "filer_file", "=", "get_object_or_404", "(", "File", ",", "pk", "=", "file_id", ",", "is_public", "=", "True", ")", "if", "(", "uploaded_at", "!=", "filer_file", ".", "upload...
40.7
0.002404
def bk_yellow(cls): "Make the text background color yellow." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.BACKGROUND_MASK wAttributes |= win32.BACKGROUND_YELLOW cls._set_text_attributes(wAttributes)
[ "def", "bk_yellow", "(", "cls", ")", ":", "wAttributes", "=", "cls", ".", "_get_text_attributes", "(", ")", "wAttributes", "&=", "~", "win32", ".", "BACKGROUND_MASK", "wAttributes", "|=", "win32", ".", "BACKGROUND_YELLOW", "cls", ".", "_set_text_attributes", "("...
42
0.011673
def update_encoding(self, encoding): """Update encoding of current file.""" value = str(encoding).upper() self.set_value(value)
[ "def", "update_encoding", "(", "self", ",", "encoding", ")", ":", "value", "=", "str", "(", "encoding", ")", ".", "upper", "(", ")", "self", ".", "set_value", "(", "value", ")" ]
37
0.013245
def prefix_iter(self, ns_uri): """Gets an iterator over the prefixes for the given namespace.""" ni = self.__lookup_uri(ns_uri) return iter(ni.prefixes)
[ "def", "prefix_iter", "(", "self", ",", "ns_uri", ")", ":", "ni", "=", "self", ".", "__lookup_uri", "(", "ns_uri", ")", "return", "iter", "(", "ni", ".", "prefixes", ")" ]
43.25
0.011364
def match(self, *command_tokens, command_context=None, **command_env): """ Match command :param command_tokens: command tokens to check :param command_context: command context :param command_env: command environment :return: bool """ if self.adapter().match(command_context, **command_env) is False: re...
[ "def", "match", "(", "self", ",", "*", "command_tokens", ",", "command_context", "=", "None", ",", "*", "*", "command_env", ")", ":", "if", "self", ".", "adapter", "(", ")", ".", "match", "(", "command_context", ",", "*", "*", "command_env", ")", "is",...
40.615385
0.025926
def write(source_mapping, output_stream=sys.stdout): """This method writes a Python module respresenting all the keys and values known to configman. """ # a set of classes, modules and/or functions that are values in # configman options. These values will have to be imported in ...
[ "def", "write", "(", "source_mapping", ",", "output_stream", "=", "sys", ".", "stdout", ")", ":", "# a set of classes, modules and/or functions that are values in", "# configman options. These values will have to be imported in the", "# module that this method is writing.", "set_of_cl...
45.014706
0.000639
def clip_grad(learn:Learner, clip:float=0.1)->Learner: "Add gradient clipping of `clip` during training." learn.callback_fns.append(partial(GradientClipping, clip=clip)) return learn
[ "def", "clip_grad", "(", "learn", ":", "Learner", ",", "clip", ":", "float", "=", "0.1", ")", "->", "Learner", ":", "learn", ".", "callback_fns", ".", "append", "(", "partial", "(", "GradientClipping", ",", "clip", "=", "clip", ")", ")", "return", "lea...
47.75
0.030928
def melt(table, key=None, variables=None, variablefield='variable', valuefield='value'): """ Reshape a table, melting fields into data. E.g.:: >>> import petl as etl >>> table1 = [['id', 'gender', 'age'], ... [1, 'F', 12], ... [2, 'M', 17], ....
[ "def", "melt", "(", "table", ",", "key", "=", "None", ",", "variables", "=", "None", ",", "variablefield", "=", "'variable'", ",", "valuefield", "=", "'value'", ")", ":", "return", "MeltView", "(", "table", ",", "key", "=", "key", ",", "variables", "="...
35.666667
0.000379
def run(xmin, ymin, xmax, ymax, step, range_, range_x, range_y, t): X,Y = t.shape pt = np.zeros((X,Y)) "omp parallel for" for i in range(X): for j in range(Y): for k in t: tmp = 6368.* np.arccos( np.cos(xmin+step*i)*np.cos( k[0] ) * np.cos((ymin+step*j)-k[1])+ np.sin...
[ "def", "run", "(", "xmin", ",", "ymin", ",", "xmax", ",", "ymax", ",", "step", ",", "range_", ",", "range_x", ",", "range_y", ",", "t", ")", ":", "X", ",", "Y", "=", "t", ".", "shape", "pt", "=", "np", ".", "zeros", "(", "(", "X", ",", "Y",...
39
0.025057
def to_json(self): """ Serialises a HucitWork to a JSON formatted string. """ titles = self.get_titles() return json.dumps({ "uri" : self.subject , "urn" : str(self.get_urn()) , "titles" : [{"language":lang, "label":label} for lang,...
[ "def", "to_json", "(", "self", ")", ":", "titles", "=", "self", ".", "get_titles", "(", ")", "return", "json", ".", "dumps", "(", "{", "\"uri\"", ":", "self", ".", "subject", ",", "\"urn\"", ":", "str", "(", "self", ".", "get_urn", "(", ")", ")", ...
34.916667
0.027907
def _input_as_lines(self, data): """ Write a seq of lines to a temp file and return the filename string data: a sequence to be written to a file, each element of the sequence will compose a line in the file * Note: the result will be the filename as a FilePath object ...
[ "def", "_input_as_lines", "(", "self", ",", "data", ")", ":", "filename", "=", "self", ".", "_input_filename", "=", "FilePath", "(", "self", ".", "getTmpFilename", "(", "self", ".", "TmpDir", ")", ")", "filename", "=", "FilePath", "(", "filename", ")", "...
44.55
0.002198
def upgrade(): """Upgrade database.""" op.drop_constraint(u'fk_access_actionsusers_user_id_accounts_user', 'access_actionsusers', type_='foreignkey') op.drop_index(op.f('ix_access_actionsusers_user_id'), table_name='access_actionsusers') op.alter_column('access_...
[ "def", "upgrade", "(", ")", ":", "op", ".", "drop_constraint", "(", "u'fk_access_actionsusers_user_id_accounts_user'", ",", "'access_actionsusers'", ",", "type_", "=", "'foreignkey'", ")", "op", ".", "drop_index", "(", "op", ".", "f", "(", "'ix_access_actionsusers_u...
49.266667
0.001328
def find_types(observatory, match=None, trend=None, connection=None, **connection_kw): """Find the available data types for a given observatory. See also -------- gwdatafind.http.HTTPConnection.find_types FflConnection.find_types for details on the underlying method(s) ""...
[ "def", "find_types", "(", "observatory", ",", "match", "=", "None", ",", "trend", "=", "None", ",", "connection", "=", "None", ",", "*", "*", "connection_kw", ")", ":", "return", "sorted", "(", "connection", ".", "find_types", "(", "observatory", ",", "m...
37.833333
0.002151
def get_page_url_title(self): ''' Get the title and current url from the remote session. Return is a 2-tuple: (page_title, page_url). ''' cr_tab_id = self.transport._get_cr_tab_meta_for_key(self.tab_id)['id'] targets = self.Target_getTargets() assert 'result' in targets assert 'targetInfos' in targe...
[ "def", "get_page_url_title", "(", "self", ")", ":", "cr_tab_id", "=", "self", ".", "transport", ".", "_get_cr_tab_meta_for_key", "(", "self", ".", "tab_id", ")", "[", "'id'", "]", "targets", "=", "self", ".", "Target_getTargets", "(", ")", "assert", "'result...
25.037037
0.032764
def pointerEvent(self, x, y, buttonmask=0): """Indicates either pointer movement or a pointer button press or release. The pointer is now at (x-position, y-position), and the current state of buttons 1 to 8 are represented by bits 0 to 7 of button-mask respectively, 0 meaning up, 1 meaning...
[ "def", "pointerEvent", "(", "self", ",", "x", ",", "y", ",", "buttonmask", "=", "0", ")", ":", "self", ".", "transport", ".", "write", "(", "pack", "(", "\"!BBHH\"", ",", "5", ",", "buttonmask", ",", "x", ",", "y", ")", ")" ]
68
0.012107
def uninstall(plugin_name, *args): ''' Uninstall plugin packages. Plugin packages must have a directory with the same name as the package in the following directory: <conda prefix>/share/microdrop/plugins/available/ Parameters ---------- plugin_name : str or list Plugin pa...
[ "def", "uninstall", "(", "plugin_name", ",", "*", "args", ")", ":", "if", "isinstance", "(", "plugin_name", ",", "types", ".", "StringTypes", ")", ":", "plugin_name", "=", "[", "plugin_name", "]", "available_path", "=", "MICRODROP_CONDA_SHARE", ".", "joinpath"...
37.333333
0.000622
def exhaustive_curie_check( self, ontology:pd.DataFrame, curie_predicate:str, curie_prefix:str, diff:bool=True, ) -> Tuple[list]: ''' All entities with conflicting curies gets a full d...
[ "def", "exhaustive_curie_check", "(", "self", ",", "ontology", ":", "pd", ".", "DataFrame", ",", "curie_predicate", ":", "str", ",", "curie_prefix", ":", "str", ",", "diff", ":", "bool", "=", "True", ",", ")", "->", "Tuple", "[", "list", "]", ":", "ins...
51.813953
0.011013
def _cache_contents(self, style_urls, asset_url_path): """ Fetches the given URLs and caches their contents and their assets in the given directory. """ files = {} asset_urls = [] for style_url in style_urls: if not self.quiet: print('...
[ "def", "_cache_contents", "(", "self", ",", "style_urls", ",", "asset_url_path", ")", ":", "files", "=", "{", "}", "asset_urls", "=", "[", "]", "for", "style_url", "in", "style_urls", ":", "if", "not", "self", ".", "quiet", ":", "print", "(", "' * Downlo...
39.919355
0.000789
def get_chempot_correction(element, temp, pres): """ Get the normalized correction term Δμ for chemical potential of a gas phase consisting of element at given temperature and pressure, referenced to that in the standard state (T_std = 298.15 K, T_std = 1 bar). The gas phase is l...
[ "def", "get_chempot_correction", "(", "element", ",", "temp", ",", "pres", ")", ":", "if", "element", "not", "in", "[", "\"O\"", ",", "\"N\"", ",", "\"Cl\"", ",", "\"F\"", ",", "\"H\"", "]", ":", "return", "0", "std_temp", "=", "298.15", "std_pres", "=...
41.017857
0.001276
def _load(self, name, workdir, quiet=False): """ Load a JSON serialized tetrad instance to continue from a checkpoint. """ ## load the JSON string and try with name+.json path = os.path.join(workdir, name) if not path.endswith(".tet.json"): path += ".tet.json...
[ "def", "_load", "(", "self", ",", "name", ",", "workdir", ",", "quiet", "=", "False", ")", ":", "## load the JSON string and try with name+.json", "path", "=", "os", ".", "path", ".", "join", "(", "workdir", ",", "name", ")", "if", "not", "path", ".", "e...
36.756098
0.008403
def ordered(self, ord='desc'): """Order the query result on the relations' indexes.""" if ord not in ('asc', 'desc', ): raise ord_f = getattr(PIDRelation.index, ord)() return self.order_by(ord_f)
[ "def", "ordered", "(", "self", ",", "ord", "=", "'desc'", ")", ":", "if", "ord", "not", "in", "(", "'asc'", ",", "'desc'", ",", ")", ":", "raise", "ord_f", "=", "getattr", "(", "PIDRelation", ".", "index", ",", "ord", ")", "(", ")", "return", "se...
39
0.008368
def registration_agency(self, ids, **kwargs): ''' Determine registration agency for DOIs :param ids: [Array] DOIs (digital object identifier) or other identifiers :param kwargs: additional named arguments passed on to `requests.get`, e.g., field queries (see examples) ...
[ "def", "registration_agency", "(", "self", ",", "ids", ",", "*", "*", "kwargs", ")", ":", "check_kwargs", "(", "[", "\"query\"", ",", "\"filter\"", ",", "\"offset\"", ",", "\"limit\"", ",", "\"sample\"", ",", "\"sort\"", ",", "\"order\"", ",", "\"facet\"", ...
39.357143
0.008857
def exec(self, payload: Log2ReqsAddOnPayload) -> TList[Request]: """Transform from json to Request Exception: ValueError: If path does not exist. """ try: return Request.from_jsonf_to_list(payload.file, encoding=self.config.encoding) except TypeError as e...
[ "def", "exec", "(", "self", ",", "payload", ":", "Log2ReqsAddOnPayload", ")", "->", "TList", "[", "Request", "]", ":", "try", ":", "return", "Request", ".", "from_jsonf_to_list", "(", "payload", ".", "file", ",", "encoding", "=", "self", ".", "config", "...
34.4
0.008499
def vpn_status(self): """Returns response dict""" # Start signal handler thread if it should be running if not self.check_pid and not self.thread_started: self._start_handler_thread() # Set color_bad as default output. Replaced if VPN active. name = None col...
[ "def", "vpn_status", "(", "self", ")", ":", "# Start signal handler thread if it should be running", "if", "not", "self", ".", "check_pid", "and", "not", "self", ".", "thread_started", ":", "self", ".", "_start_handler_thread", "(", ")", "# Set color_bad as default outp...
32.166667
0.001676
def _wall_post(session, owner_id, message=None, attachments=None, from_group=True): """ https://vk.com/dev/wall.post attachments: "photo100172_166443618,photo-1_265827614" """ response = session.fetch("wall.post", owner_id=owner_id, message=message, attachments=attachments, from_...
[ "def", "_wall_post", "(", "session", ",", "owner_id", ",", "message", "=", "None", ",", "attachments", "=", "None", ",", "from_group", "=", "True", ")", ":", "response", "=", "session", ".", "fetch", "(", "\"wall.post\"", ",", "owner_id", "=", "owner_id", ...
50.714286
0.01108
def _runner(self, job, runtime_context): """ Job running thread. """ try: job.run(runtime_context) except WorkflowException as err: _logger.exception("Got workflow error") self.exceptions.append(err) except Exception as err: # pylint: disable=broad-ex...
[ "def", "_runner", "(", "self", ",", "job", ",", "runtime_context", ")", ":", "try", ":", "job", ".", "run", "(", "runtime_context", ")", "except", "WorkflowException", "as", "err", ":", "_logger", ".", "exception", "(", "\"Got workflow error\"", ")", "self",...
47.823529
0.002413
def upsert_module_file(module_ident, fileid, filename): """Upsert a file associated with ``fileid`` with ``filename`` as a module_files entry associated with content at ``module_ident``. """ with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute("SELECT true F...
[ "def", "upsert_module_file", "(", "module_ident", ",", "fileid", ",", "filename", ")", ":", "with", "db_connect", "(", ")", "as", "db_conn", ":", "with", "db_conn", ".", "cursor", "(", ")", "as", "cursor", ":", "cursor", ".", "execute", "(", "\"SELECT true...
47.130435
0.000904
def comments_are_open(content_object): """ Return whether comments are still open for a given target object. """ moderator = get_model_moderator(content_object.__class__) if moderator is None: return True # Check the 'enable_field', 'auto_close_field' and 'close_after', # by reusing...
[ "def", "comments_are_open", "(", "content_object", ")", ":", "moderator", "=", "get_model_moderator", "(", "content_object", ".", "__class__", ")", "if", "moderator", "is", "None", ":", "return", "True", "# Check the 'enable_field', 'auto_close_field' and 'close_after',", ...
37.272727
0.002381
def generate_trajectory(group_membership, num_levels=4): """Return a single trajectory Return a single trajectory of size :math:`(g+1)`-by-:math:`k` where :math:`g` is the number of groups, and :math:`k` is the number of factors, both implied by the dimensions of `group_membership` Arguments ...
[ "def", "generate_trajectory", "(", "group_membership", ",", "num_levels", "=", "4", ")", ":", "delta", "=", "compute_delta", "(", "num_levels", ")", "# Infer number of groups `g` and number of params `k` from", "# `group_membership` matrix", "num_params", "=", "group_membersh...
30.574468
0.000674
def founditem_view(request, item_id): """View a founditem. id: founditem id """ founditem = get_object_or_404(FoundItem, id=item_id) return render(request, "itemreg/item_view.html", {"item": founditem, "type": "found"})
[ "def", "founditem_view", "(", "request", ",", "item_id", ")", ":", "founditem", "=", "get_object_or_404", "(", "FoundItem", ",", "id", "=", "item_id", ")", "return", "render", "(", "request", ",", "\"itemreg/item_view.html\"", ",", "{", "\"item\"", ":", "found...
29.25
0.008299
def _find_passwords(self, service, username, deleting=False): """Get password of the username for the service """ passwords = [] service = self._safe_string(service) username = self._safe_string(username) for attrs_tuple in (('username', 'service'), ('user', 'domain')): ...
[ "def", "_find_passwords", "(", "self", ",", "service", ",", "username", ",", "deleting", "=", "False", ")", ":", "passwords", "=", "[", "]", "service", "=", "self", ".", "_safe_string", "(", "service", ")", "username", "=", "self", ".", "_safe_string", "...
46.434783
0.001835
def generate(basename, xml_list): """Generate complete MAVLink Swift implemenation""" if os.path.isdir(basename): filename = os.path.join(basename, 'MAVLink.swift') else: filename = basename msgs = [] enums = [] filelist = [] for xml in xml_list: msgs.extend(xml.mes...
[ "def", "generate", "(", "basename", ",", "xml_list", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "basename", ")", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "basename", ",", "'MAVLink.swift'", ")", "else", ":", "filename", "...
30.222222
0.002375
def convert_cmd_scl(self, scl, cmd): """wrapping command in "scl enable" call and adds proper PATH """ # load default SCL prefix to PATH prefix = self.policy.get_default_scl_prefix() # read prefix from /etc/scl/prefixes/${scl} and strip trailing '\n' try: pref...
[ "def", "convert_cmd_scl", "(", "self", ",", "scl", ",", "cmd", ")", ":", "# load default SCL prefix to PATH", "prefix", "=", "self", ".", "policy", ".", "get_default_scl_prefix", "(", ")", "# read prefix from /etc/scl/prefixes/${scl} and strip trailing '\\n'", "try", ":",...
40.95
0.002387
def artUrl(self): """ Return the first first art url starting on the most specific for that item.""" art = self.firstAttr('art', 'grandparentArt') return self._server.url(art, includeToken=True) if art else None
[ "def", "artUrl", "(", "self", ")", ":", "art", "=", "self", ".", "firstAttr", "(", "'art'", ",", "'grandparentArt'", ")", "return", "self", ".", "_server", ".", "url", "(", "art", ",", "includeToken", "=", "True", ")", "if", "art", "else", "None" ]
58
0.012766
def update_frame(self): """ Define the view frame for this widgets""" d = self.declaration if d.x or d.y or d.width or d.height: self.frame = (d.x, d.y, d.width, d.height)
[ "def", "update_frame", "(", "self", ")", ":", "d", "=", "self", ".", "declaration", "if", "d", ".", "x", "or", "d", ".", "y", "or", "d", ".", "width", "or", "d", ".", "height", ":", "self", ".", "frame", "=", "(", "d", ".", "x", ",", "d", "...
40.6
0.009662
def fromDict(cls, d): """ Create a new instance from attribute values provided in a dictionary. @param d: A C{dict} with keys/values for the attributes of a new instance of this class. Keys 'id' and 'sequence' with C{str} values must be provided. A 'quality' C{str} key i...
[ "def", "fromDict", "(", "cls", ",", "d", ")", ":", "# Make a dummy instance whose attributes we can set explicitly.", "new", "=", "cls", "(", "AARead", "(", "''", ",", "''", ")", ",", "0", ",", "0", ",", "True", ",", "True", ")", "new", ".", "id", "=", ...
43.954545
0.002024
def read_config(): """Read configuration from setup.cfg.""" # XXX modifies global state, which is kind of evil config = ConfigParser.ConfigParser() config.read(['setup.cfg']) if not config.has_section('check-manifest'): return if (config.has_option('check-manifest', 'ignore-default-rules...
[ "def", "read_config", "(", ")", ":", "# XXX modifies global state, which is kind of evil", "config", "=", "ConfigParser", ".", "ConfigParser", "(", ")", "config", ".", "read", "(", "[", "'setup.cfg'", "]", ")", "if", "not", "config", ".", "has_section", "(", "'c...
46.642857
0.001502
def run(self, cmd, user='root', sudo=False, ignore_error=False, success_status=(0,), error_callback=None, custom_log=None, retry=0): """Run a command on the remote host. """ self.enable_user(user) return self.ssh_pool.run( user, cmd, sudo=sudo, ignore_error=ignore...
[ "def", "run", "(", "self", ",", "cmd", ",", "user", "=", "'root'", ",", "sudo", "=", "False", ",", "ignore_error", "=", "False", ",", "success_status", "=", "(", "0", ",", ")", ",", "error_callback", "=", "None", ",", "custom_log", "=", "None", ",", ...
49
0.008909