content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import json import copy def demo(): """The Nevermined Federated Learning demo. This demo showcases the nevermined Federated Learning capabilities. FLow: 1. Setup nevermined 2. Setup accounts 3. Publish compute to the data assets 4. Publish algorithm 5. Publish work...
f98ce00cc16c5d3bb96cca41640cef24e946a759
3,611,300
def cdlhangingman( client, symbol, timeframe="6m", opencol="open", highcol="high", lowcol="low", closecol="close", ): """This will return a dataframe of hanging man for the given symbol across the given timeframe Args: client (pyEX.Client): Client symbol (string)...
775510fdaebfdb100e37489bd03cee589d7aa341
3,611,301
def gast_to_code(gast, out_lang, lvl=0): """ gast router that takes generic ast and the output language that the gast needs to be converted to and executes the conversion recursively out_lang correspond to the language codes defined in datastructure: javascript: js python: py """ con...
f6256ad2e2ce2b94b830fcd9eba0c1be6249c232
3,611,302
from typing import Callable def skill(name: str) -> Callable: """Wrap function to transform it into Skill object.""" def wrapper(func: Callable) -> Skill: return Skill(name, func) return wrapper
3e5ab800f417fa5a3108747f84c23bac2fcc6df0
3,611,303
def rotate(arr, n, p): """Rotates an array. Args: arr: The array to be rotated. n: The size of arr. p: The number of rotations to be performed. Returns: An array rotated p times. Raises: ValueError: If p > n. """ if p > n: raise ValueError("The n...
cae9264ac44ef7864a74f00b93f0f3431525a5a5
3,611,304
def world2Pixel(geoMatrix, x, y): """ Uses a gdal geomatrix (gdal.GetGeoTransform()) to calculate the pixel location of a geospatial coordinate """ ulX = geoMatrix[0] ulY = geoMatrix[3] xDist = geoMatrix[1] yDist = geoMatrix[5] rtnX = geoMatrix[2] rtnY = geoMatrix[4] pixel = int((x - ulX) / xDist)...
7f676061ae12c9a7ffeedfdf1bfb88fb84d24f8f
3,611,305
def _derivative(f, a, method='central', h=0.01): """ Compute the difference formula for f'(a) with step size h. copied from: https://personal.math.ubc.ca/~pwalls/math-python/differentiation/differentiation/ Parameters ---------- f : function Vectorized function of one variable ...
de02aaf132922c0be8aeb84bea5af5d09e850b9d
3,611,306
def forbidden_request() -> dict: """ Returns a generic forbidden request response back. Used when the token given is not authorized to act on resources. """ return return_response(403, responses[403])
3e1668d923cdbada58ea0661632364dce8970147
3,611,307
import os import urllib def maybe_download_data(data_dir): """Download data sets if necessary. Args: data_dir: Path to where data should be downloaded. Returns: Paths to the training and test data files. """ if not os.path.isdir(data_dir): os.makedirs(data_dir) training_data_path = os.path...
f3e8a4d65598cab76d0824dbc3a44157becf1c34
3,611,308
def recursion_constants(max_n): """ Calculates the values useful for performing the scalar potential algorithm """ k = _gen_2d_array(max_n, max_n, 0) for n in range(1, max_n): for m in range(n + 1): k[m][n] = (((n - 1) * (n - 1)) - (m ** 2)) / ( (2.0 * n - 1) * (2...
934ae6e98314b3511fd22fdc080581e1ff3e25bf
3,611,309
import platform def return_malware(): """Return malware list per platform""" if platform.system() == "Windows": return windows_malware_list else: return linux_malware_list
977b7bcb107607aa649455683e805836460a95dc
3,611,310
def tokenize(text) -> list: """ Parses input and returns valid input as typed tokens If token starts with a: * character -> word (this will be messed up if b' or r' is introduced * number -> int || float Currently does not handle special characters """ stack = [] tokens...
f7e08180d6e15ffabdc14e6dc3aa984a33a3a3b0
3,611,311
def encode(query, doseq=False, safe='', encoding=None, errors=None, quote_via=quote_plus): """Wrapper for urllib.parse.encode""" return urlencode(query, doseq=doseq, safe=safe, encoding=encoding, errors=errors, quote_via=quote_via)
a02e681d01c7c9be2aba5df770ed405f241f06d4
3,611,312
def get_session(url, key, secret): """Get a :class:`tempoiq.client.Client` instance with the given session information. :param String url: Backend's base URL, in the form "https://your-url.backend.tempoiq.com" :param String key: API key :param String secret: API secret :r...
a79b2ce48ea916d70802dcf193e85104447322da
3,611,313
def get_diffusion_plot_analysis_features(data): """Returns all the features associated with the diffusion plot analysis, that is: DTXC, DTYC, DTRC, X2, Y2, R2, DXS, DYS, DRS, HXS, HYS, HRS, DXL, DYL, DRL, HXL, HYL, HRL""" DTXC, DTYC, DTRC, X2, Y2, R2, DXS, DYS, DRS, HXS, HYS, HRS, DXL, DYL, DRL, HXL, HYL, ...
db079212b5945ed6c4f15a511cbccfdee52783ae
3,611,314
import pdb import itertools def make_resampled_models(lbda_obs, grid_param_list, model_grid=None, model_reader=None, em_lines={}, em_grid=None, dlbda_obs=None, instru_fwhm=None, instru_idx=None, filter_reader=None, interp_nonexist=True): ...
faec105aa7181493cfaf915c3ef4d25c9f7f69d2
3,611,315
import argparse def parseCmd(): """Parse command line arguments Returns: dictionary: Dictionary with arguments """ parser = argparse.ArgumentParser(description='Renames the transcripts and genes of a GTF file.') parser.add_argument('--gtf', type=str, required=True, help='Path to a...
b9bb712686108db5051c0ac46ba94646a296738d
3,611,316
def insert_in_bst(root, node): """ Insert node in the binary search tree :param root: root node of the binary search tree :type root: TreeNode :param node: node to insert :type node: TreeNode :return: root node :rtype: TreeNode """ if root is None: root = node else: ...
3c737d71c5793e7baa51d1ad75b6cc056abbda82
3,611,317
from typing import Tuple from typing import Optional from typing import Type def _get_serializer_field_type(field: Field) -> Tuple[str, Optional[Type]]: """ Get typescript type from trivial serializer field. """ field_type: str dependency = None if type(field) in DRF_FIELD_MAPPING: fie...
3180ab5ce6f100894ee3b9ed55af6a3dd5a5b0b8
3,611,318
def format_bytes(b): """Format bytes as human-readable text.""" kb = 1024 mb = kb*1024 gb = mb*1024 if b < kb: return '%s b' % b elif b < mb: return '{0:.2f} kb'.format(float(b) / kb) elif b < gb: return '{0:.2f} mb'.format(float(b) / mb) else: return '{0:.2f} gb'.format(float(b) / gb)
4c41105449a8a07e3aca932d9ab3326176f6f1f6
3,611,319
def get(name): """ Return the :term:`doclist` of the `Page` specified by `name` """ page = dataent.get_doc('Page', name) if page.is_permitted(): page.load_assets() docs = dataent._dict(page.as_dict()) if getattr(page, '_dynamic_page', None): docs['_dynamic_page'] = 1 return docs else: dataent.res...
09373abbc03494b1cc133c9e1b2e32f767007681
3,611,320
import shutil import subprocess def is_repo(path): """Check if the path is in a git repo""" if path is None: return False if not shutil.which('git'): return False out = subprocess.run(['git', '-C', str(path), 'rev-parse'], stdout=subprocess.PIPE, ...
62d79fd80d5343992084631154b949bf65826df0
3,611,321
import os import numpy as np from nipype.utils.filemanip import split_filename as split_f from scipy.io import loadmat def import_mat_to_conmat(mat_file, data_field_name='F', orig_channel_names_file=None, orig_channel_coords_file=None): """Import mat to conmat."""...
c418b321140f7655107a2b64094d5a7677015bed
3,611,322
import os import json def initiate_correct_model(model_name=None, model_path=None, **model_parameters): """ Either specify a model path to continue training and existing model or specify a model name to initiate a new model. Returns a initiated model of type tf.keras.Model """ # Validate input ...
61f599e52dd2ead73ee8ddd939c67da22ed48eb2
3,611,323
def create_app(config_mode=None, config_file=None): """ Creates the Flask application Kwargs: config_mode (str): The configuration mode. Must be a `class` in `config.py`. One of ('Production', 'Development', 'Test', 'Docker') config_file (str): The configuration file. ...
7a2456e98dd55d0cd6063d324d57c864948f2de2
3,611,324
def computeBootstrap(data, pointingID): """Compute the 95% Bootstrap CI from a list of annotations @param data tuple of np.array containing (accs, annotTCTs, trialTCTs) @param pointingID the pointingID to look at @return a tuple (acc_avg, acc_std, tct_trial_avg, tct_trial_std, tct_annot_avg, tct_annot_s...
93e902eeec3eb6b6aeeb4ad943247eab8d49f677
3,611,325
import numpy def from_meshio(mesh): """Convert a :class:`meshio.Mesh` to :class:`toughio.Mesh`. Parameters ---------- mesh : meshio.Mesh Input mesh. Returns ------- toughio.Mesh Output mesh. """ if mesh.cell_data: version = get_meshio_version() if...
409dd5984d393f1d13587141d3783e0dedb3bfab
3,611,326
def register_decoder(name=None): """Register a decoder. name defaults to function name snake-cased.""" def decorator(decoder_fn, registration_name=None): """Register & return decoder_fn with registration_name or default name.""" decoder_name = registration_name or default_name(decoder_fn) ...
09b29c7fde8218f7150d108545f7ca80b1f200b4
3,611,327
def _CalcPanelLocalApparentWindSph(alphas, betas, angular_rate_b, apparent_wind_speed, panel, params): """Calculates local apparent wind at each sampling point on a panel. Args: alphas: Angle-of-attacks [rad] represented as a (...,) ndarray. betas: Sideslip angles [rad] r...
b79ff990852a1f81338935814a12242c5e53d0c8
3,611,328
def cross_validate(model, train, test=None, k=5): """Calculates mean error using k-fold cross-validation.""" train = train.sample(frac=1, random_state=360) # Shuffles rows. k = k if test is None else 1 chunks = np.array_split(train, k) mean_rmse = 0 for i in range(0, k): if VALIDATING:...
d53f3baf00ae7cf797e82fc476718ee702dc8236
3,611,329
def composite_difference_composite(original, other): """ Subtract all elements that belong to other from original. This is a tricky one, as we have to subtract one tree from another. Good thing we can iterate over both trees in linear time and perform the entire difference operation in linear time as w...
dd7e63924ef49191b398e3cdb90e7c4e13edd799
3,611,330
def calcular_puntos (boolean,cant_punt,difficult): """resta o suma segun si se equivoco o no en las coincidencias y segun la dificultad elegida""" if boolean: x = sumar_puntos(cant_punt,difficult) else: x = restar_puntos(cant_punt,difficult) return x
b90ab5296290f12d455bb392928974192a63ce9a
3,611,331
def conv2d(images, kernels, padding="SAME", strides=[1, 1]) -> core.Variable: """2D convolution, with same api as tf.nn.conv2d [1]. Args: images: A `Variable` of shape [n_images, imheight, imwidth, n_channels]. kernels: A `Variable` of shape [kernheight, kernwidth, channels_in, channels_out]. ...
ca04ea24e2ed645d1b9693a8596bc97287d24f9a
3,611,332
def getVelocity(data): """ Calculate velocity of a given set of values using linear regression. Arguments: data An iterable of numbers. Returns: velocity The estimates slope. """ sumY = sumXY = 0 for x, y in enumerate(data): sumY, sumXY =...
d86c5e0b6f2e6024b9578486d377915649402f3a
3,611,333
def freeze_layer(layer): """ Freeze a layer, so its weights won't be updated during training :param layer: :return: """ for param in layer.params: layer.params[param].discard('trainable') return layer
2edcd24743fc62bf5e8a7cef9ce871e691d38d85
3,611,334
def serialize_example(row): """ Creates a tf.Example message ready to be written to a file. """ # Create a dictionary mapping the feature name to the tf.Example-compatible # data type. fp = preprocess_fp(row[0]) year = preprocess_year(row[2]) feature = { "floorplan": _floats_ar...
7d201a0a06087e7bf4e8dec34215b8a1a4ddfdf3
3,611,335
import os def parse_from_text(text_path, dtype_list, path_list): """ dtype_list is a tuple, which represent a list of data type. Example: The file format like: a/1.jpg 3 2.5 a/2.jpg 4 3.4 dtype_list: (str, int, float) path_list: (true, false, false) Returns: res: according to t...
2e037b62a9b6a88a2514f331425d82a63f11c8bc
3,611,336
def parse_cached(cached_credentials): """Parse existing csv file Requires first 4 columns to be TeamNum, Password, Code, Color [in hex] """ teamnums = [] passwords = [] codes = [] with open(cached_credentials) as f: f.readline() for line in f: tokens = line[:-1]....
95b9802011f22a66aa688947f059b29592de7487
3,611,337
def ubytes(n_spin_orbitals, i, state): """ Remove electron at orbital i in state. Parameters ---------- n_spin_orbitals : int Total number of spin-orbitals in the system. i : int Spin-orbital index state : bytes Product state. Returns ------- state_new :...
157beb144221468aa6472390f39cc2ba70b25ed6
3,611,338
def tf_grad(t_scalar_func): """Maps a TF scalar-function to its TF gradient-function.""" def f_grad(t_pos): tape = tf.GradientTape() with tape: tape.watch(t_pos) t_val = t_scalar_func(t_pos) grad = tape.gradient(t_val, t_pos) assert grad is not None, '`None` gradient.' return grad ...
7ba0d2b9f74c6bdf4e62261e7d11cc34087a78b4
3,611,339
def parse_tpkl_depreciated(filename): """ A function to parse custom recarray objects. This variation is dependent upon table.py from the Anfinrud Lab Parameters: filename (str): path of file to be analyzed Returns: Trace:custom object built to hold a single scattering curve and ...
3c30df6f5aacd39ec4de4c87c18e71f19e09dd8a
3,611,340
def time_to_string(time): """Converts a datetime instance to a string""" if time is None: return time if time == "now": time = datetime.now() return mktime(time.timetuple())
137e1b9c434d3e034402c2f37acd136390d59530
3,611,341
def spacecraft_valid_id(request): """ AJAX method for checking whether a given identifier is in use or not within the database. :param request: The GET HTTP request. :return: '{ isValid: "true/false", value: "$GET.value" } """ requested_id = request.GET['value'] if not requested_id: ...
0fb635955e7c11148bbe7077042a106fab1551f7
3,611,342
import six import sys import inspect def url_for(endpoint, **kw): """ NB: Altered flask functions Assembly url_for is an alias to the flask url_for, with the ability of passing the function signature to build the url, without knowing the endpoint :param endpoint: :param kw: :return: ""...
af3043710f936e7e2dece102fbf1dfa7b271dad3
3,611,343
from unittest.mock import patch def reentrant_redis_locks(): """Decorator/context manager to enable reentrant redis locks This is useful for tests that do things like acquire a lock and then, before the lock is released, fire off a celery task (which will usually be executed synchronously due to ...
7aa7a1cb5d2dc6dd732068f00a9ac4a81830cea4
3,611,344
def include_original(dec): """ Meta decorator, which make the original function callable (via f._original() ) """ def meta_decorator(f): decorated = dec(f) decorated._original = f return decorated return meta_decorator
ba1bd643c192c1fc11df668ee4744202e1e3fd3a
3,611,345
def get_related_model(model, relationname): """Gets the class of the model to which `model` is related by the attribute whose name is `relationname`. """ if hasattr(model, relationname): attr = getattr(model, relationname) if hasattr(attr, 'property') \ and isinstance(at...
6cec4b5edf148dc9a6b1197f70a203aa63fd0730
3,611,346
from typing import List from typing import Dict def retrieve_all(database_connection: mysql.connector.connect ) -> List[Dict]: """Returns a list of OrderedDicts with scorekeeper details for all scorekeepers Arguments: database_connection (mysql.connector.connect) """ score...
60eda30a6ebfc515d6972914d16da424a9c71a9a
3,611,347
def proper_paranthetics(string): """ Evaluate whether open and closed parentheses match in proper order. Return 1 if there are unclosed open parens. Return 0 if parens are balanced. Return -1 if there are close parens not preceded by open parens. """ paren_stack = Stack() for char in st...
6f9bb2961e1386f8887b9ea7770f8154b8d58b81
3,611,348
def sqexpcov(n: int, w: float, var: float = 1.0): """Construct square exponential covariance matrix Args: n: size of the matrix w: scale var: variance Returns: """ # i, j = meshgrid(arange(n), arange(n)) # return var * exp(- w * (i - j) ** 2) return var * exp(-w * ...
8ac7230763caa9e0f9637425ae4442d35603ec55
3,611,349
def create_email_addresses_in_group(email_group_id): """ Create new /email_addresses in a certain email_group --- Method: POST @param: email_group_id int @param: email_addresses str // if many, divided by comma """ request_data = request.json # get email_group email_group = Emai...
c2f25ad7d63c9c8af5d5def1c343b86065291e84
3,611,350
from typing import Tuple def make_config( src_path: str, dst_path: str, *, data: OptAnyByStrDict = None, exclude: OptStrSeq = None, include: OptStrSeq = None, skip_if_exists: OptStrSeq = None, tasks: OptStrSeq = None, envops: OptAnyByStrDict = None, extra_paths: OptStrSeq = Non...
1efc6ea1ad90fc5611737bb729796c6b5cce04c0
3,611,351
import re def add_new_entry(): """Add an entry""" # json_data = request.get_json() title = str(request.data.get('title', '')).strip() description = str(request.data.get('description', '')) # check empty title if not title: response = {"message": "Please input title", "status": 401} ...
d0f0a42aeaecf0af6d6b48b1cca9c0baa30ac8be
3,611,352
import os def check_java_home_set(): """Check if the java home set""" # check if environ variable is set if "JAVA_HOME" not in os.environ: Log.error("JAVA_HOME not set") return False # check if the value set is correct java_path = get_java_path() if os.path.isfile(java_path) and os.access(java_pa...
2b29a2c3bc7ba2361ea9e50521a6596ac5073e17
3,611,353
def error_403(error): """ Página de erro customizada: Erro 403 Args: error: error class Returns: Template renderizado: errors/403.html """ return render_template('errors/403.html', legend='Erro 403'), 403
8628a078a4c5d5155180e98e9fa678199516b6c5
3,611,354
import json def post_sqs_message(queue, payload, delay=0): """ Send a new SQS message for backend processing :param queue: Boto3 SQS Queue object :param payload: Json Serializable Python object :param delay: Delay in second. How much time to delay before message becomes active :return: Nothing...
e148dcb0b115bbaf71982b1b08461034d17b6710
3,611,355
import privapi.tests.data import os def get_test_data_folder(schemaroot='schema', which=''): """ """ folder = os.path.dirname(os.path.abspath(privapi.tests.data.__file__)) folder = os.path.join(os.path.join(folder, schemaroot), which) return folder
12edd59fbd520de30cee1cce4f563acfcb51480a
3,611,356
import warnings def fill_nan(array: np.ndarray) -> np.ndarray: """Replace NaNs with values interpolated from their neighbors Replace NaNs with values interpolated from their neighbors using a 2D Gaussian kernel, see: https://docs.astropy.org/en/stable/convolution/#using-astropy-s-convolution-to-replace-b...
78d4c0eca90bd008e65ba604176738273590cb52
3,611,357
def backup_remote(): """Does a remote database dump and scps the file. Returns the filename.""" remote_filename = get_backup_filename(hostname=env.host_string) print("Remote filename: " + remote_filename) with cd('bookmarker'): run('source env/bin/activate && ' + BACKUP_COMMAND + remote_filenam...
abd9010cf8ae93bf51505286ca266b048bd3fbf4
3,611,358
import argparse import sys def parse_args(): """Parse command-line arguments """ parser = argparse.ArgumentParser() parser.add_argument('config', help='train config file path') parser.add_argument('--n_data', default=None, dest='n_data', type=int, help='size of dataset to ...
2c0f24c6733b585450954410a25af680502fe2fc
3,611,359
def build_signature_def_from_tensors(inputs, outputs, method_name): """Builds signature def with inputs, outputs, and method_name.""" return tf.saved_model.signature_def_utils.build_signature_def( inputs={ key: tf.saved_model.utils.build_tensor_info(tensor) for key, tensor in inputs.items(...
8f9ee68236fdbd0ecdf6e860c50020c8c8bfefd3
3,611,360
def splice_before(base, search, splice, post_splice="_"): """Splice in a string before a given substring. Args: base: String in which to splice. search: Splice before this substring. splice: Splice in this string; falls back to a "." if not found. post_splice: String to add ...
f8f5bf3c2355c38d16157836863e501cbc846d40
3,611,361
import typing def _field_from_annotation(attr: str, annotation, array_type: FieldArrayType = FieldArrayType.scalar, ) -> FieldDesc: """ Create a SimpleField or a StruturedField, given annotation information. Parameters -...
44a1ab7c67731d6e60ea7f8bb762dd1f55f32bf8
3,611,362
import csv def average_trip_length_with_protion_of_trips_longer_than_30_min(filename): """ This function reads in a file with trip data and reports the number of trips made by subscribers, customers, and total overall. """ with open(filename, 'r') as f_in: # set up csv reader object ...
eda083cde82da0f8db8f2a4716674496e81a2c74
3,611,363
def gradient_check_n(parameters, gradients, X, Y, epsilon=1e-7, print_msg=False): """ Checks if backward_propagation_n computes correctly the gradient of the cost output by forward_propagation_n Arguments: parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3"...
2c969bc4baf112384009a410fc4a1f98a73ffd3a
3,611,364
from typing import Optional def is_short_flag_reason(flag: str) -> Optional[str]: """ Checks if the given string is a valid short flag. :param flag: The string to check. :return: None if it is a valid short flag, or the reason if not. """ # Short flags must start...
5c95fe2266a964f91995ef4607475761f6dc96b7
3,611,365
def text_from_doc_list(doc_list): """ extract a text from list of html elements. """ return [doc.text for doc in doc_list]
09370e07fc34c481091a5d34683e3668da12f5a4
3,611,366
def renderHTML(maxrows,sortby,search,descend): """generate HTML table with sorted filtered results""" data_sorted = sorted(indexnotebooks(), key=lambda item: item[sortby]) if len(search)>0: data_sorted = list(filter(lambda x:x['path'].lower().find(search.lower())>-1,data_sorted)) nitems = len(da...
6394c3bbdb182c52f6f3cf6e8cbc433832ddce48
3,611,367
import librabbitmq # noqa def supports_librabbitmq() -> bool | None: """Return true if :pypi:`librabbitmq` can be used.""" if _detect_environment() == 'default': try: except ImportError: # pragma: no cover pass else: # pragma: no cover return Tr...
20700ca975514c4a2b300a257b045bd8cb65734e
3,611,368
from enum import Enum def _create_enums(properties): """Returns a list of Enums to be generated""" enums = {} for property_ in properties: # Only generate enums for keyword properties that do not require includes. if property_['field_template'] in ('keyword', 'multi_keyword') and len(prope...
c9c8acf01283515909aff380ac7196c867b17edc
3,611,369
def get_config_file(config=None): """ This method parses properties and returns the value of CONFIG_FILE. If undefined, VACCA_CONFIG is returned as fallback. """ global VACCA_CONFIG,VACCA_DIR print('-')*80 if not config: VACCA_CONFIG = get_env_variable('VACCA_CONFIG',DB_HOST) ...
fd3ac7fd151aea924032cf7e3c55abf6804f6a71
3,611,370
def adder(): """Adds all the numbers the user gives until "done" is typed.""" print("Type a number or 'done' when finished") result = 0 while True: try: val = input("Please give input: ") if val == "done": break else: result += ...
ce68159b6f071b47b9876ce3a6a7ec18ddd0d5fb
3,611,371
def fixed_start_fourier_df(pd_index, freq, k, name="ffcomp"): """ Generates fourier features, with a fixed starting point """ assert isinstance( pd_index, pd.Index ), "Provide pd.Index subclass as the first argument" assert pd_index.freq, "freq for input index is not defined" assert ...
610ac96cf84d96a94c90340ac72ada6c0638aa50
3,611,372
import os def mask_accessions(subset, taxids): """ filter lines from idmap that are not in set of masked taxids, return list of accessions """ accessions = [] mapfile = "%s/%s.taxid_map.gz" % (INDIR, subset) if os.path.isfile(mapfile): with Popen(['pigz', '-dc', mapfile], stdout=PI...
22ea97734a005fc62fa7f498cc71e126bfd222bd
3,611,373
import re def load_obj(filename): """ load from a Wavefront obj file """ vertices_pool = [] uvs_pool = [] normals_pool = [] indices = [] vertices = [] normals = [] uvs = [] vertices_map = {} for line in open(filename, 'r'): line = line.strip() spli...
b135a767e7d3e9d173506a5087a26aeb78dee8d9
3,611,374
from datetime import datetime def prepare_dataset(): """ Download out.csv, cast the right datatypes and convert date :return: Dataframe - columns = ['timestamp', 'article_id', 'click', 'date'] """ df = pd.read_csv('./data/R6A/out.csv', usecols=['timestamp', 'article_id', 'click'], sep=' ') df...
4f41827940147cf87d8d10bfc5e28c04a2a02979
3,611,375
def mse(x, y, axis=None): """Mean squared error""" if np.isclose(x.size, 0.0) and np.isclose(y.size, 0.0): return 0.0 elif np.isclose(x.size, 0.0): return np.mean(np.absolute(y)) elif np.isclose(y.size, 0.0): return np.mean(np.absolute(x)) min_l = min(len(x), len(y)) x...
b9028704bfcda9ff821b3c7d075289e7f173a241
3,611,376
from io import StringIO import sys def telemetry(fn): """ Decorator for CLI and other functions that need special Sentry client handling. This function is only required for functions that may exit *before* we set up the ._raven_client object on the Api instance *or* that specifically catch and re-rais...
52f79042a22fcc93a020ee87293da786f4b1b930
3,611,377
def detect(sess, net, im_file, mode='normal', cls='person', cls_ind=1): """Detect all objects of a single class in an image using pre-computed object proposals.""" im = cv2.imread(im_file) if mode == 'fast': scores, boxes = im_detect_fast(sess, net, im) else: scores, boxes = im_dete...
45a5f7a0480e95eb05dd5304f8c1a584d453189d
3,611,378
def is_write(node): """Try to find write primitives. Looking for things like:: *(_DWORD *)(something) = v38 arr[i] = v21 TODO: Rather rough, it is a first version... :param node: a :class:`controlFlowinator` node :type node: :class:`cinsn_t` or :class:`cexpr_t` :return: True ...
80f1b4ea201a4e048f60beaf2d4c07fbacae0788
3,611,379
from typing import Tuple def decode( data: _ByteString, errors: _Str = 'strict' ) -> Tuple[str, int]: """Convert a bytes type of escaped utf8 hexadecimal to a string. Args: data (bytes or bytearray or memoryview): The escaped utf8 hexadecimal bytes. errors (str or ...
a651c318f393791c421d60d2ab9f3e50f0a12b5b
3,611,380
def sort_chans(chans): """ A utility function to sort channel codes into Z, N, E or Z, 1, 2 order. """ sorted_chans = [] for chan in chans: if chan[2] == "Z": sorted_chans += [chan] for chan in chans: if chan[2] == "N" or chan[2] == "1": sorted_chans +...
22c37441698b7dd89daf508b055922d9781003f5
3,611,381
def encoding_space_to_vexvalid(space): """Input string, output number""" return _space_id[space]
97ddaa08037c88c11650edfcea43e7522fcbed74
3,611,382
async def async_setup_entry( hass: core.HomeAssistant, entry: config_entries.ConfigEntry ) -> bool: """Set up platforms from a ConfigEntry.""" url = entry.data["url"] hass.data[DOMAIN][entry.entry_id] = SensorManager(hass, url) if not entry.unique_id: hass.config_entries.async_update_entry(...
355d57fd35cba694231f49201666e27b901f1a4f
3,611,383
def normalize(df_origin): """Fill missing values, drop unneeded columns and convert columns to appropriate dtypes""" df = df_origin.copy() drop_columns = ["name", "owner", "repository"] for c in drop_columns: if c in df.columns: df.drop(c, axis=1, inplace=True) for c in df.column...
22af67e135d714297ffc2ea5c1fab8616be2feb3
3,611,384
def check_file_isvid(filename): """ checks if a file has a video extension, accepted files are: '.mp4', '.mpg', '.avi' :param filename: (str) name of the file :return: (bool) """ list_extensions = ['.mpg', '.MPG', '.mp4', '.MP4', '.AVI', '.avi'] if filename[-4:] in list_extensions: r...
5762f9020bce682b7eda948a92a41e85dedfe5c2
3,611,385
import sys import io def open(filename, mode="r"): """ Open a file for CSV mode in a Python 2 and 3 compatible way. mode must be one of "r" for reading or "w" for writing. """ if sys.version_info[0] < 3: return io.open(filename, mode + "b") return io.open(filename, mode, encoding="ut...
4f32da4da7d0645e861c26d7ab9f2a87e2778f87
3,611,386
def is_setext_underline(line: str) -> bool: """Evaluates whether a line could be the underlining for a setext heading Examples: ``` --- == ``` Args: line: The line to evaluate Returns: True if the line is could underline an setext heading. False other...
02c61b277b8981aecde67427980aaf82c7df9a66
3,611,387
def get_disparity_map(imageL: np.ndarray, imageR: np.ndarray, disparity_matcher: cv.StereoMatcher = None, disparity_filter: cv.ximgproc_DisparityFilter = None): """ Returns the disparity map based on image 1 and image 2. example: disparity = get_disparity_map...
b84316112c19b8ddd2354702a14ce4f25310b181
3,611,388
from typing import Iterable from re import T from typing import Iterator from typing import List def batcher(iterable: Iterable[T], batch_size: int) -> Iterator[List[T]]: """Groups elements from `iterable` into batches of size `batch_size`. >>> list(batcher("ABCDEFG", 3)) [['A', 'B', 'C'], ['D', 'E', 'F'...
6df1407ec51b3f6c75e8eddf07fcdbfb0d5aa55b
3,611,389
import random def get_qp_init_attr(cq, attr): """ Creates a QPInitAttr object with a QP type of the provided <qpts> array and other random values. :param cq: CQ to be used as send and receive CQ :param attr: Device attributes for capability checks :return: An initialized QPInitAttr object ...
f38fca2f89a73ba394e909e4ad22de9bd1f52f80
3,611,390
import os.path def _extract_filename(upload_filename): """ Extract filename from fully qualified path to use if no filename provided """ return os.path.basename(upload_filename)
85f2b1895a246fbf1bdd3c10de56b6c479b88330
3,611,391
import json def update_observation(request): """ Update observation in config advisor. Parameters ---------- request : a dict Returns ------- a readable information string in HttpResponse form """ if request.method == 'POST': if request.POST: task_id = req...
fe91f7d8235d133e63139c7564c7870464b6b025
3,611,392
import logging def logger_setup(): """ Creates a logger object and returns it """ logging.basicConfig(level=logging.DEBUG) return logging.getLogger(__name__)
f94305825941003039c4513d65d275f400fe5268
3,611,393
def closed_isosigs(snappy_manifold, tries = 20, max_tets = 50): """ Generate a slew of 1-vertex triangulations of a closed manifold using SnapPy. >>> M = snappy.Manifold('m004(1,2)') >>> len(closed_isosigs(M, tries=5)) > 0 True """ M = snappy.Manifold(snappy_manifold) assert set...
12964cf99ec082d17e4560d2037d478d355bbb8d
3,611,394
import torch def valLoss(model, timeStep, csystem): """ The validation loss is the MSE between predicted and correct solution. The loss is calculated seperatly for real and imaginary part """ x, y, t = SchrodingerEquationDataset.getInput(timeStep,csystem) x = torch.Tensor(x).float().cuda() ...
e15c6f5f298b411d3bd4fa7512315dcf89964426
3,611,395
def get_attr_lookup(lines, attr_name): """ :arg lines: a list of :class:`TextLine` instances :arg attr_name: A string, e.g. ``"y0"``, an attribute of :class:`TextLine` :returns: A dictionary of strings mapping values of the given attribute to lists of :class:`TextLine` sharing th...
3f87431edeb11e9edfe824bf58aeda93ad82d8ae
3,611,396
def encode_function_data(initializer=None, *args): """Encodes the function call so we can work with an initializer. Args: initializer ([brownie.network.contract.ContractTx], optional): The initializer function we want to call. args (Any, optional): The arguments to pass to the i...
303c297d8ea2b62d3ecb6ccc1e208fc54dd84e49
3,611,397
def parse(renpy_nodes, renpy_ast, config): """ Parse all node to a useable format. The node Label named 'start' will be the node with id '0'. :param renpy_nodes: all nodes from renpy game (renpy.game.script.namemap) :param renpy_ast: the renpy ast module (renpy.ast) :returns: a dict...
db6985cf8acc745f1ebd2fb53e7b447220e65f1b
3,611,398
def repeat_img_per_cap(imgsfeats, imgsfc7, ncap_per_img): """Repeat image features ncap_per_img times""" batchsize, featdim, feat_h, feat_w = imgsfeats.size() batchsize_cap = batchsize*ncap_per_img imgsfeats = imgsfeats.unsqueeze(1).expand(\ batchsize, ncap_per_img, featdim, feat_h, feat_w) imgsfeats = i...
da3b0d51fe8a8511ecbafed865ab571ac6d267a3
3,611,399