text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def copy_resource_dir(src, dest): """ To copy package data directory to destination """ package_name = "mocha" dest = (dest + "/" + os.path.basename(src)).rstrip("/") if pkg_resources.resource_isdir(package_name, src): if not os.path.isdir(dest): os.makedirs(dest) for...
[ "def", "copy_resource_dir", "(", "src", ",", "dest", ")", ":", "package_name", "=", "\"mocha\"", "dest", "=", "(", "dest", "+", "\"/\"", "+", "os", ".", "path", ".", "basename", "(", "src", ")", ")", ".", "rstrip", "(", "\"/\"", ")", "if", "pkg_resou...
39.142857
13.571429
def format_name(self): """Formats the media file based on enhanced metadata. The actual name of the file and even the name of the directory structure where the file is to be stored. """ self.formatted_filename = formatter.format_filename( self.series_name, self.seaso...
[ "def", "format_name", "(", "self", ")", ":", "self", ".", "formatted_filename", "=", "formatter", ".", "format_filename", "(", "self", ".", "series_name", ",", "self", ".", "season_number", ",", "self", ".", "episode_numbers", ",", "self", ".", "episode_names"...
40.666667
18
def _proxy_kwargs(browser_name, proxy, browser_kwargs={}): # pylint: disable=dangerous-default-value """ Determines the kwargs needed to set up a proxy based on the browser type. Returns: a dictionary of arguments needed to pass when instantiating the WebDriver instance. """ proxy_dic...
[ "def", "_proxy_kwargs", "(", "browser_name", ",", "proxy", ",", "browser_kwargs", "=", "{", "}", ")", ":", "# pylint: disable=dangerous-default-value", "proxy_dict", "=", "{", "\"httpProxy\"", ":", "proxy", ".", "proxy", ",", "\"proxyType\"", ":", "'manual'", ",",...
35.037037
22.888889
def add_event(request): """ Public form to add an event. """ form = AddEventForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.sites = settings.SITE_ID instance.submitted_by = request.user instance.approved = True instance.slug ...
[ "def", "add_event", "(", "request", ")", ":", "form", "=", "AddEventForm", "(", "request", ".", "POST", "or", "None", ")", "if", "form", ".", "is_valid", "(", ")", ":", "instance", "=", "form", ".", "save", "(", "commit", "=", "False", ")", "instance...
37.6875
12.1875
def delete(self): """Delete a file. The base directory is also removed, as it is assumed that only one file exists in the directory. """ fs, path = self._get_fs(create_dir=False) if fs.exists(path): fs.remove(path) if self.clean_dir and fs.exists('.')...
[ "def", "delete", "(", "self", ")", ":", "fs", ",", "path", "=", "self", ".", "_get_fs", "(", "create_dir", "=", "False", ")", "if", "fs", ".", "exists", "(", "path", ")", ":", "fs", ".", "remove", "(", "path", ")", "if", "self", ".", "clean_dir",...
30
15.166667
def merge_list(self, new_list): """Add new CM servers to the list :param new_list: a list of ``(ip, port)`` tuples :type new_list: :class:`list` """ total = len(self.list) for ip, port in new_list: if (ip, port) not in self.list: self.mark_go...
[ "def", "merge_list", "(", "self", ",", "new_list", ")", ":", "total", "=", "len", "(", "self", ".", "list", ")", "for", "ip", ",", "port", "in", "new_list", ":", "if", "(", "ip", ",", "port", ")", "not", "in", "self", ".", "list", ":", "self", ...
31.571429
15.714286
def next_frame_ae(): """Conv autoencoder.""" hparams = next_frame_basic_deterministic() hparams.bottom["inputs"] = modalities.video_bitwise_bottom hparams.top["inputs"] = modalities.video_top hparams.hidden_size = 256 hparams.batch_size = 8 hparams.num_hidden_layers = 4 hparams.num_compress_steps = 4 ...
[ "def", "next_frame_ae", "(", ")", ":", "hparams", "=", "next_frame_basic_deterministic", "(", ")", "hparams", ".", "bottom", "[", "\"inputs\"", "]", "=", "modalities", ".", "video_bitwise_bottom", "hparams", ".", "top", "[", "\"inputs\"", "]", "=", "modalities",...
31.636364
12.454545
def ISSO_eq_at_pole(r, chi): """ Polynomial that enables the calculation of the Kerr polar (inclination = +/- pi/2) innermost stable spherical orbit (ISSO) radius via its roots. Physical solutions are between 6 and 1+sqrt[3]+sqrt[3+2sqrt[3]]. Parameters ----------- r: float the...
[ "def", "ISSO_eq_at_pole", "(", "r", ",", "chi", ")", ":", "return", "r", "**", "3", "*", "(", "r", "**", "2", "*", "(", "r", "-", "6", ")", "+", "chi", "**", "2", "*", "(", "3", "*", "r", "+", "4", ")", ")", "+", "chi", "**", "4", "*", ...
28.9
20.5
def get_form(self, form_class=None): """Get form for model""" form = super().get_form(form_class) if not getattr(form, 'helper', None): form.helper = FormHelper() form.helper.form_tag = False else: form.helper.form_tag = False return form
[ "def", "get_form", "(", "self", ",", "form_class", "=", "None", ")", ":", "form", "=", "super", "(", ")", ".", "get_form", "(", "form_class", ")", "if", "not", "getattr", "(", "form", ",", "'helper'", ",", "None", ")", ":", "form", ".", "helper", "...
30.6
10.2
def setup_menu(self, minmax): """Setup context menu""" if self.minmax_action is not None: self.minmax_action.setChecked(minmax) return resize_action = create_action(self, _("Resize rows to contents"), triggered=self.re...
[ "def", "setup_menu", "(", "self", ",", "minmax", ")", ":", "if", "self", ".", "minmax_action", "is", "not", "None", ":", "self", ".", "minmax_action", ".", "setChecked", "(", "minmax", ")", "return", "resize_action", "=", "create_action", "(", "self", ",",...
57.5
21.279412
def asizeof(*objs, **opts): '''Return the combined size in bytes of all objects passed as positional argments. The available options and defaults are the following. *align=8* -- size alignment *all=False* -- all current objects *clip=80* -- clip ``repr()`` strings ...
[ "def", "asizeof", "(", "*", "objs", ",", "*", "*", "opts", ")", ":", "t", ",", "p", "=", "_objs_opts", "(", "objs", ",", "*", "*", "opts", ")", "if", "t", ":", "_asizer", ".", "reset", "(", "*", "*", "p", ")", "s", "=", "_asizer", ".", "asi...
34.542857
24.057143
def underflow(self, axis=0): """ Return the underflow for the given axis. Depending on the dimension of the histogram, may return an array. """ if axis not in range(3): raise ValueError("axis must be 0, 1, or 2") if self.DIM == 1: return self.GetB...
[ "def", "underflow", "(", "self", ",", "axis", "=", "0", ")", ":", "if", "axis", "not", "in", "range", "(", "3", ")", ":", "raise", "ValueError", "(", "\"axis must be 0, 1, or 2\"", ")", "if", "self", ".", "DIM", "==", "1", ":", "return", "self", ".",...
34.4
14.2
def get_workspace_config(namespace, workspace, cnamespace, config): """Get method configuration in workspace. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name cnamespace (str): Config namespace config (str): Config name Swagger: ...
[ "def", "get_workspace_config", "(", "namespace", ",", "workspace", ",", "cnamespace", ",", "config", ")", ":", "uri", "=", "\"workspaces/{0}/{1}/method_configs/{2}/{3}\"", ".", "format", "(", "namespace", ",", "workspace", ",", "cnamespace", ",", "config", ")", "r...
35.125
22.625
def post_url(self, url, token='', json=None, data=None, headers=None): """ Returns a post resquest object taking in a url, user token, and possible json information. Arguments: url (str): The url to make post to token (str): The authentication token j...
[ "def", "post_url", "(", "self", ",", "url", ",", "token", "=", "''", ",", "json", "=", "None", ",", "data", "=", "None", ",", "headers", "=", "None", ")", ":", "if", "(", "token", "==", "''", ")", ":", "token", "=", "self", ".", "_user_token", ...
32.428571
16.028571
def list(self, date_created_before=values.unset, date_created=values.unset, date_created_after=values.unset, date_updated_before=values.unset, date_updated=values.unset, date_updated_after=values.unset, friendly_name=values.unset, status=values.unset, limit=None, page...
[ "def", "list", "(", "self", ",", "date_created_before", "=", "values", ".", "unset", ",", "date_created", "=", "values", ".", "unset", ",", "date_created_after", "=", "values", ".", "unset", ",", "date_updated_before", "=", "values", ".", "unset", ",", "date...
58.475
28.875
def get_repository_method_acl(namespace, method, snapshot_id): """Get permissions for a method. The method should exist in the methods repository. Args: namespace (str): Methods namespace method (str): method name version (int): snapshot_id of the method Swagger: https...
[ "def", "get_repository_method_acl", "(", "namespace", ",", "method", ",", "snapshot_id", ")", ":", "uri", "=", "\"methods/{0}/{1}/{2}/permissions\"", ".", "format", "(", "namespace", ",", "method", ",", "snapshot_id", ")", "return", "__get", "(", "uri", ")" ]
31.4
21.2
def add_environment_vars(config: MutableMapping[str, Any]): """Override config with environment variables Environment variables have to be prefixed with BELBIO_ which will be stripped before splitting on '__' and lower-casing the environment variable name that is left into keys for the config dicti...
[ "def", "add_environment_vars", "(", "config", ":", "MutableMapping", "[", "str", ",", "Any", "]", ")", ":", "# TODO need to redo config - can't add value to dictionary without recursively building up the dict", "# check into config libraries again", "for", "e", "in", "os"...
41.342857
21
def _get_qtyprc(self, n_points=6): """ Returns a list of tuples of the form (qty, prc) created from the cost function. If the cost function is polynomial it will be converted to piece-wise linear using poly_to_pwl(n_points). """ if self.pcost_model == POLYNOMIAL: # C...
[ "def", "_get_qtyprc", "(", "self", ",", "n_points", "=", "6", ")", ":", "if", "self", ".", "pcost_model", "==", "POLYNOMIAL", ":", "# Convert polynomial cost function to piece-wise linear.", "self", ".", "poly_to_pwl", "(", "n_points", ")", "n_segments", "=", "len...
30.913043
17.391304
async def has_started(self): """ Whether the handler has completed all start up processes such as establishing the connection, session, link and authentication, and is not ready to process messages. **This function is now deprecated and will be removed in v2.0+.** :rtype...
[ "async", "def", "has_started", "(", "self", ")", ":", "# pylint: disable=protected-access", "timeout", "=", "False", "auth_in_progress", "=", "False", "if", "self", ".", "_handler", ".", "_connection", ".", "cbs", ":", "timeout", ",", "auth_in_progress", "=", "a...
37.238095
17.428571
def contents_size(self): ''' Returns the number of different categories to be shown in the contents side-bar in the HTML documentation. ''' count = 0 if hasattr(self,'variables'): count += 1 if hasattr(self,'types'): count += 1 if hasattr(self,'modules'): ...
[ "def", "contents_size", "(", "self", ")", ":", "count", "=", "0", "if", "hasattr", "(", "self", ",", "'variables'", ")", ":", "count", "+=", "1", "if", "hasattr", "(", "self", ",", "'types'", ")", ":", "count", "+=", "1", "if", "hasattr", "(", "sel...
43.346154
12.346154
def map(*args): """ this map works just like the builtin.map, except, this one you can also: - give it multiple functions to map over an iterable - give it a single function with multiple arguments to run a window based map operation over an iterable """ functions_to_apply = [i fo...
[ "def", "map", "(", "*", "args", ")", ":", "functions_to_apply", "=", "[", "i", "for", "i", "in", "args", "if", "callable", "(", "i", ")", "]", "iterables_to_run", "=", "[", "i", "for", "i", "in", "args", "if", "not", "callable", "(", "i", ")", "]...
49.575758
23.424242
def predict_noiseless(self, Xnew, full_cov=False, kern=None): """ Predict the underlying function f at the new point(s) Xnew. :param Xnew: The points at which to make a prediction :type Xnew: np.ndarray (Nnew x self.input_dim) :param full_cov: whether to return the full covaria...
[ "def", "predict_noiseless", "(", "self", ",", "Xnew", ",", "full_cov", "=", "False", ",", "kern", "=", "None", ")", ":", "# Predict the latent function values", "mu", ",", "var", "=", "self", ".", "_raw_predict", "(", "Xnew", ",", "full_cov", "=", "full_cov"...
47
28.384615
def resolve_realms(self, attributes): """ The format of realm settings is: {'name_of_realm': {'cls': 'location to realm class', 'account_store': 'location to realm account_store class'}} - 'name of realm' is a label used for internal tracking ...
[ "def", "resolve_realms", "(", "self", ",", "attributes", ")", ":", "realms", "=", "[", "]", "for", "realm", ",", "realm_attributes", "in", "attributes", "[", "'realms'", "]", ".", "items", "(", ")", ":", "realm_cls", "=", "maybe_resolve", "(", "realm", "...
43.918919
26.351351
def _padding_model_number(number, max_num): ''' This method returns a zero-front padded string It makes out of str(45) -> '0045' if 999 < max_num < 10000. This is meant to work for reasonable integers (maybe less than 10^6). Parameters ---------- number : integer number that the st...
[ "def", "_padding_model_number", "(", "number", ",", "max_num", ")", ":", "cnum", "=", "str", "(", "number", ")", "clen", "=", "len", "(", "cnum", ")", "cmax", "=", "int", "(", "log10", "(", "max_num", ")", ")", "+", "1", "return", "(", "cmax", "-",...
24.5
25.045455
def create_function_f_c(self): """condition function""" return ca.Function( 'f_c', [self.t, self.x, self.y, self.m, self.p, self.ng, self.nu], [self.f_c], ['t', 'x', 'y', 'm', 'p', 'ng', 'nu'], ['c'], self.func_opt)
[ "def", "create_function_f_c", "(", "self", ")", ":", "return", "ca", ".", "Function", "(", "'f_c'", ",", "[", "self", ".", "t", ",", "self", ".", "x", ",", "self", ".", "y", ",", "self", ".", "m", ",", "self", ".", "p", ",", "self", ".", "ng", ...
39
17.857143
def multinomial_resample(weights): """ This is the naive form of roulette sampling where we compute the cumulative sum of the weights and then use binary search to select the resampled point based on a uniformly distributed random number. Run time is O(n log n). You do not want to use this algorithm in ...
[ "def", "multinomial_resample", "(", "weights", ")", ":", "cumulative_sum", "=", "np", ".", "cumsum", "(", "weights", ")", "cumulative_sum", "[", "-", "1", "]", "=", "1.", "# avoid round-off errors: ensures sum is exactly one", "return", "np", ".", "searchsorted", ...
36.791667
24.416667
def db_exists(cls, impl, working_dir): """ Does the chainstate db exist? """ path = config.get_snapshots_filename(impl, working_dir) return os.path.exists(path)
[ "def", "db_exists", "(", "cls", ",", "impl", ",", "working_dir", ")", ":", "path", "=", "config", ".", "get_snapshots_filename", "(", "impl", ",", "working_dir", ")", "return", "os", ".", "path", ".", "exists", "(", "path", ")" ]
32.5
5.5
def y0(self): """Y-axis coordinate of the first data point :type: `~astropy.units.Quantity` scalar """ try: return self._y0 except AttributeError: self._y0 = Quantity(0, self.yunit) return self._y0
[ "def", "y0", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_y0", "except", "AttributeError", ":", "self", ".", "_y0", "=", "Quantity", "(", "0", ",", "self", ".", "yunit", ")", "return", "self", ".", "_y0" ]
26.5
14.4
def uservoice(parser, token): """ UserVoice tracking template tag. Renders Javascript code to track page visits. You must supply your UserVoice Widget Key in the ``USERVOICE_WIDGET_KEY`` setting or the ``uservoice_widget_key`` template context variable. """ bits = token.split_contents() ...
[ "def", "uservoice", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", ">", "1", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes no arguments\"", "%", "bits", "[", "0", "]"...
35.5
16.833333
def _spill(self): """ dump already partitioned data into disks. """ global MemoryBytesSpilled, DiskBytesSpilled path = self._get_spill_dir(self.spills) if not os.path.exists(path): os.makedirs(path) used_memory = get_used_memory() if not self....
[ "def", "_spill", "(", "self", ")", ":", "global", "MemoryBytesSpilled", ",", "DiskBytesSpilled", "path", "=", "self", ".", "_get_spill_dir", "(", "self", ".", "spills", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "os", "....
41.431034
18.637931
def rsdl_sn(self, U): """Compute dual residual normalisation term. Overriding this method is required if methods :meth:`cnst_A`, :meth:`cnst_AT`, :meth:`cnst_B`, and :meth:`cnst_c` are not overridden. """ return self.rho * np.linalg.norm(self.cnst_AT(U))
[ "def", "rsdl_sn", "(", "self", ",", "U", ")", ":", "return", "self", ".", "rho", "*", "np", ".", "linalg", ".", "norm", "(", "self", ".", "cnst_AT", "(", "U", ")", ")" ]
32.888889
21.444444
def _process_wildtypes(self, limit=None): """ This table provides the genotype IDs, name, and abbreviation of the wildtype genotypes. These are the typical genomic backgrounds...there's about 20 of them. http://zfin.org/downloads/wildtypes_fish.txt Triples created: ...
[ "def", "_process_wildtypes", "(", "self", ",", "limit", "=", "None", ")", ":", "if", "self", ".", "test_mode", ":", "graph", "=", "self", ".", "testgraph", "else", ":", "graph", "=", "self", ".", "graph", "# model = Model(graph) # unused", "LOG", ".", "in...
40.155172
21.5
def _compute_mixing_probabilities(self): """ Compute the mixing probability for each filter. """ self.cbar = dot(self.mu, self.M) for i in range(self.N): for j in range(self.N): self.omega[i, j] = (self.M[i, j]*self.mu[i]) / self.cbar[j]
[ "def", "_compute_mixing_probabilities", "(", "self", ")", ":", "self", ".", "cbar", "=", "dot", "(", "self", ".", "mu", ",", "self", ".", "M", ")", "for", "i", "in", "range", "(", "self", ".", "N", ")", ":", "for", "j", "in", "range", "(", "self"...
33.111111
11.555556
def multi_mask_sequences(records, slices): """ Replace characters sliced by slices with gap characters. """ for record in records: record_indices = list(range(len(record))) keep_indices = reduce(lambda i, s: i - frozenset(record_indices[s]), slices, frozense...
[ "def", "multi_mask_sequences", "(", "records", ",", "slices", ")", ":", "for", "record", "in", "records", ":", "record_indices", "=", "list", "(", "range", "(", "len", "(", "record", ")", ")", ")", "keep_indices", "=", "reduce", "(", "lambda", "i", ",", ...
41.166667
14.166667
def get_access_information(self, code, # pylint: disable=W0221 update_session=True): """Return the access information for an OAuth2 authorization grant. :param code: the code received in the request from the OAuth2 server :param update_session: Update the current...
[ "def", "get_access_information", "(", "self", ",", "code", ",", "# pylint: disable=W0221", "update_session", "=", "True", ")", ":", "retval", "=", "super", "(", "AuthenticatedReddit", ",", "self", ")", ".", "get_access_information", "(", "code", ")", "if", "upda...
46.6875
22.8125
def _launch_process_group(self, process_commands, streams_path): """ Launches processes defined by process_commands, but only executes max_concurrency processes at a time; if a process completes and there are still outstanding processes to be executed, the next processes are run ...
[ "def", "_launch_process_group", "(", "self", ",", "process_commands", ",", "streams_path", ")", ":", "processes", "=", "{", "}", "def", "check_complete_processes", "(", "wait", "=", "False", ")", ":", "\"\"\"\n Returns True if a process completed, False otherwi...
46.826923
17.288462
def _call(self, resource, params): """Call to get a resource. :param method: resource to get :param params: dict with the HTTP parameters needed to get the given resource """ url = self.URL % {'base': self.base_url, 'resource': resource} if self.api_token: ...
[ "def", "_call", "(", "self", ",", "resource", ",", "params", ")", ":", "url", "=", "self", ".", "URL", "%", "{", "'base'", ":", "self", ".", "base_url", ",", "'resource'", ":", "resource", "}", "if", "self", ".", "api_token", ":", "params", "[", "s...
29.888889
19.722222
def unarchive(self, experiments=None, archive=None, complete=False, project_data=False, replace_project_config=False, root=None, projectname=None, fmt=None, force=False, **kwargs): """ Extract archived experiments Parameters ---------- experim...
[ "def", "unarchive", "(", "self", ",", "experiments", "=", "None", ",", "archive", "=", "None", ",", "complete", "=", "False", ",", "project_data", "=", "False", ",", "replace_project_config", "=", "False", ",", "root", "=", "None", ",", "projectname", "=",...
42.307692
20.758974
def tailf( filepath, lastn=0, timeout=60, stopon=None, encoding="utf8", delay=0.1 ): """provide a `tail -f` like function :param filepath: file to tail -f, absolute path or relative path :param lastn: lastn line will also be yield :param timeout: (optional) stop tail -f ...
[ "def", "tailf", "(", "filepath", ",", "lastn", "=", "0", ",", "timeout", "=", "60", ",", "stopon", "=", "None", ",", "encoding", "=", "\"utf8\"", ",", "delay", "=", "0.1", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "filepath", ...
32.015385
20.030769
def matmul(a, b, output_shape=None, reduced_dims=None, name=None): """Alias for einsum([a, b]).""" return einsum( [a, b], output_shape=output_shape, reduced_dims=reduced_dims, name=name)
[ "def", "matmul", "(", "a", ",", "b", ",", "output_shape", "=", "None", ",", "reduced_dims", "=", "None", ",", "name", "=", "None", ")", ":", "return", "einsum", "(", "[", "a", ",", "b", "]", ",", "output_shape", "=", "output_shape", ",", "reduced_dim...
48.25
22
def get_asn_whois(self, retry_count=3): """ The function for retrieving ASN information for an IP address from Cymru via port 43/tcp (WHOIS). Args: retry_count (:obj:`int`): The number of times to retry in case socket errors, timeouts, connection resets, etc....
[ "def", "get_asn_whois", "(", "self", ",", "retry_count", "=", "3", ")", ":", "try", ":", "# Create the connection for the Cymru whois query.", "conn", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "conn", ...
28
23.2
def value_to_db(self, value): """ Returns field's single value prepared for saving into a database. """ assert isinstance(value, datetime.datetime) try: value = value - datetime.datetime(1970, 1, 1) except OverflowError: raise tldap.exceptions.ValidationError("is...
[ "def", "value_to_db", "(", "self", ",", "value", ")", ":", "assert", "isinstance", "(", "value", ",", "datetime", ".", "datetime", ")", "try", ":", "value", "=", "value", "-", "datetime", ".", "datetime", "(", "1970", ",", "1", ",", "1", ")", "except...
34.307692
20.384615
def render(self, url, template=None, expiration=0): """ Render feed template """ template = template or self.default_template return render_to_string(template, self.get_context(url, expiration))
[ "def", "render", "(", "self", ",", "url", ",", "template", "=", "None", ",", "expiration", "=", "0", ")", ":", "template", "=", "template", "or", "self", ".", "default_template", "return", "render_to_string", "(", "template", ",", "self", ".", "get_context...
33.857143
14.714286
def remove(self, param, author=None): """Remove by url or name""" if isinstance(param, SkillEntry): skill = param else: skill = self.find_skill(param, author) skill.remove() skills = [s for s in self.skills_data['skills'] if s['name'] != ...
[ "def", "remove", "(", "self", ",", "param", ",", "author", "=", "None", ")", ":", "if", "isinstance", "(", "param", ",", "SkillEntry", ")", ":", "skill", "=", "param", "else", ":", "skill", "=", "self", ".", "find_skill", "(", "param", ",", "author",...
34.545455
11.181818
def custom_indicator_class_factory(indicator_type, base_class, class_dict, value_fields): """Internal method for dynamically building Custom Indicator Class.""" value_count = len(value_fields) def init_1(self, tcex, value1, xid, **kwargs): # pylint: disable=W0641 """Init method for Custom Indicato...
[ "def", "custom_indicator_class_factory", "(", "indicator_type", ",", "base_class", ",", "class_dict", ",", "value_fields", ")", ":", "value_count", "=", "len", "(", "value_fields", ")", "def", "init_1", "(", "self", ",", "tcex", ",", "value1", ",", "xid", ",",...
53.517241
24.241379
def delete(self, path=None, url_kwargs=None, **kwargs): """ Sends a PUT request. :param path: The HTTP path (either absolute or relative). :param url_kwargs: Parameters to override in the generated URL. See `~hyperlink.URL`. :param **kwargs: O...
[ "def", "delete", "(", "self", ",", "path", "=", "None", ",", "url_kwargs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_session", ".", "delete", "(", "self", ".", "_url", "(", "path", ",", "url_kwargs", ")", ",", "*", ...
36.076923
17.461538
def ts_describe(self, transport, table): """ ts_describe(table) Retrieve a time series table description from the Riak cluster. .. note:: This request is automatically retried :attr:`retries` times if it fails due to network error. :param table: The timeseries table...
[ "def", "ts_describe", "(", "self", ",", "transport", ",", "table", ")", ":", "t", "=", "table", "if", "isinstance", "(", "t", ",", "six", ".", "string_types", ")", ":", "t", "=", "Table", "(", "self", ",", "table", ")", "return", "transport", ".", ...
34.058824
16.764706
def get_server_premaster_secret(self, password_verifier, server_private, client_public, common_secret): """S = (A * v^u) ^ b % N :param int password_verifier: :param int server_private: :param int client_public: :param int common_secret: :rtype: int """ r...
[ "def", "get_server_premaster_secret", "(", "self", ",", "password_verifier", ",", "server_private", ",", "client_public", ",", "common_secret", ")", ":", "return", "pow", "(", "(", "client_public", "*", "pow", "(", "password_verifier", ",", "common_secret", ",", "...
41.9
22.4
def update_token(self): """ Get token from key and secret """ headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Basic ' + base64.b64encode( (self._key + ':' + self._secret).encode()).decode() } data = {'grant_ty...
[ "def", "update_token", "(", "self", ")", ":", "headers", "=", "{", "'Content-Type'", ":", "'application/x-www-form-urlencoded'", ",", "'Authorization'", ":", "'Basic '", "+", "base64", ".", "b64encode", "(", "(", "self", ".", "_key", "+", "':'", "+", "self", ...
41.133333
17.066667
def get_transaction(self, tx_hash, id=None, endpoint=None): """ Look up a transaction by hash. Args: tx_hash: (str) hash in the form '58c634f81fbd4ae2733d7e3930a9849021840fc19dc6af064d6f2812a333f91d' id: (int, optional) id to use for response tracking endpoint...
[ "def", "get_transaction", "(", "self", ",", "tx_hash", ",", "id", "=", "None", ",", "endpoint", "=", "None", ")", ":", "return", "self", ".", "_call_endpoint", "(", "GET_RAW_TRANSACTION", ",", "params", "=", "[", "tx_hash", ",", "1", "]", ",", "id", "=...
45.416667
25.75
def normalizedFluctuationCorrelationFunction(A_n, B_n=None, N_max=None, norm=True): """Compute the normalized fluctuation (cross) correlation function of (two) stationary timeseries. C(t) = (<A(t) B(t)> - <A><B>) / (<AB> - <A><B>) This may be useful in diagnosing odd time-correlations in timeseries data. ...
[ "def", "normalizedFluctuationCorrelationFunction", "(", "A_n", ",", "B_n", "=", "None", ",", "N_max", "=", "None", ",", "norm", "=", "True", ")", ":", "# If B_n is not specified, set it to be identical to A_n.", "if", "B_n", "is", "None", ":", "B_n", "=", "A_n", ...
35.115789
28.515789
def lockfile(lockfile_name, lock_wait_timeout=-1): """ Only runs the method if the lockfile is not acquired. You should create a setting ``LOCKFILE_PATH`` which points to ``/home/username/tmp/``. In your management command, use it like so:: LOCKFILE = os.path.join( settings.LO...
[ "def", "lockfile", "(", "lockfile_name", ",", "lock_wait_timeout", "=", "-", "1", ")", ":", "def", "decorator", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "lock", "=...
28.536585
18.04878
def unite_dataset(dataset, basecolumn, fn=None): """ Unite dataset via fn Parameters ---------- dataset : list A list of data basecolumn : int A number of column which will be respected in uniting dataset fn : function A function which recieve :attr:`data` and return...
[ "def", "unite_dataset", "(", "dataset", ",", "basecolumn", ",", "fn", "=", "None", ")", ":", "# create default unite_fn", "if", "fn", "is", "None", ":", "fn", "=", "default_unite_function", "# classify dataset via unite_fn", "united_dataset", "=", "OrderedDict", "("...
32.692308
17.923077
def cache2errors(function, cache, disp=0, ftol=0.05): """ This function will attempt to identify 1 sigma errors, assuming your function is a chi^2. For this, the 1-sigma is bracketed. If you were smart enough to build a cache list of [x,y] into your function, you can pass it here. The values bracketing 1 sigma w...
[ "def", "cache2errors", "(", "function", ",", "cache", ",", "disp", "=", "0", ",", "ftol", "=", "0.05", ")", ":", "vals", "=", "numpy", ".", "array", "(", "sorted", "(", "cache", ",", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ")", ")",...
29.98913
20.815217
def draw_heatmap_array(self, image_shape, alpha_lines=1.0, alpha_points=1.0, size_lines=1, size_points=0, antialiased=True, raise_if_out_of_image=False): """ Draw the line segments and points of the line string as a heatmap array. Parameters...
[ "def", "draw_heatmap_array", "(", "self", ",", "image_shape", ",", "alpha_lines", "=", "1.0", ",", "alpha_points", "=", "1.0", ",", "size_lines", "=", "1", ",", "size_points", "=", "0", ",", "antialiased", "=", "True", ",", "raise_if_out_of_image", "=", "Fal...
34.810345
20.568966
def update(): # type: () -> None """ Update the feature with updates committed to develop. This will merge current develop into the current branch. """ branch = git.current_branch(refresh=True) develop = conf.get('git.devel_branch', 'develop') common.assert_branch_type('feature') commo...
[ "def", "update", "(", ")", ":", "# type: () -> None", "branch", "=", "git", ".", "current_branch", "(", "refresh", "=", "True", ")", "develop", "=", "conf", ".", "get", "(", "'git.devel_branch'", ",", "'develop'", ")", "common", ".", "assert_branch_type", "(...
31.357143
13.5
def traverse_json_obj(obj, path=None, callback=None): """ Recursively loop through object and perform the function defined in callback for every element. Only JSON data types are supported. :param obj: object to traverse :param path: current path :param callback: callback executed on every eleme...
[ "def", "traverse_json_obj", "(", "obj", ",", "path", "=", "None", ",", "callback", "=", "None", ")", ":", "if", "path", "is", "None", ":", "path", "=", "[", "]", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "value", "=", "{", "k", ":", ...
31.5
16.75
def element(self, inp=None): """Return an element from ``inp`` or from scratch.""" if inp is not None: s = str(inp)[:self.length] s += ' ' * (self.length - len(s)) return s else: return ' ' * self.length
[ "def", "element", "(", "self", ",", "inp", "=", "None", ")", ":", "if", "inp", "is", "not", "None", ":", "s", "=", "str", "(", "inp", ")", "[", ":", "self", ".", "length", "]", "s", "+=", "' '", "*", "(", "self", ".", "length", "-", "len", ...
33.5
10.375
def put_message(self, queue_name, content, visibility_timeout=None, time_to_live=None, timeout=None): ''' Adds a new message to the back of the message queue. The visibility timeout specifies the time that the message will be invisible. After the timeout expires, t...
[ "def", "put_message", "(", "self", ",", "queue_name", ",", "content", ",", "visibility_timeout", "=", "None", ",", "time_to_live", "=", "None", ",", "timeout", "=", "None", ")", ":", "_validate_encryption_required", "(", "self", ".", "require_encryption", ",", ...
49.698413
27.349206
def wrap_args_with_ssh_agent(self, args, ssh_key_path, ssh_auth_sock=None, silence_ssh_add=False): """ Given an existing command line and parameterization this will return the same command line wrapped with the necessary calls to ``ssh-agent`` """ if ssh_key_path: ssh...
[ "def", "wrap_args_with_ssh_agent", "(", "self", ",", "args", ",", "ssh_key_path", ",", "ssh_auth_sock", "=", "None", ",", "silence_ssh_add", "=", "False", ")", ":", "if", "ssh_key_path", ":", "ssh_add_command", "=", "args2cmdline", "(", "'ssh-add'", ",", "ssh_ke...
47.882353
18.941176
def filter_roidb(self): """Remove images without usable rois""" num_roidb = len(self._roidb) self._roidb = [roi_rec for roi_rec in self._roidb if len(roi_rec['gt_classes'])] num_after = len(self._roidb) logger.info('filter roidb: {} -> {}'.format(num_roidb, num_after))
[ "def", "filter_roidb", "(", "self", ")", ":", "num_roidb", "=", "len", "(", "self", ".", "_roidb", ")", "self", ".", "_roidb", "=", "[", "roi_rec", "for", "roi_rec", "in", "self", ".", "_roidb", "if", "len", "(", "roi_rec", "[", "'gt_classes'", "]", ...
50.666667
17.833333
def CargarFormatoPDF(self, archivo="liquidacion_form_c1116b_wslpg.csv"): "Cargo el formato de campos a generar desde una planilla CSV" # si no encuentro archivo, lo busco en el directorio predeterminado: if not os.path.exists(archivo): archivo = os.path.join(self.InstallDir, "planti...
[ "def", "CargarFormatoPDF", "(", "self", ",", "archivo", "=", "\"liquidacion_form_c1116b_wslpg.csv\"", ")", ":", "# si no encuentro archivo, lo busco en el directorio predeterminado:", "if", "not", "os", ".", "path", ".", "exists", "(", "archivo", ")", ":", "archivo", "=...
38.76087
21.195652
def calculate_error_by_annotation(graph: BELGraph, annotation: str) -> Mapping[str, List[str]]: """Group error names by a given annotation.""" results = defaultdict(list) for _, exc, ctx in graph.warnings: if not ctx or not edge_has_annotation(ctx, annotation): continue values ...
[ "def", "calculate_error_by_annotation", "(", "graph", ":", "BELGraph", ",", "annotation", ":", "str", ")", "->", "Mapping", "[", "str", ",", "List", "[", "str", "]", "]", ":", "results", "=", "defaultdict", "(", "list", ")", "for", "_", ",", "exc", ","...
33
21.333333
def configure(self): """Configure the device. Send the device configuration saved inside the MCP342x object to the target device.""" logger.debug('Configuring ' + hex(self.get_address()) + ' ch: ' + str(self.get_channel()) + ' res: ' + str(self.get_reso...
[ "def", "configure", "(", "self", ")", ":", "logger", ".", "debug", "(", "'Configuring '", "+", "hex", "(", "self", ".", "get_address", "(", ")", ")", "+", "' ch: '", "+", "str", "(", "self", ".", "get_channel", "(", ")", ")", "+", "' res: '", "+", ...
48.111111
16.333333
def setup_local_logging(config=None, parallel=None): """Setup logging for a local context, directing messages to appropriate base loggers. Handles local, multiprocessing and distributed setup, connecting to handlers created by the base logger. """ if config is None: config = {} if parallel is N...
[ "def", "setup_local_logging", "(", "config", "=", "None", ",", "parallel", "=", "None", ")", ":", "if", "config", "is", "None", ":", "config", "=", "{", "}", "if", "parallel", "is", "None", ":", "parallel", "=", "{", "}", "parallel_type", "=", "paralle...
42.75
16.65
def _get_query_parts(self, query_str, search_options=None): """ Split a query string into its parts """ if search_options is None: search_options = {} if query_str is None: raise NipapValueError("'query_string' must not be None") # find query parts ...
[ "def", "_get_query_parts", "(", "self", ",", "query_str", ",", "search_options", "=", "None", ")", ":", "if", "search_options", "is", "None", ":", "search_options", "=", "{", "}", "if", "query_str", "is", "None", ":", "raise", "NipapValueError", "(", "\"'que...
33.964286
19.821429
def doc_unwrap(raw_doc): """ Applies two transformations to raw_doc: 1. N consecutive newlines are converted into N-1 newlines. 2. A lone newline is converted to a space, which basically unwraps text. Returns a new string, or None if the input was None. """ if raw_doc is None: retur...
[ "def", "doc_unwrap", "(", "raw_doc", ")", ":", "if", "raw_doc", "is", "None", ":", "return", "None", "docstring", "=", "''", "consecutive_newlines", "=", "0", "# Remove all leading and trailing whitespace in the documentation block", "for", "c", "in", "raw_doc", ".", ...
31.791667
14.875
def display_dataset(self): """Update the widget with information about the dataset.""" header = self.dataset.header self.parent.setWindowTitle(basename(self.filename)) short_filename = short_strings(basename(self.filename)) self.idx_filename.setText(short_filename) self....
[ "def", "display_dataset", "(", "self", ")", ":", "header", "=", "self", ".", "dataset", ".", "header", "self", ".", "parent", ".", "setWindowTitle", "(", "basename", "(", "self", ".", "filename", ")", ")", "short_filename", "=", "short_strings", "(", "base...
51.5
17.857143
def get_logs(self, container_id): """ Return the full stdout/stderr of a container""" stdout = self._docker.containers.get(container_id).logs(stdout=True, stderr=False).decode('utf8') stderr = self._docker.containers.get(container_id).logs(stdout=False, stderr=True).decode('utf8') return...
[ "def", "get_logs", "(", "self", ",", "container_id", ")", ":", "stdout", "=", "self", ".", "_docker", ".", "containers", ".", "get", "(", "container_id", ")", ".", "logs", "(", "stdout", "=", "True", ",", "stderr", "=", "False", ")", ".", "decode", "...
66.2
29.6
def create_sheet(self, title): """ Create a sheet with the given title. This does not check if another sheet by the same name already exists. """ ws = self.conn.sheets_service.AddWorksheet(title, 10, 10, self.id) self._wsf = None return Sheet(self, ws)
[ "def", "create_sheet", "(", "self", ",", "title", ")", ":", "ws", "=", "self", ".", "conn", ".", "sheets_service", ".", "AddWorksheet", "(", "title", ",", "10", ",", "10", ",", "self", ".", "id", ")", "self", ".", "_wsf", "=", "None", "return", "Sh...
47.833333
11.666667
def url(self): """ Return the URL of the server. :returns: URL of the server :rtype: string """ if len(self.drivers) > 0: return self.drivers[0].url else: return self._url
[ "def", "url", "(", "self", ")", ":", "if", "len", "(", "self", ".", "drivers", ")", ">", "0", ":", "return", "self", ".", "drivers", "[", "0", "]", ".", "url", "else", ":", "return", "self", ".", "_url" ]
22
12.727273
def calculate_slope_aspect(elevation, xres, yres, z=1.0, scale=1.0): """ Calculate slope and aspect map. Return a pair of arrays 2 pixels smaller than the input elevation array. Slope is returned in radians, from 0 for sheer face to pi/2 for flat ground. Aspect is returned in radians, counterclock...
[ "def", "calculate_slope_aspect", "(", "elevation", ",", "xres", ",", "yres", ",", "z", "=", "1.0", ",", "scale", "=", "1.0", ")", ":", "z", "=", "float", "(", "z", ")", "scale", "=", "float", "(", "scale", ")", "height", ",", "width", "=", "elevati...
31.333333
21.411765
def _append_path(path, name, tree, buffer_items): """ Append a 2D or 3D path to the scene structure and put the data into buffer_items. Parameters ------------- path : trimesh.Path2D or trimesh.Path3D Source geometry name : str Name of geometry tree : dict Will be upda...
[ "def", "_append_path", "(", "path", ",", "name", ",", "tree", ",", "buffer_items", ")", ":", "# convert the path to the unnamed args for", "# a pyglet vertex list", "vxlist", "=", "rendering", ".", "path_to_vertexlist", "(", "path", ")", "tree", "[", "\"meshes\"", "...
30.584906
17.113208
def get_string(self): """A string representation of the junction :return: string represnetation :rtype: string """ return self.left.chr+':'+str(self.left.end)+'-'+self.right.chr+':'+str(self.right.start)
[ "def", "get_string", "(", "self", ")", ":", "return", "self", ".", "left", ".", "chr", "+", "':'", "+", "str", "(", "self", ".", "left", ".", "end", ")", "+", "'-'", "+", "self", ".", "right", ".", "chr", "+", "':'", "+", "str", "(", "self", ...
31.142857
19.857143
def git_repo_to_sloc(url): """ Given a Git repository URL, returns number of lines of code based on cloc Reference: - cloc: https://github.com/AlDanial/cloc - https://www.omg.org/spec/AFP/ - Another potential way to calculation effort Sample cloc output: { "header":...
[ "def", "git_repo_to_sloc", "(", "url", ")", ":", "with", "tempfile", ".", "TemporaryDirectory", "(", ")", "as", "tmp_dir", ":", "logger", ".", "debug", "(", "'Cloning: url=%s tmp_dir=%s'", ",", "url", ",", "tmp_dir", ")", "tmp_clone", "=", "os", ".", "path",...
28.328947
17.934211
def _update_serial_ports(serial_old_new): ''' Returns a list of vim.vm.device.VirtualDeviceSpec specifying to edit a deployed serial port configuration to the new given config serial_old_new Dictionary with old and new keys which contains the current and the next config for a serial ...
[ "def", "_update_serial_ports", "(", "serial_old_new", ")", ":", "serial_changes", "=", "[", "]", "if", "serial_old_new", ":", "devs", "=", "[", "serial", "[", "'old'", "]", "[", "'adapter'", "]", "for", "serial", "in", "serial_old_new", "]", "log", ".", "t...
43.695652
19.869565
def _feature_country_mentions(self, doc): """ Given a document, count how many times different country names and adjectives are mentioned. These are features used in the country picking phase. Parameters --------- doc: a spaCy nlp'ed piece of text Returns ...
[ "def", "_feature_country_mentions", "(", "self", ",", "doc", ")", ":", "c_list", "=", "[", "]", "for", "i", "in", "doc", ".", "ents", ":", "try", ":", "country", "=", "self", ".", "_both_codes", "[", "i", ".", "text", "]", "c_list", ".", "append", ...
27.6
19.142857
def hash(self, value): """ function hash() implement to acquire hash value that use simply method that weighted sum. Parameters: ----------- value: string the value is param of need acquire hash Returns: -------- ...
[ "def", "hash", "(", "self", ",", "value", ")", ":", "result", "=", "0", "for", "i", "in", "range", "(", "len", "(", "value", ")", ")", ":", "result", "+=", "self", ".", "seed", "*", "result", "+", "ord", "(", "value", "[", "i", "]", ")", "ret...
30.352941
17.411765
def retrieveVals(self): """Retrieve values for graphs.""" ntpinfo = NTPinfo() stats = ntpinfo.getPeerStats() if stats: if self.hasGraph('ntp_peer_stratum'): self.setGraphVal('ntp_peer_stratum', 'stratum', stats.get('stratum'))...
[ "def", "retrieveVals", "(", "self", ")", ":", "ntpinfo", "=", "NTPinfo", "(", ")", "stats", "=", "ntpinfo", ".", "getPeerStats", "(", ")", "if", "stats", ":", "if", "self", ".", "hasGraph", "(", "'ntp_peer_stratum'", ")", ":", "self", ".", "setGraphVal",...
46.666667
13.933333
def awaitTermination(self, timeout=None): """ Wait for the execution to stop. @param timeout: time to wait in seconds """ if timeout is None: self._jssc.awaitTermination() else: self._jssc.awaitTerminationOrTimeout(int(timeout * 1000))
[ "def", "awaitTermination", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "timeout", "is", "None", ":", "self", ".", "_jssc", ".", "awaitTermination", "(", ")", "else", ":", "self", ".", "_jssc", ".", "awaitTerminationOrTimeout", "(", "int", "...
29.9
11.9
def n_choose_k(n, k): """ get the number of quartets as n-choose-k. This is used in equal splits to decide whether a split should be exhaustively sampled or randomly sampled. Edges near tips can be exhaustive while highly nested edges probably have too many quartets """ return int(reduce(MUL, (F...
[ "def", "n_choose_k", "(", "n", ",", "k", ")", ":", "return", "int", "(", "reduce", "(", "MUL", ",", "(", "Fraction", "(", "n", "-", "i", ",", "i", "+", "1", ")", "for", "i", "in", "range", "(", "k", ")", ")", ",", "1", ")", ")" ]
50.714286
17.714286
def invalidate_cache(self, obj=None, queryset=None, extra=None, force_all=False): """ Method that should be called by all tiggers to invalidate the cache for an item(s). Should be overriden by inheriting classes to customize behavior. """ if sel...
[ "def", "invalidate_cache", "(", "self", ",", "obj", "=", "None", ",", "queryset", "=", "None", ",", "extra", "=", "None", ",", "force_all", "=", "False", ")", ":", "if", "self", ".", "cache_manager", ":", "if", "queryset", "!=", "None", ":", "force_all...
37.375
20.625
def set_vars(env): """Set MWCW_VERSION, MWCW_VERSIONS, and some codewarrior environment vars MWCW_VERSIONS is set to a list of objects representing installed versions MWCW_VERSION is set to the version object that will be used for building. MWCW_VERSION can be set to a string during Env...
[ "def", "set_vars", "(", "env", ")", ":", "desired", "=", "env", ".", "get", "(", "'MWCW_VERSION'", ",", "''", ")", "# return right away if the variables are already set", "if", "isinstance", "(", "desired", ",", "MWVersion", ")", ":", "return", "1", "elif", "d...
30.977778
21.511111
def log_attempt(self, key): """ Log an attempt against key, incrementing the number of attempts for that key and potentially adding a lock to the lock table """ with self.lock: if key not in self.attempts: self.attempts[key] = 1 else: ...
[ "def", "log_attempt", "(", "self", ",", "key", ")", ":", "with", "self", ".", "lock", ":", "if", "key", "not", "in", "self", ".", "attempts", ":", "self", ".", "attempts", "[", "key", "]", "=", "1", "else", ":", "self", ".", "attempts", "[", "key...
42.466667
22.333333
def run(cosmology, zi=0, Mi=1e12, z=False, com=True, mah=True, filename=None, verbose=None, retcosmo=None): """ Run commah code on halo of mass 'Mi' at redshift 'zi' with accretion and profile history at higher redshifts 'z' This is based on Correa et al. (2015a,b,c) Parameters ----...
[ "def", "run", "(", "cosmology", ",", "zi", "=", "0", ",", "Mi", "=", "1e12", ",", "z", "=", "False", ",", "com", "=", "True", ",", "mah", "=", "True", ",", "filename", "=", "None", ",", "verbose", "=", "None", ",", "retcosmo", "=", "None", ")",...
46.783673
22.893878
def synchronous(self): ''' True if transport is synchronous or the connection has been forced into synchronous mode, False otherwise. ''' if self._transport is None: if self._close_info and len(self._close_info['reply_text']) > 0: raise ConnectionClose...
[ "def", "synchronous", "(", "self", ")", ":", "if", "self", ".", "_transport", "is", "None", ":", "if", "self", ".", "_close_info", "and", "len", "(", "self", ".", "_close_info", "[", "'reply_text'", "]", ")", ">", "0", ":", "raise", "ConnectionClosed", ...
50.916667
24.416667
def check_ratelimit_budget(self, seconds_waited): """ If we have a ratelimit_budget, ensure it is not exceeded. """ if self.ratelimit_budget is not None: self.ratelimit_budget -= seconds_waited if self.ratelimit_budget < 1: raise RatelimitBudgetExceeded("Rate limi...
[ "def", "check_ratelimit_budget", "(", "self", ",", "seconds_waited", ")", ":", "if", "self", ".", "ratelimit_budget", "is", "not", "None", ":", "self", ".", "ratelimit_budget", "-=", "seconds_waited", "if", "self", ".", "ratelimit_budget", "<", "1", ":", "rais...
55.833333
10.333333
def GET_AUTH(self, courseid): # pylint: disable=arguments-differ """ GET request """ course = self.course_factory.get_course(courseid) username = self.user_manager.session_username() error = False change = False msg = "" data = web.input() if self.user_...
[ "def", "GET_AUTH", "(", "self", ",", "courseid", ")", ":", "# pylint: disable=arguments-differ", "course", "=", "self", ".", "course_factory", ".", "get_course", "(", "courseid", ")", "username", "=", "self", ".", "user_manager", ".", "session_username", "(", ")...
58.8
35
def modify(self, request, nodes, namespace, root_id, post_cut, breadcrumb): """ Actual modifier function :param request: request :param nodes: complete list of nodes :param namespace: Menu namespace :param root_id: eventual root_id :param post_cut: flag for modifi...
[ "def", "modify", "(", "self", ",", "request", ",", "nodes", ",", "namespace", ",", "root_id", ",", "post_cut", ",", "breadcrumb", ")", ":", "app", "=", "None", "config", "=", "None", "if", "getattr", "(", "request", ",", "'current_page'", ",", "None", ...
39.395349
18.232558
def getDescsV2(flags, fs_list=(), hs_list=(), ss_list=(), os_list=()): """ Return a FunctionFS descriptor suitable for serialisation. flags (int) Any combination of VIRTUAL_ADDR, EVENTFD, ALL_CTRL_RECIP, CONFIG0_SETUP. {fs,hs,ss,os}_list (list of descriptors) Instances of the fo...
[ "def", "getDescsV2", "(", "flags", ",", "fs_list", "=", "(", ")", ",", "hs_list", "=", "(", ")", ",", "ss_list", "=", "(", ")", ",", "os_list", "=", "(", ")", ")", ":", "count_field_list", "=", "[", "]", "descr_field_list", "=", "[", "]", "kw", "...
34.336957
16.771739
def request_token(self): """ Gets OAuth request token """ client = OAuth1( client_key=self._server_cache[self.client.server].key, client_secret=self._server_cache[self.client.server].secret, callback_uri=self.callback, ) request = {"auth": client} ...
[ "def", "request_token", "(", "self", ")", ":", "client", "=", "OAuth1", "(", "client_key", "=", "self", ".", "_server_cache", "[", "self", ".", "client", ".", "server", "]", ".", "key", ",", "client_secret", "=", "self", ".", "_server_cache", "[", "self"...
28.545455
19.545455
def fix_calldef_decls(decls, enums, cxx_std): """ some times gccxml report typedefs defined in no namespace it happens for example in next situation template< typename X> void ddd(){ typedef typename X::Y YY;} if I will fail on this bug next time, the right way to fix it may be different ...
[ "def", "fix_calldef_decls", "(", "decls", ",", "enums", ",", "cxx_std", ")", ":", "default_arg_patcher", "=", "default_argument_patcher_t", "(", "enums", ",", "cxx_std", ")", "# decls should be flat list of all declarations, you want to apply patch on", "for", "decl", "in",...
41.266667
14.6
def disable(self): """ Disable the crash reporter. No reports will be sent or saved. """ if CrashReporter.active: CrashReporter.active = False # Restore the original excepthook sys.excepthook = self._excepthook self.stop_watcher() ...
[ "def", "disable", "(", "self", ")", ":", "if", "CrashReporter", ".", "active", ":", "CrashReporter", ".", "active", "=", "False", "# Restore the original excepthook", "sys", ".", "excepthook", "=", "self", ".", "_excepthook", "self", ".", "stop_watcher", "(", ...
35.7
9.3
def decode(self, bytes, raw=False): """decode(bytearray, raw=False) -> value Decodes the given bytearray and returns the number of (fractional) seconds. If the optional parameter ``raw`` is ``True``, the byte (U8) itself will be returned. """ result = super(Tim...
[ "def", "decode", "(", "self", ",", "bytes", ",", "raw", "=", "False", ")", ":", "result", "=", "super", "(", "Time8Type", ",", "self", ")", ".", "decode", "(", "bytes", ")", "if", "not", "raw", ":", "result", "/=", "256.0", "return", "result" ]
25.25
21.1875
def add_occurrences(self, start_time, end_time, **rrule_params): ''' Add one or more occurences to the event using a comparable API to ``dateutil.rrule``. If ``rrule_params`` does not contain a ``freq``, one will be defaulted to ``rrule.DAILY``. Because ``rrule.rrule`` ...
[ "def", "add_occurrences", "(", "self", ",", "start_time", ",", "end_time", ",", "*", "*", "rrule_params", ")", ":", "count", "=", "rrule_params", ".", "get", "(", "'count'", ")", "until", "=", "rrule_params", ".", "get", "(", "'until'", ")", "if", "not",...
46.740741
25.333333
def getBigIndexFromIndices(self, indices): """ Get the big index from a given set of indices @param indices @return big index @note no checks are performed to ensure that the returned indices are valid """ return reduce(operator.add, [self.dimProd[i]*indic...
[ "def", "getBigIndexFromIndices", "(", "self", ",", "indices", ")", ":", "return", "reduce", "(", "operator", ".", "add", ",", "[", "self", ".", "dimProd", "[", "i", "]", "*", "indices", "[", "i", "]", "for", "i", "in", "range", "(", "self", ".", "n...
38.5
13.9
def request_challenges(self, identifier): """ Create a new authorization. :param ~acme.messages.Identifier identifier: The identifier to authorize. :return: The new authorization resource. :rtype: Deferred[`~acme.messages.AuthorizationResource`] """ ...
[ "def", "request_challenges", "(", "self", ",", "identifier", ")", ":", "action", "=", "LOG_ACME_CREATE_AUTHORIZATION", "(", "identifier", "=", "identifier", ")", "with", "action", ".", "context", "(", ")", ":", "message", "=", "messages", ".", "NewAuthorization"...
42
18.909091
def setup(__pkg: ModuleType) -> Tuple[Callable[[str], str], Callable[[str, str, int], str]]: """Configure ``gettext`` for given package. Args: __pkg: Package to use as location for :program:`gettext` files Returns: :program:`gettext` functions for singu...
[ "def", "setup", "(", "__pkg", ":", "ModuleType", ")", "->", "Tuple", "[", "Callable", "[", "[", "str", "]", ",", "str", "]", ",", "Callable", "[", "[", "str", ",", "str", ",", "int", "]", ",", "str", "]", "]", ":", "package_locale", "=", "path", ...
36.571429
24
def _apply_dict(self, qe_dict): ''' Apply a query expression, updating the query object ''' for k, v in qe_dict.items(): k = resolve_name(self.type, k) if not k in self.__query: self.__query[k] = v continue if not isinstance(self.__quer...
[ "def", "_apply_dict", "(", "self", ",", "qe_dict", ")", ":", "for", "k", ",", "v", "in", "qe_dict", ".", "items", "(", ")", ":", "k", "=", "resolve_name", "(", "self", ".", "type", ",", "k", ")", "if", "not", "k", "in", "self", ".", "__query", ...
48.4
16
def get_scales(self, aesthetic): """ Return the scale for the aesthetic or None if there isn't one. These are the scales specified by the user e.g `ggplot() + scale_x_continuous()` or those added by default during the plot building process """ ...
[ "def", "get_scales", "(", "self", ",", "aesthetic", ")", ":", "bool_lst", "=", "self", ".", "find", "(", "aesthetic", ")", "try", ":", "idx", "=", "bool_lst", ".", "index", "(", "True", ")", "return", "self", "[", "idx", "]", "except", "ValueError", ...
29.3125
14.0625