code
stringlengths
51
2.34k
sequence
stringlengths
186
3.94k
docstring
stringlengths
11
171
def load_config(configfile): try: with open(configfile, 'r') as ymlfile: try: config = yaml.load(ymlfile) return config except yaml.parser.ParserError: raise PyYAMLConfigError( 'Could not parse config file: {}'.forma...
module function_definition identifier parameters identifier block try_statement block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block try_statement block expression_statement assignment identifier c...
Return a dict with configuration from the supplied yaml file
def http_call(self, url=None, **kwargs): if not url: url = self.search_url http_func, arg_name = self.get_http_method_arg_name() _kwargs = { arg_name: kwargs, } response = http_func( url=url.format(**kwargs), headers=self.get_http_h...
module function_definition identifier parameters identifier default_parameter identifier none dictionary_splat_pattern identifier block if_statement not_operator identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment pattern_list identifier identifier...
Call the target URL via HTTP and return the JSON result
def metadataContributer(self): if self._metaFL is None: fl = FeatureService(url=self._metadataURL, proxy_url=self._proxy_url, proxy_port=self._proxy_port) self._metaFS = fl return self._metaFS
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identif...
gets the metadata featurelayer object
def shared_atts(self): atts = {} first = self.chunks[0] for att in sorted(first.atts): if all(fs.atts.get(att, '???') == first.atts[att] for fs in self.chunks if len(fs) > 0): atts[att] = first.atts[att] return atts
module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary expression_statement assignment identifier subscript attribute identifier identifier integer for_statement identifier call identifier argument_list attribute identifier identifier block if_statement c...
Gets atts shared among all nonzero length component Chunk
def copy(self, *args, **kwargs): for slot in self.__slots__: attr = getattr(self, slot) if slot[0] == '_': slot = slot[1:] if slot not in kwargs: kwargs[slot] = attr result = type(self)(*args, **kwargs) return result
module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block for_statement identifier attribute identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier if_statement comparison_operat...
Copy this model element and contained elements if they exist.
def _build_codes() -> Dict[str, Dict[str, str]]: built = { 'fore': {}, 'back': {}, 'style': {}, } for name, number in _namemap: built['fore'][name] = codeformat(30 + number) built['back'][name] = codeformat(40 + number) litename = 'light{}'.format(name) ...
module function_definition identifier parameters type generic_type identifier type_parameter type identifier type generic_type identifier type_parameter type identifier type identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end dictionary pair string s...
Build code map, encapsulated to reduce module-level globals.
def _vcf_info(start, end, mate_id, info=None): out = "SVTYPE=BND;MATEID={mate};IMPRECISE;CIPOS=0,{size}".format( mate=mate_id, size=end-start) if info is not None: extra_info = ";".join("{0}={1}".format(k, v) for k, v in info.iteritems()) out = "{0};{1}".format(out, extra_info) retur...
module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier identifier keyword_argument identifier bi...
Return breakend information line with mate and imprecise location.
def _write_bed_header(self): final_byte = 1 if self._bed_format == "SNP-major" else 0 self._bed.write(bytearray((108, 27, final_byte)))
module function_definition identifier parameters identifier block expression_statement assignment identifier conditional_expression integer comparison_operator attribute identifier identifier string string_start string_content string_end integer expression_statement call attribute attribute identifier identifier identi...
Writes the BED first 3 bytes.
def vsh(cmd, *args, **kw): args = '" "'.join(i.replace('"', r'\"') for i in args) easy.sh('"%s" "%s"' % (venv_bin(cmd), args))
module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier generator_expression call attribute identifier identifier argument_list s...
Execute a command installed into the active virtualenv.
def map_package(shutit_pexpect_session, package, install_type): if package in PACKAGE_MAP.keys(): for itype in PACKAGE_MAP[package].keys(): if itype == install_type: ret = PACKAGE_MAP[package][install_type] if isinstance(ret,str): return ret if callable(ret): ret(shutit_pexpect_session) ...
module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier call attribute identifier identifier argument_list block for_statement identifier call attribute subscript identifier identifier identifier argument_list block if_statement comparison_oper...
If package mapping exists, then return it, else return package.
def git_ls_tree(repo_dir, treeish='HEAD'): command = ['git', 'ls-tree', '-r', '--full-tree', treeish] raw = execute_git_command(command, repo_dir=repo_dir).splitlines() output = [l.strip() for l in raw if l.strip()] breakout = [k.split(None, 3) for k in output] headers = ['mode', 'type', 'object', '...
module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content stri...
Run git ls-tree.
def do_EOF(self, args): if _debug: ConsoleCmd._debug("do_EOF %r", args) return self.do_exit(args)
module function_definition identifier parameters identifier identifier block if_statement identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement call attribute identifier identifier argument_list identifier
Exit on system end of file character
def unzip_unicode(output, version): unzipper = zipfile.ZipFile(os.path.join(output, 'unicodedata', '%s.zip' % version)) target = os.path.join(output, 'unicodedata', version) print('Unzipping %s.zip...' % version) os.makedirs(target) for f in unzipper.namelist(): unzipper.extract(f, target)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end binary_operator stri...
Unzip the Unicode files.
def add_arguments(cls, parser, sys_arg_list=None): parser.add_argument('--tcp_check_interval', dest='tcp_check_interval', required=False, default=2, type=float, help="TCP health-test interval in seconds, " ...
module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument ...
Arguments for the TCP health monitor plugin.
def _triplify_object(self, data, parent): subject = self.get_subject(data) if self.path: yield (subject, TYPE_SCHEMA, self.path, TYPE_SCHEMA) if parent is not None: yield (parent, self.predicate, subject, TYPE_LINK) if self.reverse is not None: ...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement attribute identifier identifier block expression_statement yield tuple identifier identifier attribute identifier ...
Create bi-directional statements for object relationships.
def response_json(self, status, response, content_type='application/json', encoding='utf-8', headers=None, jsonp=None): encoder = JSONEncoder( check_circular=self.app.validate_output, allow_nan=False, sort_keys=True, indent=2 if self.app.pretty_output else None, ...
module function_definition identifier parameters identifier identifier identifier default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_content string_end default_parameter identifier none default_parameter identifier none block expression_sta...
Send a JSON response
def render_formset_errors(formset, **kwargs): renderer_cls = get_formset_renderer(**kwargs) return renderer_cls(formset, **kwargs).render_errors()
module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list dictionary_splat identifier return_statement call attribute call identifier argument_list identifier dictionary_splat identifier identifier argum...
Render formset errors to a Bootstrap layout
def find_resources(client): wildcard = Keys.DISPENSER.format('*') pattern = re.compile(Keys.DISPENSER.format('(.*)')) return [pattern.match(d).group(1) for d in client.scan_iter(wildcard)]
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list...
Detect dispensers and return corresponding resources.
def find_build_dir(path, build="_build"): path = os.path.abspath(os.path.expanduser(path)) contents = os.listdir(path) filtered_contents = [directory for directory in contents if os.path.isdir(os.path.join(path, directory))] if build in filtered_contents: return os.pa...
module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argume...
try to guess the build folder's location
def create(self, weeks): user_pageviews = self.create_profiles('Pageviews', weeks) user_downloads = self.create_profiles('Downloads', weeks) self._export_profiles('Profiles', user_pageviews, user_downloads) user_pageviews = self.create_profiles('Pageviews_IP', weeks, True) user_d...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_lis...
Create the user and ip profiles for the given weeks.
def pairwise_mean(values): "Averages between a value and the next value in a sequence" return numpy.array([numpy.mean(pair) for pair in pairwise(values)])
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end return_statement call attribute identifier identifier argument_list list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier call identifi...
Averages between a value and the next value in a sequence
def current_settings(self): settings = {} if not self.status_data: return settings for (key, val) in self.status_data.get('curvals', {}).items(): try: val = float(val) except ValueError: val = val if val in ('on', 'o...
module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary if_statement not_operator attribute identifier identifier block return_statement identifier for_statement tuple_pattern identifier identifier call attribute call attribute attribute identifier identif...
Return dict with all config include.
def scale_to(x, ratio, targ): return max(math.floor(x*ratio), targ)
module function_definition identifier parameters identifier identifier identifier block return_statement call identifier argument_list call attribute identifier identifier argument_list binary_operator identifier identifier identifier
Calculate dimension of an image during scaling with aspect ratio
def verify_chunks(self, chunks): err = [] for chunk in chunks: err.extend(self.verify_data(chunk)) return err
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier return_statement id...
Verify the chunks in a list of low data structures
def add_unique_template_variables(self, options): options.update(dict( geojson_data=json.dumps(self.data, ensure_ascii=False), colorProperty=self.color_property, colorType=self.color_function_type, colorStops=self.color_stops, strokeWidth=self.stroke_w...
module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier fa...
Update map template variables specific to circle visual
def _adb_screencap(self, scale=1.0): remote_file = tempfile.mktemp(dir='/data/local/tmp/', prefix='screencap-', suffix='.png') local_file = tempfile.mktemp(prefix='atx-screencap-', suffix='.png') self.shell('screencap', '-p', remote_file) try: self.pull(remote_file, local_fil...
module function_definition identifier parameters identifier default_parameter identifier float block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start str...
capture screen with adb shell screencap
def reset_kernel(self): client = self.get_current_client() if client is not None: self.switch_to_plugin() client.reset_namespace()
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list expression_statement call attribu...
Reset kernel of current client.
def summary(self): print("\nStatus summary") print("=" * 79) print("{0}found {1} dependencies in {2} packages.{3}\n".format( self.grey, self.count_dep, self.count_pkg, self.endc))
module function_definition identifier parameters identifier block expression_statement call identifier argument_list string string_start string_content escape_sequence string_end expression_statement call identifier argument_list binary_operator string string_start string_content string_end integer expression_statement...
Summary by packages and dependencies
def link_docstring(modules, docstring:str, overwrite:bool=False)->str: "Search `docstring` for backticks and attempt to link those functions to respective documentation." mods = listify(modules) for mod in mods: _modvars.update(mod.__dict__) return re.sub(BT_REGEX, replace_link, docstring)
module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_default_parameter identifier type identifier false type identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call identifier argument_lis...
Search `docstring` for backticks and attempt to link those functions to respective documentation.
def pretty_print_table_instance(table): assert isinstance(table, Table) def pretty_print_row(styled, plain): click.secho( " | ".join( v + " " * (table.column_widths[k] - len(plain[k])) for k, v in enumerate(styled) ) ) pretty_print_row(...
module function_definition identifier parameters identifier block assert_statement call identifier argument_list identifier identifier function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_c...
Pretty print a table instance.
def delete_set(self, x): if x not in self._parents: return members = list(self.members(x)) for v in members: del self._parents[v] del self._weights[v] del self._prev_next[v] del self._min_values[v]
module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block return_statement expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list identifier for_state...
Removes the equivalence class containing `x`.
def edge_list(self) -> List[Edge]: return [edge for edge in sorted(self._edges.values(), key=attrgetter("key"))]
module function_definition identifier parameters identifier type generic_type identifier type_parameter type identifier block return_statement list_comprehension identifier for_in_clause identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list keyword_argument ide...
The ordered list of edges in the container.
def _caching_enabled(self): try: config = self._runtime.get_configuration() parameter_id = Id('parameter:useCachingForQualifierIds@json') if config.get_value_by_parameter(parameter_id).get_boolean_value(): return True else: return F...
module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call identifier argument_list string string_start string_content string_end ...
Returns True if caching is enabled per configuration, false otherwise.
def addFeaturesSearchOptions(parser): addFeatureSetIdArgument(parser) addFeaturesReferenceNameArgument(parser) addStartArgument(parser) addEndArgument(parser) addParentFeatureIdArgument(parser) addFeatureTypesArgument(parser)
module function_definition identifier parameters identifier block expression_statement call identifier argument_list identifier expression_statement call identifier argument_list identifier expression_statement call identifier argument_list identifier expression_statement call identifier argument_list identifier expres...
Adds common options to a features search command line parser.
def _relative_frequency(self, word): count = self.type_counts.get(word, 0) return math.log(count/len(self.type_counts)) if count > 0 else 0
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier integer return_statement conditional_expression call attribute identifier identifier argument_list binary_operator id...
Computes the log relative frequency for a word form
def close(self): uwsgi.disconnect() if self._req_ctx is None: self._select_greenlet.kill() self._event.set()
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list expression_st...
Disconnects uWSGI from the client.
def add(self, items): options = self._create_options(items) for k, v in options.items(): if k in self.labels and v not in self.items: options.pop(k) count = 0 while f'{k}_{count}' in self.labels: count += 1 o...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement boolean_operator co...
Add items to options
def isotime(at=None, subsecond=False): if not at: at = utcnow() st = at.strftime(_ISO8601_TIME_FORMAT if not subsecond else _ISO8601_TIME_FORMAT_SUBSECOND) tz = at.tzinfo.tzname(None) if at.tzinfo else 'UTC' st += ('Z' if tz == 'UTC' else tz) return ...
module function_definition identifier parameters default_parameter identifier none default_parameter identifier false block if_statement not_operator identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call attribute identifier identifier ...
Stringify time in ISO 8601 format.
def read(url, **kwargs): response = open_url(url, **kwargs) try: return response.read() finally: response.close()
module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list identifier dictionary_splat identifier try_statement block return_statement call attribute identifier identifier argument_list finally_clause blo...
Read the contents of a URL into memory, return
def euclid(a, b): a = abs(a) b = abs(b) if a < b: a, b = b, a while b != 0: a, b = b, a % b return a
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier identifier block expression_sta...
returns the Greatest Common Divisor of a and b
def _get_image_size(self, maxcharno, maxlineno): return (self._get_char_x(maxcharno) + self.image_pad, self._get_line_y(maxlineno + 0) + self.image_pad)
module function_definition identifier parameters identifier identifier identifier block return_statement tuple binary_operator call attribute identifier identifier argument_list identifier attribute identifier identifier binary_operator call attribute identifier identifier argument_list binary_operator identifier integ...
Get the required image size.
def merged_gasmap(self, **kwargs): kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) self._replace_none(kwargs_copy) localpath = NameFactory.merged_gasmap_format.format(**kwargs_copy) if kwargs.get('fullpath', False): return self.fullpath(localp...
module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list dictionary_splat identifier exp...
return the file name for Galprop merged gasmaps
def get(self, key: Text, locale: Optional[Text]) -> List[Tuple[Text, ...]]: locale = self.choose_locale(locale) return self.dict[locale][key]
module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type generic_type identifier type_parameter type identifier type generic_type identifier type_parameter type generic_type identifier type_parameter type identifier type ellipsis block expres...
Get a single set of intents.
def use_settings(**kwargs): from omnic import singletons singletons.settings.use_settings_dict(kwargs) yield singletons.settings.use_previous_settings()
module function_definition identifier parameters dictionary_splat_pattern identifier block import_from_statement dotted_name identifier dotted_name identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement yield expression_statement call attr...
Context manager to temporarily override settings
def _role_remove(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): if not user_exists(name, user, host, port, maintenance_db, password=password, runas=runas): log.info('User \'%s\' does not exist', name) return False s...
module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none block if_statement not_operator call identifier argument...
Removes a role from the Postgres Server
def _write(self, session, openFile, replaceParamFile): hmetRecords = self.hmetRecords for record in hmetRecords: openFile.write('%s\t%s\t%s\t%s\t%.3f\t%s\t%s\t%s\t%s\t%.2f\t%.2f\n' % ( record.hmetDateTime.year, record.hmetDateTime.month, record...
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier attribute identifier identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_st...
Write HMET WES to File Method
def EnsureSConsVersion(self, major, minor, revision=0): if SCons.__version__ == '__' + 'VERSION__': SCons.Warnings.warn(SCons.Warnings.DevelopmentVersionWarning, "EnsureSConsVersion is ignored for development version") return scons_ver = self._get_major_minor_revi...
module function_definition identifier parameters identifier identifier identifier default_parameter identifier integer block if_statement comparison_operator attribute identifier identifier binary_operator string string_start string_content string_end string string_start string_content string_end block expression_state...
Exit abnormally if the SCons version is not late enough.
def s3_etag(url: str) -> Optional[str]: s3_resource = boto3.resource("s3") bucket_name, s3_path = split_s3_path(url) s3_object = s3_resource.Object(bucket_name, s3_path) return s3_object.e_tag
module function_definition identifier parameters typed_parameter identifier type identifier type generic_type identifier type_parameter type identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement a...
Check ETag on S3 object.
def _byteify(data): if isinstance(data, six.text_type): return data.encode("utf-8") if isinstance(data, list): return [_byteify(item) for item in data] if isinstance(data, dict): return { _byteify(key): _byteify(value) for key, value in data.items() } return d...
module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier attribute identifier identifier block return_statement call attribute identifier identifier argument_list string string_start string_content string_end if_statement call identifier argument_list ident...
Convert unicode to bytes
def remove_workspace(self): def confirm_clicked(): if len(self.document_model.workspaces) > 1: command = Workspace.RemoveWorkspaceCommand(self) command.perform() self.document_controller.push_undo_command(command) caption = _("Remove workspace ...
module function_definition identifier parameters identifier block function_definition identifier parameters block if_statement comparison_operator call identifier argument_list attribute attribute identifier identifier identifier integer block expression_statement assignment identifier call attribute identifier identif...
Pose a dialog to confirm removal then remove workspace.
def add_view(self, *args, **kwargs): try: singleton = self.model.objects.get() except (self.model.DoesNotExist, self.model.MultipleObjectsReturned): kwargs.setdefault("extra_context", {}) kwargs["extra_context"]["singleton"] = True response = super(Singlet...
module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block try_statement block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list except_clause tuple attribute at...
Redirect to the change view if the singleton instance exists.
def _filter_by_pattern(self, pattern): try: _len = len(pattern) except TypeError: raise TypeError("pattern is not a list of Booleans. Got {}".format( type(pattern))) _filt_values = [d for i, d in enumerate(self._values) if pattern[i % _len]] _filt_...
module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier call identifier argument_list identifier except_clause identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end i...
Filter the Filter the Data Collection based on a list of booleans.
def _utc_float(self): tai = self.tai leap_dates = self.ts.leap_dates leap_offsets = self.ts.leap_offsets leap_reverse_dates = leap_dates + leap_offsets / DAY_S i = searchsorted(leap_reverse_dates, tai, 'right') return tai - leap_offsets[i] / DAY_S
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier attribute attribute identifier identifie...
Return UTC as a floating point Julian date.
def url(self): url = u'{home_url}{permalink}'.format(home_url=settings.HOME_URL, permalink=self._permalink) url = re.sub(r'/{2,}', r'/', url) return url
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expre...
The site-relative URL to the post.
def _parse_template(self, has_content): reset = self._head context = contexts.TEMPLATE_NAME if has_content: context |= contexts.HAS_TEMPLATE try: template = self._parse(context) except BadRoute: self._head = reset raise self...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier if_statement identifier block expression_statement augmented_assignment identifier attribute ...
Parse a template at the head of the wikicode string.
def remove_api_key(self, api_id, stage_name): response = self.apigateway_client.get_api_keys( limit=1, nameQuery='{}_{}'.format(stage_name, api_id) ) for api_key in response.get('items'): self.apigateway_client.delete_api_key( apiKey="{}".forma...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier integer keyword_argument identifier call attribute string string_start string_content str...
Remove a generated API key for api_id and stage_name
def bar(self, progress): if not hasattr(self, "_limit") or not self._limit: self._limit = self.terminal_size() graph_progress = int(progress * self._limit) self.stdout.write('\r', ending='') progress_format = "[%-{}s] %d%%".format(self._limit) self.stdout.write( ...
module function_definition identifier parameters identifier identifier block if_statement boolean_operator not_operator call identifier argument_list identifier string string_start string_content string_end not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifie...
Shows on the stdout the progress bar for the given progress.
def clean_new(self, value): value = self.schema_class(value).full_clean() return self.object_class(**value)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier identifier argument_list return_statement call attribute identifier identifier argument_list dictionary_splat identifier
Return a new object instantiated with cleaned data.
def makeHawkExt(self): o = self.options c = o.get('credentials', {}) if c.get('clientId') and c.get('accessToken'): ext = {} cert = c.get('certificate') if cert: if six.PY3 and isinstance(cert, six.binary_type): cert = cert....
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end dictionary if_statement boolean_operato...
Make an 'ext' for Hawk authentication
def server_info(self): response = self._post(self.apiurl + "/v2/server/info", data={'apikey': self.apikey}) return self._raise_or_extract(response)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator attribute identifier identifier string string_start string_content string_end keyword_argument identifier dictionary pair string string_start st...
Query information about the server.
def print_subcommands(self): lines = ["Call"] lines.append('-'*len(lines[-1])) lines.append('') lines.append("> jhubctl <subcommand> <resource-type> <resource-name>") lines.append('') lines.append("Subcommands") lines.append('-'*len(lines[-1])) lines.appen...
module function_definition identifier parameters identifier block expression_statement assignment identifier list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end call identifier argument_l...
Print the subcommand part of the help.
def load_context(context, file_path=None): if not file_path: file_path = _get_context_filepath() if os.path.exists(file_path): with io.open(file_path, encoding='utf-8') as f: for line in f: execute(line, context)
module function_definition identifier parameters identifier default_parameter identifier none block if_statement not_operator identifier block expression_statement assignment identifier call identifier argument_list if_statement call attribute attribute identifier identifier identifier argument_list identifier block wi...
Load a Context object in place from user data directory.
def limit(self, keys): if not isinstance(keys, list) and not isinstance(keys, tuple): keys = [keys] remove_keys = [k for k in self.keys() if k not in keys] for k in remove_keys: self.pop(k)
module function_definition identifier parameters identifier identifier block if_statement boolean_operator not_operator call identifier argument_list identifier identifier not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier list identifier expression_stateme...
Remove all keys other than the keys specified.
def profile_path(profile_id, profile): user = os.path.expanduser("~") return os.path.join(user, profile_id + profile)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end return_statement call attribute attribute identifier identifier identifier argumen...
Create full path to given provide for the current user.
def passagg(recipient, sender): adj = random.choice(pmxbot.phrases.adjs) if random.choice([False, True]): lead = "" trail = recipient if not recipient else ", %s" % recipient else: lead = recipient if not recipient else "%s, " % recipient trail = "" body = random.choice(pmxbot.phrases.adj_intros) % adj if ...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute attribute identifier identifier identifier if_statement call attribute identifier identifier argument_list list false true block expression...
Generate a passive-aggressive statement to recipient from sender.
def register_bse_task(self, *args, **kwargs): kwargs["task_class"] = BseTask return self.register_task(*args, **kwargs)
module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier return_statement call attribute identifier identifier argument_list list_splat...
Register a Bethe-Salpeter task.
def add(self, histogram: Histogram1D): if self.binning and not self.binning == histogram.binning: raise ValueError("Cannot add histogram with different binning.") self.histograms.append(histogram)
module function_definition identifier parameters identifier typed_parameter identifier type identifier block if_statement boolean_operator attribute identifier identifier not_operator comparison_operator attribute identifier identifier attribute identifier identifier block raise_statement call identifier argument_list ...
Add a histogram to the collection.
def show_run(command_history_id): from pprint import pprint from .config import ConfigStore from .database import DataBase db = DataBase(ConfigStore().db_path) with db.connection(): for ch_id in command_history_id: crec = db.get_full_command_record(ch_id) pprint(crec....
module function_definition identifier parameters identifier block import_from_statement dotted_name identifier dotted_name identifier import_from_statement relative_import import_prefix dotted_name identifier dotted_name identifier import_from_statement relative_import import_prefix dotted_name identifier dotted_name i...
Show detailed command history by its ID.
def _set_complete_option(cls): get_config = cls.context.get_config complete = get_config('complete', None) if complete is None: conditions = [ get_config('transitions', False), get_config('named_transitions', False), ] complete ...
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list string string_start string_content string_end none if_statement comparison_operator i...
Check and set complete option.
def detail(callback=None, path=None, method=Method.GET, resource=None, tags=None, summary="Get specified resource.", middleware=None): def inner(c): op = Operation(c, path or PathParam('{key_field}'), method, resource, tags, summary, middleware) op.responses.add(Response(HTTPStatus.OK, "G...
module function_definition identifier parameters default_parameter identifier none default_parameter identifier none default_parameter identifier attribute identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier string string_start string_content string_end...
Decorator to configure an operation that fetches a resource.
def short_form_one_format(jupytext_format): if not isinstance(jupytext_format, dict): return jupytext_format fmt = jupytext_format['extension'] if 'suffix' in jupytext_format: fmt = jupytext_format['suffix'] + fmt elif fmt.startswith('.'): fmt = fmt[1:] if 'prefix' in jupytex...
module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier identifier block return_statement identifier expression_statement assignment identifier subscript identifier string string_start string_content string_end if_statement comparison_operator...
Represent one jupytext format as a string
def _parse_file(self): args = utilities.build_includes(self.arch.includes()) args.append('-E') args.append('-D__attribute__(x)=') args.append('-D__extension__=') self.ast = parse_file(self.filepath, use_cpp=True, cpp_path='arm-none-eabi-gcc', cpp_args=args)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_st...
Preprocess and parse C file into an AST
def _create_threads(self): creator = JobCreator( self.config, self.observers.jobs, self.logger ) self.jobs = creator.job_factory()
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier attribute attribute identifier identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier ...
This method creates job instances.
def setCell(self, x, y, v): self.cells[y][x] = v
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment subscript subscript attribute identifier identifier identifier identifier identifier
set the cell value at x,y
def load_boston(): dataset = datasets.load_boston() return Dataset(load_boston.__doc__, dataset.data, dataset.target, r2_score)
module function_definition identifier parameters block expression_statement assignment identifier call attribute identifier identifier argument_list return_statement call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier identifier
Boston House Prices Dataset.
def close(self): if self._closing: return log.info('MWorkerQueue under PID %s is closing', os.getpid()) self._closing = True if getattr(self, '_monitor', None) is not None: self._monitor.stop() self._monitor = None if getattr(self, '_w_monitor'...
module function_definition identifier parameters identifier block if_statement attribute identifier identifier block return_statement expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list expression_statem...
Cleanly shutdown the router socket
def cache_call_signatures(source, user_pos, stmt): index = user_pos[0] - 1 lines = source.splitlines() or [''] if source and source[-1] == '\n': lines.append('') before_cursor = lines[index][:user_pos[1]] other_lines = lines[stmt.start_pos[0]:index] whole = '\n'.join(other_lines + [befor...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier binary_operator subscript identifier integer integer expression_statement assignment identifier boolean_operator call attribute identifier identifier argument_list list string string_start ...
This function calculates the cache key.
def run_and_save(data): run(None, data) stats_file, idxstats_file = _get_stats_files(data) data = tz.update_in(data, ["depth", "samtools", "stats"], lambda x: stats_file) data = tz.update_in(data, ["depth", "samtools", "idxstats"], lambda x: idxstats_file) return data
module function_definition identifier parameters identifier block expression_statement call identifier argument_list none identifier expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier...
Run QC, saving file outputs in data dictionary.
def close_stream(self): if not self.is_connected: return self.stream.close() self.state = DISCONNECTED self.on_close.send(self)
module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block return_statement expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier identifier expre...
Close the underlying socket.
def symbol(self): if self._symbol is None: self._symbol = self._symbol_extract(cache.RE_CURSOR) return self._symbol
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier return_statement attribute iden...
Gets the symbol under the current cursor.
def _hue(color, **kwargs): h = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[0] return NumberValue(h * 360.0)
module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier subscript call attribute identifier identifier argument_list list_splat list_comprehension binary_operator identifier float for_in_clause identifier subscript attribute identi...
Get hue value of HSL color.
def to_dict(self): return { 'id': self.set_id, 'title': self.title, 'terms': [term.to_dict() for term in self.terms] }
module function_definition identifier parameters identifier block return_statement dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end list_comp...
Convert WordSet into raw dictionary data.
def _remove_boundaries(self, interval): begin = interval.begin end = interval.end if self.boundary_table[begin] == 1: del self.boundary_table[begin] else: self.boundary_table[begin] -= 1 if self.boundary_table[end] == 1: del self.boundary_table...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator subscript attribute identifier identifier identifier integer...
Removes the boundaries of the interval from the boundary table.
def dump_image_data(dataset_dir, data_dir, dataset, color_array_info, root=None, compress=True): if root is None: root = {} root['vtkClass'] = 'vtkImageData' container = root container['spacing'] = dataset.GetSpacing() container['origin'] = dataset.GetOrigin() container['extent'] = datas...
module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier none default_parameter identifier true block if_statement comparison_operator identifier none block expression_statement assignment identifier dictionary expression_statement assignment subscript id...
Dump image data object to vtkjs
def run(self): self.find_new() for n in self.news: print("{0}".format(n)) print("") self.msg.template(78) print("| Installed {0} new configuration files:".format( len(self.news))) self.msg.template(78) self.choices()
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list for_statement identifier attribute identifier identifier block expression_statement call identifier argument_list call attribute string string_start string_content string_end identif...
print .new configuration files
def jsontype(self, name, path=Path.rootPath()): return self.execute_command('JSON.TYPE', name, str_path(path))
module function_definition identifier parameters identifier identifier default_parameter identifier call attribute identifier identifier argument_list block return_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier call identifier argument_list identifi...
Gets the type of the JSON value under ``path`` from key ``name``
def to_node(value): if isinstance(value, Node): return value elif isinstance(value, str): return Node('string', value=value, pseudo_type='String') elif isinstance(value, int): return Node('int', value=value, pseudo_type='Int') elif isinstance(value, bool): return Node('bo...
module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block return_statement identifier elif_clause call identifier argument_list identifier identifier block return_statement call identifier argument_list string string_start string_content str...
Expand to a literal node if a basic type otherwise just returns the node
def _check_cat_dict_source(self, cat_dict_class, key_in_self, **kwargs): source = kwargs.get(cat_dict_class._KEYS.SOURCE, None) if source is None: raise CatDictError( "{}: `source` must be provided!".format(self[self._KEYS.NAME]), warn=True) for x in s...
module function_definition identifier parameters identifier identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute attribute identifier identifier identifier none if_statement comparison_operator identifier ...
Check that a source exists and that a quantity isn't erroneous.
def _update_phi(self): etaprod = 1.0 for w in range(N_NT - 1): self.phi[w] = etaprod * (1 - self.eta[w]) etaprod *= self.eta[w] self.phi[N_NT - 1] = etaprod
module function_definition identifier parameters identifier block expression_statement assignment identifier float for_statement identifier call identifier argument_list binary_operator identifier integer block expression_statement assignment subscript attribute identifier identifier identifier binary_operator identifi...
Update `phi` using current `eta`.
def runserver(debug, console_log, use_reloader, address, port, timeout, workers, socket): debug = debug or config.get('DEBUG') or console_log if debug: print(Fore.BLUE + '-=' * 20) print( Fore.YELLOW + 'Starting Superset server in ' + Fore.RED + 'DEBUG' + Fore...
module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier boolean_operator boolean_operator identifier call attribute identifier identifier argument_list string string_start string_content str...
Starts a Superset web server.
def pyspread(S=None): app = MainApplication(S=S, redirect=False) app.MainLoop()
module function_definition identifier parameters default_parameter identifier none block expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier false expression_statement call attribute identifier identifier argument_list
Holds application main loop
def graded_submissions(self): qs = self._valid_submissions().filter(state__in=[Submission.GRADED]) return qs
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list keyword_argument identifier list attribute identifier identifier return_statement identifier
Queryset for the graded submissions, which are worth closing.
def handle_starttag(self, tag, attrs): if not tag == 'a': return for attr in attrs: if attr[0] == 'href': url = urllib.unquote(attr[1]) self.active_url = url.rstrip('/').split('/')[-1] return
module function_definition identifier parameters identifier identifier identifier block if_statement not_operator comparison_operator identifier string string_start string_content string_end block return_statement for_statement identifier identifier block if_statement comparison_operator subscript identifier integer st...
Callback for when a tag gets opened.
def on_resize(self, event): self.context.set_viewport(0, 0, event.size[0], event.size[1]) for visual in self.visuals: visual.on_resize(event.size) self.update()
module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list integer integer subscript attribute identifier identifier integer subscript attribute identifier identifier integer for_statement identifier attribute...
Resize the OpenGL context.
async def echo_all(app, message): for address in app.kv.get_prefix('address.').values(): host, port = address.decode().split(':') port = int(port) await tcp_echo_client(message, loop, host, port)
module function_definition identifier parameters identifier identifier block for_statement identifier call attribute call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier argument_list block expression_statement assignment pattern_list identifie...
Send and recieve a message from all running echo servers
async def fromURL( cls, url, *, credentials=None, insecure=False): try: description = await helpers.fetch_api_description( url, insecure=insecure) except helpers.RemoteError as error: raise SessionError(str(error)) else: session = c...
module function_definition identifier parameters identifier identifier keyword_separator default_parameter identifier none default_parameter identifier false block try_statement block expression_statement assignment identifier await call attribute identifier identifier argument_list identifier keyword_argument identifi...
Return a `SessionAPI` for a given MAAS instance.
def type(self): if self.__type is None: found_type = find_definition( self.__type_name, self.message_definition()) if not (found_type is not Enum and isinstance(found_type, type) and issubclass(found_type, Enum)): ra...
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier call identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list if_statement not_opera...
Enum type used for field.
def load(path): with open(path) as rfile: steps = MODEL.parse(rfile.read()) new_steps = [] for step in steps: new_steps += expand_includes(step, path) return new_steps
module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier...
Load |path| and recursively expand any includes.
def _normalize(self, name, columns, points): for i, _ in enumerate(points): if points[i] is None: del(points[i]) del(columns[i]) continue try: points[i] = float(points[i]) except (TypeError, ValueError): ...
module function_definition identifier parameters identifier identifier identifier identifier block for_statement pattern_list identifier identifier call identifier argument_list identifier block if_statement comparison_operator subscript identifier identifier none block delete_statement parenthesized_expression subscri...
Normalize data for the InfluxDB's data model.
def _flush(self): if self._recording: raise Exception("Cannot flush data queue while recording!") if self._saving_cache: logging.warn("Flush when using cache means unsaved data will be lost and not returned!") self._cmds_q.put(("reset_data_segment",)) else: ...
module function_definition identifier parameters identifier block if_statement attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement attribute identifier identifier block expression_statement call attribute identifier identifier ar...
Returns a list of all current data