content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from pathlib import Path def generate_filename(candidate: Path) -> Path: """Generate a filename which doesn't exist on the disk. This is not atomic.""" orig = candidate i = 0 while candidate.exists(): stem = orig.stem candidate = orig.with_stem(f"{stem}-{i}") i += 1 return...
4a304b30aac5091e8a3f59db3d7d293b272b92ef
70,600
import io def build_report( *tables_desc: TableDesc, width: int, height: int, ) -> bytes: """ Сформировать отчет :param tables_desc: Описания таблиц для отчета :param width: Ширина листа :param height: Высота листа """ with io.BytesIO() as buffer: doc = Simp...
18c584995d4bec27ed0a64dc0afd4ad774d2ca11
70,601
def _IsMPKeyName(name): """Returns True if the key name looks like MP (not pre-MP). An MP key name does not contain the strings "_premp" or "_premp", and ends in something like "_mp" or "_mp_v2" or "_mpv2". """ return (_MP_KEY_NAME_PATTERN.search(name) and not _PRE_MP_KEY_NAME_PATTERN.search(name))
24024cd1a3da57f0321f643f0b62e6e5427167bc
70,602
def getPlaylists(sg): """ Returns all playlists based on the show specified in the configuration file(s). Args: param1 (shotgun_api3.Shotgun): Shotgun DB Object. Returns: list: List of dictionaries with Shotgun entity information. """ sgPlaylists = sg.find( "Playlist",...
cec358f95dc9353a6636dd3adcea2c064626e069
70,603
def load_data(filename: str): """ Load Agoda booking cancellation dataset Parameters ---------- filename: str Path to house prices dataset Returns ------- Design matrix and response vector in either of the following formats: 1) Single dataframe with last column representing ...
3ab8e167df2305017fa3a6690f8b620020d75071
70,604
from typing import Optional def code_block(text: str, language: Optional[str]) -> str: """Formats text for discord message as code block""" return f"```{language or ''}\n" f"{text}" f"```"
c54d5b3e6f456745817efd03b89bd56d7fe4794e
70,605
def get_current_gw(): """ Returns the current gameweek """ return BOOTSTRAP_STATIC['current-event']
e4965f3155e4d36a2085b76a1bbf09c355a0b226
70,606
import sqlite3 def version(database): """ """ conn = bou.backing.open(database) try: with conn: curr = conn.cursor() smt = curr.execute(""" SELECT migration FROM _bou ORDER BY id LIMIT 1 """) ...
dada19f0f33f87a320db189faaca9f0a13d0fc55
70,607
import os def get_last_bounce(data_file_name): """ Find the index of the last bounce and return it. """ if not os.path.exists(data_file_name): return None with open(data_file_name, 'r') as data_file: lines = data_file.readlines() if len(lines) == 0: return None ...
d7a18e4581220f720e160e44896a76e77351e9c0
70,608
def _parse_hparams(hparams): """Split hparams, based on key prefixes. Args: hparams: hyperparameters Returns: Tuple of hparams for respectably: agent, optimizer, runner, replay_buffer. """ prefixes = ["agent_", "optimizer_", "runner_", "replay_buffer_"] ret = [] for prefix in prefixes: ret_...
22a2331b5772f00514ca1ddbb44f6e94e3782d76
70,609
from typing import Any def tvt_by_nors( ccagt: CCAgT, categories_infos: CategoriesInfos, tvt_size: tuple[float, float, float] = (.7, .15, .15), **kwargs: Any ) -> tuple[set[int], set[int], set[int]]: """This will split the CCAgT annotations based on the number of NORs into each image. With a s...
213c201c60b3186dd59fbb8e6576bcabffe64de0
70,610
from typing import Iterable def get_event_log_records( instance: DagsterInstance, last_storage_id: int, record_filter_limit: int ) -> Iterable[EventLogRecord]: """Returns a list of Dagster event log records in ascending order from the instance's event log storage. :param instance: ...
cf2ecc1284427fb5c7cb58ec9e26d30c303cd815
70,611
import requests import time def get_encryption_data(): """Dynamically obtain the Auth token public key and encryption algorithm. This function will make an API call to the auth server upon service start up when the environment variable ``PRODUCTION`` is set to ``true`` or ``beta``. The value of ``bet...
3cfd512657984d68e0ebae140d2bc1daddf09e98
70,612
def skia_select(conditions, results): """Replaces select() for conditions [UNIX, ANDROID, IOS] Args: conditions: [CONDITION_UNIX, CONDITION_ANDROID, CONDITION_IOS] results: [RESULT_UNIX, RESULT_ANDROID, RESULT_IOS] Returns: The result matching the platform condition. """ if len(conditions) != 3 o...
3304fd1c55dffbeb42a1a418040813ff2534b8f4
70,613
def date_search(date: str) -> list: """ Для поиска по дате в поле published_item таблицы rss_tab. Добавляет данные в log_tab, при поиске. :param date: подстрока, вхождение которой в published_item необходимо найти. :return: список словарей с результатами поиска из rss_tab. """ try: ...
6c9cb097b8b8220b559a734264a0afd112d4042c
70,614
from datetime import datetime import json def api(request): """ Handle the follow params: ?search=Something+yadda &start=2009-01-01-2014-12-30&end=2014-12-30 &point=-33.4246,151.3441, &distance=100 Code mostly written by Lyndon D'arcy (imported from https://github.com/logworthy/...
0f860a7432d54a48c8adabb90737dcfa1d0278c6
70,615
from typing import Union def _flight_intersects( flight: Flight, shape: Union[ShapelyMixin, base.BaseGeometry] ) -> bool: """Returns True if the trajectory is inside the given shape. - If an Airspace is passed, the 3D trajectory is compared to each layers constituting the airspace, with correspondi...
041644b9bb92d32943071cd7c51f545d44cfe271
70,616
import psutil def check_cpu_constrained(): """"Return True if the cpu is having too much usage, False otherwise.""" return psutil.cpu_percent(1) > 80
b5af66c73b9c85b9824b15bffc3915e69efa07d2
70,617
def np_inverse_softmax(x): """Invert a softmax operation over the last axis of a np.ndarray.""" return np.log(x / x[Ellipsis, :1])
124297e509f7d9b836b7c618335bde951cbc9087
70,618
import os def get_labels_for_images(image_dir: str, y_fpath: str, delimiter=","): """ Get labels for images stored in image_dir Parameters: image_dir: Filepath to directory with images y_fpath: Filepath to csv file with labels delimiter: Delimiter used in csv file Returns: ...
e8f64030997fe7050ff91c6c7b86439bb3a87126
70,619
def Fredkin_check(function): """Decorator to check the arguments of calling Fredkin gate. Arguments: function {} -- The tested function """ def wrapper(self, control_qubit): """Method to initialize Fredkin gate. Arguments: control_qubit {Qubit} -- Possible valu...
7b62bc1998baffcffa896a6a549c3044ebbc9abd
70,620
import os def combine_hypercubes(input_paths, output_dir, output_filename=None, do_compress=True): """ combine list of hypercubes into one file, for example when you created many h5 file in parallel with one subband per file. :param [str] input_paths: paths of the hdf5 files you want to read and combine ...
676cbfa0d347cb94275ad6aab9a5a4a7abc2220a
70,621
def current_scopes(): """ init security setting :return: pending """ return []
2aa8500f0c1487723d74d975cf9e50f92904e1de
70,622
def training_decoding_layer(dec_embed_input, target_length, dec_cell, initial_state, output_layer, vocab_size, max_target_length): """Create the training logits""" training_helper = tf.contrib.seq2seq.TrainingHelper(inputs=dec_embed_input, ...
60bcf80d8f9b8a540c23ae7fb474de240fc8e708
70,623
def subtend(x1, y1, x2, y2): """ANGLE SUBTENDED BY TWO VECTORS (wrt THE ORIGIN)""" # v1 (dot) v2 = |v1| |v2| cos(theta) # d = r1 r2 cos(theta) d = dot([x1, y1], [x2, y2]) r1 = hypot(x1, y1) r2 = hypot(x2, y2) costheta = d / (r1 * r2) theta = arccos(costheta) return theta
bfe8993c836c94cccc2cd98f85693cb1a53496ee
70,624
def GetWifiInterface(): """Gets the first Wi-Fi interface name. Returns: interface: str, the first Wi-Fi interface name (e.g. en0) or None if no interface exists. """ interfaces = systemconfig.GetNetworkInterfaces() for interface in interfaces: if interface['type'] == 'IEEE80211': return ...
a99b13ee7ea047d3461035fdda9d0f7b2f201d09
70,625
from typing import List def _load_images(img_list: List) -> np.ndarray: """ This private function loads the numpy array image files that are passed within input parameter and append them into a list :param img_list: List, Contains absolute paths to image.npy files :return: N-dimensional array, Loa...
eb47d06e29f3dbc22dcebd1cc636fc3e95c222bf
70,626
import csv def load_farm_attributes(crop_type): """ Loads the attributes for specified crop to be used in the farm vector attribute table """ with open(farm_attribute_table_path(crop_type), 'r') as f: reader = csv.DictReader(f) return list(reader)
e9df8c50c4198a417dd5cd0cde0dd69e2f195c91
70,627
def softmax_layer(avg_per_word, U, b, y_mask, maxw, training=False): """ Produces the final labels via softmax :param avg_per_word: Output from word-averaging :param U: Classification weight matrix :param b: Classification bias layer :param y_mask: Because not all fragments are the same length, ...
d54c6bad48580095671747e18d4e694ae34bde7b
70,628
from typing import Dict from typing import Any from typing import List def github_installation( options: Dict[str, Any], env: sphinx.environment.BuildEnvironment, ) -> List[str]: """ Source to provide instructions for installing from GitHub. :param options: Mapping of option names to values. :param env: Th...
e1d8d80cf0e84479e77e5e2093705e9b639b8e48
70,629
def attention_bias_local(length, max_backward, max_forward): """Create an bias tensor to be added to attention logits. A position may attend to positions at most max_distance from it, forward and backwards. This does not actually save any computation. Args: length: int max_backwar...
7548dc0d6ecdaa9dfcba66845d203c7fa1e088ed
70,630
def demo_regression_report(): """Make a demo regression report.""" x = np.linspace(0, np.pi * 4, 1001) truth = np.stack([np.sin(x), np.cos(x)], axis=-1) label = np.random.binomial(1, .2, size=x.shape) predict = np.stack([ truth[:, 0] + ( (1 - label) * np.random.normal(0., scale=....
895dd769ab44025fdd71a01bb87011e4a142dec0
70,631
import os def get_endpoints_credentials(): """ Gets the oauth2 credentials from the user authenticated to Google Cloud Endpoints. Presently, this does not work for Android and iOS clients. We are open to patches to fix it. """ user = endpoints.get_current_user() if not user: return Fa...
fc8c6abe94757bf03f8f0da40f5f16639673c712
70,632
from re import T import scipy def model2geogcoords( xg: dict[str, T.Any], parm: xarray.DataArray, lalt: int, llon: int, llat: int, altlims: tuple[float, float] = None, glonlims: tuple[float, float] = None, glatlims: tuple[float, float] = None, ): """ Grid the scalar GEMINI outp...
af4feeb974671a761e3a979bb45d6ad097d03755
70,633
import re from typing import Counter def tokenizeLyrics(genius,artist_name,track_name): """ Tokenize Lyrics of song Arguments: genius: artist_name: track_name: Return: line_split_lyrics: word_frequency """ #Initialize tokenizer tknzr = nltk.Twee...
365a7e522b9d2fece6081ea01513f13e941c23f2
70,634
def api_asset_get(): """Get assets with specified names from the bank""" names = request.args.getlist("name") result = [] for name in names: asset = app.bank.get(name) if asset: result.append(asset) return jsonify(sorted(result)), 200
83aff57d194f877967caa962b5e6abe8580e4f67
70,635
import itertools import scipy import numpy def cluster(point_list, std, chance_correct): """ Given a list of points (x,y), the standard deviation of the point position measurements, and the chance that the point is correctly identified as part of the group, this returns the expectation point of where ...
f440c96578a6b0b4aa219e60604046818568896c
70,636
def upsample_ps(x, r=(1, 1)): """ Performs phase shift upsampling for width and height Args: x: Tensor to upsample r: A tuple of upsample factors(height and width) (Default value = (1) Returns: Tensor with height of original_height*r[0] and width original_width*r[1] """ x = _p...
cabd3c4f76d2f099d71b08502854d362e91972f5
70,637
def _AddMergeFromStringMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def MergeFromString(self, serialized): length = len(serialized) try: if self._InternalParse(serialized, 0, length) != length: raise message_mod.DecodeError('Unexpected end-group tag.') except (...
777201a242f0a9dfca8b7234546926dd8b8a6188
70,638
import re def return_words_and_sentences(results): """Parse xml into word and sentence 'tier' data Args: results([TODO type]): [TODO description] Returns: [TODO type]: [TODO description] """ result_id_pattern = re.compile( r""" t(?P<table>\d*) # Table ...
efb8c5f7d49806a519806bebfd2998e7d4a2992f
70,639
def check_ratio_sum(ratio): """ Check the given ratio is valid or not. Sum of ratio should be 100 """ train_ratio = int(ratio[0]) val_ratio = int(ratio[1]) test_ratio = int(ratio[2]) qa_ratio = int(ratio[3]) total = train_ratio + test_ratio + val_ratio + qa_ratio if total != 100: raise ValueError("Sum of al...
34ce3c7c9e0edecbdaa54e44ed39060df150c8dd
70,640
def check_box( iou, difficult, crowd, order, matched_ind, iou_threshold, mpolicy="greedy" ): """Check box for tp/fp/ignore. Arguments: iou (np.array): iou between predicted box and gt boxes. difficult (np.array): difficult of gt boxes. order (np.array): sorted order of iou's. ...
581aac0b3541535c6cd91243ab99a842d0183f8b
70,641
def check_mnist_cifar_dataset(method): """A wrapper that wrap a parameter checker to the original Dataset(ManifestDataset, Cifar10/100Dataset).""" @wraps(method) def new_method(*args, **kwargs): param_dict = make_param_dict(method, args, kwargs) nreq_param_int = ['num_samples', 'num_parall...
932014d6a6e6046a4862d6c02b06414ab9ee4856
70,642
def parent_technique_of(thesrc): """return subtechnique_id => {technique, relationship} describing the parent technique of the subtechnique""" return get_related(thesrc, "attack-pattern", "subtechnique-of", "attack-pattern")[0]
f91c65ad8769b3adc157a7c783f15c6f49b0e465
70,643
def index(): """ 主页 :return: """ return render_template('index.html', remote_address=request.remote_addr)
62105d3b1373ff159655ae8e390081f65924b848
70,644
from typing import List def get_mol_props_for_map(mols: List[Chem.Mol]): """Return the heavy atom count, carbon fraction, ring atom fraction and largest ring size.""" hac = [] c_frac = [] ring_atom_frac = [] largest_ring_size = [] for mol in mols: atoms = mol.GetAtoms() size =...
0b5dbbe1e0ec17edc7c28cced3f196c5a38e6023
70,645
def get_chat_messages(chat_slug) -> QuerySet: """ get chat messages """ return Chat.objects.get(slug=chat_slug).message.filter()
ca80795bcbb99f6cb68dd3531d86d07927295f9e
70,646
def mock_qnode(mock_device): """Simple PassthruQNode with default properties.""" def circuit(x): qml.RX(x, wires=0) return qml.expval(qml.PauliZ(0)) node = PassthruQNode(circuit, mock_device) return node
97e1e4bbf3b879e80777d185ed219c54b11bb4cd
70,647
def removePEOversampling(src, axes=(-2, -1), dicom_offset=DICOM_OFFSET): """ Remove phase encoding (PE) oversampling. This is implemented such that they match with the DICOM knee images. :param src: input image (np.array) :param axes: tuple of axes containing the [nFE, nPE] dimension. :param...
b94cb7d7beba58e15ef275b18da2567e32cdc599
70,648
def is_rlp_structured_access_list(val): """Returns true if 'val' is a valid rlp-structured access list.""" if not is_list_like(val): return False for item in val: if not is_list_like(item): return False if len(item) != 2: return False address, storage_...
b21d3d45277a2a015f3a7b86fb767c3b7e7593a7
70,649
import ctypes def eul2m( angle3: float, angle2: float, angle1: float, axis3: int, axis2: int, axis1: int ) -> ndarray: """ Construct a rotation matrix from a set of Euler angles. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eul2m_c.html :param angle3: Rotation angle about third rotat...
78529692795b617b392a6552f0db71c8e5ca155d
70,650
import os def make_dataset(imgs_dir, annos_dir, pkl_path, imgs_set_path, labels="voc", show_dataset=False): """ :param imgs_dir: str :param annos_dir: str :param pkl_path: str :param imgs_set_path: str :param labels: str["coco", "voc"] or list[str] or Dict[str: int] 可多对一 :param show_datas...
d4ad0316ab763b5110462d4f573713196af92fca
70,651
from datetime import datetime def create_upcoming_test_datetime() -> datetime: """ Based on 2025-01-01 00:00:00 """ return datetime(2024, 1, 1, 0, 0, 0, 0)
9a6bc020fd44e0e59441a83b75d2e7fb7630d386
70,652
def urlsplit(url): """ Splits a URL like "https://example.com/a/b?c=d&e#f" into a tuple: ("https", ["example", "com"], ["a", "b"], ["c=d", "e"], "f") A trailing slash will result in a correspondingly empty final path component. """ split_on_anchor = url.split("#", 1) split_on_query = split_o...
47cd2b556f842dd3ed499f841ff41d16c0747cbc
70,653
from typing import Any def validator(message: ErrorMessage): """ Turn a bare checker function into a descriptive validator function """ def decor(fun: CheckerFunction) -> ValidatorFunction: def inner(value: Any) -> ValidatorReturn: ok = fun(value) if not ok: ...
d13ddf5f691850e22633a7d8d011f70153826772
70,654
def separate(df, key, into, splitter=default_splitter): """Given a data frame, separates one of its columns, the key, into new variables. """ assert type(df) is pd.DataFrame assert key in df.columns # Hint: http://stackoverflow.com/questions/16236684/apply-pandas-function-to-column-to-creat...
dff62cda31086dcdf0aa8f5aa4ffb28e0fed01f4
70,655
def build_old_belief( belief_type, num_agents=NUM_AGENTS, *, low_pole=LOW_POLE, high_pole=HIGH_POLE, step=BELIEF_STEP, consensus_value=CONSENSUS_VALUE): """Builds the initial belief state according to the `belief_type`. Helper function when iterating over...
6ef5222c536acc5c9cf4496e697dd9520388c8a4
70,656
def create_markup(s, modifiers=None, targets=None, span=None, prune_inactive=True): """Creates a markup object from a sentence. s is a sentence from a list of a split report. span is the tuple of the span of the sentence. Optional. Returns a named tuple where markup=markup, span=span """ markup ...
c454010cfe272f35e11e111c29027bdc28d09c35
70,657
def sub_timedelta(date, delta, units='hours since 1800-01-01 00:00', calendar='standard'): """ Wrapper method to subtract a timedelta to a netcdftime.datetime or datetime.datetime or pd.Timestap object Parameters ---------- date : scalar_like Date to subtract <delt...
d309f58a1bf309ab11a7fd8bef1e5ba1b3cb6ac2
70,658
from typing import Optional from typing import Mapping from typing import Any def _process_environ(environ: Optional[Mapping[str, Any]] = None, ext_environ: Optional[Mapping[str, Any]] = None, enable_ext: bool = False) -> Mapping[str, str]: """ process environment var...
7ded58157f59fdb63ced8d680fd9cb1c5041416c
70,659
def rotate_key(element): """Returns a new key-value pair of the same size but with a different key.""" (key, value) = element return key[-1] + key[:-1], value
e9407e87a24571bb17e484d7954764dce38003dc
70,660
def labels_to_tags(labels): """Converts integer labels to component type labels. Input: array of integer labels Output: arry of string tags """ tag_dict = {v:k for k, v in config['arg_components'].items()} tag_dict[len(tag_dict)] = 'pad' return [tag_dict[i] for i in labels]
d7a6fcf6d77699d4f4ef4d748838ad487431d979
70,661
import math def hypotenuse_length(leg_a, leg_b): """Find the length of a right triangle's hypotenuse :param leg_a: length of one leg of triangle :param leg_b: length of other leg of triangle :return: length of hypotenuse >>> hypotenuse_length(3, 4) 5 """ return math.sqrt(leg_a**2...
7a59ede73301f86a8b6ea1ad28490b151ffaa08b
70,662
def build_add_trunk_vlan(interface, vlan, action): """Build BGP config using Jinja2""" with open(build_vlan_to_trunk) as trunk_file: build_vlan_trunk_template = Template(trunk_file.read(), keep_trailing_newline=True, trim_blocks=True, lstrip_blocks=True) vlan_trunk_config_j2 = build_vlan_trunk_...
ff611bb055e0852e483ff3c7e330a8e27b50c8b4
70,663
def getParent(obj): """ Returns the container the object was traversed via. See `ITraversalAPI` for details. """ try: location_info = ILocationInfo(obj) except TypeError: pass else: return location_info.getParent() # XXX Keep the old implementation as the fallba...
b05f9158fc60e440f86edf25cf8b06b91190d887
70,664
def minimize_ucq_in_dnf(query): """Convert UCQ to DNF form and minimise. Parameters ---------- query : LogicExpression. query in UCQ semantics. Returns ------- LogicExpression minimised query in UCQ semantics. """ query = convert_to_dnf_ucq(query) head_varia...
94f4c1e54f2b2a5dae4099902b8c2fad065d1104
70,665
def vsh_larionov_tertiary(gr, sand_line, shale_line): """ Apply Larinov equation (Larinov, 1969) to correct Gamma Ray index Vshale values. """ shale_line = float(shale_line) sand_line = float(sand_line) vsh_grindex = (gr - sand_line)/(shale_line - sand_line) vsh_larionov = 0.08...
d38092f79f4c50af2ef8f6865271a7d35a4d3b69
70,666
from typing import Union from typing import List def bincoeff(n: int, k: int = None) -> Union[int, List[int]]: """Computes the binomial coefficients of `(1 + x)^n` or returns the k-th coefficient """ if k is not None: return comb(n, k) else: result = [] for i in range(0, n + 1)...
b82a4c03470c3ded25738bc664ede8d4d2e7a217
70,667
import re def key_search (search_string, dict, silent=True): """Поиск нужного объекта в словаре, выбор по списку совпадений.""" # Создаётся регистронезависимая поисковая строка: p = re.compile(search_string, re.I) # Создаём словарь совпадений: d_found = {} counter = 0 # Поиск в словаре: ...
eea262b433f85ccb076bad34dde47b31fe02723e
70,668
def Or(a: Bit, b: Bit) -> Bit: """ Or gate out = True if (a == True or b == True) , False otherwise ``` +-------+ | | a +--+ NOT +--+ +--------+ | | +--+ | +-------+ | NAND +--+ out +---+ | +---...
0d3c3393089102370c46d8361fadd66758c42e59
70,669
import os from datetime import datetime from bs4 import BeautifulSoup def _post_project(prj=None): """Method that will post a project and return an api_types.Project.""" template_path = (os.path.join( os.path.split(__file__)[0], "post_project_template.xml")) with open(template_path, 'r') as file: ...
f7555cde6824366a2ac569ce092c8c41b1ee45ec
70,670
import numpy def ddspline(alpha, control_points): """Computes the second derivative of a Cubic Bezier curve wrt alpha. Args: alpha: scalar or list of spline parameters to calculate the curve at. control_points: n x 4 matrix of control points. n[:, 0] is the starting point, and n[...
4b739195183991c81dae968196339719597bf846
70,671
def make_rowcol(string): """ Creates a rowcol function similar to the rowcol function of a view Arguments: string -- The string on which the rowcol function should hold Returns: A function similar to the rowcol function of a sublime text view """ rowlens = [len(x) + 1 for x in string.s...
87a0c162c69dd8f1e4e50f3b40da8772e645772e
70,672
def sigmoid(x, derivative=False): """ Returns the sigmoid function applied to x. Alternatively, can return the derivative or the sigmoid function. Args: x (np.ndarray): The input to the sigmoid function. derivative (bool): Whether to return the derivative or not. Default: Fa...
b23e7316f902b8632de7751d1a1715172fb75846
70,673
def search_service(): """Connect to Google's Search API service with oauth2 using the discovery service.""" return google_service(DCLK_SEARCH_SCOPE)
065cba99bbd7258828b50c9cae8368130363c68c
70,674
def compute_llr(c, means, sds): """Compute the pulse log-likelihood supporting Target 1.""" # Define the generating distributions m0, m1 = means s0, s1 = sds d0, d1 = stats.norm(m0, s0), stats.norm(m1, s1) # Compute LLR of each pulse l0, l1 = np.log10(d0.pdf(c)), np.log10(d1.pdf(c)) llr...
16c769699a5df77eba344abda5033b5e7f2743c9
70,675
def fake_gauss_1(num_list): """Fake Gauss v1""" a = num_list[0] b = num_list[-1] n = b - a + 1 return int(n * (n + 1)/2)
d99cff9196e8a365e1260eee6625db22a25da70c
70,676
def get_activation_function(activation_fn_name: str): """Convert from an activation function name to the function itself.""" if activation_fn_name is None: return None activation_fn_name = activation_fn_name.lower() string_to_activation_fn = { "linear": None, "tanh": tf.nn.tanh,...
8d814aa9a3b53402fbd7b33653e12fb71269268b
70,677
import http from typing import Optional import gzip from datetime import datetime def export( request: http.HttpRequest, pklist: str, workflow: Optional[models.Workflow] = None, ) -> http.HttpResponse: """Export the actions given as comma separated list of ids. :param request: :param pklist: ...
4c5b4f1faae08896a275dbb05a39bcfa22f53f57
70,678
import multiprocessing as mp import logging import os import io import subprocess def loop_alt_ledger(obscon, survey='sv3', zcatdir=None, mtldir=None, altmtlbasedir=None, ndirs = 3, numobs_from_ledger=True, secondary=False, singletile = None, singleDate = None, debugOrig = False, ...
1cc9bcd06bc902c84865fab05404cd5238da9909
70,679
def check_conf_validity(config_dict): """A configuration validity test. Return false if any required option is not valid. """ if not config_dict["sample.sample_id"].isdigit(): error("Config Validity Check: sample id -- %s should be specified and be an integer!" % config_dict["sample.sample_id"]) ...
e8c04847c9e9e209a09184b98d16525143c45397
70,680
def pathManager(fileName,writingMode,askedForGoAhead,showedOverwriting,filesThatExistedBeforeExe,createdFileNames,lineNum): """Takes care of file location, naming conventions, and confirmation to overwrite filtered files.""" goAhead = False subDirName = [] subDirName.append('FL') splitFileName ...
a7e5127a64ca6d5a2e1f9fadc1cfaca1da0c46fb
70,681
from typing import List import statistics def remove_outliers(numbers: List[float], num_deviations: float = 3): """ >>> remove_outliers([0, 1, 2, 3, 4, 5, 50, 6, 7, 8, 9], num_deviations=1) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] """ if len(numbers) < 2: return numbers avg = statistics.mean(num...
251e739a301bc06f40e4847f5bdb7282012bfce9
70,682
def test_ironic_create_node( mocker, admin_context: "RequestContext", ironic_worker: "IronicWorker", database: "utils.DBFixtures", ): """Test that new nodes are created if not already existing.""" get_node_count = 0 patch_node_count = 0 fake_hw = get_fake_hardware(database) def _fak...
2cafaadca9706245b6fb23c1bde08c36e1adb94c
70,683
import requests def _get_page_num_gpzy_distribute_statistics_bank() -> int: """ 东方财富网-数据中心-特色数据-股权质押-质押机构分布统计-银行 http://data.eastmoney.com/gpzy/distributeStatistics.aspx :return: int 获取 质押机构分布统计-银行 的总页数 """ url = "http://dcfm.eastmoney.com/EM_MutiSvcExpandInterface/api/js/get" params = { ...
452f1353475315277a820486de4c30f8886784f9
70,684
from anndata.base import _normalize_index from scipy.sparse import dok_matrix def rna_velocity(adata, loomfile, copy=False): """Estimate RNA velocity [LaManno17]_ This requires generating a loom file with Velocyto, which will store the counts of spliced, unspliced and ambiguous RNA for every cell and eve...
b4cc0ed98be63279fbb10fc290356ae73001f0d1
70,685
def commonPoints(lines): """ Given a list of lines, return dictionary - vertice -> count. Where count specifies how many lines share the vertex. """ count = {} for l in lines: for c in l.coords: count[c] = count.get(c, 0) + 1 return count
1b838ddd4d6a2539b0270cd319a2197e90372c3a
70,686
def compare(isamAppliance1, isamAppliance2): """ Compare access policies between two appliances """ ret_obj1 = get_all(isamAppliance1) ret_obj2 = get_all(isamAppliance2) obj1 = {'rc': 0, 'data': []} obj2 = {'rc': 0, 'data': []} for attr in ret_obj1["data"]: if search(isamApplia...
ddb55360bd9d316210598d9575de1cda50100a24
70,687
def entity_in(entity, entities, primary_field=ct.default_int64_field_name): """ according to the primary key to judge entity in the entities list :param entity: dict {"int": 0, "vec": [0.999999, 0.111111]} :param entities: list of dict [{"int": 0, "vec": [0.999999, 0.111111]}, {"...
997661015fecd562aaa064ad097747de222d5153
70,688
def is_covered_package_name(package_name): """We exclude third-party code and code generated by javacc.""" if not package_name.startswith('com/facebook/buck/'): return False if package_name == 'com/facebook/buck/apple/xcode/xcconfig': # TODO: This package has a mix of handwritten and autogen...
297ca5ec190d149c2660a19a311a753d6f86403a
70,689
def miller_rabin_test(candidate, iterations, randfunc=None): """Perform a Miller-Rabin primality test on an integer. The test is specified in Section C.3.1 of `FIPS PUB 186-4`__. :Parameters: candidate : integer The number to test for primality. iterations : integer The maximum...
a334003b7467921246313784d60407ddafa0221e
70,690
from typing import Any async def change_account_password( schema_in: schemas.SendEmailChangePassword, db: AsyncSession = Depends(deps_auth.db_session) ) -> Any: """Send email to change user password""" auth_data = AuthorizationData.where( login=schema_in.login, registration_type=enums....
51aab1dee48faa7efd1a535f3c200a9c2467a400
70,691
import os def fullpath(path): """Expands ~ and returns an absolute path""" return os.path.abspath(os.path.expanduser(path))
9299d60d67214a19fd0c2739beda4fa3b55ac38a
70,692
import struct def load(input_data, key_is_name=False): """ py:function:: piexif.load(filename) Return exif data as dict. Keys(IFD name), be contained, are "0th", "Exif", "GPS", "Interop", "1st", and "thumbnail". Without "thumbnail", the value is dict(tag name/tag value). "thumbnail" value is JPEG as byte...
0bac04b7d533514e96f4dea694bd2865ff4ae495
70,693
def _enum_wordnetsyn_match(enum_hypothesis_list, enum_reference_list, wordnet=wordnet): """ Matches each word in reference to a word in hypothesis if any synonym of a hypothesis word is the exact match to the reference word. :param enum_hypothesis_list: enumerated hypothesis list :param enum_re...
52b42dd87f693c3681f3fa94a68096e3f4ff3f79
70,694
import os.path, glob def GetDbNames(user='sysdba', password='masterkey', dirName='.', dBase='::template1', cn=None): """ returns a list of databases that are available **Arguments** - user: the username for DB access - password: the password to be used for DB access **Returns** - a li...
33b0d1a4a541a18b5134b43fac6dd0c52ee4c292
70,695
def spring_model(): """ Creates a SpringMassModel object. """ return SpringMassModel(mass=1.5, time_step=1.0, cost=1.0)
ecf68b593c0118b5b49304232318a3a214682adf
70,696
def plotting_context(): """Context for plotting with Quantity objects Based on : https://docs.astropy.org/en/stable/_modules/astropy/visualization/units.html#quantity_support """ # Get all subclass for Quantity, since matplotlib checks on class, # not subclass. def all_issubclass(...
06768c3aaad5bb28c8b81d6900adc2db05ff4e04
70,697
def start_redis(node_ip_address, redirect_files, resource_spec, session_dir_path, port=None, redis_shard_ports=None, num_redis_shards=1, redis_max_clients=None, redirect_worker_output=False, ...
c8218a55fb46ce8b7e909c72fd34c03b851f7580
70,698
import os def add_meta_and_doc_file(test_name, json_name): """ create .meta/tests.toml .meta/config.json .docs/instructions.md (based on ../problem-specifications/exercises/[EXERCISE]/description.md) for test_name Not yet implemented. """ test_dir_name = os.pa...
1181e82b627175c885ae34b01d6e8a811793956f
70,699