content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def converting_reactions(base): """Provide a model with a couple of converting reaction.""" a = cobra.Metabolite("atp_c", compartment="c") b = cobra.Metabolite("adp_c", compartment="c") c = cobra.Metabolite("gtp_c", compartment="c") c2 = cobra.Metabolite("gtp_e", compartment="e") c3 = cobra.Meta...
a6a4a158dd577031a613a6c70edfb266120aaf1d
3,600,112
def test_compile_too_high_bitwidth(default_compilation_configuration): """Check that the check of maximal bitwidth of intermediate data works fine.""" def function(x, y): return x + y function_parameters = { "x": EncryptedScalar(Integer(64, False)), "y": EncryptedScalar(Integer(64,...
62612b65e62fdea6b0b78a30848d9dc4251a4672
3,600,113
def reshape(x, shape, name=None): """ This operator changes the shape of ``x`` without changing its data. Some tricks exist when specifying the target shape. 1. -1 means the value of this dimension is inferred from the total element number of x and remaining dimensions. Thus one and only one dimen...
4c757d9e8d5bf649b64012dc169d349e138fc5e4
3,600,114
def calc_albedo_snow(ts, snow, dc=11.0, tc=21.9, a_ice=0.34, a_freshsnow=0.9, a_firn=0.53, **config): """ ! albedo calculated using 'time' - based on time since last snowfall(Oerlemans + Knap 1998) ! albedo = albedo output grid ! ts = time(days) since last snowfall ! snow = gr...
d29d2402e67db90afd541f358bdc8c1134a5da07
3,600,115
def normalise(X): """ here I mean make max 1 and min 0 and fit everything else in. should be by feature. X is np array returns X shame shape but normalised by feature. """ n,p = X.shape for column in range(p): X[:,column] = ((X[:,column] - np.max(X[:,column])) / (np.max(X[:,colum...
420696d9cbe689db2fdc60ba00acf248b6980038
3,600,116
import ctypes def unpack_udp_packet(packet: bytes) -> PackedLittleEndianStructure: """Convert raw UDP packet to an appropriately-typed telemetry packet. Args: packet: the contents of the UDP packet to be unpacked. Returns: The decoded packet structure. Raises: UnpackError if...
8b5d9416d4c922716e2d76116487ef1e800e5a18
3,600,117
import multiprocessing import concurrent import tqdm def Run(lines): """ Method runs the translation of graphs from g6 to lgi. Input: lines -- List with lines in g6-format Return: List with lines in lgi-format. """ num_in = len(lines) num_processes = multiprocessing.cpu_count() ...
469a2073c94108906e894b7afa5ca671a8cfbfec
3,600,118
import warnings def test_deprecate(deprecation_increment: int | None, details: str | None) -> None: """ Test the deprecation warnings/errors. If the removal_version is larger than the current, it should warn. If the removal_version is smaller or equal, it should raise an error. :param deprecatio...
43de52dddf41567d32a955ce15d6c52dff3e90dc
3,600,119
from scipy import signal def get_deimos_spec1d(fn, horne=False, smoothing=False, fixfile=True): """ Gets a reduced DEIMOS spec1d file's contents Parameters ---------- fn : str The spec1d file to load horne : bool If True, use the horne extraction, otherwise boxcar smoothin...
9a0248c838a61e582c8add51735e7042ac7e60f9
3,600,120
def edit_gallery(request, gallery_id): """ Edit an image in the gallery """ if not request.user.is_superuser: # Only superusers can edit products messages.error(request, 'Sorry, only store owners can do that.') return redirect(reverse('home')) gallery = get_object_or_404(Gallery, pk...
7681a512cfdd01c7de284a91c5d61e7294aeca34
3,600,121
def getItemUrlFromHasOfferUrl(has_offer_url): """ http://ho.lazada.vn/SH3gPd?url=http%3A%2F%2Fwww.lazada.vn%2Festar-ce390a-muc-in-laser-90a-den-238124.html%3Foffer_id%3D%7Boffer_id%7D%26affiliate_id%3D%7Baffiliate_id%7D%26offer_name%3D%7Boffer_name%7D_%7Boffer_file_id%7D%26affiliate_name%3D%7Baffiliate_name%7D%...
dd820521e8d1307f2f2570841a8fae62e4d59ae7
3,600,122
from operator import concat def ppipe(iterable, func, chunk_size=1): """Multi-core pipe.""" out = pmap(func, iterable, chunk_size) return list(concat(out))
c1b24b6305e64a0b3ec548d1154a1cc637cde053
3,600,125
def gourgou(c,R=1): """ renvoie une fonction qui donne t en fonction de r dans une métrique de E. Gourgoulhon où la particule commence à la position c et atteint un horizon des évènements en R """ return (lambda r : c - r/R - np.log(abs(r/R)))
deb52b7e7e8f5bb66ada52096ca4275f85ea1953
3,600,126
from typing import Dict from pathlib import Path def train( dataset: Dict[str, pd.DataFrame], params: str, dataset_name: str = "winequality" ) -> None: """Train a model and save it to disk Args: dataset (Dict[str, pd.DataFrame]): The train and test sets. params (Dict[str, object]): The pa...
1c8906bdf10e2142d91dab99f758c0fe708c5c2a
3,600,127
def int_type(attribute: str): """ Auto-adds an ``__int__`` using the ``__int__`` of some attribute. Used to annotate a class as being "essentially an integer". Args: attribute: The name of the attribute of this class """ def __f(self): return float(getattr(self, attribute)) ...
b58b81fb9a3201b56435a54d178aec456fce2cf0
3,600,128
import re import hashlib def auth(i): """ Input: { (web_vars_post) (web_vars_get) (web_vars_session) } Output: { return - return code = 0, if successful > 0, if error (error...
2ab5cf59a93c2926a1f3dcc92d9886a4b8d91b9c
3,600,131
def two_factor_setup(): """View function for two-factor setup. This is used both for GET to fetch forms and POST to actually set configuration (and send token). There are 3 cases for setting up: 1) initial login and application requires 2FA 2) changing existing 2FA information 3) user want...
79832821d006e94dac5b4a04350750a9f1086e76
3,600,133
def newDirectory(parent, path, name = None, owned=False, define=False): """ Creates a new Directory location :type parent: location :param parent: parent location :type path: string :param path: the path for this directory (name of directory) :type name: string :param nam...
3cf16f1256c8af79ef242d2e5fb7703f4f2ef91c
3,600,134
import logging def evaluate_sensitivity (dataset,subgroup,targetColumn): """Returns the Sensitivity of a subgroup.""" #Get confusion matrix cf = confusion_matrix(dataset,subgroup,targetColumn) #Calculate sensitivity sensitivity = cf[0][0] / (cf[0][0] + cf [0][1]) logging.info('Sensitivity...
c0e687f26712458619a5508d45a91bcc5c949030
3,600,136
import urllib import json def boshio_release_to_source(resource): """Look up the github source for a given bosh release Args: resource (dict): A bosh-io-release resource from a concourse pipeline Returns: tuple(str, str): The url to the repo, and the branch """ bosh_api_url = "h...
d9f40fcb56d9b3f08e570f38d519390f91789d26
3,600,137
def string_empty(string): """Return True if the input string is None or whitespace.""" return (string is None) or not (string and string.strip())
fddb1e639a57b29674ce6d0a101e875272731d77
3,600,138
from nautilus import models def MockModel(name='TestModel'): """ This function returns a nautilus model to use throughout the test suite. """ # local imports # return the mocked model return type(name, (models.BaseModel,), { 'name': models.fields.CharField(null=True), 'da...
ebfa5aa5e8624ed75137b15a04330a4efe26e226
3,600,139
import itertools def get_hoi_dataset_dicts(dataset_names, filter_empty=True): """ Load and prepare dataset dicts for HOI detection. Args: dataset_names (list[str]): a list of dataset names filter_empty (bool): whether to filter out images without instance annotations min_keypoints...
db6006f9360a00db5437346f57df0bcde84b856f
3,600,140
def memoize(user_function): """Memoization decorator for user function of 1+ parameters""" class Memodict(dict): """Memoization performs user function call on dict miss""" def __getitem__(self, *key): return dict.__getitem__(self, key) def __missing__(self, key): ...
e8f59f5e4460e332ff88bb235a6d8beb31065de2
3,600,141
import google.auth.compute_engine as google_auth_gce def IsGceAccountCredentials(cred): """Checks if the credential is a Compute Engine service account credential.""" # Import only when necessary to decrease the startup time. Move it to # global once google-auth is ready to replace oauth2client. # pylint: dis...
2b3b4331d5dbdc7c2dc9b049376386803d87c70c
3,600,142
import urllib def google_search(query, resultsToRetrieve, userAgent, sleepDelay=1): """ perform google search and handle exceptions """ try: search_results = search(query, stop=resultsToRetrieve, user_agent=get_random_user_agent()) #search_results = ["test result 1","test result 2"] if search_results != Non...
b51b1f6deaac6449ab19ca29b470897704dab982
3,600,143
def Dic_Test_Empty_Dic(indic): """ check if indic is a (nested) empty dictionary. """ if indic.keys()!=[]: for key,keydata in indic.items(): if isinstance(keydata,dict): if keydata=={}: pass else: return Dic_Test...
360e9190fd6ab23fb1d8b4d948647baed494f417
3,600,144
def _new_package_name(src,volume,src_chimera_file): """ return package file name src=/pnfs_path/<old_volume>/<package> to /pnfs_path/<volume>/<package> @type src: str @param src: source package full path @type volume: str @param volume: destination volume name ...
5078ddc562d1af65db4ef4277c8121c7e7abccd7
3,600,145
def session_factory(connection): """ pytest対象モジュールの引数に"session_factory"を指定すると、 このfixtureが実行され、データベースの初期化を行った上でSQLAlchemyのscoped_sessionを返します。 1つのモジュール内(pyファイル)から複数回使用された場合でも、データベースの初期化処理が行われるのは 各モジュールあたり最初の一回だけです。 """ engine = create_engine(connection) session_factory = sessionmaker(bind=eng...
296d153f72a5eadf93c46015f36c1533c78c9b0a
3,600,146
def choose_OD(pos_OD, OD_no): """Chooses nodes for OD matrix according to their population size stochastically and probabilistically Args: pos_OD (list): a list of tuples representing the nodes and their population OD_no (int): Number of OD pairs to create Returns: OD_nodes [list]...
4df8f454eb436340d818fdd3923ebab3fac2f7bb
3,600,147
def nplml(theta, X, y, kernel, nugget=1e-10): """Compute the log marginal likelihood using numpy default solve (slower than cholesky)""" kernel_clone = kernel.clone_with_theta(theta) K = kernel_clone(X) K[np.diag_indices_from(K)] += nugget alpha = npsolve(K, y) # Compute log-likelihood (compare ...
6fc5a6a662138218dcb2ba64bd6c41a1f74e08de
3,600,148
def group_pairs(pairs, ret_dict=True): """ Taken from first example in https://docs.python.org/3/library/collections.html#defaultdict-examples :param ret_dict: :param pairs: :return: """ groups_dict = defaultdict(list) for key, val in pairs: groups_dict[key].append(val) if r...
93837dfb583d35547ae9baa8d9618186b2465606
3,600,149
def start_day_accept_order(): """ Получает день недели (0 - 7) с которого разрешён приём заказов. Переносит разрешаемый день на 1 один день вперёд, если текущее время больше, чем разрешённое для совершения заказа. Returns: int: `0 - 7`, то есть от понедельника до следующего понедельника. ...
a85487952c9ae65803507adcfaf86da98e9a34d8
3,600,150
def load_and_resize_image(img_path): """ Creates a tkinter image variable that can be displayed on GUI This function receives a filename as a parameter. This should be the name of a file containing a digital image. The file is first open and stored as a Pillow image file. It uses the Image.size prope...
d3cba268b50a1f4e439f251ae11f27213f9f122b
3,600,152
def peak_assignment(unknownhdf5_filename, key, knownhdf5_filename, external_peak_labels, precision=10, externallabelinput=True, plot=True): """ This function is a wrapper function from which all classification of peaks occurs. Parame...
43567b3065348116184a809cf7cccfc1b3ccdb65
3,600,155
import textwrap def make_settings(pypirc): """Returns a factory function for settings.Settings with defaults.""" default_pypirc = """ [pypi] username:foo password:bar """ def _settings(pypirc_text=default_pypirc, **settings_kwargs): pypirc.write(textwrap.dedent(pypirc...
48a694173a1fe97b621909525bf2681e08140bcb
3,600,156
def kernels(ell, cs, eig, D, A, G=DEFAULT_G, alpha=None): """Returns the density and squared sound speed kernels. I have tried to make this as notationally similar to Gough & Thompson (1991) as possible. The kernels are normalized to have unit integrals over the radius *r*. Parameters ...
d73a243a1e866cb28afc77af777648292c530fcb
3,600,157
def zonal_levels_trend(ds): """ calculated trend for depth-lat_bin field input: ds .. xr Dataset ds.OHC_zonal_levels [J m^-2] output: trend .. xr DataArray containing trends of OHC [J m^-2 year^-1] """ assert 'OHC_zonal_levels' in ds dn = ('TLAT_bins', 'z_t'...
9e98a38a8683f0e11bda8322475ed168539d2be8
3,600,159
def ignore_unique(f, decorated_obj, args, kwargs): """ Ignores exceptions caused by unique constraints or indexes in the wrapped function. 'ncm' = non class method (version) """ dbsess = _find_sa_sess(decorated_obj) try: return f(*args, **kwargs) except Exception as ...
312b60527b2672cfdf94b7b0a78cf471dea3651e
3,600,160
def sell(): """Sell shares of stock""" if request.method == "POST": # ensure symbol was submitted if not request.form.get("symbol"): return apology("must provide symbol", 403) # ensure no. of shares was submitted elif not request.form.get("shares"): retu...
b83234407761942d0fb7ce74a83b75bcde4358b7
3,600,161
import imghdr def detect_image_type(filename): """ 获取图像文件类型 :param filename: :return: jpge|png|gif|tiff等。失败返回None """ return imghdr.what(filename)
a4701aa60927e730899ed8036d6f2d875aa0524a
3,600,162
from .motor_joint import Motor def motor(shape1, speed=5): """Creates a constant rotation of the given shape around its center point. The direction of rotation is controlled by the sign of the speed. Positive speed is clockwise, negative speed is counter-clockwise. :param shape1: The shape to c...
4ba4b2b2439ebadf7ffdb8e9b8ee7c35bc3e0ce4
3,600,163
def build_stream(df,h5,line, wftype, filt, freq_min, freq_max): """ Build the Streams from events data in counts saved in hdf5 files as np.array line : integer, line number of the hdf5 File to plot wftype : str, waveform type 'ev_c', 'ev_gm' or 'noise' for events in counts, events in ground motion unit...
f78c58179d80e00b0841fe3539eda920c92d096c
3,600,165
def allowed_file(filename): """Checks if the extension of the given file is in ALLOWED_EXTENSIONS""" return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
f9d0bf2d2f9f3155bb04a499f78828126046568a
3,600,166
def english_to_french(english_text): """english to French translation""" translation= language_translator.translate(text=english_text, model_id="en-fr").get_result() french_text=translation['translations'][0]['translation'] return french_text
141fbd5eeed94cd8ec612e6483a711d1c2e6630f
3,600,167
def square_error(P, R, Γ, v): """Square error (SE), the combination of squared bias and the variance.""" bias = value_error(P, R, Γ, v) variance = sobel_variance(P, R, Γ) return variance + bias ** 2
cb7e3b4cad6b23f50a7f51433146ac30085292d0
3,600,168
import copy def build_sac_model( policy: Policy, obs_space: gym.spaces.Space, action_space: gym.spaces.Space, config: AlgorithmConfigDict, ) -> ModelV2: """Constructs the necessary ModelV2 for the Policy and returns it. Args: policy: The TFPolicy that will use the models. obs_...
4edf4947d472fe5c3e163ad9ac963f145cf7ac86
3,600,169
def multiscan_file(file): """Deprecated API - use one of the Clamd*Socket classes instead.""" return socketinst.multiscan_file(file)
c9d175d44ce2d6aa63c2533adc5a893ede035ac7
3,600,170
def update_ports_tree(ports_tree): """ Updates the ports tree, either the default or the `ports_tree` specified CLI Example: .. code-block:: bash salt '*' poudriere.update_ports_tree staging """ _check_config_exists() if ports_tree: cmd = "poudriere ports -u -p {}".format(...
fc50e6209a6c53bde236d23f762614f0f7c69865
3,600,171
import numpy as np import tensorflow as tf import torch import random def apply_seed(seed=None): """Applies a global random seed to the application state. In particular, the method seeds Python's random module and numpy, tensorflow and pytorch packages if available. Arguments: seed: Int|None, the ra...
f7f4a9bc87fbc156482491611b557299c44b73a4
3,600,172
from typing import List from typing import Tuple def calculate_coefficients(data_points: List[List[float]]) -> Tuple[int]: """Calculate coefficients for an approximate linear mapping of batch size to inference time. Uses ordinary least squares to find the coefficients alpha and beta in the following: inf...
4ab279e3c72ab41b2273cf584a9c66b6a2de00e9
3,600,173
def news_review(): """ 需审核新闻页面显示 :return: """ page = request.args.get("page", 1) keywords = request.args.get("keywords", "") try: page = int(page) except Exception as e: current_app.logger.error(e) page = 1 news_list = [] current_page = 1 total_page ...
792afdcdb8aea002bb6c1eb9e47d3dfbbaeac3d1
3,600,174
def format_link_mutation(mutationname: str, identifier_1: str, identifier_2: str): """Create a mutation with link between two identifiers to send to the Contributor Environment. Arguments: mutationname: the name of the mutation to generate identifier_1: The unique identifier of the first object....
f9cfe5fad253872312a60bebb372ca1c723231d3
3,600,175
def model_to_request_body(body_model, content_type, body_model_root_element=None): """ Convert a Python dict (body model) to XML or JSON :param body_model: Model to be parsed. This model should have a root element. :param content_type: Target representation (Content-Type header value) :param body_mo...
6d2310b8a35bb108bec6f43ad4bc4ba5d7ba0bb5
3,600,176
def _get_ext_net_obj(ctx, name): """Returns ExternalNetwork object.""" platform = _get_platform(ctx) client = ctx.obj['client'] return ExternalNetwork( client, resource=platform.get_external_network(name))
994a55c06e20271b5da6b95eb36dc54f225f6346
3,600,177
from typing import List import torch from typing import Tuple def to_bi_tgt_out( tokens: List[List[int]], device: torch.device ) -> Tuple[LongTensor, LongTensor]: """Generate bidirection tgt and out Parameters ---------- tokens : List[List[int]] indices: [b, l] device : torch.device ...
c6440c7a7e8883275053e6686b735635252c9776
3,600,178
import json def to_formatted_json(output): """Output is a single record""" return f"{json.dumps(output, indent=4)}\n"
e437c8b34e510f6a72cc27ccb7b2a14c3f60e09d
3,600,179
def _permutation_worker(k: int, items: list) -> list: """The kth Johnson-Trotter permutation of all items.""" n = len(items) if n <= 1: return items else: group = k // n item = k % n position = n - item - 1 if group % 2 == 0 else item dummy = _permutation_worker(g...
c997721d2682a9bf54b42596b093956bc17cf94b
3,600,180
def getCoeffs(airfoilCode, alphaDeg): """ Calculates CL and CM at alphaDeg for NACA 4,5-digit airfoil """ if checkAirfoilType(airfoilCode) == 'NACA4': th, x, y, dy = getNACA4(airfoilCode, _nPoints) elif checkAirfoilType(airfoilCode) == 'NACA5': th, x, y, dy = getNACA5(airfoilCode, _nPoints) ...
3776fe4ae53724a86a5e13171d5e04b50c95e1a7
3,600,181
def matrix_vector_elementwise_multiply(data, multiplier, axis=None): """Elementwise multiply a matrix by a vector. Parameters ---------- data : array-like, shape=[n_samples, n_features] Input data multiplier : array-like, shape=[n_samples, 1] or [1, n_features] Vector by which to mu...
7094d2a77875a1cebe3844fb7d35c6a0524edac5
3,600,182
def vectorize_abc(df): """ takes an abc string and returns the note vector and timing vector, split by bars """ abc_string = df['abc'] accs, mod = get_sharps_or_flats(df['mode']) note_out = [] time_out = [] for bar in split_by_bar(abc_string): note, time = vectorize_bar(bar, acc...
10e26130f21c9ddab0397155f8ea5636bf5947b7
3,600,183
def update_config_value_by_config(config_to_update, config): """Update config_to_update according to config Example: Arguments: config_to_update: { "a": "b", "c": { "d": "e", "f": "g", }, } ...
f99366f7b434fa0c47bfc279cbd04d3b4e4d0af9
3,600,184
def tiny_vgg_p3(cfg, i=3, batch_norm=False): """This function is derived from torchvision VGG make_layers() https://github.com/pytorch/vision/blob/master/torchvision/models/vgg.py""" layers = [] in_channels = i for v in cfg: if v == 'M': layers += [nn.MaxPool2d(kernel_size=2, str...
7e2647a903fd57025f8888bc6a0d647fb2dc3ed2
3,600,185
def delete_versioned_object(connection, bucket_name, obj): """ Perform a delete on a versioned object, the requirements for these types of requests is to be able to pass the ``versionID`` as a query argument """ # if obj.delete_marker is False we should not delete this and we shouldn't # have be...
2ab191efd907f814af505b52a6f2a571ef9df036
3,600,186
def list_attributes(msg_type): """List all attributes with type description of a GRPC Message class.""" return [(f.name, get_field_description(f)) for f in msg_type.fields]
99cdcaa22672c129b3fd23ec17952a50cc755fbd
3,600,187
import sqlite3 def create_connection(db_file): """ create a database connection to the SQLite database specified by db_file """ return sqlite3.connect(db_file)
4f134ebcf1d6cac0905e7966717c53a51df9902d
3,600,188
from typing import Tuple from typing import Callable def compose(*args: Tuple[Callable[[np.ndarray], np.ndarray]]) -> Callable[[np.ndarray], np.ndarray]: """composes given mappings """ assert len(args) > 0, 'Function compose requires at least one mapping as its parameter.' def _t(x: np.ndarray) -> np...
fa5e0a559b3ca5d0b85e96c4cf113bfd537bd502
3,600,189
def dot(q1,q2): """ Dot product of two quaternions >>> import qmathcore >>> a = qmathcore.quaternion('1+2i-2k') >>> b = qmathcore.quaternion('3-2i+8j') >>> qmathcore.dot(a,b) -1.0 """ Q1 = quaternion(q1) Q2 = quaternion(q2) return np.dot(Q1.q,Q2.q)
fb6a69c5715e53a8875cb83356b5828d38656f00
3,600,190
from typing import Dict def _results_data_row(row: Dict[str, str]): """ Transform the keys of each CSV row. If the CSV headers change, this will make a single place to fix it. """ return { "k": row["Key"], "v": row["Content"], }
97dc7f9842d7e6a564cbe66fd93e3dbaeca08517
3,600,191
import random def _trial_greedy_ssa_path_and_cost(r, inputs, output, size_dict, choose_fn, cost_fn): """A single, repeatable, greedy trial run. Returns ``ssa_path`` and cost. """ if r == 0: # always start with the standard greedy approach choose_fn = None else: random.seed(r) ...
c4dc7e311fe9bb377e548136d57c20a560ce06e2
3,600,192
def to_border_vtxfaces(components): """ [pm] """ if not components: return components if isinstance(components, list): pn = not is_string(components[0]) else: pn = not is_string(components) faces = to_face(components) inner_vf = to_vtxface(faces) border_vertices...
149626d156721b16df4e721c4cfd6b73955cb092
3,600,193
import logging def export_campaigns(api, assessment_id): """Add all the campaigns' data for an assessment to a list. Args: api (Gophish API): Connection to Gophish server via the API. assessment_id (string): Assessment identifier to get campaigns from. Returns: List of the assess...
69adc946cfc9dba1b4b87298fbbd0f9652d2b043
3,600,194
def build_cross_entropy_loss(logits, gold): """Constructs a cross entropy from logits and one-hot encoded gold labels. Supports skipping rows where the gold label is the magic -1 value. Args: logits: float Tensor of scores. gold: int Tensor of one-hot labels. Returns: cost, correct, total: the to...
192c09d334f3c155c9b0f6e3b78358468de86bb8
3,600,195
def wilcoxon_sgned_rank(ds1, ds2, alpha=0.05): """ is a non-parametric statistical hypothesis test used to compare two related samples, matched samples, or repeated measurements on a single sample to assess whether their population mean ranks differ (i.e. it is a paired difference test). """ ...
c455967fd915466761dc45517200779d5cecd0b1
3,600,196
def to_weight(df: pd.DataFrame, renorm=True): """ Converts molar quantities to mass quantities of the same order. Parameters ----------- df : :class:`pandas.DataFrame` Dataframe to transform. renorm : :class:`bool`, :code:`True` Whether to renormalise the dataframe after convert...
e4c50667ca44e12767d501c07aff00eb7bdec59b
3,600,198
def address_from_public_key(pubkey: bytes) -> str: """Extracts public key from an address Ripple address is in format: <1-byte ripple flag> <20-bytes account id> <4-bytes dSHA-256 checksum> - 1-byte flag is 0x00 which is 'r' (Ripple uses its own base58 alphabet) - 20-bytes account id is a ripemd16...
b8b56dce86239e270ea856c4a1ea75d1b9b305bd
3,600,199
def uploadcomentario(request): """Essa função carrega o arquivo do cliente É chamada pelo cliente(específico) enviar o arquivo/comentario para o funcionário""" context = {} if request.method == "POST": uploaded_file = request.FILES["document"] fs = FileSystemStorage() ...
04f701a73119f82fdc9e281e3c995dae8263b3fe
3,600,201
from typing import Tuple def spectrum_linear_fit( spec: Spectrum, wl_low: float = None, wl_high: float = None ) -> Tuple[ float, float ]: """ Applies a linear fit to a Specturm over the specified wavelength range. If no wl_ values are passed, the entirely of the spectrum range is used. Returns a...
ffd4ffb2f4e274e0a422ac4f7787d2606eb918ad
3,600,203
def qats_prediction(poly_coeffs, order, lambda_values): """Quantum alchemy predictions using a nth-order Taylor series. Parameters ---------- poly_coeffs : :obj:`numpy.ndarray` Polynomial coefficients in increasing order (e.g., zeroth, first, second, etc.). order :obj:`int` ...
7be48a28153827fd3beb4976583352099e356987
3,600,204
def is_odd(self, allow_rescaling_flag=True): """ Returns true iff after rescaling by some appropriate factor, the form represents some odd integers. For more details, see parity(). Requires that Q is defined over `ZZ`. EXAMPLES:: sage: Q = QuadraticForm(ZZ, 2, [1, 0, 1]) sage: Q....
3e9465a19c2ad91a024b8358d27693573c620d8d
3,600,205
def _embedding_dimension_correlation(signal, dimension_seq, delay=1, **kwargs): """Return the Correlation Dimension (CD) for a all d in dimension_seq.""" CDs = np.zeros(len(dimension_seq)) for i, d in enumerate(dimension_seq): CDs[i] = fractal_correlation(signal, dimension=d, delay=delay, **kwargs)[...
1c12e8c4a2a0121d562b6ead93d27f1971e73417
3,600,206
def evaluate_body_part_of_response(body_combine_response, body, body_toggle): """ Evaluate the body part of combine response """ tag = globe.config.body.non_priority_start + globe.config.body.non_priority_end body_test_cases = [] if body_toggle == 'indexes': body_test_cases = body_combine_respon...
34faa27bea6bc27d9f8d7d757ea5dd76250e4d7c
3,600,207
def find_related(item, item_type, related_type, address): """Returns a list of the entities of related_type which share a datastream with item""" datastreams = related_datastreams(item['@iot.id'], item_type, address) result = [] for related_datastream in datastreams: related_result = get_entitie...
9931812bf66330d5203bc9a1b06644811fc37f1e
3,600,208
def getTasksets(config): """ Load task sets from xml Return: list of names of task sets """ xml = etree.parse(config) return [tag.attrib['name'] for tag in xml.findall('//tasks')]
b23269659471b9bec39495be36698bf868e24036
3,600,209
def do_eval(dataset=None, network=None, num_class=2, assessment_method="accuracy", load_checkpoint_path=""): """ do eval """ if load_checkpoint_path == "": raise ValueError("Finetune model missed, evaluation task must load finetune model!") net_for_pretraining = network(albert_net_cfg, False, num_cl...
29a0053d9e7f71ebd2afe831e98c426355361d0b
3,600,210
import time def query_view(): """GET/POST HTTP handler for query route""" if request.method == 'POST': start = time.time() query = request.form['query'] customer_id = request.form['customer-id'] page = int(request.form['page']) df = services.run_query_to_df(customer_i...
d08e3bb7899bbdf858d7f210c4d3dd64ee0d594f
3,600,211
def _construct_url(resource, action, params=None): """ Constructs rest of API url based on resource, action and parameters. Multiple parameters must be a list. Single parameters must be a single string Internal usage """ final_url = '{}/{}'.format(resource, action) if type(params) == ...
38b85a4400e362887f965c0035b3a2b10e7ecce4
3,600,212
def _predict(model, data, proba=False, dtype=np.float32, **kwargs): """Inner predict routine. Parameters ---------- model : data : dask array of shape = [n_samples, n_features] Input feature matrix. proba : bool Should method return results of predict_proba (proba == True) or pr...
1fd2c86660c56bb148b15c407ced4c17e67a9990
3,600,213
def expm1(x): """! @brief exponential - 1.0 helper """ return np.exp(x, dtype=np.longdouble) - 1.0
bb4754a50891320ea1b7116604e5ff72422667e2
3,600,214
from typing import List def _split_inputs(inputs: str, named_groups: dict) -> List[str]: """ Identify and split inputs for torch operations. This assumes that no quotes, apostrophes, or braces show up in the operation string. Currently, items in lists that are not within functions will be broken up in...
5edc3c53fb9b7a19557504335eb04eb15dd3c932
3,600,215
def plot_chl(ax, val, zeta=None, v=None, num_levels=21, cmap=DIFF_r, title='', ssh_range=np.linspace(-0.05, 0.05, 11)): """ The function plots 2D data (originating from composites, e.g. surface chl) and configures the figure accordingly. """ # levels for ssh levels = ssh_range # init vmin and vmax vmin, vmax = N...
f9266e8224d39ae9816a4f3304ed0ea64bf91f55
3,600,216
def autoenv_settings(prefix='AES'): """ Example with aes prefix and kwargs: { "mail.password": "1234567", "mail.username": "marcelomoraes", "mail.host": "smtp.pyramid.com" } environment: AES_MAIL_PASSWORD=foobar :return { "mail.password": ...
c36d6193b3db8f4b73e8a5e61df6599df470108a
3,600,217
def get_analysis_file(filename: str) -> str: """ :param filename: The name of the file containing the source code. :return: The expected name of the file containing the analysis. """ return filename.rsplit('.', 1)[0] + '.ll.cm'
6a147b5bf69078dde81fdc72585907ece6c2f461
3,600,218
def fmt_type_name(data_type): """ Returns the JSDoc name for the given data type. (Does not attempt to enumerate subtypes.) """ if is_user_defined_type(data_type): return fmt_pascal('%s%s' % (data_type.namespace.name, data_type.name)) else: fmted_type = _base_type_table.get(data_...
947d676e20bd5f441a5c38394f46e9ab310b083c
3,600,219
def mersenne_prime(n: int) -> int: """ Returns the nth Mersenne prime. Conditions: 1) n > 0 :param n: natural number :return: the nth Mersenne prime """ p = [2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937...
b93d495a3f4fac750b9c817ba6b742c6600f6845
3,600,220
import sqlite3 def delete_user(lid: str) -> bool: """ 从user_list移除监听对象(注意: 该函数不用于群订阅操作) :param lid: 愿望单url中的lid, 可以为唯一标识一个Amazon账号开设的愿望单 """ with sqlite3.connect(DB_PATH) as connection: success = False cursor = connection.cursor() # 查看主表中是否已有记录 user_exist = cursor.e...
6def29ce0526bf59687187e157b15e1e452f59f8
3,600,221
def load_schema(schema_path): """ """ with open(schema_path) as yaml_file: """ Get the path of the CommonwWorkflowLanguage schema and return a list of DICT """ schema_list = ryaml.load(yaml_file, Loader=ryaml.Loader) return schema_list
9b24a34a5280892fa5c73e04f40bb6dbd03ae50b
3,600,222
def cutoutbbox(image,psf,cat): """ Get image cutout that covers that catalog of stars.""" ny,nx = image.shape hpsfpix = psf.npix//2 xmin = np.min(cat['x']) xmax = np.max(cat['x']) ymin = np.min(cat['y']) ymax = np.max(cat['y']) xlo = np.maximum(int(np.round(xmin)-hpsfpix),0) xhi...
fcb6e5889560d88a0b3745f9d185d30d2997374a
3,600,223
def wsgi_xmlrpc_1(environ, start_response): """ The main OpenERP WSGI handler.""" if environ['REQUEST_METHOD'] == 'POST' and environ['PATH_INFO'].startswith(XML_RPC_PATH_1): length = int(environ['CONTENT_LENGTH']) data = environ['wsgi.input'].read(length) params, method = xmlrpclib.load...
d8703d2406e91553d0c78a22770c13038d15c192
3,600,225
def _prep_server_detail(compute_client, image_client, server): """Prepare the detailed server dict for printing :param compute_client: a compute client instance :param server: a Server resource :rtype: a dict of server details """ info = server._info.copy() server = utils.find_resource(com...
04200ff1e0d28d358ebbc77c606091787cc062ee
3,600,226