text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def _irregular(singular, plural): """ A convenience function to add appropriate rules to plurals and singular for irregular words. :param singular: irregular word in singular form :param plural: irregular word in plural form """ def caseinsensitive(string): return ''.join('[' + char...
[ "def", "_irregular", "(", "singular", ",", "plural", ")", ":", "def", "caseinsensitive", "(", "string", ")", ":", "return", "''", ".", "join", "(", "'['", "+", "char", "+", "char", ".", "upper", "(", ")", "+", "']'", "for", "char", "in", "string", ...
35.156863
18.058824
def get_cuda_visible_devices(): """Get the device IDs in the CUDA_VISIBLE_DEVICES environment variable. Returns: if CUDA_VISIBLE_DEVICES is set, this returns a list of integers with the IDs of the GPUs. If it is not set, this returns None. """ gpu_ids_str = os.environ.get("CUDA_VISI...
[ "def", "get_cuda_visible_devices", "(", ")", ":", "gpu_ids_str", "=", "os", ".", "environ", ".", "get", "(", "\"CUDA_VISIBLE_DEVICES\"", ",", "None", ")", "if", "gpu_ids_str", "is", "None", ":", "return", "None", "if", "gpu_ids_str", "==", "\"\"", ":", "retu...
29.4375
22.9375
async def save(proxies, filename): """Save proxies to a file.""" with open(filename, 'w') as f: while True: proxy = await proxies.get() if proxy is None: break f.write('%s:%d\n' % (proxy.host, proxy.port))
[ "async", "def", "save", "(", "proxies", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "f", ":", "while", "True", ":", "proxy", "=", "await", "proxies", ".", "get", "(", ")", "if", "proxy", "is", "None", ":", "...
33.25
10.125
def list_assignments_for_user(self, user_id, course_id): """ List assignments for user. Returns the list of assignments for the specified user if the current user has rights to view. See {api:AssignmentsApiController#index List assignments} for valid arguments. """ ...
[ "def", "list_assignments_for_user", "(", "self", ",", "user_id", ",", "course_id", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - user_id\r", "\"\"\"ID\"\"\"", "path", "[", "\"user_id\"", "]", "=", "user...
42
29.619048
def vagrant_settings(self, name='', *args, **kwargs): """ Context manager that sets a vagrant VM as the remote host. Use this context manager inside a task to run commands on your current Vagrant box:: from burlap.vagrant import vagrant_settings with va...
[ "def", "vagrant_settings", "(", "self", ",", "name", "=", "''", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "config", "=", "self", ".", "ssh_config", "(", "name", ")", "extra_args", "=", "self", ".", "_settings_dict", "(", "config", ")", "kw...
28.052632
16.157895
def format_float_field(__, prec, number, locale): """Formats a fixed-point field.""" format_ = u'0.' if prec is None: format_ += u'#' * NUMBER_DECIMAL_DIGITS else: format_ += u'0' * int(prec) pattern = parse_pattern(format_) return pattern.apply(number, locale)
[ "def", "format_float_field", "(", "__", ",", "prec", ",", "number", ",", "locale", ")", ":", "format_", "=", "u'0.'", "if", "prec", "is", "None", ":", "format_", "+=", "u'#'", "*", "NUMBER_DECIMAL_DIGITS", "else", ":", "format_", "+=", "u'0'", "*", "int"...
32.555556
10.777778
def expand_abbreviations(txt, fields): """Expand abbreviations in a format string. If an abbreviation does not match a field, or matches multiple fields, it is left unchanged. Example: >>> fields = ("hey", "there", "dude") >>> expand_abbreviations("hello {d}", fields) 'hello d...
[ "def", "expand_abbreviations", "(", "txt", ",", "fields", ")", ":", "def", "_expand", "(", "matchobj", ")", ":", "s", "=", "matchobj", ".", "group", "(", "\"var\"", ")", "if", "s", "not", "in", "fields", ":", "matches", "=", "[", "x", "for", "x", "...
27.111111
18.888889
def make_absolute_paths(config): '''given a config dict with streamcorpus_pipeline as a key, find all keys under streamcorpus_pipeline that end with "_path" and if the value of that key is a relative path, convert it to an absolute path using the value provided by root_path ''' if not 'streamcor...
[ "def", "make_absolute_paths", "(", "config", ")", ":", "if", "not", "'streamcorpus_pipeline'", "in", "config", ":", "logger", ".", "critical", "(", "'bad config: %r'", ",", "config", ")", "raise", "ConfigurationError", "(", "'missing \"streamcorpus_pipeline\" from confi...
41.914286
18.428571
def get_photometry(self, brightest=False, min_unc=0.02, convert=True): """Returns dictionary of photometry of closest match unless brightest is True, in which case the brightest match. """ if brightest: row = self.brightest else: row =...
[ "def", "get_photometry", "(", "self", ",", "brightest", "=", "False", ",", "min_unc", "=", "0.02", ",", "convert", "=", "True", ")", ":", "if", "brightest", ":", "row", "=", "self", ".", "brightest", "else", ":", "row", "=", "self", ".", "closest", "...
27.233333
18.266667
def alignPronunciations(pronI, pronA): ''' Align the phones in two pronunciations ''' # First prep the two pronunctions pronI = [char for char in pronI] pronA = [char for char in pronA] # Remove any elements not in the other list (but maintain order) pronITmp = pronI pronAT...
[ "def", "alignPronunciations", "(", "pronI", ",", "pronA", ")", ":", "# First prep the two pronunctions", "pronI", "=", "[", "char", "for", "char", "in", "pronI", "]", "pronA", "=", "[", "char", "for", "char", "in", "pronA", "]", "# Remove any elements not in the...
32.686275
15.392157
def validate_with_permissions(self, val, caller_permissions): """ For a val to pass validation, val must be of the correct type and have all required permissioned fields present. Should only be called for callers with extra permissions. """ self.validate(val) self...
[ "def", "validate_with_permissions", "(", "self", ",", "val", ",", "caller_permissions", ")", ":", "self", ".", "validate", "(", "val", ")", "self", ".", "validate_fields_only_with_permissions", "(", "val", ",", "caller_permissions", ")", "return", "val" ]
43.777778
18.222222
def all_elements_by_type(name): """ Get specified elements based on the entry point verb from SMC api To get the entry points available, you can get these from the session:: session.cache.entry_points Execution will get the entry point for the element type, then get all elements that match. ...
[ "def", "all_elements_by_type", "(", "name", ")", ":", "if", "name", ":", "entry", "=", "element_entry_point", "(", "name", ")", "if", "entry", ":", "# in case an invalid entry point is specified", "result", "=", "element_by_href_as_json", "(", "entry", ")", "return"...
33.409091
20.409091
def ensure_json_content_type(req, app): """ ErrorMiddleware returns hard-coded content-type text/html. Here we force it to be application/json. """ res = req.get_response(app, catch_exc_info=True) res.content_type = 'application/json; charset=utf-8' return res
[ "def", "ensure_json_content_type", "(", "req", ",", "app", ")", ":", "res", "=", "req", ".", "get_response", "(", "app", ",", "catch_exc_info", "=", "True", ")", "res", ".", "content_type", "=", "'application/json; charset=utf-8'", "return", "res" ]
35.125
10.125
def register(scanner_class, relevant_properties): """ Registers a new generator class, specifying a set of properties relevant to this scanner. Ctor for that class should have one parameter: list of properties. """ assert issubclass(scanner_class, Scanner) assert isinstance(relevant_pro...
[ "def", "register", "(", "scanner_class", ",", "relevant_properties", ")", ":", "assert", "issubclass", "(", "scanner_class", ",", "Scanner", ")", "assert", "isinstance", "(", "relevant_properties", ",", "basestring", ")", "__scanners", "[", "str", "(", "scanner_cl...
48.75
10.375
def _PSat_s(s): """Define the saturated line, P=f(s) for region 3 Parameters ---------- s : float Specific entropy, [kJ/kgK] Returns ------- P : float Pressure, [MPa] Notes ------ Raise :class:`NotImplementedError` if input isn't in limit: * s'(623.15K...
[ "def", "_PSat_s", "(", "s", ")", ":", "# Check input parameters", "smin_Ps3", "=", "_Region1", "(", "623.15", ",", "Ps_623", ")", "[", "\"s\"", "]", "smax_Ps3", "=", "_Region2", "(", "623.15", ",", "Ps_623", ")", "[", "\"s\"", "]", "if", "s", "<", "smi...
28.058824
23.627451
def get_max_posterior_region(self, node, fraction = 0.9): ''' If temporal reconstruction was done using the marginal ML mode, the entire distribution of times is available. This function determines the interval around the highest posterior probability region that contains the specified f...
[ "def", "get_max_posterior_region", "(", "self", ",", "node", ",", "fraction", "=", "0.9", ")", ":", "if", "node", ".", "marginal_inverse_cdf", "==", "\"delta\"", ":", "return", "np", ".", "array", "(", "[", "node", ".", "numdate", ",", "node", ".", "numd...
51.870968
32.354839
def _new_from_xml(cls, xmlnode): """Create a new `Field` object from an XML element. :Parameters: - `xmlnode`: the XML element. :Types: - `xmlnode`: `libxml2.xmlNode` :return: the object created. :returntype: `Field` """ field_type = xmln...
[ "def", "_new_from_xml", "(", "cls", ",", "xmlnode", ")", ":", "field_type", "=", "xmlnode", ".", "prop", "(", "\"type\"", ")", "label", "=", "from_utf8", "(", "xmlnode", ".", "prop", "(", "\"label\"", ")", ")", "name", "=", "from_utf8", "(", "xmlnode", ...
37.647059
15.411765
def check_token(self, user, token): """ Check that a password reset token is correct for a given user. """ # Parse the token try: ts_b36, hash = token.split("-") except ValueError: return False try: ts = base36_to_int(ts_b36) ...
[ "def", "check_token", "(", "self", ",", "user", ",", "token", ")", ":", "# Parse the token", "try", ":", "ts_b36", ",", "hash", "=", "token", ".", "split", "(", "\"-\"", ")", "except", "ValueError", ":", "return", "False", "try", ":", "ts", "=", "base3...
29.041667
20.708333
def save_channels(self, checked=False, test_name=None): """Save channel groups to file.""" self.read_group_info() if self.filename is not None: filename = self.filename elif self.parent.info.filename is not None: filename = (splitext(self.parent.info.filename)[0]...
[ "def", "save_channels", "(", "self", ",", "checked", "=", "False", ",", "test_name", "=", "None", ")", ":", "self", ".", "read_group_info", "(", ")", "if", "self", ".", "filename", "is", "not", "None", ":", "filename", "=", "self", ".", "filename", "el...
33.419355
19.096774
def init_app(self, app): """Initialize the APScheduler with a Flask application instance.""" self.app = app self.app.apscheduler = self self._load_config() self._load_jobs() if self.api_enabled: self._load_api()
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "self", ".", "app", "=", "app", "self", ".", "app", ".", "apscheduler", "=", "self", "self", ".", "_load_config", "(", ")", "self", ".", "_load_jobs", "(", ")", "if", "self", ".", "api_enabled", ...
24
19.181818
def WorkersDensity(dataTasks): """Return the worker density data for the graph.""" start_time, end_time = getTimes(dataTasks) graphdata = [] for name in getWorkersName(dataTasks): vals = dataTasks[name] if hasattr(vals, 'values'): # Data from worker workerdata =...
[ "def", "WorkersDensity", "(", "dataTasks", ")", ":", "start_time", ",", "end_time", "=", "getTimes", "(", "dataTasks", ")", "graphdata", "=", "[", "]", "for", "name", "in", "getWorkersName", "(", "dataTasks", ")", ":", "vals", "=", "dataTasks", "[", "name"...
42.470588
18.911765
def hours_minutes_seconds(self): """ A 3-tuple of (hours, minutes, seconds). """ minutes, seconds = symmetric_divmod(self[2], 60) hours, minutes = symmetric_divmod(minutes, 60) return hours, minutes, float(seconds) + self[3]
[ "def", "hours_minutes_seconds", "(", "self", ")", ":", "minutes", ",", "seconds", "=", "symmetric_divmod", "(", "self", "[", "2", "]", ",", "60", ")", "hours", ",", "minutes", "=", "symmetric_divmod", "(", "minutes", ",", "60", ")", "return", "hours", ",...
43.166667
8.833333
def get_line(self, position): 'Returns the line number that the given string position is found on' datalen = len(self.data) count = len(self.data[0]) line = 1 while count < position: if line >= datalen: break count += len(self.data[line]) ...
[ "def", "get_line", "(", "self", ",", "position", ")", ":", "datalen", "=", "len", "(", "self", ".", "data", ")", "count", "=", "len", "(", "self", ".", "data", "[", "0", "]", ")", "line", "=", "1", "while", "count", "<", "position", ":", "if", ...
27.230769
19.076923
def cost(a,b,c,e,f,p_min,p): """cost: fuel cost based on "standard" parameters (with valve-point loading effect) """ return a + b*p + c*p*p + abs(e*math.sin(f*(p_min-p)))
[ "def", "cost", "(", "a", ",", "b", ",", "c", ",", "e", ",", "f", ",", "p_min", ",", "p", ")", ":", "return", "a", "+", "b", "*", "p", "+", "c", "*", "p", "*", "p", "+", "abs", "(", "e", "*", "math", ".", "sin", "(", "f", "*", "(", "...
36.4
6.4
def cgnr_prolongation_smoothing(A, T, B, BtBinv, Sparsity_Pattern, maxiter, tol, weighting='local', Cpt_params=None): """Use CGNR to smooth T by solving A T = 0, subject to nullspace and sparsity constraints. Parameters ---------- A : csr_matrix, bsr_matrix SPD s...
[ "def", "cgnr_prolongation_smoothing", "(", "A", ",", "T", ",", "B", ",", "BtBinv", ",", "Sparsity_Pattern", ",", "maxiter", ",", "tol", ",", "weighting", "=", "'local'", ",", "Cpt_params", "=", "None", ")", ":", "# For non-SPD system, apply CG on Normal Equations ...
38.412791
22.325581
def assert_called_with(_mock_self, *args, **kwargs): """assert that the mock was called with the specified arguments. Raises an AssertionError if the args and keyword args passed in are different to the last call to the mock.""" self = _mock_self if self.call_args is None: ...
[ "def", "assert_called_with", "(", "_mock_self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", "=", "_mock_self", "if", "self", ".", "call_args", "is", "None", ":", "expected", "=", "self", ".", "_format_mock_call_signature", "(", "args", ","...
49
19.857143
def _cb_dcnm_msg(self, method, body): """Callback function to process DCNM network creation/update/deletion message received by AMQP. It also communicates with DCNM to extract info for CPNR record insertion/deletion. :param pika.channel.Channel ch: The channel instance. ...
[ "def", "_cb_dcnm_msg", "(", "self", ",", "method", ",", "body", ")", ":", "LOG", ".", "debug", "(", "'Routing_key: %(key)s, body: %(body)s.'", ",", "{", "'key'", ":", "method", ".", "routing_key", ",", "'body'", ":", "body", "}", ")", "partition_keyword", "=...
39.456522
16.065217
def insert_paraphrase_information(germanet_db, wiktionary_files): ''' Reads in the given GermaNet relation file and inserts its contents into the given MongoDB database. Arguments: - `germanet_db`: a pymongo.database.Database object - `wiktionary_files`: ''' num_paraphrases = 0 # ca...
[ "def", "insert_paraphrase_information", "(", "germanet_db", ",", "wiktionary_files", ")", ":", "num_paraphrases", "=", "0", "# cache the lexunits while we work on them", "lexunits", "=", "{", "}", "for", "filename", "in", "wiktionary_files", ":", "paraphrases", "=", "re...
39
16.071429
def _getFirstOnBit(self, input): """ Return the bit offset of the first bit to be set in the encoder output. For periodic encoders, this can be a negative number when the encoded output wraps around. """ if input == SENTINEL_VALUE_FOR_MISSING_DATA: return [None] else: if input < self.m...
[ "def", "_getFirstOnBit", "(", "self", ",", "input", ")", ":", "if", "input", "==", "SENTINEL_VALUE_FOR_MISSING_DATA", ":", "return", "[", "None", "]", "else", ":", "if", "input", "<", "self", ".", "minval", ":", "# Don't clip periodic inputs. Out-of-range input is...
41.638298
24.234043
def mean(series): """ Returns the mean of a series. Args: series (pandas.Series): column to summarize. """ if np.issubdtype(series.dtype, np.number): return series.mean() else: return np.nan
[ "def", "mean", "(", "series", ")", ":", "if", "np", ".", "issubdtype", "(", "series", ".", "dtype", ",", "np", ".", "number", ")", ":", "return", "series", ".", "mean", "(", ")", "else", ":", "return", "np", ".", "nan" ]
19.083333
18.416667
def inject_mode(arg_namespace): """Check command line arguments and run build function.""" try: injector.inject_into_files(arg_namespace.scheme, arg_namespace.file) except (IndexError, FileNotFoundError, PermissionError, IsADirectoryError) as exception: if isinstance(exception, ...
[ "def", "inject_mode", "(", "arg_namespace", ")", ":", "try", ":", "injector", ".", "inject_into_files", "(", "arg_namespace", ".", "scheme", ",", "arg_namespace", ".", "file", ")", "except", "(", "IndexError", ",", "FileNotFoundError", ",", "PermissionError", ",...
49.222222
18
def p_review_date_1(self, p): """review_date : REVIEW_DATE DATE""" try: if six.PY2: value = p[2].decode(encoding='utf-8') else: value = p[2] self.builder.add_review_date(self.document, value) except CardinalityError: ...
[ "def", "p_review_date_1", "(", "self", ",", "p", ")", ":", "try", ":", "if", "six", ".", "PY2", ":", "value", "=", "p", "[", "2", "]", ".", "decode", "(", "encoding", "=", "'utf-8'", ")", "else", ":", "value", "=", "p", "[", "2", "]", "self", ...
38
16.5
def is_bored_of(self, board): """Return whether the simulation is probably in a loop. This is a stochastic guess. Basically, it detects whether the simulation has had the same number of cells a lot lately. May have false positives (like if you just have a screen full of gliders) or ...
[ "def", "is_bored_of", "(", "self", ",", "board", ")", ":", "self", ".", "iteration", "+=", "1", "if", "len", "(", "board", ")", "==", "self", ".", "num", ":", "self", ".", "times", "+=", "1", "is_bored", "=", "self", ".", "times", ">", "self", "....
43.05
19.45
def from_client_secrets_file(cls, client_secrets_file, scopes, **kwargs): """Creates a :class:`Flow` instance from a Google client secrets file. Args: client_secrets_file (str): The path to the client secrets .json file. scopes (Sequence[str]): The list of scopes...
[ "def", "from_client_secrets_file", "(", "cls", ",", "client_secrets_file", ",", "scopes", ",", "*", "*", "kwargs", ")", ":", "with", "open", "(", "client_secrets_file", ",", "'r'", ")", "as", "json_file", ":", "client_config", "=", "json", ".", "load", "(", ...
40.277778
23
def get_course(self, course, use_sis_id=False, **kwargs): """ Retrieve a course by its ID. :calls: `GET /api/v1/courses/:id \ <https://canvas.instructure.com/doc/api/courses.html#method.courses.show>`_ :param course: The object or ID of the course to retrieve. :type cou...
[ "def", "get_course", "(", "self", ",", "course", ",", "use_sis_id", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "use_sis_id", ":", "course_id", "=", "course", "uri_str", "=", "'courses/sis_course_id:{}'", "else", ":", "course_id", "=", "obj_or_id"...
34.464286
17.821429
def to_grayscale(cv2im): """Convert gradients to grayscale. This gives a saliency map.""" # How strongly does each position activate the output grayscale_im = np.sum(np.abs(cv2im), axis=0) # Normalize between min and 99th percentile im_max = np.percentile(grayscale_im, 99) im_min = np.min(grays...
[ "def", "to_grayscale", "(", "cv2im", ")", ":", "# How strongly does each position activate the output", "grayscale_im", "=", "np", ".", "sum", "(", "np", ".", "abs", "(", "cv2im", ")", ",", "axis", "=", "0", ")", "# Normalize between min and 99th percentile", "im_ma...
39.666667
17.333333
def validate_function(method, **kwargs): """ Validate the field matches the result of calling the given method. Example:: def myfunc(value, name): return value == name validator = validate_function(myfunc, name='tim') Essentially creates a validator that only accepts the name ...
[ "def", "validate_function", "(", "method", ",", "*", "*", "kwargs", ")", ":", "def", "function_validator", "(", "field", ",", "data", ")", ":", "if", "field", ".", "value", "is", "None", ":", "return", "if", "not", "method", "(", "field", ".", "value",...
33.571429
18.047619
def convertImagesToPIL(self, images, dither, nq=0): """ convertImagesToPIL(images, nq=0) Convert images to Paletted PIL images, which can then be written to a single animaged GIF. """ # Convert to PIL images images2 = [] for im in images: if isinsta...
[ "def", "convertImagesToPIL", "(", "self", ",", "images", ",", "dither", ",", "nq", "=", "0", ")", ":", "# Convert to PIL images", "images2", "=", "[", "]", "for", "im", "in", "images", ":", "if", "isinstance", "(", "im", ",", "Image", ".", "Image", ")"...
31.454545
16.151515
def evaluateModel(model, loader, device, batches_in_epoch=sys.maxsize, criterion=F.nll_loss, progress=None): """ Evaluate pre-trained model using given test dataset loader. :param model: Pretrained pytorch model :type model: torch.nn.Module :param loader: test dataset load...
[ "def", "evaluateModel", "(", "model", ",", "loader", ",", "device", ",", "batches_in_epoch", "=", "sys", ".", "maxsize", ",", "criterion", "=", "F", ".", "nll_loss", ",", "progress", "=", "None", ")", ":", "model", ".", "eval", "(", ")", "loss", "=", ...
31.34
18.46
def _populate_comptparms(self, img_array): """Instantiate and populate comptparms structure. This structure defines the image components. Parameters ---------- img_array : ndarray Image data to be written to file. """ # Only two precisions are possib...
[ "def", "_populate_comptparms", "(", "self", ",", "img_array", ")", ":", "# Only two precisions are possible.", "if", "img_array", ".", "dtype", "==", "np", ".", "uint8", ":", "comp_prec", "=", "8", "else", ":", "comp_prec", "=", "16", "numrows", ",", "numcols"...
35.121212
15
def clock(logger): """ :param logger: logging, a logging object :return: decorator, wraps time """ def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): _start = time.time() retval = func(*args, **kwargs) _end = time.time() ...
[ "def", "clock", "(", "logger", ")", ":", "def", "decorator", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_start", "=", "time", ".", "time", "(", ...
25.666667
16.777778
def _handle_start_nd(self, attrs): """ Handle opening nd element :param attrs: Attributes of the element :type attrs: Dict """ if isinstance(self.cur_relation_member, RelationWay): if self.cur_relation_member.geometry is None: self.cur_relatio...
[ "def", "_handle_start_nd", "(", "self", ",", "attrs", ")", ":", "if", "isinstance", "(", "self", ".", "cur_relation_member", ",", "RelationWay", ")", ":", "if", "self", ".", "cur_relation_member", ".", "geometry", "is", "None", ":", "self", ".", "cur_relatio...
35
14.181818
def organization_users(self, id, permission_set=None, role=None, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/users#list-users" api_path = "/api/v2/organizations/{id}/users.json" api_path = api_path.format(id=id) api_query = {} if "query" in kwargs.keys(): ...
[ "def", "organization_users", "(", "self", ",", "id", ",", "permission_set", "=", "None", ",", "role", "=", "None", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/organizations/{id}/users.json\"", "api_path", "=", "api_path", ".", "format", "(",...
38.352941
16.235294
def collect_by_type(self, typ): '''A more efficient way to collect nodes of a specified type than collect_nodes. ''' nodes = [] if isinstance(self, typ): nodes.append(self) for c in self: nodes.extend(c.collect_by_type(typ)) return nodes
[ "def", "collect_by_type", "(", "self", ",", "typ", ")", ":", "nodes", "=", "[", "]", "if", "isinstance", "(", "self", ",", "typ", ")", ":", "nodes", ".", "append", "(", "self", ")", "for", "c", "in", "self", ":", "nodes", ".", "extend", "(", "c",...
30.8
17.4
def _parse_config(self, requires_cfg=True): """Parse the configuration file, if one is configured, and add it to the `Bison` state. Args: requires_cfg (bool): Specify whether or not parsing should fail if a config file is not found. (default: True) """ ...
[ "def", "_parse_config", "(", "self", ",", "requires_cfg", "=", "True", ")", ":", "if", "len", "(", "self", ".", "config_paths", ")", ">", "0", ":", "try", ":", "self", ".", "_find_config", "(", ")", "except", "BisonError", ":", "if", "not", "requires_c...
37
16.961538
def select_option_dialog(windowTitle, optionList): """ Opens a select option dialog. Select the option by double clicking. TODO: Clean up this function TODO: Improve interface (i.e., add cancel, OK) """ class OptionFrame(wx.Frame): selectedOption = None def __init__(self, windo...
[ "def", "select_option_dialog", "(", "windowTitle", ",", "optionList", ")", ":", "class", "OptionFrame", "(", "wx", ".", "Frame", ")", ":", "selectedOption", "=", "None", "def", "__init__", "(", "self", ",", "windowTitle", ",", "optionList", ")", ":", "wx", ...
34.344828
15.724138
def find_codon_mismatches(sbjct_start, sbjct_seq, qry_seq): """ This function takes two alligned sequence (subject and query), and the position on the subject where the alignment starts. The sequences are compared codon by codon. If a mis matches is found it is saved in 'mis_matches'. If a gap is ...
[ "def", "find_codon_mismatches", "(", "sbjct_start", ",", "sbjct_seq", ",", "qry_seq", ")", ":", "mis_matches", "=", "[", "]", "# Find start pos of first codon in frame, i_start", "codon_offset", "=", "(", "sbjct_start", "-", "1", ")", "%", "3", "i_start", "=", "0"...
44.591195
25.433962
def post_state(self, name, state): """Asynchronously try to update the state for a service. If the update fails, nothing is reported because we don't wait for a response from the server. This function will return immmediately and not block. Args: name (string): The...
[ "def", "post_state", "(", "self", ",", "name", ",", "state", ")", ":", "self", ".", "post_command", "(", "OPERATIONS", ".", "CMD_UPDATE_STATE", ",", "{", "'name'", ":", "name", ",", "'new_status'", ":", "state", "}", ")" ]
36.571429
21.928571
def delete_object(self, bucket, obj, version_id): """Delete an existing object. :param bucket: The bucket (instance or id) to get the object from. :param obj: A :class:`invenio_files_rest.models.ObjectVersion` instance. :param version_id: The version ID. :returns: A ...
[ "def", "delete_object", "(", "self", ",", "bucket", ",", "obj", ",", "version_id", ")", ":", "if", "version_id", "is", "None", ":", "# Create a delete marker.", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "ObjectVersion", ".", "delete",...
35.769231
15.461538
def get_state_actions(self, state, **kwargs): """ Stops containers that are running. Does not check attached containers. Considers using the pre-configured ``stop_signal``. :param state: Configuration state. :type state: dockermap.map.state.ConfigState :param kwargs: Add...
[ "def", "get_state_actions", "(", "self", ",", "state", ",", "*", "*", "kwargs", ")", ":", "if", "(", "state", ".", "config_id", ".", "config_type", "==", "ItemType", ".", "CONTAINER", "and", "state", ".", "base_state", "!=", "State", ".", "ABSENT", "and"...
51.357143
23.5
def fix(args): """ %prog fix bedfile > newbedfile Fix non-standard bed files. One typical problem is start > end. """ p = OptionParser(fix.__doc__) p.add_option("--minspan", default=0, type="int", help="Enforce minimum span [default: %default]") p.set_outfile() opts, ar...
[ "def", "fix", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "fix", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--minspan\"", ",", "default", "=", "0", ",", "type", "=", "\"int\"", ",", "help", "=", "\"Enforce minimum span [default: %defaul...
27.893617
17.765957
def time(self, subname=None, class_=None): '''Returns a context manager to time execution of a block of code. :keyword subname: The subname to report data to :type subname: str :keyword class_: The :class:`~statsd.client.Client` subclass to use (e.g. :class:`~statsd.timer.Ti...
[ "def", "time", "(", "self", ",", "subname", "=", "None", ",", "class_", "=", "None", ")", ":", "if", "class_", "is", "None", ":", "class_", "=", "Timer", "timer", "=", "self", ".", "get_client", "(", "subname", ",", "class_", ")", "timer", ".", "st...
32.413793
19.724138
def lemmatise_multiple(self, string, pos=False, get_lemma_object=False, as_list=True): """ Lemmatise une liste complète :param string: Chaîne à lemmatiser :param pos: Récupère la POS :param get_lemma_object: Retrieve Lemma object instead of string representation of lemma :param ...
[ "def", "lemmatise_multiple", "(", "self", ",", "string", ",", "pos", "=", "False", ",", "get_lemma_object", "=", "False", ",", "as_list", "=", "True", ")", ":", "mots", "=", "SPACES", ".", "split", "(", "string", ")", "resultats", "=", "[", "self", "."...
48.846154
24.461538
def _summary(self, name=None): """ Return a summarized representation. Parameters ---------- name : str name to use in the summary representation Returns ------- String with a summarized representation of the index """ formatt...
[ "def", "_summary", "(", "self", ",", "name", "=", "None", ")", ":", "formatter", "=", "self", ".", "_formatter_func", "if", "len", "(", "self", ")", ">", "0", ":", "index_summary", "=", "', %s to %s'", "%", "(", "formatter", "(", "self", "[", "0", "]...
29.666667
17.933333
def run(self, input_dir, output_file_path): """Runs defense inside Docker. Args: input_dir: directory with input (adversarial images). output_file_path: path of the output file. Returns: how long it took to run submission in seconds """ logging.info('Running defense %s', self.sub...
[ "def", "run", "(", "self", ",", "input_dir", ",", "output_file_path", ")", ":", "logging", ".", "info", "(", "'Running defense %s'", ",", "self", ".", "submission_id", ")", "tmp_run_dir", "=", "self", ".", "temp_copy_extracted_submission", "(", ")", "output_dir"...
35.535714
14.428571
def _initialize_background(self): """Set up background state (zonal flow and PV gradients).""" # background vel. if len(np.shape(self.U)) == 0: self.U = (self.U * np.ones((self.ny))) print(np.shape(self.U)) self.set_U(self.U) # the meridional PV gradients in e...
[ "def", "_initialize_background", "(", "self", ")", ":", "# background vel.", "if", "len", "(", "np", ".", "shape", "(", "self", ".", "U", ")", ")", "==", "0", ":", "self", ".", "U", "=", "(", "self", ".", "U", "*", "np", ".", "ones", "(", "(", ...
34.588235
24.117647
def main(gi, ranges): """ Print the features of the genbank entry given by gi. If ranges is non-emtpy, only print features that include the ranges. gi: either a hit from a BLAST record, in the form 'gi|63148399|gb|DQ011818.1|' or a gi number (63148399 in this example). ranges: a possibly em...
[ "def", "main", "(", "gi", ",", "ranges", ")", ":", "# TODO: Make it so we can pass a 'db' argument to getSequence.", "record", "=", "getSequence", "(", "gi", ")", "if", "record", "is", "None", ":", "print", "(", "\"Looks like you're offline.\"", ")", "sys", ".", "...
38
18
def insert_image(filename, extnum_filename, auximage, extnum_auximage): """Replace image in filename by another image (same size) in newimage. Parameters ---------- filename : str File name where the new image will be inserted. extnum_filename : int Extension number in filename wher...
[ "def", "insert_image", "(", "filename", ",", "extnum_filename", ",", "auximage", ",", "extnum_auximage", ")", ":", "# read the new image", "with", "fits", ".", "open", "(", "auximage", ")", "as", "hdulist", ":", "newimage", "=", "hdulist", "[", "extnum_auximage"...
34.058824
18.970588
def count_delayed_jobs(cls, names): """ Return the number of all delayed jobs in queues with the given names """ return sum([queue.delayed.zcard() for queue in cls.get_all(names)])
[ "def", "count_delayed_jobs", "(", "cls", ",", "names", ")", ":", "return", "sum", "(", "[", "queue", ".", "delayed", ".", "zcard", "(", ")", "for", "queue", "in", "cls", ".", "get_all", "(", "names", ")", "]", ")" ]
41.6
15.2
def adsr(dur, a, d, s, r): """ Linear ADSR envelope. Parameters ---------- dur : Duration, in number of samples, including the release time. a : "Attack" time, in number of samples. d : "Decay" time, in number of samples. s : "Sustain" amplitude level (should be based on attack amplitud...
[ "def", "adsr", "(", "dur", ",", "a", ",", "d", ",", "s", ",", "r", ")", ":", "m_a", "=", "1.", "/", "a", "m_d", "=", "(", "s", "-", "1.", ")", "/", "d", "m_r", "=", "-", "s", "*", "1.", "/", "r", "len_a", "=", "int", "(", "a", "+", ...
22.605263
20.657895
def _configDevActive(self, namestr, titlestr, devlist): """Generate configuration for I/O Queue Length. @param namestr: Field name component indicating device type. @param titlestr: Title component indicating device type. @param devlist: List of devices. """ ...
[ "def", "_configDevActive", "(", "self", ",", "namestr", ",", "titlestr", ",", "devlist", ")", ":", "name", "=", "'diskio_%s_active'", "%", "namestr", "if", "self", ".", "graphEnabled", "(", "name", ")", ":", "graph", "=", "MuninGraph", "(", "'Disk I/O - %s -...
48.347826
17.913043
def get_unresolved_variables(f): """ Gets unresolved vars from file """ reporter = RReporter() checkPath(f, reporter=reporter) return dict(reporter.messages)
[ "def", "get_unresolved_variables", "(", "f", ")", ":", "reporter", "=", "RReporter", "(", ")", "checkPath", "(", "f", ",", "reporter", "=", "reporter", ")", "return", "dict", "(", "reporter", ".", "messages", ")" ]
25
5.571429
def add_ti_txt(self, lines, overwrite=False): """Add given TI-TXT string `lines`. Set `overwrite` to ``True`` to allow already added data to be overwritten. """ address = None eof_found = False for line in StringIO(lines): # Abort if data is found after end...
[ "def", "add_ti_txt", "(", "self", ",", "lines", ",", "overwrite", "=", "False", ")", ":", "address", "=", "None", "eof_found", "=", "False", "for", "line", "in", "StringIO", "(", "lines", ")", ":", "# Abort if data is found after end of file.", "if", "eof_foun...
33.241379
17.948276
def staticmap(ctx, mapid, output, features, lat, lon, zoom, size): """ Generate static map images from existing Mapbox map ids. Optionally overlay with geojson features. $ mapbox staticmap --features features.geojson mapbox.satellite out.png $ mapbox staticmap --lon -61.7 --lat 12.1 --zoom 12 m...
[ "def", "staticmap", "(", "ctx", ",", "mapid", ",", "output", ",", "features", ",", "lat", ",", "lon", ",", "zoom", ",", "size", ")", ":", "access_token", "=", "(", "ctx", ".", "obj", "and", "ctx", ".", "obj", ".", "get", "(", "'access_token'", ")",...
34.133333
20.133333
def set_unit_spike_features(self, unit_id, feature_name, value): '''This function adds a unit features data set under the given features name to the given unit. Parameters ---------- unit_id: int The unit id for which the features will be set feature_name: st...
[ "def", "set_unit_spike_features", "(", "self", ",", "unit_id", ",", "feature_name", ",", "value", ")", ":", "if", "isinstance", "(", "unit_id", ",", "(", "int", ",", "np", ".", "integer", ")", ")", ":", "if", "unit_id", "in", "self", ".", "get_unit_ids",...
46.551724
25.034483
def gen_TMY(df_output): '''generate TMY (typical meteorological year) from SuPy output. Parameters ---------- df_output : pandas.DataFrame Output from `run_supy`: longterm (e.g., >10 years) simulation results, otherwise not very useful. ''' # calculate weighted score ws = gen_WS_D...
[ "def", "gen_TMY", "(", "df_output", ")", ":", "# calculate weighted score", "ws", "=", "gen_WS_DF", "(", "df_output", ")", "# select year", "year_sel", "=", "pick_year", "(", "ws", ",", "df_output", ",", "n", "=", "5", ")", "# generate TMY data", "df_TMY", "="...
28.821429
24.392857
def get_model_indices(cls, index): ''' Returns the list of model indices (i.e. ModelIndex objects) defined for this index. :param index: index name. ''' try: return cls._idx_name_to_mdl_to_mdlidx[index].values() except KeyError: raise KeyError('Cou...
[ "def", "get_model_indices", "(", "cls", ",", "index", ")", ":", "try", ":", "return", "cls", ".", "_idx_name_to_mdl_to_mdlidx", "[", "index", "]", ".", "values", "(", ")", "except", "KeyError", ":", "raise", "KeyError", "(", "'Could not find any index named {}. ...
45.444444
31
def upgrade_addons_operation(self, addons_state, mode=None): """ Return merged set of main addons and mode's addons """ installed = set(a.name for a in addons_state if a.state in ('installed', 'to upgrade')) base_mode = self._get_version_mode() addons_list = base...
[ "def", "upgrade_addons_operation", "(", "self", ",", "addons_state", ",", "mode", "=", "None", ")", ":", "installed", "=", "set", "(", "a", ".", "name", "for", "a", "in", "addons_state", "if", "a", ".", "state", "in", "(", "'installed'", ",", "'to upgrad...
41.733333
19.2
def debug_print(self): """ Prints the ring for debugging purposes. """ ring = self._fetch_all() print('Hash ring "{key}" replicas:'.format(key=self.key)) now = time.time() n_replicas = len(ring) if ring: print('{:10} {:6} {:7} {}'.format('St...
[ "def", "debug_print", "(", "self", ")", ":", "ring", "=", "self", ".", "_fetch_all", "(", ")", "print", "(", "'Hash ring \"{key}\" replicas:'", ".", "format", "(", "key", "=", "self", ".", "key", ")", ")", "now", "=", "time", ".", "time", "(", ")", "...
32.833333
21.2
def _get_gcloud_sdk_credentials(): """Gets the credentials and project ID from the Cloud SDK.""" from google.auth import _cloud_sdk # Check if application default credentials exist. credentials_filename = ( _cloud_sdk.get_application_default_credentials_path()) if not os.path.isfile(creden...
[ "def", "_get_gcloud_sdk_credentials", "(", ")", ":", "from", "google", ".", "auth", "import", "_cloud_sdk", "# Check if application default credentials exist.", "credentials_filename", "=", "(", "_cloud_sdk", ".", "get_application_default_credentials_path", "(", ")", ")", "...
30.222222
18.833333
def remove_node(cls, cluster_id_label, private_dns, parameters=None): """ Add a node to an existing cluster """ conn = Qubole.agent(version=Cluster.api_version) parameters = {} if not parameters else parameters data = {"private_dns" : private_dns, "parameters" : parameter...
[ "def", "remove_node", "(", "cls", ",", "cluster_id_label", ",", "private_dns", ",", "parameters", "=", "None", ")", ":", "conn", "=", "Qubole", ".", "agent", "(", "version", "=", "Cluster", ".", "api_version", ")", "parameters", "=", "{", "}", "if", "not...
49.375
16.625
def ensure_data_exists(self, request, data, error_message=None): """ Ensure that the wrapped API client's response brings us valid data. If not, raise an error and log it. """ if not data: error_message = ( error_message or "Unable to fetch API response from e...
[ "def", "ensure_data_exists", "(", "self", ",", "request", ",", "data", ",", "error_message", "=", "None", ")", ":", "if", "not", "data", ":", "error_message", "=", "(", "error_message", "or", "\"Unable to fetch API response from endpoint '{}'.\"", ".", "format", "...
45.3
22.9
def get_items(self, project=None, scope_path=None, recursion_level=None, include_links=None, version_descriptor=None): """GetItems. Get a list of Tfvc items :param str project: Project ID or project name :param str scope_path: Version control path of a folder to return multiple items. ...
[ "def", "get_items", "(", "self", ",", "project", "=", "None", ",", "scope_path", "=", "None", ",", "recursion_level", "=", "None", ",", "include_links", "=", "None", ",", "version_descriptor", "=", "None", ")", ":", "route_values", "=", "{", "}", "if", "...
63.666667
29.212121
def pop(self, timeout=None): """ :param timeout: OPTIONAL DURATION :return: None, IF timeout PASSES """ with self.lock: while not self.please_stop: if self.db.status.end > self.start: value = self.db[str(self.start)] ...
[ "def", "pop", "(", "self", ",", "timeout", "=", "None", ")", ":", "with", "self", ".", "lock", ":", "while", "not", "self", ".", "please_stop", ":", "if", "self", ".", "db", ".", "status", ".", "end", ">", "self", ".", "start", ":", "value", "=",...
34.227273
11.227273
def get_url(self, resource, params=None): """ Generate url for request """ # replace placeholders pattern = r'\{(.+?)\}' resource = re.sub(pattern, lambda t: str(params.get(t.group(1), '')), resource) # build url parts = (self.endpoint, '/api/', r...
[ "def", "get_url", "(", "self", ",", "resource", ",", "params", "=", "None", ")", ":", "# replace placeholders", "pattern", "=", "r'\\{(.+?)\\}'", "resource", "=", "re", ".", "sub", "(", "pattern", ",", "lambda", "t", ":", "str", "(", "params", ".", "get"...
25.266667
21.8
def pick_tile_size(self, seg_size, data_lengths, valid_chunks, valid_lengths): """ Choose job tiles size based on science segment length """ if len(valid_lengths) == 1: return data_lengths[0], valid_chunks[0], valid_lengths[0] else: # Pick the tile size that is closest t...
[ "def", "pick_tile_size", "(", "self", ",", "seg_size", ",", "data_lengths", ",", "valid_chunks", ",", "valid_lengths", ")", ":", "if", "len", "(", "valid_lengths", ")", "==", "1", ":", "return", "data_lengths", "[", "0", "]", ",", "valid_chunks", "[", "0",...
53.692308
22.846154
def fetch_country_by_ip(ip): """ Fetches country code by IP Returns empty string if the request fails in non-200 code. Uses the ipdata.co service which has the following rules: * Max 1500 requests per day See: https://ipdata.co/docs.html#python-library """ iplookup = ipdata.ipdata() ...
[ "def", "fetch_country_by_ip", "(", "ip", ")", ":", "iplookup", "=", "ipdata", ".", "ipdata", "(", ")", "data", "=", "iplookup", ".", "lookup", "(", "ip", ")", "if", "data", ".", "get", "(", "'status'", ")", "!=", "200", ":", "return", "''", "return",...
24.777778
19.666667
def dup(args): """ %prog dup frgscffile Use the frgscf posmap file as an indication of the coverage of the library. Large insert libraries are frequently victims of high levels of redundancy. """ p = OptionParser(dup.__doc__) opts, args = p.parse_args(args) if len(args) != 1: s...
[ "def", "dup", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "dup", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "1", ":", "sys", ".", "exit", "(", "p", "...
31.511111
18.088889
def compute_empirical(cls, X): """Compute empirical distribution.""" z_left = [] z_right = [] L = [] R = [] U, V = cls.split_matrix(X) N = len(U) base = np.linspace(EPSILON, 1.0 - EPSILON, COMPUTE_EMPIRICAL_STEPS) # See https://github.com/DAI-Lab/...
[ "def", "compute_empirical", "(", "cls", ",", "X", ")", ":", "z_left", "=", "[", "]", "z_right", "=", "[", "]", "L", "=", "[", "]", "R", "=", "[", "]", "U", ",", "V", "=", "cls", ".", "split_matrix", "(", "X", ")", "N", "=", "len", "(", "U",...
29.923077
21.192308
def square_off(series, time_delta=None, transition_seconds=1): """Insert samples in regularly sampled data to produce stairsteps from ramps when plotted. New samples are 1 second (1e9 ns) before each existing samples, to facilitate plotting and sorting >>> square_off(pd.Series(range(3), index=pd.date_rang...
[ "def", "square_off", "(", "series", ",", "time_delta", "=", "None", ",", "transition_seconds", "=", "1", ")", ":", "if", "time_delta", ":", "# int, float means delta is in seconds (not years!)", "if", "isinstance", "(", "time_delta", ",", "(", "int", ",", "float",...
46.363636
19.969697
def dump(o, f): """Writes out dict as toml to a file Args: o: Object to dump into toml f: File descriptor where the toml should be stored Returns: String containing the toml corresponding to dictionary Raises: TypeError: When anything other than file descriptor is pass...
[ "def", "dump", "(", "o", ",", "f", ")", ":", "if", "not", "f", ".", "write", ":", "raise", "TypeError", "(", "\"You can only dump an object to a file descriptor\"", ")", "d", "=", "dumps", "(", "o", ")", "f", ".", "write", "(", "d", ")", "return", "d" ...
23.894737
25.315789
def add_route(app_or_blueprint, fn, context=default_context): """ a decorator that adds a transmute route to the application """ transmute_func = TransmuteFunction( fn, args_not_from_request=["request"] ) handler = create_handler(transmute_func, context=context) get_swagger_s...
[ "def", "add_route", "(", "app_or_blueprint", ",", "fn", ",", "context", "=", "default_context", ")", ":", "transmute_func", "=", "TransmuteFunction", "(", "fn", ",", "args_not_from_request", "=", "[", "\"request\"", "]", ")", "handler", "=", "create_handler", "(...
41.461538
17.461538
def Expect(inner_rule, loc=None): """A rule that executes ``inner_rule`` and emits a diagnostic error if it returns None.""" @llrule(loc, inner_rule.expected) def rule(parser): result = inner_rule(parser) if result is unmatched: expected = reduce(list.__add__, [rule.expected(pars...
[ "def", "Expect", "(", "inner_rule", ",", "loc", "=", "None", ")", ":", "@", "llrule", "(", "loc", ",", "inner_rule", ".", "expected", ")", "def", "rule", "(", "parser", ")", ":", "result", "=", "inner_rule", "(", "parser", ")", "if", "result", "is", ...
41.333333
16.833333
def quit(self): """Close driver and kill all associated displays """ # Kill the driver def _quit(): try: self.driver.quit() except Exception, err_driver: os.kill(self.driver_pid, signal.SIGKILL) raise f...
[ "def", "quit", "(", "self", ")", ":", "# Kill the driver", "def", "_quit", "(", ")", ":", "try", ":", "self", ".", "driver", ".", "quit", "(", ")", "except", "Exception", ",", "err_driver", ":", "os", ".", "kill", "(", "self", ".", "driver_pid", ",",...
31.857143
16.095238
def template(template_name): """Return a jinja template ready for rendering. If needed, global variables are initialized. Parameters ---------- template_name: str, the name of the template as defined in the templates mapping Returns ------- The Jinja template ready for rendering """ ...
[ "def", "template", "(", "template_name", ")", ":", "globals", "=", "None", "if", "template_name", ".", "startswith", "(", "'row_'", ")", ":", "# This is a row template setting global variable", "globals", "=", "dict", "(", ")", "globals", "[", "'vartype'", "]", ...
35.058824
21.941176
def distinct(self, *columns, **_filter): """ Returns all rows of a table, but removes rows in with duplicate values in ``columns``. Interally this creates a `DISTINCT statement <http://www.w3schools.com/sql/sql_distinct.asp>`_. :: # returns only one row per year, ignoring th...
[ "def", "distinct", "(", "self", ",", "*", "columns", ",", "*", "*", "_filter", ")", ":", "self", ".", "_check_dropped", "(", ")", "qargs", "=", "[", "]", "try", ":", "columns", "=", "[", "self", ".", "table", ".", "c", "[", "c", "]", "for", "c"...
37.882353
18.882353
def list_networks(conn=None, call=None): ''' List networks for OpenStack CLI Example .. code-block:: bash salt-cloud -f list_networks myopenstack ''' if call == 'action': raise SaltCloudSystemExit( 'The list_networks function must be called with ' '-f ...
[ "def", "list_networks", "(", "conn", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The list_networks function must be called with '", "'-f or --function'", ")", "if", "conn", "is", "Non...
21.315789
21.631579
def children(self, val: list): """ Sets children :param val: List of citation children """ final_value = [] if val is not None: for citation in val: if citation is None: continue elif not isinstance(citation, (BaseC...
[ "def", "children", "(", "self", ",", "val", ":", "list", ")", ":", "final_value", "=", "[", "]", "if", "val", "is", "not", "None", ":", "for", "citation", "in", "val", ":", "if", "citation", "is", "None", ":", "continue", "elif", "not", "isinstance",...
34.2
14.5
def render_source(output_dir, package_spec, jenv=JENV): """ Render and output """ path, module_name = package_spec.filepath java_template = jenv.get_template(TEMPLATE_NAME) module_path = "com." + package_spec.identifier yaml_filepath = "/".join(package_spec.filepath) + ".yaml" includes = [".".join(i.spl...
[ "def", "render_source", "(", "output_dir", ",", "package_spec", ",", "jenv", "=", "JENV", ")", ":", "path", ",", "module_name", "=", "package_spec", ".", "filepath", "java_template", "=", "jenv", ".", "get_template", "(", "TEMPLATE_NAME", ")", "module_path", "...
45.461538
16.538462
def signature(frame): '''return suitable frame signature to key display expressions off of.''' if not frame: return None code = frame.f_code return (code.co_name, code.co_filename, code.co_firstlineno)
[ "def", "signature", "(", "frame", ")", ":", "if", "not", "frame", ":", "return", "None", "code", "=", "frame", ".", "f_code", "return", "(", "code", ".", "co_name", ",", "code", ".", "co_filename", ",", "code", ".", "co_firstlineno", ")" ]
42.6
21.4
def validate_email(value: str) -> Tuple[str, str]: """ Brutally simple email address validation. Note unlike most email address validation * raw ip address (literal) domain parts are not allowed. * "John Doe <local_part@domain.com>" style "pretty" email addresses are processed * the local part check...
[ "def", "validate_email", "(", "value", ":", "str", ")", "->", "Tuple", "[", "str", ",", "str", "]", ":", "if", "email_validator", "is", "None", ":", "raise", "ImportError", "(", "'email-validator is not installed, run `pip install pydantic[email]`'", ")", "m", "="...
42.111111
27.666667
def has_kingside_castling_rights(self, color: Color) -> bool: """ Checks if the given side has kingside (that is h-side in Chess960) castling rights. """ backrank = BB_RANK_1 if color == WHITE else BB_RANK_8 king_mask = self.kings & self.occupied_co[color] & backrank & ~s...
[ "def", "has_kingside_castling_rights", "(", "self", ",", "color", ":", "Color", ")", "->", "bool", ":", "backrank", "=", "BB_RANK_1", "if", "color", "==", "WHITE", "else", "BB_RANK_8", "king_mask", "=", "self", ".", "kings", "&", "self", ".", "occupied_co", ...
33.55
22.25
def toxml(self): """ Exports this object into a LEMS XML object """ chxmlstr = '' for state_variable in self.state_variables: chxmlstr += state_variable.toxml() for derived_variable in self.derived_variables: chxmlstr += derived_variable.toxml()...
[ "def", "toxml", "(", "self", ")", ":", "chxmlstr", "=", "''", "for", "state_variable", "in", "self", ".", "state_variables", ":", "chxmlstr", "+=", "state_variable", ".", "toxml", "(", ")", "for", "derived_variable", "in", "self", ".", "derived_variables", "...
30.777778
19.4
def get_processors(processor_cat, prop_defs, data_attr=None): """ reads the prop defs and adds applicable processors for the property Args: processor_cat(str): The category of processors to retreive prop_defs: property defintions as defined by the rdf defintions data_attr: the attr to m...
[ "def", "get_processors", "(", "processor_cat", ",", "prop_defs", ",", "data_attr", "=", "None", ")", ":", "processor_defs", "=", "prop_defs", ".", "get", "(", "processor_cat", ",", "[", "]", ")", "processor_list", "=", "[", "]", "for", "processor", "in", "...
40.111111
20.111111
def get_all_comments_of_credit_note(self, credit_note_id): """ Get all comments of credit note This will iterate over all pages until it gets all elements. So if the rate limit exceeded it will throw an Exception and you will get nothing :param credit_note_id: the credit note id...
[ "def", "get_all_comments_of_credit_note", "(", "self", ",", "credit_note_id", ")", ":", "return", "self", ".", "_iterate_through_pages", "(", "get_function", "=", "self", ".", "get_comments_of_credit_note_per_page", ",", "resource", "=", "CREDIT_NOTE_COMMENTS", ",", "*"...
39.642857
16.785714
def validate_extra_link(self, extra_link): """validate extra link""" if EXTRA_LINK_NAME_KEY not in extra_link or EXTRA_LINK_FORMATTER_KEY not in extra_link: raise Exception("Invalid extra.links format. " + "Extra link must include a 'name' and 'formatter' field") self.validated_...
[ "def", "validate_extra_link", "(", "self", ",", "extra_link", ")", ":", "if", "EXTRA_LINK_NAME_KEY", "not", "in", "extra_link", "or", "EXTRA_LINK_FORMATTER_KEY", "not", "in", "extra_link", ":", "raise", "Exception", "(", "\"Invalid extra.links format. \"", "+", "\"Ext...
47.75
23.875
def get(self, wrap_exception=False): """ Return the return value of this Attempt instance or raise an Exception. If wrap_exception is true, this Attempt is wrapped inside of a RetryError before being raised. """ if self.has_exception: if wrap_exception: ...
[ "def", "get", "(", "self", ",", "wrap_exception", "=", "False", ")", ":", "if", "self", ".", "has_exception", ":", "if", "wrap_exception", ":", "raise", "RetryError", "(", "self", ")", "else", ":", "six", ".", "reraise", "(", "self", ".", "value", "[",...
36.538462
14.538462
def json(self): """Serialise the document to a ``dict`` ready for serialisation to JSON. Example:: import json jsondoc = json.dumps(doc.json()) """ self.pendingvalidation() jsondoc = {'id': self.id, 'children': [], 'declarations': self.jsondeclarations(...
[ "def", "json", "(", "self", ")", ":", "self", ".", "pendingvalidation", "(", ")", "jsondoc", "=", "{", "'id'", ":", "self", ".", "id", ",", "'children'", ":", "[", "]", ",", "'declarations'", ":", "self", ".", "jsondeclarations", "(", ")", "}", "if",...
30.55
20.4
def _pressModifiers(self, modifiers, pressed=True, globally=False): """Press given modifiers (provided in list form). Parameters: modifiers list, global or app specific Optional: keypressed state (default is True (down)) Returns: Unsigned int representing flags to set """ ...
[ "def", "_pressModifiers", "(", "self", ",", "modifiers", ",", "pressed", "=", "True", ",", "globally", "=", "False", ")", ":", "if", "not", "isinstance", "(", "modifiers", ",", "list", ")", ":", "raise", "TypeError", "(", "'Please provide modifiers in list for...
41.355556
18.777778
def uninstall(client): """Uninstall Git hooks.""" from git.index.fun import hook_path as get_hook_path for hook in HOOKS: hook_path = Path(get_hook_path(hook, client.repo.git_dir)) if hook_path.exists(): hook_path.unlink()
[ "def", "uninstall", "(", "client", ")", ":", "from", "git", ".", "index", ".", "fun", "import", "hook_path", "as", "get_hook_path", "for", "hook", "in", "HOOKS", ":", "hook_path", "=", "Path", "(", "get_hook_path", "(", "hook", ",", "client", ".", "repo"...
32
17.25