content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Dict def rand_index(pred_cluster: Dict, target_cluster: Dict) -> float: """Use contingency_table to get RI directly RI = Accuracy = (TP+TN)/(TP,TN,FP,FN) Args: pred_cluster: Dict element:cluster_id (cluster_id from 0 to max_size)| predicted clusters target_cluster: Dict...
19ccbd6708abe6b3a05dc23843fa21e0f6d804e9
3,648,600
import re import time from datetime import datetime def _strToDateTimeAndStamp(incoming_v, timezone_required=False): """Test (and convert) datetime and date timestamp values. @param incoming_v: the literal string defined as the date and time @param timezone_required: whether the timezone is required (ie, ...
fa0362976c3362e32c4176b4bd4c84ae0c653080
3,648,601
def get_price_for_market_stateless(result): """Returns the price for the symbols that the API doesnt follow the market state (ETF, Index)""" ## It seems that for ETF symbols it uses REGULAR market fields return { "current": result['regularMarketPrice']['fmt'], "previous": result['regularMark...
6afb9d443f246bd0db5c320a41c8341953f5dd7a
3,648,602
def make_sure_not_modified(arg): """ Function checking whether annotation of SomeList is never resized and never modified, useful for debugging. Does nothing when run directly """ return arg
ef86ed28a7e5ebdac27b7cee85fddec669604798
3,648,603
def jump(current_command): """Return Jump Mnemonic of current C-Command""" #jump exists after ; if ; in string. Always the last part of the command if ";" in current_command: command_list = current_command.split(";") return command_list[-1] else: return ""
2530ae99fcc4864c5e529d783b687bfc00d58156
3,648,604
def get_veterans(uname=None): """ @purpose: Runs SQL commands to querey the database for information on veterans. @args: The username of the veteran. None if the username is not provided. @returns: A list with one or more veterans. """ vet = None if uname: command = "SELECT * FROM v...
df97dee334332613b52c745c3f20c4509c0e0cb9
3,648,605
from matplotlib.collections import LineCollection def multiline(xs, ys, c=None, ax=None, **kwargs): """ Plot lines with different colorings Adapted from: https://stackoverflow.com/a/50029441/2565317 Parameters ---------- xs : iterable container of x coordinates ys : iterable container of...
d91c60faf89422f7d6659357946e816d87dd6ef8
3,648,606
def mock_movement_handler() -> AsyncMock: """Get an asynchronous mock in the shape of an MovementHandler.""" return AsyncMock(spec=MovementHandler)
85579588dc5d8e6cb37bc85bc652f70d3fca8022
3,648,607
def compute( op , x , y ): """Compute the value of expression 'x op y', where -x and y are two integers and op is an operator in '+','-','*','/'""" if (op=='+'): return x+y elif op=='-': return x-y elif op=='*': return x*y elif op=='/': return x/y else: r...
dbdf73a91bdb7092d2a18b6245ce6b8d75b5ab33
3,648,608
def list_arg(raw_value): """argparse type for a list of strings""" return str(raw_value).split(',')
24adb555037850e8458cde575ed360265a20cea5
3,648,609
def create_tracking(slug, tracking_number): """Create tracking, return tracking ID """ tracking = {'slug': slug, 'tracking_number': tracking_number} result = aftership.tracking.create_tracking(tracking=tracking, timeout=10) return result['tracking']['id']
4f5d645654604787892f1373759e5d40ce01b2fe
3,648,610
def get_indentation(line_): """ returns the number of preceding spaces """ return len(line_) - len(line_.lstrip())
23a65ba620afa3268d4ab364f64713257824340d
3,648,611
def main(): """ Find the 10001th prime main method. :param n: integer n :return: 10001th prime """ primes = {2, } for x in count(3, 2): if prime(x): primes.add(x) if len(primes) >= 10001: break return sorted(primes)[-1]
3d4f492fe3d0d7e4991003020694434145cd5983
3,648,612
import re def findDataById(objectids, level=None, version=None): """Return xml list of urls for each objectid.""" if sciflo.utils.isXml(objectids): et, xmlNs = sciflo.utils.getXmlEtree(objectids) objectids = et.xpath('.//_default:objectid/text()', xmlNs) infoLoL = [] headerLoL = ['obj...
85fdfcbd0e3733981e3ecfaf039abb5a7630cf35
3,648,613
import argparse def node_parameter_parser(s): """Expects arguments as (address,range,probability)""" try: vals = s.split(",") address = int(vals[0]) range = float(vals[1]) probability = float(vals[2]) return address, range, probability except: raise argparse...
a1d378d5f71b53fb187a920f71d7fc3373e775df
3,648,614
def launch(context, service_id, catalog_packages=""): """ Initialize the module. """ return EnvManager(context=context, service_id=service_id, catalog_packages=catalog_packages)
ba22d106efca9014d118daf4a8880bbcfe0c11fa
3,648,615
def handle_verification_token(request, token) -> [404, redirect]: """ This is just a reimplementation of what was used previously with OTC https://github.com/EuroPython/epcon/pull/809/files """ token = get_object_or_404(Token, token=token) logout(request) user = token.user user.is_acti...
f369dc743d875bee09afb6e2ca4a2c313695bcbc
3,648,616
def multi_perspective_expand_for_2d(in_tensor, weights): """Given a 2d input tensor and weights of the appropriate shape, weight the input tensor by the weights by multiplying them together. """ # Shape: (num_sentence_words, 1, rnn_hidden_dim) in_tensor_expanded = tf.expand_dims(in_tensor, axis=...
3d153e0bd9808dcd080f3d0ba75ee3bdd16123d3
3,648,617
import mimetypes import os import uuid def get_temp_url(src, *args): """ Caches `data` in a file of type specified in `mimetype`, to the images/temp folder and returns a link to the data. The generated URL is used only once, after it is accessed, the data is deleted from the machine. Argument: ...
f20d2625df13be848a0edc046b62533092d55578
3,648,618
import base64 def generateBasicAuthHeader(username, password): """ Generates a basic auth header :param username: Username of user :type username: str :param password: Password of user :type password: str :return: Dict containing basic auth header :rtype: dict >>> generateBasicAu...
835b3541212e05354a5573a5b35e8184231c7a6c
3,648,619
def correlation(df, target, limit=0, figsize=None, plot=True): """ Display Pearson correlation coefficient between target and numerical features Return a list with low-correlated features if limit is provided """ numerical = list(df.select_dtypes(include=[np.number])) numerical_f = [n for n i...
044f4708ad691ad4d275c58ff6dbd5a57a6a978d
3,648,620
def fasta_to_raw_observations(raw_lines): """ Assume that the first line is the header. @param raw_lines: lines of a fasta file with a single sequence @return: a single line string """ lines = list(gen_nonempty_stripped(raw_lines)) if not lines[0].startswith('>'): msg = 'expected the...
e75bd1f08ab68fa5a2a0d45cb23cba087e078d30
3,648,621
def pc_proj(data, pc, k): """ get the eigenvalues of principal component k """ return np.dot(data, pc[k].T) / (np.sqrt(np.sum(data**2, axis=1)) * np.sqrt(np.sum(pc[k]**2)))
768a4a9eba6427b9afda8c34326c140b360feec3
3,648,622
from datetime import datetime def compare_time(time_str): """ Compare timestamp at various hours """ t_format = "%Y-%m-%d %H:%M:%S" if datetime.datetime.now() - datetime.timedelta(hours=3) <= \ datetime.datetime.strptime(time_str, t_format): return 3 elif datetime.datetime.now() - datet...
b3d6d85e4559fa34f412ee81825e4f1214122534
3,648,623
def trendline(xd, yd, order=1, c='r', alpha=1, Rval=True): """Make a line of best fit, Set Rval=False to print the R^2 value on the plot""" #Only be sure you are using valid input (not NaN) idx = np.isfinite(xd) & np.isfinite(yd) #Calculate trendline coeffs = np.polyfit(xd[idx], yd[idx], order...
af10643b0d74fd5f7a82f803bcef0bd9e379f086
3,648,624
import collections def groupby(key, seq): """ Group a collection by a key function >>> names = ['Alice', 'Bob', 'Charlie', 'Dan', 'Edith', 'Frank'] >>> groupby(len, names) # doctest: +SKIP {3: ['Bob', 'Dan'], 5: ['Alice', 'Edith', 'Frank'], 7: ['Charlie']} >>> iseven = lambda x: x % 2 == 0 ...
bfbec3f25d1d44c9ff2568045508efbf2a2216d2
3,648,625
def evo(): """Creates a test evolution xarray file.""" nevo = 20 gen_data = {1: np.arange(nevo), 2: np.sin(np.linspace(0, 2*np.pi, nevo)), 3: np.arange(nevo)**2} data = {'X1': np.linspace(0.1, 1.7, nevo)*_unit_conversion['AU'], 'X2': np.deg2rad(np.linspace(6...
5873a3ee7a66d338a8df6b8cf6d26cf4cfeb41a3
3,648,626
from typing import List from typing import Any from typing import Optional def jinja_calc_buffer(fields: List[Any], category: Optional[str] = None) -> int: """calculate buffer for list of fields based on their length""" if category: fields = [f for f in fields if f.category == category] return max...
c1f619acd8f68a9485026b344ece0c162c6f0fb0
3,648,627
def get_delete_op(op_name): """ Determine if we are dealing with a deletion operation. Normally we just do the logic in the last return. However, we may want special behavior for some types. :param op_name: ctx.operation.name.split('.')[-1]. :return: bool """ return 'delete' == op_name
508a9aad3ac6f4d58f5890c1abc138326747ee51
3,648,628
import json def label(img_id): """ GET: return the current label for <img_id> POST: update the current label for <img_id> """ if request.method == 'PUT': #TODO: figure out how to get `request` to properly parse json on PUT req_dict = json.loads(request.data.decode()) with ...
c5e543fec0033f5888d99b7dce9f84faed70ff76
3,648,629
def random_radec(nsynths, ra_lim=[0, 360], dec_lim=[-90, 90], random_state=None, **kwargs): """ Generate random ra and dec points within a specified range. All angles in degrees. Parameters ---------- nsynths : int Number of random points to generate. ra_lim : list-l...
4649d5f8e42ada28ba45c46fac1174fc66976f16
3,648,630
def warmUp(): """ Warm up the machine in AppEngine a few minutes before the daily standup """ return "ok"
f7c83939d224b06db26570ab8ccc8f04bd69c1d6
3,648,631
def setToC(doc, toc, collapse=1): """Create new outline tree (table of contents, TOC). Args: toc: (list, tuple) each entry must contain level, title, page and optionally top margin on the page. None or '()' remove the TOC. collapse: (int) collapses entries beyond this level. Zero or...
a07648574b1bea850b4739c0e55505bbb2efe139
3,648,632
def _map_dvector_permutation(rd,d,eps): """Maps the basis vectors to a permutation. Args: rd (array-like): 2D array of the rotated basis vectors. d (array-like): 2D array of the original basis vectors. eps (float): Finite precision tolerance. Returns: RP (list): The perm...
3060cb093d769059f2af0635aafc0bd0fe94ad86
3,648,633
from astropy.time import Time import os import time import glob from datetime import datetime import re from io import StringIO import shutil from re import DEBUG import subprocess def dump_lightcurves_with_grcollect(photfileglob, lcdir, maxmemory, objectidcol=3, ...
ba3dd1d1334964752596d543a629dfcfe9fa8b93
3,648,634
import re def varPostV(self,name,value): """ Moving all the data from entry to treeview """ regex = re.search("-[@_!#$%^&*()<>?/\|}{~: ]", name) #Prevent user from giving special character and space character print(regex) if not regex == None: tk.messagebox.showerror("Forbidden Entry","The var...
07e108df0ff057ee42e39155562b32fa651ba625
3,648,635
def _mysql_int_length(subtype): """Determine smallest field that can hold data with given length.""" try: length = int(subtype) except ValueError: raise ValueError( 'Invalid subtype for Integer column: {}'.format(subtype) ) if length < 3: kind = 'TINYINT' ...
3a0e84a3ac602bb018ae7056f4ad06fe0dcab53b
3,648,636
def get_ci(vals, percent=0.95): """Confidence interval for `vals` from the Students' t distribution. Uses `stats.t.interval`. Parameters ---------- percent : float Size of the confidence interval. The default is 0.95. The only requirement is that this be above 0 and at or below 1. ...
1d5e311aab4620e070efcf685505af4a072e56eb
3,648,637
from typing import OrderedDict from datetime import datetime def kb_overview_rows(mode=None, max=None, locale=None, product=None, category=None): """Return the iterable of dicts needed to draw the new KB dashboard overview""" if mode is None: mode = LAST_30_DAYS docs = Document.objects.filte...
768d9aacf564e17b26beb53f924575202fea3276
3,648,638
def test_query_devicecontrolalert_facets(monkeypatch): """Test a Device Control alert facet query.""" _was_called = False def _run_facet_query(url, body, **kwargs): nonlocal _was_called assert url == "/appservices/v6/orgs/Z100/alerts/devicecontrol/_facet" assert body == {"query": "B...
6a0182a7b9ad15e5194bcc80aba19ab386e71f35
3,648,639
from typing import List from typing import Optional from typing import Set import math def plot_logs(experiments: List[Summary], smooth_factor: float = 0, ignore_metrics: Optional[Set[str]] = None, pretty_names: bool = False, include_metrics: Optional[Set[str]] ...
742ba64568f89e679ff3ec8dbb60894130f75a0d
3,648,640
def regularity(sequence): """ Compute the regularity of a sequence. The regularity basically measures what percentage of a user's visits are to a previously visited place. Parameters ---------- sequence : list A list of symbols. Returns ------- float 1 minus th...
e03d38cc3882ea5d0828b1f8942039865a90d49d
3,648,641
from typing import List def _make_tick_labels( tick_values: List[float], axis_subtractor: float, tick_divisor_power: int, ) -> List[str]: """Given a collection of ticks, return a formatted version. Args: tick_values (List[float]): The ticks positions in ascending order. tick_d...
13aaddc38d5fdc05d38a97c5ca7278e9898a8ed1
3,648,642
import pickle def load_coco(dataset_file, map_file): """ Load preprocessed MSCOCO 2017 dataset """ print('\nLoading dataset...') h5f = h5py.File(dataset_file, 'r') x = h5f['x'][:] y = h5f['y'][:] h5f.close() split = int(x.shape[0] * 0.8) # 80% of data is assigned to the training ...
b924b13411075f569b8cd73ee6d5414a4f932a17
3,648,643
def eval_rule(call_fn, abstract_eval_fn, *args, **kwargs): """ Python Evaluation rule for a numba4jax function respecting the XLA CustomCall interface. Evaluates `outs = abstract_eval_fn(*args)` to compute the output shape and preallocate them, then executes `call_fn(*outs, *args)` which is the...
6e52d9bdeda86c307390b95237589bd9315829ad
3,648,644
def bev_box_overlap(boxes, qboxes, criterion=-1): """ Calculate rotated 2D iou. Args: boxes: qboxes: criterion: Returns: """ riou = rotate_iou_gpu_eval(boxes, qboxes, criterion) return riou
4614a3f8c8838fc4f9f32c2ef625274239f36acf
3,648,645
def filter_shape(image): """画像にぼかしフィルターを適用。""" weight = ( (1, 1, 1), (1, 1, 1), (1, 1, 1) ) offset = 0 div = 9 return _filter(image, weight, offset, div)
f16c181c0eb24a35dfc70df25f1977a04dc9b0f5
3,648,646
import sys def ppretty(obj, indent=' ', depth=4, width=72, seq_length=5, show_protected=False, show_private=False, show_static=False, show_properties=False, show_address=False, str_length=50): """Represents any python object in a human readable format. :param obj: An object to repr...
90781dd00d5d0eca25e82dfb0d33f3240ccc8ab9
3,648,647
def makeTriangularMAFdist(low=0.02, high=0.5, beta=5): """Fake a non-uniform maf distribution to make the data more interesting - more rare alleles """ MAFdistribution = [] for i in xrange(int(100*low),int(100*high)+1): freq = (51 - i)/100.0 # large numbers of small allele freqs for j in r...
4210fffbe411364b2de8ffbc1e6487c8d3a87a09
3,648,648
def create_structures_hdf5_stitched_ref_gene_file_npy(stitching_file, joining, nr_pixels, reference_gene, blend = 'non linear'): """Takes an HDF5 file handle and creates the necessary structures. Modification of create_structures_hdf5_files to work with .npy list of files ...
2ddbc18f2f946e429ca5fcefd03a5108edbecd36
3,648,649
def contains_whitespace(s : str): """ Returns True if any whitespace chars in input string. """ return " " in s or "\t" in s
c5dc974988efcfa4fe0ec83d115dfa7508cef798
3,648,650
import itertools def get_files_to_check(files, filter_function): # type: (List[str], Callable[[str], bool]) -> List[str] """Get a list of files that need to be checked based on which files are managed by git.""" # Get a list of candidate_files candidates_nested = [expand_file_string(f) for f in files]...
6b508745aa47e51c4b8f4b88d7a2dff782289206
3,648,651
def main(argv): """Parse the argv, verify the args, and call the runner.""" args = arg_parse(argv) return run(args.top_foods, args.top_food_categories)
bb2da95cec48b1abfa0e1c0064d413e55767aa89
3,648,652
import requests def _failover_read_request(request_fn, endpoint, path, body, headers, params, timeout): """ This function auto-retries read-only requests until they return a 2xx status code. """ try: return request_fn('GET', endpoint, path, body, headers, params, timeout) except (requests.exceptions.Request...
731a14e72ff4fa88f160215f711fcca2199c736c
3,648,653
def GenerateConfig(context): """Generates configuration.""" image = ''.join(['https://www.googleapis.com/compute/v1/', 'projects/google-containers/global/images/', context.properties['containerImage']]) default_network = ''.join(['https://www.googleapis.com/compute/v1/projec...
4dbf579c780b0305b4a0b5dcfb3860a086867cbb
3,648,654
from typing import Optional from typing import List async def read_all_orders( status_order: Optional[str] = None, priority: Optional[int] = None, age: Optional[str] = None, value: Optional[str] = None, start_date: Optional[str] = None, end_date: Optional[str] = None, db: AsyncIOMotorClien...
28200a5dd9c508690ad3234c3080f0bb44a425c4
3,648,655
def read_log_file(path): """ Read the log file for 3D Match's log files """ with open(path, "r") as f: log_lines = f.readlines() log_lines = [line.strip() for line in log_lines] num_logs = len(log_lines) // 5 transforms = [] for i in range(0, num_logs, 5): meta_data...
dcd010f27c94d5bcd2287cb83765fe0eca291628
3,648,656
import math def divide_list(l, n): """Divides list l into n successive chunks.""" length = len(l) chunk_size = int(math.ceil(length/n)) expected_length = n * chunk_size chunks = [] for i in range(0, expected_length, chunk_size): chunks.append(l[i:i+chunk_size]) for i in range(le...
bad7c118988baebd5712cd496bb087cd8788abb7
3,648,657
def sigma(n): """Calculate the sum of all divisors of N.""" return sum(divisors(n))
13dd02c10744ce74b2a89bb4231c9c055eefa065
3,648,658
def ATOMPAIRSfpDataFrame(chempandas,namecol,smicol): """ AtomPairs-based fingerprints 2048 bits. """ assert chempandas.shape[0] <= MAXLINES molsmitmp = [Chem.MolFromSmiles(x) for x in chempandas.iloc[:,smicol]] i = 0 molsmi = [] for x in molsmitmp: if x is not None: x...
cb2babbebd60162c4cc9aa4300dba14cc2cf7ce8
3,648,659
def filter_by_minimum(X, region): """Filter synapses by minimum. # Arguments: X (numpy array): A matrix in the NeuroSynapsis matrix format. # Returns: numpy array: A matrix in the NeuroSynapsis matrix format. """ vals = np.where((X[:,2] >= i[0])*(X[:,3] >= i[1])*(X[:,4]...
6af135d7ecc716c957bf44ed17caab4f9dd63215
3,648,660
import tqdm def gen_graphs(sizes): """ Generate community graphs. """ A = [] for V in tqdm(sizes): G = nx.barabasi_albert_graph(V, 3) G = nx.to_numpy_array(G) P = np.eye(V) np.random.shuffle(P) A.append(P.T @ G @ P) return np.array(A)
6decd819a5e2afad9744270c616a60c532f2e6fd
3,648,661
def daemonize(identity: str, kind: str = 'workspace') -> DaemonID: """Convert to DaemonID :param identity: uuid or DaemonID :param kind: defaults to 'workspace' :return: DaemonID from identity """ try: return DaemonID(identity) except TypeError: return DaemonID(f'j{kind}-{id...
8cd08d9d8a558b9f78de60d2df96db553fbca8bf
3,648,662
from typing import Counter def count_gender(data_list:list): """ Contar a população dos gêneros args: data_list (list): Lista de dados que possui a propriedade 'Gender' return (list): Retorna uma lista com o total de elementos do gênero 'Male' e 'Female', nessa ordem ...
9e8a05067a617ca0606eec8d216e25d3f937e097
3,648,663
async def card_balance(request: Request): """ 返回用户校园卡余额 """ cookies = await get_cookies(request) balance_data = await balance.balance(cookies) return success(data=balance_data)
09e2b7e84743a0ed5625a6cc19dda0e97eb6df10
3,648,664
def _grid_vals(grid, dist_name, scn_save_fs, mod_thy_info, constraint_dct): """ efef """ # Initialize the lists locs_lst = [] enes_lst = [] # Build the lists of all the locs for the grid grid_locs = [] for grid_val_i in grid: if constraint_dct is None: ...
a401632285c9ac48136239fcfa7f3c2eb760734c
3,648,665
import vtool as vt def group_images_by_label(label_arr, gid_arr): """ Input: Length N list of labels and ids Output: Length M list of unique labels, and lenth M list of lists of ids """ # Reverse the image to cluster index mapping labels_, groupxs_ = vt.group_indices(label_arr) sortx = np....
9bdc83f2a9a5810b5d3cf443dcd72852dd35c26b
3,648,666
from typing import Optional def ask_user(prompt: str, default: str = None) -> Optional[str]: """ Prompts the user, with a default. Returns user input from ``stdin``. """ if default is None: prompt += ": " else: prompt += " [" + default + "]: " result = input(prompt) return ...
7803d7e71b2cc3864440cd99c276784cebf81f91
3,648,667
def tensor_index_by_tuple(data, tuple_index): """Tensor getitem by tuple of various types with None""" if not tuple_index: return data op_name = const_utils.TENSOR_GETITEM tuple_index = _transform_ellipsis_to_slice(data, tuple_index, op_name) data, tuple_index = _expand_data_dims(data, tupl...
4a32d9f4028f4ac57d1e523c946bb4a4d349b120
3,648,668
import scipy def are_neurons_responsive(spike_times, spike_clusters, stimulus_intervals=None, spontaneous_period=None, p_value_threshold=.05): """ Return which neurons are responsive after specific stimulus events, compared to spontaneous activity, according to a Wilcoxon test. ...
b5b835113644d7c42e7950cc8fc5699e62d631fa
3,648,669
def _get_book(**keywords): """Get an instance of :class:`Book` from an excel source Where the dictionary should have text as keys and two dimensional array as values. """ source = factory.get_book_source(**keywords) sheets = source.get_data() filename, path = source.get_source_info() re...
2e6114c2948272ce2d342d954594a8d626a45635
3,648,670
def handler( state_store: StateStore, hardware_api: HardwareAPI, movement_handler: MovementHandler, ) -> PipettingHandler: """Create a PipettingHandler with its dependencies mocked out.""" return PipettingHandler( state_store=state_store, hardware_api=hardware_api, movement_h...
099532e3c7d51812548643d10758ec23c8354a00
3,648,671
def get_domain(domain_name): """ Query the Rackspace DNS API to get a domain object for the domain name. Keyword arguments: domain_name -- the domain name that needs a challenge record """ base_domain_name = get_tld("http://{0}".format(domain_name)) domain = rax_dns.find(name=base_domain_na...
5ea1bbe9c73250abf60c5ad9f1d796035ed87654
3,648,672
import sympy def lobatto(n): """Get Gauss-Lobatto-Legendre points and weights. Parameters ---------- n : int Number of points """ if n == 2: return ([0, 1], [sympy.Rational(1, 2), sympy.Rational(1, 2)]) if n == 3: return ([0, sympy.Rational(1, 2), 1...
595610ec035dd9b059ab085375c017856359b837
3,648,673
def login(): """Login.""" username = request.form.get('username') password = request.form.get('password') if not username: flask.flash('Username is required.', 'warning') elif password is None: flask.flash('Password is required.', 'warning') else: user = models.User.login_user(username, password...
c54bc743ac305db8f0d74a7bd62f7bb70a952454
3,648,674
def comp_periodicity(self, p=None): """Compute the periodicity factor of the lamination Parameters ---------- self : LamSlotMulti A LamSlotMulti object Returns ------- per_a : int Number of spatial periodicities of the lamination is_antiper_a : bool True if an s...
5880ce1f8e3785d93e2979180133b64c014b9927
3,648,675
def sha2_384(data: bytes) -> hashes.MessageDigest: """ Convenience function to hash a message. """ return HashlibHash.hash(hashes.sha2_384(), data)
7523ca7e2d11e3b686db45a28d09ccdad17ff243
3,648,676
import string def cat(arr, match="CAT", upper_bound=None, lower_bound=None): """ Basic idea is if a monkey typed randomly, how long would it take for it to write `CAT`. Practically, we are mapping generated numbers onto the alphabet. >"There are 26**3 = 17 576 possible 3-letter words, so the aver...
1077bc5c4bc989e416cdaf27427f5a617491210d
3,648,677
def encrypt_data(key: bytes, data: str) -> str: """ Encrypt the data :param key: key to encrypt the data :param data: data to be encrypted :returns: bytes encrypted """ # instance class cipher_suite = Fernet(key) # convert our data into bytes mode data_to_bytes = bytes(data, "ut...
80e69657987956b3a0dc6d87dee79a4dcc5db3f7
3,648,678
from typing import List from typing import Dict def make_doi_table(dataset: ObservatoryDataset) -> List[Dict]: """Generate the DOI table from an ObservatoryDataset instance. :param dataset: the Observatory Dataset. :return: table rows. """ records = [] for paper in dataset.papers: # ...
6347142546579712574a63048e6d778dfd558249
3,648,679
from typing import List import os def get_output_file_path(file_path: str) -> str: """ get the output file's path :param file_path: the file path :return: the output file's path """ split_file_path: List[str] = list(os.path.splitext(file_path)) return f'{split_file_path[0]}_sorted{split_fi...
baf014ab2587c2b8b3248284e4993a76c502983a
3,648,680
def binarySearch(arr, val): """ array values must be sorted """ left = 0 right = len(arr) - 1 half = (left + right) // 2 while arr[half] != val: if val < arr[half]: right = half - 1 else: left = half + 1 half = (left + right) // 2 if arr[ha...
2457e01dee0f3e3dd988471ca708883d2a612066
3,648,681
from typing import Union from re import M from typing import cast def foreign_key( recipe: Union[Recipe[M], str], one_to_one: bool = False ) -> RecipeForeignKey[M]: """Return a `RecipeForeignKey`. Return the callable, so that the associated `_model` will not be created during the recipe definition. ...
f865bf1c7a91a124ca7518a2a2050371112e820e
3,648,682
def posterize(image, num_bits): """Equivalent of PIL Posterize.""" shift = 8 - num_bits return tf.bitwise.left_shift(tf.bitwise.right_shift(image, shift), shift)
11dc20facfd5ac57e7547036304d192ce21fdb0a
3,648,683
import os def validate_targetRegionBedFile_for_runType( value, field_label, runType, reference, nucleotideType=None, applicationGroupName=None, isPrimaryTargetRegion=True, barcodeId="", runType_label=ugettext_lazy("workflow.step.application.fields.runType.label"), ): """ va...
11369d8f74f2eea600676fee5d4deae17250efe7
3,648,684
def polyFit(x, y): """ Function to fit a straight line to data and estimate slope and intercept of the line and corresponding errors using first order polynomial fitting. Parameters ---------- x : ndarray X-axis data y : ndarray Y-axis data Return...
0acc032492a63dbb271293bed8cf11c800621a35
3,648,685
import tdub.internal.stab_tests as tist from pathlib import Path import os def stability_test_standard( umbrella: Path, outdir: Path | None = None, tests: str | list[str] = "all", ) -> None: """Perform a battery of standard stability tests. This function expects a rigid `umbrella` directory struc...
91b9d7d059a9c60e9079529da65fe44dcc6bcbe4
3,648,686
def evaluate_error(X, y, w): """Returns the mean squared error. X : numpy.ndarray Numpy array of data. y : numpy.ndarray Numpy array of outputs. Dimensions are n * 1, where n is the number of rows in `X`. w : numpy.ndarray Numpy array with dimensions (m + 1) * 1, where m...
2e54a2bb64a590e3e35456b5039b4cfce7632c0f
3,648,687
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up ha_reef_pi from a config entry.""" websession = async_get_clientsession(hass) coordinator = ReefPiDataUpdateCoordinator(hass, websession, entry) await coordinator.async_config_entry_first_refresh() if not coor...
655a1265a77cec38346931a6cf5feaf923c1573b
3,648,688
def get_list(client): """ """ request = client.__getattr__(MODULE).ListIpBlocks() response, _ = request.result() return response['results']
0836bc58d8108a804c9464a713184ac582bd4e90
3,648,689
import six def file_asset(class_obj): """ Decorator to annotate the FileAsset class. Registers the decorated class as the FileAsset known type. """ assert isinstance(class_obj, six.class_types), "class_obj is not a Class" global _file_asset_resource_type _file_asset_resource_type = class_o...
a21ae9d8ba84d2f6505194db6fd8bd84593f3928
3,648,690
import glob import os def get_bam_list(args): """ Retrieve bam list from given tumor bam directory """ bamList = [] for bam in glob.glob(os.path.join(args.tumor_bams_directory, "*.bam")): # Todo: CMO bams don't always end in 'T' # if os.path.basename(bam).split('_')[0].split('-')[-...
151a4fd90164277ef38cf09d2f7243f3b204d2e9
3,648,691
def scheming_field_by_name(fields, name): """ Simple helper to grab a field from a schema field list based on the field name passed. Returns None when not found. """ for f in fields: if f.get('field_name') == name: return f
ba4d04585b12ab941db8bc0787b076c32e76cadb
3,648,692
import os import re def saveResult(img_file, img, boxes, dirname='./result/', verticals=None, texts=None): """ save text detection result one by one Args: img_file (str): image file name img (array): raw image context boxes (array): array of result file ...
10f68d8411f9f0a5fb9d0d4082960f6163dad7b3
3,648,693
def merge_sort(items): """Sorts a list of items. Uses merge sort to sort the list items. Args: items: A list of items. Returns: The sorted list of items. """ n = len(items) if n < 2: return items m = n // 2 left = merge_sort(items[:m]) right = mer...
d42c60dda40fc421adef2d47f302426d7c176ba1
3,648,694
from typing import Optional def hunk_boundary( hunk: HunkInfo, operation_type: Optional[str] = None ) -> Optional[HunkBoundary]: """ Calculates boundary for the given hunk, returning a tuple of the form: (<line number of boundary start>, <line number of boundary end>) If operation_type is provide...
c5ec0065e5ab85652a5d0d679a832fdd0dae1629
3,648,695
from pm4py.statistics.attributes.pandas import get as pd_attributes_filter from pm4py.statistics.attributes.log import get as log_attributes_filter def get_activities_list(log, parameters=None): """ Gets the activities list from a log object, sorted by activity name Parameters -------------- log ...
b0e335dd31cae3fb291317a559c721199217605f
3,648,696
def encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob, source_vocab_size, encoding_embedding_size): """ :return: tuple (RNN output, RNN state) """ embed = tf.contrib.layers.embed_sequence(rnn_inputs, vocab_size=s...
3179d478478e2c7ca5d415bb23643a836127f6fe
3,648,697
def point_selection(start, end, faces): """ Calculates the intersection points between a line segment and triangle mesh. :param start: line segment start point :type start: Vector3 :param end: line segment end point :type end: Vector3 :param faces: faces: N x 9 array of triangular face vertices...
287295de09a5375118ed050f025fa32b0690a9a9
3,648,698
def daysBetweenDates(year1, month1, day1, year2, month2, day2): """Returns the number of days between year1/month1/day1 and year2/month2/day2. Assumes inputs are valid dates in Gregorian calendar, and the first date is not after the second.""" month = month2 year = year2 day = day2 ...
687a7ff0b29ec2a931d872c18057741d93571ac1
3,648,699