content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_operation_namespace_symbol(var: str): """Get operation namespace and symbol.""" ops_info = (trope_ns, var) logger.debug("get operation ops info: %r", ops_info) return ops_info
371ebd5843616dc47ef7b9c128906ff3f6f7f0ec
3,599,500
def get_voms_proxy_vo(): """ Returns the virtual organization name of the voms proxy. """ return _voms_proxy_info(["--vo"])[1].strip()
68497ab9f4a1814c7a0d0e46e1f611acb25bf23c
3,599,501
def readImage(filename): """ Read in an image file, errors out if we can't find the file :param filename: The image filename. :return: The img object in matrix form. """ img = cv2.imread(filename, 0) if img is None: print('Invalid image:' + filename) return None else: ...
a868b79627561ed4a47bac3bf589fe950240a70f
3,599,502
import os def interpretDumpedContinuum(T): """Interpret dumped continuum file. """ print('Interpreting dumped continuum for T=%g' % T) # read in continum from each file continuua = {} for element in all_elements: filename = os.path.join( tmpdir, 'tmp_conti_T%010f_%s.asc'...
c884458288a71ad240b9deb10d86be702d51bbdf
3,599,503
def mk_contract_address(sender: str, nonce: int) -> str: """Create a contract address using eth-utils. https://ethereum.stackexchange.com/a/761/620 """ sender_bytes = to_bytes(hexstr=sender) raw = rlp.encode([sender_bytes, nonce]) h = keccak(raw) address_bytes = h[12:] return to_checksu...
ae974160651089e2a35ba23e9b29e7e74963ea0f
3,599,504
import functools def synchronize(lock): """ Decorator that invokes the lock acquire call before a function call and releases after """ def sync_func(func): @functools.wraps(func) def wrapper(*args, **kwargs): lock.acquire() res = func(*args, **kwargs) lock.r...
e9ac48d67cf45e1b0cf9b6e776a93f569726b5d4
3,599,505
def help_invocation_for_command(prefix, command, locale): """ Get the help command invocation for a command. Parameters ---------- prefix: str The command prefix to show. command: senko.Command The command to get the help invocation for. locale: senko.Locale The loca...
abf80554c479e3f766e6a7dc1e7bbcafdbaa6098
3,599,506
from re import T import numpy def fourier_complex_morlet(bandwidths, centers, N): """Complex Morlet wavelet in Fourier Parameters ---------- bandwidths: array the bandwidth of the wavelet centers: array the centers of the wavelet freqs: array (optional) the frequenc...
b801822178cffcbb71b240fb3d1465481b0f42f0
3,599,507
from datetime import datetime def payment(): """ Payment Page ------------ """ user_cart = current_user.cart # extracting user info entered in checkout form form = CheckoutForm() name = form.name.data city = form.city.data address = form.address.data phone = form.phone.data...
3f160dcff655a96422a318239d9fc1533351ed18
3,599,508
import torch def derivative_sigmoid(x): """Compute the derivative of the sigmoid for a given input. Args: x (torch.Tensor): The input. Returns: (torch.Tensor): The derivative at the input. """ return torch.mul(torch.sigmoid(x), 1. - torch.sigmoid(x))
00da3734436294bc8bb40189bc1298972fbe7f93
3,599,509
def registry(add_cls=None): """Global registry of action classes.""" if add_cls != None: REGISTRY[add_cls._id] = add_cls return REGISTRY
462b30a1278b61c3eeca9c00bdc0e8477d1faa63
3,599,510
from typing import Tuple from typing import Optional def nvidia_driver_version() -> Tuple[Optional[int], Optional[int]]: """ Returns the nvidia driver version. Returns: tuple: A tuple with major and minor driver version. """ query = smi.getInstance().DeviceQuery('driver_version') if q...
febb7679100a641b98970dd8eace98ec9bfe15b4
3,599,511
def bands_to_frequency(bands): """Converts a list of bands into an array of frequency in Hz :param bands: List of bands. :type bands: list[str] :return: An array of frequency associated with the given bands. :rtype: np.ndarray """ if bands is None: bands = [] df = pd.read_csv(f"...
c9b98c2d45ab3a0bad70dd1af27c7ca215e4b4bb
3,599,512
def SBP_single(ell_fix, redshift, pixel_scale, zeropoint, ax=None, offset=0.0, x_min=1.0, x_max=4.0, alpha=1, physical_unit=False, show_dots=False, show_grid=False, show_banner=True, vertical_line=None, linecolor='firebrick', linestyle='-', linewidth=3, labelsize=25, ticksize=30, label='SBP', labelloc='l...
c9133d9dbb9b48e7b278bff061a6d66fad5b547c
3,599,513
def get_chromedriver_url(version): """ Generates the download URL for current platform , architecture and the given version. Supports Linux, MacOS and Windows. :param version: chromedriver version string :return: Download URL for chromedriver """ base_url = 'https://chromedriver.storage.goog...
c74c116e1afce42e8c048d5d914e00e2afab62ea
3,599,514
def augment(image_samples): """ augments each of the given images by addying noise, blur and both :param image_samples: image samples as dict indexed by the kanji the image depicts, with a list of (font_name, image) as value :return: a list containing the original as well as...
f8d5ce69f84d6c30a96be476b4cd041f2d11e8bb
3,599,515
def loginUser(username, password): # noqa: E501 """ # noqa: E501 :param username: The user name for login :type username: :param password: The password for login in clear text :type password: :rtype: """ return 'do some magic!'
20466f242fd92ae09113e6fe3b2ef0c1b03b85b8
3,599,516
def API_to_APP_ABPBA(API_pre, API, idx2apk, apk2node, A, B, P, p, q): """ A helper funtion for generating ABPBA random walks. Given previous API and current API, sample next APP (second A edge) """ # find neignbors of current API ser = pd.Series(A.T[API].toarray()[0]) A_neibors = ser[ser == ...
3b60e5b73fb29e4f61feff50439084243059421c
3,599,517
import os def parse_folder_info(path): """ Function: get the foldres and files within a particular path. Input: path Output: lists of folders and files """ folders = [f for f in os.listdir(path) if not os.path.isfile(os.path.join(path, f))] files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(pa...
0d486a315348cdb87d696f66b95b54961a5427c4
3,599,518
import urllib import time import sys import tqdm def download_fasta(dldir, db, tmpdir=False, force=False, skip_check=False, skip_idmap=False): """Downloads a protein fasta file If db is any of the 'UniRef' versions this function downloads a UniRef fasta file from ftp.uniprot.org/. ...
fb466cc2f3192b328374d81f0a78b6477490dbfb
3,599,519
import apysc as ap from apysc._string import indent_util def append_stroke_linejoin_expression( *, graphics: Graphics, expression: str, indent_num: int) -> str: """ Append stroke linejoin expression to specified expression's string. Parameters ---------- graphics : Graphics Target...
bb60c99658170208769e389bdd16065ecfd8886a
3,599,520
def plot_saturation( isoseq=None, ax=None, cov_th=2, expr_th=[0.5, 1, 2, 5, 10], x_range=(1e4, 1e7, 1e4), legend=True, label=True, **axparams, ): """Plots Negative Binomial model to analyze the saturation of LRTS data. Saturation (e.g. the probability to observe a transcript of ...
a21018873f441ff84defb9a6ddb0f8650c6f7d78
3,599,521
def canRead(*args, **kwargs): """ Check if an input can be read by the module class. """ return MultiFileTileSource.canRead(*args, **kwargs)
4ab00bcca27abc7d8286904177aafe5ebbc4eb38
3,599,522
import time import traceback def ep_get_delete_jobs(h, overlay_vnid, event_ts=None): """ from provided ep_history entry, create one or more ep_analyze jobs to delete the corresponding event return list of jobs or None on error """ jobs = [] if event_ts is None: event_ts = time.time() ...
b9ec23b1188e72e8554ef82d1c016e6002c4d16c
3,599,523
def conv_to_onehot_12(grid): """ :param grid: matrix with item equal to 0 or time of 2 :return: 16*grid.shape one-hot format 3D matrix """ one_hot = np.zeros((12,) + grid.shape) # , dtype=np.int) one_hot[0, grid == 0] = 1 for i in range(1, 12): one_hot[i, grid == 2**i] = 1 ret...
4c55bd4e8f46af518d30b6902bc543f69fc2a264
3,599,524
def cluster_update(context, cluster, values): """Set the given properties on cluster and update it.""" return IMPL.cluster_update(context, cluster, values)
518a512bfb86d062bc3d3a258ad7faf99db86009
3,599,525
from typing import Callable from typing import Generator import functools from typing import Any def listify( func: Callable[..., Generator[Item, None, None]] ) -> Callable[..., list[Item]]: """Decorator to make generator function return a list.""" @functools.wraps(func) def _wrapper(*args: Any, **kw...
fd05a339e77dab373ed4dd8efb7e4db4b248724f
3,599,526
import scipy def _experiment_01(): """Rejection sampling experiment 01.""" _pdf_gen_1 = scipy.stats.norm(5, 1) _pdf_gen_2 = scipy.stats.norm(-2, 3) _pdf_gen_3 = scipy.stats.expon() def complex_fun( x: t.Union[int, float, np.ndarray]) -> t.Union[np.ndarray, float]: return (0.2...
c89af2ff4f3cf72f03036e9ff21b0c73686a32bd
3,599,527
def get_shape_input(): """Get shape of the dataset for Thyroid dataset""" return (None, 36)
56786b62a6ea699ef6cad4e92777ead4e60b6b3c
3,599,528
def generate_all_nbr_from_dataframe(dist_df, nbr_distance = 100.0): """ Given a distance matrix, return a list of index positions of all neighbors within a certain distance. Parameters ---------- dist_df : DataFrame nbr_distanace : float Returns ------- all_nbrs : list ...
a735c25febbab446e28486174aa2d5ef3cb3d5d0
3,599,529
import requests import json def getToken(): """ tokenを取得する。tokenの初期化や有効期限が切れていた時などに呼ばれる。 成功したらtrueを、失敗したらfalseとその時のHTTPレスポンスを返す """ header = { "Accept": "application/json", "Content-Type": "application/json", "Content-Length": "*" } body = {"email": data.email} ...
8bc931a5b07223253d5564fcc620149fc234fa84
3,599,530
import os def from_path(tk, path, previous_context=None): """ Factory method that constructs a context object from a path on disk. The algorithm will navigate upwards in the file system and collect as much tank metadata as possible to construct a Tank context. :param path: a file system path ...
1bcffd97332b811b3aaec4412441282b0b10da98
3,599,531
def get_facility_of_source(client: Client, id: int) -> dict: # noqa: unused client """Get facility for specific source by ID.""" disallow_parameters(request) source = _get_source(id, client) if source.facility_id is None: raise NotFound(f'No facility for source ({source.id})') else: ...
23a4cbc45c3c5612f4c507aaa844448d303b02ca
3,599,532
def ess(log_weights: jnp.ndarray, log: bool = True) -> float: """Compute the effective sample size from the log-weights in a numerically stable way. Parameters ---------- log_weights: np.ndarray log-weights of the sample log: bool Compute the log-ESS or the ESS Returns ----...
b72ea46de276618e019a9162710237c74c97e4f9
3,599,533
def mi(x, y, bins=64): """Calculate the mutual information between two random variables. Calculates mutual information, I = S(x) + S(y) - S(x,y), between two random variables x and y, where S(x) is the Shannon entropy. Parameters ---------- x : array First random variable. y : arra...
9c1d371270573b10acffa5629e160d4bc9d1ea7d
3,599,534
def filter_by_predicate(walk: OsWalk, predicate: WalkPredicate, abs_path: bool = False, prune: bool = False) -> OsWalk: """ Filters a walk's folder AND file collection using the given predicate. :param walk: The walk 'object' to filter :param predicate: The condition to check; should take in the folder...
32913812a9adf8a511416e3799992897399b1d60
3,599,535
def simple_builder(pot_family, queue, code, calc_cls): """Submit simple example in AiiDA 0.12.0 and higher.""" builder = calc_cls.get_builder() builder.structure = create_structure_Si() builder.kpoints = create_kpoints() builder.parameters = create_params_simple() builder.code = code builde...
2f7b58d87589eb3095dace4ac189dbbb4e82cede
3,599,536
import warnings def fetch_latest_schema( schema_name, schema_group, mongo_collection, ): """find latest schema in database Args: schema_name (str): data source name schema_group (str): datas source group mongo_collection (:obj:`pymongo.collection`): db connecti...
986850593d8b9f2565e5c7d61e935c31f8ad05bf
3,599,537
from pathlib import Path async def check_node_modules(): """Check if node_modules exists and has contents. Returns: {bool} -- True if exists and has contents. """ ui_path = Path(__file__).parent / "ui" node_modules = ui_path / "node_modules" exists = node_modules.exists() valid ...
e76703372c46982cf728b26125808e50e2b92907
3,599,538
def FCN_ResNet34(in_channels=1, **kwargs): """ Constructs FCN based on ResNet18 model. """ backbone_net = resnet34(in_channels=in_channels) model = FCN_ResNet(backbone_net, **kwargs) return model
7a17560e27e2b4c14149c4781c5a5ca639b6289c
3,599,539
from typing import Tuple from typing import Optional from typing import Sequence from typing import Dict from operator import gt def flat_model( adata: AnnData, max_iterations: int = 1000000, epsilon: float = 0, equilibrate: bool = False, wait: int = 1000, nbreaks: int = 2, collect_margina...
c8c763040ea1ae754397be55a33e5e59f28bb00a
3,599,540
from typing import Optional def get_lambda_decay(schedule_type: str, decay: float, decay_step: Optional[int] = None): """Create learning rate scheduler (different strategies).""" if schedule_type in ['exponential', 'smooth']: assert 1.0 >= decay >= 0.9, \ f"A decay factor >1 or <0.9 is no...
cc8fdeb81f4cb0263fe1b84753a4d5e72bfa08b7
3,599,541
def get_default_permissions(opts): """Get default add/change/delete permissions given model._meta. Args: opts: model ._meta attribute. Returns: tuple of tuples (codename, verbose_name) for each default permission. """ return ((get_permission_codename(action, opts), ...
906e9b79be3ba4ac6c27105a7351fc979d620590
3,599,542
def _execute_c2(state, context): """REP: Reset status bits. When used, it will set the bits specified by the 1 byte immediate value. This is the only means of setting the M and X status register bits. """ state.flags &= ~state.current_operand return context, None
d9ae38f7b9c3c8caf14e578b29693417f04b8234
3,599,543
def fetchsoil(mukey): """ https://wepp.cloud/webservices/weppsoilbuilder/fetchsoil/100000/ """ fn = '%s.sol' % mukey fn_cache = _join(soil_dir, 'cache', fn[:3], fn) fn_invalid = _join(soil_dir, 'invalid', fn[:3], mukey) if _exists(fn_cache): result = open(fn_cache).read() ...
2ee277d4366c7344ade6bcf3201f706f0fc1488b
3,599,544
def bytes_int(b: bytes) -> int: """convert bytes to int""" return int.from_bytes(bytes=b, byteorder=ENDIAN, signed=SIGNED)
8740fc90886d812f16a5aff1831d181a6a619a83
3,599,545
import json def cognitive_states(): """ Returns json in format { 'affect': <predicted affect score>, 'drives': <predicted drives score>, 'load': <predicted cognitive load score> 'percept': <predicted percept score>, 'social': <predicted s...
672b2c2e04e431626033b6035acf76b19449d8c8
3,599,546
def loss_function_E_wlco(params, params_const, ts, E_exp, bins=np.arange(0, 1.1, 0.03), cache=True): """Loss function for E histograms and WLC distance distribution with offset """ bph = recolor_burstsph_wlco(params, params_const, ts, cache=cache) return iloss_loglike_E(bph, E_e...
647ccfe96ae84c7187c1e392a43181515ab4c44e
3,599,547
def fcast_corr(h5file, avg_trial=False): """ Calculate the local anomaly correlation for a LIM forecast at every point. Parameters ---------- h5file: tables.File PyTables HDF5 file containing LIM forecast data. All necessary variables are loaded from this file. Returns ---...
b310f9be5584035d46015e9676e7de5691ebd1f2
3,599,548
import requests def delete_video_summary(self, summaryId): """Delete a video summary""" (endpoint, method) = self.endpoints['delete_video_summary'] endpoint = endpoint.replace(':summaryId', summaryId) try: headers = {'Authorization': self.token.authorization_header()} return requests.request(method,...
891e9c77b43b0efcbcd60066cff12cc1fda777d8
3,599,549
import json def task_update(request, task_id): """ update task info :param request: request object :param task_id: task id :return: json """ if request.method == 'POST': task = Task.objects.filter(id=task_id) data = json.loads(request.body) data['clients'] = json.du...
a6cff6942c3a443d4f0bd65c7163ad2c6d51e5f8
3,599,550
def rowcol_to_xy(rows, cols, raster): """non-uri version of rowcol_to_xy_uri""" gt = raster.GetGeoTransform() X = gt[0] + cols * gt[1] + rows * gt[2] Y = gt[3] + cols * gt[4] + rows * gt[5] return (X, Y)
26ccf8da771387fffdcfc4d5b188aa562fd7be7e
3,599,551
import copy def validate(spec, data): """Validates the data and creates the config objects""" data = copy.deepcopy(data) validated_data = {} def add_validated_section(section, config): if data.get(section): validated_data[section] = config.from_dict(data[section]) add_validat...
a39e98c110036c30dafc07a1341972f41aa53aec
3,599,552
async def service(the_service, trigger, entry) -> int: """ dynamic loading of service and submitting data to this one :param the_service: :param trigger: :param entry: :return: """ attr = 'joplin_folder' if the_service.lower() == 'joplin' else the_service.lower() # check if the attri...
7a5f64bd31c8f3c61e9ec8ba351ca3dd270fd13b
3,599,553
import sys def memory_check(block_sizes, qlength_max, estimate_memory): """Return amount of memory required. Estimate memory consumption exactly as CESAR2.0 doest it. """ num_states, rlength, extra = 0, 0, 100000 for block_size in block_sizes: num_codons = block_size // 3 num_...
8539fe72e864c7aedb8e7d9daf65876e78ef2fad
3,599,554
from typing import Callable from typing import Iterable from typing import Tuple from typing import List def solve_eval( fenics_function: Callable, fenics_templates: Iterable[FenicsVariable], *args: np.array, ) -> Tuple[np.array, ufl.Form, Tuple[FenicsVariable], List[fenics.DirichletBC]]: """Computes ...
d215df785420a3701d37fad19e7d60633a30ffe4
3,599,555
def test_call_fuzz(): """Fuzz some functions.""" return """ fn main() { {dest} = takes_args(fuzz(), fuzz(), fuzz()); } fn takes_args(a: u8, b: u1, c: u4) -> u4 { write_value(&b, 10); return a + b + c; } fn write_value(ptr: *u1, val: u1) { *ptr = val; }...
4291bc625b51715c286ef61ce910fae0257c4852
3,599,556
def woe_apply(S_data, DF_groups): """ Применение группировки и WoE-преобразования Parameters--------------- S_data : pandas.Series Значения предиктора DF_groups : pandas.DataFrame Данные о группировке предиктора Returns --------------- X_woe ...
fdc1ea58c8fbefb7c5b4576a8cf94396943be6dc
3,599,557
def prepare_sonar_gid_data(): """Prepare GID Sonar data.""" potholes_file = prod_file_base + "pothole_" + prod_file_end # Read CSV gid = pd.read_csv(potholes_file) # Set accepted fields fields = ['service_request_id', 'date_requested', 'date_updated', 'case_origin', 'service_name...
e2b3d07d1d2b8922125ba6a3f1dac9b9779effd8
3,599,558
def property_cached(fun=None, pytree_node=False): """Decorator to make the method behave as a property but cache the resulting value and clears it upon replace. Args: pytree_node: a leaf node in the pytree representation of this dataclass. If False this must be hashable """ if f...
90b01dc30c9b53c96349d3ad4521a27f9129ccb3
3,599,559
def show_vocabulary(word_id: int) -> str: """指定したものを表示する""" slack_msg = "該当する番号は見つからなかったっぽ!" with VocabularyDatabase() as v_d: result = v_d.get_word_list() cnt = 1 for row in result: _, text = row if cnt == word_id: slack_msg = text cnt += 1 return...
33206b0fb307d75ffb89c1eaa5b128b9350498c7
3,599,560
def index(): """Video streaming home page.""" #FRmodel = faceRecoModel(input_shape=(3, 96, 96)) #FRmodel.compile(optimizer = 'adam', loss = triplet_loss, metrics = ['accuracy']) #load_weights_from_FaceNet(FRmodel) return render_template('index.html')
76c8718b16f62bf1a9a0c5823d4ff704119a579d
3,599,561
import logging def file_read_auth( gateway, volume ): """ Verify whether or not the given gateway (which can be None) is allowed to read (GET) file metadata from the given volume. """ # gateway authentication required? if volume.need_gateway_auth() and gateway is None: logging.error( "no ...
3063525b8c009c85d281e92ef448963bc402b88a
3,599,562
def remove_redundant_characters(str, char1, char2): """ remove substrings before and after two characters exmaple: input: '12@[123]57'. '[',']' output: '[123]' """ left_index = str.find(char1) right_index = str.find(char2) result = str[left_index: (right_index +1)] return result
7e7dc284cd1ee4b8709bdc76b6ac864fb0dead8f
3,599,563
def process_fov(field_num: int, experiment_str: str): """Process a single field of view of ISS data Parameters ---------- field_num : int the field of view to process experiment_str : int path of experiment json file Returns ------- DecodedSpots : tabular object ...
eae8c774ba9410c9c1ec0ccf0a9c787b0c484aa9
3,599,564
def state_changes_during_period(start_time, end_time=None, entity_id=None): """ Return states changes during UTC period start_time - end_time. """ where = "last_changed=last_updated AND last_changed > ? " data = [start_time] if end_time is not None: where += "AND last_changed < ? " ...
f1086d5cca74fc2f44049ee1dc9d1250f5f047e7
3,599,565
def double(number): """ This function returns twice the value of a given number """ return number * 2
65a4bb13ecb45b37f0349f4be2f834f2fd23f813
3,599,566
def fund_nav_df_fillna(fund_nav_df): """ 为 fund_nav_df 补充nav数据并记录错误日志 :param fund_nav_df: :return: """ fund_nav_df.dropna(subset=['nav'], inplace=True) fund_nav_df['nav_acc'] = fund_nav_df[['nav', 'nav_acc']].fillna(method='ffill', axis=1)['nav_acc'] return fund_nav_df
b61fdf7986c782a831bb9c97c190e161210ff925
3,599,567
def run_test_c1_start(server): """Tests that a subscriber C1 starts correctly.""" return start_and_check_client(server, "1")
5e19b3a668826a955ee3398fa586d3b31fdd1111
3,599,568
def librarianIDExists(accID): """ Da li postoji bibliotekar sa datim ID-jem """ for _, v in _users.items(): loopAccLevel = v.GetAccessLevel() if loopAccLevel == 1 and v.getID() == accID: return True return False
eb2934cda0b3abafb4202e213c243ecef40eaedc
3,599,569
def find_holes(x): """find the beginning and end of continuous None in the given iterator Args: x (iterator): the input sequence Returns: list of (int, int) indicating the beginning and the end of a continuous None sub-sequence """ holes = [] in_hole = False for idx, val in...
4d4c91fa28965501018c8c5ea24e2feef6530c1e
3,599,570
def getAllPathsInfo(demands, d_links, g, wt="weight"): """ Gets info on all the solution paths from the demand-link solution variables Parameters ---------- demands : dictionary dictionary of original problem demands. Note that the demand volumes are not used just the demand pairs. ...
4c0b6915b05a2996803001c7a91c53dfd90acb18
3,599,571
def eliminate_duplicates(duplicated_iterable): """ 对于包含重复元素且基于数组(可以通过下标访问)的可迭代对象,清除其重复元素并保持原顺序不变 @日期: 过去的某个时刻 @作者: 徐嘉辉 Args: duplicated_iterable: 包含重复元素且基于数组(可以通过下标访问)的可迭代对象 Returns: 返回一个保持了原来元素顺序且去重完毕的列表 """ return sorted(set(duplicated_iterable), key=duplicated_iterab...
ca86f37050ed6b1830c952bd76f5ac57a76eb149
3,599,572
def permutate_and_concat_batch_patches(batch_patch_embeddings, perms): """Permutates patches from a mini batch according to permutations. Args: batch_patch_embeddings: input tensor with shape [n*PATCH_COUNT, h, w, c] or [n*PATCH_COUNT, c], where PATCH_COUNT is the patch number per image and n is th...
5ba1de02791b4dc3cf9c54e55c69d90d6882ddad
3,599,573
def unique_dict_in_list(array): """Returns the unique dictionaries in the input list, preserving the original order. Replaces ``unique_elements_in_list`` because `dict` is not hashable. Parameters ---------- array: `List` [`dict`] List of dictionaries. Returns ------- uniqu...
ef18d64c4a896321d57f984c0ede3e0e897c59f5
3,599,574
def update_weights_2(x_sample, y_target_sample, F_weights,F_weights_2, G_weights,G_weights_2, omega,omega_2, thresholds,thresholds_2, buffer_bins, dt, leak, ...
0172287ad3b30ddf24c783d52bdfb55ee7a496a7
3,599,575
def zangle_to_quat(zangle): """ :param zangle in rad :return: quaternion """ return quat_mul(quat_create(np.array([0, 1., 0]), np.pi/2), quat_create(np.array([-1., 0, 0]), zangle))
bb2c6cfd8bc2f68d4355079370fcf943aff9b26e
3,599,576
import sys def builtin_readupto(t): """Read up to a given character or characters from standard input.""" if t == BInt(-1): return BStr(sys.stdin.read()) tv = set(t.convert(BStr()).value) rv = [] while True: c = sys.stdin.read(1) if not c or c in tv: break rv.append(c) return BStr(''.join(rv))
c33bb3c0a4181d859c3e08de1619086dd77f68fc
3,599,577
def merge(prevArtifacts, nextArtifacts): """Merge artifact lists with nextArtifacts masking prevArtifacts""" artifactList = list(nextArtifacts.copy()) artifactList.extend(prevArtifacts) merged = [] excludedNames = set() for artifact in artifactList: if artifact.name not in excludedName...
089aaf140111b08a98e64118fde8f8a4fd413982
3,599,578
def update(isamAppliance, name, description=None, authenticateCallbacks=None, signInCallbacks=None, localIdCallbacks=None, signOutCallbacks=None, authnPolicyCallbacks=None, check_mode=False, force=False): """ Update a specific point of contact profile """ update_required, poc_id = _check(isam...
c802a182218bdd6bb3d9ef13084e5318cdad5d51
3,599,579
def handler403(request): """ custom 403 view :param request: :return: """ return permission_denied(request, Exception(), template_name='base/403.html')
c540c03f18d20ab5b516aa8d8f569a124ca53f93
3,599,580
def init_sparksession(name: str="my-streaming-app", shuffle_partitions: int=2, log_level: str="ERROR"): """ Initialise SparkSession, and set some configuration parameters Parameters ---------- name: str Name for the Spark Application. shuffle_partitions: int, optional Number...
61b2f9187f08e83226ae166bbe3d9a09b3ef5e52
3,599,581
def get_random_state(random_state=None): """Return a Mersenne Twister pseudo-random number generator. Parameters ---------- seed : integer or ``numpy.random.RandomState``, optional, default ``None`` Returns ------- random_state : mtrand.RandomState object """ if not random_state: ...
b73333a4e95e105d3c118556822a232a155feddb
3,599,582
def fill_gaps(current_time: int, lookback: int, resolution: str) -> set: """ This function will fill time-series gaps. For example, if a second resolution metric has no data values for three seconds during a period of time, the value will be filled zero. This helps make the data more palatable ...
2546ff71525a9e00eac921c20a4d535a3f6353d3
3,599,583
def query_ensembl_karyotype_db(db_tuples_list): """Query for karyotype data in Ensembl Genomes. This function is launched many times simultaneously in a thread pool. :param db_tuples_list: List of (db, name_slug) tuples :return: List of [name_slug, asm_data] lists """ cursor = get_ensembl_curso...
050abc3103c5adb14337cb10eab379d6af77231f
3,599,584
def stencil_residual(pp_image, hp_nn, y): """Objective function.""" avg_weight = 0.5 ** 0.5 * 1 / len(y.reshape(-1)) ** 0.5 r1 = pp_image[None,:,:,:] - y[None,:,:,:] r2 = net_apply(hp_nn,pp_image[None,:,:,:]) out = jnp.concatenate((r1.reshape(-1),r2.reshape(-1)),axis=0) return avg_weight * out
bbfbf992c3e5349fff05d91983b4b818dd502809
3,599,585
import os def getpyfile(filename, split=os.path.splitext, exists=os.path.exists): """Return the .py file for a filename. Resolves things like .pyo and .pyc files to the original .py. If *filename* doesn't have a .py extension, it will be returned as-is. :param filename: the path to a file. :para...
fe004fd9f9d635a4c6538df1cc7fd48517e3d975
3,599,586
def is_datetime(val: str, tzone=None): """Check if a string is datetime, return the datetime if yes""" try: # default time zone if tzone is None: tzone = UTC else: tzone = gettz(tzone) dt = parse_dt(val) dt = dt.replace(tzinfo=tzone) ret...
be4fc5f337b4eb41be80091b9bb449f653fe067d
3,599,587
def get_city_lat_long(request): """ City code based on ISO 3166-1 (http://en.wikipedia.org/wiki/ISO_3166-1) :param request: Request Object :return: ISO Code of the City """ if 'X-AppEngine-City' in request.headers: return request.headers['X-AppEngine-CityLatLong'] return None
35310e397489b9a80a90eeb2cff952566ba22f91
3,599,588
def compare_events(df, wf=1): """ compare_events compares anomalous events that are technician labeled and machine detected. Labeled and detected data may have been widened to increase the window of overlap. Arguments: wf: integer widening factor used when generating events df: data fram...
50646e80426487678b0d04461306f8704b945ac7
3,599,589
def get_signature_genes(input_path, sig_genes_complete, var_cutoff=0.1): """ Get overlap between signature genes and available genes :param input_path: :param sig_genes_complete: :return: new sig_genes """ data = pd.read_table(input_path, index_col=0) keep = data.var(axis=1) > var_cutoff...
d8de309a122944e55bcf3ea9c4a39fc8af0eef34
3,599,590
def create_quart_app(name, static_url_path="", static_folder=""): """创建 quart app,并注入 middleware""" global PASSTHROUGH_HTTP_ERROR PASSTHROUGH_HTTP_ERROR = Global.config.get("common.http.passthrough_http_error") app = Quart(name, static_folder=static_folder, static_url_path=static_url_path) app.regi...
fa7062df48f43260baabf340751c03f5018d19b9
3,599,591
from bcbio.structural import cnvkit def run(vrn_info, cnvs_by_name, somatic_info): """Run THetA analysis given output from CNV caller on a tumor/normal pair. """ cmd = _get_cmd("RunTHeTA.py") if not cmd: logger.info("THetA scripts not found in current PATH. Skipping.") else: work_d...
56976654b04ca5ea28ef1c1b9d225fcfe9419f7b
3,599,592
import argparse def parse_arguments(): """ Must specify a directory path, a Clowder url and a service key""" parser = argparse.ArgumentParser(description='Upload nested folders to clowder') parser.add_argument('--path', required=True) parser.add_argument('--host', required=True) parser.add_argumen...
5f2cd0a16ca5d9566dee67f42e1d99e58d8197b8
3,599,593
import math def gen_new_patches(swatches_XYZ_old, metric='L*VAC'): """ colors match the l*VAC instead or l* """ targets = {} steps = {} abs_tols = {} functions = {} targets['L*VAC'] = 47 steps['L*VAC'] = 0.0001 abs_tols['L*VAC'] = 0.01 functions['L*VAC'] = c.lightness_hk_xy...
487b775919e30d1aed778a2b2a7b58d0b0844904
3,599,594
from typing import Any import sympy import numbers def is_parameterized(val: Any) -> bool: """Returns whether the object is parameterized with any Symbols. A value is parameterized when it has an `_is_parameterized_` method and that method returns a truthy value, or if the value is an instance of sym...
4c8764bab58473a9d66c7dd47fad000449d4a14c
3,599,595
from typing import Any def resnet18(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet: """ ResNet-18 model from "Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>_. Args: pretrained: If True, returns a model pre-trained on ImageNet ...
0616f01454a3734d5e3889cab08cc548c8760304
3,599,596
from datetime import datetime def get_trials_meta(filename): """ Take a filename and extract time_iso and block information from it. :param filename: file name of trials table of form trials-[time_iso]-Block_[n].csv :type filename: str :return: time_iso and block as namedtuple :rtype: tuple ...
64f4cf93650440b5e7ed4826a1f72b8ccfc8cd98
3,599,597
from typing import List from typing import Optional from typing import Any def fusion_with_peer_attention(inputs: List[tf.Tensor], index: int = None, attention_mode=None, attention_in=None, use_...
40976d67dc78aef6bc94552210e1df92ab554a63
3,599,598
def parse_checksum(header: str) -> str: """ Parse the Checksum header (eg. from the email epilogue) """ # Epilogue example: # "Checksum: e231f8e724890aca477ca5efdfc7bc9c31e1da124510b4f420ebcf9c2d1fbe74\r\n" msg = HeaderParser().parsestr(header) return msg["Checksum"]
81c62822f0e0e3e30b24daf8b33f86cfab3dec28
3,599,599