content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from pathlib import Path def select_file(start_path=config['data_saving']['h5file']['save_path'], save=True, ext=None): """Save or open a file with Qt5 file dialog, to be used within an Qt5 loop. Usage:: from pymodaq.daq_utils.daq_utils import select_file select_file(start_path="C:\\test.h5"...
64dfa3bf7dff4caa46725fb2e0d140c84dd4700d
3,603,100
import os def _mkdir(dir_path): """Safely make directory.""" try: os.makedirs(dir_path) except OSError: pass return dir_path
f02ed083c90c25eb04c46e694da617b94eaacb29
3,603,101
import json def fix_hardprof_str(hardprof): """Fixture for a hard profile string""" return json.dumps(hardprof)
7cf08fceb561ebadcb44d6b13bcb7ad52198934d
3,603,102
import logging def eval_policy(policy, rng, state, model, test_ds, epoch): """Eval for a single epoch.""" batch_metrics = [] policy = flax.jax_utils.unreplicate(flax.jax_utils.replicate(policy)) # Function is recompiled for this specific policy. test_ds = util_fns.get_iterator(test_ds) for batch in test...
5dcac82776a6671960d7500621409dcec17edb44
3,603,103
def Imp(x, y): """Return True if X implies Y Performs a bitwise comparison of identically positioned bits and sets corresponding bit in the output. This amounts to the following truth table: X Y Output F F T T F F F T T ...
68ac0456879d0aedec58988de2528bd9c6141941
3,603,104
def learning_edge_subset(g, num_pos, num_neg, remove_positives=False, seed=None): """ Returns a tuple of (num_pos positives edges, num_neg negative edges). Selected edges are of kind g.graph['edge_key'], start at the node kind specified by g.graph['source_kind'], and end at the node kind specified by ...
603640e20b73062e3e09c8a59b655fb1b58f989c
3,603,105
from typing import Callable from typing import Set from typing import Type def is_quorum(is_slice_contained: Callable[[Set[Type], Type], bool], nodes_subset: set): """ Check whether nodes_subset is a quorum in FBAS F (implicitly is_slice_contained method). """ return all([ is_slice_contained(n...
4a4af3af8ca5a3f969570ef3537ae75c17a8015c
3,603,106
def code_flag(*args): """ code_flag() -> flags_t 'FF_CODE' """ return _ida_bytes.code_flag(*args)
4de69be17407ef52aa1f04b3753ecd8d399133e4
3,603,107
def makecorr_tid(ptsfs=None,dmsfs=None,**kwargs): """Tau ID SF, pT-dependent.""" verb = kwargs.get('verb',0) tag = kwargs.get('tag',"") # output tag for JSON file outdir = kwargs.get('outdir',"data/tau") # output directory for JSON file dms = [0,1,2,10,11] ptbins = kwargs.get('bins',[20.,25.,30...
d3e56c2e92bbcc12ffec8b452cc4d73a0bae0343
3,603,108
from typing import Optional def eval_acq_func( acq_func: AcquisitionFunction, X_test: MatrixLike2d, return_type: Optional[str] = 'tensor' ) -> MatrixLike2d: """Evaluate acquisition function at test values Parameters ---------- acq_func : 'botorch.acquisition.AcquisitionFunction'_ ...
f688f2e1e9642ef92a8e108ae558c8732905aea9
3,603,109
from datetime import datetime def add_datetime_to_page(pdf_page, font_size=12, h_offset=1, v_offset=0, header=None, include_date=False, include_micro=False, datetime_formatter=None, position="nw", char_w_factor=0.5, li...
b571511ac4240eaf07460d172d04a05049ba873d
3,603,110
from typing import Union from typing import Dict def make_source_tech( info: Union[message_ix.Scenario, ScenarioInfo], common, **values ) -> Dict[str, pd.DataFrame]: """Return parameter data for a ‘source’ technology. The technology has no inputs; its output commodity and/or level are determined by `...
92b35e3d1eb2010a91707eea298a99abb7a3add5
3,603,111
def _kmeans_plusplus(X, n_clusters, x_squared_norms, random_state, n_local_trials=None): """ Initialise a specified number of centroids using the k-means++ method (heuristic). Prior validation of data is assumed. Parameters ---------- X : ndarray of shape (n_samples, n_features) The dat...
380a6ed165040a7e77c0f0812b1df2d8379291ff
3,603,112
def bat_day(soc, temp, cycles, soc_low, soc_high, rate): """Model the degradation from the battery in one day. This was a test model that isn't used in the finak optimizer """ # Maybe add some code to check inputs are OK range, etc. DegCycle = bat_cycle(400, soc_low, soc_high, rate)**(cycles/400) ...
6b1b80e60f3aee4a323da8ca2f4fbf71c7e2f7cf
3,603,113
def count_consonant(token): """ Count consonants in a given token. token: string to be counted for consonants returns INTEGER """ count = 0 for tok in token: if check_consonant(tok): count+=1 return count
ef99ba94eead9bf0b234ffe05de795fb6a4e645e
3,603,114
def enso_finder(dfoni): """From an ONI dataframe, this function returns an array with 1 for El Nino, -1 for La Nina and 0 for neutral years. It has been established that if ONI persists over 0.5 or below -0.5 for 5 consecutive months it is an El Nino or a La Nina respectively. Parameters ------...
d0c56bd19867cd83358cd9fde60200cb7abb602c
3,603,115
def jensen_shannon_divergence(m1, m2): """ Jensen Shannon Divergence between two probability matrices/vectors :param m1: :param m2: :return: """ m = 0.5*(m1+m2) return (0.5 * kullback_leibler_divergence(m1, m)) + (0.5 * kullback_leibler_divergence(m2, m))
f3c419705e436fbecdd684e332ae50013471a210
3,603,116
from datetime import datetime import os def export_hdf_day(code, market_type=None, export_path='export', features=None): """ 训练用隶属数据导出模块 """ if (isinstance(code, list)): code = code[0] if (market_type == QA.MARKET_TYPE.STOCK_CN): market_type_alis = 'A股' elif (market_type == QA...
41291fe013e49b381ffc638cbeca20e1f748cb39
3,603,117
import copy def get_aecg_intervals( anns_df_in_ms: pd.DataFrame, include_all_found_intervals: bool = False) -> pd.DataFrame: """Calculate intervals (e.g., PR, QT, ...) from annotations All intervals are computed regardless of whether intervals are within or outside of physiological ranges in ...
6a3b477277d046309630886a7f9f18b16f1337b4
3,603,118
from pathlib import Path import json def save_local(data, file_path="tmp", file_name="tmp"): """Saves data locally.""" if file_path == "tmp": file_path = "TMP/" file_path = Path(file_path) / Path(file_name) Path(file_path).parent.mkdir(parents=True, exist_ok=True) if isinstance(data, p...
6d44ab5443b6ad45bbfa52a4360feb96fcad9948
3,603,119
import os def get_maps_dir(): """ Get the exploration/maps dir :return str: exploration/maps dir """ return os.path.join(os.path.dirname(os.path.dirname(__file__)), "maps")
d30410b4fe5e87f9183d18a7d5ee82d6f3cc0b7a
3,603,120
import copy def clustal_from_alignment(aln, wrap=None): """ Parameters ---------- aln can be an Alignment object or a dict wrap sequence line width. Only available if sequences are aligned. Returns ------- Returns a string in Clustal format """ if not ...
49218ea82e58ead3740feda836b337577c77e7e2
3,603,121
import contextlib import wave def read_wave(path): """Reads a .wav file. Takes the path, and returns (PCM audio data, sample rate). """ with contextlib.closing(wave.open(path, 'rb')) as wf: num_channels = wf.getnchannels() assert num_channels == 1 sample_width = wf.getsampwidth...
e5537450f91bea491a6aa6f35d98095386d6260c
3,603,122
def smeft_evolve_leadinglog(C_in, scale_in, scale_out, newphys=True): """Solve the SMEFT RGEs in the leading log approximation. Input C_in and output C_out are dictionaries of arrays.""" C_out = deepcopy(C_in) b = beta.beta(C_out, newphys=newphys) for k, C in C_out.items(): C_out[k] = C + b...
ea004f9a858b7f15e8aa4f62968390f50b3830e2
3,603,123
def move_column(df: pd.DataFrame, column: str, index=0) -> pd.DataFrame: """ Moves the column with the given name to the given index, returns dataframe """ columns = list(df.columns) if column not in columns: logger.warning(f"move_column - column {column} is not present in df.columns: {df.columns}")...
c4da45fddf458944ecfa083859b1fff3a054c197
3,603,124
def getSkinFrictionBetweenPosition(data_outVTK, wall_outVTK, cord_choice, x_p0, x_p1, Npts, Uinf=None, Rhoinf=None): """ Compute the boundary layer thickness for *Npts* equally distributed between the 2 position defined thanks to *x_p0*, *x_p1* and *cord_choice*. See the documentation of the function g...
0b97b52766f17edfc20a8272f2ab749167176e67
3,603,125
import os def _split_by_regions(regions, dirname, out_ext, in_key): """Split a BAM file data analysis into chromosomal regions. """ def _do_work(data): bam_file = data[in_key] if bam_file is None: return None, [] part_info = [] base_out = os.path.splitext(os.pat...
71007f0da5934aad0b3ed38ad96efd33707bdbe3
3,603,126
import os def _write_bilby( parameters, samples, outdir="./", label=None, filename=None, overwrite=False, extension="json", save=True, analytic_priors=None, cls=None, meta_data=None, **kwargs ): """Write a set of samples to a bilby file Parameters ---------- parameters: list list ...
1612a43e88d1117fb6abb1e7ced82d72bb721a7c
3,603,127
def xcor_redshift(spectra, template, sub=False, z1=0, z2=1, zstep=0.001): """Meaure the redshift of a spectra by cross correlating it with a template returns an array of correlation values """ zvalue=np.arange(z1,z2,zstep) cc_arr=np.zeros(len(zvalue)) sflux=continuum_subtract(spectra...
ec766187f2de01a4f5c3353e196f478a6138f38b
3,603,128
from re import match def extrakey(key): """Return True if key is not a boring standard FITS keyword. To make the data model more human readable, we don't overwhelm the output with required keywords which are required by the FITS standard anyway, or cases where the number of headers might change over ...
d4c36c3a5408d7056e55d5e67ebebe0b960e5b72
3,603,129
def get_number_rows(ai_settings, ship_height, alien_height): """Calculating how much rows of aliens can be fitted in screen""" available_space_y = (ai_settings.screen_height - (3 * alien_height) - ship_height) number_rows = int(available_space_y / (2 * alien_height)) return number_rows
8ce25635ce0e68d1634d8c301a38090815aece03
3,603,130
from typing import Dict from typing import Any import os def extract_region(m: Dict[str, Any]) -> ct.Region: """Returns the region specified in the args; defaults to an environment variable. If that's not supplied defaults to the default cloud provider from caliban.cloud. """ region = m.get("region") or os...
635a4439d1bf687d8c5da96733c341adf4cff51d
3,603,131
def failed(err = adp_err_failed): """ the adp event callback failure result. """ return adp_result(err)
60185225394c6360444e1f430f567d1f48e77164
3,603,132
def copy_structure(x, y): """ copy a new x which has same rotation and center as y """ n = min(x.shape[0], y.shape[0]) x1 = x[:n, :] x2 = y[:n, :] center1 = x1.mean(axis=0) center2 = x2.mean(axis=0) _, _, u = superposition(x2, x1) xa = x1 # centering x xb = x1 - np.tile(c...
7d2bc4ed8c52048e63515c88092ca95e59ce3d68
3,603,133
def dropStudentsWithMinEvents(df, saveDroppedAs=None, studentId='BookletNumber', blockId="BlockCode", minEvents=3, verbose=True): """Drop students with fewer than a c...
8743c8e8f1d6c48b852013c53d9e9cf647a17fab
3,603,134
def P(N_c, N_cb, e_t, t, A, N_bb): """ Returns the points :math:`P_1`, :math:`P_2` and :math:`P_3`. Parameters ---------- N_c : numeric Surround chromatic induction factor :math:`N_{c}`. N_cb : numeric Chromatic induction factor :math:`N_{cb}`. e_t : numeric Eccentri...
82e444ca0e7563f061b69daedd82ff3fc771f190
3,603,135
def update_env(request): """ 修改环境信息 处理的异常: id类型错误 指定ID不存在 参数不合法 完整性约束 :param request: object, http request information :return: status information """ @process_frame(request, 'POST') @safe_response def func(): env_id = int(request.POST['id']) ...
d1440faa0d933aec07a4a9b25f23a828f8f544d9
3,603,136
def create(*args, **kwargs): """Returns a NLDataset.""" return NLDataset(*args, **kwargs)
10e926cf9f834cb03effd8c0cd57143b98a1a9af
3,603,137
from datetime import datetime def index(request): """Index page (with daily game scores). """ date = datetime.today().date() return render_score_page(request, 'main/index.html', date, 'Home')
d21b0f8052935ce752a855bc90f565ed276b0785
3,603,138
import os import re import json import importlib def generate_testcase(schema, graphql_path, base_test_class=DefaultBaseTestCase, django_environment=False): """ Generate one test case class, corresponding to a `.gql` file. """ # compute test class name class_name = graphql_path.split(o...
acdda3f7af668f325517e31632b515f12f6f93a8
3,603,139
import random import string def randomStringGenerator(length=13): """create random string ascii values""" return ''.join(random.choice(string.ascii_letters) for _ in range(length))
5f4406f67d953cc1198ae79ae049dbd6e9b678b4
3,603,140
def resnet50(**kwargs): """Constructs a ResNet-50 model. """ model = SlowFast(Bottleneck, [3, 4, 6, 3], **kwargs) return model
19efaa10875f25ff5b26acb82f73d735c24dfa4f
3,603,141
def schedule_conv1d_ncw(outs): """Schedule for conv1d_ncw Parameters ---------- outs: Array of Tensor The computation graph description of conv1d_ncw in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """...
4dc517cd91e9bbf6881cc4f93940516731dc0a3b
3,603,142
def crushmap_get_all(context): """get all crushmaps""" return IMPL.crushmap_get_all(context)
523ca4a90fda81f1aac5d9c3df70cf51f3f1e717
3,603,143
from typing import Dict from typing import Any import json async def load_results(config: Config, document: Dict[str, Any]) -> dict: """ Load the analysis results. Hide the alternative loading from a `results.json` file. These files are only generated if the analysis data would have exceeded the MongoDB s...
963ea88c1e70f8a6cce23bc4f864fa285f576114
3,603,144
from typing import Dict from typing import Any def obj_blockwords_to_snake(obj: Dict[str, Any]) -> Dict[str, Any]: """Converts block cased keys in a dict like SETTLEMENTDATE into settlement_date""" return {blockwords_to_snake_case(k): v for k, v in obj.items()}
b92d02a1e081113f00947f4bbdd9107e33ff3862
3,603,145
from typing import Callable from typing import Any def Depends(call: Callable, *, to_async: bool = False) -> Any: """ Used to provide extra information about a field. :param call: callable that will be called when a dependency is needed for this field :param to_async: whether to convert the callable ...
b689de3f0c8876cc73912a78bbf83630192c755b
3,603,146
import os def _update_root_build_dir(commands, root_build_dir): """Update the GN root build dir when it appears in commands. The absolute root build dir sometimes appears in build commands (e.g. when building with a 'gcc' variant, in a -fdebug-prefix=<...> compiler argument). This function replaces i...
80c7cce2ae8600ff5d7cd235672994c7d3edca1b
3,603,147
import os import pickle def _load_static_data(module_path): """ load the data, raise the error if failed to load latlongrid.dat Parameters ---------- module_path : string mainpath of the LatLonGrid module Returns ------- latlondata : dict dictionary containing for each ...
e3ec215abb3bf7389c18583375d8a3c234af8cbf
3,603,148
import copy def FE_convert_all_object_columns_to_numeric(train, test=""): """ FE stands for Feature Engineering - it means this function performs feature engineering ###################################################################################### This is a utility that converts string columns to...
67d398073b4ed5aae7db57c87ef72753902c9a77
3,603,149
def to_networkx( nodes, edges, direction="oneway", from_id_col="u", to_id_col="v", edge_id_col="id", node_id_col="id", force_bidirectional=False, network_type=None, retain_all=False, osmnx_compatible=True, ): """ Creates a NetworkX.MultiDiGraph from given OSM GeoDataF...
b397fe54449dc49d152f42ef2da79836545bfb7c
3,603,150
def paramvec_to_lmfit(paramvec, max_amp, max_fwhm=None): """Transform a Python iterable of parameters into a LMFIT Parameters object.""" ncomps = int(len(paramvec) / 3) params = Parameters() for i in range(len(paramvec)): if 0 <= i < ncomps: if max_amp is not None: pa...
80480a2266dcccae4cdb7532496dc83436833f0e
3,603,151
def CGaussFilter_Image16_sigma2Size(dSigma): """CGaussFilter_Image16_sigma2Size(dSigma) -> vpl::tSize""" return _ImageFilters.CGaussFilter_Image16_sigma2Size(dSigma)
4150bc88e3a2164a5c9e796552cdaa251cc58f79
3,603,152
def append_disputed_countries(grid_ctrys): """Add "disputed aliases" to the list of GRID countries, to "forgive" either GRID or the matching dataset for using the "wrong" country, in the case of disputed countries. Args: grid_ctrys (set): Set of countries to be extended with disputed aliases. ...
2535114e0d7873db012702fe9ee176d2e36fb13d
3,603,153
def _exp_greenwoods_ci(mf, nf, r, alpha=0.05): """ Gets the exponential Greenwood's confidence interval. """ if alpha <= 0 or alpha >= 1: raise ValueError("alpha must be between 0 and 1 exclusive.") # Don't calculate confidence interval for time 0 where R(t)=1. mf = mf[1:] nf = nf[1...
e7524853e388262703acf3657bea8381192aebce
3,603,154
import requests import time import json def api_call_networkcontainer_views(view, logger): """ DDI api call for network containers within the 'view' value. Returns the utf-8 decoded with a json load. Return Variables: -- rddijsonnetcont """ trynetworkview = 3 rnetcont = None ...
4356bb73fd679c8d9ad6210dadefc042466f099a
3,603,155
def turnoverrate(cftable, end=yesterdayobj()): """ calculate the annualized turnoverrate :param cftable: pd.DataFrame of cftable :param end: str or obj of datetime for the end date of the estimation """ if len(cftable) == 0: return 0 end = convert_date(end) start = cftable.iloc[...
2f8c63ce7d0e965e38d03900bc11e47268f99aa2
3,603,156
def build_production_problem(products, resources, consumptions, **kwargs): """ Takes as input: - a list of product tuples (name, demand, inside, outside) - a list of resource tuples (name, capacity) - a list of consumption tuples (product_name, resource_named, consumed) """ mdl = Mod...
9fd893e6c555ff654ddf9fdeb9f238b8bb3caf73
3,603,157
def C(classname): """get an ObjC Class by name""" return objc.objc_getClass(_utf8(classname))
a9ab411a637760be0cf9038728151017cf2d3e01
3,603,158
def GetMessages(): """Import and return the appropriate admin messages module.""" return apis.GetMessagesModule('datastore', _DATASTORE_API_VERSION)
4a83b56cd2c2831efa8baaa27e19695ccacf8636
3,603,159
def Jolanta_GTO_H(GTO_fn, alphas, Ns, param, l=1): """ Hamiltonian matrix in a GTO basis set Parameters ---------- GTO_fn : either Jolanta_1D_GTO() or Jolanta_3D_GTO() alphas : np.array of GTO exponents Ns : np.array of normalization constants param : (a, b, c): parameters of the Jo...
0105b7b035ff9b880b53683a3a5c91fa68fac1b7
3,603,160
import torch def list_of_dict_to_dict_of_array(old_lis, force_list=None, force_cat=None, stop_recursion=None, to_tensor=None): """ From a list of dict to a dict of array (or list) """ if isinstance(old_lis, list): if not old_lis: return {} elif not isinstance(old_lis[0], di...
0d306eb59af9b13477e02b2b5a27805b9797ab25
3,603,161
def testCuadro(linkCuadro): """ Dado el link de un cuadro, devuelve un diccionario con su info """ util.abrir_url_recarga(linkCuadro,"ficheros/cuadro.txt",True) f = open ("ficheros/cuadro.txt", "r") s = f.read() f.close() bs=BeautifulSoup(s,"html.parser") cuadro={} info=bs.find("...
531b80766b8d6001b7ffa44d89a989dbd9792f90
3,603,162
from typing import List def extract_transmon_coupled_Noscillator(capMatrix, Ic: float, CJ: float, N: int, fb: List[float], ...
481f1f1c4def657001d23faf50c4aed40e7c12d2
3,603,163
def bi_class(raw, boundary): """ divide raw input into two classes, based on selected boundary """ bi_class = pd.Series([0 if i < boundary else 1 for i in raw]) return bi_class
4e80f7cafeb1d66f660818b86b04331737991c75
3,603,164
import subprocess import time def mount_windows_share(): """Mount the Windows images share for use in Windows setup""" # Blindly skip if we mounted earlier if WINDOWS_SERVER['Mounted']: return None else: try: # Test connection run_program('ping -w 800 -n 2 {IP}...
455a78657de110e2e454cef561e7e503c07c894d
3,603,165
import os def report_directory_path(): """Path to directory where monitor write report files to. This must point to the directory which is mounted to the monitor service container to read issued reports. """ base_directory = os.path.realpath( os.path.join(os.path.dirname(__file__), os.par...
555a901e0c665d753ec38d736264a7b37eb11a1f
3,603,166
def calculate_results(subject, eval_time, testfields, reffields): """ Function to print out the results of the colorimetric analysis Input: subject: ID of the subject eval_time: Evaluation time, after which the input image was taken: 30: Glucose, Bilirubin ...
1774ce16a2765f5b2b31fbbc1cd9ae8c28ee4702
3,603,167
def detect_delimiter_separated_values(filename): """Attempts to check for csv or tsv mimetypes""" df = pd.read_csv(filename) if len(df.columns) > 1: return 'text/csv' if len(df.columns) == 1: if df.columns[0].count('\t') >= 1: return 'text/tab-separated-values'
e653004be38db84c5ac2da7914591673e5cd8cf4
3,603,168
import os import sys def import_every_module(python_path, module_list, only_installed=True, fLOG=print, start=0, end=-1): """ import every module in *module_list* assuming they are defined by @see cl ModuleInstall or a string @param python_path python path @param module_list mod...
8ea468e1a27bda9272e8b364e14eef3991a4a51e
3,603,169
from shapely.geometry import Polygon # Find max in region def find_max_in_region(geodf,region): """ Find the largest cases value within a specified region and days list region_Lon = {'name': 'London', 'xlim':[-0.6,0.5], 'ylim':[51.2,51.8], 'date_loc':[0.2,51.75] } maxval = find_max_in_region(geodf,re...
dd49f86305380309c2b795a2e5932c42da88633b
3,603,170
def is_token_blacklisted(encoded_token, public_key=None): """ Decode an encoded token and check if it is blacklisted. Args: encoded_token (str): JWT to check public key (Optional[str]): key to decode JWT with Return: bool: whether JWT is blacklisted """ public_key = pub...
9bb4a42055b462fc2732f706006e044d90deff33
3,603,171
def config_multiple(): """Return multiple config fixture.""" return load_multiple_config_yaml()
f48c03f9c713700cec8b172454533bc87a554c40
3,603,172
def perimeterCircle(r=1.): """Calculate the length of the perimeter of a circle. Parameters ---------- r: float, optional (default=1.) Radius of the circle, r>0. Returns ------- float Perimeter of the circle. """ return 2. * np.pi * r
c1af01851816109fae5506aa022b55f3a31c588a
3,603,173
def _gh_stepsize(vP): """ Purpose: Calculate stepsize close (but not too close) to machine precision Inputs: vP 1D array of parameters Return value: vh 1D array of step sizes """ vh = 1e-8*(np.fabs(vP)+1e-8) # Find stepsize vh= np.maximum(vh, 5e-6) ...
f53089dd00b3b853fb330b04c124f8cdd1eb602b
3,603,174
from typing import Optional import json def read_template_description(filename: str) -> Optional[TemplateEntity]: """ Reads the template description file, and returns None if it isn't valid, or a template entity (with the purpose left blank) if it is. """ with open(filename, 'r') as f: dat...
7173cd93202527122cfab57cd87238f5a1bc9685
3,603,175
import os from sys import path def load_dtu_flockwork_params(scaled=False): """Load the standard parameters to generate surrogate networks for one week of DTU data using the Flockwork-P model with varying rates. Parameters ---------- scaled : bool, optional If this is `True`, load the re...
4ab1c9551b1434fc92f0b9bc40e9d171d058a875
3,603,176
async def import_file( name: str, md5sum: str, background_tasks: BackgroundTasks, file: UploadFile = File(...), ): """ This is a file importer to be validate postpone or just saved. """ token: str = await Funcs._generate_token() background_tasks.add_task(BatchService.upload, name, fi...
ac10c314a2e91158733c6a60715abed6d16900af
3,603,177
from datetime import datetime def fetch_from_github(shapes_graph, client, oauth_token, topics, github_direct_search): """Fetch shapes files from GitHub using the GraphQL API. We filter repositories by topics provided as argument """ time_start = datetime.now() stopping_job = False for github_t...
a81385f8ca804eeddfd238a8d976efe68ef27431
3,603,178
from typing import List def roles_required(roles: List[str], require_all: bool = False): """ Wrapper used to check for multiple roles for a current user. User can be required to have all roles or only 1 of the provided list. :param roles: List of String names for the roles :param require_all: If ...
f24604f64041e9d5957b8577e7cb99f9a2240482
3,603,179
import requests import html import re def get_stat (ipaddr): """ Get statistics from a host. May be 4 miners type. 0 - unsupported device 1 - antminer hwv 1.0.0.6 or 1.0.1.3 or 16.8.1.3 2 - antminer hwv 1.0.0.9 3 - innosilicon Return string with parameters """ miners_device = {} ...
13a255b287476f2be2cd57376fc7193531bd4122
3,603,180
def forensic(): """ brute force / comprendre le problème ... """ def is_strange(i): l = len(str(i)) if l == 1: return True if i % l != 0: return False return is_strange(i // l) def construction(i): s = str(i) l = len(s) if l...
02acb3a92aa2fc110ab356dc5786dac247c3c63f
3,603,181
def analyze_msg(raws, a): """ Analyze message. Determine if sender and command are valid. Return values: None: Sender is invalid or no text part False: Invalid command Otherwise: Array: message split by lines :type raws: dict """ print("Analyzing message with uid " + str(a)) ...
a7583ca657e49b472f77300fadddb73b1aa6d131
3,603,182
def adjust_RED_by_structure_name(dicom_dataset): """Adjust the structure electron density based on structure name. """ structure_names = [ structure_set.ROIName for structure_set in dicom_dataset.StructureSetROISequence ] adjustment_map = RED_adjustment_map_from_structure_names(structure_na...
0ef06038806795d7e42e4e88fa18e1ab832e0fd5
3,603,183
def mass_comp_function(values, bins, scale=1, aktomassd=183): """ M(>Ak), mass weighted complimentary cdf """ if hasattr(bins, "__getitem__"): range = (np.nanmin(bins), np.nanmax(bins)) else: range = None # if scale != 1: # aktomassd = scale h, bins = np.histogram( ...
a94f56c94c037543202d90e472c0ca2e57945091
3,603,184
import itertools import math def split_dl(data_it: dataset.DataIterable, fpath_template: str, num_artcles_per_file: int) -> dataset.DataIterable: """Split the dataloader data into `num_articles_per_file` articles splits and generate new paths with the template `fpath_template` for each split. Parameters ...
6bf9802b70a10fcd58256106fb58efcd4ff86a74
3,603,185
def generate_all_bns_parameters(sample, likelihood=None, priors=None): """ From either a single sample or a set of samples fill in all missing BNS parameters, in place. Since we assume BNS waveforms are aligned, component spins won't be calculated. Parameters ---------- sample: dict or...
8e9b6b256f436a6c415e715e79c897be2874ac64
3,603,186
def load(fp, *, fmt=None, use_builtin_types=True, dict_type=dict): """Read a .plist file. 'fp' should be (readable) file object. Return the unpacked root object (which usually is a dictionary). """ if fmt is None: header = fp.read(32) fp.seek(0) for info in _FORMATS.values(): ...
daa0f41e0814654e49dbdb6d86f277b8c84d37d9
3,603,187
def _conv_arg_to_workload(data, kernel, strides, padding, layout, out_dtype): """convert argument to workload""" if len(kernel.shape) == 4: raw_kernel = kernel else: # the input kernel is transformed by alter_op_layout shape = get_const_tuple(kernel.shape) raw_kernel = tvm.placehold...
c38369d25e0336f7c2a72bda63bac09566a439d5
3,603,188
def avgDicts(list_of_dicts): """given a non empty list of dicts with the same keys, it returns a dict which contains the avg of each dict in the list Arguments: list_of_dicts {list} -- """ result_dict = {x:0 for x in list_of_dicts[0].keys()} for key in result_dict.keys(): re...
2cd24e3260f933df2082b426cfb5f9058f05d319
3,603,189
def binarize_weights(x, name=None): """Creates the binarize_weights Op with f as forward pass and df as the gradient for the backward pass Args: x: The input Tensor name: the name for the Op Returns: The output tensor """ def f(x): alpha = np.abs(x).sum(0).s...
67be10ec023c7923d7fb52a698b85a38f1e04ce4
3,603,190
def similarity(data_lst, user1, user2): """ gets list of sets of hashtags for both users for each item in user lists find intersection of hashtags add intersection to intersection list at that month :param data_lst - list of twitter data: :param user1 - first twitter user entered by ...
f908337cf27bf368f651c7d5c2fd3a5cd17fa645
3,603,191
import re def trim_http(url :str) -> str: """ Discard the "http://" or "https://" prefix from an url. Args: url: A str containing an URL. Returns: The str corresponding to the trimmed URL. """ return re.sub("https?://", "", url, flags = re.IGNORECASE)
472e71a646de94a1ad9b84f46fc576ed5eb5a889
3,603,192
def _create_overpass_query(polygon_coord_str, tags): """ Create an overpass query string based on passed tags. Parameters ---------- polygon_coord_str : list list of lat lng coordinates tags : dict dict of tags used for finding elements in the selected area Returns ----...
aa766c983d4fa7aa46c9dfd5259f82b94f153798
3,603,193
import time def cache_function(length): """ Cache the result of function :param length: time in seconds to stay in cache """ def _decorated(func): def _cache(*args, **kwargs): key = sha1(str(func.__module__) + str(func.__name__)).hexdigest() # Search in cache if...
18585ee83dfcae3608e7d99fbbe51dc2d9378c96
3,603,194
from aquaregia.unction import MaskedBatchNorm import random def test_MaskedBatchNorm(): """test the `MaskedBatchNorm`; ensure it appropriately masks the right dimension and scales outputs to unit normal""" _inputs = random.normal(random.PRNGKey(2623), shape = (5,3)) _mask = Array([1,1,1,1,0], dtype=jnp.bo...
2c3218f604aa08db9f52615390b8087186f49682
3,603,195
def notify_sample_status(profile_id=str(), action="message", msg=str(), data={}, html_id=""): """ function notifies client changes in Sample creation status :param profile_id: :param action: :param msg: :return: """ # type points to the object type which will be passe...
07f13a2c19c7f9fb280504a484e1fb6e2e0c8bf4
3,603,196
def tf_augment_image(image, random_augmentation=False, intensity=0, rotation=0, width_shift=0., height_shift=0., brightness=None, horizontal_flip=False, vertical_flip=False,...
cd360c6c38c83c657fb6c51474b205a7ea26cd62
3,603,197
def test_validate(monkeypatch): """ . """ # pylint: disable=unused-argument @counter_wrapper def fake_validate_false(self) -> bool: """ . """ return False @counter_wrapper def fake_validate_true(self) -> bool: """ . """ re...
eec55c3a46886d2af7aee5e5c9c9110515230442
3,603,198
def logger(function): """ Wrap a Bottle request so that a log line is emitted after it's handled in case of errors to make it easy to debug. """ @wraps(function) def _logger(*args, **kwargs): actual_response = function(*args, **kwargs) # get function name closures = functio...
19b89f400687ec5c5a24c4566c7a5ebb5a29dbe4
3,603,199