content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_key_from_insecure_cbc(encryption_oracle): """Recovers the key from the lazy encryption oracle using the key also as iv. The approach used is the simple one outlined in the challenge description. """ block_length = find_block_length(encryption_oracle.encrypt) prefix_length = find_prefix_lengt...
1d5e087b0bb93fddb72ccba40bd2c5a5482d376d
48,888
def mises_pari_rembourse_si_perdant(cotes, mise_max, rang=-1, remb_freebet=False, taux_remboursement=1, output=False): """ Calcule les mises lorsque l'un des paris est rembourse. Par defaut, la mise remboursee est placee sur la cote la plus haute et le remboursement e...
d3bff4e8187a666d6b8869bb39dd28f1f32d8c36
48,889
import collections def sort_2GX(*msg): """ Route T-Stick messages for T-Stick #015. """ if msg[0] == 0: return False elif msg[0] == 1: named_return = collections.namedtuple('tstick_sensor', 'rawcapsense') rawcapsense = msg[1:] return named_return(list(rawcapsense)) ...
291812e80e12ca6da5cec9afb43cc741cced156d
48,890
import io, csv def export_tweets(): """ Export all results as CSV file from the latest tweet. :param limit: limit the number of result to be returned """ @copy_current_request_context def generate(): output = io.StringIO() writer = csv.DictWriter(output, dialect='unix', fiel...
591800f25457142eec550c7ca264abad303ae2be
48,891
def read_double(fid, count=1): """ Read 64bit float from bti file """ return _unpack_simple(fid, '>' + ('d' * count), count)
5b21cd58ee74532c8c70d71b662b5cc5761a5bf6
48,892
import time def is_rover_in_perpetual_loop(Rover): """ Check to see if rover is is in perpetual loop Inputs: Rover (Rover object) Returns: bool statement of the sign uniformity of the latest Rover steers """ if Rover.angling_towards_sample_start_time and not Rover.approaching_s...
aa94810c9d962f453a1353d62a0af3c16ea5f637
48,893
def gdf_geom_clip(gdf_in, clip_geom): """Filter a dataframe to contain only features within a clipping geometry Parameters --------- gdf_in geopandas dataframe to be clipped in province_geom shapely geometry of province for what we do the calculation Returns ------- fil...
6c3ef364b25474aee42cf8894f83983caffce505
48,895
def getAnm(P, mstr, Bmat, findmin, findmax, Ndec): """ Return the (N+1)^2-element list containing SHDs of STFTs :param P: STFTs of the M channels of recordings :param mstr: Dict containing the microphone array properties :param Bmat: List of response equalisation matrices :param findmin: Index ...
2d2278d02168dc45b50f8aa27fc7ccd034444d5d
48,896
def _(message, *_): """ NOOP implementation of sphinx.locale.get_translation shortcut. """ return message
faf850b4bd49141b28b39debffb4e284ddc0d4d3
48,897
import random import colorsys def random_color_hsv(): """random a hex color, only random h value to get a brighter color""" h, s, v = random.random(), 1, 1 float_rgb = colorsys.hsv_to_rgb(h, s, v) return convert_rgb([int(x * 255) for x in float_rgb])
15dda41912caff17e86e3adfa410b5dce1f38630
48,898
from typing import Callable from re import S from re import T from typing import Optional def optional(f: Callable[[S], T], x: Optional[S]) -> Optional[T]: """Apply ``f`` to ``x`` if ``x`` is not ``None``.""" if x is None: return None return f(x)
07587950ef738164906bfb0b19622c6cb24f3fe4
48,899
def pdist(x, y, z, index, dmax=8.0): """ Pairwise distance computation for points in cartesian space. Does return distance vectors. """ dmax2 = dmax**2 m = len(x) n = m*(m - 1)//2 dx = np.empty((n, ), dtype=np.float64) dy = dx.copy() dz = dx.copy() dr = dx.copy() atom0 =...
fcb12aea28e980783270a2eb69698b1bbb68c94d
48,901
def ss(inlist): """ Squares each value in the passed list, adds up these squares and returns the result. Usage: lss(inlist) """ ss = 0 for item in inlist: ss = ss + item * item return ss
3760d84641178d836d2b62a5377dfa09e2861e40
48,902
def make_pre_build_hook(extra_compiler_config_params): """Return a pre-build hook function for C++ builders. When called, during graph build, it computes and stores the compiler-config object on the target, as well as adding it to the internal_dict prop for hashing purposes. """ def pre_build_...
2f45d1702c073a29451fed6efc6a266fe264a41d
48,903
def melfrequencies_mel_filterbank( num_bands, freq_min, freq_max, num_fft_bands ): """Returns centerfrequencies and band edges for a mel filter bank Parameters ---------- num_bands : int Number of mel bands. freq_min : scalar Minimum frequency for the first band. freq_max : s...
84b6583dfbe80dc258ee6d7d532ff9d6362640ca
48,904
def get_commit_link(repo_name: str, commit_sha: str) -> str: """ Build a commit URL for manual browser access using full repository name and commit SHA1 :param repo_name: full repository name (i.e. `{username}/{repoanme}`) :param commit_sha: 40 byte SHA1 for a commit :return: A commit URL """ ...
a1cf8d30f3e5c5ce3c5fefc719cca7c1c4d92331
48,905
import string import random def create_short_link(db: Session, link: schemas.ShortLink): """Create and add a new short link """ chars = string.ascii_letters + string.digits random_string = ''.join(random.choice(chars) for i in range(8)) new_short_link = models.ShortLink( short_link_path =...
476e160cddcb5553ee045b2204c36d624b1f1fc5
48,906
def username(user_id): """ Find the user name associated to a user ID. """ return UserIndex.instance().username(user_id)
085c56ddd9cf3ffe44d51c7a2576d02617ab948d
48,908
def get_sqr_levels(): """Get the sawtooth levels and take out the even harmonics to get square levels.""" saw_levels = get_saw_levels() levels = [] for i in range(len(saw_levels)): n = i + 1 level = saw_levels[n] if n % 2 != 0 else 0 levels.append(level) return levels
cc57c8c66440550bea525920dd85fab520ea1550
48,909
def load_temporal_statistics(keys): """Load statistical features of the lifted data, computed over the temporal domain at each spatial point. Parameters ---------- keys : list(str) Which data set(s) to load. Options: * {var}_min : minimum of variable var * {var}_max : maximu...
8dd61e54352607f0fd80bf0a4d7f18360caa562f
48,910
import re def parse_gpu_info_lines(gpu_lines): """Parses the gpu info from 2 lines cut out from the nvidia-smi result. Args: gpu_lines (list of strings): Two nvidi-smi lines representing current gpu info. Returns: Tuple: Gpu id ('gpuX') and a dict with gpu info. """ gpu_id = 'gp...
689eae75e2000f6ee0189cd3fdac16d1bd7149a4
48,911
from typing import Iterable from typing import Dict from typing import List import pprint import json def submit_batch_detection_api(images_to_detect: Iterable[str], task_lists_dir: str, detector_version: str, account: str, ...
97960a093960127917436c8e66a2afa3129a17e1
48,913
def fill_between_angle(arr, s, e, center=None, is_radian=True): """Fill Between ``s`` and ``e``. Args: arr (np.ndarray) : Input array. s (Number) : Start angle of fill. e (Number) : End angle of fill. center (tuple) : Center coor...
61f2d234d071c0b29e14f87d42046db5307d8dcb
48,914
from dexbot.strategies.external_feeds.price_feed import PriceFeed def test_get_external_market_center_price(monkeypatch, ro_worker): """ Simply test if get_external_market_center_price does correct proxying to PriceFeed class """ def mocked_cp(*args): return 1 monkeypatch.setattr(PriceFeed,...
84cbb0fed8187e9f070643b981e3f6c71430f7fd
48,917
def _get_submodel(model, name): """ Return the first occurence of a sub-model. Search is performed by model name. """ if not isinstance(model, CompoundModel): return model if model.name == name else None for m in model.traverse_postorder(): if m.name == name: return ...
e2c72ad0cac949ed89b04e448ca20f4445ea190d
48,919
def to_ascii(x): """ Converts a 0-indexed integer to the corresponding Excel-style column name """ x += 1 result = [] while x: x, rem = divmod(x-1, 26) result[:0] = ascii_uppercase[rem] return ''.join(result)
16c44817b60034fb0600fcb55ef583412f05c6ba
48,921
def step(stripped, pos, prev): """ Move along the path one or two steps (if ducking under), at location pos, and previous given. Return new location, plus the number of steps (1 or 2) that was taken. """ (x, y) = pos tile = stripped[pos] dx, dy, steps = direction(pos, prev) if tile == "...
26f38e9010d1189aa3b8a9c25c5e1337b665f5f8
48,922
def validate_actions(data): """ Validate an Action configuration dictionary, as imported from actions.yml, for example. The method returns a validated and sanitized configuration dictionary. :arg data: The configuration dictionary :rtype: dict """ # data is the ENTIRE schema... cle...
327c90b0a02efb5148f5486a2a07eb962070cf5c
48,924
def load_model_from_tarball_stream( tarball_stream, gpg_home_dir=None, run_model_validation=True ) -> SerializableModel: """Load a model from a tarball stream Args: tarball_stream: a readable stream gpg_home_dir: home directory for gpg to verify signed model (e.g. path/to/.gnupg) ...
68fff3882029e05a24a516d84e14a2b8d5d3820e
48,925
def TChA_LoadTxt(*args): """ TChA_LoadTxt(PSIn const & SIn, TChA ChA) Parameters: SIn: PSIn const & ChA: TChA & """ return _snap.TChA_LoadTxt(*args)
de1e91f11ae4ce4206cb0ac3e09fb9b98e370ede
48,926
from pathlib import Path def init_default_parser() -> ArgumentParser: """Creates the default argument parser. :returns: an ArgumentParser with the default options. """ version = "1.1.0" parser = ArgumentParser() parser.add_argument( "target_path", help="path to the xml fi...
e62fd60e5a735c1ce98f58dceff976b18b8d271d
48,927
def msi_file_finder(pth): """ Return True if pth represents a msi file file. """ return bool(pth.fname.endswith('.msi.txt'))
35c0d0dac72d44cbdd6f87b280a70917d264db0c
48,928
from typing import List from typing import Dict def get_flat_tree(dependencies: List, package_map: Dict[str, str]) -> Dict: """Parse yarn list json dependencies and add them locked version Example: { "package@1.2.3": { "name": "package", "version": "1.2.3", dependencies: { ...
7d95c7f8c2c2648df7348b70c3c6c5edb620fbed
48,929
def windows_start(args, version): """ :type args: WindowsIntegrationConfig :type version: str :rtype: AnsibleCoreCI """ core_ci = AnsibleCoreCI(args, 'windows', version, stage=args.remote_stage, provider=args.remote_provider) core_ci.start() return core_ci.save()
e5774933e6a72407e2201c287a02ac49b2b90d6b
48,930
from typing import Any import logging def load_spacy_model(model_name: str = CONFIG["spacy_model"]) -> Any: """ Loading Spacy model for name entity recognition. Pre-trained models should be downloaded in advance by `python -m spacy download <model_name>` """ logging.info("Loading pre-trained model...
08888c6dfbb0ba7e22216ac313c07bafdbd08019
48,931
def create_message(account, subject, body, to_recipients): """ Consolida os elementos mais básicos para a criação de um objeto de mensagem a ser gerenciado externamente pelo usuário ou por demais funções neste módulo. Em linhas gerais, o código neste bloco instancia a classe Message() da biblio...
f691ec6b5cc130a0610f78374a559c156857dafe
48,932
def client_from_parameters( base_url: str, password: str, team_name: str, username: str, verify_ssl: bool = True, concourse_api_version=None, ): """ returns a concourse-client w/ the credentials valid for the current execution environment. The returned client is authorised to perform...
957737da5daa3d6ae192bee01971eaa5de6bccd8
48,933
def get_k2_epic_catalog(): """ Parameters ---------- Returns ------- """ global k2_epic_table if k2_epic_table is None: catalogs = Vizier.get_catalogs(huber2016) k2_epic_table = catalogs[0] # This is the table with the data k2_epic_table.add_index('EPIC') r...
a678e94442936f4246dbf51a1350d14b4bea1d46
48,934
import warnings def bandpass_unit_conversion( freqs, weights=None, output_unit=None, input_unit=u.uK_RJ, cut=1e-10 ): """Unit conversion from input to output unit given a bandpass The bandpass is always assumed in power units (Jy/sr) Gain weights below cut are removed. Parameters ---------- ...
1ee62b4a2fdc7f535939c754e9f9e1e9a364ebcc
48,935
def CheckIssueClosed(issue_id): """Checks if a given issue is closed. Returns False when in doubt.""" try: return GetIssueState(issue_id) == 'closed' except IssueTrackerQueryException: # When we can't be sure we return false return False
230aabd098c8ae782c6584e467c7eadeac2137d9
48,937
import itertools def get_accuracy_and_plot_confusion(y_correct, y_pred, classes, plot=True, title='Confusion matrix'): """Return the accuracy of the prediction and plot the corresponding confusion matrix if desired""" if plot: cm = confusion_matrix(y_correct, y_pred) plt.imshow(cm, interpolati...
199f7c9e8cdd2c0c28f41856f4e00aa4ca4381f4
48,938
def random_stochastic_function(x, delta): """ Creates a random stochastic function that adds a value between [-delta, delta] Parameters ============ x: the input value. delta: defines the range """ return (np.random.random_sample() * 2 * delta) - delta
601253016610e44dbff3a1a31c46c103f1fcd9d2
48,940
def _converter(val): """ """ lval = val.lower() if lval in ENABLE_STRINGS: return True if lval in DISABLE_STRINGS: return False return val
f76b415e8a29aea539a5681c8aae1b652c680eb1
48,941
def cagr(qf_series: QFSeries, frequency=None): """ Returns the Compound Annual Growth Rate (CAGR) calculated for the given series. Parameters ---------- qf_series: QFSeries series of returns of an asset frequency: Frequency Frequency of the timeseries of returns; if it i...
bbe931a516805ec3b6e2f868e5cec96c6b205a07
48,942
from typing import Callable from typing import Optional import io import struct def decrypt_sun_message(sdm_meta_read_key: bytes, sdm_file_read_key: Callable[[bytes], bytes], picc_enc_data: bytes, sdmmac: bytes, enc_file_d...
aaee4cdb8e1ea39909df541be4a44befede2efcc
48,943
def head_pos(raw, param_compute_amplitudes_t_step_min, param_compute_amplitudes_t_window, param_compute_amplitudes_ext_order, param_compute_amplitudes_tmin, param_compute_amplitudes_tmax, param_compute_locs_t_step_max, param_compute_locs_too_close, ...
37fb24e2fb1fd2032c0f5e04f1b4c63ebeecc447
48,944
def parseNum(num): """0x is hex, 0b is binary, 0 is octal. Otherwise assume decimal.""" num = str(num).strip() base = 10 if (num[0] == '0') & (len(num) > 1): if num[1] == 'x': base = 16 elif num[1] == 'b': base = 2 else: base = 8 return int(num, base)
fc49b0a536a64ddf58e9ea5a36759e03f17de0a5
48,946
def compute_with_trace(*args): """Do Dask compute(), but with added Eliot tracing. Dask is a graph of tasks, but Eliot logs trees. So we need to emulate a graph using a tree. We do this by making Eliot action for each task, but having it list the tasks it depends on. We use the following algorit...
19d241457055241dc8d6c34042fd4e4e3fe3db32
48,947
def read_mem(addr, size): """Read a chunk of memory.""" buf = create_string_buffer(size) memmove(buf, addr, size) return buf.raw
5274b4e2a844e0daef63fe5c203529268dff73bf
48,948
def get_ranges(headervalue, content_length): """Return a list of (start, stop) indices from a Range header, or None. Each (start, stop) tuple will be composed of two ints, which are suitable for use in a slicing operation. That is, the header "Range: bytes=3-6", if applied against a Python string, ...
042cc2147e9d63da6133e9d6212a8c572a9ffe9b
48,949
def families_dipoles(): """.""" return ['B']
cca7010c86e56ef39c84cd82c960d6c2238f65ec
48,950
from typing import Optional from typing import List from typing import Tuple import httpx async def get_currencies_rates( # noqa: WPS234 api_key: Optional[str], base_currency: str = BASE_CURRENCY, ) -> List[Tuple[str, float]]: """Get currencies rates from remote server. Args: api_key: servic...
04b29a9aaa0304c55fb822600a422edc71aa00e1
48,951
def mon_vm_sync(task_id, sender, vm_uuid=None, log=LOG, **kwargs): """ Create or synchronize zabbix host according to VM. """ assert vm_uuid vm = log.obj = Vm.objects.select_related('dc', 'slavevm').get(uuid=vm_uuid) log.dc_id = vm.dc.id if vm.is_slave_vm(): logger.info('Ignoring VM...
84eceb2163337cccb5d49bb0888885ca1669d919
48,952
import pkg_resources import re from datetime import datetime def get_emissions(infile, outfile=None, fuelin=None, emisin=None): """Get emissions estimates with FINN Args: infile (str) - path to input file outfile (str) - optional path to output file. If None, then this is construc...
e252e5947f30d979f1ced3938ef70ebae7d5e1c9
48,953
def pad_subword_sequence(subword_seq, max_seq_length): """ The subword sequence (graphemic / phonetic) can be of variable length. In order to store this data in a numpy array, one pads and masks the subword dimension to the max sequence length. subword_seq: numpy array with dimensions (grap...
cb84a10b20cf30bcfb58d0250e7aeb20dc405e98
48,954
def program_to_instrument_name(program_number): """Converts a MIDI program number to the corresponding General MIDI instrument name. Parameters ---------- program_number : int MIDI program number, between 0 and 127. Returns ------- instrument_name : str Name of the inst...
03065bb232183a190286974556552abc065c17fe
48,955
import sqlite3 def recordcomfort(): """Record comfort-score today""" # User reached route via GET (as by clicking a link or via redirect) if not request.method == "POST": pass # User reached route via POST (as by submitting a form via POST) else: pass # DB connection and cursor...
fc89c86121b71fd023affaa329d65b8e194082cb
48,956
def GetLatestAFDOFile(cpv, arch, buildroot, gs_context): """Try to find the latest suitable AFDO profile file. Try to find the latest AFDO profile generated for current release and architecture. If there is none, check the previous release (mostly in case we have just branched). Args: cpv: cpv object fo...
472309dc9754f0f21f6bedbd189dad35bab4beda
48,957
def HadamardTest(P: QuantumCircuit, U: QuantumCircuit, U_active_qubits: list, shots: int = 10000): """ :param shots: the number of measurement :param U: Testing state generation circuit :param U_active_qubits: :param P: Pauli matrix :return: Re(<x|P|x>) """ p_size = len(P.qubits) u_s...
4c429c028499f4d3ec32fb6eacb8def54d65c422
48,958
def get_entry_points(config): """Process the [entry_points] section of setup.cfg. Processes setup.cfg to handle setuptools entry points. This is, of course, not a standard feature of distutils2/packaging, but as there is not currently a standard alternative in packaging, we provide support for them. ...
17287ec89f33bede790266e37ef456aadfcbc765
48,959
def logout(): """User logout route.""" do_logout() return redirect(url_for('auth.index'))
834488be7a2b5c2a4a49e2250c1b653b2a73b9b7
48,961
def _maybe_expand_labels(labels, predictions): """If necessary, expand `labels` along last dimension to match `predictions`. Args: labels: `Tensor` or `SparseTensor` with shape [D1, ... DN, num_labels] or [D1, ... DN]. The latter implies num_labels=1, in which case the result is an expanded `labels...
596895c71ef3709c3f811a93f69006cd99358b3d
48,962
import torch def quat_loss_geodesic(q1, q2): """ Geodesic rotation loss. Args: q1: N X 4 q2: N X 4 Returns: loss : N x 1 """ q1 = torch.unsqueeze(q1, 1) q2 = torch.unsqueeze(q2, 1) q2_conj = torch.cat([ q2[:, :, [0]] , -1*q2[:, :, 1:4] ], dim=-1) q_rel ...
d1e327901853e9806707411fe6b80f9e88a18881
48,963
def _expectation(p, mean1, none1, mean2, none2, nghp=None): """ Compute the expectation: expectation[n] = <m1(x_n)^T m2(x_n)>_p(x_n) - m1(.), m2(.) :: Constant mean functions :return: NxQ1xQ2 """ return mean1(p.mu)[:, :, None] * mean2(p.mu)[:, None, :]
4f177a1a850ae5d4ac7d3de96cdf5374ab9f09ba
48,964
def get_accuracy(y_true, y_predicted): """Compute the accuracy for given predicted class labels. Parameters ---------- y_true: numpy array The true class labels of shape=(number_points,). y_predicted: numpy array The predicted class labels of shape=(number_points,). Returns ...
c88a6b51021c9e01133852fa84c6f434043391a5
48,965
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ with Configurator(settings=settings) as config: config.include("pyramid_chameleon") config.include(".routes") init_database() config.scan() return config.make_wsgi_app()
fbdbb1f859dcf8a77bb9a1050582e3fe3b7501bc
48,966
def make_motif(desc, full_name, rep_list, seq_left, seq_right, rep_type, chromosome, start, end, unmapped, mapq, min_flank, min_flank_complex, min_rep): """ Make motif for config file. :param desc: str - motif description :param full_name: str - motif full name :param rep_list: list(R...
143fef642ca31109dc97f09734cc231dc591f466
48,967
def get_connections(network): """ Function creates a dictionary with agent id's as a key and adjacent nodes as a value. :param network: object of graph :type network: networkx.classes.graph.Graph """ return {agent_id: list(adj_agents.keys()) for (agent_id, adj_agents) in network.adjacency()}
fa614b599c577de5c2554818366159e918c1335b
48,968
def run_length_encode(mask): """ Descripition: Convert mask image into run-length enconde. Args ----- mask: A simple of gray image. The simple consists of digital signals(1 and 0). Returns -------- rle: A list of positions which encoded by run-length. """ signals = np....
601f6a0291e3207e063369a83c2224d714be607b
48,969
def cube_attack(f, X, y, eps, n_trials, p=0.5, deltas_init=None, independent_delta=False, min_val=0.0, max_val=1.0): """ A simple, but efficient black-box attack that just adds random steps of values in {-2eps, 0, 2eps} (i.e., the considered points are always corners). The random change is added if the loss dec...
4a847e423fc0005299c98abb19151b1a4c54ae97
48,970
def svn_utf_initialize(*args): """svn_utf_initialize(apr_pool_t pool)""" return _core.svn_utf_initialize(*args)
3eba24046428ca05463051c316eea63031e38006
48,971
def update_profile(request): """Update a user's profile view.""" profile = request.user.profile if request.method == 'POST': form = ProfileForm(request.POST, request.FILES) if form.is_valid(): data = form.cleaned_data profile.website = data['website'] profile.phone_number = data['phone_number'] pro...
837515216c090c4b00d25251a771a79c44bdc1b2
48,972
def compute(data, ncols, alg, compress=False, n_power_iter=0): """ Compute separable NMF of the input matrix. :param data: Input matrix :type data: numpy.ndarray :param ncols: Number of columns to select :type ncols: int :param alg: Choice of algorithm for computing the columns. One of...
4f8ebae39d8210bf434e50d6c5499e14f48e3535
48,973
def prox_owl(v, w): """Proximal operator of the OWL norm dot(w, reversed(sort(v))) Follows description and notation from: X. Zeng, M. Figueiredo, The ordered weighted L1 norm: Atomic formulation, dual norm, and projections. eprint http://arxiv.org/abs/1409.4271 """ # wlog operate on ab...
f00864f647c2c716197adad5edf3ed7255a52233
48,974
def get_repo(path="."): """ Returns a git repo from the specified path :param path: is the optional path to the git repo :return: git.Repo representing the input path """ return git.Repo(path)
0d8ca9b7a7f62fc63969410b3826c0874c2cea3e
48,975
from mapc2p import mapc2p import numpy as np from clawpack.visclaw import colormaps def setplot(plotdata): """ Plot solution using VisClaw. """ plotdata.clearfigures() # clear any old figures,axes,items data plotdata.mapc2p = mapc2p # Figure for contour plot plotfigure = plotdata.n...
ba7c20401297af0125b8bcdc1fe71019c2a516ca
48,976
def disclaimers(): """Sign-in disclaimer.""" return render_template("disclaimers.html", routes_to=url_for(request.args["routes_to"]))
c2c01f0b7b971417cc9871d82de10109715a03aa
48,977
def meta_name(file_name): """Generate the name of the meta file""" return "{}.json".format(file_name)
fc168d19c145c4f93fb8d92e3c0daa109aad31b6
48,978
def has_down(pdgid): """Does this particle contain a down quark?""" return _has_quark_q(pdgid, 1)
6d7bb949491b1a6da0d56c486bb6b17d5ecf2d92
48,979
import json import pkgutil def _JMS_to_Flavio_VII(C, parameters): """From JMS to flavio basis for class VII, i.e. flavour blind operators.""" d = {} dtrans = json.loads(pkgutil.get_data('wilson', 'data/flavio_jms_vii.json').decode('utf8')) for cj, cf in dtrans.items(): d[cf] = C.get(cj, 0) ...
24bad69a4c194aa26f93f361622b55b6b673d8cc
48,980
def _get_land_fraction(cube, fx_variables): """Extract land fraction as :mod:`dask.array`.""" land_fraction = None errors = [] if not fx_variables: errors.append("No fx files given.") return (land_fraction, errors) for (fx_var, fx_path) in fx_variables.items(): if not fx_path...
23378e363d1cdf64523dd460bb6e0943a58d1e31
48,982
def datasets_startswith(names): """ Return a list of strings with dataset names that begin with the given names. :param names: String or tuple of strings. :return: List of strings. """ # Load dict with info about all the datasets. info_datasets = load_info_datasets() ...
6fa239d4515efb50b4f91d7f80d1d13eeec95c7d
48,983
def get_pid_uid_sequences(infile, max_len=5000): """ Fetch a hierarchical dictionary with keys [pid][uid] and values which are sequences of actions :param infile: :param max_len: maximum length of sequence to store :return: hierarchical dictionary with keys [pid][uid] and values which are np.ndarray...
79dc6598137422dabe01375af09dc4dbbf5b6f3c
48,984
def randomDatabaseName() -> str: """ Generate a unique string for use as a database name. """ return f"d{uuid4().hex}"
79ff0dc75c7e6aa3c849253a0d847f3cb2afefce
48,986
def concat_body_paragraphs(body_candidates): """ Concatenate paragraphs constituting the question body. :param body_candidates: :return: """ return ' '.join(' '.join(body_candidates).split())
a0faaa0ae0be0cda007c2af1f6e47f3b745862b3
48,987
def home(request): """docstring for home""" return render(request,"home.html",{})
437c43886f4c52e62b7a07f5f35878591ca4bfd1
48,988
def AlbersUsaProjection(): """ Create function to project coordinates using an Albers USA projection. """ # Based on D3's AlbersUSA projection # https://github.com/mbostock/d3/blob/master/src/geo/albers-usa.js # http://spatialreference.org/ref/esri/usa-contiguous-albers-equal-area-conic/ lo...
a473bffa8dd64badf10dd179a2a04dc42d9247c8
48,989
from keras.preprocessing.sequence import pad_sequences def _build_generator(X_list, y_list, batch_size, timesteps, input_size, shuffle, positive_weight): """ Build looping generator of training batches. Will return the generator and the number of batches in each epoch. In each epoch, all samples are rando...
ef9edc0d43faeaae12ed45bb54ab1e5d278d6ad4
48,990
def merge_tables(version=''): """ given hdf5s, pivot and merge them at the same time """ df_merged = merge_duplicates_and_pivot(df=None, version=version) # Fluid balance OUT == hourly urine df_merged['vm32'] = df_merged['vm24'] output_path = mimic_paths.merged_dir + version + '/reduced/merge...
ec6328709d645a27b94519d3cbf4d2af0ebe8558
48,992
import tempfile import json def get_fuzzer_stats(stats_filestore_path): """Reads, validates and returns the stats in |stats_filestore_path|.""" with tempfile.NamedTemporaryFile() as temp_file: result = filestore_utils.cp(stats_filestore_path, temp_file.name, ...
03f934069b987c782910cf8164fcb184ac1685b2
48,993
def combine_sample_standard_deviation(As, n = None, u = None, v = None): """Computes the combined sample standard deviation of a group of `measured_value`s. Let: * `g = len(As)`. * `u_i = As[i].quantity`. * `s_i = As[i].uncertainty`. * `n_i = As[i].samples`. * `n` denote the combined sample ...
f3ddb6006c62fdc93b29444049a19d51725f9f72
48,996
def hash_password(pwd): """ https://passlib.readthedocs.io/en/stable/index.html :param pwd: :return: """ return _pwd_context.hash(pwd)
b17bec236389fd45762822e482d63766734b6c9a
48,997
import re def matchNumbersOnly(value): """Match strings with numbers and '.' only.""" if re.match('^[0-9.]+$', value): return True return False
04d782431b79e78f93269c662c747d1f7348c9ec
48,998
def read_one(person_id): """ This function responds to a request for /api/people/{person_id} with one matching person from people :param person_id: Id of person to find :return: person matching id """ # Get the person requested person = Person.query.filter(Person.person_id ...
e3ddbecf9779fd032646c9e847785776b42a409d
49,000
import numpy as np def getPointsProjectedToPlane(pointsArray, planePosition, planeNormal): """ Returns points projected to the plane in world coordinate system and in the plane coordinate system, and an array of booleans that tell if the point was above/below the plane. pointsArray contains each point as a co...
21a36e32230477d987ace80c9d8fdfd23fb3feee
49,001
def diff_one_tc(x: int, y: int) -> int: """Compute x - y. This problem has only one test case to make inspecting the specific error message easier. """ return x - y
96634c095af4dade2c158788f2b1af0728c0a23d
49,002
from re import S def reduce_rational_inequalities(exprs, gen, relational=True): """ Reduce a system of rational inequalities with rational coefficients. Examples ======== >>> x = Symbol('x', real=True) >>> reduce_rational_inequalities([[x**2 <= 0]], x) Eq(x, 0) >>> reduce_rational_i...
909f233f644e40b23e2a22fc51e5230d21d950ca
49,003
def read(string: str) -> dict: """Parse an ordered map file. :arg string: Content of an ordered map file. :returns: An ordered map. """ data = {} for line in string.split('\n'): if line and line[0] not in ('#', ' ', '\t', '\r'): data = _merge(data, _deserialise(line)) r...
b20d5767995aad4bb110bf6bc3ef6b7885d2ecb6
49,004
def _generate_indicators(catalog, validator=None, only_numeric=False, broken_links=False, verify_ssl=True, url_check_timeout=1, broken_links_threads=1): """Genera los indicadores de un catálogo individual. Args: catalog (dict): diccionario de un data.js...
be7516ec0adf469b698b2271555282e6424d12af
49,005
import numpy def metric_weekday(weekday_1, weekday_2): """Calculate the distance between two weekdays as a positive integer. :param weekday_1: A positive integer between 0 and 6 :param weekday_2: A positive integer between 0 and 6 :returns: The absolute valued distance between two weekdays :rtype...
71a0a5d5a5166458597e0007063a4c19e8f195a9
49,006