content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def effective_sample_size(x, mu, var, logger): """ Calculate the effective sample size of sequence generated by MCMC. :param x: :param mu: mean of the variable :param var: variance of the variable :param logger: logg :return: effective sample size of the sequence Make sure that `mu` and ...
0c19c0f9b95da5d837f16bf6e92248db6e839304
79,125
def route(*, db_session: Session = Depends(get_db), route_in: RouteRequest): """ Determine the correct entities to dispatch. """ return {"recommendation": get(db_session=db_session, route_in=route_in)}
b2934dda89249200315464ae73c8c27ecba94aeb
79,126
import torch def change_last_layer_vgg(model): """ Change last layer of a vgg model :param model: torchvision.models.module :return: torchvision.models.module """ # num filters in bottleneck layer num_filters = model.classifier[6].in_features # convert all layers to list and remove the...
3540ddae99e0cb5d2915ec70fa051f2dc7819e27
79,128
def xcorr2(signal, kernel, centered_p=True): """Signal-kernel 2D convolution Convolution of a 2-diemensional signal (the contact map) with a kernel (the pattern template). Parameters ---------- signal: array_like A 2-dimensional numpy array Ms x Ns acting as the detrended Hi-C map. ...
fa653530efad0d27d7721d795c1bbc16e576a8b2
79,129
import unittest def suite(): """A testsuite that has all the sender tests. """ suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(MailTestCase)) suite.addTest(unittest.makeSuite(MessageTestCase)) suite.addTest(unittest.makeSuite(AttachmentTestCase)) suite.addTest(unittest.makeSu...
f3338a7a963b4e9cb00e4d60f9fbd9923c0610ba
79,130
from typing import Union def get_sharpe_ratio( pf_return: Union[float, pd.Series], rf_return: float, std_deviation: Union[float, pd.Series], ) -> Union[float, pd.Series]: """ Calculate Sharpe ratio. """ return (pf_return - rf_return) / std_deviation
e3d6516e021f0596895fbc8189c70bd91e05060f
79,132
import torch import tqdm import math def estimate_entropies(qzCx_samples, qzCx_params, device, n_samples=10000, weights=None): """Computes the term: E_{p(x)} E_{q(z|x)} [-log q(z)] and E_{p(x)} E_{q(z_j|x)} [-log q(z_j)] where marginal q(z) = 1/N sum_n=1^N q(z|x_n). Assumes samples ar...
43e1b8a8b573f182599bb555b229eb1d1494f027
79,133
import ast from typing import List from typing import Tuple def _get_sim117(node: ast.With) -> List[Tuple[int, int, str]]: """ Find multiple with-statements with same scope. With( items=[ withitem( context_expr=Call( func=Name(id...
d58989f2a832481eb6bb53c166478f415df9769b
79,135
def get_snapshot_arn_instance(rds_client, snapshot_identifier): """Function to get the full ARN of a snapshot. Args: rds_client (Client): AWS RDS Client object. snapshot_identifier (str): Snapshot identifier to get full ARN Returns: str: The full ARN of the snapshot_identifier input,...
2693c4eaff9edeadc142957ab0729c4d6d66893d
79,136
from typing import List from typing import Tuple def tabulate(rows: List[Tuple[str, str]]) -> List[str]: """Utility function for printing a two-column table as text with whitespace padding. Args: rows (List[Tuple[str, str]]): Rows of table as tuples of (left cell, right cell) Returns: Ro...
838540161e06544f81bdf4ea78b0973f75949fb3
79,138
def hit(row, column, fleet): """ This method returns a tuple (fleet, ship) where ship is the ship from the fleet that receives a hit by the shot at the square represented by row and column, and fleet is the fleet resulting from this hit. :param row: int :param column: int :param fleet: list ...
673994265cec6e0167b764b25eba1006e16c7257
79,139
def is_meta_field(field_name: str) -> bool: """Return True if the field is considered a meta field in the schema, and False otherwise.""" return field_name in ALL_SUPPORTED_META_FIELDS
075d3d326fdca8ca5ed3f83b36b3b6ed925b2e79
79,141
def expect_FE02_did(cmd, did, value=None, timeout=2, ack=False, said=None, gids=None, gid_type="U16", check_seq=True, **kwargs): """ 测试EIOU时,通过工装接收设备发送的报文,采用7E+FE02+7E形式。 解EIOU工装7E包7E :param cmd: 支持“READ”,"WRITE","REPORT","NO...
81656e071e5b8f6ff1746e85db3847fd1fad1d53
79,142
def pack_list(input_list, pack_size=5000): """ 列表片段打包 :param input_list: 1d list, the whole list :param pack_size: int, the number of a pack :return: 2d list [pack_list, pack_list] """ assert np.array(input_list).ndim == 1 length = len(input_list) k = 0 result = [] while ...
368e6093d905bd6696f42ccc81a2d9140fae32af
79,146
import collections def format_data(data, exclude_labels=[], exclude_properties=[]): """ Format the data into a json response. :param data: Data that you are formatting and returning a json response for. :type data: Iterable of :class:`ruruki.interfaces.IEntity` :param exclude_labels: List...
424b34962d8badd8d7b6dff80b955d057f815edd
79,147
import pickle def load_vocab(load_vocab_model_path): """加载模型""" with open(file=load_vocab_model_path, mode='rb') as fp: return pickle.load(file=fp)
ccbb1313a28c3f54147fbc7bad899ac9774f91af
79,148
def find_link_to_join(model, link_name): """Finds a link in the model to move the contents of the provided link. This is done by first finding the joint that attaches this link to another link in the model.""" for el in model.findall('joint'): # Joining is only possible if the joint is a fixed ...
68600b70e6a6d29cceeae6e365ae4dfeacfd69f2
79,149
import json def generic_exc_handler(exc): # pylint:disable=W0613 """generic_exc_handler :param exc: """ logger.exception('') resp = InternalServerError().get_response() resp.data = json.dumps({ 'message': 'Server error', }) resp.content_type = 'application/json' return re...
89e9ca1dfe1417b0e2f57cb143a3a00b7b0eb271
79,151
def XYZ_to_ProLab( XYZ: ArrayLike, illuminant: ArrayLike = CCS_ILLUMINANTS[ "CIE 1931 2 Degree Standard Observer" ]["D65"], ) -> NDArray: """ Converts from *CIE XYZ* tristimulus values to *ProLab* colourspace. Parameters ---------- XYZ *CIE XYZ* tristimulus values. i...
3d49d7d12e29c79937a4e879f8cad2da4cd42c78
79,153
def is_phrasal(subtree): """True if this treebank subtree is not a terminal or a preterminal node.""" return isinstance(subtree, list) and \ (len(subtree) == 1 or isinstance(subtree[1], list))
c38aa1f092f141b7a14cc14248c19c5c59c7dd45
79,154
from typing import Iterable def _produce_not_impl_error( client_message: lsp_message.LspMessage) -> Iterable[lsp_message.LspMessage]: """If the client_message is a request, responds with not impl error. Produces no response if the client_message is not an LspRequest. Args: client_message: An RPC sent ...
e0c5e70fc25af005d4a29ef6149921098707d87c
79,155
def find_first_min_points(pt, n): """ Usage ----- Return the index of the min-point in the vector pt of size n. Parameters ---------- param pt : len(t1)x1 numpy_array param n : int Returns ------- min_point_index : nbumber of min points x1 numpy_array """ if n =...
eb21df246a15e493a24a2bfb6a4896f027bdc210
79,156
def get_contours(img): """Get array of contours around drug pack. Args: img: Drug original or resized image. Returns: contours: Image contour arrays. """ # Convert color to gray # cvt_color = cv2.cvtColor(img,cv2.COLOR_BGR2Lab) # Get edges # edged = cv2.Canny(cvt_c...
8c8540336ad373fca1ad0c61ae8795781a0fcfa0
79,157
def gram_matrix(A): """ Style Matrix ------------ Argument: A -- matrix of shape (n_C, n_H*n_W) Returns: GA -- Gram matrix of A, of shape (n_C, n_C) """ GM = tf.matmul(A,A,transpose_b=True) return GM
7e34abf70237b593cb7327341c717f912b68908a
79,158
def splitb(g, mg): """ Determines a usable rank based on modest rise in Picard Vector after the low point in the PCV.""" w = decide_width(mg) if w < 2: return mg # splitb needs w>=2 to be reliable # magnify any divergence by squaring gg = np.zeros(mg) for i in range(0, mg): ...
e043d05fe05d7ef858ffe11963908d183d0359f2
79,159
def sync(): """Decorator which can be applied to functions which adds a field 'sync' to them. Recovery tests use this to determine if the servers should be started with the --sync mode flag for backups. """ def decorate(f): def new_f(*args, **kwargs): return f(*args, **kwargs) ...
c197ee4c4bd242e7f050501e2114ae4e0f290f4e
79,160
def _countWeightInBins(sortedData, binBoundaries): """ This method counts the number of data items in the sorted_data Returns an array with the number. ret[0] is the number of data points <= binBoundaries[0], ret[len(binBoundaries)] is the number of points > binBoundaries[len(binBoundaries)-1] @ ...
4c84ccfe6c8055ae52610fa06fd4e4a9c07cf295
79,161
import time from mpi4py import MPI def get_n_workers(pool=None): """Extract how many workers our pool has (mostly for working out how many tasks to pre-dispatch). """ if pool is None: pool = get_pool() try: return pool._max_workers except AttributeError: pass back...
918a26ad3887d67a14cf6a6dedbf11a96c90a031
79,162
def select_lessons_assoc(user_obj, **kwargs): """ Query the database and select UserLessonAssociations, for the given user_obj and attendance_code. """ # Create a base query. base_query = UserLessonAssociation.query.filter(UserLessonAssociation.user == user_obj).join(UserLessonAssociation.lesson...
ee6b0983cb63574fbc46f6bbff7635c222036490
79,163
def __lop__(op): """ binary left operator decorator """ def tmpop(self,right): return self._run_op(self, right, op) return tmpop
5e84a705a2f1901a1545ce75b139ea4cb6342c1a
79,164
def get_instance_name(inst): """Get the name of an instance, or None if it doesn't have one. The name is the value for the metadata tag "Name," if it exists. """ if inst.get('Tags'): for tag in inst['Tags']: if tag['Key'] == 'Name': return tag['Value'] return Non...
1fa24ac813f0245a08585c0a776a9ada27099393
79,165
def filter_ann_and_variants(annotations_w_aa_variants): """ Transforms SUBs and DELs so that they're all of length 1 Removes - substitutions whose alternative sequence is X (aligner error) - variants with NULL start coordinate """ new_annotations_w_aa_variants = [] for gene_name, product...
d1b3a67ea23f33d68ef81ebd9f79ef5b3e422c66
79,166
def pack_as_dict(batches, input_name='spect'): """ Helper function converting mini-batches from (list of ndarray, list of dict) to dict of ndarray. `input_name` gives the key to use for the first ndarray. """ def pack_array(array): if isinstance(array, (list, tuple)): if len(arra...
39666453aafb912838ad66bf653ef6e9002107b5
79,167
def peaks(image, return_numpy=True): """ Detect all peaks from a full SLI measurement. Peaks will not be filtered in any way. To detect only significant peaks, filter the peaks by using the prominence as a threshold. Args: image: Complete SLI measurement image stack as a 2D/3D Numpy array ...
db3edfd3c57e842d81d2850212f104bcc9b34f87
79,169
def post_login(account, password, proxy=None): """ Post tinychat login info. :param account: str tinychat account name. :param password: str tinychat account password. :param proxy: str(ipv4:port) use a proxy for this request :return: dict{'content', 'cookies', 'headers', 'status_code'} or None ...
39ba2ce95f59f1bc777e0fb898210c4e19898ed4
79,170
def detail(request, pk): """ Detailed company view per PK """ if not has_access(request): raise PermissionDenied context = get_base_context(request) context["company"] = get_object_or_404(Company, pk=pk) if request.method == "POST": company_form = CompanyForm(request.POST...
bfc3b8c73dbe0bc00d1ae6664d1ded8cf0060cd7
79,171
import json def get_extracted_hl_features(ofile): """returns the extracted high-level features from json file in dictionary format""" features = {} with open(ofile, 'r') as ef: content = json.load(ef) for f in content['highlevel']: features[f] = content['highlevel'][f]['v...
02ffb2e3881c1293d696e19969cf9246a0835403
79,174
def get_value(config_map, key): """ This does not do truly validate the config value but it at least makes sure it is present and is not an empty string and not just all whitespace """ try: return config_map[key] except: return None
0b5e344de48100882f4d9c6c5d441b75f6900f41
79,175
def x_seconds_after_now(seconds): """ Get the datetime that ``y`` seconds after now. :type seconds: int :param seconds: :rtype: datetime :return: """ return utc_now() + timedelta(seconds=seconds)
72bb2b2bb71b5924ff8b730af40777dbb2e7ab56
79,176
def cec_module_params(): """ Define some CEC module parameters for testing. The scope of the fixture is set to ``'function'`` to allow tests to modify parameters if required without affecting other tests. """ parameters = { 'Name': 'Example Module', 'BIPV': 'Y', 'Date': ...
27da851a8253d4309c8efa9f4c8903820531f872
79,177
async def statistical_ext_source_2(): """ EndPoint to get some statistics - EXT SOURCE 2 """ ext_source_2_data_repaid = df_current_clients_by_target_repaid.groupby("EXT_SOURCE_2").size() ext_source_2_data_repaid = pd.DataFrame(ext_source_2_data_repaid).reset_index() ext_source_2_data_repaid.co...
a3e536c27cb1bc779297b1501805991d8a24bcb2
79,179
import logging def _checkDefaultLogger() -> logging.Logger: """ Check if default logger already exists and raise exception if not. Returns: Logger instance object. """ if _defaultLogger is None: errorMsg = "No default logger instance available." raise Exception(errorMsg) ...
51e01ac6c37d9c27f913ebab558fec84646f4fe3
79,180
from typing import Any async def densenet_upload_weights( file: UploadFile = File(...) ) -> Any: """ Upload densenet weights. """ if ( file.content_type not in ['application/octet-stream'] or file.filename.split('.')[-1] not in ['h5'] ): raise HTTPException( ...
56765627e7e9d11810b51a482870ce0a1bc2311a
79,181
def J2Btu(x): """J -> Btu""" return x*3412./1000./3600.
8136dbb87424e1e7cfabbc98e0b5a33ddbd813a2
79,182
def GradientBooster(param_grid, n_jobs): """Function to optimize the fit with data. Start using: 1. min_samples_split = 0.5%-1% total values 2. min_samples_leaf = 0.1*min_samples_split (or round to 1) 3. max_depth = should be chosen from 5-8 4. max_features = 'sqrt' 5. subsample = 0.8 (common va...
82921bedf7aaf9e674f6377b8d969ba94ca05266
79,183
import torch def fastercnn_loss_focal(class_logits, box_regression, labels, regression_targets): # type: (Tensor, Tensor, List[Tensor], List[Tensor]) -> Tuple[Tensor, Tensor] """ Computes the loss for Faster R-CNN. Args: class_logits (Tensor) box_regression (Tensor) labels (li...
be2462a43f640aa81bec97738ec9cbc7d8b6d87f
79,185
import dis def _instructions_up_to_offset(x, lasti: int) -> list: """Get all instructions up to offset *lasti*. """ instructions = [] for instruction in dis.get_instructions(x): instructions.append(instruction) if instruction.offset == lasti: break return instructions
a38ad93350146fb98e559522d86d3674de0539fd
79,186
def calc_rho(RhoRef,T,S,alpha=2.0E-4, beta=7.4E-4): """----------------------------------------------------------------------------- calc_rho calculates the density profile using a linear equation of state. INPUT: state: xarray dataframe RhoRef : reference density at the same z as T and S slice...
7132858623ec88e7989abb1e383132d269b083b6
79,187
def add_depth_channels(image_array): """Add 2 extra channels to a 1 channel numpy array One channel is a linear sequence from 0 to 1 starting from the top of the image to the bottom The second channel is the product of the input channel and the 'depth' channel Args: image_array (numpy.Array): 2...
0af3100d11dc35a35779381535603d0b7e73bef8
79,188
import msgpack def structure_to_mmtf_string(structure): """Converts a :py:class:`.AtomStructure` to a .mmtf filestring. No compression is currently performed. :param AtomStructure structure: the structure to convert. :rtype: ``bytes``""" chains, ligands, waters, properties, entities = get_struc...
434078f76d74d35300b74613d45fa3aa028bb637
79,189
def db_for_read_write(model, write=True): """ :param model: Django model being queried :param write: Default to True since the DB for writes can also handle reads :return: Django DB alias to use for query """ app_label = model._meta.app_label if app_label == WAREHOUSE_APP: return se...
6b497c4be54da0ac62adf1299defaf5b0a73f719
79,190
import torch def distance2bbox(points, distance, max_shape=None): """Decode distance prediction to bounding box. Args: points (Tensor): Shape (n, 2), [x, y]. distance (Tensor): Distance from the given point to 4 boundaries (left, top, right, bottom). max_shape (tuple): Sha...
fd68eabd7cce196b9e48e794fc981e3d44ae657f
79,191
import pickle def build_RFC(data, file): """ Build random forest classifier """ clf = RandomForestClassifier(random_state=42) train_classifier(clf, data[0], data[2]) pickle.dump(clf, open(file, 'wb')) return clf
7b4976e28a87fe6454517f004de570f914ae904d
79,192
from typing import Iterable from typing import List from typing import Tuple def get_eigenvalues_with_degeneracies(evals: Iterable[float]) -> List[Tuple[float, int]]: """ Given a set of sorted eigenvalues (possibly including degenerate eigenvalues), return a list of (eigenvalue, degeneracy) pairs, with ei...
37b0244b15eda2159f79e4de8da8a86e2b7e6352
79,194
def rsa_jwk_to_pubkey(jwk): """ Only RS256 supported so far :return: """ e = int.from_bytes(base64url_decode(jwk['e']), byteorder='big') n = int.from_bytes(base64url_decode(jwk['n']), byteorder='big') pub_num = RSAPublicNumbers(e, n) return pub_num.public_key(backend=default_backend())
78f9aebbbc80f6e01d1dfe9046c018ad47ca953e
79,195
import requests def address_utxos_asset(self, address: str, asset: str, **kwargs): """ UTXOs of the address. https://docs.blockfrost.io/#tag/Cardano-Addresses/paths/~1addresses~1{address}~1utxos~1{asset}/get :param address: Bech32 address. :type address: str :param asset: Concatenation of th...
9a7f86f14fba26ba11d3972c7ef7e29f05ae3d14
79,197
import time import io def create_placeholder(cache_id, token_id): """ Create a placeholder file for a generated cache_id using a token_id. The metadata on this placeholder file can be used for later validating uploads and checking expirations. If a placeholder has already been created, but no file up...
e39235aa1572314ab8f04d1af735b80f4ff550a2
79,198
def get_municipalities_with_filter(id_state_code=None): # noqa: E501 """get_municipalities_with_filter Get municipalities with filter # noqa: E501 :rtype: List[Municipality] """ if id_state_code is not None: return get_municipalities_by_state(id_state_code) return get_municipalities()
a6d290319bf2b6cd6f3c7f4fa9ac5f64b0b9df57
79,200
import torch def to_tensor(pic, use_half=False): """Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor. See ``ToTensor`` for more details. Args: pic (PIL Image or numpy.ndarray): Image to be converted to tensor. Returns: Tensor: Converted image. """ if not(_is_pil_image(...
2ba0feedbc3d683f2522ea60949b428e85ab49fd
79,201
def _get_first_mstump_profile(start, T_A, T_B, m, excl_zone, M_T, Σ_T): """ Multi-dimensional wrapper to compute the multi-dimensional matrix profile and multi-dimensional matrix profile index for a given window within the times series or sequence that is denote by the `start` index. Essentially, th...
c82f4150f29cba8836a3364f0dfabbc4dd70853d
79,202
def directly_follows(trace): """ Get the directly-follows relations given a list of activities Parameters -------------- trace List activities Returns -------------- rel Directly-follows relations inside the trace """ return set((trace[i], trace[i+1]) for i in r...
1e93d16a3bd002aa29b43309dc0a32360e2046db
79,203
def inf_is_graph_view(*args): """ inf_is_graph_view() -> bool """ return _ida_ida.inf_is_graph_view(*args)
7abb467be1018f3274ecb436a17fec502be30b88
79,204
import time def pre_experiment( board: board_reader.BoardReader, psd_extractor: feature_extraction.PSDFeatureExtractor, band_power_chart, psd_chart: tk_plots.PSDPlot, ) -> float: """ :return: average band power for pre-experiment phase """ print( f"Taking PSD baseline before st...
768b179c323e27802b31debd2b4791c216a03ed3
79,205
def get_datacap_dashboard(): """ 获取钱包列表 :return: """ result = DataCapService.get_datacap_dashboard() return response_json(result)
1255e0e0f3fabbe7396dda47123e48e782da2a0c
79,206
def getLibraryVersion(): """Return a long representing library version""" m = _ft.DWORD() call_ft(_ft.FT_GetLibraryVersion, c.byref(m)) return m.value
f475a922c3687cac6dc62109c00f915b432538e2
79,207
import textwrap def docMakeChunks(optList, width=80): """ Makes doc chunks for option declarations. Takes a list of dictionaries, each of which may have one or more of the keys 'long', 'short', 'doc', 'default', 'optType'. Returns a list of strings. The strings may be multiple lines, all...
d89d038668bd69bdd9cbc3c842840aac884475f2
79,208
def encodetextlist(arr): """arrを\n区切りの文字列にする。""" return encodewrap("\n".join(arr))
fcd6dfe5d518ceabbcff16e9eb9b9ca314e489c1
79,209
def app_uninstall(app, request): """ Uninstalls the application. Parameters ---------- app: application name request: the global request object Returns ------- `True` on success, `False` on failure """ try: # Hey App, this is your end... path...
993ff980f03a52edf73e696ff53e2f9f4a070aaf
79,210
def get_gsub_ligature_lookup(font): """If the font does not have a GSUB table, create one with a ligature substitution lookup. If it does, ensure the first lookup is a properly initialized ligature substitution lookup. Return the lookup.""" # The template might include more lookups after lookup 0, if it has ...
10197f392017ca2bdd3d235ec0755eaeb63b5c12
79,211
import tqdm def filter_by_language(data, column='text', lan='en'): """ Keeps rows of the given DataFrame(data) that have the given column value written in the given language. Args: data: pandas DataFrame column: lan: Returns: pd DataFrame with rows containing texts in the...
d1388452ede7c3bed107c1156da2a9db01725ebb
79,212
from typing import List from typing import cast def compute_yaw_rate_from_states( agent_states_horizon: List[List[StateSE2]], time_stamps: List[TimePoint] ) -> npt.NDArray[np.float32]: """ Computes the yaw rate of all agents over the trajectory from heading :param agent_states_horizon: agent trajector...
ed2c94cf044ca32b30e589ff5536a7b2308612a2
79,214
def _find_lt(a, x): """ Find rightmost value less than x""" i = bisect_left(a, x) if i: return int(i - 1) print('in _find_lt,{}'.format(a)) raise ValueError
203e66c470d5d50aacca9dff5159d52fc0dcfae5
79,215
def lj_v(positions_1,positions_2,sigma,epsilon): """ Calculate the Lennard-Jones interaction energy between two particles, given their positions and definitions for their equilbrium interaction distance (sigma) and strength (epsilon). :param positions_1: Positions for the first particle ...
ebb4ab97b6e1e4a257d89e9356bd1b2b99ddf746
79,216
def minical_data_old(fe, pms, diag=False): """ Obtains power meter readings for a mini-calibration @type fe : FE (front end) instance @param fe : receiver to be calibrated @type pms : list of pms instances @param pms : power meters taking the readings @type diag : bool @param diag : output diagnostic...
37a262ae80f8ac9881fea5a5775b1770b9f94687
79,217
def function_key_generator(namespace, fn, to_str=compat.string_type): """Return a function that generates a string key, based on a given function as well as arguments to the returned function itself. This is used by :meth:`.CacheRegion.cache_on_arguments` to generate a cache key from a decorated fu...
8d83648ea2bcf7c3f120683d623ec5aabea64878
79,219
import time def wait(sentry, timeout=900): """Waits for all units to be active/idle.""" def check_status(): status = sentry.get_status() for service_name in sentry.service_names: service = status.get(service_name, {}) for unit_name, unit in service.items(): ...
a0072f863f5afbde2c0b3b749974fa38f2cf5c55
79,220
def get_input_fn(dataset_split, batch_size, capacity=10000, min_after_dequeue=3000): """Input function over MNIST data.""" def _input_fn(): """Prepare features and labels.""" images_batch, labels_batch = tf.train.shuffle_batch( tensors=[dataset_spl...
8a8ff74aba089cc06e46b04911da08697bdff9f4
79,221
def coin_piles(t: tuple) -> str: """ [Medium] https://cses.fi/problemset/task/1754 [Solution] https://cses.fi/paste/61697edb44edc7a922cce0/ You have two coin piles containing a and b coins. On each move, you can either remove one coin from the left pile and two coins from the right pile, or t...
5bb8ee989377807bfea48d0685e1ffa66bc58a4b
79,222
def bit_mat_det(a): """return the determinant of bit Matrix a.""" try: bit_mat_inverse(a) return 1 except ZeroDivisionError: return 0
0ce44e87051f6ceb9b8ab0158dc1f0ca122d715f
79,223
def FocalMechanism_Meta(): """FocalMechanism_Meta() -> MetaObject""" return _DataModel.FocalMechanism_Meta()
fbf00cef31edaa5ed4c10407ef3ee3e698b56857
79,224
def find_tag_path(xml, tags): """Find a unique xml object with a list of tags.""" assert(type(tags) is not str) assert(len(tags) > 0) if (xml.tag == tags[0]): tags.pop(0) matches = list(gen_by_tag_path(xml, tags)) if len(matches) == 0: raise errors.MissingXMLError(f"Object does ...
b90bf1e6ca3e8ea21379ef6017d0f6f09d369337
79,225
def get_version(): """ Return the runtime version as a tuple of (major, minor) """ return runtime.get_version()
5da7f18a7c37fb7035910fc78c1dda217a919f76
79,226
def get_share_in_repo_list(username, org_id): """List share in repos. """ if org_id: repo_list = seafile_api.get_org_share_in_repo_list(org_id, username, -1, -1) else: repo_list = seafile_api.get_share_in_repo_list(username, -1, ...
dec8aa885d69d02c4384581571770bd3ddc6979d
79,227
def _get_num_steps(trajectory: gsd.hoomd.HOOMDTrajectory) -> int: """Find the number of steps in a Hoomd trajectory handling errors. There are cases where it makes sense to run an analysis on the trajectory of a simulation which is not yet finished, which has the potential to have errors reading the fi...
45da9138dcc7713c8825dc522ba8e9674fb67abc
79,228
def test_in_df_out_df_dict(): """Test a function with input and output data set, but as dictionary not DataFrame""" def func(in_df: DataFrame): return {"out_df": in_df} name = "test_in_df_out_df_dict" sqlpy.drop_sproc(name) output_params = {"out_df": DataFrame} sqlpy.create_sproc_from...
9788fa3d3403f987a2dd300d3673e2165f1fd611
79,229
def env(belt_ts, samplerate, out_samplerate, window=10, lags=(0,)): """Calculate respiratory pattern variability across a sliding window. Parameters ---------- belt_ts : (X,) :obj:`numpy.ndarray` A 1D array with the respiratory belt time series. samplerate : :obj:`float` Sampling ra...
c32bbbc254e29bdbf22d99c580df0aad1d827fdc
79,230
def nullsink(stream: Stream, *args, **kwargs) -> FilterableStream: """https://ffmpeg.org/ffmpeg-filters.html#nullsink""" return filter(stream, nullsink.__name__, *args, **kwargs)
8e91ea1a3bd6f6d8c152109522e7bc44661aa7aa
79,231
import tempfile import ctypes def delta(f, s, d=None): """ Create a delta for the file `f` using the signature read from `s`. The delta will be written to `d`. If `d` is omitted, a temporary file will be used. This function returns the delta file `d`. All parameters must be file-like objects. ...
586cb251033a4f18535e3388451c3b6f8dc43552
79,232
def l1_divergence(a, b): """ The L1 di, a continuous valued norm between two arrays of the same shape. """ return np.sum(np.abs(a - b))
3e51579495ae15d9defa76ab14bda07a4f6611a8
79,234
def get_manual_glyphs(glyphs): """ From the glyph list, extract the Gamera ImageList of manual glyphs. """ # Prepare the training glyphs training_glyphs = [] for glyph in glyphs: if glyph['id_state_manual']: # Get the gamera image gamera_image = convert_to_gamera_...
7f3327cafccc12945f684fc4db3cce467bc08048
79,235
import zipfile def is_apk_file(filepath): """ Function to check if a file is an APK Params: - filepath (str): Path where is the file to check Return: True (bool) if the file is an APK False (bool) otherwise """ try: zip = zipfile.ZipFile(...
b859fa83539ce7ae455cfdbd52d42c89ab77c17d
79,237
def best_prefix(bytes, system=NIST): """Return a bitmath instance representing the best human-readable representation of the number of bytes given by ``bytes``. In addition to a numeric type, the ``bytes`` parameter may also be a bitmath type. Optionally select a preferred unit system by specifying the ``system`` ...
8ad91a538bf0aab21c61be7147f94687cd207077
79,238
def signal_to_noise(fname, col=1, method='var', fname_cov=''): """Return signal to noise ratio for WL measurements in file fname. Parameters ---------- fname: string Input file name col: integer Column number for signal, default=1 method: string Noise method, 'var' (defa...
f86111248e368f4d0e4ba92e5184c0d433154820
79,239
def _app_oso(): """Get the flask oso plugin for the current app instance.""" try: return _app_context().oso_flask_oso except AttributeError: raise OsoError( "No oso instance on current application. " "Did you forget to call init_app?" )
d48df0d973852ee2548080695ad716fff0fc11b7
79,240
def findClosestElements(arr, k, x): """ :type arr: List[int] :type k: int :type x: int :rtype: List[int] """ lo, hi = 0, len(arr)-k while lo < hi: mid = (lo + hi)//2 if x-arr[mid] > arr[mid+k]-x: lo = mid + 1 else: hi = mid return arr[l...
066a40467b293a57852f0bbbce9415dc387e414e
79,241
import re import torch def david_generate_single_program(question, program_generator, vocab, question_len=46): """ Generate a single program from a given natural-language question using the provided model. Parameters ---------- question : str The question to produce a program from. p...
67125f701a513b20a671a182084548696eb490e0
79,242
def scrubbing(time_series, FD, thres=0.2): """ simple scrubbing strategy based on timepoint removal """ scrubbed_time_series = time_series.T[:, (FD < thres)] return scrubbed_time_series.T
beacdde75494ad8e4a346657a18ca48bf5990996
79,243
from typing import cast def get_all_actors(use_selection=False, actor_class=None, actor_tag=None, world=None): """ # use_selection: bool : True if you want to get only the selected actors # actor_class: class unreal.Actor : The class used to filter the actors. Can be None if you do not want to use this fi...
4300280086f7837a55b172c6fa9040fc7235e1d8
79,244
def idrs(A, b, x0=None, tol=1e-5, s=4, maxiter=None, M=None, callback=None): """ Use Induced Dimension Reduction method [IDR(s)] to solve A x = b Parameters ---------- A : {sparse matrix, dense matrix, LinearOperator} The real or complex N-by-N matrix of the linear system. b : ...
0a0641d85bed334b3654f2a222551247e02bd865
79,245
def create_instructions_writer(entity, iso_request, rack_containers, parent=None): """ Factory method returning the :class:`_InstructionsWriter` for the passed entity. :param entity: The ISO or the ISO job for which to generate the summary. :type entity: :class:`LabIs...
73e5c5f20caadfad0b8c3a5b6fc65475b776f07b
79,246