Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
339,900
def export(self, image_path, tmptar=None): from spython.utils import check_install check_install() if tmptar is None: tmptar = "/%s/tmptar.tar" %(tempfile.mkdtemp()) cmd = [, , , tmptar, image_path] output = self.run_command(cmd, sudo=False) return tmptar
export will export an image, sudo must be used. Parameters ========== image_path: full path to image tmptar: if defined, use custom temporary path for tar export
339,901
def _generate_list_heading(self): local = self.parser.find().first_result() id_container_heading_before = ( AccessibleNavigationImplementation.ID_CONTAINER_HEADING_BEFORE ) id_container_heading_after = ( AccessibleNavigationImplementation.ID_CONTAINER_HE...
Generate the list of heading links of page.
339,902
def triples(self, (s, p, o), context=None): named_graph = _get_named_graph(context) query_sets = _get_query_sets_for_object(o) filter_parameters = dict() if named_graph is not None: filter_parameters[] = named_graph.id if s: filter_parameters[] =...
Returns all triples in the current store.
339,903
def getcellslice(self, rownr, blc, trc, inc=[]): return self._table.getcellslice(self._column, rownr, blc, trc, inc)
Get a slice from a column cell holding an array. (see :func:`table.getcellslice`)
339,904
def linspace_bins(self,bins=None,units=None,conversion_function=convert_time,resolution=None,end_at_end=True,extra_bins=0): bins = self.linspace(bins=bins,units=units,conversion_function=conversion_function,resolution=resolution,end_at_end=end_at_end,extra_bins=extra_bins) resolution = bins[1] ...
Generates bin edges for a linspace tiling: there is one edge more than bins and each bin is in the middle between two edges
339,905
def kldiv(p, q, distp = None, distq = None, scale_factor = 1): assert q != None or distq != None, "Either q or distq have to be given" assert p != None or distp != None, "Either p or distp have to be given" try: if p == None: p = compute_fdm(distp, scale_factor = scale_factor) ...
Computes the Kullback-Leibler divergence between two distributions. Parameters p : Matrix The first probability distribution q : Matrix The second probability distribution distp : fixmat If p is None, distp is used to compute a FDM which is th...
339,906
def as_iso8601(self): if self.__time is None: return None return "%s:%s:%s0Z" % (self.__time[:2], self.__time[2:4], self.__time[4:])
example: 00:38:05.210Z
339,907
def recall(truth, recommend, k=None): if len(truth) == 0: if len(recommend) == 0: return 1. return 0. if k is None: k = len(recommend) return count_true_positive(truth, recommend[:k]) / float(truth.size)
Recall@k. Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. k (int): Top-k items in `recommend` will be recommended. Returns: float: Recall@k.
339,908
def create_key_filter(properties: Dict[str, list]) -> List[Tuple]: combinations = (product([k], v) for k, v in properties.items()) return chain.from_iterable(combinations)
Generate combinations of key, value pairs for each key in properties. Examples -------- properties = {'ent': ['geo_rev', 'supply_chain'], 'own', 'fi'} >> create_key_filter(properties) --> [('ent', 'geo_rev'), ('ent', 'supply_chain'), ('own', 'fi')]
339,909
def get_or_create_unique(klass, defaults, unique_fields): if not unique_fields or not defaults: return (None, False) uniqueness_query = {k: v for k, v in defaults.items() if k in unique_fields} try: with transaction.atomic(): instance, created = klass.objects.get_or_create...
Returns a tuple of (instance, created), where `instance` is the retrieved or created instance of `klass` and `created` is a boolean specifying whether a new object was created. The value for the unique fields must be present in the defaults dictionary.
339,910
def height_to_geopotential(height): r geopot = mpconsts.G * mpconsts.me * ((1 / mpconsts.Re) - (1 / (mpconsts.Re + height))) return geopot
r"""Compute geopotential for a given height. Parameters ---------- height : `pint.Quantity` Height above sea level (array_like) Returns ------- `pint.Quantity` The corresponding geopotential value(s) Examples -------- >>> from metpy.constants import g, G, me, Re ...
339,911
def size(self): (lat1, lon1) = self.coord((0,0)) (lat2, lon2) = self.coord((TILES_WIDTH,0)) width = mp_util.gps_distance(lat1, lon1, lat2, lon2) (lat2, lon2) = self.coord((0,TILES_HEIGHT)) height = mp_util.gps_distance(lat1, lon1, lat2, lon2) return (width,height)
return tile size as (width,height) in meters
339,912
def write(url, object_, **args): default_content_type = (, {: }) content_encoding = args.get(, ) content_type, params = args.get(, default_content_type) data = content_types.get(content_type).format(object_, **params) args[].write(.format(content_type)) for param, value in params.items(): ...
Writes an object to a data URI.
339,913
def update(self, request, datum): if getattr(self, , False): self.verbose_name = self._get_action_name() self.verbose_name_plural = self._get_action_name()
Switches the action verbose name, if needed.
339,914
def checkPrediction2(possibleOutcome, predictedOutcome): missN = 0 for i in xrange(len(possibleOutcome)): miss = 1 for j in xrange(len(predictedOutcome)): if predictedOutcome[j] == possibleOutcome[i]: miss = 0 missN += miss fpN = 0 for i in xrange(len(predictedOutcome)): fp = 1...
:param possibleOutcome: list of all possible outcomes :param predictedOutcome: list of all predicted outomes :return missN: number of misses (a possible outcome not predicted) fpN: number of false positives (a predicted outcome is not possible to happen)
339,915
def keys(self, namespace, prefix=None, limit=None, offset=None): params = [namespace] query = if prefix is not None: query += params.append(prefix + ) if limit is not None: query += params.append(limit) if offset is not ...
Get keys from a namespace
339,916
def _get_passage(self, urn): urn = URN(urn) subreference = None if len(urn) < 4: raise InvalidURN if urn.reference is not None: subreference = str(urn.reference) node = self.resolver.getTextualNode(textId=urn.upTo(URN.NO_PASSAGE), subreference=sub...
Provisional route for GetPassage request :param urn: URN to filter the resource :return: GetPassage response
339,917
def run(self): self.assert_has_content() env = self.state.document.settings.env node = nodes.container() node[] = [] if not in env.temp_data: env.temp_data[] = 0 if not in env.temp_data: env.temp_data[] = [] tabs_id = env.temp...
Parse a tabs directive
339,918
def load_nd_from_pickle(filename=None, path=): abs_path = os.path.abspath(path) if filename is None: raise NotImplementedError return pickle.load(open(os.path.join(abs_path, filename), "rb"))
Use pickle to save the whole nd-object to disc Parameters ---------- filename : str Filename of nd pickle path : str Absolute or relative path where pickle should be saved. Default is '' which means pickle is save to PWD Returns ------- nd : NetworkDing0 Din...
339,919
def save(self, revision): if not isinstance(revision, Revision): raise InvalidArgType() self.state.update(revision)
:param revision: :type revision: :class:`revision.data.Revision`
339,920
def pre_filter(self, queryset, user): s condition in one of their carts. ' in_user_carts = Q( enabling_category__product__productitem__cart__user=user ) released = commerce.Cart.STATUS_RELEASED in_released_carts = Q( enabling_category__product__pr...
Returns all of the items from queryset where the user has a product from a category invoking that item's condition in one of their carts.
339,921
def do_execute(self): result = None cont = self.input.payload name = str(self.resolve_option("value")) value = cont.get(name) switch = bool(self.resolve_option("switch")) if switch: if self.first_active is not None: self.first_active.i...
The actual execution of the actor. :return: None if successful, otherwise error message :rtype: str
339,922
def comments_for(context, obj): form_class = import_dotted_path(settings.COMMENT_FORM_CLASS) form = form_class(context["request"], obj) context_form = context.get("posted_comment_form", form) context.update({ : context_form if context_form.target_object == obj else form, ...
Provides a generic context variable name for the object that comments are being rendered for.
339,923
def iter_orgs(username, number=-1, etag=None): return gh.iter_orgs(username, number, etag) if username else []
List the organizations associated with ``username``. :param str username: (required), login of the user :param int number: (optional), number of orgs to return. Default: -1, return all of the issues :param str etag: (optional), ETag from a previous request to the same endpoint :returns:...
339,924
def reindex(self, kdims=[], force=False): if not isinstance(kdims, list): kdims = [kdims] kdims = [self.get_dimension(kd, strict=True) for kd in kdims] dropped = [kd for kd in self.kdims if kd not in kdims] if dropped: raise ValueError("DynamicMap does no...
Reorders key dimensions on DynamicMap Create a new object with a reordered set of key dimensions. Dropping dimensions is not allowed on a DynamicMap. Args: kdims: List of dimensions to reindex the mapping with force: Not applicable to a DynamicMap Returns: ...
339,925
def set(self, key, value): changed = super().set(key=key, value=value) if not changed: return False self._log.info(, self._filename) with open(self._filename, ) as stream: stream.write(self.content) self._log.info(, self._filename) ...
Updates the value of the given key in the file. Args: key (str): Key of the property to update. value (str): New value of the property. Return: bool: Indicates whether or not a change was made.
339,926
def setQuery(self, query, autoRefresh=True): self._query = query tableType = self.tableType() if not tableType: return False if autoRefresh: self.refresh(tableType.select(where = query)) return True
Sets the query for this record box for generating records. :param query | <Query> || None
339,927
def rtruediv(self, other, axis="columns", level=None, fill_value=None): return self._binary_op( "rtruediv", other, axis=axis, level=level, fill_value=fill_value )
Div this DataFrame against another DataFrame/Series/scalar. Args: other: The object to use to apply the div against this. axis: The axis to div over. level: The Multilevel index level to apply div over. fill_value: The value to fill NaNs with. Re...
339,928
def apps_installation_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/apps api_path = "/api/v2/apps/installations.json" return self.call(api_path, method="POST", data=data, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/apps#install-app
339,929
def exhandler(function, parser): args = vars(bparser.parse_known_args()[0]) if args["examples"]: function() exit(0) if args["verbose"]: from msg import set_verbosity set_verbosity(args["verbose"]) args.update(vars(parser.parse_known_args()[0])) return args
If -examples was specified in 'args', the specified function is called and the application exits. :arg function: the function that prints the examples. :arg parser: the initialized instance of the parser that has the additional, script-specific parameters.
339,930
def set_threadlocal(self, **values): with self._lock: self._ensure_threadlocal() self._tpayload.context = values
Set current thread's logging context to specified `values`
339,931
def __update_offsets(self, fileobj, atoms, delta, offset): if delta == 0: return moov = atoms[b"moov"] for atom in moov.findall(b, True): self.__update_offset_table(fileobj, ">%dI", atom, delta, offset) for atom in moov.findall(b, True): self....
Update offset tables in all 'stco' and 'co64' atoms.
339,932
def out_64(library, session, space, offset, data, extended=False): if extended: return library.viOut64Ex(session, space, offset, data) else: return library.viOut64(session, space, offset, data)
Write in an 64-bit value from the specified memory space and offset. Corresponds to viOut64* functions of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :param space: Specifies the address space. (Constants.*SPACE*) :pa...
339,933
def redirect_to_login(next, redirect_field_name=REDIRECT_FIELD_NAME): resolved_url = reverse() login_url_parts = list(urlparse(resolved_url)) if redirect_field_name: querystring = QueryDict(login_url_parts[4], mutable=True) querystring[redirect_field_name] = next login_url_part...
Redirects the user to the login page, passing the given 'next' page
339,934
def kml_map_root(map_source): map = app.config["mapsources"][map_source] kml_doc = KMLMapRoot(app.config["url_formatter"], map, app.config["LOG_TILES_PER_ROW"]) return kml_response(kml_doc)
KML for a given map
339,935
def rotateInDeclination(v1, theta_deg): axis = np.array([0,-1,0]) return rotateAroundVector(v1, axis, theta_deg)
Rotation is chosen so a rotation of 90 degrees from zenith ends up at ra=0, dec=0
339,936
def draw_profile(self, coordinates, num_points=500, save=False, name=): BaseProfile.png fig = plt.figure(figsize=(27, len(coordinates) * 8)) gs = gridspec.GridSpec(len(coordinates), 4) if len(coordinates) == 4: assert type(coordinates[0]) == tuple,\ ...
Draw a profile between a point (lon0,lat0) and (lon1,lat1). Args: coordinates: Tupples which list the different desired profiles. Each profil has to be defined as a tupple which follows (lon0,lon1,lat0,lat1) with (lon0,lat0) the first point ...
339,937
def _data_frame(content): response = loads(content) key = [x for x in response.keys() if x in c.response_data][0] frame = DataFrame(response[key]) final_frame = _convert(frame) return final_frame
Helper funcation that converts text-based get response to a pandas dataframe for additional manipulation.
339,938
def AIC(data, model, params=None, corrected=True): n = len(data) L = nll(data, model) if not params: k = len(model.kwds) + len(model.args) else: k = params if corrected: aic_value = 2 * k + 2 * L + (2 * k * (k + 1)) / (n - k - 1) else: aic_value = 2 * k +...
Akaike Information Criteria given data and a model Parameters ---------- {0} {1} params : int Number of parameters in the model. If None, calculated from model object. corrected : bool If True, calculates the small-sample size correct AICC. Default True. Returns ...
339,939
def get_freesurfer_cmap(vis_type): if vis_type in (, ): LUT = get_freesurfer_cortical_LUT() cmap = ListedColormap(LUT) elif vis_type in (, ): black = np.array([0, 0, 0, 1]) cmap = plt.get_cmap() cmap = cmap(np.linspace(0, 1, 20)) co...
Provides different colormaps for different visualization types.
339,940
def predict(self, u=None): xs, Ps = [], [] for i, (f, w) in enumerate(zip(self.filters, self.omega.T)): x = zeros(self.x.shape) for kf, wj in zip(self.filters, w): x += kf.x * wj xs.append(x) P = zeros(self.P.shape) ...
Predict next state (prior) using the IMM state propagation equations. Parameters ---------- u : np.array, optional Control vector. If not `None`, it is multiplied by B to create the control input into the system.
339,941
def remove(self, symbol): self._unit_system_id = None if symbol not in self.lut: raise SymbolNotFoundError( "Tried to remove the symbol , but it does not exist " "in this registry." % symbol ) del self.lut[symbol]
Remove the entry for the unit matching `symbol`. Parameters ---------- symbol : str The name of the unit symbol to remove from the registry.
339,942
def _bnd(self, xloc, left, right, cache): left = evaluation.get_forward_cache(left, cache) right = evaluation.get_forward_cache(right, cache) if isinstance(left, Dist): if isinstance(right, Dist): raise StochasticallyDependentError( "unde...
Distribution bounds. Example: >>> print(chaospy.Uniform().range([-2, 0, 2, 4])) [[0. 0. 0. 0.] [1. 1. 1. 1.]] >>> print(chaospy.Pow(chaospy.Uniform(), 2).range([-2, 0, 2, 4])) [[0. 0. 0. 0.] [1. 1. 1. 1.]] >>> print(chaospy.P...
339,943
def change_email(self, email, as_username=False): email = email.lower() data = {"email": email} if self.email != email: if self.get_by_email(email): raise exceptions.AuthError("Email exists already") if as_username: if self.usernam...
Change account email :param email: :param as_username :return: the email provided
339,944
async def main(): client = Client(BMAS_ENDPOINT) response = await client(bma.node.summary) print(response) salt = getpass.getpass("Enter your passphrase (salt): ") password = getpass.getpass("Enter your password: ") pubkey = input("Enter your public key: ") ...
Main code
339,945
def bytes_iter(obj): if obj is None: return elif isinstance(obj, six.binary_type): yield obj elif isinstance(obj, six.string_types): yield obj elif isinstance(obj, (date, datetime)): yield obj.isoformat() elif is_mapping(obj): for key in sorted(obj.keys()...
Turn a complex object into an iterator of byte strings. The resulting iterator can be used for caching.
339,946
def _countmatrix(lxs): share = np.zeros((lxs.shape[0], lxs.shape[0])) names = range(lxs.shape[0]) for row in lxs: for samp1, samp2 in itertools.combinations(names, 2): shared = lxs[samp1, lxs[samp2] > 0].sum() share[samp1, samp2] = shared ...
fill a matrix with pairwise data sharing
339,947
def configure(self, options, conf): self.conf = conf if not options.capture: self.enabled = False
Configure plugin. Plugin is enabled by default.
339,948
def _delim_accum(control_files, filename_template, keys=None, exclude_keys=None, separator=DEFAULT_SEP, missing_action=): def map_fn(d, control, keys=keys): f = os.path.join(d, filename_template.format(**control)) keys = keys if keys is not None else control.keys() if exclude_k...
Accumulator for delimited files Combines each file with values from JSON dictionary in same directory :param iterable control_files: Iterable of control files :param filename_template: A template for the file to nest_map :param keys: List of keys to select from JSON dictionary. If ``None``, keep ...
339,949
def text( body, status=200, headers=None, content_type="text/plain; charset=utf-8" ): return HTTPResponse( body, status=status, headers=headers, content_type=content_type )
Returns response object with body in text format. :param body: Response data to be encoded. :param status: Response code. :param headers: Custom Headers. :param content_type: the content type (string) of the response
339,950
def build_input_pipeline(train_images, batch_size): training_dataset = tf.data.Dataset.from_tensor_slices(train_images) training_batches = training_dataset.shuffle( 50000, reshuffle_each_iteration=True).repeat().batch(batch_size) training_iterator = tf.compat.v1.data.make_one_shot_iterator(training_batc...
Build an iterator over training batches.
339,951
def list(self, limit=None, offset=None): uri = "/%s%s" % (self.uri_base, self._get_pagination_qs(limit, offset)) return self._list(uri)
Gets a list of all domains, or optionally a page of domains.
339,952
def get_subdomain_entry_at_zonefile_index(self, fqn, zonefile_index, cur=None): get_cmd = "SELECT * FROM {} WHERE fully_qualified_subdomain=? AND parent_zonefile_index=?".format(self.subdomain_table) cursor = None if cur is None: cursor = self.conn.cursor() else: ...
Given a fully-qualified subdomain and a sequence number, get its historic subdomain record at that sequence. Raises SubdomainNotFound if there is no such subdomain
339,953
def HiResHDU(model): cards = model._mission.HDUCards(model.meta, hdu=5) cards.append((, )) cards.append((, )) cards.append((, )) cards.append((, model.mission, )) cards.append((, EVEREST_MAJOR_MINOR, )) cards.append((, EVEREST_VERSION, )) cards.append((, strftime(), ...
Construct the HDU containing the hi res image of the target.
339,954
def create_user( self, username, email, short_name, full_name, institute, password=None, **extra_fields): return self._create_user( username=username, email=email, short_name=short_name, full_name=full_name, institute=institute, password=passw...
Creates a new ordinary person.
339,955
def scroll_to_beginning_horizontally(self, steps=10, *args,**selectors): return self.device(**selectors).scroll.horiz.toBeginning(steps=steps)
Scroll the object which has *selectors* attributes to *beginning* horizontally. See `Scroll Forward Vertically` for more details.
339,956
def h_L(self, L, theta, Ts, **statef): Nu_L = self.Nu_L(L, theta, Ts, **statef) k = self._fluid.k(T=self.Tr) return Nu_L * k / L
Calculate the average heat transfer coefficient. :param L: [m] characteristic length of the heat transfer surface :param theta: [°] angle of the surface with the vertical :param Ts: [K] heat transfer surface temperature :param Tf: [K] bulk fluid temperature :returns: [W/m2/K] f...
339,957
def printOptions(options, tm, outFile): print >>outFile, "TM parameters:" printTemporalMemory(tm, outFile) print >>outFile, "Experiment parameters:" for k,v in options.__dict__.iteritems(): print >>outFile, " %s : %s" % (k,str(v)) outFile.flush()
Pretty print the set of options
339,958
def prompt(self): name = self.term.prompt_input() if name: submission_pattern = re.compile(r) match = submission_pattern.search(name) if match: url = .format(match....
Open a prompt to navigate to a different subreddit or comment"
339,959
def median_images(images): images_data = np.array([image.data for image in images]) median_image_data = np.median(images_data, axis=0) an_image = images[0] return type(an_image)( median_image_data.astype( an_image.data.dtype), an_image.fr...
Create a median Image from a list of Images. Parameters ---------- :obj:`list` of :obj:`Image` A list of Image objects. Returns ------- :obj:`Image` A new Image of the same type whose data is the median of all of the images' data.
339,960
def import_wiki_json(path=, model=WikiItem, batch_len=100, db_alias=, verbosity=2): return djdb.import_json(path=path, model=model, batch_len=batch_len, db_alias=db_alias, verbosity=verbosity)
Read json file and create the appropriate records according to the given database model.
339,961
def useradd(pwfile, user, password, opts=, runas=None): t update file; display results on stdout. - `m` Force MD5 encryption of the password (default). - `d` Force CRYPT encryption of the password. - `p` Do not encrypt the password (plaintext). - `s` Force SHA enc...
Add a user to htpasswd file using the htpasswd command. If the htpasswd file does not exist, it will be created. pwfile Path to htpasswd file user User name password User password opts Valid options that can be passed are: - `n` Don't update file; di...
339,962
def _transform_rows(self): self._find_all_step_methods() for row in self._source_reader.next(): self._transform_row_wrapper(row)
Transforms all source rows.
339,963
def optional(self, value = None): if value is None: return this._optional else: this._optional = value and True or False
Optional Getter/Setter method for optional flag Args: value (bool): If set, the method is a setter Returns: bool | None
339,964
def cublasCher(handle, uplo, n, alpha, x, incx, A, lda): status = _libcublas.cublasCher_v2(handle, _CUBLAS_FILL_MODE[uplo], n, alpha, int(x), incx, int(A), lda) cublasCheckStatus(status)
Rank-1 operation on Hermitian matrix.
339,965
def as_square_array(arr): arr = np.atleast_2d(arr) if len(arr.shape) != 2 or arr.shape[0] != arr.shape[1]: raise ValueError("Expected square array") return arr
Return arr massaged into a square array. Raises ValueError if arr cannot be so massaged.
339,966
def _on_delete(ent): cascade seen_d = set([ent._pk]) to_delete = [ent] seen_s = set() to_save = [] def _set_default(ent, attr, de=NULL): pk = ent._pk if pk in seen_d: for self in to_delete: self.delete(skip_on_delete_i_really_mean_it=SKIP_ON_DELETE)...
This function handles all on_delete semantics defined on OneToMany columns. This function only exists because 'cascade' is *very* hard to get right.
339,967
def serialize_ndarray_b64(o): if o.flags[]: o_data = o.data else: o_data = np.ascontiguousarray(o).data data_b64 = base64.b64encode(o_data) return dict( _type=, data=data_b64.decode(), dtype=o.dtype, shape=o.shape)
Serializes a :obj:`numpy.ndarray` in a format where the datatype and shape are human-readable, but the array data itself is binary64 encoded. Args: o (:obj:`numpy.ndarray`): :obj:`ndarray` to be serialized. Returns: A dictionary that can be passed to :obj:`json.dumps`.
339,968
def _process_robots(self): try: self._item_session.request = request = self._new_initial_request(with_body=False) verdict, reason = (yield from self._should_fetch_reason_with_robots( request)) except REMOTE_ERRORS as error: _logger.error( ...
Process robots.txt. Coroutine.
339,969
def libvlc_audio_output_list_get(p_instance): f = _Cfunctions.get(, None) or \ _Cfunction(, ((1,),), None, ctypes.POINTER(AudioOutput), Instance) return f(p_instance)
Gets the list of available audio output modules. @param p_instance: libvlc instance. @return: list of available audio outputs. It must be freed it with In case of error, NULL is returned.
339,970
def scientific(number, operation, number2=None, logbase=10): if operation == : return math.log(number, logbase) elif operation == : return math.acos(number) elif operation == : return math.asin(number) elif operation == : return math.atan(number) elif operation =...
Solve scientific operations manually
339,971
def make_value_from_shell(self, param, value_type, function): try: value = check_output(param, shell=True).rstrip() except CalledProcessError: if value_type == "bool": value = False else: if self.py3_wrapper: ...
run command in the shell
339,972
def create_wsgi_request(event_info, server_name=, script_name=None, trailing_slash=True, binary_support=False, base_path=None, context_header_mappings={}, ...
Given some event_info via API Gateway, create and return a valid WSGI request environ.
339,973
def _get_adjustments_in_range(self, asset, dts, field): sid = int(asset) start = normalize_date(dts[0]) end = normalize_date(dts[-1]) adjs = {} if field != : mergers = self._adjustments_reader.get_adjustments_for_sid( , sid) for m ...
Get the Float64Multiply objects to pass to an AdjustedArrayWindow. For the use of AdjustedArrayWindow in the loader, which looks back from current simulation time back to a window of data the dictionary is structured with: - the key into the dictionary for adjustments is the location of...
339,974
def vabsFromSpt(spt): if spt in _sptToVminiVabsDictionary: return _sptToVminiVabsDictionary[spt][1] else: message="Unknown spectral type. Allowed values are: " for key in _sptToVminiVabsDictionary.keys(): message += key+" " raise Exception(message)
Obtain M_V (absolute magnitude in V-band) for the input spectral type. Parameters ---------- spt - String representing the spectral type of the star. Returns ------- The value of M_V.
339,975
def get_colmap(fns, pattern, single_col=False, antipattern=False): colmap = {} for fn in fns: header = tsvreader.get_tsv_header(fn) basefn = os.path.basename(fn) cols = tsvreader.get_cols_in_file(pattern, header, single_col) if antipattern: anticols = tsvreader.g...
For table files, loops through headers and checks which column(s) match a passed pattern. Those column(s) names are returned in a map with filenames as keys
339,976
def generate_validation_function(self, uri, name): self._validation_functions_done.add(uri) self.l() with self._resolver.resolving(uri) as definition: with self.l(, name): self.generate_func_code_block(definition, , , clear_variables=True) sel...
Generate validation function for given uri with given name
339,977
def ascii_mode(enabled=True): global _backups, _chars, _primary_style, _secondary_style, _ascii_mode if not (enabled or _backups) or (enabled and _ascii_mode): return if enabled: _backups = _chars.copy(), _primary_style, _secondary_style _chars = { "primary": {"selec...
Disables color and switches to an ASCII character set if True.
339,978
def value(self): C0 = self._C0.value() C1 = self._C1.value() return kron(C0, self._GG) + kron(C1, self._I)
Covariance matrix K = C₀ ⊗ GGᵀ + C₁ ⊗ I. Returns ------- K : ndarray C₀ ⊗ GGᵀ + C₁ ⊗ I.
339,979
def condition_from_code(condcode): if condcode in __BRCONDITIONS: cond_data = __BRCONDITIONS[condcode] return {CONDCODE: condcode, CONDITION: cond_data[0], DETAILED: cond_data[1], EXACT: cond_data[2], EXACTNL: cond_data[3], ...
Get the condition name from the condition code.
339,980
def overlay_type_data(graph: BELGraph, data: Mapping[str, float], func: str, namespace: str, label: Optional[str] = None, overwrite: bool = False, impute: Optional[float] = None, ...
Overlay tabular data on the network for data that comes from an data set with identifiers that lack namespaces. For example, if you want to overlay differential gene expression data from a table, that table probably has HGNC identifiers, but no specific annotations that they are in the HGNC namespace or ...
339,981
def records(): import uuid from invenio_records.api import Record from invenio_pidstore.models import PersistentIdentifier, PIDStatus with db.session.begin_nested(): pid1 = PersistentIdentifier.create( , , object_type=, object_uuid=rec1_uuid, status=PIDStatus.R...
Load test data fixture.
339,982
def get_versions(config) -> dict: try: import bel.__version__ config["bel"]["version"] = bel.__version__.__version__ except KeyError: config["bel"] = {"version": bel.__version__.__version__} except ModuleNotFoundError: pass try: import tools.__ve...
Get versions of bel modules and tools
339,983
def current_set(self): assert self.model.KEY_FIELDS != (), "Just use model.current() if there are no KEY_FIELDS" return self.get_queryset().filter( pk__in=self._current_ids_subquery() ).annotate( is_active=models.Value(1, output_field=models.IntegerField()) ...
A queryset for the active configuration entries only. Only useful if KEY_FIELDS is set. Active means the means recent entries for each unique combination of keys. It does not necessaryily mean enbled.
339,984
def fetch(self, category=CATEGORY_BUG, from_date=DEFAULT_DATETIME): if not from_date: from_date = DEFAULT_DATETIME kwargs = {: from_date} items = super().fetch(category, **kwargs) return items
Fetch the bugs from the repository. The method retrieves, from a Bugzilla repository, the bugs updated since the given date. :param category: the category of items to fetch :param from_date: obtain bugs updated since this date :returns: a generator of bugs
339,985
def _get_final_freq(approx, m1, m2, s1z, s2z): m1kg = float(m1) * lal.MSUN_SI m2kg = float(m2) * lal.MSUN_SI return lalsimulation.SimInspiralGetFinalFreq( m1kg, m2kg, 0, 0, float(s1z), 0, 0, float(s2z), int(approx))
Wrapper of the LALSimulation function returning the final (highest) frequency for a given approximant an template parameters Parameters ---------- approx : lalsimulation approximant wrapped object e.g. lalsimulation.EOBNRv2 m1 : float-ish, i.e. castable to float First component mass...
339,986
def add_object(self, obj): if _debug: Application._debug("add_object %r", obj) object_name = obj.objectName if not object_name: raise RuntimeError("object name required") object_identifier = obj.objectIdentifier if not object_identifier: ...
Add an object to the local collection.
339,987
def make_fileitem_fileattributes(attributes, condition=, negate=False, preserve_case=False): document = search = content_type = content = attributes ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, neg...
Create a node for FileItem/FileAttributes :return: A IndicatorItem represented as an Element node
339,988
def get_biospecimen_data(tcga_id): payload = { : , "filters": json.dumps({ "op": "and", "content": [ { "op":"in", "content":{ "field":"cases.project.program.name", "v...
Get biospecimen data for a TCGA project. Parameters ---------- tcga_id : str The TCGA project ID. Returns ------- `pandas.DataFrame` The biospecmin data. Notes ----- Biospecimen data is associated with individual vials. TCGA vials correspond to portions...
339,989
def _get_current_deployment_id(self): deploymentId = stage = __salt__[](restApiId=self.restApiId, stageName=self._stage_name, **self._common_aws_args).get() if ...
Helper method to find the deployment id that the stage name is currently assocaited with.
339,990
def get_dataset_url(self, tournament=1): query = arguments = {: tournament} url = self.raw_query(query, arguments)[][] return url
Fetch url of the current dataset. Args: tournament (int, optional): ID of the tournament, defaults to 1 Returns: str: url of the current dataset Example: >>> NumerAPI().get_dataset_url() https://numerai-datasets.s3.amazonaws.com/t1/104/numerai_d...
339,991
def visit_With(self, node): withitem, = node.items context = withitem.context_expr if context.func.id == "describe": describes = context.args[0].id example_group_name = withitem.optional_vars.id return self.transform_describe(node, describes, exampl...
with describe(thing) as it: ... | v class TestThing(TestCase): ...
339,992
def count(self, **query_dict): param_dict = query_dict.copy() param_dict[] = 0 resp_dict = self._get_query(**param_dict) return resp_dict[][]
Return the number of entries that match query.
339,993
async def get(self): shepherd = self.request.app.vmshepherd data = {: {}, : shepherd.config} presets = await shepherd.preset_manager.list_presets() runtime = shepherd.runtime_manager for name in presets: preset = shepherd.preset_manager.get_preset(name) ...
Inject all preset data to Panel and Render a Home Page
339,994
def get_user_info(access_key, secret_key): u = p = dict(check_auth=1) r = requests.get(u, params=p, auth=auth.S3Auth(access_key, secret_key)) r.raise_for_status() j = r.json() if j.get(): raise AuthenticationError(j.get()) else: return j
Returns details about an Archive.org user given an IA-S3 key pair. :type access_key: str :param access_key: IA-S3 access_key to use when making the given request. :type secret_key: str :param secret_key: IA-S3 secret_key to use when making the given request.
339,995
def parse_doc(doc): if not doc: return {} out = {} for s in doc.split(): s = s.strip().split(, maxsplit=1) if len(s) == 2: out[s[0]] = s[1] return out
Parse docstrings to dict, it should look like: key: value
339,996
def unmarshal(self, value, custom_formatters=None, strict=True): if self.deprecated: warnings.warn("The schema is deprecated", DeprecationWarning) casted = self.cast(value, custom_formatters=custom_formatters, strict=strict) if casted is None and not self.required: ...
Unmarshal parameter from the value.
339,997
def relaxNGValidateDoc(self, doc): if doc is None: doc__o = None else: doc__o = doc._o ret = libxml2mod.xmlRelaxNGValidateDoc(self._o, doc__o) return ret
Validate a document tree in memory.
339,998
def QA_SU_save_etf_day(engine, client=DATABASE): engine = select_save_engine(engine) engine.QA_SU_save_etf_day(client=client)
save etf_day Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE})
339,999
def valence(self): if self.group == 18: return (np.nan, 0) L_symbols = valence = [] full_electron_config = self.full_electronic_structure for _, l_symbol, ne in full_electron_config[::-1]: l = L_symbols.lower().index(l_symbol) ...
# From full electron config obtain valence subshell # angular moment (L) and number of valence e- (v_e)