content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def efficientnet_b0(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """EfficientNet-B0""" model_name = "tf_efficientnet_b0" default_cfg = default_cfgs[model_name] # NOTE for train, drop_rate should be 0.2 # kwargs['drop_connect_rate'] = 0.2 # set when training, TODO add as cmd arg mo...
b01644546a005b856ba35a9965fbff33e9bae132
3,645,900
import urllib def application(environ, start_response): """ make Passenger interpret PATH_INFO the same way that the WSGI standard does """ environ["PATH_INFO"] = urllib.parse.unquote(environ["PATH_INFO"]) return app.app(environ, start_response)
3de57b31206a374da0378788f20e7bd8b1eca9af
3,645,901
from railrl.torch.pytorch_util import set_gpu_mode import random def run_experiment_here( experiment_function, variant=None, exp_id=0, seed=0, use_gpu=True, # Logger params: exp_prefix="default", snapshot_mode='last', snapshot_gap=1, git_...
ee8b0f727027d8dcee804565606a7f82f2c77ca9
3,645,902
from typing import Tuple def normalize_chunks(chunks: Tuple[Tuple[int, int]]) -> Tuple[Tuple[int, int]]: """ Minimize the amount of chunks needed to describe a smaller portion of a file. :param chunks: A tuple with (start, end,) offsets :return: A tuple containing as few as possible (start, end,) off...
d49d1abed0573a86e0eeee5d2e5ed2e129f3274e
3,645,903
def learning_rate_schedule(adjusted_learning_rate, lr_warmup_init, lr_warmup_step, first_lr_drop_step, second_lr_drop_step, global_step): """Handles linear scaling rule, gradual warmup, and LR decay.""" # lr_warmup_init is the starting learning rate; the learnin...
26021c7cbdb264ddc84fad94d4a01b51913f3a72
3,645,904
from typing import List import logging def set_power_state_server(power_state: ServerPowerState) -> List[float]: """Record the current power limit and set power limit using nvidia-smi.""" # Record current power limits. if power_state.power_limit: cmd = "nvidia-smi --query-gpu=power.limit --format...
8a9ac60dbd58dedf5f39386a7233b88b7cc5aa79
3,645,905
from typing import Union def score_normalization(extracted_score: Union[str, None]): """ Sofa score normalization. If available, returns the integer value of the SOFA score. """ score_range = list(range(0, 30)) if (extracted_score is not None) and (int(extracted_score) in score_range): ...
74501e9351296037ecc90ae647155e3c6b76ae01
3,645,906
import os import requests def get_session(): """Creates an authorized Requests Session.""" credentials = service_account.Credentials.from_service_account_file( filename=os.environ["GOOGLE_APPLICATION_CREDENTIALS"], scopes=["https://www.googleapis.com/auth/cloud-platform"], ) # Create ...
3afcba8e4cb9b71f384110d30f39fa737fc7a6d9
3,645,907
def wrap(wrapping_key_public, plaintext): """ RSA-OAEP key wrapping. Args: wrapping_key_public: The public key of the RSA wrapping key plaintext: The plaintext key to wrap """ rsa_cipher = PKCS1_OAEP.new( key=wrapping_key_public, hashAlgo=SHA256, mgfunc=lambda x, y: pss.MGF1...
171074a46440184138ccb1684754f328afc50efe
3,645,908
from datetime import datetime import os def get_output_filenames(output_path: str): """Returns a dict of output filenames.""" now = datetime.datetime.now() now_string = now.strftime("%Y%m%d_%H%M%S") filenames ={ 'train': os.path.join(output_path, "train_split_"+now_string+".csv"), 'val': os.path.j...
b943544c03009ca470aeb3aac0502baafe50b44f
3,645,909
def compute_horizontal_vessel_purchase_cost(W, D, F_M): """ Return the purchase cost [Cp; in USD] of a horizontal vessel, including thes cost of platforms and ladders. Parameters ---------- W : float Weight [lb]. D : float Diameter [ft]. F_M : float Vessel ma...
22d38ffc38dddb992d2fd7b2c20c3dc1d0ddb53d
3,645,910
def format_dev_sub_dev_id(pciIdPair): """ pciIdPair (int pci device id, int pci sub device id or None) """ if pciIdPair[1] is None: return "(0x%08X, None)" % pciIdPair[0] return "(0x%08X, 0x%08X)" % pciIdPair
fded71eee57f4fac60175bfb015845bf1eba58f7
3,645,911
def mychats(): """ Show Chats where I can write :return: { error: 0, chats: [...Chat] } """ result = { 'error': 0, 'chats': [] } if 'user_id' in session: chats_rows = query_db('SELECT * FROM chats WHERE user1_id = ? OR user2_id = ?', [session['...
4af7cd34fb8649ed10723b258e7a864e3e12edc2
3,645,912
def polynom_prmzt(x, t, order): """ Polynomial (deterministic) parameterization of fast variables (Y). NB: Only valid for system settings of Wilks'2005. Note: In order to observe an improvement in DA performance w higher orders, the EnKF must be reasonably tuned with There is very ...
80d3f9563c5f8a04a65de7d2d22f5d49d35c71fe
3,645,913
import sys def new_binning(xmin, xmax, nbin=25, bin_type='lin', out_type=int, custom_bins=None): """ Define the new binning. Parameters ---------- Returns ------- array the array with the edges of the new binning """ if bin_type == 'lin' and custom_bins is None: binning_ = np.lin...
cb4eacdb4648a968ff9dfcd3571ddfe157799588
3,645,914
def decode(s): """ Deserialize an EDS object from an EDS string. """ lexer = _EDSLexer.lex(s.splitlines()) return _decode_eds(lexer)
3c7eb8ac7e570aeb1297b052e35c804dd27b0f49
3,645,915
import errno import os def pid_exists(pid): """Check whether pid exists in the current process table.""" if pid < 0: return False try: os.kill(pid, 0) except OSError as e: return e.errno == errno.EPERM else: return True
0ebefcc958e629aac6d06e6d79d8aaa1acf7607b
3,645,916
def allowed_file(filename): """ Verifies if file extension is compatible """ return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
75e0047eff0787e33f687e7a9b689ad8661b7501
3,645,917
def clap_convert(txt): """convert string of clap values on medium to actualy number Args: txt (str): claps values Returns: number on claps (int) """ # Medium annotation if txt[-1] == "K": output = int(float(txt[:-1]) * 1000) return output else: return int(txt)
253e0e2be4f37f1994637bbfc80edfc5d72bc4e5
3,645,918
import io def write_phase1_capsummary(inst, isStringIO=True): """ Write out a multiweek summary of capacity, demand, understaffing. :param inst: Model instance :param isStringIO: True (default) to return StringIO object, False to return string :return: capacity summary as StringIO object or a str...
6d6e7d083693b74ea27e7f10cec4899735f32541
3,645,919
def glorot_uniform(shape): """ :param shape: tuple with the shape of the wanted output (filters_amount, depth, height, width) :return: array (it's shape=param shape) with initialized values using 'glorot uniform' initializer """ fan_in, fan_out = _calc_fans(shape) scale = 1. / ((fan_in + fan_out...
0cec12b0342db827286248a722b32852cab2bdad
3,645,920
import platform import os def get_server() -> str: """Generate a server information. :return: server info :rtype: str """ uname = platform.uname() fmt_plat = f"OS: {uname.system} {uname.release} v{uname.version}\n" fmt_plat += f"CPU: {uname.processor} ({os.cpu_count()} threads)\n" fmt...
f37ad21b3d5526878fbc5484072986b77bbeff90
3,645,921
import warnings def second_order_moments(n_components, e2, m1, alpha0): """Second-Order Moments To prevent creating 2nd order moments explicitly, we construct its decomposition with `n_components`. check reference [?] section 5.2 for details. Parameters ---------- n_components: int ...
4b2ac9d43352d856875d86cd1975ec59ac5664c8
3,645,922
import traceback def callback_query_wrapper(func): """Create a session, handle permissions and exceptions for callback queries.""" def wrapper(update, context): user = None if context.user_data.get("ban"): return temp_ban_time = context.user_data.get("temporary-ban-time")...
296930fbc16480689ef6f4a0da5ef385ad9cb2df
3,645,923
def remove_names(df: pd.DataFrame) -> pd.DataFrame: """Convert personal names to numerical values.""" df = df.reset_index() df.drop(columns='Name', inplace=True) return df
9dab1803a153d5effd2e08b6e6ff5df30fee8407
3,645,924
import torch def handle_epoch_metrics(step_metrics, epoch_labels, epoch_predictions): """ Function that handles the metrics per epoch. Inputs: step_metrics - Dictionary containing the results of the steps of an epoch epoch_labels - List of labels from the different steps epoch_pred...
a1d0180095535eec641258dd921c90808aa6858f
3,645,925
def project_disk_sed(bulge_sed, disk_sed): """Project the disk SED onto the space where it is bluer For the majority of observed galaxies, it appears that the difference between the bulge and the disk SEDs is roughly monotonic, making the disk bluer. This projection operator projects colors that a...
5faf8f7d8d0d780f61586f7fae39f4ba04d3752d
3,645,926
import os def load_image_url(image_url, image_size=(256, 256), preserve_aspect_ratio=True): """Loads and preprocesses images from a given url.""" # Cache image file locally. image_path = tf.keras.utils.get_file( os.path.basename(image_url)[-128:], image_url) # Load and convert to float32 numpy...
cad02eaf590431b922159ac3dedbf2d418d29335
3,645,927
def qlog_numpy(q): """ Applies logarithm map to q :param q: (4,) :return: (3,) """ if all(q[1:] == 0): q = np.zeros(3) else: q = np.arccos(q[0]) * q[1:] / np.linalg.norm(q[1:]) return q
82cf0ff2054c02e4cc3dc3a6500b1c8a0e3eb870
3,645,928
def get_ML_features(df: pd.DataFrame, protease: str='trypsin', **kwargs) -> pd.DataFrame: """ Uses the specified score in df to filter psms and to apply the fdr_level threshold. Args: df (pd.DataFrame): psms table of search results from alphapept. protease (str, optional): string specifying...
4ac4202fa5c86b78b1bda1a2b96d5ed4b8552b4f
3,645,929
def revcomp(sequence): """ Find reverse complementary sequence :param sequence: The RNA sequence in string form :return: The reverse complement sequence in string form """ complement = {"A": "U", "U": "A", "C": "G", "G": "C", "N": "N"} revcompseq = "" sequence_list = list(sequence) s...
c66b9ad967e612fa97f18bb2932e7eb4bbee8245
3,645,930
def J(X, mean, r): """K-meansの目的関数(最小化を目指す)""" summation = 0.0 for n in range(len(X)): temp = 0.0 for k in range(K): temp += r[n, k] * np.linalg.norm(X[n] - mean[k]) ** 2 summation += temp return summation
1d2dd241fc30cb5897b0224285c5c7f2f2fec675
3,645,931
def get_all_subs(): """ Temporary function until we work out a better autocomplete for createpost """ # TODO return [x.name for x in Sub.select(Sub.name)]
5a956bc743f765026f86ed5928698f58d4791338
3,645,932
import time def timesince(): """ Get the amount of time since 00:00 on 1 January 1970, the raw date before formatting it. """ return time.time()
7e6944d74172947c4ac990c0fa993524ab865e18
3,645,933
def gencoords_outside(N, d, rad=None, truncmask=False, trunctype='circ'): """ generate coordinates of all points in an NxN..xN grid with d dimensions coords in each dimension are [-N/2, N/2) N should be even""" if not truncmask: _, truncc, _ = gencoords_outside(N, d, rad, True) return ...
0b4f3db165cb495e5d540412cb77bd36e8a42c62
3,645,934
def map_orientation(cur_orientation, cur_count): """ . . . . . x . . . . . x . . . . . x . . . . . x . . . . . x . . . . . x """ right_edge = 34905131040 """ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . x x x ...
5fa5e0c386da56cab336f33e560bf9591814060c
3,645,935
import ctypes def glGetShaderInfoLog( baseOperation, obj ): """Retrieve the shader's error messages as a Python string returns string which is '' if no message """ target = GLsizei() glGetShaderiv(obj, GL_INFO_LOG_LENGTH,target) length = target.value if length > 0: log = ctypes.cr...
0173aa2cbeac8c8b2cb9072d0d56584285af2e0d
3,645,936
def _CheckGrdTranslations(grd_file, grd_lines, wanted_locales): """Check all <file> elements that correspond to an .xtb output file. Args: grd_file: Input .grd file path. grd_lines: List of input .grd lines. wanted_locales: set of wanted Chromium locale names. Returns: List of error message strin...
49b73187cd2ac3c7b9796a8a139d89f9a74c91a3
3,645,937
def choose_diverging_palette(as_cmap=False): """Launch an interactive widget to choose a diverging color palette. This corresponds with the :func:`diverging_palette` function. This kind of palette is good for data that range between interesting low values and interesting high values with a meaningful m...
0c2ffc8710a56e643e6c4ccdd453bd00cc59e6a2
3,645,938
def get_lm_model(args, device, config): """Get language model(based on GPT-2) used for sequence prediction.""" ninp = config["ninp"] nhead = config["nhead"] initrange = config["initrange"] dropout = config["dropout"] vocab_size = config["vocab_size"] nhid = config["nhid"] ndecoder = con...
071f43b9537ca8024f980271c64750e7afae864e
3,645,939
def get_meminfo(): """ Get and format the content of /proc/meminfo """ buf = open('/proc/meminfo').read() buf = ','.join([v.replace(' ', '') for v in buf.split('\n') if v]) return buf
47a0d57d1b8c90b4907fab8e39154b8e4ad5b7ee
3,645,940
def effective_area(true_energy, reco_energy, simu_area): """ Compute the effective area from a list of simulated energy and reconstructed energy Parameters ---------- true_energy: 1d numpy array reco_energy: 1d numpy array simu_area: float - area on which events are simulated Returns ...
b17efa390a1ae14bb8ecb959740bad8c391b1d2e
3,645,941
def execute(queries, arglists, fetchone=False): """Execute multiple queries to the sqlite3 jobtracker database. All queries will be executed as a single transaction. Return the result of the last query, or the ID of the last INSERT, whichever is applicaple. Inputs: queri...
a64e12262150514dbc5e6e7f4c193481ab8162aa
3,645,942
def physical_cpu_mhz(vir_connection): """ Get the CPU frequency in MHz using libvirt. :param vir_connection: A libvirt connection object. :type vir_connection: virConnect :return: The CPU frequency in MHz. :rtype: int """ return vir_connection.getInfo()[3]
f6a404a6d531940fbc762f493e90355e2fc78690
3,645,943
def addstream(bot, input): """Add a stream from the notify list""" if not input.admin: return False if not input.group(2): return stream = input.group(2).lower() if not stream in bot.config.streams: bot.config.set_add('streams', stream) bot.reply("Added {0} to stream list".format(stream)) else: bot.reply("{...
48465633ea58968efca31231eb5e1a47a537c979
3,645,944
def get_author(search): """ Queries google scholar to find an author given a search string. If != 0 results are found it gives an error """ authors = list(scholarly.search_author(search)) if len(authors) > 1: raise ValueError(f'Found >1 authors with search string: {searc}, try...
8fffd75f588194db0707ddd7249823fb73324549
3,645,945
import torch def _named_tensor_generic_operation( tensor: torch.Tensor, tensor_ops_pre: callable = dummy, tensor_ops_post: callable = dummy, name_ops: callable = dummy) -> torch.Tensor: """ generic base function used by others First store the names Args: tensor ...
8a343f2ab2c4aeaebcf64e8fc5e75cb3d8776241
3,645,946
def normalize_address_components(parsed_addr): # type: (MutableMapping[str, str]) -> MutableMapping[str, str] """Normalize parsed sections of address as appropriate. Processes parsed address through subsets of normalization rules. :param parsed_addr: address parsed into ordereddict per usaddress. ...
48730c85ee7930b27260b97a6ad876bcecf1b5cc
3,645,947
def model_inputs(): """ 构造输入 返回:inputs, targets, learning_rate, source_sequence_len, target_sequence_len, max_target_sequence_len,类型为tensor """ inputs = tf.placeholder(tf.int32, [None, None], name="inputs") targets = tf.placeholder(tf.int32, [None, None], name="targets") learning_rate = tf....
e9bc9464c826bc8b6c4ea172af189822359735e4
3,645,948
def is_key_in_store(loc, key): """ A quick check to determine whether the :class:`pandas.HDFStore` has datA for ``key`` :ARGS: loc: :class:`string` of path to :class:`pandas.HDFStore` key: :class:`string` of the ticker to check if currently available :RETURNS: ...
273bd534daa0f70831e77da88808033e4f1683eb
3,645,949
def transform_rows_nonlinear06(data, **kwargs): """ Nonlinear row transformation 06. 12 simulated data sources; Functions: 1.0, 0.5*(x+1)^2, sin(pi*x), sin(2*pi*x), cos(pi*x), cos(2*pi*x), x^5, exp2, log10(x-x.min()), boxcox(2), boxcox(4), boxcox(6). """ sources_transformers = [ 1.0, lam...
dd51c838d9721fe310463fa8a0cdb0505e9c4f0f
3,645,950
def catch_parameter(opt): """Change the captured parameters names""" switch = {'-h': 'help', '-o': 'one_timestamp', '-a': 'activity', '-f': 'file_name', '-i': 'imp', '-l': 'lstm_act', '-d': 'dense_act', '-p': 'optim', '-n': 'norm_method', '-m': 'model_type', '-z': 'n_si...
ad3a25e3786b657947893f96a76e80f17eb3b0f0
3,645,951
from loopy.kernel import LoopKernel from loopy.translation_unit import make_program from loopy import CACHING_ENABLED from loopy.kernel import KernelState from loopy.preprocess import preprocess_program from loopy.type_inference import infer_unknown_types from loopy.schedule import linearize from loopy.check import pre...
2f3e4a9b2dd7ea9994ec7cf1a1112db7abacf8bf
3,645,952
import sys import glob def serial_ports(): """ Lists serial port names :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of the serial ports available on the system """ if sys.platform.startswith('win'): ports = ['COM%s' % (i + ...
3693ed759d596308dc7fd817fd32a6643a3533e8
3,645,953
def get_mgr_pods(mgr_label=constants.MGR_APP_LABEL, namespace=None): """ Fetches info about mgr pods in the cluster Args: mgr_label (str): label associated with mgr pods (default: defaults.MGR_APP_LABEL) namespace (str): Namespace in which ceph cluster lives (default...
8079d291d5e2b996547ecd615fbc00a8c70aa4e9
3,645,954
from typing import Union def normalise_architecture(architecture: Union[str, int]): """Convert any valid architecture alias to either 'x86_64' or 'i686'. Raise an error for invalid input. """ for (true_name, aliases) in architecture_aliases.items(): if architecture in aliases: retu...
a7e99a2e8cc527028b82c7e628bd18f9c63c7f61
3,645,955
def process_m(filename, m, estimator): """Returns the list of file sizes and PSNR values for compression method m. """ filesize, psnr = [], [] for q in range(0, 101, 5): _size, _psnr = process_q(filename, q, m, estimator) filesize.append(_size / 1024) # in kilobyte(s) psnr....
7bf1bbcdf31709393788006d8d5cd1bef3bf5509
3,645,956
def fmt(n): """format number with a space in front if it is single digit""" if n < 10: return " " + str(n) else: return str(n)
976acc22cafd6d6bdb4e251853f49a114b63ec21
3,645,957
def test_registration(): """Test registering a magic and getting a copy of it and de-registering.""" manager.MagicManager.clear_magics() def my_magic(cell=None, line=None): """This is a magic.""" if not cell: cell = 'foo' if not line: line = 'bar' return f'{cell}{line}' my_magic.ma...
899573442f12e6e6544f32dcd472fd495eb9dc3b
3,645,958
def stop(): """Stop cleaning This is using docstrings for specifications. --- definitions: stop: type: object properties: did: type: string siid: type: integer aiid: type: integer code: type: in...
e9d7558f4433e73a92229fbf79628eb48357e12b
3,645,959
import json def save_key(access_key, output_filename=DEFAULT_ACCESS_KEY_FILE): """ saves access key to .yc json file """ with open(output_filename, "w+") as f: f.write(json.dumps(access_key, indent=4)) return output_filename
7f15a469ad9b74a39452d8bde46223ef214300d9
3,645,960
def PutObject(object_id: str): """Add/replace DRS object with a user-supplied ID. Args: object_id: Identifier of DRS object to be created/updated. Returns: Identifier of created/updated DRS object. """ return register_object( data=request.json, object_id=object_id,...
faf0aa633ef149c34f3fe0e80d8fdcc9df68dfec
3,645,961
def get_handler_name(method: str, url_path: str, path_params: dict): """ Возвращает имя необходимого хендлера для рефлексифного вызова метода :param method: Метод :param url_path: URL :param path_params: Параметры :return: """ handler = url_path.replace('/', '_') for key, value in pa...
e8060538a6bf73e6291ecbcbec14f11997a53507
3,645,962
import argparse def parse_args(): """Process input arguments""" parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('genotypes', metavar='G', help="Genotype table") parser.add_argument(...
276aed3028ae4d9614b7afae58ece670b8d2b806
3,645,963
import json def plot_AP(file_path: str): """ 绘制 AP 柱状图 """ with open(file_path, encoding='utf-8') as f: result = json.load(f) AP = [] classes = [] for k, v in result.items(): if k!='mAP': AP.append(v['AP']) classes.append(k) fig, ax = plt.subplots(1, 1...
7d691161d07d5f4a70c2b46b8971f54c93972a7b
3,645,964
def partner_data_ingest_new_files(source, destination): """ :param source : list of files to process: :param destination: destination to copy validated files check s3 path for new file, trigger partner_data_ingest for new files. """ hook = S3SyncHook(aws_conn_id="aws_default", verify=True) ...
49685cac11c12af7aa3e2e9ecc152dc46f1b2c5e
3,645,965
import six def _mofval(value, indent, maxline, line_pos=0, end_space=0): """ Low level function that returns the MOF representation of a non-string value (i.e. a value that cannot not be split into multiple parts, for example a numeric or boolean value). If the MOF representation of the value doe...
964e788a228ac88305fb8d82e7e9b9a4a8cd1a2f
3,645,966
import os def get_ammr_version(folder=None): """Return the AMMR version if possible. The function will walk up a directory tree looking for a ammr_verion.any file to parse. """ folder = folder or os.getcwd() any_version_file = "AMMR.version.any" xml_version_file = "AMMR.version.xml" f...
ccb5380550d9cdaec6c4073e3884ea6052b4f448
3,645,967
def to_vector(texto,model,idf): """ Receives a sentence string along with a word embedding model and returns the vector representation of the sentence""" tokens = normalizer(texto).split() # splits the text by space and returns a list of words vec = np.zeros(300) # creates an empty vector of 300 dimens...
24f811110f9b6d9b0fc8a0f6ffcf2d37e1cd6feb
3,645,968
def evaluate_interval_detection(labels, predictions, event_val, def_val, seq_length, other_vals=[]): """Evaluate interval detection for sequences by calculating tp, fp, and fn. Extends the metric outlined by Kyritsis et al. (2019) in Modeling wrist micromovements to measure in-meal eating behavior from ...
4149eaf357d28236077e9cfac7d7ed8ee113818c
3,645,969
def _div(v): """Pure spatial divergence""" return _div_id(np.vstack((v, [np.zeros_like(v[0])])), l1_ratio=0.)
706a97e4d5930067b6524210738fce5b27f407c5
3,645,970
import aiohttp import logging async def delete_share_handler(request: aiohttp.web.Request) -> aiohttp.web.Response: """Handle unshare-container endpoint query.""" try: await request.app["db_conn"].delete_share( request.match_info["owner"], request.match_info["container"], ...
400888b0b75e8c4c73337b1f3444304b3526f510
3,645,971
def _always_run(*args, **kwargs) -> bool: """ This returns False to indicate that the step is not already completed. """ return False
db31e0ac20ac0eef410fb051928308ce7414f5b6
3,645,972
def generate_urls(search): """Generates a URLS in the correct format that brings to Google Image seearch page""" return [(BASE_URL+quote(word)+GOOGLE_PICTURE_ID) for word in search]
4d7d13cdf15fb3e029f11bb2e3f28920cf7c2f97
3,645,973
def batch_provider(data, batch_size, processor=None, worker_count=1, queue_size=16, report_progress=True): """ Return an object that produces a sequence of batches from input data Input data is split into batches of size :attr:`batch_size` which are processed with function :attr:`processor` Data is split a...
2760e9bc9977f4fcdc07624bf896d6b48ce1276d
3,645,974
import random def simplex(key, log_L_constraint, live_points_U, loglikelihood_from_constrained, prior_transform, sampler_state, replace_id): """ Samples from the prior restricted to the likelihood constraint. This undoes the shrinkage at each step to approxima...
f88038eca201b87fdc8f4b4722357a4eafd0366e
3,645,975
def has_anonymous_link(node, auth): """check if the node is anonymous to the user :param Node node: Node which the user wants to visit :param str link: any view-only link in the current url :return bool anonymous: Whether the node is anonymous to the user or not """ if auth.private_link: ...
c5941bce3f0110dfcd5e9bbb19bae0682c5e731f
3,645,976
def lstm(c_prev, x): """Long Short-Term Memory units as an activation function. This function implements LSTM units with forget gates. Let the previous cell state :math:`c_{\\text{prev}}` and the incoming signal :math:`x`. First, the incoming signal :math:`x` is split into four arrays :math:`a, i,...
795fb92554c04be29a75f770fe0fb88d4224f94a
3,645,977
import torch import time def hals(video, video_factorization, maxiter_hals=30, nnt=False, verbose=False, indent='', device='cuda', **kwargs): """Perform maxiter HALS updates To Temporal & Spatial Components Parameter: video: LowRankVideo ...
a993f9e434c3196110c0569cb124d9edbb794dec
3,645,978
def generate_random_sd(error, seq = None): """ generates random sd with error% error rate If seq is specified, random sd is generated from a substring of it.""" if seq == None: seq1 = randSeq(rand(minLen, maxLen)) else: length = rand(minLen, maxLen) start = rand(0, len(seq) - le...
34694895cd37e5714666c3f9f80ae5a010310d3c
3,645,979
def is_successful(gsm_log): """ Success is defined as having converged to a transition state. """ with open(gsm_log) as f: for line in reversed(f.readlines()): if '-XTS-' in line or '-TS-' in line: return True return False
9bab6837c8e6b818cceb025c5df9aed78074edcf
3,645,980
def indicator(function_array_to_be_indicated, its_domain, barrier): """the indicator influences the function argument, not value. So here it iterates through x-domain and cuts any values of function with an argument less than H""" indicated = [] for index in range(len(its_domain)): if its_domain...
440f423b7b25b0d152bc691acd3d7dea6c785aed
3,645,981
def list_calendars(service): """ Given a google 'service' object, return a list of calendars. Each calendar is represented by a dict, so that it can be stored in the session object and converted to json for cookies. The returned list is sorted to have the primary calendar first, and selected (t...
c84efde3699a2c7b3e88dc0a0c799a0da6b4bebb
3,645,982
def _causes_name_clash(candidate, path_list, allowed_occurences=1): """Determine if candidate leads to a name clash. Args: candidate (tuple): Tuple with parts of a path. path_list (list): List of pathlib.Paths. allowed_occurences (int): How often a name can occur before we call it a cla...
3b874e4ea6d8780483100e464e3325321c82689e
3,645,983
def run_eqm(results: Results, options: Options, state: PromisedObject) -> dict: """Run the eqm jobs.""" # set user-defined valuess results['job_opts_eqm'] = edit_calculator_options( options, ['eqm', 'xtpdft', 'esp2multipole']) cmd_eqm_write = create_promise_command( "xtp_parallel -e eqm...
941d51a0de22dd4d66f5de68fc315bf318d112cf
3,645,984
def is_within_boundary(boundary_right_most_x, boundary_top_most_y, boundary_left_most_x, boundary_bottom_most_y, cursor): """ Checks if cursor is within given boundary :param boundary_right_most_x: :param boundary_top_most_y: :param boundary_left_most_x...
d53106c9d525eb1bb51cfe4c30bc7e143ac6a517
3,645,985
import os def mixrng(numbytes, port='COM4'): """Returns bitwise xor of an inbuilt and hardware CSRNG""" internal = os.urandom(numbytes) external = extrng(numbytes, port) return xorbytes(internal, external)
0b8eaa516c4afeb697474649f13e3e9d6c3f6867
3,645,986
def save_matchmaking_auth_key(auth_key: str) -> bool: """Register a new matchmaking auth key. !This will overwrite the existing matchmaking key for this chain! Args: auth_key: auth_key to add for matchmaking Returns: Boolean if successful """ try: redis.set_sync(MATCHMAKING_K...
5f18614f2b2950a942e7a98773911b7f58aabd74
3,645,987
import requests from bs4 import BeautifulSoup def get_game_page(url): """ Get the HTML for a given URL, where the URL is a game's page in the Xbox Store """ try: response = requests.get(url) except (requests.exceptions.MissingSchema, ConnectionError): return None game_pag...
40d578ce8cda0b5139515e03f8308911169e0442
3,645,988
from typing import List import logging import itertools import asyncio async def generate_spam_round_tx_xdrs(pool, prioritizers: List[Keypair], prioritized_builders, unprioritized_builders, rnd): """Generate transaction XDRs for a single spam round (ledger) according to given builders. Some of the generated ...
7e33455718f6c99ccb9fc1ad6a7c3de47964ec98
3,645,989
import collections from datetime import datetime def json_custom_parser(obj): """ A custom json parser to handle json.dumps calls properly for Decimal and Datetime data types. """ if isinstance(obj, Decimal): return float(obj) elif not isinstance(obj, basestring) and isinstance(obj, co...
fb5d14b4416df4540ed3091dcf229aa7b037003d
3,645,990
import sys def process(arguments: list = None) -> str: """ Run the process Parameters ---------- arguments : list Injectable arguments to execute Returns ------- str The name of the library command to execute """ if not arguments: arguments = [] __...
9216d8db0f806d7d097343f9e0aa906e031414d7
3,645,991
def fs_open(path, flag, mode=default_file_mode): """ Open a file, potentially creating it. Return the new fd's id or else -1 if file can not be opened (or potentially created) """ # Check if file should be created if it doesn't exist O_CREAT = 64 create = flag & 64 # If requested, try to create the fi...
218940a6fc14c47f7a3df6d9a4e1bbc971b6b0b5
3,645,992
def new_user(): """ Create Instance of User class to be used by the module """ user_details = ['Daudi', 'Jesee', '[email protected]', 'password'] user = Users(user_details) return user
4d5b2c4cad858113fceef150143b9688488000f4
3,645,993
import math def normalise_angle(angle: float) -> float: """Normalises the angle in the range (-pi, pi]. args: angle (rad): The angle to normalise. return: angle (rad): The normalised angle. """ while angle > math.pi: angle -= 2 * math.pi while angle <= -math.pi: ...
0a4cfa6e9da58bfdbb6cd4a04e7a742e8c432002
3,645,994
def get_hdf_len(*path): """ Returns the number of rows in an hdf file as an int. """ path = construct_path(*path) with pd.HDFStore(path) as store: numrows = store.get_storer('data').nrows return numrows
ad188b2733612e7ed1950a2df0ef5164f9cda021
3,645,995
def matmul(A, B, transpose_A=False, transpose_B=False, master='/gpu:0'): """ distributed matrix multiplication. A: DistMat, B: single tensor or a list of tensors. Note: returns a single tensor or a list of tensors, Not a DistMat. """ if isinstance(A, tf.Tensor) or isinstance(A, tf.Variable)...
268068cd73b56ef747142ebc2df839d124d406d5
3,645,996
def celerybeat_started(): """ Returns true/false depending on whether the celerybeat service is started or not """ if is_systemd(): running = 'active' in fabric.api.sudo('systemctl is-active %s' % celerybeat_service_name()) return running return fabtools.service.is_running(celerybea...
b3578b6dbe91b9a16342c53c488fe01fc37275cd
3,645,997
def highest_greedy_score(board, disks): """ Compute the highest possible score that can be obtained by dropping each of the given disks on the given board in a greedy way. - The disks must be dropped in the order in which they appear in the given list of disks. Each dis...
22fc70db81d6051158bdb9bf80a42d81a215dba1
3,645,998
def normalize_and_discard(df: pd.DataFrame) -> pd.DataFrame: """ Normalize numeric values between 0 and 1 and discard records that are out of bounds. """ # ## 2. Discard values out of range of x and y df_cleaned = df[(df.x >= 0) & (df.x <= 120) & (df.y >= 0) & (df.y <= (160 / 3))] print(f'Shape ...
0b1a1e6ed76c72797cf7b3f65058592c6ec95b03
3,645,999