content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_centerline_tolerance(centerline, n=50): """ Finds tolerance based on average length between first N points along the input centerline. Args: centerline (vtkPolyData): Centerline data. n (int): Number of points Returns: tolerance (float): Tolerance value. """...
f670bc529a586591d1db8f9a948e8b4ce6b6ba40
50,100
import token import requests def _api_action(url, req, data=None): """Take action based on what kind of request is needed.""" requisite_headers = {'Accept': 'application/json', 'Content-Type': 'application/json'} auth = (user, token) if req == "GET": response = reques...
42c2e4cbde1c907730e241e68c01b9076a003021
50,101
def detf(entry, evals): """Determines a function value given a number of evaluations. Let A be the algorithm considered. Let f=f_A(evals) be the smallest target value such that the average running time of algorithm A was smaller than or equal to evals. :keyword DataSet entry: data set :keyword...
0cf27a8edf218be762509bf1905d9d580c18409f
50,102
def make_visit_output_schema(visual_attributes): """Return the visit output schema.""" schema = [ ("lid", pa.int64()), ("pid", pa.int64()), ("inf_prob", pa.float64()), ("n_contacts", pa.int32()), ] columns = set(k for k, _ in schema) for attr in visual_attributes: ...
d5ea46c0aa0946917027127a2231ddc9511bb368
50,103
def _xrank(a, w, b, vol, scale = 0 , reweight = False): """ performs a cross-sectional rank a = np.random.normal(0,1,20) a[np.random.normal(0,1,20) > 1] = np.nan w = np.full(20, 1.) b = np.full(20, 1.) scale = 0; vol = -1; reweight = False a _xrank(a, w, b, vol) ra...
aefa45d2831bda4d6a00e53821e36b0dbfff5297
50,104
import copy import datatable as dt from datatable import sort, f, by, ifelse, join import polars as pl from polars import col from polars.lazy import col import numpy as np import datatable as dt from datatable import f, by, rbind, join from catboost import Pool import xgboost as xgb import lightgbm as lgbm def ML0_G...
181d6d24e2e304ef9b5462e16a32326df87a07cf
50,105
def softmax(x): """ Compute softmax values for each sets of scores in x. Parameters: x (numpy.ndarray): array containing m samples with n-dimensions (m,n) Returns: x_softmax (numpy.ndarray) softmaxed values for initial (m,n) array """ e_x = np.exp(x - np.max(x)) # Subtract ...
3a5ad143126f9adcdd46aecd207439a0e6fe23ad
50,106
import os from operator import add def merge(): """ Merges two branches. Since we currently support only one branch, merge takes the commit from FETCH_HEAD for now """ had_conflict = False repo_root_path = get_repo_root_path() fetch_head_path = os.path.join(repo_root_path, '.git', 'FETCH_HEAD'...
91956c4fb90418f95d09f46bd60544e1a4bf9405
50,107
def vareq(x1, x2): """Determine if two vars are equal. This does not check if they're values are the same, but if they are exactly the same pointer. Also note that it makes no difference at all if they have the same `name` value. @param x1: A Logic Variable @param x2: Another Logic Variable ...
ba123f9be3cad453399f8e6002ee98d9cb1cf336
50,108
def compute_induced_segment_family_coverage(path_family): """Compute induced segment family and coverage from path family Notebook: C4/C4S3_AudioThumbnailing.ipynb Args: path_family: Path family Returns segment_family: Induced segment family coverage: Coverage of path family ...
213482828207b41f773ca790e3bee5bbf14e97a1
50,109
def slugify(text, delim=u'-'): """Generates an ASCII-only slug.""" result = [] for word in _punct_re.split(text.lower()): result.extend(undecode(word).split()) return unicode(delim.join(result))
00c17b82070627c7e49cf3ebcf64199be3fee6e4
50,110
def _find_last_larger_than(target, val_array): """ Takes an array and finds the last value larger than the target value. Returns the index of that value, returns -1 if none exists in array. """ ind = -1 for j in range(len(val_array), 0, -1): if val_array[j - 1] > target: ind ...
dbdba59ba35b502669082c8416159770843b7312
50,111
import six def requires_auth(f): """Wraps a request handler with token authentication.""" @wraps(f) def decorated(*args, **kwargs): self = args[0] request = args[1] if six.PY3: token = request.args.get(b'token', [b''])[0].decode("utf8") else: token ...
a9e65de80d264838a8fe827ac90c5fd625bf92a4
50,112
from typing import List import logging def determine_valid_intersection_points( intersection_geoms: gpd.GeoSeries, ) -> List[Point]: """ Filter intersection points between trace candidates and geom. Only allows Point geometries as intersections. LineString intersections would be possible if geome...
d1f46abf2a0b4eb9dac1790bca3adc4ae88cffa8
50,113
import struct def readStruct(fb, structFormat, seek=False, cleanStrings=True): """ Return a structured value in an ABF file as a Python object. If cleanStrings is enabled, ascii-safe strings are returned. """ if seek: fb.seek(seek) varSize = struct.calcsize(structFormat) byteStri...
1920c69f1881698a3898774be95e8f10a462d936
50,114
def hello_world(event, context): """ Test function, calls algorithmia algorithm :param event: AWS lambdas function event :param context: AWS lambdas function context :return: """ if "algorithm" in event: algo_name = event['algorithm'] else: raise Exception("'algorithm' fi...
8d12674b30c1964119e90c969e00c882b12009d7
50,115
def remove_from_query(context, *args, **kwargs): """Renders a link with modified current query parameters""" query_params = [] # go through current query params.. for key, value_list in context["request"].GET.lists(): # skip keys mentioned in the args if key not in args: for ...
0fcdc4b6da91ab64c27e225728567d4034d1f626
50,116
def trapz_int(x, y): """ This function computes the area underneath a curve (y) over time vector (x) including checking if the time vector is sorted. Parameters ---------- x : list Time vector. y : list Vector of the integrand. Returns ------- float Area...
c74a56508cb9fae20a29e3e12b5ad1a9ad5c8895
50,117
def register(func, *args, **kwargs): """Register a specialization of a `Function` into the graph. This won't actually call the function with the inputs, and only put the function definition into graph. Register function with different input param will result into multiple version of functions registered in gra...
1d39c32f45758e1fa9dca14ae666ac395f92fa98
50,118
def chainable_batches(parent_batch_id, job_level): """Returns all batches that have completed and we could possibly chain from""" if job_level == 1: raise Exception("can't chain in job_level 1") if job_level == 2: return db.get_child_batch_metadata( parent_batch_id, BatchMetada...
6aa442d1b6298d94d7434908d2070366508adcb1
50,119
import os import click def clean(): """キャッシュをゴミ箱に移動します""" user_cache_dir = os.getenv(_MLKOKUJI_CACHE_DIR) if user_cache_dir is not None: if os.path.exists(user_cache_dir): if not click.confirm('You are using a custom cache directory ({}). Do you want to continue?'.format(user_cache_d...
121beffc7c392bb72471e32d5067fc9fc3152b47
50,120
def mask_rgb(rgb, mask): """ Apply a binary (T/F, 1/0) mask to a 3-channel RGB image and output the result. Args: rgb: RGB image as a NumPy array. mask: An image mask to determine which pixels in the original image should be displayed. Returns: NumPy array representing an RGB image with mask appli...
1d81d4e0c5ddae69163e969ad24313ac7bc87743
50,121
import os import time def create_tags_for_metadata(src_client, run, export_metadata_tags): """ Create destination tags from source run """ tags = run.data.tags.copy() for k in _databricks_skip_tags: tags.pop(k, None) if export_metadata_tags: uri = mlflow.tracking.get_tracking_uri() ...
5218f217d3cddd269c7140fa585bcbec92486c79
50,122
def fit_table(lc, expect=1.0): """Generate a summary table from a light curve dataframe""" fits = lc.fit flux = fits.apply(lambda f: f.flux) errors = fits.apply(lambda f: (round(f.errors[0]-f.flux,3), rorebinnedund(f.errors[1]-f.flux ,3) ) ) sigma_dev = fits.apply(lambda f: round(f.poiss.sigma_dev(e...
334b4e07696e796c04a6243566419960f5446da2
50,123
def createDagNode(nodeType, nodeName, mDagMod): """ Create and rename node :param nodeType: string :param nodeName: string :param mDagMod: MDagModifier :return: MObjectHandle """ nodeMObj = mDagMod.createNode(nodeType) mDagMod.renameNode(nodeMObj, nodeName) mDagMod.doIt() no...
d46bbb2076566df36d76127c8a41a77d7e324ecc
50,124
import os import errno from operator import invert def get_ppis(reactome_ppis, threshold=5000.0): """ Get human co-expressed pairs of proteins. They are not necessarily ppi, but to keep same naming structure. :param reactome_ppis: dictionary one --> set :param threshold: Maximum correlation score to be c...
b2e81617f4eac3ae6aaf1f06d3a430d406202978
50,125
def is_denied_because_of_spider(ua_str): """检查user-agent是否因为是蜘蛛或机器人而需要ban掉""" ua_str = ua_str.lower() if 'spider' in ua_str or 'bot' in ua_str: if is_ua_in_whitelist(ua_str): infoprint("A Spider/Bot's access was granted", ua_str) return False infoprint('A Spider/Bot w...
8e186ab286bab50b4f5368c812d4477e27d46c6b
50,126
import torch def predict(model, dataset, out_channels, device, x=None, y=None, z=None): """ Return prediction masks by applying the model on the given dataset Args: model (Unet3D): trained 3D UNet model used for prediction dataset (torch.utils.data.Dataset): input dataset out_chan...
718acda917f05cb3e567471884e666ea3dd9cdf6
50,127
def arc_argmax(parse_probs, length, tokens_to_keep, ensure_tree=True): """ Adopted from Timothy Dozat https://github.com/tdozat/Parser/blob/master/lib/models/nn.py Parameters ---------- parse_probs : NDArray seq_len x seq_len, the probability of arcs length : NDArray real senten...
2d0488660b2b95e2af8c9c6b6964497bdc8bda03
50,128
def addr(registers, a, b, c): """(add register) stores into register C the result of adding register A and register B.""" registers[c] = registers[a] + registers[b] return registers
db88d8e4faeb69660a279f8a893130e83053176a
50,129
def get_data_frame(): """A function to read the csv files and return dataframe objects""" roaster = pd.read_csv ("roaster.csv") activity = pd.read_csv ("activity.csv") headimpact = pd.read_csv ("headimpacts.csv") return roaster, activity,headimpact
07b272832d0656a34e5ae394fccbff2401385bfa
50,130
def latin1_to_ascii (unicrap): """This replaces UNICODE Latin-1 characters with something equivalent in 7-bit ASCII. All characters in the standard 7-bit ASCII range are preserved. In the 8th bit range all the Latin-1 accented letters are stripped of their accents. Most symbol characters are convert...
3ca0631c4cbb0e3fc9c18a09785b4be40fde8a48
50,131
async def queue_clear_handler(): """ Clear the plan queue. """ msg = await zmq_to_manager.send_message(method="queue_clear") return msg
2a53c4ba4be5751a6e09abf4449e01bcce68305a
50,132
def create_rain_gauge_reading(r, loc_obj, sys_type, dev_obj): """Creat rain gauge object in database from array row""" datetime = r.get('datetime', None) rain = r.get('rain', None) accum_rain = r.get('AccumulatedRain', None) rgr = Raingaugereading.objects.create( LocationID=loc_obj, ...
f200da8ebc99f9a1adf723f7d929df52926b619b
50,133
def _pre_validate_int(value, name): """ Converts the given `value` to `int`. Parameters ---------- value : `Any` The value to convert. name : `str` The name of the value. Returns ------- value : `int` Raises ------ TypeError If `value` w...
29291514faf3c77fd37a88a7b55a3159a65a6b5d
50,134
import re import math def load_hessian(shess: str, dtype: str) -> np.ndarray: """Construct a Hessian array from any recognized string format. Parameters ---------- shess Multiline string specification of Hessian in a recognized format. dtype {"fcmfinal", "cfour", "gamess"} ...
d5011f2381fbf1d23b4914112d444a6d385f7167
50,135
import torch def as_rgb_visual(x, vallina=False, colors=None): """ Make tensor into colorful image. Args: x (torch.Tensor): shape in (C, H, W) or (N, C, H, W). vallina (bool) : if True, then use the `stack_visuals`. """ def batched_colorize(batched_x): n, c, h, w = batched_x....
cfce54774841d948544f5308e464a19e82f6cce4
50,136
def detach_dict(dict_tensor, to_numpy=False): """ Helper function to recursively detach a dictionary of tensors This should be used when storing elements that could accumulate gradients. """ for key, val in dict_tensor.items(): if isinstance(val, dict): dict_tensor[key] = detach_...
27b217eb44cb00012460bc1b954d89165a26545c
50,137
def model_query(session, model): """model query.""" if not issubclass(model, models.Base): raise exception.DatabaseException("model should be a subclass of BASE!") return session.query(model)
aa72c20fa2f13b49f0dead5cd886bf351f9e9132
50,138
import gzip import pickle def load_batch_gcnn(sample_files): """ Loads and concatenates a bunch of samples into one mini-batch. """ c_features = [] e_indices = [] e_features = [] v_features = [] candss = [] cand_choices = [] cand_scoress = [] # load samples for filenam...
49afc38949128009682a3b828a0cd2a8fc14ce46
50,139
def mutate_uniform(individual, lb, ub): """ Mutate one variable from the individual Uses uniform random within the range """ indi = np.copy(individual) mut_idx = np.random.choice(len(indi)) indi[mut_idx] = np.random.uniform(low=lb[mut_idx], high=ub[...
4fe62bb1aee666a0f075ac350f8f7a864f2a2b05
50,140
def make_qfq(data, xdxr, fq_type='01'): """使用数据库数据进行复权""" # 过滤其他,只留除权信息 xdxr = xdxr.query('category==1') # data = data.assign(if_trade=1) if len(xdxr) > 0: # 有除权信息, 合并原数据 + 除权数据 # data = pd.concat([data, xdxr.loc[data.index[0]:data.index[-1], ['category']]], axis=1) # data[...
eba76a3a2a9c23a9d0430ade3dcabc281d562929
50,141
def compute_average_precision_detection(ground_truth, prediction, tiou_thresholds=np.linspace(0.5, 0.95, 10)): """Compute average precision (detection task) between ground truth and predictions data frames. If multiple predictions occurs for the same predicted segment, only the one with highest score is mat...
c1e84350bde0f998d86c30be46edd69ec49b94ef
50,142
def data_augmenter(image, label, shift, rotate, scale, intensity, flip): """ Online data augmentation Perform affine transformation on image and label, which are 4D tensor of shape (N, H, W, C) and 3D tensor of shape (N, H, W). """ image2 = np.zeros(image.shape, dtype=np.float32) ...
4d6115f72c5bbd3b57f265aa8630b80831b02b02
50,143
def RidPreviouslyProcessed(dtCurrentHosts,sPreviousProcessedFileName): """Remove host-guests processed for NEB calculations previously. [dtHosts]: dict, key: host name; value: int, binary flags for presence of each guest for this host. [sPreviousProcessedFileName]: string, name of file listing previously processed f...
deca4c0510542ca36c0f390badf8a26ce581de48
50,144
def abspath(newpath, curpath): """Return the absolute path to the given 'newpath'. The current directory string must be given by 'curpath' as an absolute path. """ assert newpath assert curpath assert curpath.startswith('/') subdirs = newpath.split('/') if not subdirs[0] or curpath...
0b1416492891121f433ce3bfbf934601bfc96f06
50,145
import os import logging def loadSiteLocalConfig(): """ _loadSiteLocalConfig_ Runtime Accessor for the site local config. Requires that CMS_PATH is defined as an environment variable """ overVarName = "WMAGENT_SITE_CONFIG_OVERRIDE" if os.getenv(overVarName, None): overridePath =...
3489c073ea69d173d5ca97bcfacee7957eed0725
50,146
import os def icbm_v1_nifti(): """ Returns the ICBM v1 test nifti data """ return NiftiImageContainer( nifti_img=nib.load( os.path.join(definitions.ROOT_DIR, "data", "hrgt_ICBM_2009a_NLS_v1.nii.gz") ) )
67e3539d5d5262c30491398bcc0b1f6392fc2019
50,147
def _create_vector_Iqxy(model_info): """ Define Iqxy as a vector function if it exists, or default it from Iq(). """ Iq, Iqxy = model_info.Iq, model_info.Iqxy if callable(Iqxy): if not getattr(Iqxy, 'vectorized', False): #print("vectorizing Iqxy") def vector_Iqxy(qx, ...
05751cf921279f305cdf68c49955f5dc23046f8e
50,148
def load_geo_adwords(filename='AdWords API Location Criteria 2017-06-26.csv.gz'): """ WARN: Not a good source of city names. This table has many errors, even after cleaning""" df = pd.read_csv(filename, header=0, index_col=0, low_memory=False) df.columns = [c.replace(' ', '_').lower() for c in df.columns] ...
b0c69b74c61d18d677b35ef994d5a4446ad9e645
50,149
from typing import List from typing import Dict from typing import Any def from_protos( proto_list: List[american_option_pb2.AmericanEquityOption], config: "AmericanOptionConfig" = None ) -> Dict[str, Any]: """Creates a dictionary of preprocessed swap data.""" prepare_fras = {} for am_option_proto i...
59680f34e45125e619d353f1d0744fb0132730ca
50,150
def optimal_step_weights(): """Return the optimal weights for the neural network with a step activation function. This function will not be graded if there are no optimal weights. See the PDF for instructions on what each weight represents. The hidden layer weights are notated by [1] on the pr...
0a38b9f7fc017a6a90dbb2fb51a394386f0fafd0
50,151
import time import requests def get_remote_file_content( url, as_text=True, headers_only=False, headers=None, _delay=0, ): """ Fetch and return a tuple of (headers, content) at `url`. Return content as a text string if `as_text` is True. Otherwise return the content as bytes. If `...
f96f0f841873c318584305665b66be37d198aa97
50,152
from typing import Sequence from typing import Optional def crop_img_padded( img: np.ndarray, cropping_range: Sequence[int], dtype: Optional["DTypeLike"] = None ) -> np.ndarray: """Crop image or mask with padding. Parameters ---------- img : np.ndarray Input image/mask as 2D (heig...
353a209decb7a0f0cc2ab0d947fcb9e42e709900
50,153
import os def extractImageCorners(directory, filename): """ Extract the image corners from an image that is assumed to be a DICOM image. Corners are returned as: [bl, br, tl, tr] :param directory: the directory where the file given with filename exists. :param filename: the filename of ...
b104ea6ec8a6fed5f089621514abd67f4ec24699
50,154
from typing import cast import copy def merge(this: SchemaCompatibilityResult, that: SchemaCompatibilityResult) -> SchemaCompatibilityResult: """ Merges two {@code SchemaCompatibilityResult} into a new instance, combining the list of Incompatibilities and regressing to the SchemaCompatibilityType.incompat...
0e404c80c0dd074ab65780da4bc086d2a214e3b9
50,155
def flatten(attname): """Fixup helper for serialize. Given an attribute name, returns a fixup function suitable for serialize() that will pull all items from the sub-dict and into the main dict. If any of the keys from the sub-dict already exist in the main dict, they'll be overwritten. """ ...
242726a7dcd6c57458e6276527f08b62cb4ef941
50,156
def P_DCG(rank, b=2): # pylint: disable=invalid-name """ Discounted Cumulative gain based stopping probability Args: rank (int): rank b (int, optional): Defaults to 1. log base. Returns: float: stopping probability at the given rank """ def __log_n(x, n): # pylint: dis...
616fb6440bd4462e397bd4ce4dfe3f5a220bf217
50,157
def _get_player_regions(player_id): """ Return a list of regions for whom 'player_id' has reported latency values. """ regions_key = _make_player_regions_key(player_id) if g.redis.conn.exists(regions_key): return g.redis.conn.smembers(_make_player_regions_key(player_id)) return set()
8f3e371bd58111109480eaad48e17f570d2be655
50,158
def getImageFromTexture2d(texture2d, flip=True) -> Image: """ 将给定的纹理转换为PIL.Image :param texture2d: 要转换的纹理 :type texture2d: Texture2D :param flip: 将图像翻转回原始(默认情况下,所有Uniiity纹理都翻转) :type flip: bool :return: PIL.Image object :rtype: Image """ imageData = texture2d.imageData textur...
b08492424dc951eddc5e4144c581c63e103ba95e
50,159
def _finalize_build(stage_results): """ stage_results (list of (stage_exit_code, stage_name, stage_status)) as returned by _perform_stage() logs a final report and returns an overall exit code for whether the build succeeded. """ overall_success = True final_report = "" for sta...
f5096ffd4f14db9694e535e57c125aa347df0e1c
50,160
import os def indentr(model, wdir, infile, input_data, aux_file, toab_gmean): """Compute the material entropy production with the indirect method. The function computes the material entropy production with the indirect method, isolating a vertical and a horizontal component (after Lucarini et al., 20...
6380b957d94846fac81084f56a50c27e948dacc1
50,161
import base64 def derive_key(secret: bytes, salt: bytes): """Derives the key from specified secret and salt using KDF function""" kdf = get_kdf(salt) key = base64.urlsafe_b64encode(kdf.derive(secret)) return key
f0edb615261f282dedc313793a0865be98efbf0e
50,162
def load_image(infilename): """ Function to load the image """ data = mpimg.imread(infilename) return data
4f8be3212caa56669f9d785f1af5478a18ae397b
50,163
from pathlib import Path def outdir(): """Determine if test artifacts should be stored somewhere or deleted.""" return None if test_output_dir is None else Path(test_output_dir)
b9191a6bb1e8bf916070d4ca99a0f307ef05bad5
50,164
import os def check_mask_patches(): """ Returns this list of mask patches that we have from the images. There are patches taken from the masks. :return: python list of strings """ path_to_mask_patches = os.path.join(SEGMENTATION_DATA_PATH, "results", "mask_patches_"+ str(PATCH_COUNT_PER_IMAG...
f5f60a1ffe8a4a38be9a7ebde65f80f1227fc4ef
50,165
def status(user): """ :param user: User whose status we want to look at :return: dict of boolean status codes """ return AttrDict({ 'member': user.member_of(config.member_group), 'traffic_exceeded': user.current_credit < 0, 'network_access': user.has_property('network_access'...
64accc7a55ddfa93d274f3629a440d2e6b83b4b0
50,166
def doublePendulumDerivativesSolver(t, x): """ Returns time derivative of double pendulum phase space vector, solve_ivp compatible """ g = 9.8 t1, w1, t2, w2 = x return [w1, (-w1**2*np.sin(t1-t2)*np.cos(t1-t2) + g*np.sin(t2)*np.cos(t1-t2) - w2**2*np.sin(t1-t2) - 2*g*n...
cfe855ae644ff8206a2b24fb100ebe008caf1a9b
50,167
def feedback_fm(gain1=1, gain2=1, carrier1=900, modulator1=300, carrier2=900, modulator2=300, index1=5, index2=0, attack=0.01, release=1, sr=44100): """A convenience to render as function call.""" return FeedbackFM1(gain1=gain1, gain2=gain2, carrier1=carrier1, modulator1=modulator1, ...
4717a64ce554b043d842cab822d0c865168ede5b
50,168
def polya(): """Fixture returning a Polya instance.""" perm_a = np.array([[8, 9, 10, 11], [9, 10, 8, 11], [10, 8, 9, 11],]) perm_b = np.array([[3, 4, 5], [5, 4, 3], [3, 4, 5],]) perms_list = [perm_a, perm_b] return Polya(perms_list)
905102e4183460e88a1f2fdea7d139532d05abf4
50,169
def get_by_string(source_dict, search_string, default_if_not_found=None): """ Search a dictionary using keys provided by the search string. The search string is made up of keywords separated by a '.' Example: 'fee.fie.foe.fum' :param source_dict: the dictionary to search :param search_string: se...
59386f5777805f2e7c5a7c7204c56d3d5792c190
50,170
def get_history_dropdown(obj, project=None): """Return link to object timeline events within project""" timeline = get_backend_api('timeline_backend') if not timeline: return '' url = timeline.get_object_url(obj, project) return ( '<a class="dropdown-item" href="{}">\n' '<i c...
5e19a7f57189819db77f7b7840a461505c606345
50,171
def get_na_row_values(columns): """ returns na values for all columns starting from gender """ row_values = [ -1, -1, -1, -1, -1, -1, -1, False, -1 ] actions_idx = columns.index('actions') row_values += [0] * (len(columns) - actions_idx) return row_val...
11c45f3a5a7bb9a42458c6f4c4b3d73a5e75fc3c
50,172
def avg_waves(*waves): """ Create the average wave. :param waves: an iterator of waves :return: a wave """ return map(lambda x: x / len(waves), add_waves(*waves))
8720f90a1e5a105e6b752ada106245f62cddecdc
50,173
import logging import hashlib def md5(fpath="", data=""): """ Calculates the the MD5 hash of a file. You can only provide a file path OR a data string, not both. :param fpath: Path of the file for which the MD5 hash is required. :param data: Data string for which the MD5 hash should be calculated....
bf065e682cf243271a48a2a84717121c696c7f72
50,174
def _drop_ignored(gold, pred, ignore_in_gold, ignore_in_pred): """Remove from gold and pred all items with labels designated to ignore.""" keepers = np.ones_like(gold).astype(bool) for x in ignore_in_gold: keepers *= np.where(gold != x, 1, 0).astype(bool) for x in ignore_in_pred: keepers...
e76a14cfa1a8e37bbbac9026235f4ec4d3010a2b
50,175
def nonspecific(rna_id, sequence, min_length, max_length): """ Compute all the fragment sequences in case of nonspecific cleavage, based on the info selected by the user on minimum and maximum length for the sequences generated from nonspecific cleavage """ output_sequences, seq_list = [], list(sequ...
c507d5ffdf5dad5ad6c30e7aab095c9db59cc16c
50,176
from sympy.tensor.array import NDimArray def flatten(iterable, levels=None, cls=None): # noqa: F811 """ Recursively denest iterable containers. >>> from sympy import flatten >>> flatten([1, 2, 3]) [1, 2, 3] >>> flatten([1, 2, [3]]) [1, 2, 3] >>> flatten([1, [2, 3], [4, 5]]) [1, ...
9c7960a962e271698a475bd40202f7656a688cd0
50,177
def black_thresh(img): """ Extract the black part based on RGB color space """ thresh_R = threshold(thresh(img_channel(img, 'RGB', 0), thresh=[0, 40])) thresh_G = threshold(thresh(img_channel(img, 'RGB', 1), thresh=[0, 40])) thresh_B = threshold(thresh(img_channel(img, 'RGB', 2), thresh=[0, 40])...
af4765ae8088b8862efce4acbd33a064327817b1
50,178
def covmat2direction(covmat): """Return eccentricity and principal direction given a covariance matrix. The eccentricity is the ratio of the largest eigenvalue to the second largest. In a 3D problem, there is probably some more descriptive shape metric that uses all three eigenvalues. """ evals...
89027b13bb118599afbb75453f2e5a117fef78dc
50,179
def get_summary(master_bricks, mastervol, slavehost, slavevol): """ Wrapper function around Geo-rep Status and Gluster Volume Info This combines the output from Bricks list and Geo-rep Status. If a Master Brick node is down or Status is faulty then increments the faulty counter. It also collects the...
5a89206bb380cc9f4b5f0440c4c94b14da83bae6
50,180
def _get_request_url(message: str, chat_id: int): """Compose url for telegram.""" bot_token = settings.TELEGRAM_BOT_TOKEN url = f'{TELEGRAM_API_URL}{bot_token}/sendMessage?chat_id={chat_id}&text={message}' return url
b8b3f367186259cb7c3259925d5f27633a740700
50,181
def print_projection_cv2(points, color, image, black_background=False): """ project converted velodyne points into camera image """ if black_background: image = np.zeros_like(image) hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) for i in range(points.shape[1]): cv2.circle( hsv_image, (np.in...
c43281911f869b2bfe6ecb030fe990cbcb241dfa
50,182
import socket import struct def int_to_ip(addr): """ Converts a the numeric representation of an ip address to an ip address strin Example: >>> int_to_ip(2130706433) '127.0.0.1' """ return socket.inet_ntoa(struct.pack("!I", addr))
6db99b4cb7e7274eb1ac2b7783a4b606d845c4a5
50,183
def general_telescope(empty_lamda, grid_size, PASSVALUE): """ #TODO pass complex datacube for photon phases propagates instantaneous complex E-field through the optical system in loop over wavelength range this function is called as a 'prescription' by proper uses PyPROPER3 to generate the comple...
e3a635de3a6718cada6b1082c2f79aeabbfa8d6f
50,184
def has_hue_shifted( before: np.ndarray, after: np.ndarray, hue: float, tolerance: float = 0.02 ) -> bool: """ Detect whether pixels of a specified 'hue' have shifted away from where pixels were in a baseline image. Used to detect whether rasters of pages with colorized images had contain accidental...
440a29587eb1c89c75d93b26e2113280711ef37a
50,185
def plotdim(npanel, maxcol=12, mode="square"): """work out a rectangular plot grid that achieves a total of npanel. maxcol limits how many columns we allow. mode can be 'square' (keep approximately equal nrow and ncol), 'cols' (as few rows as possible), 'rows' (as few columns as possible).""" # here...
10fe99e6dd9b0fb56694b7c1c6fe49041e25e5e5
50,186
def a_lambda_cardelli_fast(W,R=3.08): """Description: inspired by Eran's function of the same name, faster version using numba. Input : wavelength in microns Output : numpy array of A(lambda), the size of wavelengths. Tested : ? By : Erez (Dec 2019), on top of Ido Irani (Nov 2019) URL ...
21d6655482f4e4f8b77151ea99bb1abf6a4f0aed
50,187
from pathlib import Path from typing import Tuple from typing import Collection def preprocess(path: Path) -> Tuple[Collection[Context], Collection[ContextTagging]]: """ Preprocess data file :param path: Path to data file :return: Contexts with their corresponding tags (if there are any) """ w...
ad104c1544d10c3bb84f8c13b1b2841169874b99
50,188
import argparse def parse(): """Parse system arguments.""" parser = argparse.ArgumentParser(description="Main entry point into \ the MoonTracker application") parser.add_argument('-p', dest='port', action='store', default=5000, type=int, help='h...
4feafae8a598eee96e049c4830e17987d5476dad
50,189
def SectionsMenu(base_title="Sections", section_items_key="all", ignore_options=True): """ displays the menu for all sections :return: """ items = get_all_items("sections") return dig_tree(SubFolderObjectContainer(title2="Sections", no_cache=True, no_history=True), items, None, ...
c59f7340c9dc79bed51756ebea4798cc82f6aef9
50,190
from astroquery.vizier import Vizier import numpy as np from astropy.coordinates import SkyCoord def query_cat(catalog, min_ra, max_ra, min_dec, max_dec, columns=None, column_filters=None): """ Use vizquery to get a reference catalog from vizier """ # Build vizquery statement width = int(n...
2983412579e8c5b2cef597aded712d3998b73e26
50,191
import types import pandas def hpat_pandas_series_ge(self, other, level=None, fill_value=None, axis=0): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.ge Limitations ----------- - Parameters level, fill_value are cu...
65c1e874b65c5624639c0b36e3b20b19602faa29
50,192
def aa_seq_doc(aa_sequence): """This function takes in an amino acid sequence (aa sequence) and adds spaces between each amino acid.""" return ' '.join([aa_sequence[i:i+1] for i in range(0, len(aa_sequence))])
cb497c340d5ecc29184dc079ea9530ebddc43fbd
50,193
def load(project_path): """ Loads the given project and returns a Project Instance :param project_path: Path to the location you want to save the project path. :type project_path: str :return: fracture.Project instance """ return _project.Project(project_path)
aec53a3da8d053853029d1f5f526ba1226463414
50,194
import re def _find_units(powers_cleaned, dimensions, strict): """ Finds the powers associated with each of the units :param list((chemdataextractor.quantities.Unit, str, str, str)) powers_cleaned: The units found, in the format (units found, string in which this occured, power associated with the unit, s...
13851922fffa7cf9e373e2d3308f0c075c00a433
50,195
from typing import Dict from typing import Union from typing import Callable from typing import Any def get_result_data(result: Dict, value: Union[str, Callable]) -> Any: """Returns data from a GCP API call result dict. Args: result: Dict containing the result or a GCP API execute() call. val...
15c1eb46fe78e1df48d3068f30e2cba8a86f8e49
50,196
def expr_plot(data, exp, dim=[1, 2], cmap=plt.cm.magma, marker='o', s=MARKER_SIZE, alpha=1, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_...
8eabbd722a4a8fea0a9ef9fe0a096007701a1216
50,197
import json def get_blacklists(blacklist_config, filename): """ Updates blacklist file. :param blacklist_config: A dict object containing Name/Url key value pairs. :param filename: File name to write the lists. """ blacklists = get_blacklist_items(blacklist_config) with open(filename, 'w') a...
591cfceb76478dede34315550a6e1387439f4c28
50,198
def neighborhood_density_all_words(corpus_context, tierdict, tier_type = None, sequence_type = None, algorithm = 'edit_distance', max_distance = 1, output_format = 'spelling', num_cores = -1, settable_attr = None, collapse_homophones = False, stop_check = None, call_back = None): ...
28d32eb05af2cde8ad405326c55625630a59145b
50,199