content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from rst2pdf.createpdf import PageCounter as pc import shlex def parseRaw(data, node): """Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): * PageBreak * EvenPageBreak * OddPageBreak * FrameBreak * Spacer width, height * Transition...
5b24c6a47dc56ee4a3ee77ff46391704b940465f
3,610,900
def yolo_loss(args, anchors, num_classes, rescore_confidence=False, print_loss=False): """YOLO localization loss function. Parameters ---------- yolo_output : tensor Final convolutional layer features. true_boxes : tensor Grou...
0c18252cbce632f6997e499bfbae73a625e03ee5
3,610,901
import re def extract_authorization_token(request): """ Get the access token using Authorization Request Header Field method. Or try getting via GET. See: http://tools.ietf.org/html/rfc6750#section-2.1 Return a string. """ auth_header = request.META.get('HTTP_AUTHORIZATION', '') if r...
9776df3ecd59ba3db15664259a6e65114ec61a07
3,610,902
def resnet101(pretrained=False, **kwargs): """Constructs a ResNet-101 model. """ model_args = dict(block=Bottleneck, layers=[3, 4, 23, 3], **kwargs) return _create_resnet('resnet101', pretrained, **model_args)
42da2c20d6b66bc31b5c3a8c0232f19d5726fd4f
3,610,903
def filter_problematic(features, vcf_file="data/problematic_sites_sarsCov2.vcf", callback=None): """ Apply problematic sites annotation from de Maio et al., https://virological.org/t/issues-with-sars-cov-2-sequencing-data/473 which are published and maintained as a VCF-formatted file. :param featur...
e1edd82c6223fc88b1db5e929c6147464fc7051d
3,610,904
import jinja2 def gen_model_header(env: jinja2.environment.Environment, model: onnx.ModelProto) -> str: """ Generates the header of the script for the given `model` :param env: Jinja environment to load the template files :param model: the onnx model for which the header shall be generated :retur...
e12b7ac02d382fcb541d6df94ac2bea722f7ea2c
3,610,905
def abmag(flux): """ takes flux as nanomaggies, gives AB mag """ # don't take the log of 0! if flux <= 0: return 0 return -2.5 * np.log10(flux) + 22.5
e09380c76dbaaba0c37dd5eb42e9d010960b6d68
3,610,906
import os def add_map(new_prot, new_target, map_path, map_type): """Add a Django map obect :param new_prot: the Django protein object :param new_target: the Django target object :param map_path: the path to the map file :param map_type: the two letter code signifyign the type of the map :retu...
1e1a5b9bb26ad62f29dc0a78000adb534762e485
3,610,907
import os def _make_requirements(foldername, virtual_env_obj): """ Function that build the 'requirements.txt' file used to create a virtual environment by the PIPENV, based on :virtual_env_obj: object. """ requirements_filename = os.path.join(foldername, 'requirements.txt') with open(r...
daa8bb3af7c0a953cf7ce64e13e21259128c2127
3,610,908
def block2(x, filters, kernel_size=3, stride=1, conv_shortcut=False, name=None): """ residual 블록. Parameters ---------- x : [type] 입력 텐서 filters : int bottleneck 레이어의 필터 수. kernel_size : int, optional, default=3 bottleneck 레이어의 커널 크기. stride : int, optional, defa...
1739e6cd9f774bed7c608900c77b1bc983120ac2
3,610,909
import logging def _get_port_v1(port_name, depth=0, selector=None, **kwargs): """ Perform a GET call to retrieve data for a Port table entry :param port_name: Alphanumeric name of the port :param kwargs: keyword s: requests.session object with loaded cookie jar keyword url: URL in mai...
e6db99eda520016dd4b67f620a99a6970633eadc
3,610,910
import random def sample_with_replacement(population,len,choose=random.choice): """Sample from a population with replacement Taken from Python Cookbook, 2nd ed, recipe 18.3 """ s = [] for i in xrange(len): s.append(choose(population)) return s
3fe59998c19c501a5eeb26f0cc65e15ff3c1af7e
3,610,911
def power_mod(val, power, m_value): """ Calculate power mod the efficent way """ if power <= 100: return (val ** power) % m_value if power % 2 == 0: return (power_mod(val, power // 2, m_value) ** 2) % m_value return (power_mod(val, power // 2, m_value) * power_mod(val, power ...
59bb407db88e344b33571d74eef75ae0f7baa54e
3,610,912
def stokes_right_circular(): """Stokes vector for right circular polarized light.""" return np.array([1, 0, 0, 1])
65f1b90e9b3799026a8ec4b79543efc1ea6a472c
3,610,913
def hello_http(request): """HTTP Cloud Function. Args: request (flask.Request): The request object. <http://flask.pocoo.org/docs/0.12/api/#flask.Request> Returns: The response text, or any set of values that can be turned into a Response object using `make_response` <...
60353b0d7d54a3f95bb0b8ad1b641aabbc64f03b
3,610,914
def search_objects(params: dict, results: dict, meta: dict): """ Convert Elasticsearch results into the RPC results conforming to the "search_objects" method """ post_processing = _get_post_processing(params) objects = _get_object_data_from_search_results(results, post_processing) ret = { ...
9e0a7eafcd9442fc88994cbf48ce088cb249cb69
3,610,915
def encode_raw(objs): """ Encode a list of raw data and types to binary wire format Useful for analyzing Protobuf messages with unknown schema """ return RawWire().encode(objs)
91680c2a5fbfab11292b58d976602a56d1934d70
3,610,916
def inv_income_weighted_utility(coin_endowments, utilities): """Social welfare, as weighted average utility (weighted by inverse endowment). Args: coin_endowments (ndarray): The array of coin endowments for each of the agents in the simulated economy. utilities (ndarray): The array ...
0cca315fc52b5a90867300d595a0d1c7bf6cf11c
3,610,917
import os def get_full_path(pset, photo): """ Assemble a full path from the photoset and photo titles @param pset: str, photo set name @param photo: str, photo name @return: str, full sanitized path """ return os.path.join(sanitize_filepath(pset), sanitize_filepath(photo))
16fb05dea97315804de5c8763238d447c8ab2c4e
3,610,918
from datetime import datetime def new_post(): """ Display and handle form for creating a new blog post. """ form = PostForm() if form.validate_on_submit(): post = Post(pub_date=datetime.date.today()) post.title = form.title.data post.content = form.content.data post...
d9f54039cce68fc850d0225c43c9593da7d4735d
3,610,919
from typing import List def _inv_shift_rows(s: List[List[bytes]]) -> List[List[bytes]]: """ Performs the inverted shift rows transformation as described in the standard :param s: the state matrix :return: the new state matrix with shifted rows """ s[0][1], s[1][1], s[2][1], s[3][1] = s[3][1], ...
bdb593e912275bfdf387334916123830e081ed50
3,610,920
def create(dtype, key_len=None, val_len=None): """ Input : Example input dtype=i32:i32 will create an i32_i32 instance. """ k_ty, v_type = None, None try: splitted_words = dtype.split(':') except AttributeError as e: raise TypeError("dtype must be a string") if len(splitted_words) != 2: raise ValueErr...
a44b78f797030625252da5f48b0ebe0a31b48809
3,610,921
import io def read(*filenames, **kwargs): """ Read specified filenames and return contents """ enc = kwargs.get('enc', 'utf-8') sep = kwargs.get('sep', '\n') buf = [] for filename in filenames: with io.open(filename, encoding=enc) as f: buf.append(f.read()) return sep.join...
9261a976cfdc1775888220001cba52aefb45efb3
3,610,922
def tile_context_feature(feat, max_sequence_size): """ Tile context features to max_sequence_size. Do nothing if sequence feature Parameters ---------- feat: Tensor Feature tensor to be tiled Shape: [batch_size, max_len] or [batch_size, sequence_size, max_len] max_sequence_size:...
c0eb6e12770116773e073f6d6a9f42ba0a67569c
3,610,923
import uuid import os def thread_image_file_path(instance, filename): """Generating a file path for avatar image""" ext = filename.split('.')[-1] filename = f'{uuid.uuid4()}.{ext}' return os.path.join('uploads/thread/', filename)
5cb2f7afecd3e54b8ab0f3bcb47a0c7cf69cc94f
3,610,924
def conv_transpose(num_filters, kernel_size=3, activation='relu', conv_order='conv_first', use_batch_norm=True, name=None, **conv_kwargs): """A composite layer for deconvolution with BatchNormalization.""" assert conv_order in ['conv_first', 'conv_last'] def inner(x): conv_first...
0c08edb87107b7246d3938458b96487f51045cf4
3,610,925
def get_id_character_mapping(data, columns): """Creating a mapping between characters and ids given dataframe. Args: data: dataframe that contains characters that need to be converted to ids column: a column of the dataframe that contains characters that need to be converted to ids columns: ...
904a9dde05c26d2d669d16e466317379acbdeec5
3,610,926
import os import subprocess def ensure_local_services_are_running() -> int: """Ensure all required services (mysql, redis) are running.""" # NOTE: if you have any problems with this, please contact me # @cmyui#0425/cmyuiosu@gmail.com. i'm interested in knowing # how people are using the software so th...
d6e42e46cb219bafc635fdfaadd7cffd30eb26df
3,610,927
def estimate_dimension(X, n_neighbors='auto', neighbors_estimator=None): """Estimate intrinsic dimensionality. Based on "Manifold-Adaptive Dimension Estimation" Farahmand, Szepavari, Audibert ICML 2007. Parameters ---------- X : nd-array, shape (n_samples, n_features) Input data. ...
bdeb2631b22f443378746f0728a8e0062e55b962
3,610,928
def start(subj, body): """ parse Twitter message """ lines = body.splitlines() for index, line in enumerate(lines): if line in SUBJECTS: text = '\n'.join(lines[index + 1:]) return TITLE + line + '\n' + cut_text(text) if DELIMETER in body: return convert_p...
f36cfc5a6b6c1e01abc2d4077a7f6eece94cd04e
3,610,929
import re import os def load_json_files(dirpath): """ Collects process definitions (JSON files) from a local process directory. Parameters ---------- dirpath : str Directory path of the process files (.json) folder. Returns ------- list List of processes decoded as di...
e7cc37a8085373af55f2a7d51e927b52445d1264
3,610,930
import torch def img_collate(imgs): """ Args: imgs: Returns: torch.tensor, (B, 3, H, W) """ w = imgs[0].width h = imgs[0].height tensor = torch.zeros( (len(imgs), 3, h, w), dtype=torch.uint8).contiguous() for i, img in enumerate(imgs): nump_array = np.a...
c6d8cc0434f4db6d70f388b99037448587b2784f
3,610,931
def __args_to_weka_options(args): """ Function that creates list with options (args) in format approperiate for weka. :param args: dictionery with command line input :return: list of command line arguments """ result = [] for k,v in args.items(): if v: result.append(...
1d480ffaf840ae67d805d7845684eef24d3da583
3,610,932
import json def execute( context: cli.CommandContext, verbose: bool = False, as_json: bool = False ) -> Response: """ :return: """ response = context.response settings = environ.package_settings if verbose: data = environ.systems.get_system_data() dat...
fee4e55b52902ccc62339687d298db2d2c635c70
3,610,933
import os def batch_input_file_validator(value): """ All input files should be valid image files. Supported extensions: ['.jpg','.jpeg','.png','.bmp','.webp'] """ for i in value: if not os.path.isfile(value): raise TypeError("Select a valid input file.") return value
2e326ee3022bfe1def13a775c9585669a27eb3cd
3,610,934
import torch def generate_response(tokenizer, model, chat_round, chat_history_ids, question): """ Generate a response to some user input. """ # Encode user input and End-of-String (EOS) token new_input_ids = tokenizer.encode(">> You: "+ question + tokenizer.eos_token, return_tensors='pt') ...
138299247b6b5b46b8999489e44676a6819e3e10
3,610,935
def gamma_closures(expressions, could_not_close=None): """ Try to compute gamma closure for each of expressions. :param expressions: list of moment expressions, where each expression is a product of powers of moments :param could_not_close: a list that will be filled with expressions that c...
f84351a4fd0361b2f7de02707c9e3c13877d0974
3,610,936
def find_by_history(view: kvstore.View, storage: bool, key: bytes, block_number: int) -> (bytes, bytes): """find_by_history""" if storage: bucket = tables.STORAGE_HISTORY_LABEL else: bucket = tables.ACCOUNTS_HISTORY_LABEL index_chunck_key = history_index.index_chunck_key(key, block_numb...
973fe9d02ffaac30d19fbc8df83b2d98f3013dad
3,610,937
def linear_coeff(x, y): """ This function returns the inclination coeffecient and y axis interception coeffecient m and b. ---------- Parameters ---------- x : Output of the split vector function. y : Output of the split vector function. ------- Returns ------- float numb...
d38669165af0752837a32ee0df11a4e56e57abdf
3,610,938
import struct def _package_contents_metadata(origin_label, grouping_label): """Named construct for helping to identify conflicting packaged contents""" return struct( origin = origin_label if origin_label else "<UNKNOWN>", group = grouping_label, )
505776bf36740e91e1eb25470b22527af89309e2
3,610,939
import math def str_to_feet(value="0'-0"): """ Returns string converted into decimal feet. Acceptible formats include: 1. 5'-7" 5'-7 1/2" 5'-7 1/2'' 5'-7 5'-7 1/2 2. 7 3/4 -8 The trailing quotation mark can b...
3d9e17f3a900d4962ab65e5fdac3dcd44fa49399
3,610,940
from typing import Tuple from typing import List def deconstruct_answer( answer_sentence: T5_SENTENCE = '' ) -> Tuple[List[T5_SENTENCE], List[str]]: """Gets individual answer subsentences from the compound answer sentence. Args: answer sentence: a T5 output sentence. Examples: >>> se...
c6aa7402382e71828d2146166b20ab50430416a6
3,610,941
def distance_modulus(distance): """Given a distance in parsecs, returns the value :math:`m - M`, a characteristic value used to convert from apparent magnitude :math:`m` to absolute magnitude, :math:`M`. Uses the formula from Carroll and Ostlie, where :math:`d` is in parsecs .. math:: m - M = 5 \log_{...
4d09231ea999a8ddaabf587cfba219b264da6442
3,610,942
def _serialize_data_asset(asset: DataAsset) -> JSON: """Serialize a DataAsset to JSON.""" return _serialize_asset(asset)
d1ed7dd410e9de0f70ef84ebc2da0f5afe492dea
3,610,943
def behroozi10_model_dictionary(redshift=sim_defaults.default_redshift, **kwargs): """ Dictionary that can be passed to the `~halotools.empirical_models.SubhaloModelFactory` to build a subhalo-based composite model using the stellar-to-halo-mass relation published in Behroozi et al. (2010), `arXiv:1...
c45219b650ca9e69c9a157c6b84023da92f81479
3,610,944
def detects(label=None, frac=None): """list of outlier detection algorithms to select from""" algo = {'isoForest': IsolationForest(contamination=frac, random_state=42), 'MCD': EllipticEnvelope(contamination=frac), 'LOF': LocalOutlierFactor(n_neighbors=20, contamination=frac)} return ...
aa1cad7376b25ede814df9d3f1522666a6364865
3,610,945
def zpadlist(values: list, inputtype: str, minval: int, maxval: int) -> list: """Return a list of zero padded strings and perform input checks. Returns a list of zero padded strings of day numbers from a list of input days. Invalid month numbers (e.g. outside of 1-31) will raise an exception. Para...
bcc06dfb36b93af69d031b44f64dfd3ee7d082c3
3,610,946
def find_backend(txt): """ Determine the needed background based on a text string Parameters ---------- txt : str name to find in the list Returns ------- b : :class:`~beast.physicsmodel.helpers.gridbackends.GridBackend` subclass corresponding backend class """ ...
34de08e646aa1ed78eeaa666fd0926eb5cff9dcc
3,610,947
def _make_gmm(ft_data: pd.DataFrame, n_feature: int, cluster_name: str): """ fit a gaussian model and set subcluster names for each feature. Auxiliary function to process cluster. Parameters ---------- ft_data : DataFrame The mz and rt columns of the cluster DataFrame n_feature : in...
fc2fb4ac47e158bc5c476ced11d3349321e1af3e
3,610,948
def _set_health_check_defaults(health_check): """Sets default values for any missing attributes in HealthCheck. These defaults need to be kept up to date with the production values in health_check.cc Args: health_check: An instance of appinfo.HealthCheck or None. Returns: An instance of appinfo.Hea...
cb6cfb86722912cb10b316c5750a4b09601aec2e
3,610,949
import math def singular_values_plot(syslist, omega=None, plot=True, omega_limits=None, omega_num=None, *args, **kwargs): """Singular value plot for a system Plots a Singular Value plot for the system over a (optional) frequency range. Parameters ---...
26db379b0f7b598d05d345edb6110f4e35485747
3,610,950
from dmriprep.interfaces.bids import BIDSDataGrabber from niworkflows.engine.workflows import LiterateWorkflow as Workflow from niworkflows.interfaces.bids import BIDSInfo from smriprep.workflows.anatomical import init_anat_preproc_wf from ..interfaces import DerivativesDataSink from ..utils.misc import sub_prefix as _...
4188f07bb03a6b4806f0197d5c4ba0020d3d9440
3,610,951
import os def _get_scxdir(scxdir=None): """Retrieve the base secondary directory with error checking. Parameters ---------- scxdir : :class:`str`, optional, defaults to :envvar:`SCND_DIR` Directory containing secondary target files to which to match. If not specified, the directory is...
a2affd580a078582de3af8bf9936e50a61f0f10e
3,610,952
def find_spike_from_templates(recording, waveform_extractor, method='simple', method_kwargs={}, **job_kwargs): """Find spike from a recording from given templates. Parameters ---------- recording: RecordingExtractor The recording extractor object. waveform_extr...
a02e61d9c7ff668e0264cd50d1fe4294394cb58e
3,610,953
import os import json def get_metadata(path): """ Find the json metadata file associated with content at `path` (dir or file). """ metadata_filename = get_metadata_file_path(path) if not os.path.exists(metadata_filename): return {} with open(metadata_filename, 'r') as json_file: ...
ab8f84624dd0e6090fcfa3d98d380a312f886671
3,610,954
def model_outputs() -> str: """ Parses the model outputs in a human readable format. It also gets the boathouses by reach, so the user knows what boathouses are associated with each reach. Returns: Rendering of the model outputs via the `model_outputs.html` template. """ df = latest...
848dba8f8b29c4176bce827c2e5c831c3f534b73
3,610,955
import itertools import copy import logging def check_process(process, evaluator, quick, options): """Check the helas calls for a process by generating the process using all different permutations of the process legs (or, if quick, use a subset of permutations), and check that the matrix element is in...
a4cb209596353ebc873aab0fecc7bbc4de42fa3e
3,610,956
def getFileState(fileName, workDir, jobId, ftype="output"): """ Return the current state of a given file """ # create a temporary file state object FS = FileState(workDir=workDir, jobId=jobId, ftype=ftype) # update this file state = FS.getFileState(fileName) # cleanup del FS return s...
b19f193deb0a2a0268589d1f87f1f0906a778c07
3,610,957
def to_minimal_subject_jobject(subdomain, minimal_subject): """Converts the given MinimalSubject of Subject into an object that can be passed to to_json().""" subject_types = cache.SUBJECT_TYPES[subdomain] attributes = get_attributes_to_render(subject_types) attribute_jobjects, attribute_is = make_j...
8d229cebf859ec26b1f4c879e20bcb7f4d841e96
3,610,958
def left_ascending_super_operator(hamiltonian, isometry, unitary): """ binary mera left ascending super operator Args: hamiltonian (tf.Tensor): hamiltonian isometry (tf.Tensor): isometry of the binary mera unitary (tf.Tensor): disentanlger of the mera Returns: tf.Tensor...
2833b9cad67f3889c1d04a47af33544fca10170d
3,610,959
def TASK_JUMP_FWD(step=1): """Jumps to the next task - eng.jumpCallForward() example: A, B, TASK_JUMP_FWD(2), C, D, ... will produce: A, B, D @var step: int """ def _x(obj, eng): eng.jumpCallForward(step) _x.__name__ = 'TASK_JUMP_FWD' return _x
de2bb5e71d54ea8cfcef61fa3ba687695b00315c
3,610,960
from pathlib import Path import jinja2 from functools import reduce def __save__( script_name: str, benchbuild: BoundCommand, experiment: 'Experiment', projects: tp.Iterable[str] ) -> str: """ Dump a bash script that can be given to SLURM. Args: script_name (str): name of the bash script....
c7f0628fbf293626e42a7c6b1ce288a6b1b0e577
3,610,961
def fib_iterative(n): """Calcualte n-th element of Fibonacci sequence. Assumes n >= 2 Returns: Fibonacci sequence up to element n, and n-th element of the seq. """ fibSeq = [0, 1] # base case for ii in range(2,n): # note: list(range(2,2)) is an empty list [] fibSeq.append(fibSeq[ii-2...
f28c44bc277c8f5e97e507461f3321bc0aa0510e
3,610,962
from typing import Union from pathlib import Path from typing import Iterable from typing import Type from typing import Callable from typing import List from typing import Any def discover_functions( source: Union[Path, str, Module, Iterable[Module], type], signature: Type[Callable] = Callable, # ty...
3169e7979cf6e138e4116e9512f5fd4583acbeee
3,610,963
from sys import path def is_single_file(source_ref_path): """return bool""" return path.isfile(source_ref_path) or uri_validator(source_ref_path)
9dfae30ab5e72c8de87d1adcd213db6a3719c8b3
3,610,964
import re def translate_connstring(connstring): """ Acepta un parámetro "connstring" que tenga la forma user@host/dbname y devuelve todos los parámetros por separado. Tiene en cuenta los valores por defecto y las diferentes formas de abreviar que existen. """ user = "postgres" ...
d74d5a1f22179d8906c8a2e8b568b68b97cc4ba9
3,610,965
def bytescale(im): """ The input should be between [0,1] output is [0,255] in a unsigned byte array """ imout = (im*255).astype('u1') return imout
d3de7ebeb7601235c91d2ea345925ae0e11351ad
3,610,966
import hashlib def gen_md5(src_byte): """ gen md5 :param src_byte: :return: """ m2 = hashlib.md5() m2.update(src_byte.encode("utf-8")) return m2.hexdigest()
3243606076735065c87c28eed473d47c6166b0b0
3,610,967
import json def workout_map_shot(context, request): """ Ask for the screenshot of a map, creating one if it does not exist. A json object is returned, containing the info for the needed screenshot """ if context.map_screenshot is None: save_map_screenshot(context, request) info = {'ur...
efd560ce96545262aa01f774a62a3352caa91f2e
3,610,968
import os def config_read_only(host): """ Determine how read_only should be set in the cnf file Args: host - a hostaddr object Returns: The string value of READ_ONLY_OFF or READ_ONLY_ON. """ zk = MysqlZookeeper() try: (_, replica_type) = zk.get_replica_set_from_instance(host)...
163141531ccefd29166e033094ae236721251f8b
3,610,969
def to_string(opt): """Encodes the option into a string""" entry = opt.entry if not tosave(entry): return False line = '' for key, val in entry.items(): if key in ['kid']: continue val = '{!r}'.format(val) val = val.replace(assign_sym, ...
dffa69ffb4468da9704db04728fcf144fab25c21
3,610,970
from typing import List from typing import Union from typing import Optional from typing import Match import re def search_in_comments( comments: List[Union[str, Comment]], filter_regex: str ) -> Optional[Match[str]]: """ Find match in pull request description or comments. Args: comments: Lis...
488723975d8d91a2796c25bd6bed12e562194c38
3,610,971
import os import logging import time def train(): """Train fasterrcnn dataset.""" config_train = DatasetConfig().to_dict() config_train = config_train['_class_data'].train prefix = "FasterRcnn.mindrecord" mindrecord_dir = config_train.mindrecord_dir mindrecord_file = os.path.join(mindrecord_di...
e8ecbe34249c4b420b2745c3f5074003c3d1c63c
3,610,972
def create_local_adapter_access(mmu_access, adapter_description, adapter): """ Creates a local adapter access. Parameters ------------ mmu_access : MMUAccess The mmu access the adapters are connected to adapter_descriptions : AdapterDescription The adapter description ad...
4151336f814daad1c0357eafd6426357f0638285
3,610,973
def avro_artifacts(version = "1.8.2"): """ version: str = "1.8.2" - the version of avro to fetch """ return [ maven.artifact( group = group_id, artifact = artifact_id, version = version, ) for [group_id, artifact_id] in [AVRO, AVRO_TOOLS] ]
0f5120fc73fa060bd3ea0291e99222fd714a3a32
3,610,974
import keras.backend as K from keras.layers import Input from keras.layers import Conv2D from keras.layers import MaxPooling2D from keras.layers import BatchNormalization from keras.layers import Activation from keras.layers import GlobalAveragePooling2D from keras.layers import ZeroPadding2D from keras.layers import D...
720a61c92d1e873e789e9e73b3b5c8669e4e86a4
3,610,975
import subprocess import re def bed_generate_random_negatives(in_bed, chr_sizes_file, out_bed, incl_bed=False, excl_bed=False, allow_overlaps=False): """ Shuffle given in_bed, generating random negative regio...
bebd8983a7c91289a9b4430fb9b4f97861ed65b0
3,610,976
import re def parse(docs): """Parse __docs__ text into markdown. Will parse directives like `:param name:` etc""" # strip leading tabs if not docs: return "" docs = strip_leading_tabs(docs) if ":param" in docs: out, title_set = [], False for line in docs.splitlines(): if ":param" in line: if not t...
d78f2e1cac80134f65c492b7a48109c745b1ea81
3,610,977
def mergersort(arr): """Sort function.""" def split(arr): if len(arr) <= 1: return lst mid = len(arr) // 2 left = arr[:middle] right = arr[middle:] left = split(left) right = split(right) return merge(left, right) def merge(left, right):...
a592c75d6903c0d82feff4eda21d9136e13fe452
3,610,978
def default_interface(): """ Return just the default interface device dictionary. """ parser = get_parser() return parser.default_interface
b0e8c296e43b00d224db4e243b033957e8b380b2
3,610,979
def ape(y, p): """Absolute Percentage Error (APE). Args: y (float): target p (float): prediction Returns: e (float): APE """ assert np.abs(y) > EPS return np.abs(1 - p / y)
0093cb2474b42a2dddc00577afbcc5b920bf1964
3,610,980
def new_record(score): """Verifie si le score peu entrer dans le top ten""" topten = load_json('topten.json') for index, player in enumerate(topten): if score > player["score"]: return index return None
2ea1ca763d2f60ccc668377f0c694815eb9a1e84
3,610,981
def _mean_of_cycle(data, setup_time=30, data_dict={}): """ Calculates mean of raw and reference signal during a zero cycle setup_time in seconds """ row_selection = (data.zerocycle_runtime >= setup_time) & (data.State_Zero == 1) cycle = data.loc[row_selection].agg( { "times...
789cce42efebfa4b46b19e7be991cb1fa433ddae
3,610,982
def proteinnet_tf_dataset(pn_map, batch_size, prefetch=0, shuffle_buffer=0, repeat=True): """ Initiate a TensorFlow Dataset from a ProteinNetMap. Create a TensorFlow Dataset from a ProteinNetMap, taking the output of the map and adding batching, shuffling and repeating in additio...
c277a591793e9618d3bd8ffc29b21533250ec3a1
3,610,983
import json import requests def post_gist(content, description="", filename="file", auth=False): """Post some text to a Gist, and return the URL.""" post_data = json.dumps( { "description": description, "public": True, "files": {filename: {"content": content}}, ...
eddeada0d9bf04f10bc94e290a0f57912573f95b
3,610,984
import functools def lru_cache(protected: bool = False, maxsize: int = 128, typed: bool = False): """ Wrapped version of the functools.lru_cache decorator which keeps track of all decorated functions to allow clearing all caches. :param protected: if set to True, the cache for this function will only...
2ba9ddc450d78f74d509718d6493c6aa8a5a42a5
3,610,985
def mask2rle(mask): """ Efficient implementation of mask2rle, from @paulorzp img: numpy array, 1 - mask, 0 - background Returns run length as string formated Source: https://www.kaggle.com/xhlulu/efficient-mask2rle """ pixels = mask.T.flatten() pixels = np.pad(pixels, ((1, 1), )) ru...
8b5feabbb73d88e7055be3cc973f6d4f517aa673
3,610,986
def CreateUniformBuffer(program, uniform_type, uniform_name, default_data=None): """ create uniform buffer from .mat(shader) file """ uniform_classes = [ UniformBool, UniformInt, UniformUint, UniformFloat, UniformVector2, UniformVector3, UniformVector4, UniformBoolVector2, UniformBoolVec...
83f5b54ec44a6a8f9100ecb1d4f390d65dea7302
3,610,987
def root(): """Base view.""" over10 = Record.query.filter(Record.value >= 10).all() return str(over10)
040f7d39311c525b8356065e7cad0a4c65deb920
3,610,988
def quadratic_2d(data): """ Compute the quadratic estimate of the centroid in a 2d-array. Args: data (2darray): two dimensional data array Returns center (tuple): centroid estimate on the row and column directions, respectively """ arg_data_max = np.argm...
b064d0f6fe4dd5eef51ffe3514731ee3bb588767
3,610,989
def tr_to_final_ph(stage, tr_to_ph, wind_final_perf, final_ph): """ Computes the number of trials required to reach the final phase. """ time = np.where(stage == final_ph)[0] # find those trials in phase 4 reached = False if len(time) != 0: first_tr = np.min(time) # min trial is first tria...
985ef980475450b62815d5daf200250bcf944798
3,610,990
def get_shannon_entropy(sequence): """Given a sequence, compute the Shannon Entropy, defined in https://ijssst.info/Vol-16/No-4/data/8258a127.pdf Args: sequence (np.array, [t, ]): sequence over which to compute. Returns: float: shannon entropy. """ # Remove zero entries in sequ...
9b7a66ef8c0b0d3a05c58e36f1a038471af60f59
3,610,991
def interpolate_df(x, name, fp): """Interpolate a dataframe :param x: the x-coordinates at which to evaluate the interpolated values :type x: array :param name: the name of the column to use in the dataframe for the x-coordinate :type name: str :param fp: the dataframe containing the y-coordina...
a48231f4557053082658fe67c479bf31ad5b249d
3,610,992
def geocoder_to_place(result): """Convert a result object from geocoder to a Place object""" return Place( name=result.address, country=result.country, country_code=result.country_code, state=result.state, description=result.description + " - " + result.class_description,...
bf0a3d5772dbbdb85c25fdd206b0b8e5c4483bfa
3,610,993
def query_session_job_status(session, status, user=None): """ :type session: Session :type user: User """ session = Session.objects.with_id(session) if not session: return None, HTTPStatus.NOT_FOUND if status not in ['success', 'started', 'dispatched', 'ready', 'failure', 'created']...
3ccc3de65dc834e837c46bea3c6465b8df45c4b6
3,610,994
def replace_string_newline(str_start: str, str_end: str, text: str) -> str: """ re.sub function stops at newline characters, but this function moves past these params: str_start, the start character of the string to be delted str_end, the end character of the string to be deleted te...
c2f4888ed285dc6a48b6a839ff62dbe50865472c
3,610,995
def convert_cell(ase_cell): """ Convert a parallelepiped (forming right hand basis) to lower triangular matrix LAMMPS can accept. This function transposes cell matrix so the bases are column vectors """ cell = ase_cell.T if not is_upper_triangular(cell): tri_mat = np.zeros((3, 3)) ...
e3272d91517979cfb0be1be0a158f359c88c278e
3,610,996
def header_required(response, name, callback=do_nothing): """Checks that a specific header is in a headers dictionary. Args: response (object): An HTTP response object, expected to have a ``headers`` attribute that is a ``Mapping[str, str]``. name (str): The name of a required heade...
6454b2e201114051a85da5e3142030d46ec88130
3,610,997
def test_node_catchup_when_3_not_primary_node_restarted( looper, txnPoolNodeSet, tdir, tconf, allPluginsPath, steward1, stewardWallet): """ Test case: 1. Create pool of 4 nodes 2. Stop not primary node 3. Send some txns 4. Start stopped node 5. Ensure, that restarted node go...
ea3eb0a7ce7ec9dd81c753193a12d572fe03aeb6
3,610,998
def get_model(point_cloud, is_training, num_class, bn_decay=None): """ Semantic segmentation PointNet, input is BxNx3, output Bxnum_class """ if isinstance(num_class, int): num_class = [num_class] batch_size = point_cloud.get_shape()[0].value num_point = point_cloud.get_shape()[1].value end_...
751d27dddab1948a0cba2bf9bcf89ad7a13f4b2e
3,610,999