content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
async def post_user(ctx: Context, user: MemberOrUser) -> t.Optional[dict]: """ Create a new user in the database. Used when an infraction needs to be applied on a user absent in the guild. """ log.trace(f"Attempting to add user {user.id} to the database.") payload = { 'discriminator': ...
25a6a710d7d94cc9837d9d67408a09fd6ff48596
4,066
from typing import List def delete(ids: List = Body(...)): """ Deletes from an embeddings index. Returns list of ids deleted. Args: ids: list of ids to delete Returns: ids deleted """ try: return application.get().delete(ids) except ReadOnlyError as e: ra...
9075db7c7dd174b850d1d4acbe1cdb4001162b5d
4,067
def main(): """ Simple Event Viewer """ events = None try: events = remote('127.0.0.1', EventOutServerPort, ssl=False, timeout=5) while True: event_data = '' while True: tmp = len(event_data) event_data += events.recv(numb=8192, timeout=1).decode('latin-1') if tmp == len(event_data): bre...
d96500a3114785dbb408681e96d7ffb7a5c59d04
4,068
def fsi_acm_up_profiler_descending(vp1, vp2, vp3): """ Description: Calculates the VEL3D Series A and L upwards velocity data product VELPTMN-VLU-DSC_L1 for the Falmouth Scientific (FSI) Acoustic Current Meter (ACM) mounted on a McLane profiler. Because of the orientation of th...
e176ff1b23bf4b5624cdc8a698d03c8d2ee1947a
4,069
from typing import Tuple def colour_name(colour: Tuple[int, int, int]) -> str: """Return the colour name associated with this colour value, or the empty string if this colour value isn't in our colour list. >>> colour_name((1, 128, 181)) 'Pacific Point' >>> colour_name(PACIFIC_POINT) 'Pacific...
e596bf802b8f168e6c8d9bd9b8e4113b61e7fd58
4,070
def score_fn(subj_score, comp_score): """ Generates the TextStim with the updated score values Parameters ---------- subj_score : INT The subjects score at the moment comp_score : INT The computer's score at the moment' Returns ------- score_stim : psychopy.visual.t...
2d52b4c8d47543c6c1c98e5aa7feb8c3341ff7a4
4,071
def parse_write_beam(line): """ Write_beam (type -2) If btype = −2, output particle phase-space coordinate information at given location V3(m) into filename fort.Bmpstp with particle sample frequency Bnseg. Here, the maximum number of phase- space files which can be output is 100. Here, 40 and ...
7ce86ae39a51ea8d4636e37bea26edd3caae19e8
4,072
def get_tone(pinyin): """Renvoie le ton du pinyin saisi par l'utilisateur. Args: pinyin {str}: l'entrée pinyin par l'utilisateur Returns: number/None : Si pas None, la partie du ton du pinyin (chiffre) """ # Prenez le dernier chaine du pinyin tone = pin...
fc0b02902053b3f2470acf952812573f5125c4cf
4,073
def authIfV2(sydent, request, requireTermsAgreed=True): """For v2 APIs check that the request has a valid access token associated with it :returns Account|None: The account object if there is correct auth, or None for v1 APIs :raises MatrixRestError: If the request is v2 but could not be authed or the user...
6c3f60df233cc030dfc3ec2658bd2a70c5a20aed
4,074
def gen_rho(K): """The Ideal Soliton Distribution, we precompute an array for speed """ return [1.0/K] + [1.0/(d*(d-1)) for d in range(2, K+1)]
40382af047d0f2efba0eb6db17c28b92e47d3c92
4,075
import numpy as np def assert_array_max_ulp(a, b, maxulp=1, dtype=None): """ Check that all items of arrays differ in at most N Units in the Last Place. Parameters ---------- a, b : array_like Input arrays to be compared. maxulp : int, optional The maximum number of units in t...
8ca9698e5b213f753002535061b17aeb59f12e83
4,076
def Ambient_Switching(crop_PPFDmin, Trans, consumption): """ Inputs: consumption (returned from Light_Sel) """ #How much energy can you save if you switch off when ambient lighting is enough for plant needs? #Assume that when ambient is higher than max recommended PPFD, that the greenhouse is cloaked, allowin...
5a8ab9d6eb0c6b3ddd7bb3f7efb1599b952aa345
4,077
from typing import Callable def get_numerical_gradient(position: np.ndarray, function: Callable[[np.ndarray], float], delta_magnitude: float = 1e-6) -> np.ndarray: """ Returns the numerical derivative of an input function at the specified position.""" dimension = position.shape[0] ...
a439acd3934006e2b8f9188e3204e12ef3885ae5
4,078
def stable_point(r): """ repeat the process n times to make sure we have reaches fixed points """ n = 1500 x = np.zeros(n) x[0] = np.random.uniform(0, 0.5) for i in range(n - 1): x[i + 1] = f(x[i], r) print(x[-200:]) return x[-200:]
9d9c32abfb0fea74abb32ec8cebd8c76738669b1
4,080
def vary_on_headers(*headers): """ A view decorator that adds the specified headers to the Vary header of the response. Usage: @vary_on_headers('Cookie', 'Accept-language') def index(request): ... Note that the header names are not case-sensitive. """ def decorator(fu...
9892ac00aa31b0e294f79b2d1539d6d79f3eaed7
4,081
def non_daemonic_process_pool_map(func, jobs, n_workers, timeout_per_job=None): """ function for calculating in parallel a function that may not be run a in a regular pool (due to forking processes for example) :param func: a function that accepts one input argument :param jobs: a list of input arg...
41fbdaae1e584839692eae4d5034ffd6828eb5c7
4,083
import random import textwrap from datetime import datetime def result_list_handler(*args: list, **kwargs) -> str: """ Handles the main search result for each query. It checks whether there are any result for this qeury or not. 1. If there was results, then it sorts and decorates the them. 2 O...
c0fb0db46e3c47d24b06c290ba9d0129eb436edf
4,084
def flip_mask(mask, x_flip, y_flip): """ Args: mask: バイナリマスク [height, width] """ mask = mask.copy() if y_flip: mask = np.flip(mask, axis=0) if x_flip: mask = np.flip(mask, axis=1) return mask
d3d783fb3e5913448f4e9d06f1f96d89559a686c
4,085
def sbn2journal(sbn_record, permalink_template="http://id.sbn.it/bid/%s"): """ Creates a `dbmodels.Journal` instance out of a dictionary with metadata. :param record: the dictionary returned by `resolution.supporting_functions.enrich_metadata()` :return: an instance of `dbmodels.Journal` """ bi...
059b00aeb81dd1bdbc987f31c045b6eb5aedc3b3
4,086
def median(data): """Calculates the median value from |data|.""" data = sorted(data) n = len(data) if n % 2 == 1: return data[n / 2] else: n2 = n / 2 return (data[n2 - 1] + data[n2]) / 2.0
ad2b3f7eb3f5446c81c6c400bc16c7833e75c05c
4,087
from typing import Optional def split_text_by_length(text: str, length: Optional[int] = None, # 方案一:length + delta delta: Optional[int] = 30, max_length: Optional[int] = None, # 方案二:直接确定长度上下限 min_length: Optional[int...
60bf713a2cbe3eff85237d9637a303668a9f436b
4,089
def _tfidf_fit_transform(vectors: np.ndarray): """ Train TF-IDF (Term Frequency — Inverse Document Frequency) Transformer & Extract TF-IDF features on training data """ transformer = TfidfTransformer() features = transformer.fit_transform(vectors).toarray() return features, transformer
c38aa629d11258291f306052ac0e4c9c2a474ebd
4,090
from typing import List def _is_missing_sites(spectra: List[XAS]): """ Determines if the collection of spectra are missing any indicies for the given element """ structure = spectra[0].structure element = spectra[0].absorbing_element # Find missing symmeterically inequivalent sites symm_s...
0ae7ad0622e8ec398306e05def214b0ad40fd90f
4,091
def get_objects(params, meta): """ Retrieve a list of objects based on their upas. params: guids - list of string - KBase IDs (upas) to fetch post_processing - object of post-query filters (see PostProcessing def at top of this module) output: objects - list of ObjectData - see t...
17d38a1a5e09847700537076c0bfefdd55947682
4,092
def parseMidi(midifile): """Take a MIDI file and return the list Of Chords and Interval Vectors. The file is first parsed, midi or xml. Then with chordify and PC-Set we compute a list of PC-chords and Interval Vectors. """ mfile = ms.converter.parse(midifile) mChords = mfile.chordify() chor...
8c803c297eee5cc29a78d6c8b864a85e8bfd3d52
4,095
def get_similarity(s1, s2): """ Return similarity of both strings as a float between 0 and 1 """ return SM(None, s1, s2).ratio()
3964670a69a135fbc6837e9c68a2e7ac713d67dc
4,096
from typing import Union from typing import Sequence from re import T def concrete_values_from_iterable( value: Value, ctx: CanAssignContext ) -> Union[None, Value, Sequence[Value]]: """Return the exact values that can be extracted from an iterable. Three possible return types: - ``None`` if the arg...
3acdda92df4e27d4eecf39630570b90049580d6d
4,097
def quat_conjugate(quat_a): """Create quatConjugate-node to conjugate a quaternion. Args: quat_a (NcNode or NcAttrs or str or list or tuple): Quaternion to conjugate. Returns: NcNode: Instance with quatConjugate-node and output-attribute(s) Example: :: ...
2bff8b1e472ad2975ba96084843004ce86205f9f
4,099
def askfont(): """ Opens a :class:`FontChooser` toplevel to allow the user to select a font :return: font tuple (family_name, size, \*options), :class:`~font.Font` object """ chooser = FontChooser() chooser.wait_window() return chooser.font
8bce830a24d92be38c23ba09b6754f2e6cc6d161
4,100
def load_data(train_file, test_file): """ The method reads train and test data from their dataset files. Then, it splits train data into features and labels. Parameters ---------- train_file: directory of the file in which train data set is located test_file: directory of the file in which ...
d830f4bcd3efe467a23cab0dfa4a3cdb4694559e
4,101
def guide(batch_X, batch_y=None, num_obs_total=None): """Defines the probabilistic guide for z (variational approximation to posterior): q(z) ~ p(z|x) """ # we are interested in the posterior of w and intercept # since this is a fairly simple model, we just initialize them according # to our prior b...
889f3224424496a4f001d81b046e1279ba0efe77
4,103
def get_reddit_tables(): """Returns 12 reddit tables corresponding to 2016""" reddit_2016_tables = [] temp = '`fh-bigquery.reddit_posts.2016_{}`' for i in range(1, 10): reddit_2016_tables.append(temp.format('0' + str(i))) for i in range(10, 13): reddit_2016_tables.append(temp.format(...
e590ab35becbe46aa220257f6629e54f720b3a13
4,105
def first_empty(): """Return the lowest numbered workspace that is empty.""" workspaces = sorted(get_workspace_numbers(get_workspaces().keys())) for i in range(len(workspaces)): if workspaces[i] != i + 1: return str(i + 1) return str(len(workspaces) + 1)
f9c9f868570bbcc15a28097930d304b308ddf452
4,106
def get_local_tzone(): """Get the current time zone on the local host""" if localtime().tm_isdst: if altzone < 0: tzone = '+' + \ str(int(float(altzone) / 60 // 60)).rjust(2, '0') + \ str(int(float( ...
dec1d9f9c5ecf937779de55a33397436841913bc
4,108
def subscribers_tables_merge(tablename1: Tablename, tablename2: Tablename, csv_path=csvpath, verbose=True): """ Сводит таблицы, полученные загрузчиком, в одну. Может принимать pandas.DataFrame или имя группы, в этом случае группа должна быть в списке групп, а соответствующий файл - в <csv_path> """ ...
56c5c80b57aa4103f1836f8b9a5ca7bbb67e25bc
4,109
def get_current_offset(session): """ For backfilling only, this function works with the init container to look up it's job_id so it can line that up with it's consumer group and offest so that we can backfill up to a given point and then kill the worker afterwards. """ if settings.JOB_ID is None...
97d0b0485005a709a047582667f56a79f636388d
4,110
def get_params(p1, p2, L): """ Return the curve parameters 'a', 'p', 'q' as well as the integration constant 'c', given the input parameters. """ hv = p2 - p1 m = p1 + p2 def f_bind(a): return f(a, *hv, L) def fprime_bind(a): return fprime(a, hv[0]) # Newton-Raphson algorithm to fin...
eae7d942b4272b3addc6c3f3912abc564e93f339
4,111
def _unpack(f): """to unpack arguments""" def decorated(input): if not isinstance(input, tuple): input = (input,) return f(*input) return decorated
245d425b45d9d7ef90239b791d6d65bcbd0433d5
4,112
from .ops.classes import WriteRichOp from typing import Iterable from functools import reduce def chain_rich(iterable: Iterable['WriteRichOp']) -> 'WriteRichOp': """Take an `iterable` of `WriteRich` segments and combine them to produce a single WriteRich operation.""" return reduce(WriteRichOp.then, iterable...
fa75ab929fb01b9c68e58938aa04aebddc26f245
4,113
def sum_plot_chi2_curve(bin_num, sum_bin, r_mpc, ax=None, cov_type='bt', label=None, xlabel=True, ylabel=True, show_bin=True, ref_sig=None): """Plot the chi2 curve.""" if ax is None: fig = plt.figure(figsize=(6, 6)) fig.subplots_adjust( left=0.165, bottom=0.13...
6f0b7adf2daa98ecac9ff722eab9f6b748ef188b
4,114
import dfim import dfim.util def compute_importance(model, sequences, tasks, score_type='gradient_input', find_scores_layer_idx=0, target_layer_idx=-2, reference_gc=0.46, reference_shuffle_type=None, ...
a7ebe928f4e3b50d5c8735d438d28c034d5dfeb9
4,115
from typing import Iterable def test_check_non_existing() -> None: """Test a check on a non-existing column.""" class Schema(pa.SchemaModel): a: Series[int] @pa.check("nope") @classmethod def int_column_lt_100(cls, series: pd.Series) -> Iterable[bool]: return seri...
473b0e1c4b4c785970bdc648e4290426524882c7
4,116
import requests def fetch_url(url): """Fetches the specified URL. :param url: The URL to fetch :type url: string :returns: The response object """ return requests.get(url)
26198dbc4f7af306e7a09c86b59a7da1a4802241
4,117
def _nw_score_(s1, s2, insert=lambda c: -2, delete=lambda c: -2, substitute=lambda c1, c2: 2 if c1 == c2 else -1): """Compute Needleman Wunsch score for aligning two strings. This algorithm basically performs the same operations as Needleman Wunsch alignment, but is made more ...
009c9eb4afec828adde53bddfd2a8b4d2a952c24
4,118
import pickle import torch import re import warnings from typing import Counter from typing import OrderedDict def load_gisaid_data( *, device="cpu", min_region_size=50, include={}, exclude={}, end_day=None, columns_filename="results/usher.columns.pkl", features_filename="results/usher...
eaa9c5b3735f291706ea783272b3372ad9e7937c
4,119
def get_symbol_size(sym): """Get the size of a symbol""" return sym["st_size"]
b2d39afe39542e7a4e1b4fed60acfc83e6a58677
4,120
def to_unnamed_recursive(sexpr, scheme): """Convert all named column references to unnamed column references.""" def convert(n): if isinstance(n, NamedAttributeRef): n = toUnnamed(n, scheme) n.apply(convert) return n return convert(sexpr)
ffb58acb1cfbef654c5c936880961b8cc982ec01
4,122
def login_process(): """Process login.""" email_address = request.form.get("email") password = request.form.get("password") user = User.query.filter_by(email_address=email_address).first() if not user: flash("Please try again!") return redirect('/') if user.password != passwor...
afee068b653e5f759329658e3614b0ce7ee2d405
4,123
def get_doc_translations(doctype, name): """ Returns a dict custom tailored for the document. - Translations with the following contexts are handled: - doctype:name:docfield - doctype:name - doctype:docfield (Select fields only) - 'Select' docfields will have a values dict which will have trans...
e7fd896de3162452a77ab989670e61b01e8e35a2
4,124
def app(request): """ Default view for Person Authority App """ return direct_to_template(request, 'person_authority/app.html', {'app':APP})
9e75c9cf381c69b19bfdf08c74b2e0dc2106822b
4,126
def is_xbar(top, name): """Check if the given name is crossbar """ xbars = list(filter(lambda node: node["name"] == name, top["xbar"])) if len(xbars) == 0: return False, None if len(xbars) > 1: log.error("Matching crossbar {} is more than one.".format(name)) raise SystemExit...
435b84a30f3f749f07d0cc6dfdd5e7f0c5343c4f
4,127
def index(): """ Root URL response """ return "Reminder: return some useful information in json format about the service here", status.HTTP_200_OK
d8128c8ba8976238c1d68376eaa64a77d09ce525
4,128
def backproject(depth, K): """Backproject a depth map to a cloud map depth: depth ---- organized cloud map: (H,W,3) """ H, W = depth.shape X, Y = np.meshgrid(np.asarray(range(W)) - K[0, 2], np.asarray(range(H)) - K[1, 2]) return np.stack((X * depth / K[0, 0], Y * depth / K[1, 1], depth)...
5433fd408932f48c238cad7e5e8d7b14ee7b00de
4,129
from pathlib import Path def get_parent_dir(os_path: str) -> str: """ Get the parent directory. """ return str(Path(os_path).parents[1])
3a6e518119e39bfbdb9381bc570ac772b88b1334
4,130
def parse_work_url(work_url): """Extract work id from work url Args: work_url (str): work url Returns: str: bdrc work id """ work_id = "" if work_url: work_url_parts = work_url.split("/") work_id = work_url_parts[-1] return work_id
1e7f5e222a2f6c7d01cbcb7df556adf6dd33f7cf
4,132
def room(): """Create a Room instance for all tests to share.""" return Room({"x": 4, "y": 4, "z": 4}, savable=False)
f031faa1bf654ff32868b678f79c2af040926b44
4,133
import re def searchLiteralLocation(a_string, patterns): """assumes a_string is a string, being searched in assumes patterns is a list of strings, to be search for in a_string returns a list of re span object, representing the found literal if it exists, else returns an empty list""" results = [] ...
0f751bae801eaee594216688551919ed61784187
4,134
def UIOSelector_Highlight(inUIOSelector): """ Highlight (draw outline) the element (in app) by the UIO selector. :param inUIOSelector: UIOSelector - List of items, which contains condition attributes :return: """ # Check the bitness lSafeOtherProcess = UIOSelector_SafeOtherGet_Process(inUI...
9ab5930396aa9813f09d858c4bb94adc2170f312
4,135
import torch def completeMessage_BERT(mod, tok, ind, max_length=50): """ Sentence Completion of the secret text from BERT """ tokens_tensor = torch.tensor([ind]) outInd = mod.generate(tokens_tensor, max_length=50) outText=tok.decode(outInd[0].tolist()) newText=outText[len(tok.decode(ind)):] newText=n...
c2a47bbe90a9e5d222af0bbe5959c82d2ebd2cd3
4,136
def load_real_tcs(): """ Load real timecourses after djICA preprocessing """ try: return sio.loadmat(REAL_TC_DIR)['Shat'][0] except KeyError: try: return sio.loadmat(REAL_TC_DIR)['Shat_'][0] except KeyError: print("Incorrect key") pass
68b148e6fc6088d8ef9f90daf25e07609010d9fe
4,138
def create_fsaverage_forward(epoch, **kwargs): """ A forward model is an estimation of the potential or field distribution for a known source and for a known model of the head. Returns EEG forward operator with a downloaded template MRI (fsaverage). Parameters: epoch: mne.epochs.Epochs ...
34d72211babf23e41927ebe7df13c58bf6876e4d
4,139
def midi_to_hz(notes): """Hello Part 6! You should add documentation to this function. """ return 440.0 * (2.0 ** ((np.asanyarray(notes) - 69.0) / 12.0))
7215126d25ff969a8aa187c7f49216ec7743a9e9
4,141
def bond_stereo_parities(chi, one_indexed=False): """ Parse the bond stereo parities from the stereochemistry layers. :param chi: ChI string :type chi: str :param one_indexed: Return indices in one-indexing? :type one_indexed: bool :returns: A dictionary mapping bond keys on...
02729db6888899a91e69a25dae81c06777b89182
4,142
def filter_camera_angle(places): """Filter camera angles for KiTTI Datasets""" bool_in = np.logical_and((places[:, 1] < places[:, 0] - 0.27), (-places[:, 1] < places[:, 0] - 0.27)) # bool_in = np.logical_and((places[:, 1] < places[:, 0]), (-places[:, 1] < places[:, 0])) return places[bool_in]
417fccfbb240c5defc36b4ce465fe14333922b94
4,143
def neural_log_literal_function(identifier): """ A decorator for NeuralLog literal functions. :param identifier: the identifier of the function :type identifier: str :return: the decorated function :rtype: function """ return lambda x: registry(x, identifier, literal_functions)
84651d58b7da677ee213d1ff4667dc3be702f243
4,144
def get_factors(n: int) -> list: """Returns the factors of a given integer. """ return [i for i in range(1, n+1) if n % i == 0]
c15a0e30e58597daf439facd3900c214831687f2
4,145
def fetch_tables(): """ Used by the frontend, returns a JSON list of all the tables including metadata. """ return jsonify([ { "tab": "animeTables", "name": "Anime", "tables": [ { "id": "englishAnimeSites", "titl...
5c07e7bc9f3366bc72e21dd5468edf57b6c448b3
4,146
def base_positive_warps(): """ Get warp functions associated with domain (0,inf), scale 1.0 Warp function is defined as f(x) = log(exp(x)-1) Returns ------- Callable[torch.Tensor,torch.Tensor], Callable[torch.Tensor,torch.Tensor], Callable[torch.Tensor,torch.Tensor] Function...
389db769f55f7542a45e6acbbccf5760dc7b8c26
4,147
import re import json from datetime import datetime def dev_work_create(): """ Create work order. :return: """ db_ins = current_user.dbs audits = User.query.filter(User.role == 'audit') form = WorkForm() if form.validate_on_submit(): sql_content = form.sql_content.data ...
b11f840bbc6428696afabe7f2fe00b5d0b6ad7d1
4,148
def blur(x, mean=0.0, stddev=1.0): """ Resize to smaller size (AREA) and then resize to original size (BILINEAR) """ size = tf.shape(x)[:2] downsample_factor = 1 + tf.math.abs(tf.random.normal([], mean=mean, stddev=stddev)) small_size = tf.to_int32(tf.to_float(size)/downsample_factor) x = tf.image.resize_...
b0101a4b820beb84c627bef048bbafeb1d11cdea
4,149
def improve(update, close, guess=1, max_updates=100): """Iteratively improve guess with update until close(guess) is true or max_updates have been applied.""" k = 0 while not close(guess) and k < max_updates: guess = update(guess) k = k + 1 return guess
3475c07a3e9a674661d90e116bfb91fa12344d63
4,150
def images_to_sequence(tensor): """Convert a batch of images into a batch of sequences. Args: tensor: a (num_images, height, width, depth) tensor Returns: (width, num_images*height, depth) sequence tensor """ num_image_batches, height, width, depth = _shape(tensor) transposed = tf.transpose(tenso...
cc89ce931239b5335d5788bc6e9007e5186648bf
4,151
from typing import Any import logging def transform_regions(regions: list[dict[str, Any]]) -> list[dict[str, Any]]: """ Transform aggregated region data for map regions -- aggregated data from region pipeline """ records = [] for record in regions: if "latitude" in record["_id"].keys(...
599e58e3bd66159114d0dbf27b339c47134c29c3
4,152
def _file_to_import_exists(storage_client: storage.client.Client, bucket_name: str, filename: str) -> bool: """Helper function that returns whether the given GCS file exists or not.""" storage_bucket = storage_client.get_bucket(bucket_name) return storage.Blob( bucket=storage_buc...
cb051aba0d5e787e85dbc0283aa439e3c17e819c
4,153
from typing import Optional from typing import List from typing import Tuple def get_relative_poses( num_frames: int, frames: np.ndarray, selected_track_id: Optional[int], agents: List[np.ndarray], agent_from_world: np.ndarray, current_agent_yaw: float, ) -> Tuple[np.ndarray, np.ndarray, np.nd...
e1dad983e5070310ce239615c98f85d8b09b9c45
4,155
import numpy def read_mat_cplx_bin(fname): """ Reads a .bin file containing floating-point values (complex) saved by Koala Parameters ---------- fname : string Path to the file Returns ------- buffer : ndarray An array containing the complex floating-point values read...
f2761f4cd7031dc16cb2f9903fd431bc7b4212d8
4,156
def DeleteDataBundle(**kwargs): """ Deletes a Data Bundle by ID. :param kwargs: :return: """ data_bundle_id = kwargs['data_bundle_id'] del data_bundles[data_bundle_id] return(kwargs, 200)
88ded979e45beebe885eeb1890ce66ae367b1fd6
4,157
def determineactions(repo, deficiencies, sourcereqs, destreqs): """Determine upgrade actions that will be performed. Given a list of improvements as returned by ``finddeficiencies`` and ``findoptimizations``, determine the list of upgrade actions that will be performed. The role of this function i...
0ec771565560607e839ce87a65426e01d0276f36
4,158
def filter_ccfs(ccfs, sc_thresh, min_ccf): """ Remove noisy ccfs from irrelevant experiments :param ccfs: 2d array :param sc_thresh: int number of sign changes expected :param min_ccf: float cutoff value for a ccf to be above the noise threshold :return: """ if sc_thresh ...
06941eaea7bc5dc25f261669532c66ac37cbb9ab
4,159
def market_data(symbol, expirationDate, strike, optionType, info=None): """Gets option market data from information. Takes time to load pages.""" assert all(isinstance(i, str) for i in [symbol, expirationDate, strike, optionType]) return robin_stocks.options.get_option_market_data(symbol, expirationDate, strike, opt...
153d15af1030be22fa6c97b8d68fdf2049ebc416
4,160
def get_documents_embeddings (y, embedder, column): """ Given a Dataframe containing study_id and a text column, return a numpy array of embeddings The idea of this function is to prevent to embed two times the same text (for computation efficiency) Parameters: ----------- ...
9a748ef8b276d68a61d78c6fa567a40aae4fc222
4,161
def index(request): """view fonction de la page d'accueil Render templates de la page d'accueil """ return render(request, "t_myapp/index.html")
b3cf3be5d3c2a286d5705281e35042ad19d0a050
4,162
def cidr_mask_to_subnet_mask(mask_num): """ 掩码位数转换为点分掩码 :param mask_num: 掩码位数, 如 16 :return: 十进制点分ipv4地址 """ return convert_to_ipv4(cidr_mask_to_ip_int(mask_num), stype='int')
83556c856f68e82824fa1f3a34b4d629361081af
4,163
def correlate(A,B, rows=None,columns=None, mode_row='zero', mode_column='zero'): """Correlate A and B. Input: ------ A,B : array Input data. columns : int Do correlation at columns 0..columns, defaults to the number of columns in A. rows : int Do correlatio...
88bfec52c318aaf119a6fac5cff731855f0a0d81
4,164
def getChrLenList(chrLenDict, c): """ Given a chromosome length dictionary keyed on chromosome names and a chromosome name (c) this returns a list of all the runtimes for a given chromosome across all Step names. """ l = [] if c not in chrLenDict: return l for n in chrLenDict[c]: ...
aedf613484262ac5bd31baf384ade2eb35f3e1eb
4,165
from typing import Optional def query_sessions(user_id: Optional[int]) -> TList[Session]: """ Return all user's sessions :param user_id: current user ID (None if user auth is disabled) :return: list of session objects """ adb = get_data_file_db(user_id) return [Session(db_session) for db...
c7449c7805f1ba0c425140603952215b67e3ce0e
4,167
import torch import math def positionalencoding3d(d_model, dx, dy, dz): """ :param d_model: dimension of the model :param height: height of the positions :param width: width of the positions :return: d_model*height*width position matrix """ # if d_model % 6 != 0: # raise ValueError("...
178dc3b86e3be0c9e799f5f0c658808f541f1eca
4,168
def make_headers(context: TraceContext) -> Headers: """Creates dict with zipkin headers from supplied trace context. """ headers = { TRACE_ID_HEADER: context.trace_id, SPAN_ID_HEADER: context.span_id, FLAGS_HEADER: '0', SAMPLED_ID_HEADER: '1' if context.sampled else '0', ...
474e3a57af1bda99585f7d140fbd0bb1d9bd18b2
4,169
def shiftRightUnsigned(col, numBits): """Unsigned shift the given value numBits right. >>> df = spark.createDataFrame([(-42,)], ['a']) >>> df.select(shiftRightUnsigned('a', 1).alias('r')).collect() [Row(r=9223372036854775787)] """ sc = SparkContext._active_spark_context jc = sc._jvm.functio...
342d08644c56c2cce5e02f0d3d0ddd9df0b2f173
4,170
def scalar_sub(x: Number, y: Number) -> Number: """Implement `scalar_sub`.""" _assert_scalar(x, y) return x - y
74c9d44eaaabb1bfeea012b4ec1503e37d7c9f8b
4,171
def predict_attack(h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11,h12,h13): """ Parameters: -name:h1 in:query type:number required=True -name:h5 in:query type:number required:True -name:h4 in:query type:number required:True -name:h8 ...
907f6b52c3b1c24a409b8b7ebc157412bd67777d
4,172
def _check_varrlist_integrity(vlist): """Return true if shapes and datatypes are the same""" shape = vlist[0].data.shape datatype = vlist[0].data.dtype for v in vlist: if v.data.shape != shape: raise(Exception("Data shapes don't match")) if v.data.dtype != datatype: ...
1b6fedd1222757c0bc92490be85d8030ee877842
4,173
def subclassfactory(fact_method): """fact_method takes the same args as init and returns the subclass appropriate to those args that subclass may in turn override the same factory method and choose amoung it's subclasses. If this factory method isn't overridden in the subclass an object of that class is ini...
eb0b8227276ed7499d21d9998ec08fb830d89642
4,174
def simulate_var1(x_tnow, b, mu, sigma2, m_, *, j_=1000, nu=10**9, init_value=True): """For details, see here. Parameters ---------- x_tnow : array, shape(n_, ) b : array, shape(n_,n_) mu : array, shape(n_, ) sigma2 : array, shape(n_,n_) m_ : int ...
66bf82052e933e14d16e82738d36a4c96b51ca43
4,175
from typing import Optional def is_drom(insee_city: Optional[str] = None, insee_region: Optional[str] = None) -> bool: """ Est-ce que le code INSEE de la ville ou de la région correspond à un DROM ? Args: insee_city: Code INSEE de la ville insee_region: Code INSEE de la région Return...
7a33516eb31c5ff7800eb6dc663d76d5e2c445cb
4,176
import math def pack_rows(rows, bitdepth): """Yield packed rows that are a byte array. Each byte is packed with the values from several pixels. """ assert bitdepth < 8 assert 8 % bitdepth == 0 # samples per byte spb = int(8 / bitdepth) def make_byte(block): """Take a block o...
e0b8a4701adf1757a558475e2ea5830a3d53ab2a
4,177
def reset_user_pwd(username: str) -> int: """ :param username: 用户名 :return: 结果代码: 1: 成功, 0: 失败 """ return update_user_info(username=username, args={ 'password': '12345678' })
a9703bb82913b47e9b59ba36cd9257323cbfeec2
4,178
def location_engineering(df: pd.DataFrame) -> pd.DataFrame: """Call the `location_dict()` function to get the location dictionary and the `location_dataframe()` one to add the location dictionary info to the DataFrame. Parameters ---------- df : The dataframe to work with. Returns ...
cca3e1724da08ffcb895aa9fc323ebaf380760e4
4,179
import re def extract_energyxtb(logfile=None): """ Extracts xtb energies from xtb logfile using regex matching. Args: logfile (str): Specifies logfile to pull energy from Returns: energy (list[float]): List of floats containing the energy in each step """ re_energy = re.comp...
075f9d48d3bcc9f6bd12aa791cc4d0444299dd74
4,180
def make_transaction_frame(transactions): """ Formats a transaction DataFrame. Parameters ---------- transactions : pd.DataFrame Contains improperly formatted transactional data. Returns ------- df : pd.DataFrame Daily transaction volume and dollar ammount. - S...
ab8feafb1a441fddf574ebd12a7720a7c4d7398b
4,182