content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def create_covg_table(fname, table_data): """Add average CpG depth table to document.""" samps = sorted( list(constants.SAMPLE_NAMES.keys()), key=lambda d: constants.INTERLEAVE_ORDER[d], reverse=False ) data = format_covg_data(table_data) with open(fname, 'a') as f: ...
489559cd80fa8b2c731e9d49a26d693f345b92d9
69,128
def perform_plot(strain1, strain2, txtome): """ Plot the STP between two strains. Params: ------- strain1, strain2: str Strains to plot txtome: txtome A transcriptome object that contains the data to plot. Output: ------- ...
90278169196d3ffadfa8aa2b837587c243612626
69,129
def _cosine_similarity(x, y, eps): """cosine similarity between two tensors""" dotxy = jnp.sum(x * y, axis=1) normx = jnp.linalg.norm(x, axis=1) normy = jnp.linalg.norm(y, axis=1) return jnp.abs(dotxy) / jnp.maximum(eps, normx * normy)
12b93561df009c8320daaed42aff409ca646acd5
69,130
def build_df_per_id(trajectories): """Build one dataframe per id Arguments: trajectories: Dict mapping each id to a list of tuple (x,y,frame) Returns: df_per_id: dict mapping each id to a dataframe with its trajectory Raises: """ df_per_id = {} full_trajectories = add_nan_tra...
c27534b6a8b6b8e7a81015bc42cbc0279346f820
69,133
def int64_feature(values): """Returns a TF-Feature of int64s. Args: values: A scalar or list of values. Returns: A TF-Feature. """ if not isinstance(values, (tuple, list)): values = [values] return tf.train.Feature(int64_list=tf.train.Int64List(value=values))
01378bf614f3d289f2511c755f505bbaa8a99f1c
69,134
def mul(mean1, var1, mean2, var2): """ Multiply Gaussian (mean1, var1) with (mean2, var2) and return the results as a tuple (mean, var). Strictly speaking the product of two Gaussian PDFs is a Gaussian function, not Gaussian PDF. It is, however, proportional to a Gaussian PDF, so it is safe to ...
71844426a2b9f1d7466d85d8c6c1d2037626c7f5
69,135
def load_item(item_id: int): """ Load an item from item_template, convert it to a object of Class Item and return it """ if item_id <= 0 or not isinstance(item_id, int): raise Exception("There is no such item with an ID that's 0 or negative!") item_template_info: ItemTemplateSchema = sessio...
0d31e007cf3bfed7f98c480bdef778350e461087
69,136
def revokeCloseBankAccount(request): """ 정액제 해지신청을 취소합니다. """ try: # 팝빌회원 사업자번호 CorpNum = settings.testCorpNum # 팝빌회원 아이디 UserID = settings.testUserID # [필수] 기관코드 # 산업은행-0002 / 기업은행-0003 / 국민은행-0004 /수협은행-0007 / 농협은행-0011 / 우리은행-0020 # SC은행-0023 ...
fb7cbdf564a3705776a9d81dc4b39a5ff2a8619e
69,137
def download_post(client: Instaloader, post: Post) -> bool: """ Downloads content and returns True """ client.download_post(post, post.owner_username) return True
a3bfc7dd6344e2d31266ee2f113f245984c0dd5d
69,138
def json_dumper(obj): """ Dumps generic objects to JSON. Useful to serialize ENV_CONFIG. """ # extra hacky, but works try: return obj.toJSON() except: try: return obj.__dict__ except: return str(obj)
31d7ddcebb16bf437a18aa5584383f7ca5c83aed
69,139
from typing import Counter def apply_rules( candidates: "list[Commit]", advisory_record: AdvisoryRecord, active_rules=["ALL"], ) -> "list[Commit]": """ This applies a set of hand-crafted rules and returns a dict in the following form: commits_ruled[candidate] = ["explanation"] where 'exp...
2b11cbda939bfeab4b904b20c7d830f0e0f0d949
69,140
def get_paired_bams(align_bams, items): """Split aligned bams into tumor / normal pairs if this is a paired analysis. Allows cases with only tumor BAMs to handle callers that can work without normal BAMs or with normal VCF panels. """ tumor_bam, tumor_name, normal_bam, normal_name, normal_panel, tum...
434d6c951d3e29d02d1bb1b0b594f7002e465775
69,141
def macroexpand(tree, module_name): """Expand the toplevel macros for the `tree`. Load the macros from the given `module_name`, then expand the (top-level) macros in `tree` until it stops changing. """ load_macros(module_name) old = None while old != tree: old = tree tree =...
e9954ddb5df6298532bdfd2861d20d43e24a4bbc
69,142
def create_dimensions(): """ This Function that will create all the dimensions for stroopwafel, a dimension is basically one of the variables you want to sample Invoke the Dimension class to create objects for each variable. Look at the Dimension class definition in classes.py for more. It takes the nam...
b7ad49793b1251489c8c066f8bc1b316343411b5
69,144
from typing import Tuple from typing import Optional def parse_trailing_comment(line: str) -> Tuple[str, Optional[str]]: """Split the line and return the extracted trailing comment.""" chunks = REGEX_QUOTE.split(line) result = "" while chunks: text, *comment = REGEX_COMMENT.split(chunks.pop(0...
339cc320d9242bcc2e0a0d929d51083059570716
69,145
from typing import List import re def get_dic(data)->List[float]: """ """ new_data = [0,0,0,0] for key, item in data.items(): if re.match(r"\b(elevation)\b", str(key), re.IGNORECASE): new_data[0] = item.value elif re.match(r"\b(thickness)\b", str(key), re.IGNORECASE): ...
8d8adab78e739e364b7726f78a49403f5c9ae34a
69,146
def make_header(in_files,args): """Make sam header given input file species and""" #parse input barcode file and make list of individuals in_files['header'] = 'location of header' return in_files
8a4a222391a462d0d6187080ed2eccc631526513
69,147
def accuracy(actual_y: list, predicted_y: list) -> float: """ Calculate the value of accuracy based-on predictions :param actual_y:a list containing initial Y values generated by 'y_generator' function :param predicted_y: a list containing predicted Y values generated by 'predict_y_value...
7082d0e5505fc58e9ba80883b63bec98f4632676
69,148
def send_messages(queue, messages): """ Send a batch of messages in a single request to an SQS queue. This request may return overall success even when some messages were not sent. The caller must inspect the Successful and Failed lists in the response and resend any failed messages. Usage is s...
806bd30fb5efc9fef226ddb6c2d46ffe33402cbb
69,149
def get_graph(network_data, vocab): """ Build graph, treat all nodes as the same type Parameters ---------- network_data: a dict keys describing the edge types, values representing edges vocab: a dict mapping node IDs to node indices Output ------ DGLHeteroGraph ...
b3bb88a8d7d3b3d102a38fec41bb57d3e9d45e73
69,150
def dict2columns(data, id_col=None): """Convert a dict-based object to two-column output. Also make sure the id field is at top. """ if not data: return ({}, {}) else: if id_col is not None and id_col in data: keys = [id_col] [keys.append(key) for key in sort...
24917339d53febc4239e21ebb8b39e487f45a370
69,151
def insertTimer (signal, type): """ - param signal a plugged input signal. - return an Timer entity. """ assert signal.isPlugged() Timer = getTimerType (type) timer = Timer ("timer_of_" + signal.name) other = signal.getPlugged() plug(other, timer.sin) plug(timer.sout, signal) ...
3f1671647ac7842fd32e0b1b107069371f4e4cdd
69,152
def resolve_int_list_arg(arg): """Resolve a CLI argument as a list of integers""" if arg is None: return None if isinstance(arg, int): return [arg] if isinstance(arg, str): return [int(arg)] if isinstance(arg, tuple): # Interpret as range (ignore any other items in tu...
5201d191946c69e10253e476341ab70c76b3a67d
69,153
def divide_by_two(a): """Return a / 2. """ return a / 2.0
f7c71a468f91892d327d7e9745934f6f4760deeb
69,155
import csv def read_ensembl_genes(fpath, source, name): """ :param fpath: :param source: content of ensemblSource file; contains transcript type info, e.g., protein coding :param name: content of ensemblToGeneName file; contains gene symbol/name info :return: """ fieldnames = ['bin', 'name...
820bbb02dec86da382137ad7eddb52ee596a02a6
69,156
def SystemYChanged(): """(read-only) Flag that indicates if elements of the System Y have been changed by recent activity.""" return lib.Solution_Get_SystemYChanged() != 0
04195262f03ef6df39caf4f56c95fb117f0e279f
69,157
def groupwise_normalise(gs): """ Normalises each group of GeoSeries :param gs: GeoSeries :return: normalised GeoSeries """ return gs.groupby(level=0).apply(lambda x: x / x.sum())
e0c87701658481ccea01828c75244b7a1043ee29
69,158
def dnn_batch_normalization_train(inputs, gamma, beta, mode='per-activation', epsilon=1e-4, running_average_factor=0.1, running_mean=None, running_var=None): """ Performs batch normalization of the given inputs, using the mean and variance ...
853f5a2c130ff4aa6b319b40a456817d982a2332
69,159
from typing import Dict def component_io_to_rest_obj(io_dict: Dict): """Component inputs/outputs entity to rest object.""" rest_component_io = {} for name, port in io_dict.items(): rest_component_io[name] = port._to_rest_object() return rest_component_io
03c3b5fc0033c3488a1190db89e8361483fc765d
69,161
def delta(net: ann.NeuralNetwork, sample: Sample, error_function_deriv: List[Mapping[Tuple(Sample, ann.NeuralNetwork ), float] ...
3f8b411750f7b3266eaaef814e21eaba36cf68ec
69,162
def PolynomialJac(mu, *u): """The derivative matrix of the polynomial model.""" jac = -np.array([(1 - mu) ** (l + 1) for l in range(len(u))]).transpose() return jac
495dd55004b8014ef7ee2499ba79188eaee48707
69,163
import struct def b58decode(v, length=None): """ decode v into a string of len bytes.""" if isinstance(v, bytes): v = v.decode() for c in v: if c not in __b58chars: raise ValueError("invalid Base58 string") long_value = 0 for (i, c) in enumerate(v[::-1]): long...
496b70440346b4545371b9293ff50e7c1e05300d
69,164
def transformRemoveXmlTagsC14NId(): """ The 'remove xml tags' transform id (used before base64 transforms) (http://www.w3.org/TR/xmldsig-core/sec-Base-64). Returns : 'remove xml tags' transform id. """ return TransformId(_obj=xmlsecmod.transformRemoveXmlTagsC14NId())
856dd18d4e04e3b9e94d911a02f564b3561dccf1
69,165
def correlation(season, metric, n, connection, generalize=False, traditional=False, mixed=False, playoffs=False, multiple=False, partitioned=False, evaluation_start=None, evaluation_end=None): """ Calculate the correlation coefficients (Pearson/Spearman) for a specific numbe...
ca31974b6ec8e78b300afe0bf58931b358b01f18
69,166
def generate_wrapper(config): """ Generates a wrapper script for the format. :param config: The configuration for the format """ return "#!/bin/sh\n%s" % config['interpreter']
694ecb3369de8ab4af4c57418c732d39ed57aceb
69,168
import itertools def string_between(left, right, subject, *args, **kwargs): """ string_between(left, right, subject, [,start [,end]] [,greedy=False] [,inclusive=False] [,repl=None] [,retn_all_on_fail=False] [,retn_class=False] [,rightmost=False]) -> str Return the substring sub delineated by being betwe...
8f80f15b27fe8dfde0afcbb6aa85d55250fd13ae
69,169
def logout(request): """ Return logout page """ django_logout(request) print("Logging out") return redirect('/')
923ded3599a435d9a782afdbf43d66f4b4b44a02
69,170
def tgram_to_bundles(tgram, bundle_dict, reference): """ Convert a StatefulTractogram object to a dict with StatefulTractogram objects for each bundle. Parameters ---------- tgram : StatefulTractogram class instance. Requires a data_per_streamline['bundle'][bundle_name]['uid'] attribute...
9d9595a90a6103641e2acfe551c8d95f001bf5d6
69,171
def params_to_dict(params): """ Converts the parameters of a mwparserfromhell template to a dictionary """ dct = {} for param in params: dct[param.name.strip()] = param.value.strip() return dct
0799a22627b1f09e684d2b506f69eabcc942ec2f
69,172
import fastapi async def delete_feed( *, db: sa.orm.Session = params.Depends(deps.get_db), id: int, ): """ Delete RSS feed. """ obj = crud.rss_feed.get(db, id=id) if obj is None: raise fastapi.HTTPException(404, detail="RSS Feed not found") return crud.rss_feed.remove(db, i...
b893b3d48db0476e1ac2f8c0c04a7705027cf2e2
69,173
def filter_definition_names(names, origin, position=None): """ Filter names that are actual definitions in a scope. Names that are just used will be ignored. """ # Just calculate the scope from the first stmt = names[0].get_definition() scope = stmt.get_parent_scope() if not (isinstance...
14ef64d3df898e1b64890c54252d64079e2b478e
69,174
def new_deconstruct(self): """Patches makemigration's logic to ignore fields that are not of relevance to our database. This avoids unnecessary, annoying migrations whenever a frontend facing string is changed.""" name, path, args, kwargs = original_deconstruct(self) for attr in IGNORED_ATTRS: ...
71965fe02b032f31574f42787c8a5f6398540945
69,175
def render_network_key(ssid, address): """ssid:address""" return ssid + ':' + address
daf47616c455c3b542688293195f45607fb8b7ea
69,176
from typing import Callable def percentage_income_contributions( income: float, contribution_rate: float, income_growth: float = 0.0, tax_function: Callable[[float], float] = (lambda x: 0), ) -> Callable[[int], float]: """ Creates a function that returns a contribution based on a percentage of...
a122d7d4afa95f3be799e0913ddd127e761fe6ca
69,177
import math def scattering_filter_factory(N, J_support, J_scattering, Q, T, r_psi=math.sqrt(0.5), criterion_amplitude=1e-3, normalize='l1', max_subsampling=None, sigma0=0.1, alpha=4., P_max=5, eps=1e-7, **kwargs): """ Bu...
cbf0c3533037822f24a42c2e27f31263e94dfe72
69,178
def get_response(zone_key, url, session=None): """Get response""" ses = session or Session() response = ses.get(url) if response.status_code != 200: raise ParserException(zone_key, 'Response code: {0}'.format(response.status_code)) return response
d44b2f9e78e37acd0ed17b0864e8f989e57d0171
69,180
def make_one_shot_iterator(dataset): """Returns a dataset's one-shot iterator.""" try: return v1.data.make_one_shot_iterator(dataset) except AttributeError: return dataset.make_one_shot_iterator()
b1d55a21af7f031a2f4f09b4fcdca38167dd0add
69,181
def checkPossibility(nums): """ :param nums: :return: """ modified = False size = len(nums) for i in range(len(nums)-1): if nums[i] > nums[i + 1]: if modified: return False """ i-1 i i+1 1 2 3 ...
83b5205ad3009b09d6f90a69c1e4a702cc17b6d0
69,182
from typing import Iterable from typing import Any from typing import List def serialize_list(items: Iterable[Any]) -> List[Any]: """Serializes UFP data list""" new_items: List[Any] = [] for item in items: new_items.append(serialize_unifi_obj(item)) return new_items
ea24ffca17d7475938cf0400e68a890b4e6bcf4b
69,183
def generic_scalar_product(b1, b2=None, scalar_product=None): """ Calculates the pairwise scalar product between the elements of the :py:class:`.ApproximationBase` *b1* and *b2*. Args: b1 (:py:class:`.ApproximationBase`): first basis b2 (:py:class:`.ApproximationBase`): second basis, if...
40b9ba0cd785959090f1d70fca489afcfcd6dcde
69,184
def rename(src, dst): """ Calls gfs_rename.""" p0 = abst_path(src) s0 = str(p0).encode(name_coding) p1 = abst_path(dst) s1 = str(p1).encode(name_coding) cc = _gfs_rename(s0, s1) return cc
dd9f04573dbffb17cf8cbf952d2c85b54145b7ea
69,186
def feature_extraction(df, df1, n): """The function performs feature extraction on the information from xyz files Requirements: numpy Args: df (pandas dataframe): Data table with spatial distribution and atom info df1 (pandas dataframe): Data table with lattice vectors (o...
ef13a079ca454d65603b3544500638e3063b67ab
69,187
def locality_sensitive_hashing(min_hash, b): """Locality sensitive hash to find identical pair :param min_hash: signature matrix :param b: number of bands to split signature matrix :return: candidate pairs for each band """ all_rdd = [] # Empty list to store all rd...
cacee5c2023fd3d663c69ac0efa7546f13f355b1
69,188
def false_negative_rate(pred, target): """ 正样本中被误判为负样本的比例,1 - recall/true_positive_rate """ try: return false_negative(pred, target) / (target == 1).sum().item() except: # divide by zero return -1
f02e77423a9448163fd5e12500a2a651e0084ce5
69,189
def fateman_poly_F_1(n): """Fateman's GCD benchmark: trivial GCD """ Y = [Symbol("y_" + str(i)) for i in range(n + 1)] y_0, y_1 = Y[0], Y[1] u = y_0 + Add(*[y for y in Y[1:]]) v = y_0 ** 2 + Add(*[y ** 2 for y in Y[1:]]) F = ((u + 1) * (u + 2)).as_poly(*Y) G = ((v + 1) * (-3 * y_1 * y_0 *...
aacb38639704e7e64b8f120db662fe5789c566f4
69,190
import cgi def safe_enter2p(s): """正文 换行替换""" return '<p>' + cgi.escape(s).replace("\n", "</p><p>") + '</p>' if s else ''
7ca789f9b12bc6cb685975f37548d43504c4d3f8
69,191
import torch def accuracy(output, target, topk=(1,)): """Computes the accuracy over the k top predictions for the specified values of k""" with torch.no_grad(): maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() corre...
76571ef880404138a16f814415a987c8ecbbe750
69,192
import json import PIL import io import base64 def input_fn(request_body): """Pre-processes the input data from JSON to PyTorch Tensor. Parameters ---------- request_body: dict, required The request body submitted by the client. Expect an entry 'url' containing a URL of an image to classify. ...
363e9a064f7f82576cab77bb40974b39ba0440be
69,193
def _auto_backward(loss, startup_program=None, parameter_list=None, no_grad_set=None, callbacks=None): """ modification is inplaced """ act_no_grad_set = _get_no_grad_set(loss, no_grad_set) assert isinstance(loss, Variable),...
08977b52e1229eac110f9c3fa37a897bdab6c536
69,194
from typing import Optional from typing import Callable def count_hint( dsid: str, etype: ir_datasets.EntityType = ir_datasets.EntityType.docs, metadata_provier: Optional[MetadataProvider] = None) -> Callable[[], Optional[int]]: """ Returns a lambda expression that provides the count from metadata...
c9d6e0f76fb302393f5ad4a6c52ab7fd1d3b76ba
69,196
def lambda_handler(event, context): """ Main Lambda function """ try: response = PINPOINT.phone_number_validate( NumberValidateRequest={ 'PhoneNumber': MOBILE_ENDPOINT } ) except PINPOINT.exceptions.BadRequestException: response_body = f"Not a ...
0e35a1d2c319136298d9836fa83ae05756bca0ef
69,197
def calc_gradient_from_gate( c_sys: CompositeSystem, hs: np.ndarray, var_index: int, is_estimation_object: bool = True, on_para_eq_constraint: bool = True, on_algo_eq_constraint: bool = True, on_algo_ineq_constraint: bool = True, mode_proj_order: str = "eq_ineq", eps_proj_physical: f...
e5da4b971a8b8dc318b51adfc813987209a007f9
69,198
import io def part1(stdin: io.TextIOWrapper, stderr: io.TextIOWrapper) -> int: """ As a sanity check, look through your list of boarding passes. What is the highest seat ID on a boarding pass? """ tickets = parse(stdin) stderr.write(f"{tickets}\n") max_ticket = max(seat_ids(tickets)) ...
2460a3785264ac9d9f6987a88a851f80a1b5a047
69,199
from typing import OrderedDict def read_populations(flname): """ Read populations from a file. We assume that the file has one population per line. The population name comes first and is followed by a comma. The name of each sample follows, also separated by comma. For example: pop1,s...
9467bf2e882a2de0ebfb1ecfb566baeab16a1500
69,200
import inspect def is_instance_of_django_model(reference): """ Tests if a given reference is a reference to a class that extends django.db.models.Model :param reference: A given Anonymous reference. :rtype: boolean :returns: A boolean value that is true only if the given reference is ...
b54536bded37e4a078c266bdc9b3553cbf48e0f3
69,201
def extract_peers(units, boxes): """ **Function Provided by UDACITY** Initialize a mapping from box names to a list of peer boxes (i.e., a flat list of boxes that are in a unit together with the key box) Parameters ---------- units(dict) a dictionary with a key for each box (string) who...
7a40e913d4b0c0b059b535d7a2b77481127ebf0b
69,203
async def unset_user(session: CommandSession): """注销绑定""" bot = nonebot.get_bot() message_type = session.ctx['message_type'] # 消息类型 user_id = session.ctx['user_id'] # qq群的qq成员id号 # 判断消息是否为群消息 if message_type == "group": message = session.ctx['message'] message = str(message)[1:...
6422156f25b636324d813f4f5930165f71a28c3e
69,204
def edit(request, carrera_jurisdiccional_id): """ Edición de los datos de un título jurisdiccional. """ carrera_jurisdiccional = CarreraJurisdiccional.objects.get(pk=carrera_jurisdiccional_id) titulo_anterior_id = int(carrera_jurisdiccional.carrera_id) if request.method == 'POST': form = CarreraJurisdiccionalD...
2d156a8315f12ec9af746cf10550af457e186be5
69,205
def parse_expression(expression, doc_dict): """Parse an expression.""" return Parser(doc_dict).parse(expression)
5c01121e102cea1114f34ccf7d2a0f201c47520d
69,206
from datetime import datetime def get_unix(str_ts, date_format): """Get unix timestamp from a string timestamp in date_format. Args: str_ts: string timestamp in `date_format` date_format: datetime time stamp format Returns: int: unix timestamp """ return datetime.strptim...
6d0c591734fa78defed11cd5ed8c66da63ad3b5b
69,207
import io import json def load_json(buffer): """ Returns a structure if file was json :param buffer: :return: JSON created object or None """ fp = io.BytesIO(buffer) try: data = json.load(fp) return data except json.decoder.JSONDecodeError: return None
6893a22009ca0093298060913d27d30e2645a92e
69,208
def compute_raw_transect_depths(shore_point, \ direction_vector, bathymetry, bathymetry_uri, landmass, landmass_uri, \ bathymetry_resolution, max_land_profile_len, max_land_profile_height, \ max_sea_profile_len): """ compute the transect endpoints that will be used to cut transects""" # Maximum tran...
71b8e7e48ecd28e4431a5be40c4e4dd52bb81c20
69,209
import torch def convert_raw_locations_batched_top_down(raw_locations, stacking_program, primitives): """ Args raw_locations (tensor [*shape, num_blocks]) stacking_program (tensor [*shape, num_blocks]) primitives (list [num_primitives]) Returns [*shape, num_blocks, 2] """ ...
cee051c4e3450910328bb1fa377a0f4cd02499e8
69,210
def _preprocess_cameras(example, indices, dataset_info): """Instantiates the ops used to preprocess the cameras data.""" raw_pose_params = example['cameras'] raw_pose_params = tf.reshape( raw_pose_params, [-1, dataset_info.sequence_size, _NUM_RAW_CAMERA_PARAMS]) raw_pose_params = tf.gath...
fc43470ac26d793539f305a9a44117c15861d440
69,212
def lad_msoa_mapping(): """Map between lad and msoa {LAD: [MOAS]} """ msoa_lad_map = { 'E06000047': ['E02004297', 'E02004290', 'E02004298', 'E02004299', 'E02004291', 'E02004300', 'E02004292', 'E02004301', 'E02004302', 'E02004303', 'E02004293', 'E02004304', 'E02004294', 'E02004305', 'E02004295',...
55f97fecca6e11df2141991de9bdb4295ca5e4af
69,213
import random import logging def build_encapsulated_ip_packet( rand_selected_interface, ptfadapter, rand_selected_dut, tunnel_traffic_monitor ): """ Build the encapsulated packet to be sent from T1 to ToR. """ tor = rand_selected_dut _, server_ips = rand_selected_interface s...
f2ac6dd830eeadb60404135206b657b1689a03c2
69,214
def test_rows_filled(): """ cycles through all rows in placement_map and returns a list of all row indecies that are filled """ rows_filled = [] for i in range(len(placement_map)): if 0 not in placement_map[i]: rows_filled.append(i) return rows_filled
8a6d937c089a806992690a96d4bd3cedc684d3fa
69,216
def load_img_info(files): """Load the information of one image. Args: files (tuple): The tuple of (img_file, groundtruth_file) Returns: img_info (dict): The dict of the img and annotation information """ assert isinstance(files, tuple) img_file, gt_file = files assert osp.b...
5f1e3ce6dc410985e082fc7b66315e7d80167aed
69,217
def run_transport(definition, transport) -> bool: """ Runs schedule & watch for a transport :param definition: :param transport: :return: """ with definition.transport(binaries=[]): transport.schedule( command="--mocked--", definition=definition, is_backup=T...
e8a3442f670351ed7642abe4b4a837fd84d36f55
69,218
def rivers_by_station_number(stations, N): """Passed a list of station objects and a number N, returns the list of N river objects from with the most monitoring stations on it.""" riverstation = stations_by_river(stations) numstations = sorted_by_key([(i, len(riverstation[i])) for i in riverstation], 1, rev...
d2965c4f68bb8519144308f4eff11e3017b1ba28
69,220
def fake_request(): """A faked APIRequest.""" class FakeApiRequest(APIRequest): def send(self, params=None): return self class FakeApiClient(API): def __init__(self): super().__init__("notempty") self.base_url = "" # Overwrite with empty base @property def request_class(self): return FakeApiR...
c6d1639e8f2b43971ffe1176d3511cd665f15dc1
69,221
def band_dos_atoms_spin_polarized( band_folder, dos_folder, atoms, output='band_dos_atoms_sp.png', scale_factor=5, color_list=None, legend=True, linewidth=0.75, band_color='black', unprojected_band_color='gray', unprojected_linewidth=0.6, figsize=(8, 6), width_ratios=...
83b684619f68f7262ada90f7673bd655f7cde9f6
69,223
from typing import Dict from typing import Any def load_screens() -> Dict[str, Any]: """ Initialize screen components and screens, and store references to them """ for component_name in SCREEN_COMPONENTS: load_kv(component_name) screens = {} for screen_name, screen_cls in SCREENS.items(): ...
3241880c714dc2a709bcbadd1f9f52b30452c2ef
69,224
def play_game(board, original_total_time, time_left, turn_count, move_count_no_change): """ plays the best move using a portion of remaining time input: board (list), time_left (float), turn_count (int) output: result (tuple) -> e.g. ("E", (5, 2), (4, 3)) """ num_pieces_board_in = board.num_pi...
3bab79e00fc1caeb4b3e06c836f67a9e4186b59d
69,225
def skgrcnn109(num_classes=1000): """ Args: num_classes (uint): number of classes """ model = GRCNN([3, 3, 22, 3], [128, 256, 512, 1024], SKconv=True, expansion=2, num_classes=num_classes) return model
7ee3b244a0689396423e1a6d9753c74a3135e934
69,227
import re def string_to_arrow(datasets_dtype: str) -> pa.DataType: """ string_to_arrow takes a datasets string dtype and converts it to a pyarrow.DataType. In effect, `dt == string_to_arrow(_arrow_to_datasets_dtype(dt))` This is necessary because the datasets.Value() primitive type is constructed usin...
206d66e4c18fc085852667890e7bd4903703299a
69,228
def document_list_folders(request, destination, location_id): """ Get the folders that are associated with the destination and location id Method ~~~~~~ 1. Get all the document permissions connected to the destination and location 2. Get the folder information from this :param request: ...
c1c4fe9581128a369cc844e1b29ca601e80a3687
69,231
def datacursor(artists=None, axes=None, **kwargs): """ Create an interactive data cursor for the specified artists or specified axes. The data cursor displays information about a selected artist in a "popup" annotation box. If a specific sequence of artists is given, only the specified artists will...
713dcdf67a465afd055f10ad94d0744b776c8522
69,232
def channel_to_module_output(channel): """Returns a (module, output) pair given a CCD channel number.""" if channel < 1 or channel > 88: raise ValueError("Channel number must be in the range 1-88.") lookup = _get_channel_lookup_array() lookup[:,0] = 0 modout = np.where(lookup == channel) ...
dddf0a38bae7f03fb5de8fbbb71e1c932594c58c
69,233
def score_openpose(e, image, w, h): """Score an image using OpenPose model. Args: e: OpenPose model. image: Image in CV2 format. Returns: Nubmer of people in image. """ resize_out_ratio = 4.0 humans = e.inference( image, resize_to_default=(w > 0 and h > ...
d2969d5af4736497d463482c6b0f532b9e9f908c
69,234
def generate_expired_token(create_user): """ generate expired JWT token """ user = create_user user_data = { "email": user.email, "username": user.username } jwt = JWTAuthentication() # encode token encoded_token = jwt.generate_token(user_data) return encoded_toke...
437745a9a7276f448f4dae60e9d405887fb72cb0
69,235
def int_fn_vt(dm_comp, method, timeArr=time_arr, vArr=v_arr, vsun=v_sun, t1=tvernal, from_scratch=False, what_inter='interp2d'): """ Interpolation of a function method for a DM component, coming from a 2D time [days]-velocity [km/s] table, for fixed vsun and t1. The table is either constructed from scratch, or ...
4294f3a7349bffc3552b78612dd17c5677c81547
69,236
def readable_join(xs, conjunction="and", sep=","): """ Accepts a list of strings and separates them with commas as grammatically appropriate with a conjunction before the final entry. Any input strings containing only whitespace will not be included in the result. >>> readable_join(['foo']) 'fo...
d518007954b79ff1cf8120a9bdea010e9594f02b
69,237
def minimize_sat(u, u_min, u_max, desaturation_vector): """ Minimize the saturation of the actuators by adding or substracting a fraction of desaturation_vector. desaturation_vector is the vector that added to the output u, modifies the thrust or angular acceleration on a specific axis. For ...
79e5e898cad83e32c9eb09b084ce3bd3df0639d1
69,239
import shlex def help(bot, message): """#help """ try: cmd, *args = shlex.split(message.text) except ValueError: return False if not cmd[0] in config['trigger']: return False if not cmd[1:] == 'help': return False msg = ['ケルベロス ver3.0.5'] msg_help = [] ...
f07caa7b3b00b334fc1af153ed1a086ff72282e2
69,240
def _cond_apply(x, y, func, prob): """Conditionally apply func to x and y with probability prob.""" return tf.cond((tf.random.uniform([], 0, 1) >= (1.0 - prob)), lambda: func(x,y), lambda: (x,y))
c8f93e40407fc4e7edf8c72095036f19a49db455
69,241
def replace_underscore_with_space(original_string): """ Another really simple method to remove underscores and replace with spaces for titles of plots. Args: original_string: String with underscores Returns: replaced_string: String with underscores replaced """ return original_...
27bea63c33c2ffe44b1ddc591a7813d8830e9f76
69,242
def residual(parameters_vector, datatube, vartube, xfibre, yfibre, wavelength, model_name, fixed_parameters=None, secondary=False): """Return the residual in each fibre for the given model.""" parameters_dict = parameters_vector_to_dict(parameters_vector, model_name) parameters_dict = insert_fi...
6353f2fa17aa09df6f4b98e6195ebc4be07d19a5
69,243
import numpy def gradient_array(ndarray): """ transform numpy array into python list """ out = ndarray if isinstance(out, numpy.ndarray): out = ndarray.tolist() return out
41d4a37e50db0a319d23d18d95978f0d16e569f8
69,244
def is_submod(mod_obj): """ Find out whether module has a parent or not. :param mod_obj: module object :return: module status """ try: bt = mod_obj.get('belongs-to') if not bt: return False return True except Exception as e: return False
274d985b3b7b07f02e919af20ed7fd4531136ccc
69,245