content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import os def setup_package_data(): """ Set up package data -- these are mostly resources generated from TS track organizers.""" data = [ # 2013 test event xml os.path.join(u'2013-data', u'trec2013-ts-topics-test.xml'), # 2013 nugget and match dat...
b60ab3004dd26ff3fcf9d0664d121c81cdc238cc
630,573
import json def create_eupeg_json(df): """Transforms a Pandas dataframe to a EUPEG json""" filtered = df.reset_index()[['locations','loc_spans','coord_points']] all_toponyms = [] for i in range(len(filtered)): row = filtered.iloc[i] json_entry = {'start':row['loc_spans'][0], 'end'...
d5e0a161961e9375df5dae13b8dcc7176630af36
630,574
def partial_word(secret_word, guessed_letters): """ Return the secret_word in user-visible format, with underscores used to replace characters that have not yet been guessed. """ result = '' for letter in secret_word: if letter in guessed_letters: result = result + letter ...
224a22d853d161b5711430d2bde31c8ff85d192c
630,576
import math def hexagon_points(radius, center, rotate): """ Computes the (x,y) points of a hexagon with the given properties. :param radius: radius of the hexagon :param center: (x,y) pair, the center of the hexagon :param rotate: degrees the hexagon is rotated. 0 -> flat top, 30 -> pointed top ...
58792412765b11ac789533a55cfda279704284af
630,577
import torch def compute_elastic_loss(jacobian, eps=1e-6, loss_type="log_svals"): """Compute the elastic regularization loss. The loss is given by sum(log(S)^2). This penalizes the singular values when they deviate from the identity since log(1) = 0.0, where D is the diagonal matrix containing the singular v...
58ae72ac9bb7c06bcc7e6d6d155af2d85eff4c9b
630,578
def convert_bool_to_int(value): """convert True/False to 1/0.""" if value is True: return int(1) if value is False: return int(0) return int(-1)
ab33bf7dd21cf31c3f84339b271d2b636f9d0713
630,579
import requests def set_website_preference_for_header( url_pref: str, session: requests.Session, ) -> requests.Session: """ Set the 'Email Headers' of the 'Archive Preferences' for the auth session to 'Show All Headers'. Otherwise only a restricted list of header fields is shown. """ u...
2293a0aa0e0b389617bfd31c084fa8423b90cdf0
630,581
def check_mod(module_name, version=None): """ returns true if module of input version can be imported """ try: new_module = __import__(module_name) except: return False if version is not None: if new_module.__version__ == version: return True else: ...
4c498ac6ce0de44c79c957fbc0f74bcc120f606e
630,582
def _normalize_var_name(text, start_del, end_del): """ Search&replace all pairs of (start_del, end_del) with pairs of ({, }). :param text: str to normalize :param start_del: delimiter that indicates start of variable name, typically {{ :param end_del: delimiter that indicates end of variable name, ...
f847ad8900aa240735016b3a8e0e21c419a4c441
630,583
import torch def transform_view(x, w): """ Input: (b*H*W, K*K*A, P*P) Output: (b*H*W, K*K*A, B, P*P) """ b, A, psize = x.shape _, Aw, B, P, _ = w.shape assert psize == P * P x = x.view(b, A, 1, P, P) w = w.repeat(b, 1, 1, 1, 1) x = x.repeat(1, 1, B, 1, 1) v ...
eecee19db6839f3833bad4db5fc6bd8c9b1046b5
630,584
def wsgi_invoke(app, environ): """Serve 1 requeset from a WSGI application.""" response = {} def start_response(status, headers): response.update({ 'status': status, 'headers': headers, }) response['body'] = b''.join( app(environ, start_response), ) ...
06da6037eecf7a6cae5cbac0a00ce71fbd839db0
630,586
import pickle def load(filename): """Reload compiled models for reuse.""" return pickle.load(open(filename, 'rb'))
c5978242f45bc562fb4b7323de717ade27d28f10
630,587
import math def get_k_ratio_correction(atomic_number): """ * Get the constant k ratio correction needed by the mean ionization potential * from the atomic number. * * @param[in] atomicNumber Atomic number. """ value = 0.734 * math.pow(atomic_number, 0.037) return value
1bc706b55759232f0a6ccb343b1815bfde7b6339
630,589
def getMedianvalue(lst, points): """ Returns the median of a list of numerics. :param lst: A list of numerics from which the median will be retrieved. \t :type lst: [numerics] \n :returns: The median. \t :rtype: : Numeric \n """ if points[1] == -1: if len(lst) == 1: ...
1a0c92e312df93295f9395f805e520740540d757
630,590
def nn_default_param(): """ Objective: Return NN default parameters defined in build_nn function located in regressors.py :return: """ return {'n_hidden': 2, 'n_neuron': 50, 'learning_rate': 1e-3, 'in_shape': 200, 'drop': 0.1}
a93582c3ed1887e3dc97859ecb38b636eb975f46
630,592
import os def read_image_response_body(): """Image response payload (cat gif)""" image_file = open(os.path.join(os.path.dirname(__file__), 'image.gif'), 'rb') return image_file.read()
1a5fec3d2507d73cfb81cb7fa5b690ada722bee1
630,593
import torch def compute_entropy_loss(logits, mask): """Return the entropy loss, i.e., the negative entropy of the policy.""" policy = torch.nn.functional.softmax(logits, dim=-1) log_policy = torch.nn.functional.log_softmax(logits, dim=-1) return torch.sum(policy * log_policy * mask.unsqueeze(-1)) / (...
dd9be96323567991653c4444c93b6d5f2367bd5e
630,594
def calcFixedAspectRatio(win_dim, tar_dim): """ @param: win_dim current window dim (width, height) @param: tar_dim target image dim (width, height) """ w, h = win_dim tw, th = tar_dim if w > h: h_r = h ; w_r = int(h * (tw/ th)) if w_r > w: h_r = int(w * (th / tw))...
407473f89035679a2ee4b574635b9a24c965bc3e
630,595
import os def current_boost_dir(): """Returns the (relative) path to the Boost source-directory this file is located in (if any).""" # Path to directory containing this script. path = os.path.dirname( os.path.realpath(__file__) ) # Making sure it is located in "${boost-dir}/libs/mpl/preprocessed". ...
ae0a46dd992166862f636e40f978fa4f92677a53
630,596
def convert_to_celsius(fahrenheit): """ (number) -> float Return the number of Celsius degrees equivalent to fahrenheit degrees >>> convert_to_celsius(75) 23.88888888889 """ return (fahrenheit - 32.0) * 5.0 / 9.0
511075e1967edec7a4709955da1880e5648ecab8
630,597
def get_aws_env(args): """Returns a dictionary of AWS related environment variables based on command line args""" env = {} env_values = { "AWS_PROFILE": args.aws_profile, "AWS_ACCESS_KEY_ID": args.aws_access_key_id, "AWS_SECRET_ACCESS_KEY": args.aws_secret_access_key, "AWS_SE...
b15c5a4c30682d499488ad24ddfce17c293dfdf5
630,598
import torch def new_mdn_loss(pi, sigma, mu, target): """ Copied from : https://github.com/sksq96/pytorch-mdn/blob/master/mdn.ipynb """ m = torch.distributions.Normal(loc=mu, scale=sigma) loss = torch.exp(m.log_prob(target)) loss = torch.sum(loss * pi, dim=1) loss = -torch.log(loss) ...
edcc845cc8db55f2f51fd0a004d986a1043e1c46
630,599
import math def string_similarity(string1, string2): """ This implements a "cosine-similarity" algorithm as described for example in *Proceedings of the 22nd International Conference on Computation Linguistics* (Coling 2008), pages 593-600, Manchester, August 2008. The measure-vectors used i...
29871f6f5a0652937938fb4cb58a08be6e7e6d31
630,601
import mpmath def invcdf(p, mu=0, b=1): """ Laplace distribution inverse CDF. This function is also known as the quantile function or the percent point function. """ if b <= 0: raise ValueError('b must be positive.') with mpmath.extradps(5): p = mpmath.mpf(p) mu = ...
2a751e717ca76ff6b7abd42a93b2581fe8617580
630,602
def wrap_p(value): """ Adds enclosing <p> and </p> tags to value. """ return '<p>%s</p>' % value
2837535c081795553616927b75b803f04ddf6592
630,603
import json import requests def get_bolt_data(destination_coords, origin_coords): """ (tuple) -> response Get data about a trip using Bolt taxi """ prices = {} url = "***" payload = {'campaign_code': "", 'destination_stops': [ {'lat': destination_coords[0], '...
6e81f4aa356c81c00dc38f9142e509ec773459f9
630,604
async def api(): """Discoverable API by hitting root endpoint""" return { "links": { "datasets": "/datasets", "natural_earth_feature": "/natural_earth_feature", "viewport": "/viewport" } }
3f7eced51ab30e292216d6dda105fd24e4a65b53
630,605
def josephus(n, k): """ josephus(n, k) = (josephus(n-1, k) + k) % n josephus(1, k) = 0 After the first person (kth from beginning) is killed, n-1 persons are left So we call josephus(n-1, k) to get the position with n-1 persons. But the position returned by josephus(n-1, k) will consider the po...
51d8cac04aa85ba2fa43ea31473bc1388e38b4c7
630,606
def sub2indSH (m,n): """ i = sub2indSH(m,n) Convert Spherical Harmonic (m,n) indices to array index i Assumes that i iterates from 0 (Python style) """ i = n**2 + n + m return i
9700b78c8a06e58d207307e6b00f3948ba88e02b
630,607
from typing import Optional from typing import Match import re def is_attr_private(attrname: str) -> Optional[Match[str]]: """Check that attribute name is private (at least two leading underscores, at most one trailing underscore) """ regex = re.compile('^_{2,}.*[^_]+_?$') return regex.match(attrn...
cde57dd98a2eb4250a14d81438e8ffc056cb318c
630,608
def drop_constant_column(dataframe): """ Drops constant value columns of pandas dataframe. """ return dataframe.loc[:, (dataframe != dataframe.iloc[0]).any()]
cae8cc18e191a9373425ca679b8e152a5dd6e857
630,609
def parse_file_string(filestring): """ >>> parse_file_string("File 123: ABC (X, Y) Z") ('ABC (X, Y) Z', '') >>> parse_file_string("File 123: ABC (X) Y (Z)") ('ABC (X) Y', 'Z') >>> parse_file_string("File: ABC") ('ABC', '') >>> parse_file_string("File 2: A, B, 1-2") ('A, B, 1-2', '') ...
53bad5bcfed7ed66149a82bb5d604f6996c56bd0
630,610
import click def n_bins_option(**kwargs): """Get the number of bins in the histograms""" possible_strings = ["auto", "fd", "doane", "scott", "rice", "sturges", "sqrt"] def custom_n_bins_option(func): def callback(ctx, param, value): if value is None: value = ["doane"] ...
ea4e413dcdf352d432416209ac893d1cf3f637a7
630,611
import subprocess def _GetOutput(args): """Runs a subprocess and waits for termination. Returns (stdout, returncode) of the process. stderr is attached to the parent.""" proc = subprocess.Popen(args, stdout=subprocess.PIPE) stdout, _ = proc.communicate() return stdout.decode('UTF-8'), proc.returncode
b92953c50cd0ea7989b88d905893f3b666fe4a3f
630,612
def gram_matrix(x): """Computes the gram matrix of the input Parameters ---------- input : tensor The tensor to compute the gram matrix """ a, b, c, d = x.size() features = x.view(a * b, c * d) # For input matrices with large dimensions, the gram matrix # typically has large val...
d1138e0adc919707c19efdb758862a9e214f15e3
630,613
def VStack_Calc(N, Vcell): """ Calculate VStack. :param N: number of single cells :type N :int :param Vcell: cell voltage [V} :type Vcell:float :return: VStack [V] as float """ try: result = N * (Vcell) return result except TypeError: print( ...
886e66f79a852da0da748d49d9cf01c272138f74
630,615
def update_point(move, point): """Returns new point representing position after move""" moves = { '^': (0, -1), '<': (-1, 0), 'v': (0, 1), '>': (1, 0), } return (point[0]+moves.get(move, (0, 0))[0], point[1]+moves.get(move, (0, 0))[1])
da19f62445973cffd7c89c5dcbc56efe11170c0d
630,616
def positive_fft_bins(n_bin, include_zero=False): """Give the range of positive frequencies of a complex FFT. This assumes we are using Numpy's FFT, or something compatible with it, like ``pyfftw.interfaces.numpy_fft``, where the positive frequencies come before the negative ones, the Nyquist frequency...
9ecb8d4b879e8dec113a440ac4207863b88ca86b
630,617
def parse_ansi(ansi): """ Takes raw ansi code and returns 8-bit color code. """ _, raw_ansi = ansi.split("[") codes = raw_ansi.split(";") if codes[0] == "38" and codes[1] == "5": # if 8-bit ansi color code return color return int(codes[-1][:-1]) else: end_code = int(codes[-...
88fefce9a12426bfe14f59d107d57b538f848947
630,618
import math def ceil_day(tval): """ Find ceiling day """ return(math.ceil(tval/86400.0) * 86400.0)
91bc601ff69a2562d53b08b3b59d834a3d023938
630,619
def combi_to_int(s): """ use integer as index of a set """ i = 0 for x in s: i += 2 ** x return i
0212dbf3f092405fcf33bfba5aedbec3515f39aa
630,620
def get_risk_score(track, other): """ Get "risk" score between a track an another track. The "risk" evaluates how likely the two tracks are to be the same, lower being better, with 0 being a perfect match. This is a super handcrafted score, with little to no tuning, will probably not catch all possi...
4216a872c1c67aeb72002f9ce0dc03bc879e98dc
630,621
from typing import Optional import os def get_absolute_path_for_mounting(relative_path: str, mount_dir: Optional[str] = None) -> str: """Drone runs each job in a new Docker container FOO. That Docker container has a new filesystem. Anything in that container can read anything in that filesystem. To read f...
5118ed1fd03e459ab9dd79c5559c95acbe9afb49
630,622
import copy import math def convex_hull(points): """Returns the convex hull of a set of points. Parameters ---------- points : list A list of points for computing the convex hull. Returns ------- stack : list A list of points representing the convex hull. Exa...
9520b2432dd39c0676bc7da3a1121090a2f86adf
630,623
def fill_model( model, time_stop, time_step, initial_state, seed, n_points): """ Fill up model with output file and initial state and write it down in an input file Parameters ---------- model: str smoldyn model description time_stop: Float Simulation duration time_s...
778abce1319ca5c400d0c4a25f5b2ba6d759e508
630,624
import importlib def import_string(dotted_path): """ Import a dotted module path and return the attribute designated by the last name in the path. Raise ImportError if the import failed. """ module_path, attribute_name = dotted_path.rsplit('.', 1) module = importlib.import_module(module_path) ...
eb898d6c733ef6845bf50b4de7ed83beddcee894
630,625
import os def isValidVideoFolder(path): """A valid video folder must have \\groundtruth, \\input, ROI.bmp, temporalROI.txt""" isValid = os.path.exists(os.path.join(path, 'groundtruth')) and os.path.exists(os.path.join(path, 'input')) and os.path.exists(os.path.join(path, 'ROI.bmp')) and os.path.exists(os.pat...
c6ba3924b1022a4e392451c421d474a825f6e196
630,626
import networkx as nx def nxMarkovGraph(self, all_vars=False): """Get networkx Graph object of the Markov graph of the model Example: >>> G = nxMarkovGraph(model) >>> nx.draw(G) """ G = nx.Graph() G.add_nodes_from( [v.label for v in self.X if (all_vars or v.states > 1)] ) for f in sel...
ffa8edd26488b3403b98759689722ced9dcaa68c
630,627
from typing import Union import pathlib import tempfile import hashlib def _resolve_experiment_buffer( buffer_root: Union[None, str, pathlib.Path], exp_id: int, experiment_name: str, filter_string: str, ) -> pathlib.Path: """ Resolve the buffer root for a given experiment and filter string. ...
abab260348df035061d340779cf66d41c44b1a27
630,628
def dic_alk_scale(vs, DIC, alkalinity): """Redistribute change in DIC as change in alkalinity""" return {alkalinity: (vs.temporary_tracers[DIC] - vs.npzd_tracers[DIC][:, :, :, vs.tau]) / vs.redfield_ratio_CN}
a442ffaa0be919cc8754f47def58b8514d43662f
630,629
def get_message_type_from_message(message: str) -> str: """Parses the message_type from the message.""" return message.split(" ")[2].replace("\n", "")
94bd310785f3abce75e5cf7c7cb28eaabab561dc
630,630
import torch def generate_many_samples(model, num_samples, batch_size): """ Generate samples for likelihood estimation :param model: :param num_samples: :param batch_size: :return: samples """ size = 0 res = [] while size < num_samples: res.append(model.generate_samples...
de83784ef7dee31a043c59d00e116e66b372d0e4
630,631
import re import struct def GetFormatType(format_): """ Get format type and bitsize without prefix @param format_: format specifier @return: (format_, 0) or (format without prefix, bitsize) """ formattype = format_ bitsize = 0 if isinstance(format_, str): mat...
4f4cc9aa7dacbe766d93cee29e4b94f0b8ef9d8f
630,632
import re def strip_texcmds(tex): """Removes all tex or latex commands from a text-string. QUICK HACK: DO NOT RELY ON THIS! (MIGHT DELETE TOO MUCH in SOME CASES) """ return re.sub(r"\\\\\S+\s|\\\\\S", "", tex.replace("\\&", "&"))
ea525d7476dbb6cc473dbb0aa83397a25a08b044
630,633
import os def walkdir(rootdir, include="", exclude=None): """ Returns a list of files in all subdirectories with full path. :param rootdir: base path from which walk should start :param include: list of file endings to include only e.g. ['.py', '.res'] :return: list of files >>> walkdir("../s...
d185859f12864c13e3354c3bd5e6a5993afa51bd
630,636
def retrieve_parameters(monitor, gradients=False): """Retrieves the parameters of the model or their gradients :param monitor: either a training or evaluation monitor :param gradients: whether to retrieve the gradients instead of the values :returns: the values of the parameters (or gradients) for each...
c0a297c973c83a43a80ba21d3b1deff8ff09ec33
630,637
import itertools def score (board, draw): """Scores the bingo `board`, including the last `draw`.""" return sum(s for s in itertools.chain(*board) if s != 'x') * draw
47b1dfdfa5d7275d30920d70c0d549dbcd780279
630,638
def sum_mat_bins(mat): """ Compute the sum of matrices bins (i.e. rows or columns) using only the upper triangle, assuming symmetrical matrices. Parameters ---------- mat : scipy.sparse.csr_matrix Contact map in sparse format, either in upper triangle or full matrix. Re...
24b3140b6d2c5b74f03197144ceda6f72f7a6cde
630,639
import re def token_labels_from_treestring(s): """extract token labels from sentiment tree""" return list(map(int, re.findall(r"\(([0-9]) [^\(\)]", s)))
37e3f0ada8994116b627497176fd88804f54b3ae
630,640
def get_note( level2 ): """ Return the note of an event. Continuation lines concatinated to a single string.""" # Pre version 7.0 the note lines were short; requiring continuation lines. # # There are rules about adding spaces and not stripping spaces from continuation lines. # I'm not sure I'm han...
1c230654127f86dc0a8c8cc42de7e315bac70e00
630,641
def register_sql(spark, files, schema=None, sep=None, table_name="table", return_count=False): """ Register a list of files as a SQL temporary view. parameters: - files is overloaded: can be one file path or list of file paths. - spark: pyspark.sql.SparkSession - table_name: this is how we will...
f7f79211c2ad0dc8591dfdca7823e595f86ef035
630,642
from io import StringIO def print_sentence(s, acscore=True, lmscore=True, tscore=True, tscore_wip=False, wcount=False, lmwt=10.0, maxwords=None, wer=True): """Prints all sentence scores including acoustic, lm, overall, etc.""" output = StringIO() number_template = '{:8,.2f}' spaces ...
4361624570e2974ca7b58984807fd8bb17fbe5b6
630,643
def coloringToColorList(G, coloring): """ coloringToColorList(G, coloring) Calculate node colors based on an input graph and color dict. Parameters ---------- G : networkit.Graph The input graph. coloring : dict() Coloring scheme as dict. Returns ------- list(tuple(float, float, float)) List with col...
c78933a23f258232f01a027cbbb33e0f76fcfde4
630,645
import torch def get_ray_directions(H, W, focal): """ Get ray directions for all pixels in camera coordinate. Reference: https://www.scratchapixel.com/lessons/3d-basic-rendering/ ray-tracing-generating-camera-rays/standard-coordinate-systems Inputs: H, W, focal: image height, w...
71ed0146fc03630a38a10c0ed8b452e46a0a64f8
630,646
def generate_person(election_authorities): """ PURPOSE: generates person dataframe for .txt file INPUT: election_authorities RETURN: person dataframe SPEC: https://vip-specification.readthedocs.io/en/latest/csv/element_files/person.html """ # SELECT feature(s) (3 selected) person = elec...
8452bc323b8af8ead8f7cf1e43eaecd27d678f40
630,647
import os def get_image_size(cursor, image_id): """Obtain image dimensions :param cursor: cursor to postgres connection :param image_id: a valid image id :return tuple image_ids: (sizex, sizey, sizez) """ if image_id is not None: query_string = "select sizex, sizey, sizez from pixels ...
f615875e8f33bbdfb152ea81a05bf5d8a81cb081
630,648
def ast_make_expr(op, nodes, balance=True): """Create an ``Expr`` Node of type ``op``, with children given in ``nodes``.""" def _ast_make_expr(nodes): return nodes[0] if len(nodes) == 1 else op(nodes[0], _ast_make_expr(nodes[1:])) def _ast_make_bal_expr(nodes): half = len(nodes) // 2 ...
ef26e5a81d0156901b9aa2de3fd3540826d3b99b
630,649
import re def clean_speaker_name(text: str) -> str: """ Checks if the text starts with the pattern: [speaker name followed by colon] and returns a clean version of it by removing the pattern """ start_text, rest_text = text.split(": ", maxsplit = 1) start_tokens = re.sub(" +", " ", text).stri...
5aa5d2d477cc20a77c073e2131d8e41254782ab0
630,650
def check_crossing_lines(first_img, second_img, rectbegin, rectend, first_color, second_color): """Zwraca True jeśli na prostokątnym obszarze (rectbegin) X (rectend) na obrazkach first_img i second_img przecinają się linie o kolorach odpowiednio: first_color i second_color.""" # Ustawia prawidłowy prost...
ca4d3ef0bd5fec1df2e29c40eb242fdff8a655bc
630,652
def trace(a, offset=0, axis1=0, axis2=1, dtype=None): """ Returns the sum along diagonals of the array. If `a` is 2-D, the sum along its diagonal with the given offset is returned, i.e., the sum of elements ``a[i,i+offset]`` for all `i`. If `a` has more than two dimensions, then the axes specified ...
95f1549ca09c6bd6f38eec56f520e07077617e76
630,653
def to_dict(self, ignore_fields=()): """将一个model转换成一个dict""" attr_dict = {} for field in self._meta.fields: name = field.attrname if name not in ignore_fields: attr_dict[name] = getattr(self, name) return attr_dict
0e45fd8cb0be9eea2b6e0546cfba1e566bf00bfb
630,654
def openai(base_lr, num_processed_images, num_epochs, num_warmup_epochs): """ Learning rate scheduling strategy from openai/glow :param base_lr: base learning rate :type base_lr: float :param num_processed_images: number of processed images :type num_processed_images: int :param num_epochs:...
2ca1551ba3e0790c8f3e7d9457b7fa090ae5e4a0
630,655
def make_archive(entries, yargs): """Make an index (archive) page""" # title # subtitle/summary/abstract # last updated # keywords (under "category") docme = "---\ntitle: Archive | "+ yargs.feed_title+"\n---\n" for ue in entries[::-1]: e = ue[1] docme += "### [" + e...
19e9888cf69c4fcbcc135cdb5595732f2b42b473
630,657
def calculate_symmetric_kl_divergence(p, q, calculate_kl_divergence): """ This function calculates the symmetric KL-divergence between distributions p and q. In particular, it defines the symmetric KL-divergence to be: .. math:: D_{sym}(p||q) := \frac{D(p||q) + D(p||p)}{2} Args: ...
37793378b6b9020824d02dcc1707688404c55721
630,658
from dateutil import tz from datetime import datetime def fordtime_to_datetime(fordTimeString, useUTC=True): """Convert Ford UTC time string to local datetime object""" from_zone = tz.tzutc() to_zone = tz.tzlocal() try: utc_dt = datetime.strptime(fordTimeString, "%m-%d-%Y %H:%M:%S.%f") exc...
8aff092d60559f5fa8da8de7a430180b68b571a2
630,660
def create_obj(vertices, textures, normals, faces, filename=None): """ Create content of the OBJ file given the vertices, textures, normals, and faces. Args: vertices (list): list of vertices (for each corner of a triangular mesh) textures (list): list of textures normals (list): li...
30e07abcebc764889aef4e4bafa792c190fdca41
630,662
def transform_data(data_to_transform: list): """ Transforms data_to_transform from a 2d array to a 1d array Parameters ---------- data_to_transform: list the data which needs to be transformed Returns ------- new_data:list the transformed data """ new_data = [] ...
e9e38be008a7b603b20331dd912edcde9855ffa7
630,663
import torch def half_masker(batch_size, mask_shape, dim=0): """Return a mask which masks the top half features of `dim`.""" mask = torch.zeros(mask_shape).bool() slcs = [slice(None)] * (len(mask_shape)) slcs[dim] = slice(0, mask_shape[dim] // 2) mask[slcs] = 1 # share memory return mask.u...
5cac47871f1b22d44e306fc419d705ded54a9d6c
630,664
def clean_minmax(dic): """ Clean (set to zero) the MAX/MIN dictionary keys. """ # maximum and minimum values dic["FDMAX"] = 0.0 dic["FDDISPMAX"] = 0.0 dic["FDMIN"] = 0.0 dic["FDDISPMIN"] = 0.0 dic["FDSCALEFLAG"] = 0.0 # FDMIN/MAX not valid return dic
9947574eb54c1b54e59ae21d52370e29cacd6670
630,665
import torch def tanh(x: torch.Tensor) -> torch.Tensor: """Return torch.tanh(x)""" return torch.tanh(x)
f08460e1f2b53d565afbe29e37103d24efc6dccb
630,666
import sys import os import select def capture_cpp_cout(f): """ Executes the function f, without parameters, returns a tuple of (return of f, output written to cout) Solution found online: https://stackoverflow.com/questions/9488560/capturing-print-output-from-shared-library-called-from-python-with-ctypes...
bcb6d757308a28a0f3281f2afabc622e12387b43
630,667
import shutil def bam_tmp_file(bam_path, bam_tmp_path): """Return the path to a temporary small bam file""" shutil.copy(str(bam_path), str(bam_tmp_path)) return bam_tmp_path
69c5046e4c30b03c2f8f1b364bf8f5053df31026
630,671
def keywords_parser(keywords): """ EM : Converts the string input from the GUI to a list object of strings. """ # Remove spaces kwrds = keywords.replace(' ','') # Split at ',' to separate time windows, then keep non-empty words kwrds = [x for x in kwrds.split(',') if x] if kwrds: ...
710b4f3940f507898685979a4df94926a420947f
630,672
def cf_or(a, b): """The OR of two certainty factors.""" if a > 0 and b > 0: return a + b - a * b elif a < 0 and b < 0: return a + b + a * b else: return (a + b) / (1 - min(abs(a), abs(b)))
b2d5814065271c6982a4079e7e2176885fa15779
630,674
import re def remove_hanging_parenthesis(sample_string): """ Removes parenthesis at the end of strings. Args: sample_string (str): Input string Returns: str """ return re.sub(r"[^.*]\($", "", sample_string).strip()
23d4deb582973e209c5bb04f9b573c93997c7388
630,675
import subprocess def win32_mount(details): """ A function that mounts a new network file system on a windows OS """ try: persistent = 'yes' if details.persistent else 'no' win_path = '\\\\' + details.ip_address + '\\' + details.directory path = '//' + details.ip_address + '/' ...
f1baa629a1542cff81d89c420250abd6aac32dc9
630,676
def _lemma_extractor(tokens): """Turn an iterable of tokens into language model input. :param tokens: An iterable of tokens (see :meth:`tokenize` for the token representation). :return: An iterable of token identifiers of the form ``(<graphic lemma variant>, <phonetic lemma variant>)``. "...
3d251303d70d045964718dba6ebf6c3643e4588b
630,677
def isWord(wordList, word): """ Determines if word is a valid word. wordList: list of words in the dictionary. word: a possible word. returns True if word is in wordList. Example: >>> isWord(wordList, 'bat') returns True >>> isWord(wordList, 'asdf') returns False """ wo...
ffead901ccc10797928c966b14cf4c2ac3f7f558
630,678
def color_to_hex(color): """ Converts a (R, G, B) tuple into a hex color string. """ return "#" + "".join('{:02X}'.format(x) for x in color)
60fe5c30fbf9bee81a225c027f564e3be9f891ee
630,679
import os def prep_paths(db, category): """ Creates paths in the filesystem and return the path names """ path1 = 'output' path2 = '{}/{}'.format(path1, db) if category: path2 += '__' + category for path in [path1, path2]: try: os.mkdir(path) except OSEr...
40c6adbc303a04de6ad6fa82f75ad60491329976
630,680
def oscale(l): """Convert from 0.0-1.0 in linear gamma to gamma table format (0-1023 gamma 2.2)""" omax = 1023 out_gamma = 1/2.2 if l < 0: o = 0 else: o = (l ** out_gamma) * omax oi = int(round(o, 0)) if oi >= omax: oi = omax return oi
f01245c8970de3a4b3a0ccea402398f6149da2f7
630,681
import re def assets_from_string(text): """Correctly split a string containing an asset pair. Splits the string into two assets with the separator being on of the following: ``:``, ``/``, or ``-``. """ return re.split(r'[\-:/]', text)
250d57bd524d2090042058a5ce142340340c0f44
630,683
def get_min_rooms(lectures): """ Given an array of start and end times for lectures, find the minimum number of classrooms necessary. """ starts = sorted(start for start, _ in lectures) ends = sorted(end for _, end in lectures) num_rooms = 0 current_overlap = 0 start_idx, end_idx = ...
157f870ef7c83d1f4b5038ec0c5b0d5dded949cf
630,684
def _axis_label(label, unit=None): """Return a formatted label with units.""" return f"{label} / ({unit})" if unit not in [None, ""] else label
e9f2fc801a60f99fb2ce7ad8d4d69f8b4936b240
630,685
def read_default(field): """ Read the default value otherwise return an empty string. :param field: field to get the default value if exists :type field: rosidl_parser.definition.Member :returns: dictionary with the compact definition (constanst and message with links) :rtype: dict """ ...
c2d3f1fc564bd34d7bf082ce7f7c57d7e8ef896c
630,686
def make_label_target_explicit(label): """Takes a label with a potentially implicit target name, and makes the target name explicit. For example, if the label is "//path/to/pkg", this macro will return "//path/to/pkg:pkg". If the label is already in the latter form, the label will be returned unchanged. ...
cb3a1c6f622605ae77eb18f8e869b807f2b96489
630,687
def cents_to_frequency(cents): """Converts cents to frequency in Hz""" return 10 * 2 ** (cents / 1200)
b1f6ed12ff5b8c94205eaa150188b9163b62b5a3
630,688
def findRelativeRanks(self, nums): """ :type nums: List[int] :rtype: List[str] """ new_num = nums[:] num_dict = {} for i, v in enumerate(sorted(nums, reverse=True)): num_dict[v] = i + 1 return ["Gold Medal" * (num_dict[item] is 1) or "Silver Medal" * (num_dict[item] is 2) or "Br...
11ee750baba42b97fe8a6b71246f8a612208d9e7
630,689
import functools def needs_connection(f): """ Sets up the conn member of the Command object upon calling this method. If this decorator is specified *inside* (after) ``@wet_method``, the connection will not be established upon dry run. """ @functools.wraps(f) def g(self, resource_handler,...
825af699a2c969e0d9f3e4faa8952bbf12fd42e6
630,690
def assign_veh_to_roads(x,veh_list): """Assign terrain as flat or mountain to national roads Parameters x - Pandas DataFrame of values - dia_hinh__ - String value of type of terrain Returns String value of terrain as flat or mountain """ veh_no = 0 road_no = str(x.r...
08d2ef48f6cf16811e2eb3b24c93b44bbd168b3c
630,691