Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
354,800
def _gamma_factorial(self, expr, n): r if n == 0: return 1 return product([expr+i for i in range(n)])
r""" Compute :math:`\frac {(\alpha)_m = (\alpha + m - 1)!}{(\alpha - 1)!}` See Eq. 3 in Gamma moment closure Lakatos 2014 unpublished :param expr: a symbolic expression :type expr: :param n: :type n: `int` :return: a symbolic expression
354,801
def get_options_for_id(options: Dict[str, Dict[str, Any]], identifier: str): check_var(options, var_types=dict, var_name=) res = options[identifier] if identifier in options.keys() else dict() check_var(res, var_types=dict, var_name= + identifier + ) return res
Helper method, from the full options dict of dicts, to return either the options related to this parser or an empty dictionary. It also performs all the var type checks :param options: :param identifier: :return:
354,802
def from_cwl(cls, data, __reference__=None): class_name = data.get(, None) cls = cls.registry.get(class_name, cls) if __reference__: with with_reference(__reference__): self = cls( **{k: v for k, v in iteritems(data...
Return an instance from CWL data.
354,803
def accumulate(self, axis: AxisIdentifier) -> HistogramBase: new_one = self.copy() axis_id = self._get_axis(axis) new_one._frequencies = np.cumsum(new_one.frequencies, axis_id[0]) return new_one
Calculate cumulative frequencies along a certain axis. Returns ------- new_hist: Histogram of the same type & size
354,804
def move(self, x, y): self._cursor = self._normalizePoint(x, y)
Move the virtual cursor. Args: x (int): x-coordinate to place the cursor. y (int): y-coordinate to place the cursor. .. seealso:: :any:`get_cursor`, :any:`print_str`, :any:`write`
354,805
def setDefaults(configObj={}): paramDict = { : 7, : 1, : 0, : 5, : , : , : 0, : } if len(configObj) > 0: for key in configObj: ...
Return a dictionary of the default parameters which also been updated with the user overrides.
354,806
def as_doc(self): doc = SON([("$ref", self.collection), ("$id", self.id)]) if self.database is not None: doc["$db"] = self.database doc.update(self.__kwargs) return doc
Get the SON document representation of this DBRef. Generally not needed by application developers
354,807
def get_subpackages(name): splist = [] for dirpath, _dirnames, _filenames in os.walk(name): if osp.isfile(osp.join(dirpath, )): splist.append(".".join(dirpath.split(os.sep))) return splist
Return subpackages of package *name*
354,808
def merge_user_commits(cls, commits): user = None for commit in commits: if not user: user = commit else: if commit.committer_time > user.committer_time: commit.line_count += user.line_count user = c...
Merge all the commits for the user. Aggregate line counts, and use the most recent commit (by date/time) as the representative commit for the user.
354,809
def imsave(filename, data, maxval=None, pam=False): try: netpbm = NetpbmFile(data, maxval=maxval) netpbm.write(filename, pam=pam) finally: netpbm.close()
Write image data to Netpbm file. Examples -------- >>> image = numpy.array([[0, 1],[65534, 65535]], dtype=numpy.uint16) >>> imsave('_tmp.pgm', image)
354,810
def _extract_proxies(self, ajax_endpoint): proxy_xml = requests.get(ajax_endpoint) print(proxy_xml.content) root = etree.XML(proxy_xml.content) quote = root.xpath()[0] raw_text = quote.text t need You will definitely love it! Give ...
request the xml object
354,811
def _zforce(self,R,z,phi=0.,t=0.): l,n = bovy_coords.Rz_to_lambdanu (R,z,ac=self._ac,Delta=self._Delta) jac = bovy_coords.Rz_to_lambdanu_jac(R,z, Delta=self._Delta) dldz = jac[0,1] dndz = jac[1,1] return - (dldz * self._lderiv(l,n) + \ dnd...
NAME: _zforce PURPOSE: evaluate the vertical force for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: the vertical force HISTORY: ...
354,812
def unpack(self, obs): planes = getattr(obs.feature_layer_data, self.layer_set) plane = getattr(planes, self.name) return self.unpack_layer(plane)
Return a correctly shaped numpy array for this feature.
354,813
def customize(self, customize): for k, v in list(customize.items()): if k in TABLE_R: continue op = k[ :k.rfind() ] if k.startswith(): TABLE_R[k] = (, 0, (1, -1, , 100)) elif self.version >= 3.6 and k.star...
Special handling for opcodes, such as those that take a variable number of arguments -- we add a new entry for each in TABLE_R.
354,814
def is_(self, value): newq = self.copy() newq.setOp(Query.Op.Is) newq.setValue(value) return newq
Sets the operator type to Query.Op.Is and sets the value to the inputted value. :param value <variant> :return <Query> :sa __eq__ :usage |>>> from orb import Query as Q |>>> query = Q('test').is_(...
354,815
def _read(self, ti, try_number, metadata=None): log_relative_path = self._render_filename(ti, try_number) remote_loc = os.path.join(self.remote_base, log_relative_path) if self.wasb_log_exists(remote_loc): re...
Read logs of given task instance and try_number from Wasb remote storage. If failed, read the log from task instance host machine. :param ti: task instance object :param try_number: task instance try_number to read logs from :param metadata: log metadata, can be ...
354,816
def rpc_get_account_balance(self, address, token_type, **con_info): if not check_account_address(address): return {: , : 400} if not check_token_type(token_type): return {: , : 400} if is_c32_address(address): address = c32ToB58(address) ...
Get the balance of an address for a particular token type Returns the value on success Returns 0 if the balance is 0, or if there is no address
354,817
def handle_friday(next_date: Datum, period: str, mult: int, start_date: Datum): assert isinstance(next_date, Datum) assert isinstance(start_date, Datum) tmp_sat = next_date.clone() tmp_sat.add_days(1) tmp_sun = next_date.clone() tmp_sun.add_days(2) if period == RecurrencePeriod....
Extracted the calculation for when the next_day is Friday
354,818
def get_existing_pipelines(self): url = "{0}/applications/{1}/pipelineConfigs".format(API_URL, self.app_name) resp = requests.get(url, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT) assert resp.ok, .format(self.app_name, resp.text) return resp.json()
Get existing pipeline configs for specific application. Returns: str: Pipeline config json
354,819
def accel_next(self, *args): if self.get_notebook().get_current_page() + 1 == self.get_notebook().get_n_pages(): self.get_notebook().set_current_page(0) else: self.get_notebook().next_page() return True
Callback to go to the next tab. Called by the accel key.
354,820
def _installed_packages(self) -> Generator[str, None, None]: with (self._build_dir / ).open() as f: packages = json.load(f) yield from packages[].keys()
Extract installed packages as list from `package.json`.
354,821
def handle(dispatcher, *accept_args, **accept_kwargs): def bind_function_later(f): bind_function(f, dispatcher, *accept_args, **accept_kwargs) return f return bind_function_later
:param dispatcher: dispatcher to recieve events from :param accept_args: args to match on :param accept_kwargs: kwargs to match on Creates an MNDFunction instance which containing the argspec and adds the function to the dispatcher.
354,822
def main(): parser = argparse.ArgumentParser( description=) parser.add_argument(, nargs=, help=) parser.add_argument(, , help= , default=sys.stdout) parser.add_argument(, , help= ...
Parses the command-line args, and calls run.
354,823
def _pack_image(filename, max_size, form_field=, f=None): if f is None: try: if os.path.getsize(filename) > (max_size * 1024): raise TweepError( % max_size) except os.error as e: raise TweepError( % e.strerror) ...
Pack image from file into multipart-formdata post body
354,824
def do_global_lock(self, args): if args.purge: self.task_master.registry.force_clear_lock() else: owner = self.task_master.registry.read_lock() if owner: heartbeat = self.task_master.get_heartbeat(owner) if in heartbeat: ...
read (or clear) the global lock
354,825
def daterange(start, stop, step=1, inclusive=False): if not isinstance(start, date): raise TypeError("start expected datetime.date instance") if stop and not isinstance(stop, date): raise TypeError("stop expected datetime.date instance or None") try: y_step, m_step, d_step = ste...
In the spirit of :func:`range` and :func:`xrange`, the `daterange` generator that yields a sequence of :class:`~datetime.date` objects, starting at *start*, incrementing by *step*, until *stop* is reached. When *inclusive* is True, the final date may be *stop*, **if** *step* falls evenly on it. By ...
354,826
def get_consistent_set_and_saxis(magmoms, saxis=None): magmoms = [Magmom(magmom) for magmom in magmoms] if saxis is None: saxis = Magmom.get_suggested_saxis(magmoms) else: saxis = saxis/np.linalg.norm(saxis) magmoms = [magmom.get_moment(saxis=saxis) for m...
Method to ensure a list of magmoms use the same spin axis. Returns a tuple of a list of Magmoms and their global spin axis. :param magmoms: list of magmoms (Magmoms, scalars or vectors) :param saxis: can provide a specific global spin axis :return: (list of Magmoms, global spin axis) tu...
354,827
def html(self) -> str: if self._inner_element: return self.start_tag + self._inner_element.html + self.end_tag return super().html
Get whole html representation of this node.
354,828
def to_dict(self): return { : self.id, : str(self.type.ver_type), : canon_ref(self.did, self.controller), **self.type.specification(self.value) }
Return dict representation of public key to embed in DID document.
354,829
def host_diskpool_get_info(self, disk_pool=None): if disk_pool is None: disk_pool = CONF.zvm.disk_pool if not in disk_pool: msg = ( ) LOG.error(msg) raise exception.SDKInvalidInputFormat(msg) ...
Retrieve diskpool information. :param str disk_pool: the disk pool info. It use ':' to separate disk pool type and pool name, eg "ECKD:eckdpool" or "FBA:fbapool" :returns: Dictionary describing disk pool usage info
354,830
def sync_counts(**kwargs): badges = kwargs.get() excluded = kwargs.get() instances = registry.get_recipe_instances(badges=badges, excluded=excluded) updated_badges, unchanged_badges = [], [] for instance in instances: reset_queries() badge, updated = instance.update_badge_user...
Iterates over registered recipes and denormalizes ``Badge.users.count()`` into ``Badge.users_count`` field.
354,831
def discover():
Automatically discover the paths to various data folders in this project and compose a Project instance. Returns: A constructed Project object. Raises: ValueError: if the paths could not be figured out automatically. In this case, you have to create a Pr...
354,832
def cropcenter(sz, img=None): l = len(sz) sz = np.array(sz) def wrapped(im): imsz = np.array(im.shape) s = (imsz[:l] - sz) / 2 to = s + sz slices = [slice(s, e) for s, e in zip(s, to)] return im[slices] if img is not None: return wrap...
if no img, then return crop function :param sz: :param img: :return:
354,833
def add_bool_option(self, *args, **kwargs): dest = [o for o in args if o.startswith("--")][0].replace("--", "").replace("-", "_") self.parser.add_option(dest=dest, action="store_true", default=False, help=kwargs[], *args)
Add a boolean option. @keyword help: Option description.
354,834
def parse_setup(options: Union[List, str]) -> str: if isinstance(options, str): return options return "\n".join(options)
Convert potentially a list of commands into a single string. This creates a single string with newlines between each element of the list so that they will all run after each other in a bash script.
354,835
def remove_readonly(func, path, _): "Clear the readonly bit and reattempt the removal" os.chmod(path, stat.S_IWRITE) func(path)
Clear the readonly bit and reattempt the removal
354,836
def token_at_cursor(code, pos=0): l = len(code) end = start = pos while end < l and code[end].isalpha(): end += 1 while start > 0 and code[start-1].isalpha(): start -= 1 if start > 0 and code[start-1] == : start -= 1 return code[start:end], start
Find the token present at the passed position in the code buffer :return (tuple): a pair (token, start_position)
354,837
def image_data(image): data = image.tobytes() components = len(data) // (image.size[0] * image.size[1]) return components, data
Get components and bytes for an image
354,838
def alleles_to_retrieve(df): contig_blastn_records = defaultdict(list) markers = df.marker.unique() for m in markers: dfsub = df[df.marker == m] for i, r in dfsub.iterrows(): if r.coverage < 1.0: contig_blastn_records[r.stitle].append(r) break ...
Alleles to retrieve from genome fasta Get a dict of the genome fasta contig title to a list of blastn results of the allele sequences that must be retrieved from the genome contig. Args: df (pandas.DataFrame): blastn results dataframe Returns: {str:[pandas.Series]}: dict of contig tit...
354,839
def _parse(self, fname): def _find_section(line): return line.strip().strip().strip() def _add_info(sys_or_mol, section, container): if sys_or_mol.information.get(section, False) is False: sys_or_mol.information[section] = container ...
Parse a processed.top GROMACS topology file The function reads in the file line-by-line, and it's a bunch of 'elif' statements, writing parameter/atom line to current section/molecule. ParamTypes are added to self.xyztypes (AtomType goes to self.atomtypes). Params are added to current ...
354,840
def generate_default_filename(infile_path, is_cropped_file=True): if is_cropped_file: suffix = prefix = args.stringCropped else: suffix = prefix = args.stringUncropped file_name = os.path.basename(infile_path) nameBeforeExtension, extension = os.path.splitext(file_name) if extension not ...
Generate the name of the default output file from the name of the input file. The is_cropped_file boolean is used to indicate that the file has been (or will be) cropped, to determine which filename-modification string to use. Function assumes that args has been set globally by argparse.
354,841
def search_rule_by_id(self, ruleID) -> Rule: for r in self.rules: if r.id == ruleID: return r return None
searches a rule by given id Args: ruleID(str): the rule to search for Returns the rule object or None if it couldn't find a rule
354,842
def io_priority(self): return ( self._iocb.aio_reqprio if self._iocb.u.c.flags & libaio.IOCB_FLAG_IOPRIO else None )
IO priority for this instance.
354,843
def get_built_image_info(self): logger.info("getting information about built image ", self.image) image_info = self.tasker.get_image_info_by_image_name(self.image) items_count = len(image_info) if items_count == 1: return image_info[0] elif items_count <= 0: ...
query docker about built image :return dict
354,844
def _generic_convert_string(v, from_type, to_type, encoding): assert six.PY2, "This function should be used with Python 2 only" assert from_type != to_type if from_type == six.binary_type and isinstance(v, six.binary_type): return six.text_type(v, encoding) elif from_type == six.text_typ...
Generic method to convert any argument type (string type, list, set, tuple, dict) to an equivalent, with string values converted to given 'to_type' (str or unicode). This method must be used with Python 2 interpreter only. :param v: The value to convert :param from_type: The original string type to con...
354,845
def generic_modis5kmto1km(*data5km): cols5km = np.arange(2, 1354, 5) cols1km = np.arange(1354) lines = data5km[0].shape[0] * 5 rows5km = np.arange(2, lines, 5) rows1km = np.arange(lines) along_track_order = 1 cross_track_order = 3 satint = Interpolator(list(data5km), ...
Getting 1km data for modis from 5km tiepoints.
354,846
def draw_strip_text(self, text_lines, location, pid): ax = self.axs[pid] themeable = self.figure._themeable dim = self.strip_dimensions(text_lines, location, pid) if location == : rotation = -90 label = .join(reversed(text_lines)) else: ...
Create a background patch and put a label on it
354,847
def get_next_character(self): cursor = self.textCursor() cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor) return cursor.selectedText()
Returns the character after the cursor. :return: Next cursor character. :rtype: QString
354,848
def get_job_details(self, job_id): response = requests.get(self._get_job_details_url(job_id)) response.raise_for_status() return response
Gets all details for existing job :param job_id: job_id as returned by 'create_operation_job(...)' :return: job info as xml
354,849
def _temp_exists(method, ip): _type = method.replace(, ).upper() cmd = "csf -t | awk -v code=1 -v type=_type -v ip=ip ".format(_type=_type, ip=ip) exists = __salt__[](cmd) return not bool(exists[])
Checks if the ip exists as a temporary rule based on the method supplied, (tempallow, tempdeny).
354,850
def install_setuptools(python_cmd=, use_sudo=True): setuptools_version = package_version(, python_cmd) distribute_version = package_version(, python_cmd) if setuptools_version is None: _install_from_scratch(python_cmd, use_sudo) else: if distribute_version is None: _up...
Install the latest version of `setuptools`_. :: import burlap burlap.python_setuptools.install_setuptools()
354,851
def _check_for_slash_endings(self, readnames): split readnames = [x.split()[0] for x in readnames] if any(x for x in readnames if x.endswith() or x.endswith()): result = True else: result = False return result
Provide a list of read names to be checked for the /1 or /2 endings which cause troubles downstream when working with paired reads. This function checks the list for ANY read ending in /1 or /2. The reads are first stripped of any comment lines, using the 'split' function Parameters ...
354,852
def routes(self): if self._routes: return self._routes request = requests.get(self.endpoint) request.raise_for_status() data = request.json() self._routes = { "collections": parse_uri(data["collections"], self.endpoint), "documents": ...
Retrieves the main routes of the DTS Collection Response format expected : { "@context": "/dts/api/contexts/EntryPoint.jsonld", "@id": "/dts/api/", "@type": "EntryPoint", "collections": "/dts/api/collections/", "documents": "/dts...
354,853
async def import_image(self, data, stream: bool = False): headers = {"Content-Type": "application/x-tar"} response = await self.docker._query_chunked_post( "images/load", "POST", data=data, headers=headers ) return await json_stream_result(response, stream=stream)
Import tarball of image to docker. Args: data: tarball data of image to be imported Returns: Tarball of the image
354,854
def update_cache_for_instance( model_name, instance_pk, instance=None, version=None): cache = SampleCache() invalid = cache.update_instance(model_name, instance_pk, instance, version) for invalid_name, invalid_pk, invalid_version in invalid: update_cache_for_instance.delay( ...
Update the cache for an instance, with cascading updates.
354,855
def find_lc_timegroups(lctimes, mingap=4.0): lc_time_diffs = [(lctimes[x] - lctimes[x-1]) for x in range(1,len(lctimes))] lc_time_diffs = np.array(lc_time_diffs) group_start_indices = np.where(lc_time_diffs > mingap)[0] if len(group_start_indices) > 0: group_indices = [] for i,...
This finds the time gaps in the light curve, so we can figure out which times are for consecutive observations and which represent gaps between seasons. Parameters ---------- lctimes : np.array This is the input array of times, assumed to be in some form of JD. mingap : float ...
354,856
def update_opdocs(self, checksum, opdocs, revision=None): return self._update(checksum=checksum, opdocs=opdocs, revision=revision)
Modifies the internal state based a change to the content and returns the sets of words added and removed. :Parameters: checksum : `hashable` A checksum generated from the text of a revision opdocs : `iterable` ( `dict` ) A sequence of operations ...
354,857
def transform_sequence(f): @wraps(f) def wrapper(*args, **kwargs): return lambda seq: seq.map_points(partial(f, *args, **kwargs)) return wrapper
A decorator to take a function operating on a point and turn it into a function returning a callable operating on a sequence. The functions passed to this decorator must define a kwarg called "point", or have point be the last positional argument
354,858
def to_literal(self): if not self.nodes: return (self.tag, self.attrib, self.text, []) else: return (self.tag, self.attrib, self.text, list(map(to_literal, self.nodes)))
Convert the node into a literal Python object
354,859
def spt(points, max_dist_error, max_speed_error): if len(points) <= 2: return points else: is_error = False e = 1 while e < len(points) and not is_error: i = 1 while i < e and not is_error: delta_e = time_dist(points[e], points[0]) * I...
A combination of both `td_sp` and `td_tr` Detailed in, Spatiotemporal Compression Techniques for Moving Point Objects, Nirvana Meratnia and Rolf A. de By, 2004, in Advances in Database Technology - EDBT 2004: 9th International Conference on Extending Database Technology, Her...
354,860
def create_committee_member(self, url="", account=None, **kwargs): if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(a...
Create a committee member :param str url: URL to read more about the worker :param str account: (optional) the account to allow access to (defaults to ``default_account``)
354,861
def merge(arg, *rest, **kwargs): ensure_keyword_args(kwargs, optional=(,)) has_default = in kwargs if has_default: default = ensure_callable(kwargs[]) unary_result = True if rest: fs = (ensure_callable(arg),) + tuple(imap(ensure_callable, rest)) unary_r...
Merge a collection, with functions as items, into a single function that takes a collection and maps its items through corresponding functions. :param arg: A collection of functions, such as list, tuple, or dictionary :param default: Optional default function to use for items within mer...
354,862
def create_config(): file_exists = exists(CONFIG_FILE) if not file_exists: config.add_section() defaults = [ (, expanduser()), (, expanduser()), (, expanduser()), (, expanduser()), (, expanduser()), (, expandus...
Initiates process to generate configuration file.
354,863
def get_info(self, code): currency = self.get_currency(code) info = {} users = list(filter(None, currency[].split())) if users: info[] = users alt = list(filter(None, currency[].split())) if alt: info[] = alt if self.modified: ...
Return a dict of information about the currency
354,864
def wait_event(self, filter: Callable[[T_Event], bool] = None) -> Awaitable[T_Event]: return wait_event([self], filter)
Shortcut for calling :func:`wait_event` with this signal in the first argument.
354,865
def new_dataset(data, identifier=None): if isinstance(data, dict): return fmt_dict.RTDC_Dict(data, identifier=identifier) elif isinstance(data, (str_types)) or isinstance(data, pathlib.Path): return load_file(data, identifier=identifier) elif isinstance(data, RTDCBase): return f...
Initialize a new RT-DC dataset Parameters ---------- data: can be one of the following: - dict - .tdms file - .rtdc file - subclass of `RTDCBase` (will create a hierarchy child) identifier: str A unique identifier for this dataset. If set to `N...
354,866
def _maybe_host_form_to_py_ast( _: GeneratorContext, node: MaybeHostForm ) -> GeneratedPyAST: assert node.op == NodeOp.MAYBE_HOST_FORM return GeneratedPyAST( node=_load_attr( f"{Maybe(_MODULE_ALIASES.get(node.class_)).or_else_get(node.class_)}.{node.field}" ) )
Generate a Python AST node for accessing a potential Python module variable name with a namespace.
354,867
def pad_matrix(self, matrix, pad_value=0): max_columns = 0 total_rows = len(matrix) for row in matrix: max_columns = max(max_columns, len(row)) total_rows = max(max_columns, total_rows) new_matrix = [] for row in matrix: row_len = len(r...
Pad a possibly non-square matrix to make it square. :Parameters: matrix : list of lists matrix to pad pad_value : int value to use to pad the matrix :rtype: list of lists :return: a new, possibly padded, matrix
354,868
def find_key(self, regex): log = logging.getLogger(self.cls_logger + ) if not isinstance(regex, basestring): log.error() return None log.info(, regex) matched_keys = [] for item in self.bucket.objects.all(): log.debug(, item.key) ...
Attempts to find a single S3 key based on the passed regex Given a regular expression, this method searches the S3 bucket for a matching key, and returns it if exactly 1 key matches. Otherwise, None is returned. :param regex: (str) Regular expression for an S3 key :return: (str...
354,869
def label_sectors( *, labels=["I", "II", "IV", "VI", "V", "III"], ax=None, lw=2, lc="k", cs=None, c_zlevel=2, c_alpha=0.5, fontsize=40 ): if ax is None: ax = plt.gca() factors = [ [0.25, 0.75], [2 / 3, 5 / 6], [5 / 6, 2 / 3], ...
Label the six time-orderings in a three-pulse experiment. Parameters ---------- labels : list of strings Labels to place within sectors, starting in the upper left and proceeding clockwise. Default is ['I', 'II', 'IV', 'VI', 'V', 'III']. ax : matplotlib axis object (optional) Ax...
354,870
def derive_source_offset(self, offset, is_end=False): for segment in self.segments: if offset <= segment.end: if isinstance(segment, MacroSegment): if is_end: return ( segment.src_end, ...
Given a post-preprocessed coordinate, derives the corresponding coordinate in the original source file. Returns result in the following tuple: (src_offset, src_path, include_ref) where: - src_offset is the translated coordinate If the input offset lands o...
354,871
def start(self): self._observer_params.update(dict(once=True)) super(CurrentResourceValue, self).start() self._api.ensure_notifications_thread() self._api._mds_rpc_post( device_id=self.device_id, method=, uri=self.resource_path, ...
Start the channel
354,872
def get_line_number(line_map, offset): for lineno, line_offset in enumerate(line_map, start=1): if line_offset > offset: return lineno return -1
Find a line number, given a line map and a character offset.
354,873
def delete_interconnect(self, enclosure_uri, bay, timeout=-1): uri = "{path}?location=Enclosure:{enclosure_uri},Bay:{bay}".format(path=self.LOCATIONS_PATH, enclosure_uri=enclosure_uri, ...
Deletes an interconnect from a location. Warning: This won't delete the LOGICAL INTERCONNECT itself and might cause inconsistency between the enclosure and Logical Interconnect Group. Args: enclosure_uri: URI of the Enclosure bay: Bay timeout...
354,874
def revise(self, data, ignore_none=True): if not isinstance(data, dict): raise TypeError("`data` has to be a dict!") if ignore_none: for key, value in data.items(): if value is not None: setattr(self, key, deepcopy(value)) els...
Revise attributes value with dictionary data. :type data: dict :type ignore_none: bool **中文文档** 将一个字典中的数据更新到本条文档。当且仅当数据值不为None时。
354,875
def _trim_and_decode(ids, subtokenizer): try: index = list(ids).index(tokenizer.EOS_ID) return subtokenizer.decode(ids[:index]) except ValueError: return subtokenizer.decode(ids)
Trim EOS and PAD tokens from ids, and decode to return a string.
354,876
def _write_images(self, name:str, images:[Tensor])->None: "Writes list of images as tensors to Tensorboard." tag = self.ds_type.name + + name self.tbwriter.add_image(tag=tag, img_tensor=vutils.make_grid(images, normalize=True), global_step=self.iteration)
Writes list of images as tensors to Tensorboard.
354,877
def mask_file(regionfile, infile, outfile, negate=False): if not os.path.exists(infile): raise AssertionError("Cannot locate fits file {0}".format(infile)) im = pyfits.open(infile) if not os.path.exists(regionfile): raise AssertionError("Cannot locate region file {0}".format(regionfile)) regio...
Created a masked version of file, using a region. Parameters ---------- regionfile : str A file which can be loaded as a :class:`AegeanTools.regions.Region`. The image will be masked according to this region. infile : str Input FITS image. outfile : str Output FIT...
354,878
def get_trade_histories(self, symbol): data = { : symbol } return self._get(, False, data=data)
List the latest trades for a symbol https://docs.kucoin.com/#get-trade-histories :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string .. code:: python orders = client.get_trade_histories('KCS-BTC') :returns: ApiResponse .. code:: python ...
354,879
def _get_x_axis(self): x_centers = np.linspace(.5, self.x_size - .5, self.x_size) y_centers = x_centers * 0 return (self.geotransform[0] + self.geotransform[1] * x_centers + self.geotransform[2] * y_centers)
See http://www.gdal.org/gdal_datamodel.html for details.
354,880
def close(self): close_command = StandardSend(self._address, COMMAND_LIGHT_OFF_0X13_0X00) self._send_method(close_command, self._close_message_received)
Send CLOSE command to device.
354,881
def params(dirnames, param_func, t_steady=None): return np.array([param_func(get_recent_model(d)) for d in dirnames])
Calculate a parameter of a set of model output directories, for a measure function which returns an associated uncertainty. Parameters ---------- dirnames: list[str] Model output directory paths. param_func: function Function which takes a :class:`Model` instance as a single argumen...
354,882
def clean(self): if not self.priorDays and not self.startDate: raise ValidationError(_( + )) super(GenericRepeatedExpense,self).clean()
priorDays is required for Generic Repeated Expenses to avoid infinite loops
354,883
def _coerce_type(self, field_type, value): if value is None: return None if field_type == : return str(value) elif field_type == : return str(value) elif field_type == : try: v = int(value) return st...
Returns unicode(value) after trying to coerce it into the Solr field type. @param field_type(string) The Solr field type for the value @param value(any) The value that is to be represented as Unicode text.
354,884
def run(self, gin): with ScratchDir("."): p = subprocess.Popen( self._gulp_cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE ) out, err = p.communicate(bytearray(gin, "utf-8")) out = out.decode("ut...
Run GULP using the gin as input Args: gin: GULP input string Returns: gout: GULP output string
354,885
def _convolve_spatial2(im, hs, mode = "constant", grid_dim = None, pad_factor = 2, plan = None, return_plan = False): if grid_dim: Gs = tuple(grid_dim) else: Gs = hs.shape[:2] ...
spatial varying convolution of an 2d image with a 2d grid of psfs shape(im_ = (Ny,Nx) shape(hs) = (Gy,Gx, Hy,Hx) the input image im is subdivided into (Gy,Gx) blocks hs[j,i] is the psf at the center of each block (i,j) as of now each image dimension has to be divisible by the grid dim, i.e. N...
354,886
def dedent(text): if text.startswith():
Equivalent of textwrap.dedent that ignores unindented first line. This means it will still dedent strings like: '''foo is a bar ''' For use in wrap_paragraphs.
354,887
def loadmask(self, filename: str) -> np.ndarray: mask = scipy.io.loadmat(self.find_file(filename, what=)) maskkey = [k for k in mask.keys() if not (k.startswith() or k.endswith())][0] return mask[maskkey].astype(np.bool)
Load a mask file.
354,888
def texto_decimal(valor, remover_zeros=True): texto = .format(valor) if remover_zeros: dp = locale.localeconv().get() texto = texto.rstrip().rstrip(dp) if dp in texto else texto return texto
Converte um valor :py:class:`decimal.Decimal` para texto, com a opção de remover os zeros à direita não significativos. A conversão para texto irá considerar o :py:module:`locale` para converter o texto pronto para apresentação. :param decimal.Decimal valor: Valor a converter para texto. :param boo...
354,889
def __init_from_list_np2d(self, mats, params_str, ref_dataset): ncol = mats[0].shape[1] nrow = np.zeros((len(mats),), np.int32) if mats[0].dtype == np.float64: ptr_data = (ctypes.POINTER(ctypes.c_double) * len(mats))() else: ptr_data = (ctypes.POINTER(cty...
Initialize data from a list of 2-D numpy matrices.
354,890
def write_multiple_registers(slave_id, starting_address, values): function = WriteMultipleRegisters() function.starting_address = starting_address function.values = values return _create_request_adu(slave_id, function.request_pdu)
Return ADU for Modbus function code 16: Write Multiple Registers. :param slave_id: Number of slave. :return: Byte array with ADU.
354,891
def scale(self, selections, factor): if in selections: atms = selections[].mask if factor is None: self.scale_factors[atms] = 1.0 else: self.scale_factors[atms] = factor self.update_scale_factors(self.scale_factors)
Scale the objects represented by *selections* up to a certain *factor*.
354,892
def get_min_distance(self, mesh): dists = [surf.get_min_distance(mesh) for surf in self.surfaces] return numpy.min(dists, axis=0)
For each point in ``mesh`` compute the minimum distance to each surface element and return the smallest value. See :meth:`superclass method <.base.BaseSurface.get_min_distance>` for spec of input and result values.
354,893
def is_dxlink(x): if not isinstance(x, dict): return False if not in x: return False link = x[] if isinstance(link, basestring): return True elif isinstance(link, dict): return any(key in link for key in (, )) return False
:param x: A potential DNAnexus link Returns whether *x* appears to be a DNAnexus link (is a dict with key ``"$dnanexus_link"``) with a referenced data object.
354,894
def share(self, project, to_user, force_send, auth_role, user_message): if self._is_current_user(to_user): raise ShareWithSelfError(SHARE_WITH_SELF_MESSAGE.format("share")) if not to_user.email: self._raise_user_missing_email_exception("share") self.set_user_proj...
Send mail and give user specified access to the project. :param project: RemoteProject project to share :param to_user: RemoteUser user to receive email/access :param auth_role: str project role eg 'project_admin' to give to the user :param user_message: str message to be sent with the s...
354,895
def get_queryset(self): if self.request and self.request.query_params.get(, False): return self.queryset.prefetch_related() return self.queryset
Return queryset.
354,896
def repmd(instr, marker, value, sigdig): lenout = ctypes.c_int(len(instr) + len(marker) + 15) instr = stypes.stringToCharP(instr) marker = stypes.stringToCharP(marker) value = ctypes.c_double(value) sigdig = ctypes.c_int(sigdig) out = stypes.stringToCharP(lenout) libspice.repmd_c(instr,...
Replace a marker with a double precision number. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/repmd_c.html :param instr: Input string. :type instr: str :param marker: Marker to be replaced. :type marker: str :param value: Replacement value. :type value: float :param sigdig: ...
354,897
def run(self): model = Model(self.fP, self.doc) self.doc.walkabout(model) return model
Parse the script file. :rtype: :py:class:`~turberfield.dialogue.model.Model`
354,898
def lsdirs(root=".", **kwargs): paths = ls(root=root, **kwargs) if isfile(root): return [] return [_path for _path in paths if isdir(path(root, _path))]
Return only subdirectories from a directory listing. Arguments: root (str): Path to directory. Can be relative or absolute. **kwargs: Any additional arguments to be passed to ls(). Returns: list of str: A list of directory paths. Raises: OSError: If root directory does ...
354,899
def delete_password(self, service, username): if not self.connected(service): raise PasswordDeleteError("Cancelled by user") if not self.iface.hasEntry(self.handle, service, username, self.appid): raise PasswordDeleteError("Password not found") self....
Delete the password for the username of the service.