code
stringlengths
64
7.01k
docstring
stringlengths
2
15.8k
text
stringlengths
144
19.2k
#vtb def delete(block_id): _url = get_root_url() try: DB.delete_processing_block(block_id) response = dict(message=, id=.format(block_id), links=dict(list=.format(_url), home=.format(_url))) return re...
Processing block detail resource.
### Input: Processing block detail resource. ### Response: #vtb def delete(block_id): _url = get_root_url() try: DB.delete_processing_block(block_id) response = dict(message=, id=.format(block_id), links=dict(list=.format(_url), ...
#vtb def total_stored(self, wanted, slots=None): if slots is None: slots = self.window.slots wanted = make_slot_check(wanted) return sum(slot.amount for slot in slots if wanted(slot))
Calculates the total number of items of that type in the current window or given slot range. Args: wanted: function(Slot) or Slot or itemID or (itemID, metadata)
### Input: Calculates the total number of items of that type in the current window or given slot range. Args: wanted: function(Slot) or Slot or itemID or (itemID, metadata) ### Response: #vtb def total_stored(self, wanted, slots=None): if slots is None: slots ...
#vtb def select_entry(self, core_element_id, by_cursor=True): for row_num, element_row in enumerate(self.list_store): if element_row[self.ID_STORAGE_ID] == core_element_id: if by_cursor: self.tree_view.set_cursor(row_num) else...
Selects the row entry belonging to the given core_element_id by cursor or tree selection
### Input: Selects the row entry belonging to the given core_element_id by cursor or tree selection ### Response: #vtb def select_entry(self, core_element_id, by_cursor=True): for row_num, element_row in enumerate(self.list_store): if element_row[self.ID_STORAGE_ID] == core_e...
#vtb def get_activities_for_objective(self, objective_id=None): if objective_id is None: raise NullArgument() url_path = construct_url(, bank_id=self._catalog_idstr, obj_id=objective_id) return object...
Gets the activities for the given objective. In plenary mode, the returned list contains all of the activities mapped to the objective Id or an error results if an Id in the supplied list is not found or inaccessible. Otherwise, inaccessible Activities may be omitted from the list and ma...
### Input: Gets the activities for the given objective. In plenary mode, the returned list contains all of the activities mapped to the objective Id or an error results if an Id in the supplied list is not found or inaccessible. Otherwise, inaccessible Activities may be omitted from the...
#vtb def get_broadcast_date(pid): print("Extracting first broadcast date...") broadcast_etree = open_listing_page(pid + ) original_broadcast_date, = broadcast_etree.xpath( ) return original_broadcast_date
Take BBC pid (string); extract and return broadcast date as string.
### Input: Take BBC pid (string); extract and return broadcast date as string. ### Response: #vtb def get_broadcast_date(pid): print("Extracting first broadcast date...") broadcast_etree = open_listing_page(pid + ) original_broadcast_date, = broadcast_etree.xpath( ) return origin...
#vtb def seek(self, timestamp): if not re.match(r, timestamp): raise ValueError() self.avTransport.Seek([ (, 0), (, ), (, timestamp) ])
Seek to a given timestamp in the current track, specified in the format of HH:MM:SS or H:MM:SS. Raises: ValueError: if the given timestamp is invalid.
### Input: Seek to a given timestamp in the current track, specified in the format of HH:MM:SS or H:MM:SS. Raises: ValueError: if the given timestamp is invalid. ### Response: #vtb def seek(self, timestamp): if not re.match(r, timestamp): raise ValueError() ...
#vtb def stream_fastq_full(fastq, threads): logging.info("Nanoget: Starting to collect full metrics from plain fastq file.") inputfastq = handle_compressed_input(fastq) with cfutures.ProcessPoolExecutor(max_workers=threads) as executor: for results in executor.map(extract_all_from_fastq, SeqIO....
Generator for returning metrics extracted from fastq. Extract from a fastq file: -readname -average and median quality -read_lenght
### Input: Generator for returning metrics extracted from fastq. Extract from a fastq file: -readname -average and median quality -read_lenght ### Response: #vtb def stream_fastq_full(fastq, threads): logging.info("Nanoget: Starting to collect full metrics from plain fastq file.") inputf...
#vtb def expand_recurring(number, repeat=5): if "[" in number: pattern_index = number.index("[") pattern = number[pattern_index + 1:-1] number = number[:pattern_index] number = number + pattern * (repeat + 1) return number
Expands a recurring pattern within a number. Args: number(tuple): the number to process in the form: (int, int, int, ... ".", ... , int int int) repeat: the number of times to expand the pattern. Returns: The original number with recurring pattern expanded. E...
### Input: Expands a recurring pattern within a number. Args: number(tuple): the number to process in the form: (int, int, int, ... ".", ... , int int int) repeat: the number of times to expand the pattern. Returns: The original number with recurring pattern expand...
#vtb def is_revision_chain_placeholder(pid): return d1_gmn.app.models.ReplicaRevisionChainReference.objects.filter( pid__did=pid ).exists()
For replicas, the PIDs referenced in revision chains are reserved for use by other replicas.
### Input: For replicas, the PIDs referenced in revision chains are reserved for use by other replicas. ### Response: #vtb def is_revision_chain_placeholder(pid): return d1_gmn.app.models.ReplicaRevisionChainReference.objects.filter( pid__did=pid ).exists()
#vtb def update_ports(self, ports, id_or_uri, timeout=-1): resources = merge_default_values(ports, {: }) uri = self._client.build_uri(id_or_uri) + "/update-ports" return self._client.update(resources, uri, timeout)
Updates the interconnect ports. Args: id_or_uri: Can be either the interconnect id or the interconnect uri. ports (list): Ports to update. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView; i...
### Input: Updates the interconnect ports. Args: id_or_uri: Can be either the interconnect id or the interconnect uri. ports (list): Ports to update. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation i...
#vtb def qs_from_dict(qsdict, prefix=""): prefix = prefix + if prefix else "" def descend(qsd): for key, val in sorted(qsd.items()): if val: yield qs_from_dict(val, prefix + key) else: yield prefix + key return ",".join(descend(qsdict))
Same as dict_from_qs, but in reverse i.e. {"period": {"di": {}, "fhr": {}}} => "period.di,period.fhr"
### Input: Same as dict_from_qs, but in reverse i.e. {"period": {"di": {}, "fhr": {}}} => "period.di,period.fhr" ### Response: #vtb def qs_from_dict(qsdict, prefix=""): prefix = prefix + if prefix else "" def descend(qsd): for key, val in sorted(qsd.items()): if val: ...
#vtb def plot_transaction_rate_heterogeneity( model, suptitle="Heterogeneity in Transaction Rate", xlabel="Transaction Rate", ylabel="Density", suptitle_fontsize=14, **kwargs ): from matplotlib import pyplot as plt r, alpha = model._unload_params("r", "alpha") rate_mean = r / a...
Plot the estimated gamma distribution of lambda (customers' propensities to purchase). Parameters ---------- model: lifetimes model A fitted lifetimes model, for now only for BG/NBD suptitle: str, optional Figure suptitle xlabel: str, optional Figure xlabel ylabel: str, ...
### Input: Plot the estimated gamma distribution of lambda (customers' propensities to purchase). Parameters ---------- model: lifetimes model A fitted lifetimes model, for now only for BG/NBD suptitle: str, optional Figure suptitle xlabel: str, optional Figure xlabel y...
#vtb def Ctrl(cls, key): element = cls._element() element.send_keys(Keys.CONTROL, key)
在指定元素上执行ctrl组合键事件 @note: key event -> control + key @param key: 如'X'
### Input: 在指定元素上执行ctrl组合键事件 @note: key event -> control + key @param key: 如'X' ### Response: #vtb def Ctrl(cls, key): element = cls._element() element.send_keys(Keys.CONTROL, key)
#vtb def connect(self): try: if S3Handler.S3_KEYS: self.s3 = BotoClient(self.opt, S3Handler.S3_KEYS[0], S3Handler.S3_KEYS[1]) else: self.s3 = BotoClient(self.opt) except Exception as e: raise RetryFailure( % e)
Connect to S3 storage
### Input: Connect to S3 storage ### Response: #vtb def connect(self): try: if S3Handler.S3_KEYS: self.s3 = BotoClient(self.opt, S3Handler.S3_KEYS[0], S3Handler.S3_KEYS[1]) else: self.s3 = BotoClient(self.opt) except Exception as e: raise RetryFailure( % e)
#vtb def internal_energy(self, t, structure=None): if t==0: return self.zero_point_energy(structure=structure) freqs = self._positive_frequencies dens = self._positive_densities coth = lambda x: 1.0 / np.tanh(x) wd2kt = freqs / (2 * BOLTZ_THZ_PER_K * t) ...
Phonon contribution to the internal energy at temperature T obtained from the integration of the DOS. Only positive frequencies will be used. Result in J/mol-c. A mol-c is the abbreviation of a mole-cell, that is, the number of Avogadro times the atoms in a unit cell. To compare with experimenta...
### Input: Phonon contribution to the internal energy at temperature T obtained from the integration of the DOS. Only positive frequencies will be used. Result in J/mol-c. A mol-c is the abbreviation of a mole-cell, that is, the number of Avogadro times the atoms in a unit cell. To compare with...
#vtb def parse_raid(rule): parser = argparse.ArgumentParser() rules = shlex.split(rule) rules.pop(0) partitions = [] newrules = [] for count in range(0, len(rules)): if count == 0: newrules.append(rules[count]) continue elif rules[count].startswith()...
Parse the raid line
### Input: Parse the raid line ### Response: #vtb def parse_raid(rule): parser = argparse.ArgumentParser() rules = shlex.split(rule) rules.pop(0) partitions = [] newrules = [] for count in range(0, len(rules)): if count == 0: newrules.append(rules[count]) ...
#vtb def reverse_whois(self, query, exclude=[], scope=, mode=None, **kwargs): return self._results(, , terms=delimited(query), exclude=delimited(exclude), scope=scope, mode=mode, **kwargs)
List of one or more terms to search for in the Whois record, as a Python list or separated with the pipe character ( | ).
### Input: List of one or more terms to search for in the Whois record, as a Python list or separated with the pipe character ( | ). ### Response: #vtb def reverse_whois(self, query, exclude=[], scope=, mode=None, **kwargs): return self._results(, , terms=delimited(query), exclude=delimite...
#vtb def render_files(self, root=None): if root is None: tmp = os.environ.get() root = sys.path[1 if tmp and tmp in sys.path else 0] items = [] for filename in os.listdir(root): ...
Render the file path as accordions
### Input: Render the file path as accordions ### Response: #vtb def render_files(self, root=None): if root is None: tmp = os.environ.get() root = sys.path[1 if tmp and tmp in sys.path else 0] items = [] for filename in os.listdir(root): ...
#vtb def org_update(object_id, input_params={}, always_retry=True, **kwargs): return DXHTTPRequest( % object_id, input_params, always_retry=always_retry, **kwargs)
Invokes the /org-xxxx/update API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Organizations#API-method%3A-%2Forg-xxxx%2Fupdate
### Input: Invokes the /org-xxxx/update API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Organizations#API-method%3A-%2Forg-xxxx%2Fupdate ### Response: #vtb def org_update(object_id, input_params={}, always_retry=True, **kwargs): return DXHTTPRequest( % object_id, input...
#vtb def upload_file(self, local_path, remote_path): logger.debug("{0}: uploading {1} to {0}:{2}".format(self.target_address, local_path, remote_path)) try: sftp =...
Upload a file from the local filesystem to the remote host :type local_path: str :param local_path: path of local file to upload :type remote_path: str :param remote_path: destination path of upload on remote host
### Input: Upload a file from the local filesystem to the remote host :type local_path: str :param local_path: path of local file to upload :type remote_path: str :param remote_path: destination path of upload on remote host ### Response: #vtb def upload_file(self, local_path, remote_...
#vtb def get_all_related_many_to_many_objects(opts): if django.VERSION < (1, 9): return opts.get_all_related_many_to_many_objects() else: return [r for r in opts.related_objects if r.field.many_to_many]
Django 1.8 changed meta api, see docstr in compat.get_all_related_objects() :param opts: Options instance :return: list of many-to-many relations
### Input: Django 1.8 changed meta api, see docstr in compat.get_all_related_objects() :param opts: Options instance :return: list of many-to-many relations ### Response: #vtb def get_all_related_many_to_many_objects(opts): if django.VERSION < (1, 9): return opts.get_all_related_many_to_many...
#vtb def fold_columns_to_rows(df, levels_from=2): df = df.copy() df.reset_index(inplace=True, drop=True) df = df.T a = [list( set( df.index.get_level_values(i) ) ) for i in range(0, levels_from)] combinations = list(itertools.product(*a)) names = df.index.names[:levels...
Take a levels from the columns and fold down into the row index. This destroys the existing index; existing rows will appear as columns under the new column index :param df: :param levels_from: The level (inclusive) from which column index will be folded :return:
### Input: Take a levels from the columns and fold down into the row index. This destroys the existing index; existing rows will appear as columns under the new column index :param df: :param levels_from: The level (inclusive) from which column index will be folded :return: ### Response: #vtb def...
#vtb def update_energy(self, bypass_check=False): for outlet in self.outlets: outlet.update_energy(bypass_check)
Fetch updated energy information about devices
### Input: Fetch updated energy information about devices ### Response: #vtb def update_energy(self, bypass_check=False): for outlet in self.outlets: outlet.update_energy(bypass_check)
#vtb def mesh(**kwargs): obs_params = [] syn_params, constraints = mesh_syn(syn=False, **kwargs) obs_params += syn_params.to_list() obs_params += [SelectParameter(qualifier=, value=kwargs.get(, []), description=, choices=[])] obs_params += [SelectParameter(qualifier=, value=kwargs.get(, [])...
Create parameters for a new mesh dataset. Generally, this will be used as an input to the kind argument in :meth:`phoebe.frontend.bundle.Bundle.add_dataset` :parameter **kwargs: defaults for the values of any of the parameters :return: a :class:`phoebe.parameters.parameters.ParameterSet` of all newly ...
### Input: Create parameters for a new mesh dataset. Generally, this will be used as an input to the kind argument in :meth:`phoebe.frontend.bundle.Bundle.add_dataset` :parameter **kwargs: defaults for the values of any of the parameters :return: a :class:`phoebe.parameters.parameters.ParameterSet` o...
#vtb def reads(paths, filename=, options=None, **keywords): if groupname not in f \ or not isinstance(f[groupname], h5py.Group): raise exceptions.CantReadError( \ \ + groupname + ) data...
Reads data from an HDF5 file (high level). High level function to read one or more pieces of data from an HDF5 file located at the paths specified in `paths` into Python types. Each path is specified as a POSIX style path where the data to read is located. There are various options that can be use...
### Input: Reads data from an HDF5 file (high level). High level function to read one or more pieces of data from an HDF5 file located at the paths specified in `paths` into Python types. Each path is specified as a POSIX style path where the data to read is located. There are various options tha...
#vtb def register(self, model_alias, code=, name=None, order=None, display_filter=None): model_alias = self.get_model_alias(model_alias) def wrapper(create_layout): item = TabItem( code=code, create_layout=create_layout, name=name, ...
Register new tab :param model_alias: :param code: :param name: :param order: :return:
### Input: Register new tab :param model_alias: :param code: :param name: :param order: :return: ### Response: #vtb def register(self, model_alias, code=, name=None, order=None, display_filter=None): model_alias = self.get_model_alias(model_alias) def...
#vtb def ops_to_words(item): unsupp_ops = ["~=", "==="] supp_ops = [">=", ">", "==", "<=", "<", "!="] tokens = sorted(item.split(","), reverse=True) actual_tokens = [] for req in tokens: for op in unsupp_ops: if req.startswith(op): raise RuntimeError("Un...
Translate requirement specification to words.
### Input: Translate requirement specification to words. ### Response: #vtb def ops_to_words(item): unsupp_ops = ["~=", "==="] supp_ops = [">=", ">", "==", "<=", "<", "!="] tokens = sorted(item.split(","), reverse=True) actual_tokens = [] for req in tokens: for op in unsupp_ops: ...
#vtb def error(self, i: int=None) -> str: head = "[" + colors.red("error") + "]" if i is not None: head = str(i) + " " + head return head
Returns an error message
### Input: Returns an error message ### Response: #vtb def error(self, i: int=None) -> str: head = "[" + colors.red("error") + "]" if i is not None: head = str(i) + " " + head return head
#vtb def anoteElements(ax, anotelist, showAccName=False, efilter=None, textypos=None, **kwargs): defaultstyle = {: 0.8, : dict(arrowstyle=), : -60, : } defaultstyle.update(kwargs) anote_list = [] if efilter is None: for anote in anotelist: ...
annotate elements to axes :param ax: matplotlib axes object :param anotelist: element annotation object list :param showAccName: tag name for accelerator tubes? default is False, show acceleration band type, e.g. 'S', 'C', 'X', or for '[S,C,X]D' for cavi...
### Input: annotate elements to axes :param ax: matplotlib axes object :param anotelist: element annotation object list :param showAccName: tag name for accelerator tubes? default is False, show acceleration band type, e.g. 'S', 'C', 'X', or for '[S,C,X...
#vtb def palette_image(self): if self.pimage is None: palette = [] for i in range(self.NETSIZE): palette.extend(self.colormap[i][:3]) palette.extend([0] * (256 - self.NETSIZE) * 3) self.pimage = Image.new("P", (1, 1), 0) ...
PIL weird interface for making a paletted image: create an image which already has the palette, and use that in Image.quantize. This function returns this palette image.
### Input: PIL weird interface for making a paletted image: create an image which already has the palette, and use that in Image.quantize. This function returns this palette image. ### Response: #vtb def palette_image(self): if self.pimage is None: palette = [] ...
#vtb def visit_console_html(self, node): if self.builder.name in (, ) and node[]: self.document._console_directive_used_flag = True uid = node[] self.body.append( % {: uid}) try: self.visit_literal_block(node) except nodes.SkipNode: ...
Generate HTML for the console directive.
### Input: Generate HTML for the console directive. ### Response: #vtb def visit_console_html(self, node): if self.builder.name in (, ) and node[]: self.document._console_directive_used_flag = True uid = node[] self.body.append( % {: uid}) try: se...
#vtb def _mkfs(root, fs_format, fs_opts=None): if fs_opts is None: fs_opts = {} if fs_format in (, , ): __salt__[](root, fs_format, **fs_opts) elif fs_format in (,): __salt__[](root, **fs_opts) elif fs_format in (,): __salt__[](root, **fs_opts)
Make a filesystem using the appropriate module .. versionadded:: Beryllium
### Input: Make a filesystem using the appropriate module .. versionadded:: Beryllium ### Response: #vtb def _mkfs(root, fs_format, fs_opts=None): if fs_opts is None: fs_opts = {} if fs_format in (, , ): __salt__[](root, fs_format, **fs_opts) elif fs_format in (,): __sal...
#vtb def random_indexes(max_index, subset_size=None, seed=None, rng=None): subst_ = np.arange(0, max_index) rng = ensure_rng(seed if rng is None else rng) rng.shuffle(subst_) if subset_size is None: subst = subst_ else: subst = subst_[0:min(subset_size, max_index)] return su...
random unrepeated indicies Args: max_index (?): subset_size (None): (default = None) seed (None): (default = None) rng (RandomState): random number generator(default = None) Returns: ?: subst CommandLine: python -m utool.util_numpy --exec-random_indexes ...
### Input: random unrepeated indicies Args: max_index (?): subset_size (None): (default = None) seed (None): (default = None) rng (RandomState): random number generator(default = None) Returns: ?: subst CommandLine: python -m utool.util_numpy --exec-rando...
#vtb def parse_expression(expression: str) -> Tuple[Set[str], List[CompositeAxis]]: identifiers = set() composite_axes = [] if in expression: if not in expression: raise EinopsError() if str.count(expression, ) != 1 or str.count(expression, ) != 3: raise Einops...
Parses an indexing expression (for a single tensor). Checks uniqueness of names, checks usage of '...' (allowed only once) Returns set of all used identifiers and a list of axis groups
### Input: Parses an indexing expression (for a single tensor). Checks uniqueness of names, checks usage of '...' (allowed only once) Returns set of all used identifiers and a list of axis groups ### Response: #vtb def parse_expression(expression: str) -> Tuple[Set[str], List[CompositeAxis]]: identif...
#vtb def invokeCompletionIfAvailable(self, requestedByUser=False): if self._qpart.completionEnabled and self._wordSet is not None: wordBeforeCursor = self._wordBeforeCursor() wholeWord = wordBeforeCursor + self._wordAfterCursor() forceShow = requestedByUser or self....
Invoke completion, if available. Called after text has been typed in qpart Returns True, if invoked
### Input: Invoke completion, if available. Called after text has been typed in qpart Returns True, if invoked ### Response: #vtb def invokeCompletionIfAvailable(self, requestedByUser=False): if self._qpart.completionEnabled and self._wordSet is not None: wordBeforeCursor = self._...
#vtb def _set_request_cache_if_django_cache_hit(key, django_cached_response): if django_cached_response.is_found: DEFAULT_REQUEST_CACHE.set(key, django_cached_response.value)
Sets the value in the request cache if the django cached response was a hit. Args: key (string) django_cached_response (CachedResponse)
### Input: Sets the value in the request cache if the django cached response was a hit. Args: key (string) django_cached_response (CachedResponse) ### Response: #vtb def _set_request_cache_if_django_cache_hit(key, django_cached_response): if django_cached_response.is_...
#vtb def to_json(self): res_dict = {} def gen_dep_edge(node, edge, dep_tgt, aliases): return { : dep_tgt.address.spec, : self._edge_type(node.concrete_target, edge, dep_tgt), : len(edge.products_used), : self._used_ratio(dep_tgt, edge), : [alias.address.spec f...
Outputs the entire graph.
### Input: Outputs the entire graph. ### Response: #vtb def to_json(self): res_dict = {} def gen_dep_edge(node, edge, dep_tgt, aliases): return { : dep_tgt.address.spec, : self._edge_type(node.concrete_target, edge, dep_tgt), : len(edge.products_used), : self._used_...
#vtb def run_transaction(self, command_list, do_commit=True): pass for c in command_list: if c.find(";") != -1 or c.find("\\G") != -1: raise Exception("The SQL command contains a semi-colon or \\G. This is a potential SQ...
This can be used to stage multiple commands and roll back the transaction if an error occurs. This is useful if you want to remove multiple records in multiple tables for one entity but do not want the deletion to occur if the entity is tied to table not specified in the list of commands. Perfor...
### Input: This can be used to stage multiple commands and roll back the transaction if an error occurs. This is useful if you want to remove multiple records in multiple tables for one entity but do not want the deletion to occur if the entity is tied to table not specified in the list of comm...
#vtb def _serialize_value(self, value): if isinstance(value, (list, tuple, set)): return [self._serialize_value(v) for v in value] elif isinstance(value, dict): return dict([(k, self._serialize_value(v)) for k, v in value.items()]) elif isinstance(value, ModelBas...
Called by :py:meth:`._serialize` to serialise an individual value.
### Input: Called by :py:meth:`._serialize` to serialise an individual value. ### Response: #vtb def _serialize_value(self, value): if isinstance(value, (list, tuple, set)): return [self._serialize_value(v) for v in value] elif isinstance(value, dict): return dict([(k,...
#vtb def latcyl(radius, lon, lat): radius = ctypes.c_double(radius) lon = ctypes.c_double(lon) lat = ctypes.c_double(lat) r = ctypes.c_double() lonc = ctypes.c_double() z = ctypes.c_double() libspice.latcyl_c(radius, lon, lat, ctypes.byref(r), ctypes.byref(lonc), c...
Convert from latitudinal coordinates to cylindrical coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/latcyl_c.html :param radius: Distance of a point from the origin. :type radius: :param lon: Angle of the point from the XZ plane in radians. :param lat: Angle of the point from ...
### Input: Convert from latitudinal coordinates to cylindrical coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/latcyl_c.html :param radius: Distance of a point from the origin. :type radius: :param lon: Angle of the point from the XZ plane in radians. :param lat: Angle of the...
#vtb def _pull_out_perm_rhs(rest, rhs, out_port, in_port): in_im, rhs_red = rhs._factor_rhs(in_port) return (Feedback.create( SeriesProduct.create(*rest), out_port=out_port, in_port=in_im) << rhs_red)
Similar to :func:`_pull_out_perm_lhs` but on the RHS of a series product self-feedback.
### Input: Similar to :func:`_pull_out_perm_lhs` but on the RHS of a series product self-feedback. ### Response: #vtb def _pull_out_perm_rhs(rest, rhs, out_port, in_port): in_im, rhs_red = rhs._factor_rhs(in_port) return (Feedback.create( SeriesProduct.create(*rest), o...
#vtb def postinit(self, value, conversion=None, format_spec=None): self.value = value self.conversion = conversion self.format_spec = format_spec
Do some setup after initialisation. :param value: The value to be formatted into the string. :type value: NodeNG :param conversion: The type of formatting to be applied to the value. :type conversion: int or None :param format_spec: The formatting to be applied to the value. ...
### Input: Do some setup after initialisation. :param value: The value to be formatted into the string. :type value: NodeNG :param conversion: The type of formatting to be applied to the value. :type conversion: int or None :param format_spec: The formatting to be applied to ...
#vtb def spiro_image(R, r, r_, resolution=2*PI/1000, spins=50, size=[32, 32]): x, y = give_dots(200, r, r_, spins=20) xy = np.array([x, y]).T xy = np.array(np.around(xy), dtype=np.int64) xy = xy[(xy[:, 0] >= -250) & (xy[:, 1] >= -250) & (xy[:, 0] < 250) & (xy[:, 1] < 250)] xy = xy +...
Create image with given Spirograph parameters using numpy and scipy.
### Input: Create image with given Spirograph parameters using numpy and scipy. ### Response: #vtb def spiro_image(R, r, r_, resolution=2*PI/1000, spins=50, size=[32, 32]): x, y = give_dots(200, r, r_, spins=20) xy = np.array([x, y]).T xy = np.array(np.around(xy), dtype=np.int64) xy = xy[(xy[:, 0...
#vtb def match(self, pattern, context=None): matches = [] regex = pattern if regex == : regex = regex = re.compile(regex) for choice in self.choices(context): if regex.search(choice): matches.append(choice) return matches
This method returns a (possibly empty) list of strings that match the regular expression ``pattern`` provided. You can also provide a ``context`` as described above. This method calls ``choices`` to get a list of all possible choices and then filters the list by performing a regular ...
### Input: This method returns a (possibly empty) list of strings that match the regular expression ``pattern`` provided. You can also provide a ``context`` as described above. This method calls ``choices`` to get a list of all possible choices and then filters the list by performing ...
#vtb def get_formset(self, request, obj=None, **kwargs): data = super().get_formset(request, obj, **kwargs) if obj: data.form.base_fields[].initial = request.user.id return data
Default user to the current version owner.
### Input: Default user to the current version owner. ### Response: #vtb def get_formset(self, request, obj=None, **kwargs): data = super().get_formset(request, obj, **kwargs) if obj: data.form.base_fields[].initial = request.user.id return data
#vtb def r_q_send(self, msg_dict): no_pickle_keys = self.invalid_dict_pickle_keys(msg_dict) if no_pickle_keys == []: self.r_q.put(msg_dict) else: hash_func = md5() hash_func.update(str(msg_dict)) dict_hash = str(ha...
Send message dicts through r_q, and throw explicit errors for pickle problems
### Input: Send message dicts through r_q, and throw explicit errors for pickle problems ### Response: #vtb def r_q_send(self, msg_dict): no_pickle_keys = self.invalid_dict_pickle_keys(msg_dict) if no_pickle_keys == []: self.r_q.put(msg_dict) else: ...
#vtb def assert_not_equal(first, second, msg_fmt="{msg}"): if first == second: msg = "{!r} == {!r}".format(first, second) fail(msg_fmt.format(msg=msg, first=first, second=second))
Fail if first equals second, as determined by the '==' operator. >>> assert_not_equal(5, 8) >>> assert_not_equal(-7, -7.0) Traceback (most recent call last): ... AssertionError: -7 == -7.0 The following msg_fmt arguments are supported: * msg - the default error message * first - th...
### Input: Fail if first equals second, as determined by the '==' operator. >>> assert_not_equal(5, 8) >>> assert_not_equal(-7, -7.0) Traceback (most recent call last): ... AssertionError: -7 == -7.0 The following msg_fmt arguments are supported: * msg - the default error message ...
#vtb def guest_stop(self, userid, **kwargs): requestData = "PowerVM " + userid + " off" if in kwargs.keys() and kwargs[]: requestData += + str(kwargs[]) if in kwargs.keys() and kwargs[]: requestData += + str(kwargs[]) with zvmutils.log_and_reraise_s...
Power off VM.
### Input: Power off VM. ### Response: #vtb def guest_stop(self, userid, **kwargs): requestData = "PowerVM " + userid + " off" if in kwargs.keys() and kwargs[]: requestData += + str(kwargs[]) if in kwargs.keys() and kwargs[]: requestData += + str(kwargs[])...
#vtb def from_irc(self, irc_nickname=None, irc_password=None): if have_bottom: from .findall import IrcListener bot = IrcListener(irc_nickname=irc_nickname, irc_password=irc_password) results = bot.loop.run_until_complete(bot.collect_data(...
Connect to the IRC channel and find all servers presently connected. Slow; takes 30+ seconds but authoritative and current. OBSOLETE.
### Input: Connect to the IRC channel and find all servers presently connected. Slow; takes 30+ seconds but authoritative and current. OBSOLETE. ### Response: #vtb def from_irc(self, irc_nickname=None, irc_password=None): if have_bottom: from .findall import IrcL...
#vtb def register_frontend_media(request, media): if not hasattr(request, ): request._fluent_contents_frontend_media = Media() add_media(request._fluent_contents_frontend_media, media)
Add a :class:`~django.forms.Media` class to the current request. This will be rendered by the ``render_plugin_media`` template tag.
### Input: Add a :class:`~django.forms.Media` class to the current request. This will be rendered by the ``render_plugin_media`` template tag. ### Response: #vtb def register_frontend_media(request, media): if not hasattr(request, ): request._fluent_contents_frontend_media = Media() add_medi...
#vtb def _parse_call_args(self,*args,**kwargs): interp= kwargs.get(,self._useInterp) if len(args) == 5: raise IOError("Must specify phi for streamdf") elif len(args) == 6: if kwargs.get(,False): if isinstance(args[0],(int,float,numpy.float32,numpy...
Helper function to parse the arguments to the __call__ and related functions, return [6,nobj] array of frequencies (:3) and angles (3:)
### Input: Helper function to parse the arguments to the __call__ and related functions, return [6,nobj] array of frequencies (:3) and angles (3:) ### Response: #vtb def _parse_call_args(self,*args,**kwargs): interp= kwargs.get(,self._useInterp) if len(args) == 5: raise IO...
#vtb def change_node_subscriptions(self, jid, node, subscriptions_to_set): iq = aioxmpp.stanza.IQ( type_=aioxmpp.structs.IQType.SET, to=jid, payload=pubsub_xso.OwnerRequest( pubsub_xso.OwnerSubscriptions( node, ...
Update the subscriptions at a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the node to modify :type node: :class:`str` :param subscriptions_to_set: The subscriptions to set at the node. :type subscriptions_to_set: ...
### Input: Update the subscriptions at a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the node to modify :type node: :class:`str` :param subscriptions_to_set: The subscriptions to set at the node. :type subscripti...
#vtb def image_preprocessing(image_buffer, bbox, train, thread_id=0): if bbox is None: raise ValueError() image = decode_jpeg(image_buffer) height = FLAGS.image_size width = FLAGS.image_size if train: image = distort_image(image, height, width, bbox, thread_id) else: image = eval_image(imag...
Decode and preprocess one image for evaluation or training. Args: image_buffer: JPEG encoded string Tensor bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords] where each coordinate is [0, 1) and the coordinates are arranged as [ymin, xmin, ymax, xmax]. train: boolean ...
### Input: Decode and preprocess one image for evaluation or training. Args: image_buffer: JPEG encoded string Tensor bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords] where each coordinate is [0, 1) and the coordinates are arranged as [ymin, xmin, ymax, xmax]. train: ...
#vtb def __create_url_node_for_content(self, content, content_type, url=None, modification_time=None): loc = url if loc is None: loc = urljoin(self.url_site, self.context.get().format(**content.url_format)) lastmod = None if modification_time is not None: ...
Creates the required <url> node for the sitemap xml. :param content: the content class to handle :type content: pelican.contents.Content | None :param content_type: the type of the given content to match settings.EXTENDED_SITEMAP_PLUGIN :type content_type; str :param url; if give...
### Input: Creates the required <url> node for the sitemap xml. :param content: the content class to handle :type content: pelican.contents.Content | None :param content_type: the type of the given content to match settings.EXTENDED_SITEMAP_PLUGIN :type content_type; str :param ...
#vtb def _nextSequence(cls, name=None): if not name: name = cls._sqlSequence if not name: curs = cls.cursor() curs.execute("SELECT nextval()" % name) value = curs.fetchone()[0] curs.close() return value
Return a new sequence number for insertion in self._sqlTable. Note that if your sequences are not named tablename_primarykey_seq (ie. for table 'blapp' with primary key 'john_id', sequence name blapp_john_id_seq) you must give the full sequence name as an optional argument to _nextSe...
### Input: Return a new sequence number for insertion in self._sqlTable. Note that if your sequences are not named tablename_primarykey_seq (ie. for table 'blapp' with primary key 'john_id', sequence name blapp_john_id_seq) you must give the full sequence name as an optional argumen...
#vtb def from_time( year=None, month=None, day=None, hours=None, minutes=None, seconds=None, microseconds=None, timezone=None ): def str_or_stars(i, length): if i is None: return "*" * length else: return str(i).rjust(length, "0") wmi_time = "" wmi_time += ...
Convenience wrapper to take a series of date/time elements and return a WMI time of the form `yyyymmddHHMMSS.mmmmmm+UUU`. All elements may be int, string or omitted altogether. If omitted, they will be replaced in the output string by a series of stars of the appropriate length. :param year: The year el...
### Input: Convenience wrapper to take a series of date/time elements and return a WMI time of the form `yyyymmddHHMMSS.mmmmmm+UUU`. All elements may be int, string or omitted altogether. If omitted, they will be replaced in the output string by a series of stars of the appropriate length. :param year:...
#vtb def normalizeGlyphHeight(value): if not isinstance(value, (int, float)): raise TypeError("Glyph height must be an :ref:`type-int-float`, not " "%s." % type(value).__name__) return value
Normalizes glyph height. * **value** must be a :ref:`type-int-float`. * Returned value is the same type as the input value.
### Input: Normalizes glyph height. * **value** must be a :ref:`type-int-float`. * Returned value is the same type as the input value. ### Response: #vtb def normalizeGlyphHeight(value): if not isinstance(value, (int, float)): raise TypeError("Glyph height must be an :ref:`type-int-float`, n...
#vtb def input(self, input, song): try: cmd = getattr(self, self.CMD_MAP[input][1]) except (IndexError, KeyError): return self.screen.print_error( "Invalid command {!r}!".format(input)) cmd(song)
Input callback, handles key presses
### Input: Input callback, handles key presses ### Response: #vtb def input(self, input, song): try: cmd = getattr(self, self.CMD_MAP[input][1]) except (IndexError, KeyError): return self.screen.print_error( "Invalid command {!r}!".format(input)) ...
#vtb def run_process(self, slug, inputs): def export_files(value): if isinstance(value, str) and os.path.isfile(value): print("export {}".format(value)) elif isinstance(value, dict): for item in value...
Run a new process from a running process.
### Input: Run a new process from a running process. ### Response: #vtb def run_process(self, slug, inputs): def export_files(value): if isinstance(value, str) and os.path.isfile(value): print("export {}".format(value)) ...
#vtb def run_pipes(executable, input_path, output_path, more_args=None, properties=None, force_pydoop_submitter=False, hadoop_conf_dir=None, logger=None, keep_streams=False): if logger is None: logger = utils.NullLogger() if not hdfs.path.exists(executable): rais...
Run a pipes command. ``more_args`` (after setting input/output path) and ``properties`` are passed to :func:`run_cmd`. If not specified otherwise, this function sets the properties ``mapreduce.pipes.isjavarecordreader`` and ``mapreduce.pipes.isjavarecordwriter`` to ``"true"``. This function w...
### Input: Run a pipes command. ``more_args`` (after setting input/output path) and ``properties`` are passed to :func:`run_cmd`. If not specified otherwise, this function sets the properties ``mapreduce.pipes.isjavarecordreader`` and ``mapreduce.pipes.isjavarecordwriter`` to ``"true"``. Thi...
#vtb def get_lldp_neighbor_detail_output_lldp_neighbor_detail_lldp_pdu_received(self, **kwargs): config = ET.Element("config") get_lldp_neighbor_detail = ET.Element("get_lldp_neighbor_detail") config = get_lldp_neighbor_detail output = ET.SubElement(get_lldp_neighbor_detail, "ou...
Auto Generated Code
### Input: Auto Generated Code ### Response: #vtb def get_lldp_neighbor_detail_output_lldp_neighbor_detail_lldp_pdu_received(self, **kwargs): config = ET.Element("config") get_lldp_neighbor_detail = ET.Element("get_lldp_neighbor_detail") config = get_lldp_neighbor_detail outpu...
#vtb def get_schedule(self, ehr_username, start_date, changed_since, include_pix, other_user=, end_date=, appointment_types=None, status_filter=): if not start_date: raise ValueError() if end_date: start_date...
invokes TouchWorksMagicConstants.ACTION_GET_SCHEDULE action :return: JSON response
### Input: invokes TouchWorksMagicConstants.ACTION_GET_SCHEDULE action :return: JSON response ### Response: #vtb def get_schedule(self, ehr_username, start_date, changed_since, include_pix, other_user=, end_date=, appointment_types=None, status_fi...
#vtb def get_last_modified_datetime(dir_path=os.path.dirname(__file__)): max_mtime = 0 for root, dirs, files in os.walk(dir_path): for f in files: p = os.path.join(root, f) try: max_mtime = max(max_mtime, os.stat(p).st_mtime) except FileNotFoundEr...
Return datetime object of latest change in kerncraft module directory.
### Input: Return datetime object of latest change in kerncraft module directory. ### Response: #vtb def get_last_modified_datetime(dir_path=os.path.dirname(__file__)): max_mtime = 0 for root, dirs, files in os.walk(dir_path): for f in files: p = os.path.join(root, f) try:...
#vtb def data_cifar10(train_start=0, train_end=50000, test_start=0, test_end=10000): img_rows = 32 img_cols = 32 nb_classes = 10 (x_train, y_train), (x_test, y_test) = cifar10.load_data() if tf.keras.backend.image_data_format() == : x_train = x_train.reshape(x_train.shape[0], 3, img_rows, img...
Preprocess CIFAR10 dataset :return:
### Input: Preprocess CIFAR10 dataset :return: ### Response: #vtb def data_cifar10(train_start=0, train_end=50000, test_start=0, test_end=10000): img_rows = 32 img_cols = 32 nb_classes = 10 (x_train, y_train), (x_test, y_test) = cifar10.load_data() if tf.keras.backend.image_data_format() == :...
#vtb def to_size(value, convert_to_human=True): value = from_size(value) if value is None: value = if isinstance(value, Number) and value > 1024 and convert_to_human: v_power = int(math.floor(math.log(value, 1024))) v_multiplier = math.pow(1024, v_power) ...
Convert python int (bytes) to zfs size NOTE: http://src.illumos.org/source/xref/illumos-gate/usr/src/lib/pyzfs/common/util.py#114
### Input: Convert python int (bytes) to zfs size NOTE: http://src.illumos.org/source/xref/illumos-gate/usr/src/lib/pyzfs/common/util.py#114 ### Response: #vtb def to_size(value, convert_to_human=True): value = from_size(value) if value is None: value = if isinstance(value, Number) and...
#vtb def address_to_scripthash(address: str) -> UInt160: AddressVersion = 23 data = b58decode(address) if len(data) != 25: raise ValueError() if data[0] != AddressVersion: raise ValueError() checksum_data = data[:21] checksum = hashlib.sha256(hashlib.sha256(checksum_data)...
Just a helper method
### Input: Just a helper method ### Response: #vtb def address_to_scripthash(address: str) -> UInt160: AddressVersion = 23 data = b58decode(address) if len(data) != 25: raise ValueError() if data[0] != AddressVersion: raise ValueError() checksum_data = data[:21] checksu...
#vtb def remove_cable_distributor(self, cable_dist): if cable_dist in self.cable_distributors() and isinstance(cable_dist, MVCableDistributorDing0): self._cable_distributors.remove(cable_dist) if self...
Removes a cable distributor from _cable_distributors if existing
### Input: Removes a cable distributor from _cable_distributors if existing ### Response: #vtb def remove_cable_distributor(self, cable_dist): if cable_dist in self.cable_distributors() and isinstance(cable_dist, MVCableDistributorDing...
#vtb def kappa_statistic(self): r if self.population() == 0: return float() random_accuracy = ( (self._tn + self._fp) * (self._tn + self._fn) + (self._fn + self._tp) * (self._fp + self._tp) ) / self.population() ** 2 return (self.accuracy() - r...
r"""Return κ statistic. The κ statistic is defined as: :math:`\kappa = \frac{accuracy - random~ accuracy} {1 - random~ accuracy}` The κ statistic compares the performance of the classifier relative to the performance of a random classifier. :math:`\kappa` = 0 indicates ...
### Input: r"""Return κ statistic. The κ statistic is defined as: :math:`\kappa = \frac{accuracy - random~ accuracy} {1 - random~ accuracy}` The κ statistic compares the performance of the classifier relative to the performance of a random classifier. :math:`\kappa` = 0 indica...
#vtb def percentile(values, percent): N = sorted(values) if not N: return None k = (len(N) - 1) * percent f = int(math.floor(k)) c = int(math.ceil(k)) if f == c: return N[int(k)] d0 = N[f] * (c - k) d1 = N[c] * (k - f) return d0 + d1
PERCENTILE WITH INTERPOLATION RETURN VALUE AT, OR ABOVE, percentile OF THE VALUES snagged from http://code.activestate.com/recipes/511478-finding-the-percentile-of-the-values/
### Input: PERCENTILE WITH INTERPOLATION RETURN VALUE AT, OR ABOVE, percentile OF THE VALUES snagged from http://code.activestate.com/recipes/511478-finding-the-percentile-of-the-values/ ### Response: #vtb def percentile(values, percent): N = sorted(values) if not N: return None k = ...
#vtb def get_comments_content_object(parser, token): keywords = token.contents.split() if len(keywords) != 5: raise template.TemplateSyntaxError( " tag takes exactly 2 arguments" % (keywords[0],)) if keywords[1] != : raise template.TemplateSyntaxError( "first arg...
Get a limited set of comments for a given object. Defaults to a limit of 5. Setting the limit to -1 disables limiting. usage: {% get_comments_content_object for form_object as variable_name %}
### Input: Get a limited set of comments for a given object. Defaults to a limit of 5. Setting the limit to -1 disables limiting. usage: {% get_comments_content_object for form_object as variable_name %} ### Response: #vtb def get_comments_content_object(parser, token): keywords = token.con...
#vtb def get_open_orders(self, market=None): return self._api_query(path_dict={ API_V1_1: , API_V2_0: }, options={: market, : market} if market else None, protection=PROTECTION_PRV)
Get all orders that you currently have opened. A specific market can be requested. Endpoint: 1.1 /market/getopenorders 2.0 /key/market/getopenorders :param market: String literal for the market (ie. BTC-LTC) :type market: str :return: Open orders info in JSON ...
### Input: Get all orders that you currently have opened. A specific market can be requested. Endpoint: 1.1 /market/getopenorders 2.0 /key/market/getopenorders :param market: String literal for the market (ie. BTC-LTC) :type market: str :return: Open orders inf...
#vtb def create_markdown_cell(block): kwargs = {: block[], : block[]} markdown_cell = nbbase.new_markdown_cell(**kwargs) return markdown_cell
Create a markdown cell from a block.
### Input: Create a markdown cell from a block. ### Response: #vtb def create_markdown_cell(block): kwargs = {: block[], : block[]} markdown_cell = nbbase.new_markdown_cell(**kwargs) return markdown_cell
#vtb def clusterQueues(self): servers = yield self.getClusterServers() queues = {} for sname in servers: qs = yield self.get( % sname) uuid = yield self.get( % sname) qs = json.loads(qs) for q in qs: if q not in ...
Return a dict of queues in cluster and servers running them
### Input: Return a dict of queues in cluster and servers running them ### Response: #vtb def clusterQueues(self): servers = yield self.getClusterServers() queues = {} for sname in servers: qs = yield self.get( % sname) uuid = yield self.get( % sname) ...
#vtb def parse_from_array(arr): syn_set = SynonymSet() for synonyms in arr: _set = set() for synonym in synonyms: _set.add(synonym) syn_set.add_set(_set) return syn_set
Parse 2d array into synonym set Every array inside arr is considered a set of synonyms
### Input: Parse 2d array into synonym set Every array inside arr is considered a set of synonyms ### Response: #vtb def parse_from_array(arr): syn_set = SynonymSet() for synonyms in arr: _set = set() for synonym in synonyms: _set.add(synonym) syn_set.add_set(_s...
#vtb def fetch_all_messages(self, conn, directory, readonly): conn.select(directory, readonly) message_data = [] typ, data = conn.search(None, ) for num in data[0].split(): typ, data = conn.fetch(num, ) for response_part in data: ...
Fetches all messages at @conn from @directory. Params: conn IMAP4_SSL connection directory The IMAP directory to look for readonly readonly mode, true or false Returns: List of subject-body tuples
### Input: Fetches all messages at @conn from @directory. Params: conn IMAP4_SSL connection directory The IMAP directory to look for readonly readonly mode, true or false Returns: List of subject-body tuples ### Respon...
#vtb def save_files(self, nodes): metrics = {"Opened": 0, "Cached": 0} for node in nodes: file = node.file if self.__container.get_editor(file): if self.__container.save_file(file): metrics["Opened"] += 1 self.__un...
Saves user defined files using give nodes. :param nodes: Nodes. :type nodes: list :return: Method success. :rtype: bool
### Input: Saves user defined files using give nodes. :param nodes: Nodes. :type nodes: list :return: Method success. :rtype: bool ### Response: #vtb def save_files(self, nodes): metrics = {"Opened": 0, "Cached": 0} for node in nodes: file = node....
#vtb def ext_pillar(minion_id, pillar, **kwargs): filter_out_source_path_option(kwargs) set_inventory_base_uri_default(__opts__, kwargs) return reclass_ext_pillar(minion_id, pillar, **kwargs) except TypeError as e: ...
Obtain the Pillar data from **reclass** for the given ``minion_id``.
### Input: Obtain the Pillar data from **reclass** for the given ``minion_id``. ### Response: #vtb def ext_pillar(minion_id, pillar, **kwargs): filter_out_source_path_option(kwargs) set_inventory_base_uri_default(__opts__, kwargs) ...
#vtb def namedbuffer(buffer_name, fields_spec): if not len(buffer_name): raise ValueError() if not len(fields_spec): raise ValueError() fields = [ field for field in fields_spec if not isinstance(field, Pad) ] if any(field.size_bytes < 0 for fi...
Class factory, returns a class to wrap a buffer instance and expose the data as fields. The field spec specifies how many bytes should be used for a field and what is the encoding / decoding function.
### Input: Class factory, returns a class to wrap a buffer instance and expose the data as fields. The field spec specifies how many bytes should be used for a field and what is the encoding / decoding function. ### Response: #vtb def namedbuffer(buffer_name, fields_spec): if not len(buf...
#vtb def input_yn(conf_mess): ui_erase_ln() ui_print(conf_mess) with term.cbreak(): input_flush() val = input_by_key() return bool(val.lower() == )
Print Confirmation Message and Get Y/N response from user.
### Input: Print Confirmation Message and Get Y/N response from user. ### Response: #vtb def input_yn(conf_mess): ui_erase_ln() ui_print(conf_mess) with term.cbreak(): input_flush() val = input_by_key() return bool(val.lower() == )
#vtb def get_domain(self): if self.domain is None: return np.array([self.points.min(axis=0), self.points.max(axis=0)]) return self.domain
:returns: opposite vertices of the bounding prism for this object. :rtype: ndarray([min], [max])
### Input: :returns: opposite vertices of the bounding prism for this object. :rtype: ndarray([min], [max]) ### Response: #vtb def get_domain(self): if self.domain is None: return np.array([self.points.min(axis=0), self.points.max(a...
#vtb def check_query(state, query, error_msg=None, expand_msg=None): if error_msg is None: error_msg = "Running `{{query}}` after your submission generated an error." if expand_msg is None: expand_msg = "The autograder verified the result of running `{{query}}` against the database. " ...
Run arbitrary queries against to the DB connection to verify the database state. For queries that do not return any output (INSERTs, UPDATEs, ...), you cannot use functions like ``check_col()`` and ``is_equal()`` to verify the query result. ``check_query()`` will rerun the solution query in the transactio...
### Input: Run arbitrary queries against to the DB connection to verify the database state. For queries that do not return any output (INSERTs, UPDATEs, ...), you cannot use functions like ``check_col()`` and ``is_equal()`` to verify the query result. ``check_query()`` will rerun the solution query in th...
#vtb def fixed_string(self, data=None): old = self.fixed if data != None: new = self._decode_input_string(data) if len(new) <= 16: self.fixed = new else: raise yubico_exception.InputError() return old
The fixed string is used to identify a particular Yubikey device. The fixed string is referred to as the 'Token Identifier' in OATH-HOTP mode. The length of the fixed string can be set between 0 and 16 bytes. Tip: This can also be used to extend the length of a static password.
### Input: The fixed string is used to identify a particular Yubikey device. The fixed string is referred to as the 'Token Identifier' in OATH-HOTP mode. The length of the fixed string can be set between 0 and 16 bytes. Tip: This can also be used to extend the length of a static password. ##...
#vtb def path_regex(self): try: path = % urljoin(self.monthly_build_list_regex, self.builds[self.build_index]) if self.application in APPLICATIONS_MULTI_LOCALE \ and self.locale != : path = % urljoin(path, ...
Return the regex for the path to the build folder.
### Input: Return the regex for the path to the build folder. ### Response: #vtb def path_regex(self): try: path = % urljoin(self.monthly_build_list_regex, self.builds[self.build_index]) if self.application in APPLICATIONS_MULTI_LOCALE \ ...
#vtb def get_F_y(fname=, y=[]): f = open(fname,) data = json.load(f) f.close() occurr = [] for cell_type in y: occurr += [data[][cell_type][]] return list(np.array(occurr)/np.sum(occurr))
Extract frequency of occurrences of those cell types that are modeled. The data set contains cell types that are not modeled (TCs etc.) The returned percentages are renormalized onto modeled cell-types, i.e. they sum up to 1
### Input: Extract frequency of occurrences of those cell types that are modeled. The data set contains cell types that are not modeled (TCs etc.) The returned percentages are renormalized onto modeled cell-types, i.e. they sum up to 1 ### Response: #vtb def get_F_y(fname=, y=[]): f = open(fnam...
#vtb def open_package(locals=None, dr=None): if locals is None: locals = caller_locals() try: return op(locals[]) except KeyError: package_name = None build_package_dir = None source_package = None if dr is None: dr = g...
Try to open a package with the metatab_doc variable, which is set when a Notebook is run as a resource. If that does not exist, try the local _packages directory
### Input: Try to open a package with the metatab_doc variable, which is set when a Notebook is run as a resource. If that does not exist, try the local _packages directory ### Response: #vtb def open_package(locals=None, dr=None): if locals is None: locals = caller_locals() try: ...
#vtb def custom_callback(self, view_func): @wraps(view_func) def decorated(*args, **kwargs): plainreturn, data = self._process_callback() if plainreturn: return data else: return view_func(data, *args, **kwargs) self._c...
Wrapper function to use a custom callback. The custom OIDC callback will get the custom state field passed in with redirect_to_auth_server.
### Input: Wrapper function to use a custom callback. The custom OIDC callback will get the custom state field passed in with redirect_to_auth_server. ### Response: #vtb def custom_callback(self, view_func): @wraps(view_func) def decorated(*args, **kwargs): plainre...
#vtb def save_data_files(vr, bs, prefix=None, directory=None): filename = .format(prefix) if prefix else directory = directory if directory else filename = os.path.join(directory, filename) if bs.is_metal(): zero = vr.efermi else: zero = bs.get_vbm()[] with open(filename...
Write the band structure data files to disk. Args: vs (`Vasprun`): Pymatgen `Vasprun` object. bs (`BandStructureSymmLine`): Calculated band structure. prefix (`str`, optional): Prefix for data file. directory (`str`, optional): Directory in which to save the data. Returns: ...
### Input: Write the band structure data files to disk. Args: vs (`Vasprun`): Pymatgen `Vasprun` object. bs (`BandStructureSymmLine`): Calculated band structure. prefix (`str`, optional): Prefix for data file. directory (`str`, optional): Directory in which to save the data. R...
#vtb def plot_rebit_prior(prior, rebit_axes=REBIT_AXES, n_samples=2000, true_state=None, true_size=250, force_mean=None, legend=True, mean_color_index=2 ): pallette = plt.rcParams[] plot_rebit_modelparams(prior.sample(n_samples), c=pallette[0], label=, ...
Plots rebit states drawn from a given prior. :param qinfer.tomography.DensityOperatorDistribution prior: Distribution over rebit states to plot. :param list rebit_axes: List containing indices for the :math:`x` and :math:`z` axes. :param int n_samples: Number of samples to draw from the ...
### Input: Plots rebit states drawn from a given prior. :param qinfer.tomography.DensityOperatorDistribution prior: Distribution over rebit states to plot. :param list rebit_axes: List containing indices for the :math:`x` and :math:`z` axes. :param int n_samples: Number of samples to draw ...
#vtb def nearest_overlap(self, overlap, bins): bins_overlap = overlap * bins if bins_overlap % 2 != 0: bins_overlap = math.ceil(bins_overlap / 2) * 2 overlap = bins_overlap / bins logger.warning( .format(overlap)) return ove...
Return nearest overlap/crop factor based on number of bins
### Input: Return nearest overlap/crop factor based on number of bins ### Response: #vtb def nearest_overlap(self, overlap, bins): bins_overlap = overlap * bins if bins_overlap % 2 != 0: bins_overlap = math.ceil(bins_overlap / 2) * 2 overlap = bins_overlap / bins ...
#vtb def ft2file(self, **kwargs): kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) kwargs_copy[] = kwargs.get( , self.dataset(**kwargs)) self._replace_none(kwargs_copy) localpath = NameFactory.ft2file_format.format(**kwargs_copy) ...
return the name of the input ft2 file list
### Input: return the name of the input ft2 file list ### Response: #vtb def ft2file(self, **kwargs): kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) kwargs_copy[] = kwargs.get( , self.dataset(**kwargs)) self._replace_none(kwargs_copy) ...
#vtb def _get_parseable_methods(cls): _LOG.debug("Retrieving parseable methods for ", cls.__name__) init_parser = None methods_to_parse = {} for name, obj in vars(cls).items(): if name == "__init__": init_parse...
Return all methods of cls that are parseable i.e. have been decorated by '@create_parser'. Args: cls: the class currently being decorated Note: classmethods will not be included as they can only be referenced once the class has been defined Returns: a 2-tuple with the p...
### Input: Return all methods of cls that are parseable i.e. have been decorated by '@create_parser'. Args: cls: the class currently being decorated Note: classmethods will not be included as they can only be referenced once the class has been defined Returns: a 2-tupl...
#vtb def p_namespace(self, p): if p[1] == : doc = None if len(p) > 4: doc = p[5] p[0] = AstNamespace( self.path, p.lineno(1), p.lexpos(1), p[2], doc) else: raise ValueError()
namespace : KEYWORD ID NL | KEYWORD ID NL INDENT docsection DEDENT
### Input: namespace : KEYWORD ID NL | KEYWORD ID NL INDENT docsection DEDENT ### Response: #vtb def p_namespace(self, p): if p[1] == : doc = None if len(p) > 4: doc = p[5] p[0] = AstNamespace( self.path, p.linen...
#vtb def write_block_data(self, address, register, value): return self.smbus.write_block_data(address, register, value)
SMBus Block Write: i2c_smbus_write_block_data() ================================================ The opposite of the Block Read command, this writes up to 32 bytes to a device, to a designated register that is specified through the Comm byte. The amount of data is specified in the Coun...
### Input: SMBus Block Write: i2c_smbus_write_block_data() ================================================ The opposite of the Block Read command, this writes up to 32 bytes to a device, to a designated register that is specified through the Comm byte. The amount of data is specified...
#vtb def generate(self): part = creator.Particle( [random.uniform(-1, 1) for _ in range(len(self._params[]))]) part.speed = [ random.uniform(-self._params[], self._params[]) for _ in range(len(self._params[]))] ...
Generates a particle using the creator function. Notes ----- Position and speed are uniformly randomly seeded within allowed bounds. The particle also has speed limit settings taken from global values. Returns ------- particle object
### Input: Generates a particle using the creator function. Notes ----- Position and speed are uniformly randomly seeded within allowed bounds. The particle also has speed limit settings taken from global values. Returns ------- particle object ### Respo...
#vtb def _recurse(data, obj): content = _ContentManager() for child in obj.get_children(): if isinstance(child, mpl.spines.Spine): continue if isinstance(child, mpl.axes.Axes): ax = axes.Axes(data, child) if ax.is_colorbar: ...
Iterates over all children of the current object, gathers the contents contributing to the resulting PGFPlots file, and returns those.
### Input: Iterates over all children of the current object, gathers the contents contributing to the resulting PGFPlots file, and returns those. ### Response: #vtb def _recurse(data, obj): content = _ContentManager() for child in obj.get_children(): if isinstance(child, mpl...
#vtb def is_in_range(self, values, unit=None, raise_exception=True): self._is_numeric(values) if unit is None or unit == self.units[0]: minimum = self.min maximum = self.max else: namespace = {: self} self.is_unit_acceptable(unit, True) ...
Check if a list of values is within physically/mathematically possible range. Args: values: A list of values. unit: The unit of the values. If not specified, the default metric unit will be assumed. raise_exception: Set to True to raise an exception if not i...
### Input: Check if a list of values is within physically/mathematically possible range. Args: values: A list of values. unit: The unit of the values. If not specified, the default metric unit will be assumed. raise_exception: Set to True to raise an except...
#vtb def user( state, host, name, present=True, home=None, shell=None, group=None, groups=None, public_keys=None, delete_keys=False, ensure_home=True, system=False, uid=None, ): users = host.fact.users or {} user = users.get(name) if groups is None: groups = [] if home is...
Add/remove/update system users & their ssh `authorized_keys`. + name: name of the user to ensure + present: whether this user should exist + home: the users home directory + shell: the users shell + group: the users primary group + groups: the users secondary groups + public_keys: list of p...
### Input: Add/remove/update system users & their ssh `authorized_keys`. + name: name of the user to ensure + present: whether this user should exist + home: the users home directory + shell: the users shell + group: the users primary group + groups: the users secondary groups + public_key...
#vtb def factory(cls, registry): cls_name = str(cls.__name__) MyMetricsHandler = type(cls_name, (cls, object), {"registry": registry}) return MyMetricsHandler
Returns a dynamic MetricsHandler class tied to the passed registry.
### Input: Returns a dynamic MetricsHandler class tied to the passed registry. ### Response: #vtb def factory(cls, registry): cls_name = str(cls.__name__) MyMetricsHandler = type(cls_name, (cls, object), {"registr...
#vtb def _reorderForPreference(themeList, preferredThemeName): for theme in themeList: if preferredThemeName == theme.themeName: themeList.remove(theme) themeList.insert(0, theme) return
Re-order the input themeList according to the preferred theme. Returns None.
### Input: Re-order the input themeList according to the preferred theme. Returns None. ### Response: #vtb def _reorderForPreference(themeList, preferredThemeName): for theme in themeList: if preferredThemeName == theme.themeName: themeList.remove(theme) themeList.insert(...
#vtb def page_sequence(n_sheets: int, one_based: bool = True) -> List[int]: n_pages = calc_n_virtual_pages(n_sheets) assert n_pages % 4 == 0 half_n_pages = n_pages // 2 firsthalf = list(range(half_n_pages)) secondhalf = list(reversed(range(half_n_pages, n_pages))) s...
Generates the final page sequence from the starting number of sheets.
### Input: Generates the final page sequence from the starting number of sheets. ### Response: #vtb def page_sequence(n_sheets: int, one_based: bool = True) -> List[int]: n_pages = calc_n_virtual_pages(n_sheets) assert n_pages % 4 == 0 half_n_pages = n_pages // 2 firsthalf = list(range(half_n_pag...