code
stringlengths
51
2.34k
sequence
stringlengths
186
3.94k
docstring
stringlengths
11
171
def _get_files_variantcall(sample): out = [] algorithm = sample["config"]["algorithm"] out = _maybe_add_summary(algorithm, sample, out) out = _maybe_add_alignment(algorithm, sample, out) out = _maybe_add_callable(sample, out) out = _maybe_add_disambiguate(algorithm, sample, out) out = _maybe...
module function_definition identifier parameters identifier block expression_statement assignment identifier list expression_statement assignment identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifi...
Return output files for the variant calling pipeline.
def validate_json(file): max_file_size = current_app.config.get( 'PREVIEWER_MAX_FILE_SIZE_BYTES', 1 * 1024 * 1024) if file.size > max_file_size: return False with file.open() as fp: try: json.loads(fp.read().decode('utf-8')) return True except: ...
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 binary_operator binary_operator integer integer integer if_statement comparison_operator attr...
Validate a JSON file.
def wsgi_app(self, environ, start_response): @_LOCAL_MANAGER.middleware def _wrapped_app(environ, start_response): request = Request(environ) setattr(_local, _CURRENT_REQUEST_KEY, request) response = self._dispatch_request(request) return response(environ,...
module function_definition identifier parameters identifier identifier identifier block decorated_definition decorator attribute identifier identifier function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_stat...
A basic WSGI app
def __parse_email_to_employer_line(self, raw_email, raw_enrollment): e = re.match(self.EMAIL_ADDRESS_REGEX, raw_email, re.UNICODE) if not e and self.email_validation: cause = "invalid email format: '%s'" % raw_email raise InvalidFormatError(cause=cause) if self.email_vali...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier identifier attribute identifier identifier if_statement boolean_operator not_operator identifier attribute...
Parse email to employer lines
def data(self, data): self._data = {det: d.copy() for (det, d) in data.items()}
module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier dictionary_comprehension pair identifier call attribute identifier identifier argument_list for_in_clause tuple_pattern identifier identifier call attribute identifier identifier ...
Store a copy of the data.
def fetch_build_egg(self, req): from setuptools.command.easy_install import easy_install dist = self.__class__({'script_args': ['easy_install']}) opts = dist.get_option_dict('easy_install') opts.clear() opts.update( (k, v) for k, v in self.get_option_dict(...
module function_definition identifier parameters identifier identifier block import_from_statement dotted_name identifier identifier identifier dotted_name identifier expression_statement assignment identifier call attribute identifier identifier argument_list dictionary pair string string_start string_content string_e...
Fetch an egg needed for building
def range(cls, dataset, dimension): dim = dataset.get_dimension(dimension, strict=True) values = dataset.dimension_values(dim.name, False) return (np.nanmin(values), np.nanmax(values))
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier true expression_statement assignment identifier call attribute identifier identifier argument_list ...
Computes the range along a particular dimension.
def tempfile(self, mode='wb', **args): "write the contents of the file to a tempfile and return the tempfile filename" tf = tempfile.NamedTemporaryFile(mode=mode) self.write(tf.name, mode=mode, **args) return tfn
module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end dictionary_splat_pattern identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute identifier identif...
write the contents of the file to a tempfile and return the tempfile filename
def create_reference_server_flask_app(cfg): app = Flask(__name__) Flask.secret_key = "SECRET_HERE" app.debug = cfg.debug client_prefixes = dict() for api_version in cfg.api_versions: handler_config = Config(cfg) handler_config.api_version = api_version handler_config.klass_na...
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identif...
Create referece server Flask application with one or more IIIF handlers.
def incident_path(cls, project, incident): return google.api_core.path_template.expand( "projects/{project}/incidents/{incident}", project=project, incident=incident, )
module function_definition identifier parameters identifier identifier identifier block return_statement call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifie...
Return a fully-qualified incident string.
def current_reading(self) -> Optional[Union[int, float]]: return self._get_field_value(SpecialDevice.PROP_CURRENT_READING)
module function_definition identifier parameters identifier type generic_type identifier type_parameter type generic_type identifier type_parameter type identifier type identifier block return_statement call attribute identifier identifier argument_list attribute identifier identifier
Current reading for a special sensor.
def layer(command=None, *args): 'hints the start of a new layer' if not command: return eval([['hint', 'layer']]) else: lst = [['layer']] for arg in args: lst.append([command, arg]) lst.append(['layer']) return eval(lst)
module function_definition identifier parameters default_parameter identifier none list_splat_pattern identifier block expression_statement string string_start string_content string_end if_statement not_operator identifier block return_statement call identifier argument_list list list string string_start string_content...
hints the start of a new layer
async def handle_agent_job_ssh_debug(self, _, message: AgentJobSSHDebug): await ZMQUtils.send_with_addr(self._client_socket, message.job_id[0], BackendJobSSHDebug(message.job_id[1], message.host, message.port, messa...
module function_definition identifier parameters identifier identifier typed_parameter identifier type identifier block expression_statement await call attribute identifier identifier argument_list attribute identifier identifier subscript attribute identifier identifier integer call identifier argument_list subscript ...
Handle an AgentJobSSHDebug message. Send the data back to the client
def _replace_bbox_none(self, bbox): (bb_top, bb_left), (bb_bottom, bb_right) = bbox if bb_top is None: bb_top = 0 if bb_left is None: bb_left = 0 if bb_bottom is None: bb_bottom = self.code_array.shape[0] - 1 if bb_right is None: bb...
module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list tuple_pattern identifier identifier tuple_pattern identifier identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier integer if_statem...
Returns bbox, in which None is replaced by grid boundaries
def _check_jointcaller(data): allowed = set(joint.get_callers() + [None, False]) cs = data["algorithm"].get("jointcaller", []) if not isinstance(cs, (tuple, list)): cs = [cs] problem = [x for x in cs if x not in allowed] if len(problem) > 0: raise ValueError("Unexpected algorithm 'jo...
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list binary_operator call attribute identifier identifier argument_list list none false expression_statement assignment identifier call attribute subscript identifier string string_start...
Ensure specified jointcaller is valid.
def crossover(self, gene2): assert self.key == gene2.key new_gene = self.__class__(self.key) for a in self._gene_attributes: if random() > 0.5: setattr(new_gene, a.name, getattr(self, a.name)) else: setattr(new_gene, a.name, getattr(gene2, ...
module function_definition identifier parameters identifier identifier block assert_statement comparison_operator attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier for_statement id...
Creates a new gene randomly inheriting attributes from its parents.
def stop(self): LOGGER.info('Shutting down controller') self.set_state(self.STATE_STOP_REQUESTED) signal.setitimer(signal.ITIMER_PROF, 0, 0) self._mcp.stop_processes() if self._mcp.is_running: LOGGER.info('Waiting up to 3 seconds for MCP to shut things down') ...
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attrib...
Shutdown the MCP and child processes cleanly
def write_xml(self, xmlfile, config=None): root = ElementTree.Element('source_library') root.set('title', 'source_library') for s in self._srcs: s.write_xml(root) if config is not None: srcs = self.create_diffuse_srcs(config) diffuse_srcs = {s.name: s ...
module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_li...
Save the ROI model as an XML file.
def getboolean_config(section, option, default=False): try: return config.getboolean(section, option) or default except ConfigParser.NoSectionError: return default
module function_definition identifier parameters identifier identifier default_parameter identifier false block try_statement block return_statement boolean_operator call attribute identifier identifier argument_list identifier identifier identifier except_clause attribute identifier identifier block return_statement i...
Get data from configs which store boolean records
def build_conversion_table(self, dataframes): self.data = pd.DataFrame(dataframes) tmp_pairs = [s.split("/") for s in self.data.columns] self.data.columns = pd.MultiIndex.from_tuples(tmp_pairs)
module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list stri...
Build conversion table from a dictionary of dataframes
def title(self): return (u'[{}] {}>>'.format( os.path.split(os.path.abspath('.'))[-1], u' '.join(self.command))).encode('utf8')
module function_definition identifier parameters identifier block return_statement call attribute parenthesized_expression call attribute string string_start string_content string_end identifier argument_list subscript call attribute attribute identifier identifier identifier argument_list call attribute attribute iden...
Returns the UTF-8 encoded title
def bullet_ant(): locals().update(default()) import pybullet_envs env = 'AntBulletEnv-v0' max_length = 1000 steps = 3e7 update_every = 60 return locals()
module function_definition identifier parameters block expression_statement call attribute call identifier argument_list identifier argument_list call identifier argument_list import_statement dotted_name identifier expression_statement assignment identifier string string_start string_content string_end expression_stat...
Configuration for PyBullet's ant task.
def token(config, token): if not token: info_out( "To generate a personal API token, go to:\n\n\t" "https://github.com/settings/tokens\n\n" "To read more about it, go to:\n\n\t" "https://help.github.com/articles/creating-an-access" "-token-for-comm...
module function_definition identifier parameters identifier identifier block if_statement not_operator identifier block expression_statement call identifier argument_list concatenated_string string string_start string_content escape_sequence escape_sequence escape_sequence string_end string string_start string_content ...
Store and fetch a GitHub access token
def head(self, wg_uuid, uuid): url = "%(base)s/%(wg_uuid)s/nodes/%(uuid)s" % { 'base': self.local_base_url, 'wg_uuid': wg_uuid, 'uuid': uuid } try: return self.core.get(url) except LinShareException: return False
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_c...
Get one workgroup node.
def _asdict(self): retval = {key: self._declarations[key].default_value for key in self._declarations if self._declarations[key].has_default} retval.update(self._loaded_values) for key, value in self._modules['six'].iteritems(self._flag_values): if key in self._declarations: retv...
module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary_comprehension pair identifier attribute subscript attribute identifier identifier identifier identifier for_in_clause identifier attribute identifier identifier if_clause attribute subscript attribute...
Create a dictionary snapshot of the current config values.
def _doAtomicFileCreation(filePath): try: _os.close(_os.open(filePath, _os.O_CREAT | _os.O_EXCL)) return True except OSError as e: if e.errno == _errno.EEXIST: return False else: raise e
module function_definition identifier parameters identifier block try_statement block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier binary_operator attribute identifier identifier attribute identifier identifier return_statement tru...
Tries to atomically create the requested file.
def _get_parent_classes_transparent(cls, slot, page, instance=None): parent_classes = super(CascadePluginBase, cls).get_parent_classes(slot, page, instance) if parent_classes is None: if cls.get_require_parent(slot, page) is False: return parent_classes = [] ...
module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier identifier argument_list identifier identifier identifier if_statement comparison_operat...
Return all parent classes including those marked as "transparent".
def _serialize(self, include_run_logs=False, strict_json=False): try: topo_sorted = self.topological_sort() t = [self.tasks[task]._serialize(include_run_logs=include_run_logs, strict_json=strict_json) for task in topo_sorted] ...
module function_definition identifier parameters identifier default_parameter identifier false default_parameter identifier false block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier list_comprehension call att...
Serialize a representation of this Job to a Python dict object.
def next_token(self): if self.lookahead: self.current_token = self.lookahead.popleft() return self.current_token self.current_token = self._parse_next_token() return self.current_token
module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list return_statement attribute identifier identifier expression_stateme...
Returns the next logical token, advancing the tokenizer.
def all_subclasses(cls): for s in cls.__subclasses__(): yield s for c in s.all_subclasses(): yield c
module function_definition identifier parameters identifier block for_statement identifier call attribute identifier identifier argument_list block expression_statement yield identifier for_statement identifier call attribute identifier identifier argument_list block expression_statement yield identifier
An iterator over all subclasses of `cls`.
def getAggregator(cls, instanceId, name): parent = cls.parentMap.get(instanceId) while parent: stat = cls.getStat(parent, name) if stat: return stat, parent parent = cls.parentMap.get(statsId(parent))
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier while_statement identifier block expression_statement assignment identifier call attribute identifier iden...
Gets the aggregate stat for the given stat.
def format_list(data): if isinstance(data, (list, tuple)): to_clean = ['[', ']', '(', ')', "'"] for item in to_clean: data = str(data).replace("u\"", "\"").replace("u\'", "\'") data = str(data).replace(item, '') return data
module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier tuple identifier identifier block expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end string string_start string...
Remove useless characters to output a clean list.
def matches(self, client, event_data): for f in self.filters: if not f(client, event_data): return False return True
module function_definition identifier parameters identifier identifier identifier block for_statement identifier attribute identifier identifier block if_statement not_operator call identifier argument_list identifier identifier block return_statement false return_statement true
True if all filters are matching.
def _do_timeout_for_leave(self, timeout, datapath, dst, in_port): parser = datapath.ofproto_parser dpid = datapath.id hub.sleep(timeout) outport = self._to_querier[dpid]['port'] if self._to_hosts[dpid][dst]['ports'][in_port]['out']: return del self._to_hosts[d...
module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier ar...
the process when the QUERY from the switch timeout expired.
def _interpolate_with_fill(self, method='pad', axis=0, inplace=False, limit=None, fill_value=None, coerce=False, downcast=None): inplace = validate_bool_kwarg(inplace, 'inplace') if coerce: if not self._can_hold_na: ...
module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier integer default_parameter identifier false default_parameter identifier none default_parameter identifier none default_parameter identifier false default_pa...
fillna but using the interpolate machinery
def append_sources_from(self, other): self_aliases = self[self._KEYS.SOURCE].split(',') other_aliases = other[self._KEYS.SOURCE].split(',') self[self._KEYS.SOURCE] = uniq_cdl(self_aliases + other_aliases) return
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute subscript identifier attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifi...
Merge the source alias lists of two CatDicts.
def process_tags(self, tag=None): if self.downloaded is False: raise serror("Track not downloaded, can't process tags..") filetype = magic.from_file(self.filepath, mime=True) if filetype != "audio/mpeg": raise serror("Cannot process tags for file type %s." % filetype) ...
module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator attribute identifier identifier false block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call att...
Process ID3 Tags for mp3 files.
def _check_import(module_names): diagnostics = {} for module_name in module_names: try: __import__(module_name) res = 'ok' except ImportError as err: res = str(err) diagnostics[module_name] = res return diagnostics
module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary for_statement identifier identifier block try_statement block expression_statement call identifier argument_list identifier expression_statement assignment identifier string string_start string_conten...
Import the specified modules and provide status.
def add_semantic_hub_layout(cx, hub): graph = cx_to_networkx(cx) hub_node = get_node_by_name(graph, hub) node_classes = classify_nodes(graph, hub_node) layout_aspect = get_layout_aspect(hub_node, node_classes) cx['cartesianLayout'] = layout_aspect
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 identifier expression_statement assignment identifier call identifier argum...
Attach a layout aspect to a CX network given a hub node.
def streamy_download_file(context, path): bio = io.BytesIO() ok, metadata = mitogen.service.FileService.get(context, path, bio) return { 'success': ok, 'metadata': metadata, 'size': len(bio.getvalue()), }
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment pattern_list identifier identifier call attribute attribute attribute identifier identifier identifier identifier arg...
Fetch a file from the FileService hosted by `context`.
def xview(self, *args): self.after_idle(self.__updateWnds) ttk.Treeview.xview(self, *args)
module function_definition identifier parameters identifier list_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier list_splat ident...
Update inplace widgets position when doing horizontal scroll
def namer(cls, imageUrl, pageUrl): imgname = imageUrl.split('/')[-1] imgbase = imgname.rsplit('-', 1)[0] imgext = imgname.rsplit('.', 1)[1] return '%s.%s' % (imgbase, imgext)
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier subscript call attribute identifier identifier argument_list string string_start string_content string_end unary_operator integer expression_statement assignment identifier subscript call a...
Remove random junk from image names.
def _timesheet_url(url_name, pk, date=None): url = reverse(url_name, args=(pk,)) if date: params = {'month': date.month, 'year': date.year} return '?'.join((url, urlencode(params))) return url
module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier tuple identifier if_statement identifier block expression_statement assignment identifier diction...
Utility to create a time sheet URL with optional date parameters.
def updateColumnWidths(tag, cw, options): longforms = {"med": "median", "ave": "average", "min": "min", "total": "total", "max": "max",} for category in ["time", "clock", "wait", "memory"]: if category in options.categories: ...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_con...
Update the column width attributes for this tag's fields.
def _reset_flood_offenders(self, *args): offenders = [] for offender, offence_time in self._flooding.items(): if time() - offence_time < 10: self.log('Removed offender from flood list:', offender) offenders.append(offender) for offender in offenders: ...
module function_definition identifier parameters identifier list_splat_pattern identifier block expression_statement assignment identifier list for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block if_statement comparison_operator binary_operator ...
Resets the list of flood offenders on event trigger
def _validate_lattice_vectors(self, lattice_vectors): dataType = np.float64 if lattice_vectors is None: lattice_vectors = np.identity(self.dimension, dtype=dataType) else: lattice_vectors = np.asarray(lattice_vectors, dtype=dataType) if (self.dimension, se...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifie...
Ensure that the lattice_vectors are reasonable inputs.
def destroy(self, folder=None, as_coro=False): async def _destroy(folder): ret = self.save_info(folder) await self.stop_slaves() if self._pool is not None: self._pool.terminate() self._pool.join() await self._env.shutdown(as_coro=Tr...
module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier false block function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement ...
Destroy the multiprocessing environment and its slave environments.
def send_theme_file(self, filename): cache_timeout = self.get_send_file_max_age(filename) return send_from_directory(self.config['THEME_STATIC_FOLDER'], filename, cache_timeout=cache_timeout)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end ide...
Function used to send static theme files from the theme folder to the browser.
def file_pour(filepath, block_size=10240, *args, **kwargs): def opener(archive_res): _LOGGER.debug("Opening from file (file_pour): %s", filepath) _archive_read_open_filename(archive_res, filepath, block_size) return _pour(opener, *args, flags=0, **kwargs)
module function_definition identifier parameters identifier default_parameter identifier integer list_splat_pattern identifier dictionary_splat_pattern identifier block function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start ...
Write physical files from entries.
def enable_evb(self): if self.is_ncb: self.run_lldptool(["-T", "-i", self.port_name, "-g", "ncb", "-V", "evb", "enableTx=yes"]) ret = self.enable_gpid() return ret else: LOG.error("EVB cannot be set on NB") return...
module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list list string string_start string_content string_end string string_start string_content string_end attribute identifier identifier st...
Function to enable EVB on the interface.
def bind(self) -> None: self.base.metadata.bind = self.engine self.base.query = self.session.query_property()
module function_definition identifier parameters identifier type none block expression_statement assignment attribute attribute attribute identifier identifier identifier identifier attribute identifier identifier expression_statement assignment attribute attribute identifier identifier identifier call attribute attrib...
Bind the metadata to the engine and session.
def i2osp(self, long_integer, block_size): 'Convert a long integer into an octet string.' hex_string = '%X' % long_integer if len(hex_string) > 2 * block_size: raise ValueError('integer %i too large to encode in %i octets' % (long_integer, block_size)) return a2b_hex(hex_stri...
module function_definition identifier parameters identifier identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier binary_operator string string_start string_content string_end identifier if_statement comparison_operator call identifier ...
Convert a long integer into an octet string.
def hook(self, *hook_names): def wrapper(decorated): for hook_name in hook_names: self.register(hook_name, decorated) else: self.register(decorated.__name__, decorated) if '_' in decorated.__name__: self.register( ...
module function_definition identifier parameters identifier list_splat_pattern identifier block function_definition identifier parameters identifier block for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier else_clause block expression_...
Decorator, registering them as hooks
def languages2marc(self, key, value): return {'a': pycountry.languages.get(alpha_2=value).name.lower()}
module function_definition identifier parameters identifier identifier identifier block return_statement dictionary pair string string_start string_content string_end call attribute attribute call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier identifier identi...
Populate the ``041`` MARC field.
def process_kill(pid, sig=None): sig = sig or signal.SIGTERM os.kill(pid, sig)
module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier boolean_operator identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier
Send signal to process.
def _rts_from_ra(ra, tspan, labels, block=True): def _convert(a, tspan, labels): from nsim import Timeseries return Timeseries(a, tspan, labels) return distob.call( _convert, ra, tspan, labels, prefer_local=False, block=block)
module function_definition identifier parameters identifier identifier identifier default_parameter identifier true block function_definition identifier parameters identifier identifier identifier block import_from_statement dotted_name identifier dotted_name identifier return_statement call identifier argument_list id...
construct a RemoteTimeseries from a RemoteArray
def _dry_message_received(self, msg): for callback in self._dry_wet_callbacks: callback(LeakSensorState.DRY) self._update_subscribers(0x11)
module function_definition identifier parameters identifier identifier block for_statement identifier attribute identifier identifier block expression_statement call identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list integer
Report a dry state.
def rlmb_grid(rhp): rhp.set_categorical("loop.game", ["breakout", "pong", "freeway"]) base = 100000 medium = base // 2 small = medium // 2 rhp.set_discrete("loop.num_real_env_frames", [base, medium, small]) rhp.set_discrete("model.moe_loss_coef", list(range(5)))
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end list string string_start string_content string_end string string_start string_content string_end string string_start string_content stri...
Grid over games and frames, and 5 runs each for variance.
def filter_record(self, record): if len(record) >= self.max_length: return record[:self.max_length] else: return record
module function_definition identifier parameters identifier identifier block if_statement comparison_operator call identifier argument_list identifier attribute identifier identifier block return_statement subscript identifier slice attribute identifier identifier else_clause block return_statement identifier
Filter record, truncating any over some maximum length
def _uncheck_descendant(self, item): children = self.get_children(item) for iid in children: self.change_state(iid, "unchecked") self._uncheck_descendant(iid)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier string string...
Uncheck the boxes of item's descendant.
def dataSetElementType(h5Dataset): dtype = h5Dataset.dtype if dtype.names: return '<structured>' else: if dtype.metadata and 'vlen' in dtype.metadata: vlen_type = dtype.metadata['vlen'] try: return "<vlen {}>".format(vlen_type.__name__) ex...
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier if_statement attribute identifier identifier block return_statement string string_start string_content string_end else_clause block if_statement boolean_operator attribute identif...
Returns a string describing the element type of the dataset
def meta(self): if not self._pv.meta_data_property or not self._meta_target: return {} return getattr(self._meta_target, self._pv.meta_data_property)
module function_definition identifier parameters identifier block if_statement boolean_operator not_operator attribute attribute identifier identifier identifier not_operator attribute identifier identifier block return_statement dictionary return_statement call identifier argument_list attribute identifier identifier ...
Value of the bound meta-property on the target.
def reboot(self): reboot_msg = self.message_factory.command_long_encode( 0, 0, mavutil.mavlink.MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN, 0, 1, 0, 0, 0, 0, 0, 0) self.send_mavlink(reboot_msg)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list integer integer attribute attribute identifier identifier identifier integer integer integer integer integer integer integer integer expres...
Requests an autopilot reboot by sending a ``MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN`` command.
def save_shortcuts(self): self.check_shortcuts() for shortcut in self.source_model.shortcuts: shortcut.save()
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list for_statement identifier attribute attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list
Save shortcuts from table model.
def _check_command_result(self): if self.commandResult.startswith('/bin/bash'): raise UtilError('%s' % self.commandResult.split(' ', 1)[1]) if self.commandResult.startswith('/bin/mv'): raise UtilError('%s' % self.commandResult.split(' ', 1)[1]) if self.commandResult.start...
module function_definition identifier parameters identifier block if_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block raise_statement call identifier argument_list binary_operator string string_start string_content string_end subscript...
If command result exists run these checks.
def turn_on(self): if self.device_status != 'on': body = helpers.req_body(self.manager, 'devicestatus') body['uuid'] = self.uuid body['status'] = 'on' head = helpers.req_headers(self.manager) r, _ = helpers.call_api('/131airPurifier/v1/device/deviceSta...
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier string stri...
Turn Air Purifier on
def peek_step(self, val: ObjectValue, sn: "DataNode") -> Tuple[None, "DataNode"]: cn = sn.get_child(self.name, self.namespace) return (None, cn)
module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type string string_start string_content string_end type generic_type identifier type_parameter type none type string string_start string_content string_end block expression_statement assignm...
Fail because there is no action instance.
def items(self): return [(k, unidecode.unidecode(v)) for k, v in self.identity_dict.items()]
module function_definition identifier parameters identifier block return_statement list_comprehension tuple identifier call attribute identifier identifier argument_list identifier for_in_clause pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list
Return a copy of identity_dict items.
def sep_dist_clay(ConcClay, material): return ((material.Density/ConcClay)*((np.pi * material.Diameter ** 3)/6))**(1/3)
module function_definition identifier parameters identifier identifier block return_statement binary_operator parenthesized_expression binary_operator parenthesized_expression binary_operator attribute identifier identifier identifier parenthesized_expression binary_operator parenthesized_expression binary_operator att...
Return the separation distance between clay particles.
def reset(self): self.info(self.tr("About to reset..")) models = self.data["models"] models["instances"].store_checkstate() models["plugins"].store_checkstate() models["instances"].ids = [] for m in models.values(): m.reset() for b in self.data["button...
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier subscript attribute identifier identifier ...
Prepare GUI for reset
def shuffle_records(fname): tf.logging.info("Shuffling records in file %s" % fname) tmp_fname = fname + ".unshuffled" tf.gfile.Rename(fname, tmp_fname) reader = tf.python_io.tf_record_iterator(tmp_fname) records = [] for record in reader: records.append(record) if len(records) % 100000 == 0: t...
module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier binary_operator identifier string string_star...
Shuffle records in a single file.
def _patch_original_class(self): cls = self._cls base_names = self._base_names if self._delete_attribs: for name in self._attr_names: if ( name not in base_names and getattr(cls, name, None) is not None ): ...
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier if_statement attribute identifier identifier block for_statement identifier attribute identifier identif...
Apply accumulated methods and return the class.
def page_next(self): window_start = (self.parent.value('window_start') + self.parent.value('window_length')) self.parent.overview.update_position(window_start)
module function_definition identifier parameters identifier block expression_statement assignment identifier parenthesized_expression binary_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end call attribute attribute identifier identifier ident...
Go to the next page.
def run( paths, output=_I_STILL_HATE_EVERYTHING, recurse=core.flat, sort_by=None, ls=core.ls, stdout=stdout, ): if output is _I_STILL_HATE_EVERYTHING: output = core.columnized if stdout.isatty() else core.one_per_line if sort_by is None: if output == core.as_tree: ...
module function_definition identifier parameters identifier default_parameter identifier identifier default_parameter identifier attribute identifier identifier default_parameter identifier none default_parameter identifier attribute identifier identifier default_parameter identifier identifier block if_statement compa...
Project-oriented directory and file information lister.
def authenticate_peer(self, auth_data, peer_id, message): logger.debug('message: {}'.format(dump(message))) signed_octets = message + self.Ni + prf(self.SK_pr, peer_id._data) auth_type = const.AuthenticationType(struct.unpack(const.AUTH_HEADER, auth_data[:4])[0]) assert auth_type == cons...
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier expression_statement a...
Verifies the peers authentication.
def on_batch_end(self, iteration:int, smooth_loss:TensorOrNumber, **kwargs:Any)->None: "Determine if loss has runaway and we should stop." if iteration==0 or smooth_loss < self.best_loss: self.best_loss = smooth_loss self.opt.lr = self.sched.step() if self.sched.is_done or (self.stop_div...
module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter dictionary_splat_pattern identifier type identifier type none block expression_statement string string_start string_content string_end if_statement boolean_op...
Determine if loss has runaway and we should stop.
def modules(self): defmodule = lib.EnvGetNextDefmodule(self._env, ffi.NULL) while defmodule != ffi.NULL: yield Module(self._env, defmodule) defmodule = lib.EnvGetNextDefmodule(self._env, defmodule)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier while_statement comparison_operator identifier attribute identifier identifier block expression_...
Iterates over the defined Modules.
def trial(request): job_id = request.GET.get("job_id") trial_id = request.GET.get("trial_id") recent_trials = TrialRecord.objects \ .filter(job_id=job_id) \ .order_by("-start_time") recent_results = ResultRecord.objects \ .filter(trial_id=trial_id) \ .order_by("-date")[0:...
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 attribute identifier identifier ide...
View for a single trial.
def content_type(self) -> str: raw = self._headers.get(hdrs.CONTENT_TYPE) if self._stored_content_type != raw: self._parse_content_type(raw) return self._content_type
module function_definition identifier parameters identifier type identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier if_statement comparison_operator attribute identifier identifier identifier block expressio...
The value of content part for Content-Type HTTP header.
def poll(poll, msg, server): poll = remove_smart_quotes(poll.replace(u"\u2014", u"--")) try: args = ARGPARSE.parse_args(shlex.split(poll)).poll except ValueError: return ERROR_INVALID_FORMAT if not 2 < len(args) < len(POLL_EMOJIS) + 1: return ERROR_WRONG_NUMBER_OF_ARGUMENTS r...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end string string_start string_content string_end ...
Given a question and answers, present a poll
def empty(self): for k in list(self.children.keys()): self.remove_child(self.children[k])
module function_definition identifier parameters identifier block for_statement identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list subscript attribute identifier identifier identif...
remove all children from the widget
def run(arguments: typing.List[str] = None): initialize() from cauldron.invoke import parser from cauldron.invoke import invoker args = parser.parse(arguments) exit_code = invoker.run(args.get('command'), args) sys.exit(exit_code)
module function_definition identifier parameters typed_default_parameter identifier type subscript attribute identifier identifier identifier none block expression_statement call identifier argument_list import_from_statement dotted_name identifier identifier dotted_name identifier import_from_statement dotted_name ide...
Executes the cauldron command
def StopToTuple(stop): return (stop.stop_id, stop.stop_name, float(stop.stop_lat), float(stop.stop_lon), stop.location_type)
module function_definition identifier parameters identifier block return_statement tuple attribute identifier identifier attribute identifier identifier call identifier argument_list attribute identifier identifier call identifier argument_list attribute identifier identifier attribute identifier identifier
Return tuple as expected by javascript function addStopMarkerFromList
def insertions_from_masked(seq): insertions = [] prev = True for i, base in enumerate(seq): if base.isupper() and prev is True: insertions.append([]) prev = False elif base.islower(): insertions[-1].append(i) prev = True return [[min(i), ma...
module function_definition identifier parameters identifier block expression_statement assignment identifier list expression_statement assignment identifier true for_statement pattern_list identifier identifier call identifier argument_list identifier block if_statement boolean_operator call attribute identifier identi...
get coordinates of insertions from insertion-masked sequence
def _set_other(self): if self.dst.style['in'] == 'numpydoc': if self.docs['in']['raw'] is not None: self.docs['out']['post'] = self.dst.numpydoc.get_raw_not_managed(self.docs['in']['raw']) elif 'post' not in self.docs['out'] or self.docs['out']['post'] is None: ...
module function_definition identifier parameters identifier block if_statement comparison_operator subscript attribute attribute identifier identifier identifier string string_start string_content string_end string string_start string_content string_end block if_statement comparison_operator subscript subscript attribu...
Sets other specific sections
def klm(p, q): p, q = flatten(p), flatten(q) return max(abs(p * np.nan_to_num(np.log(p / q))))
module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier expression_list call identifier argument_list identifier call identifier argument_list identifier return_statement call identifier argument_list call identifier argument_list b...
Compute the KLM divergence.
def from_shakemap(cls, shakemap_array): self = object.__new__(cls) self.complete = self n = len(shakemap_array) dtype = numpy.dtype([(p, site_param_dt[p]) for p in 'sids lon lat depth vs30'.split()]) self.array = arr = numpy.zeros(n, dtype) ar...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment identifier call identifier argu...
Build a site collection from a shakemap array
def clean(self, *args, **kwargs): if not self.pk: if self.node.participation_settings.voting_allowed is not True: raise ValidationError("Voting not allowed for this node") if 'nodeshot.core.layers' in settings.INSTALLED_APPS: layer = self.node.layer ...
module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement not_operator attribute identifier identifier block if_statement comparison_operator attribute attribute attribute identifier identifier identifier identifier true block raise_...
Check if votes can be inserted for parent node or parent layer
def print_all_signals(self): for o in dir(self): obj= getattr(self, o) div = False for c in dir(obj): cobj = getattr(obj, c) if isinstance(cobj, Signal): print('def _on_{}__{}(self):'.format(o, c)) div = ...
module function_definition identifier parameters identifier block for_statement identifier call identifier argument_list identifier block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier false for_statement identifier call identifi...
Prints out every signal available for this widget and childs.
def visit_set(self, node): return "{%s}" % ", ".join(child.accept(self) for child in node.elts)
module function_definition identifier parameters identifier identifier block return_statement binary_operator string string_start string_content string_end call attribute string string_start string_content string_end identifier generator_expression call attribute identifier identifier argument_list identifier for_in_cl...
return an astroid.Set node as string
def create_api_v4_virtual_interface(self): return ApiV4VirtualInterface( self.networkapi_url, self.user, self.password, self.user_ldap)
module function_definition identifier parameters identifier block return_statement call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier
Get an instance of Api Virtual Interface services facade.
def _prepare_bam_file(bam_file, tmp_dir, config): sort_mode = _get_sort_order(bam_file, config) if sort_mode != "queryname": bam_file = sort(bam_file, config, "queryname") return bam_file
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifie...
Pipe sort by name cmd in case sort by coordinates
def reset (self): super(FtpUrl, self).reset() self.files = [] self.filename = None self.filename_encoding = 'iso-8859-1'
module function_definition identifier parameters identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier list expression_statement assignment attribute identifier identifier none exp...
Initialize FTP url data.
def gen_encode(data): "A generator for unsynchronizing a byte iterable." sync = False for b in data: if sync and (b == 0x00 or b & 0xE0): yield 0x00 yield b sync = (b == 0xFF) if sync: yield 0x00
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier false for_statement identifier identifier block if_statement boolean_operator identifier parenthesized_expression boolean_operator comparison_op...
A generator for unsynchronizing a byte iterable.
def load_entities(): path = os.path.join(TOPDIR, 'entities.json') entities = json.load(open(path)) names = [i['name'] for i in entities] try: assert len(set(names)) == len(entities) except AssertionError: raise Exception('Entities with same name: %s' % [i for i in names if ...
module function_definition identifier parameters block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list...
Load entities from JSON file.
def validator(ch): global screen_needs_update try: if screen_needs_update: curses.doupdate() screen_needs_update = False return ch finally: winlock.release() sleep(0.01) winlock.acquire()
module function_definition identifier parameters identifier block global_statement identifier try_statement block if_statement identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier false return_statement identifier finally_clause block expres...
Update screen if necessary and release the lock so receiveThread can run
def send(self, cmd, timeout, wait_for_string, password): return self.target_device.send(cmd, timeout=timeout, wait_for_string=wait_for_string, password=password)
module function_definition identifier parameters identifier identifier identifier identifier identifier block return_statement call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier iden...
Send command to the target device.
def output_callback(self, line, kill_switch): self.notifications += line + "\n" if "Initialization Sequence Completed" in line: self.started = True if "ERROR:" in line or "Cannot resolve host address:" in line: self.error = True if "process exiting" in line: ...
module function_definition identifier parameters identifier identifier identifier block expression_statement augmented_assignment attribute identifier identifier binary_operator identifier string string_start string_content escape_sequence string_end if_statement comparison_operator string string_start string_content s...
Set status of openvpn according to what we process
def split_markers_from_line(line): if not any(line.startswith(uri_prefix) for uri_prefix in SCHEME_LIST): marker_sep = ";" else: marker_sep = "; " markers = None if marker_sep in line: line, markers = line.split(marker_sep, 1) markers = markers.strip() if markers else Non...
module function_definition identifier parameters identifier block if_statement not_operator call identifier generator_expression call attribute identifier identifier argument_list identifier for_in_clause identifier identifier block expression_statement assignment identifier string string_start string_content string_en...
Split markers from a dependency
def hybrid_forward(self, F, a, b): tilde_a = self.f(a) tilde_b = self.f(b) e = F.batch_dot(tilde_a, tilde_b, transpose_b=True) beta = F.batch_dot(e.softmax(), tilde_b) alpha = F.batch_dot(e.transpose([0, 2, 1]).softmax(), tilde_a) feature1 = self.g(F.concat(tilde_a, beta,...
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_...
Forward of Decomposable Attention layer