code
stringlengths
51
2.38k
docstring
stringlengths
4
15.2k
def set_language(self, language): if isinstance(language, str): language_obj = languages.getlang(language) if language_obj: self.language = language_obj.code else: raise TypeError("Language code {} not found".format(language)) if isinst...
Set self.language to internal lang. repr. code from str or Language object.
def weave_on(advices, pointcut=None, ctx=None, depth=1, ttl=None): def __weave(target): weave( target=target, advices=advices, pointcut=pointcut, ctx=ctx, depth=depth, ttl=ttl ) return target return __weave
Decorator for weaving advices on a callable target. :param pointcut: condition for weaving advices on joinpointe. The condition depends on its type. :param ctx: target ctx (instance or class). :type pointcut: - NoneType: advices are weaved on target. - str: target name is compared t...
def index(in_cram, config): out_file = in_cram + ".crai" if not utils.file_uptodate(out_file, in_cram): with file_transaction(config, in_cram + ".crai") as tx_out_file: tx_in_file = os.path.splitext(tx_out_file)[0] utils.symlink_plus(in_cram, tx_in_file) cmd = "samtoo...
Ensure CRAM file has a .crai index file.
def _gen_success_message(publish_output): application_id = publish_output.get('application_id') details = json.dumps(publish_output.get('details'), indent=2) if CREATE_APPLICATION in publish_output.get('actions'): return "Created new application with the following metadata:\n{}".format(details) ...
Generate detailed success message for published applications. Parameters ---------- publish_output : dict Output from serverlessrepo publish_application Returns ------- str Detailed success message
def create_deployment(self, ref, force=False, payload='', auto_merge=False, description='', environment=None): json = None if ref: url = self._build_url('deployments', base_url=self._api) data = {'ref': ref, 'force': force, 'payload': payload, ...
Create a deployment. :param str ref: (required), The ref to deploy. This can be a branch, tag, or sha. :param bool force: Optional parameter to bypass any ahead/behind checks or commit status checks. Default: False :param str payload: Optional JSON payload with extra inf...
def addSource(self, sourceUri, weight): assert isinstance(weight, (float, int)), "weight value has to be a positive or negative integer" self.topicPage["sources"].append({"uri": sourceUri, "wgt": weight})
add a news source to the topic page @param sourceUri: uri of the news source to add to the topic page @param weight: importance of the news source (typically in range 1 - 50)
def translate(self): expressions, varnames, funcnames = self.expr.translate() argnames = [] for varname in varnames: argnames.append(VARIABLE_PREFIX + varname) for funcname in funcnames: argnames.append(FUNCTION_PREFIX + funcname) func = compile_func( ...
Compile the template to a Python function.
def _active_todos(self): return [todo for todo in self.todolist.todos() if not self._uncompleted_children(todo) and todo.is_active()]
Returns a list of active todos, taking uncompleted subtodos into account. The stored length of the todolist is taken into account, to prevent new todos created by recurrence to pop up as newly activated tasks. Since these todos pop up at the end of the list, we cut off the list ...
def remove_all_listeners(self, event=None): if event is not None: self._events[event] = OrderedDict() else: self._events = defaultdict(OrderedDict)
Remove all listeners attached to ``event``. If ``event`` is ``None``, remove all listeners on all events.
def delete(self, robj, rw=None, r=None, w=None, dw=None, pr=None, pw=None, timeout=None): raise NotImplementedError
Deletes an object.
def _objects_touch_each_other(self, object1: Object, object2: Object) -> bool: in_vertical_range = object1.y_loc <= object2.y_loc + object2.size and \ object1.y_loc + object1.size >= object2.y_loc in_horizantal_range = object1.x_loc <= object2.x_loc + object2.size and \ ...
Returns true iff the objects touch each other.
def _generate_field_with_default(**kwargs): field = kwargs['field'] if callable(field.default): return field.default() return field.default
Only called if field.default != NOT_PROVIDED
def trans_history( self, from_=None, count=None, from_id=None, end_id=None, order=None, since=None, end=None ): return self._trade_api_call( 'TransHistory', from_=from_, count=count, from_id=from_id, end_id=end_id, order=order, since=since, end=end )
Returns the history of transactions. To use this method you need a privilege of the info key. :param int or None from_: transaction ID, from which the display starts (default 0) :param int or None count: number of transaction to be displayed (default 1000) :param int or None from_id: tr...
def cmd_start(self, argv, help): parser = argparse.ArgumentParser( prog="%s start" % self.progname, description=help, ) instances = self.get_instances(command='start') parser.add_argument("instance", nargs=1, metavar="instance", ...
Starts the instance
def select_candidates(config): download_candidates = [] for group in config.group: summary_file = get_summary(config.section, group, config.uri, config.use_cache) entries = parse_summary(summary_file) for entry in filter_entries(entries, config): download_candidates.append((e...
Select candidates to download. Parameters ---------- config: NgdConfig Runtime configuration object Returns ------- list of (<candidate entry>, <taxonomic group>)
def config_set(self, parameter, value): if not isinstance(parameter, str): raise TypeError("parameter must be str") fut = self.execute(b'CONFIG', b'SET', parameter, value) return wait_ok(fut)
Set a configuration parameter to the given value.
def flag_calls(func): if hasattr(func, 'called'): return func def wrapper(*args, **kw): wrapper.called = False out = func(*args, **kw) wrapper.called = True return out wrapper.called = False wrapper.__doc__ = func.__doc__ return wrapper
Wrap a function to detect and flag when it gets called. This is a decorator which takes a function and wraps it in a function with a 'called' attribute. wrapper.called is initialized to False. The wrapper.called attribute is set to False right before each call to the wrapped function, so if the call f...
def wait(self): now = _monotonic() if now < self._ref: delay = max(0, self._ref - now) self.sleep_func(delay) self._update_ref()
Blocks until the rate is met
def flush_all(self, delay=0, noreply=None): if noreply is None: noreply = self.default_noreply cmd = b'flush_all ' + six.text_type(delay).encode('ascii') if noreply: cmd += b' noreply' cmd += b'\r\n' results = self._misc_cmd([cmd], b'flush_all', noreply) ...
The memcached "flush_all" command. Args: delay: optional int, the number of seconds to wait before flushing, or zero to flush immediately (the default). noreply: optional bool, True to not wait for the reply (defaults to self.default_noreply). Re...
def read_blocking(self): while True: data = self._read() if data != None: break return self._parse_message(data)
Same as read, except blocks untill data is available to be read.
def cancelOperation(self): if self.isLongTouchingPoint: self.toggleLongTouchPoint() elif self.isTouchingPoint: self.toggleTouchPoint() elif self.isGeneratingTestCondition: self.toggleGenerateTestCondition()
Cancels the ongoing operation if any.
def activate(self, event): self._index += 1 if self._index >= len(self._values): self._index = 0 self._selection = self._values[self._index] self.ao2.speak(self._selection)
Change the value.
def get_files(*bases): for base in bases: basedir, _ = base.split(".", 1) base = os.path.join(os.path.dirname(__file__), *base.split(".")) rem = len(os.path.dirname(base)) + len(basedir) + 2 for root, dirs, files in os.walk(base): for name in files...
List all files in a data directory.
def register_shortcut(self, qaction_or_qshortcut, context, name, add_sc_to_tip=False): self.main.register_shortcut(qaction_or_qshortcut, context, name, add_sc_to_tip)
Register QAction or QShortcut to Spyder main application. if add_sc_to_tip is True, the shortcut is added to the action's tooltip
def to_dict(self): return { 'name': self.name, 'id': self.id, 'type': self.type, 'workflow_id': self.workflow_id, 'queue': self.queue, 'start_time': self.start_time, 'arguments': self.arguments, 'acknowledged': self....
Return a dictionary of the job stats. Returns: dict: Dictionary of the stats.
def flavor_extra_set(request, flavor_id, metadata): flavor = _nova.novaclient(request).flavors.get(flavor_id) if (not metadata): return None return flavor.set_keys(metadata)
Set the flavor extra spec keys.
def conditions(self) -> Dict[str, Dict[str, Union[float, numpy.ndarray]]]: conditions = {} for subname in NAMES_CONDITIONSEQUENCES: subseqs = getattr(self, subname, ()) subconditions = {seq.name: copy.deepcopy(seq.values) for seq in subseqs} ...
Nested dictionary containing the values of all condition sequences. See the documentation on property |HydPy.conditions| for further information.
def delete(self): if self._new: raise Exception("This is a new object, %s not in data, \ indicating this entry isn't stored." % self.primaryKey) r.table(self.table).get(self._data[self.primaryKey]) \ .delete(durability=self.durability).run(self._conn) return True
Deletes the current instance. This assumes that we know what we're doing, and have a primary key in our data already. If this is a new instance, then we'll let the user know with an Exception
def _response_item_to_object(self, resp_item): item_cls = resources.get_model_class(self.resource_type) properties_dict = resp_item[self.resource_type] new_dict = helpers.remove_properties_containing_None(properties_dict) obj = item_cls(new_dict) return obj
take json and make a resource out of it
def add_pool(self, pool, match=None): if match is None: self.default_pool = pool else: self.pools.append((match, pool))
Adds a new account pool. If the given match argument is None, the pool the default pool. Otherwise, the match argument is a callback function that is invoked to decide whether or not the given pool should be used for a host. When Exscript logs into a host, the account is chosen in the f...
def realpath(path): if path == '~': return userdir if path == '/': return sysroot if path.startswith('/'): return os.path.abspath(path) if path.startswith('~/'): return os.path.expanduser(path) if path.startswith('./'): return os.path.abspath(os.path.join(os.p...
Create the real absolute path for the given path. Add supports for userdir & / supports. Args: * path: pathname to use for realpath. Returns: Platform independent real absolute path.
def load_and_check(self, base_settings, prompt=None): checker = Checker(self.file_name, self.section, self.registry, self.strategy_type, prompt) settings = self.load(base_settings) if checker.check(settings): return settings, True return None, False
Load settings and check them. Loads the settings from ``base_settings``, then checks them. Returns: (merged settings, True) on success (None, False) on failure
def _parameter_sweep(self, parameter_space, kernel_options, device_options, tuning_options): results = [] parameter_space = list(parameter_space) random.shuffle(parameter_space) work_per_thread = int(numpy.ceil(len(parameter_space) / float(self.max_threads))) chunks = _chunk_list...
Build a Noodles workflow by sweeping the parameter space
def _ParseSourcePathOption(self, options): self._source_path = self.ParseStringOption(options, self._SOURCE_OPTION) if not self._source_path: raise errors.BadConfigOption('Missing source path.') self._source_path = os.path.abspath(self._source_path)
Parses the source path option. Args: options (argparse.Namespace): command line arguments. Raises: BadConfigOption: if the options are invalid.
def json(self): try: return json.loads(self.text) except Exception as e: raise ContentDecodingError(e)
Load response body as json. :raises: :class:`ContentDecodingError`
def email_secure(self): email = self._email if not email: return '' address, host = email.split('@') if len(address) <= 2: return ('*' * len(address)) + '@' + host import re host = '@' + host obfuscated = re.sub(r'[a-zA-z0-9]', '*', address[1:-1]) return a...
Obfuscated email used for display
def _download_datasets(): def filepath(*args): return abspath(join(dirname(__file__), '..', 'vega_datasets', *args)) dataset_listing = {} for name in DATASETS_TO_DOWNLOAD: data = Dataset(name) url = data.url filename = filepath('_data', data.filename) print("retrievin...
Utility to download datasets into package source
def _timed_process(self, *args, **kwargs): for processor in self._processors: start_time = _time.process_time() processor.process(*args, **kwargs) process_time = int(round((_time.process_time() - start_time) * 1000, 2)) self.process_times[processor.__class__.__nam...
Track Processor execution time for benchmarking.
def _clean_doc(self, doc=None): if doc is None: doc = self.doc resources = doc['Resources'] for arg in ['startline', 'headerlines', 'encoding']: for e in list(resources.args): if e.lower() == arg: resources.args.remove(e) for te...
Clean the doc before writing it, removing unnecessary properties and doing other operations.
def visit_extslice(self, node, parent): newnode = nodes.ExtSlice(parent=parent) newnode.postinit([self.visit(dim, newnode) for dim in node.dims]) return newnode
visit an ExtSlice node by returning a fresh instance of it
def get_cp2k_structure(atoms): from cp2k_tools.generator import dict2cp2k cp2k_cell = {sym: ('[angstrom]',) + tuple(coords) for sym, coords in zip(('a', 'b', 'c'), atoms.get_cell()*Bohr)} cp2k_cell['periodic'] = 'XYZ' cp2k_coord = { 'scaled': True, '*': [[sym] + list(coord) for sym, coor...
Convert the atoms structure to a CP2K input file skeleton string
def begin_commit(): session_token = request.headers['session_token'] repository = request.headers['repository'] current_user = have_authenticated_user(request.environ['REMOTE_ADDR'], repository, session_token) if current_user is False: return fail(user_auth_fail_msg) repository_path = config['rep...
Allow a client to begin a commit and acquire the write lock
def ensure_all_columns_are_used(num_vars_accounted_for, dataframe, data_title='long_data'): dataframe_vars = set(dataframe.columns.tolist()) num_dataframe_vars = len(dataframe_vars) if num_vars_accounted_for == num_dataframe_vars: pass ...
Ensure that all of the columns from dataframe are in the list of used_cols. Will raise a helpful UserWarning if otherwise. Parameters ---------- num_vars_accounted_for : int. Denotes the number of variables used in one's function. dataframe : pandas dataframe. Contains all of the da...
def _BuildPluginRequest(self, app_id, challenge_data, origin): client_data_map = {} encoded_challenges = [] app_id_hash_encoded = self._Base64Encode(self._SHA256(app_id)) for challenge_item in challenge_data: key = challenge_item['key'] key_handle_encoded = self._Base64Encode(key.key_handle)...
Builds a JSON request in the form that the plugin expects.
def render_embed_css(self, css_embed: Iterable[bytes]) -> bytes: return b'<style type="text/css">\n' + b"\n".join(css_embed) + b"\n</style>"
Default method used to render the final embedded css for the rendered webpage. Override this method in a sub-classed controller to change the output.
def clean_asciidoc(text): r text = re.sub(r'(\b|^)[\[_*]{1,2}([a-zA-Z0-9])', r'"\2', text) text = re.sub(r'([a-zA-Z0-9])[\]_*]{1,2}', r'\1"', text) return text
r""" Transform asciidoc text into ASCII text that NL parsers can handle TODO: Tag lines and words with meta data like italics, underlined, bold, title, heading 1, etc >>> clean_asciidoc('**Hello** _world_!') '"Hello" "world"!'
def apply_template(template, *args, **kw): if six.callable(template): return template(*args, **kw) if isinstance(template, six.string_types): return template if isinstance(template, collections.Mapping): return template.__class__((k, apply_template(v, *args, **kw)) for k, v in templa...
Applies every callable in any Mapping or Iterable
def describe_page_numbers(current_page, total_count, per_page, page_numbers_at_ends=3, pages_numbers_around_current=3): if total_count: page_count = int(math.ceil(1.0 * total_count / per_page)) if page_count < current_page: raise PageNumberOutOfBounds page_numbers = get_page_numb...
Produces a description of how to display a paginated list's page numbers. Rather than just spitting out a list of every page available, the page numbers returned will be trimmed to display only the immediate numbers around the start, end, and the current page. :param current_page: the current page number (...
def _merge_pool_kwargs(self, override): base_pool_kwargs = self.connection_pool_kw.copy() if override: for key, value in override.items(): if value is None: try: del base_pool_kwargs[key] except KeyError: ...
Merge a dictionary of override values for self.connection_pool_kw. This does not modify self.connection_pool_kw and returns a new dict. Any keys in the override dictionary with a value of ``None`` are removed from the merged dictionary.
def canonicalize_clusters(clusters: DefaultDict[int, List[Tuple[int, int]]]) -> List[List[Tuple[int, int]]]: merged_clusters: List[Set[Tuple[int, int]]] = [] for cluster in clusters.values(): cluster_with_overlapping_mention = None for mention in cluster: for cluster2 in merged_clust...
The CONLL 2012 data includes 2 annotated spans which are identical, but have different ids. This checks all clusters for spans which are identical, and if it finds any, merges the clusters containing the identical spans.
def yaml_force_unicode(): if sys.version_info[0] == 2: def construct_func(self, node): return self.construct_scalar(node) yaml.Loader.add_constructor(U('tag:yaml.org,2002:str'), construct_func) yaml.SafeLoader.add_constructor(U('tag:yaml.org,2002:str'), constr...
Force pyyaml to return unicode values.
def try_to_set_up_global_logging(): root = logging.getLogger() root.setLevel(logging.DEBUG) formatter = logging.Formatter( '%(asctime)s %(levelname)-7s %(threadName)-10s:%(process)d [%(filename)s:%(funcName)s():%(lineno)s] %(message)s') if env.is_debug(): handler = logging.StreamHandler(...
Try to set up global W&B debug log that gets re-written by every W&B process. It may fail (and return False) eg. if the current directory isn't user-writable
def list_members(self, name, type="USER", recurse=True, max_results=1000): results = self.client.service.getListMembership( name, type, recurse, max_results, self.proxy_id, ) return [item["member"] for item in results]
Look up all the members of a list. Args: name (str): The name of the list type (str): The type of results to return. "USER" to get users, "LIST" to get lists. recurse (bool): Presumably, whether to recurse into member lists when retrieving use...
def getPeer(self, url): peers = filter(lambda x: x.getUrl() == url, self.getPeers()) if len(peers) == 0: raise exceptions.PeerNotFoundException(url) return peers[0]
Select the first peer in the datarepo with the given url simulating the behavior of selecting by URL. This is only used during testing.
def _conv(self, data): if isinstance(data, pd.Series): if data.name is None: data = data.to_frame(name='') else: data = data.to_frame() data = data.fillna('NaN') return data
Convert each input to appropriate for table outplot
def _send_command_list(self, commands): output = "" for command in commands: output += self.device.send_command( command, strip_prompt=False, strip_command=False ) return output
Wrapper for Netmiko's send_command method (for list of commands.
def process_tomography_programs(process, qubits=None, pre_rotation_generator=tomography.default_rotations, post_rotation_generator=tomography.default_rotations): if qubits is None: qubits = process.get_qubits() for tomographic_pre_rotation ...
Generator that yields tomographic sequences that wrap a process encoded by a QUIL program `proc` in tomographic rotations on the specified `qubits`. If `qubits is None`, it assumes all qubits in the program should be tomographically rotated. :param Program process: A Quil program :param list|NoneT...
def WSDLUriToVersion(self, uri): value = self._wsdl_uri_mapping.get(uri) if value is not None: return value raise ValueError( 'Unsupported SOAP envelope uri: %s' % uri )
Return the WSDL version related to a WSDL namespace uri.
def closeEvent(self, event): max_dataset_history = self.value('max_dataset_history') keep_recent_datasets(max_dataset_history, self.info) settings.setValue('window/geometry', self.saveGeometry()) settings.setValue('window/state', self.saveState()) event.accept()
save the name of the last open dataset.
def get_package_info_from_line(tpip_pkg, line): lower_line = line.lower() try: metadata_key, metadata_value = lower_line.split(':', 1) except ValueError: return metadata_key = metadata_key.strip() metadata_value = metadata_value.strip() if metadata_value == 'unknown': ret...
Given a line of text from metadata, extract semantic info
def _module_iterator(root, recursive=True): yield root stack = collections.deque((root,)) while stack: package = stack.popleft() paths = getattr(package, '__path__', []) for path in paths: modules = pkgutil.iter_modules([path]) for finder, name, is_package in ...
Iterate over modules.
def get_constant_state(self): ret = self.constant_states[self.next_constant_state] self.next_constant_state += 1 return ret
Read state that was written in "first_part" mode. Returns: a structure
def delete(self, url, headers=None, **kwargs): if headers is None: headers = [] if kwargs: url = url + UrlEncoded('?' + _encode(**kwargs), skip_encode=True) message = { 'method': "DELETE", 'headers': headers, } return self.request(url, message)
Sends a DELETE request to a URL. :param url: The URL. :type url: ``string`` :param headers: A list of pairs specifying the headers for the HTTP response (for example, ``[('Content-Type': 'text/cthulhu'), ('Token': 'boris')]``). :type headers: ``list`` :param kwargs: ...
def convert_to_vertexlist(geometry, **kwargs): if util.is_instance_named(geometry, 'Trimesh'): return mesh_to_vertexlist(geometry, **kwargs) elif util.is_instance_named(geometry, 'Path'): return path_to_vertexlist(geometry, **kwargs) elif util.is_instance_named(geometry, 'PointCloud'): ...
Try to convert various geometry objects to the constructor args for a pyglet indexed vertex list. Parameters ------------ obj : Trimesh, Path2D, Path3D, (n,2) float, (n,3) float Object to render Returns ------------ args : tuple Args to be passed to pyglet indexed vertex list ...
def condition_on_par_knowledge(cov,par_knowledge_dict): missing = [] for parnme in par_knowledge_dict.keys(): if parnme not in cov.row_names: missing.append(parnme) if len(missing): raise Exception("par knowledge dict parameters not found: {0}".\ format(',...
experimental function to include conditional prior information for one or more parameters in a full covariance matrix
def add_scroller_widget(self, ref, left=1, top=1, right=20, bottom=1, direction="h", speed=1, text="Message"): if ref not in self.widgets: widget = ScrollerWidget(screen=self, ref=ref, left=left, top=top, right=right, bottom=bottom, direction=direction, speed=speed, text=text) se...
Add Scroller Widget
def enable_disable(self): if self.enabled: self.data['enabled'] = False else: self.data['enabled'] = True self.update()
Enable or disable this endpoint. If enabled, it will be disabled and vice versa. :return: None
def get_experiment_status(port): result, response = check_rest_server_quick(port) if result: return json.loads(response.text).get('status') return None
get the status of an experiment
def filename( self, node ): if not node.directory: return None if node.filename == '~': return None return os.path.join(node.directory, node.filename)
Extension to squaremap api to provide "what file is this" information
def Reorder(x, params, output=None, **kwargs): del params, kwargs if output is None: return x return base.nested_map(output, lambda i: x[i])
Reorder a tuple into another tuple. For example, we can re-order (x, y) into (y, x) or even (y, (x, y), y). The output argument specifies how to re-order, using integers that refer to indices in the input tuple. For example, if input = (x, y, z) then Reorder(input, output=(1, 0, 2)) = (y, x, z) ...
def _ratio_scores(parameters_value, clusteringmodel_gmm_good, clusteringmodel_gmm_bad): ratio = clusteringmodel_gmm_good.score([parameters_value]) / clusteringmodel_gmm_bad.score([parameters_value]) sigma = 0 return ratio, sigma
The ratio is smaller the better
def size(pathname): if os.path.isfile(pathname): return os.path.getsize(pathname) return sum([size('{}/{}'.format(pathname, name)) for name in get_content_list(pathname)])
Returns size of a file or folder in Bytes :param pathname: path to file or folder to be sized :type pathname: str :return: size of file or folder in Bytes :rtype: int :raises: os.error if file is not accessible
def delete(self): with self._qpart: for cursor in self.cursors(): if cursor.hasSelection(): cursor.deleteChar()
Del or Backspace pressed. Delete selection
def getratio(self, code) : if len(code) == 0 : return 0 code_replaced = self.prog.sub('', code) return (len(code) - len(code_replaced)) / len(code)
Get ratio of code and pattern matched
def _cla_adder_unit(a, b, cin): gen = a & b prop = a ^ b assert(len(prop) == len(gen)) carry = [gen[0] | prop[0] & cin] sum_bit = prop[0] ^ cin cur_gen = gen[0] cur_prop = prop[0] for i in range(1, len(prop)): cur_gen = gen[i] | (prop[i] & cur_gen) cur_prop = cur_prop & p...
Carry generation and propogation signals will be calculated only using the inputs; their values don't rely on the sum. Every unit generates a cout signal which is used as cin for the next unit.
def _has_role(self, organisation_id, role): if organisation_id is None: return False try: org = self.organisations.get(organisation_id, {}) user_role = org.get('role') state = org.get('state') except AttributeError: return False ...
Check the user's role for the organisation
def _retryable_read_command(self, command, value=1, check=True, allowable_errors=None, read_preference=None, codec_options=DEFAULT_CODEC_OPTIONS, session=None, **kwargs): if read_preference is None: read_preference = ((session and session._txn_read_preference()) ...
Same as command but used for retryable read commands.
def add_field(self, name, fragment_size=150, number_of_fragments=3, fragment_offset=None, order="score", type=None): data = {} if fragment_size: data['fragment_size'] = fragment_size if number_of_fragments is not None: data['number_of_fragments'] = number_of_fragments ...
Add a field to Highlinghter
def get_instance(self, payload): return WorkflowInstance(self._version, payload, workspace_sid=self._solution['workspace_sid'], )
Build an instance of WorkflowInstance :param dict payload: Payload response from the API :returns: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowInstance :rtype: twilio.rest.taskrouter.v1.workspace.workflow.WorkflowInstance
def dump(self): return dict( self.other, name=self.name, url=self.url, credentials=self.credentials, description=self.description, )
Return a dict of fields that can be used to recreate this profile. For example:: >>> profile = Profile(name="foobar", ...) >>> profile == Profile(**profile.dump()) True Use this value when persisting a profile.
def append(self, entry): if not self.is_appendable(entry): raise ValueError('entry not appendable') self.data += entry.data
Append an entry to self
def get_importer(path_item): try: importer = sys.path_importer_cache[path_item] except KeyError: for path_hook in sys.path_hooks: try: importer = path_hook(path_item) break except ImportError: pass else: ...
Retrieve a PEP 302 importer for the given path item The returned importer is cached in sys.path_importer_cache if it was newly created by a path hook. If there is no importer, a wrapper around the basic import machinery is returned. This wrapper is never inserted into the importer cache (None is i...
def get_apis(self): out = set(x.api for x in self.types.values() if x.api) for ft in self.features.values(): out.update(ft.get_apis()) for ext in self.extensions.values(): out.update(ext.get_apis()) return out
Returns set of api names referenced in this Registry :return: set of api name strings
def file_can_be_written(path): if path is None: return False try: with io.open(path, "wb") as test_file: pass delete_file(None, path) return True except (IOError, OSError): pass return False
Return ``True`` if a file can be written at the given ``path``. :param string path: the file path :rtype: bool .. warning:: This function will attempt to open the given ``path`` in write mode, possibly destroying the file previously existing there. .. versionadded:: 1.4.0
def readlines(self, timeout=1): lines = [] while 1: line = self.readline(timeout=timeout) if line: lines.append(line) if not line or line[-1:] != '\n': break return lines
read all lines that are available. abort after timeout when no more data arrives.
def onStart(self, event): c = event.container print '+' * 5, 'started:', c kv = lambda s: s.split('=', 1) env = {k: v for (k, v) in (kv(s) for s in c.attrs['Config']['Env'])} print env
Display the environment of a started container
def refresh(self) -> None: logger.info('refreshing sources') for source in list(self): self.unload(source) if not os.path.exists(self.__registry_fn): return with open(self.__registry_fn, 'r') as f: registry = yaml.load(f) assert isinstance(regi...
Reloads all sources that are registered with this server.
def run_locally(self): self.thread = threading.Thread(target=self.execute_locally) self.thread.daemon = True self.thread.start()
A convenience method to run the same result as a SLURM job but locally in a non-blocking way. Useful for testing.
def find_existing(self): instances = self.consul.find_servers(self.tags) maxnames = len(instances) while instances: i = instances.pop(0) server_id = i[A.server.ID] if self.namespace.add_if_unique(server_id): log.info('Found existing server, %s'...
Searches for existing server instances with matching tags. To match, the existing instances must also be "running".
def walkSignalPorts(rootPort: LPort): if rootPort.children: for ch in rootPort.children: yield from walkSignalPorts(ch) else: yield rootPort
recursively walk ports without any children
def handler(ca_file=None): def request(url, message, **kwargs): scheme, host, port, path = spliturl(url) if scheme != "https": ValueError("unsupported scheme: %s" % scheme) connection = HTTPSConnection(host, port, ca_file) try: body = message.get('body', "") ...
Returns an HTTP request handler configured with the given ca_file.
def addlayer(self, name, srs, geomType): self.vector.CreateLayer(name, srs, geomType) self.init_layer()
add a layer to the vector layer Parameters ---------- name: str the layer name srs: int, str or :osgeo:class:`osr.SpatialReference` the spatial reference system. See :func:`spatialist.auxil.crsConvert` for options. geomType: int an OGR well-kn...
def bit_reversal(qubits: List[int]) -> Program: p = Program() n = len(qubits) for i in range(int(n / 2)): p.inst(SWAP(qubits[i], qubits[-i - 1])) return p
Generate a circuit to do bit reversal. :param qubits: Qubits to do bit reversal with. :return: A program to do bit reversal.
def get_input(prompt, check, *, redo_prompt=None, repeat_prompt=False): if isinstance(check, str): check = (check,) to_join = [] for item in check: if item: to_join.append(str(item)) else: to_join.append("''") prompt += " [{}]: ".format('/'.join(to_join)) ...
Ask the user to input something on the terminal level, check their response and ask again if they didn't answer correctly
def get_client_properties_per_page(self, per_page=1000, page=1, params=None): return self._get_resource_per_page( resource=CLIENT_PROPERTIES, per_page=per_page, page=page, params=params )
Get client properties per page :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :param params: Search parameters. Default: {} :return: list
def class_name_str(obj, skip_parent=False): rt = str(type(obj)).split(" ")[1][1:-2] if skip_parent: rt = rt.split(".")[-1] return rt
return's object's class name as string
def ecb(base, target): api_url = 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml' resp = requests.get(api_url, timeout=1) text = resp.text def _find_rate(symbol): if symbol == 'EUR': return decimal.Decimal(1.00) m = re.findall(r"currency='%s' rate='([0-9\.]+)'" ...
Parse data from European Central Bank.
def create_prj_model(self, ): prjs = djadapter.projects.all() rootdata = treemodel.ListItemData(['Name', 'Short', 'Rootpath']) prjroot = treemodel.TreeItem(rootdata) for prj in prjs: prjdata = djitemdata.ProjectItemData(prj) treemodel.TreeItem(prjdata, prjroot) ...
Create and return a tree model that represents a list of projects :returns: the creeated model :rtype: :class:`jukeboxcore.gui.treemodel.TreeModel` :raises: None
def _hash_data(hasher, data): _hasher = hasher.copy() _hasher.update(data) return _hasher.finalize()
Generate hash of data using provided hash type. :param hasher: Hasher instance to use as a base for calculating hash :type hasher: cryptography.hazmat.primitives.hashes.Hash :param bytes data: Data to sign :returns: Hash of data :rtype: bytes
def _ensure_filepath(filename): filepath = os.path.dirname(filename) if not os.path.exists(filepath): os.makedirs(filepath)
Ensure that the directory exists before trying to write to the file.