content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def contain(descriptors, target_descriptor): """Check if the target descriptor is in the descriptors.""" for descriptor in descriptors: if edit_distance(descriptor, target_descriptor) < 1e-5: return True return False
5afc51540c681a6c85c4d2992ca9f035405b98e9
41,800
def remap(im, coords): """ Remap an RGB image using the given target coordinate array. If available, OpenCV is used (faster), otherwise SciPy. :type im: ndarray of shape (h,w,3) :param im: RGB image to be remapped :type coords: ndarray of shape (h,w,2) :param coords: target coordin...
7aa8ef71703dd8cf1229b04239ac32112f3be2d9
41,801
import time def epoch_time(offset=0): """Returns time since epoch.""" try: return time.time() - offset except TypeError as e: LOG.error("Couldn't reduce offset, %s, from epoch time, ex %s.", offset, e) return time.time()
6eb8604d2897b18a7e448f7bb3d40f5d1c04e7fc
41,802
def init_device(n=0): """ Initialize a GPU device. Initialize a specified GPU device rather than the default device found by `pycuda.autoinit`. Parameters ---------- n : int Device number. Returns ------- dev : pycuda.driver.Device Initialized device. """ ...
c328072bb3d6879a584f39b106dc0cff85a0dbc5
41,803
import ast def _visit_local(gen_sym, node, to_mangle, mangled): """ Replacing known variables with literal values """ is_name = type(node) == ast.Name node_id = node.id if is_name else node.arg if node_id in to_mangle: if node_id in mangled: mangled_id = mangled[node_id]...
26bd532d8f3c73cd25395a4982aff63e75fdc5ac
41,804
def pathtoPath(svg): """Converts SVG("path", d="...") into Path(d=[...]).""" if not isinstance(svg, SVG) or svg.t != "path": raise TypeError, "Only SVG <path /> objects can be converted into Paths" attr = dict(svg.attr) d = attr["d"] del attr["d"] for key in attr.keys(): if not i...
18d9e04f7aa582922eba5878a1162bef8930b11c
41,805
def zenodo_doi_metric(mocker, zenodo_doi_index_html, zenodo_doi_june_html): """Fixture for COD records metric instance.""" prefix = '10.5281' def load_index_data(self, url): return zenodo_doi_index_html def load_stats_data(self, url): return zenodo_doi_june_html mocker.patch.objec...
8ff6ab22d59d35db7e1d4dedc389476451f633da
41,806
def convert_shape_to_list(shape): """ Convert shape(list, tuple, variable) to list in imperative mode """ if isinstance(shape, (list, tuple)): shape = list( map(lambda x: x.numpy()[0] if isinstance(x, Variable) else x, shape)) else: shape = shape.numpy().a...
1c3174dcabe7048c6197487f4f3a92c606659ab1
41,807
def get_longest_key(tuple_of_tuples): """ Why is this needed? Because sometimes we want to know how long a CharField should be -- so let's have it as long as the longest choice available. (For example, when we have a radio button and we want to store a single value.) INPUT=( ('short', 'blah...
a0a55ced79bb6e27edb82790ee7ea4d1c1efc3c7
41,808
def mass_within_region(gals, x_bound, y_bound): """ Calculate the total mass and number of galaxies within a specified region. Parameters ---------- gals: list of ``Galaxy`` class instances. Galaxies that we're calculating the mass for. x_bound, y_bound: [float, float] The min...
b9d1564a88239ab33402255c44646101f8116060
41,809
import os import time def submit_and_download(report_request, api_client, data_dir, data_file, overwrite_if_exists, decompress: bool = False): """ Submit the download request and then use the ReportingDownloadOperation result to track status until the report is complete. Id the file already exists, do...
2fe0c4abfe870a7c34cac07d0aad235e1d797ae3
41,810
def getSNR( flmfile, wsig=100, wnoise=500, plot=False ): """ Estimates the average S/N ratio for a spectrum. <wsig>: the smoothing window used to estimate the signal (A) <wnoise>: the smoothing window used to average the noise (A) """ d = np.loadtxt( flmfile ) d = d[ ~np.isnan(d[:,1]) ] ...
862be41f4c2930bbe81a85545349a569556ab06b
41,811
def splitCentersByStrips(centers, splitter_array): """ Split list of note centers by strip. """ # Sort by rows row_sorted_centers = sorted(centers, key=lambda x: x[1]) # Split notehead into strips strips = {} current_offset = 0 counter = 0 for i in range(1, len(splitter_array) +...
9ae82e74f12e298f1a1924883db66e11cb86d0fc
41,812
from typing import Union import requests def uploaded_images_list(skill_id: str, oauth_token: str, raw: bool = False) -> Union[dict, requests.Response]: """ Get uploaded skill images :param skill_id: alice skill id :param oauth_token: oauth token :param raw: return raw api response :return: u...
2628a47b0300c4e8fc84692afbf646a2f4475f1d
41,813
def make_trip_geometry(start_station_num: int, end_station_num: int): """ Takes 2 stations and returns a linestring between them. """ start_point = find_station_geo(start_station_num) end_point = find_station_geo(end_station_num) try: return LineString((start_point, end_point)) exc...
97fd3a43734f216f6e20a301d691ca81dbe797a6
41,814
def wiener(frame_matrix, hop_size, window_type, noise_est, original_signal_length): """ Return the enhacned signal after Wiener filtering """ # Setting initial variables frame_length = len(frame_matrix) fftlen = int(np.around(frame_length / 2) + 1) hwin = getWindow(frame_length, window_type...
092085142468c9dc2a07c6c806734dafaf224bcc
41,815
import math def normalize_to(target, source=1): """ Multiplies the target so that its total content matches the source. :param target: a tensor :param source: a tensor or number :return: normalized tensor of the same shape as target """ return target * (math.sum(source) / math.sum(target))
c9f7ae4bf67b50f72877f1c090c1249f7a6c378a
41,816
def get_category(): """ Gets a Category --- tags: - category parameters: - name: name in: query schema: type: string description: The name of the category. - name: sponsor in: query schema: type: string...
14e228770b94fa54eb860d443dd3085ff14fa9a5
41,817
def LAHC_search_loop(): """ Search loop for Late Acceptance Hill Climbing. This is the LAHC pseudo-code from Burke and Bykov: Produce an initial solution best Calculate initial cost function C(best) Specify Lfa For all k in {0...Lfa-1} f_k := C(best) First itera...
a4beb9080ebda70ba1ea1b4a928127351327b69b
41,818
def string_to_nonstopword_counter(text, lowercase=True): """Converts string to util.Counter of non-stopwords in text string. Args: text: The string to process. lowercase: Whether the convert the words in the string to lowercase. Returns: util.Counter object containing counts of non...
ecd479f116833a2c78e1ac48b0724ed6cbeccc13
41,819
def plot_bad_chs_group_summary(bad_ch_info, ch_names): """ Makes a summary plot of bad channels across all subjects including: - heatmap of channels by subject indicating if channel was marked bad - Bad channel % for each participant - % of subjects with channel marked bad for each subje...
9946e13667473f87baeb36918ac7396f6e80dfd7
41,820
def submit_entry(contest, code): """submits an entry to the submission. """ return _update_sketch(contest, code, action="submit")
ded28cfb87ca1031002acea28d66c9c131f70a33
41,821
def gndvi(image): """ Takes an image and processes it using GNDVI. Returns a single channel grayscale scaled output. :return: """ # using array slicing to split into channel green = image[:, :, 1].astype(np.float32) NIR = image[:, :, 2].astype(np.float32) imgOut = (NIR - green) / (NIR +...
a4a0818ce720e159b79b5f178aba8fb6127ae10a
41,822
import json def read_status(path="status.json"): """ opens the written status file in case of restarts that we do not start with an empty status file. If there is no file, create empty status dict :path: str :returns: dict """ try: with open(path, "r") as jsonfile: ...
d44529230a6fa39d9655425508f968220d6fb67e
41,823
import urllib import json def get_my_ip(): """Obtain external visible IP address""" url='https://api.myip.com' response = urllib.request.urlopen(url) if response.status != 200: raise Exception(f'Unable to obtain this hosts public IP, got HTTP status {response.status} from {url}') doc = js...
c6418ddd1c53618456aa49d28c5852c2faa50f45
41,824
import pprint def create_airport( id=None, type=None, altitude=None, name=None, city=None, municipality=None, region=None, country=None, iata=None, icao=None, ident=None, local_code=None, latitude=None, longitude=None, ): """ Get or create an Airport. ...
25330fda9074124c594296b2b56104f169c39672
41,825
def tags_match(blacklist_entry, tags): """ Returns true if the filename in <blacklist_entry> contains a tag in <tags>. """ try: blacklisted_file = blacklist_entry.split()[0] except IndexError: # Empty line return False try: _, tag, _, _ = datman.scanid.parse_file...
e0357b33450a7f7da3d45618b99af470c7cec9bb
41,826
def get_rawdir(): """ Returns the standard raw data directory """ workdir = get_workdir() rawdir = ut.truepath(join(workdir, '../raw')) return rawdir
97f23111506213dff48346783a7af2dd94d12949
41,827
def write_ellipsoid(sz, loc, mat, cut_neg=[-1, -1, -1], cut_pos=[1, 1, 1], cut_global=[1,1,1], orPhi=0.0, orTheta=90.0, uvecs=[], pols=[], eps=1.0, mu=1.0, tellegen=0.0): """ @brief Writes an ellipsoid. @param sz [size u_vec 1, size uvec 2, size uvec 3] @param loc locati...
2c6d332737020c092ba3366bebbbbd7c1ef6ea87
41,828
def get_json_for_r_log_entry(req, x_set): """Returns a dict used to match r_log entries returned through API.""" return { "request": req.to_dct(), "x_set": x_set }
989650af29c25f3d11346945d905d48af6718d25
41,829
def parse_segment(input_seg): """ Creates an asrtoolkit segment object from an input gk segment :param: input_seg: dict (segment-level dict: input_data['segments'][i] -> dict with keys 'channel', 'startTimeSec' etc mapping to attributes :return: asrtoolkit segment object """ extracted_dict...
8d2166536bf1faf1828d62a1f5e824b6c08773da
41,830
def read_vcf(input_file,output_file=None): """ Usage: [arg1]:[Input File] [arg2]:[Output File - Optional Parameter (The return dataframe will be written to csv if output path is specified)] Description: Reads the vcf file and returns the name, phone numbers and email as DataFrame Returns: [Dataframe of ...
609a58600acbf727580f5f9d0fa74d1f26f36f0c
41,831
def _get_sub_types_of_compositional_types(compositional_type: str) -> tuple: """ Extract the sub-types of compositional types. This method handles both specification types (e.g. pt:set[], pt:dict[]) as well as python types (e.g. FrozenSet[], Union[]). :param compositional_type: the compositional type ...
4fb1e67f8b6db717ccdf8c33e0b2458baf98c661
41,832
import os import pickle import sys def spimi(CHUNK_SIZE, out_dict, out_postings): """================================================================== open up every file opening file DOES NOT loading file contents into memory ==================================================================""" ...
4f863d46f7d41c105e8a425500e5bdda385835eb
41,833
import timeit import logging def test_find_redundant_constraints(verbose=False, show_timing=True, n_runs=1000): """Tested against results of LP method in section 3.2 of [1]. [1] S. Paulraj and P. Sumathi, "A comparative study of redundant constraints identification methods in linear programming problems,...
8d509ce544e4b2ed73c2f0bf02f0c3e350e7492e
41,834
import sys def find_python(version, path=None, required=True): """ :type version: str :type path: str | None :type required: bool :rtype: str """ version_info = tuple(int(n) for n in version.split('.')) if not path and version_info == sys.version_info[:len(version_info)]: pyth...
6504fd6b3541f4a0373f0b070e8421e423c471a3
41,835
import random def unsort(list): """Return a copy of unsorted list""" new_list = [] for chance in range(len(list)): char = random.choice(list) list.remove(char) new_list.append(char) return new_list
249a61de0de500305bd9f1fe54ea7ac8f2d07d84
41,836
def sample_account(user, **params): """Create and return a sample customer""" defaults = {} defaults.update(params) return Account.objects.create(user=user, **defaults)
eca2423fa56d0ba015452ebd14e11914cdf0c669
41,837
def gitupdate(request): """ DEPRECATED This could be reinstated by changing the Git directory seen below. """ if request.method == 'POST': try: g = git.cmd.Git("/home/ubuntu/seads-git/ShR2/") g.pull() return HttpResponse(status=200) except: re...
0ec22c9fb96a101800a10a8e0ade96048a1bf35e
41,838
def _coverage_loss(attn_dists, padding_mask): """ Calculates the coverage loss from the attention distributions. args: attn_dists: the attention distributions for each decoder timestep. A list of length max_dec_steps containing shape (batch_size, attn_length) padding_mask: sha...
cdeb4218317b3d8280b4a4f73b8e40fc95bed0f6
41,839
import sys def alpha_083(code, end_date=None, fq="pre"): """ 公式: (-1 * RANK(COVIANCE(RANK(HIGH), RANK(VOLUME), 5))) Inputs: code: 股票池 end_date: 查询日期 Outputs: 因子的值 """ end_date = to_date_str(end_date) func_name = sys._getframe().f_code.co_name return JQDat...
abe3e01b146418dbcb44fb20b797cabb19773ef0
41,840
def make_hop_info_from_url(url, verify_reachability=None): """ This is a factory function to build HopInfo object from url. It allows only telnet and ssh as a valid protocols. Args: url (str): The url string describing the node. i.e. telnet://username@1.1.1.1. The protocol, username...
c377fdcc4955afd0aceca7d448e5c890f3f70fdf
41,841
def sample_q0(V, lmd, d0, z0): """ Inputs: V: double (n_dofs,n_dofs) eigenvectors of covariance matrix lmd: double, (n_dofs,) eigenvalues of covariance matrix d0: int, dimension of the low dimensional subspace z0: int, (d0,n_sample) Gaussian random...
938aa9d22bdada72e5f244baa7b80f4b3b4b7d29
41,842
from pathlib import Path def raster_to_xarray(fpath, chunk_scale=2): """Read raster image into an xarray.DataArray. Using the `chunks` keyword in the open_rasterio method activates the return of an out-of-memory virtual array instead of the in-memory xarray.DataArray fpath: pathlib.Path, str ...
0eda3d569ac93cf2e5362fcd2c1147ade1a54b9d
41,843
def count_lines(file): """Given a file, returns the number of lines it contains. The current file position should be preserved as long as the file supports tell() and seek().""" old_position = file.tell() file.seek(0) count = 0 while file.readline() != '': count += 1 file.seek(ol...
53c1578d96f7bf031c4a8a5131739e36d35be5e7
41,844
def loads(data): """Loads the json data""" try: data = loader(data) except Exception: data = loader(data.decode('utf-8')) return data
d8082a8007f1710ca407647cb9de715ffd54f9a9
41,845
def getImageExplanation(response): """gets photo explanation Args: response (Dict): Custom response from NASA APOD API Returns: String: image explanation """ explanation = response['response_data_raw'][EXPLANATION_PARAMETER] return explanation
acff2646d5ff68714e5794d1e238a2314c1f2cb6
41,846
def latency(session, policy_name, policy_display_name, interval, service, return_type=None, **kwargs): """ Retrieves details of storage policy latency over time :type session: zadarapy.session.Session :param session: A valid zadarapy.session.Session object. Required. :type policy_name: str :p...
d31a6bead7cbcb6ddbebe8b067be47589aeab494
41,847
def np_soften_probabilities(probs, epsilon=1e-8): """Returns heavily weighted average of categorical distribution and uniform. Args: probs: Categorical probabilities of shape [num_samples, num_classes]. epsilon: Small positive value for weighted average. Returns: epsilon * uniform + (1-epsilon) * pro...
33b8f2d1ae821b0feb0b5353dc9727834d9b0a07
41,848
import subprocess def __get_commit(): """ :return: git commit ID, with trailing '*' if modified """ p = subprocess.Popen(["git", "rev-parse", "HEAD"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=__sct_dir__) output, _ = p.communicate() status = p.returncode ...
56f8174ad96aafdfb2c6f487792415af44b9841f
41,849
def cite(): """Returns BibTeX citation for the dataset.""" return """@misc{stackoverflow2019, title={TensorFlow Federated Stack Overflow dataset}, author={The TensorFlow Federated Authors.}, year={2019}, }"""
b156145455d1f9c69f612bcf9958f1d49fc94137
41,850
def calc_aqi(value, index): """ Calculates the corresponding air quality index based off the available conversion data using the sensors current Particulate Matter 2.5 value. Returns an AQI between 0 and 999 or None if the sensor reading is invalid. See AQI_BREAKPOINTS in const.py. """ if...
95f699e4bccd4dbe6a69adbe216cdda817f2505c
41,851
import os def update_block_relation(relation_df, parent_folder, block, new_folder, sep="/"): """Replace the old folder names by the new folder only to the paths where the block appears""" relation_df.loc[relation_df["Path"].str.endswith(block), "Path"] = relation_df.loc[ relation_df["Path"].str.endsw...
935ced0b26515c766108649e06a9df4c6198989c
41,852
import astropy.units as ur import astropy.constants as cr import numpy as np from .zodi import load_zodi def bgd_sky_rate(**kwargs): """ Loads the zodiacal background and normalizes it at 500 nm to a particular flux level (low_zodi = 77, med_zodi = 300, high_zodi = 6000), which are taken from a paper ...
5f42c4fb49a42d7cd7b8d07367f2ded78060e10f
41,853
def se3_to_transform(transform_nparray): """ convert 4x4 SE(3) to geometry_msgs/Transform Args: transform_nparray (np.array): 4x4 SE(3) Returns: transform (geometry_msgs/Transform): ROS transform of given SE(3) """ pos = transform_nparray[:3, 3] quat = t.quaternion_from_matrix(...
0bed2e49a62d5ba2e265dde67c1aa5821791e765
41,854
import torch def trainer( model, criterion, optimizer, trainloader, validloader, epochs=5, verbose=True ): """Simple training wrapper for PyTorch network.""" train_loss, valid_loss, valid_accuracy, train_accuracy = [], [], [], [] for epoch in range(epochs): train_batch_loss = 0 train_...
bbab3b3358ecb8c0a08e307f678afc66395665ab
41,855
def create_random_code(chars=AVAIABLE_CHARS): """ Creates a random string with the predetermined size """ return "".join( [choice(chars) for _ in range(SIZE)] )
86402c28f330adbced26d78eda855a5bbc01fcfd
41,856
def __improve_cluster_tasks_info(cluster_name): """Get more infomation for a list of tasks of a cluster.""" tasks = ecs_facade.get_all_tasks_cluster(cluster_name) return __improve_tasks_info(cluster_name, tasks)
dd7351cd317f49269e0c59da943058f9be7d1f78
41,857
def multi_fit_coef(t_, h_, bs_, lew_, tes_): """ Calculate scattering correction for height time series. The correction is given as a linear combination (multivariate fit) of waveform parameters. The correction time series is obtain in two steps: 1) Fit the coefficients to the differenced/detr...
02eaebe0e6da133f0b4d854a76106a6f6d98ae61
41,858
def locate(E,K,L1,L2,MM,OMEGA,model): """ Args: E: input orbit energy K: input orbit kappa (normalized angular momentum) L1: radial frequency integer L2: azimuthal frequency integer MM: pattern frequency integer OMEGA: pattern frequency model: input spherical model, see cl...
2de61727c8141eb86e3c1b6b3e15f409fdc5c30d
41,859
def instantiate_feature(feature_name: str): """ @param feature_name: The feature to instantiate """ log.info('Loading feature {} ...'.format(feature_name)) if feature_name == 'lm': feature = LanguageModel() elif feature_name == 'deep': feature = DeepExtractor() elif feature...
d6d6a89df2858523ab8c9afa68386fa692330c8d
41,860
def load(request): """Renders the about page.""" assert isinstance(request, HttpRequest) return render( request, 'app/load.html', context_instance = RequestContext(request, { 'title':'System LA (Average Load)', 'message':'On this page you can see the a...
b4ddf8cf0ba540128d2f05be1e8b4dd685e476f7
41,861
def look_at(eye, center, world_up): """Computes camera viewing matrices. Functionality mimes gluLookAt (third_party/GL/glu/include/GLU/glu.h). Args: eye: 2-D float32 Tensor (or convertible value) with shape [batch_size, 3] containing the XYZ world space position of the camera. center: 2-D float32 ...
5277035d33862133949b80c068b3b2e32ff9f38c
41,862
import time def create_file(n,m,filename='DataBlock'): """Create a scratch file of a given size. :param n: size of block :param m: number of blocks :param filename: desired filename :returns: time to allocate block of size n, time to write a file of size m*n :rtype: tuple """ t1=time...
9be5be472f5c4c3127341f473d121ff91d1dd55b
41,863
def join_apply(df, func, new_column_name): """ Join the result of applying a function across dataframe rows. This method does not mutate the original DataFrame. This is a convenience function that allows us to apply arbitrary functions that take any combination of information from any of the colum...
474fc3628d7f4066f33154df78ac945a72e8166f
41,864
def solve(task: str) -> int: """Find the biggest connected component in graph.""" connections = process_data(task) nodes = process_nodes(connections) return len(nodes["0"])
c20fc45b31241329b5f62536759fbaf62bbf5c4e
41,865
import threading def is_main_thread() -> bool: """ Check if we are in the main thread. """ return threading.main_thread() == threading.current_thread()
1f91ae9e2d5b395cd995efcc2f87002ade53e6a9
41,866
def get_z_icp(x_prev, transf): """ Apply transformation matrix from icp to previous pose to get measurement """ pose_new = x_prev[0:3] + transf[0:3, 3] pose_head = np.array([np.cos(x_prev[3]), np.sin(x_prev[3]), 0])[np.newaxis, :] transf_se3 = SE3(rotation=transf[0:3, 0:3], translation=np.zeros...
c6f358a01a0a82b19f83e2b80f15b27ab0b3140c
41,867
def _validate_target_url(url): """Only accept URLs that are basic. No query, fragment or embedded auth allowed""" if not isinstance(url, str) and not isinstance(url, unicode): return False p = urlparse.urlparse(url) if p.scheme not in ('http', 'https'): return False if p.query or p.f...
a40833aaa38209379ed98b2014d33f7d4086b018
41,868
def open(name=None, mode='rb', fileobj=None): """ Open an RPM archive for reading. Return an appropriate RPMFile class. """ return RPMFile(name, mode, fileobj)
f02d5ae410ca0482cbaeb9e4a1d57fe2ec6c4771
41,869
def MoveInDirection(square, direction): """ Returns the given square moved in the given direction. """ (x, y) = square if direction == UP: return (x, y-1) elif direction == DOWN: return (x, y+1) elif direction == LEFT: return (x-1, y) elif direction == RIGHT: return (x+1, y)
c6eddd8d4caf209150e5531e8a61de0e2827d2d8
41,870
def remove_small_blobs(img, threshold=1, debug=True): """ Find blobs/clusters of same label. Only keep blobs with more than threshold elements. This can be used for postprocessing. """ # Also considers diagonal elements for determining if a element belongs to a blob # mask, number_of_blobs = ndi...
7e5ce4f6807190e28c8406477e1899f8891e7545
41,871
from typing import List from typing import Tuple def fast_text_prediction_to_language_code(res: List[Tuple[str, str]]) -> List[str]: """Convert fastText language predictions to language codes""" labels, _ = res return [tmp[tmp.rfind("_") + 1 :] for tmp in labels]
3a39c3d416b4f66d1519284496fbaab940b202fc
41,872
def _format(src, language, class_name, md): """Inline math formatter.""" return '<span class="lang-%s %s">%s</span>' % (language, class_name, src)
6c6d47e41569d07092085aa2f009663641035c8a
41,873
import types def check_foreign_key_required( *, fk_spec: types.Schema, fk_logical_name: str, model_schema: types.Schema, schemas: types.Schemas, ) -> bool: """ Check whether a foreign key has already been defined. Assume model_schema has already resolved any $ref and allOf at the obje...
8b090293f64864117982b9092975295e6aa4f583
41,874
def load_config(config_file, schema, postprocessing=None, retain=None, drop=None): """ Loads a configobj-type configuration file. It is also possible to specify an application-specific postprocessing function which has three arguments: the configuration object and the warnings and errors lists. Thes...
09b0eba99f86e0a55d74734c09ec90b8ad00de0b
41,875
def fizz_buzz(n): """Returns fizz when divisible by 3 Returns buzz when divisible by 5 and fizzbuzz if divisible by both 3 and 5""" if n % 3 == 0 and n % 5 == 0: return 'fizzbuzz' elif n % 3 == 0: return 'fizz' elif n % 5 == 0: return 'buzz'
0ebdda7174f77b66d4f61ac59b24508f266d6ccd
41,876
def partition_spline_curve(alpha): """Applies a curve to alpha >= 0 to compress its range before interpolation. This is a weird hand-crafted function designed to take in alpha values and curve them to occupy a short finite range that works well when using spline interpolation to model the partition function Z(...
c41eb6168d268b8b301becfaa89ad058a7e533aa
41,877
def get_sector(fn): """Figure out the label to associate with this file, sigh.""" # NB nc.source_scene is not the region of view tokens = fn.split("-") s = tokens[2].replace("CMIP", "") return SECTORS.get(s, s)
f13b6d36bdcf37889e8550ce2abbfa4aa992ec4b
41,878
def redirect_with_error(msg: str, url: str = '/') -> Response: """"Redirect to specific URL, flashing an error message.""" log_web_event('Error redirect to %s with flash message: %s', url, msg) flash(msg) return redirect(url)
4a2e82ca2d0a1971c86a490fb7aa6e0a7c6948a8
41,879
def get_engine_conf_file(sensor): """ return the corresponding configuration file for passed in sensor (engine and version) also returns the variables (stripped out from config) """ # user's browser should be making request to dynamically update 'coverage' submission page try: conf_file...
7ee9b24a71abdcbfd1929c93df175cf00bb57c0c
41,880
import os def _fetch_surf_fsaverage5_sphere(data_dir=None): """Helper function to ship fsaverage5 spherical meshes. These meshes can be used for visualization purposes, but also to run cortical surface-based searchlight decoding. The source of the data is downloaded from OSF. """ fsaverage_...
20006159b418dc85c990ed0ac1627727754be298
41,881
def get_candidates(simi): """ Get best translation pairs candidates. """ knn = '10' assert knn.isdigit() knn = int(knn) average_dist1 = get_nn_avg_dist(simi, knn) average_dist2 = get_nn_avg_dist(simi.T, knn) score = 2 * simi score = score - average_dist1 - average_dist2 retur...
7fbfa186d376397b942a037875db5bcc7f5e985c
41,882
def memoize(func): """Memoize given function.""" cache = {} def _wrapper(*args, **kwargs): # serialize argument list to a string key key = repr(args + KWARG_MARK + tuple(sorted(kwargs.items()))) if key not in cache: cache[key] = func(*args, **kwargs) return cache...
13c32e1717c325eaf8ed62ef3dd5868343091bc4
41,883
def validation(plags, psr, src_offsets, susp_offsets, src_bow, susp_bow, src_gap, src_gap_least, susp_gap, susp_gap_least, src_size, susp_size, th3): """ DESCRIPTION: Compute the similarity of the resulting plagiarism cases from extension. In case of being below certain threshold extension is applied again with...
3931d17ce50179152d9297f2d981204ed477d304
41,884
def default_create_container_arguments(local=True): """Get set of arguments which would create first known distribution.""" distro_config = list(available_distributions())[0] arguments = ("distro", "release") config = {k: v for k, v in distro_config.items() if k in arguments} # We must force local ...
1e6633b26ebc3b4dfc688b82689166a897ec8352
41,885
def logout(): """ Logs a user out of their profile. Clears the user id from the current session and redirects to the home page. Returns Login Page: Redirects to login page. """ session.clear() flash('See you again soon!') return redirect(url_for('.login'))
7adb4627e96ea2ddfce8c9f85da2c29bd5492138
41,886
from datetime import datetime import pytz def _parse_formatted_date_range(date_range_str): """ Parses a string representing a date range (e.g.: "May 1, 2020 - Jan 30, 2021") Args: date_range_str (str): A string representing a date range Returns: Tuple[datetime.datetime, Optional[date...
4c34834bd69019a47f25263b538a9202e21afea0
41,887
import random def _gevent_blocking_call(gce_service, project_id, response, polling_interval: int = DEFAULT_SLEEP_TIME): """ polling_interval is seconds """ status = response['status'] attempt = 0 max_sleep_time = 5000 while status != 'DONE' and response: ...
24c0d410115209a4c3678e5fb84054025411bc32
41,888
def get_document_segmentation_details_url( document_id: int, project_id: int = KONFUZIO_PROJECT_ID, host: str = KONFUZIO_HOST, action='segmentation' ) -> str: """ Generate URL to get the segmentation results of a document. :param document_id: ID of the document as integer :param project_id: ID of t...
de5c5242b4578a4b7f86b6e590ffcf7fd1fe2db1
41,889
import os def get_file_size(file_path, h=True): """获取文件的大小 :param file_path: 文件路径 :param h: 是否human可读 :return: {'value': 数值,'measure': 单位,'str': 字串} """ # file_path = unicode(file_path, 'utf8') org_fsize = os.path.getsize(file_path) res_info = file_num2size(org_fsize, h=h) return ...
8b51617ebd4b70269d165401312ce3f86f7652a9
41,890
def checkout_shipping_price( checkout: "Checkout", discounts: "DiscountsListType" = None ) -> "TaxedMoney": """Return checkout shipping price. It takes in account all extensions. """ return get_extensions_manager().calculate_checkout_shipping(checkout, discounts)
f01269af90f3c592caa6b5e0a16b751619ee3930
41,891
def get_metrics(event): """Returns all OPRs, DPRs, and CCWM's from event in a dictionary event: event key (e.g. 2020mdbet)""" return tba_session.get(BASE_URL + '/event/%s/oprs' %event).json()
892699f57aa0740fcbcf087d6aecefc5a0749bbc
41,892
import os def document_process_change_status(request, document_request_id): """Change document status from process to get. Args: request: URL request document_request_id: Document ID Returns: Update document status in firebase from process to get. """ document_ref = db.collec...
ed658a50c24ae21bbe58aa8db4b23edc4c29ea84
41,893
def nll_loss( input, target, weight=None, size_average=None, ignore_index=None, reduce=None, reduction='mean', ): """Compute the negative likelihood loss. Parameters ---------- input : dragon.vm.torch.Tensor The input tensor. target : dragon.vm.torch.Tensor ...
60c05e00a6d02fec5a062aa6e1ef32fbb59230b8
41,894
def add_newline_to_end_of_each_sentence(x: str) -> str: """This was added to get rougeLsum scores matching published rougeL scores for BART and PEGASUS.""" if "<n>" in x: return x.replace("<n>", "\n") # remove pegasus newline char else: return x
54842070d316d07fd98a06d8c33d5171d5ae7a57
41,895
import matplotlib.pyplot as plt import numpy as np import scipy.interpolate as si from sklearn.base import TransformerMixin from sklearn.pipeline import make_pipeline from sklearn.linear_model import LinearRegression, RANSACRegressor,\ from sklearn.metrics import mean_squared_error def ransac_spline(x_data, y_data, n...
8d3dd4e63a4e8b1576efeb4ebf7f75264d64e520
41,896
def _open_sam(fn, fmt): """Open SAM | BAM file as AlignmentFile""" assert fmt == 'sam' or fmt == 'bam' mode = read_mode_of_file(fn) return AlignmentFile(fn, mode, check_sq=False)
b45e191b2cd13972e50226eda2ddc4d94beb5e10
41,897
def _excluded_scenario(test_name, scenario): """Skip list generator for scenarios to skip in test_name. Arguments --------- test_name : str, name of test scenario : instance of TestScenario, to be used in test Returns ------- bool, whether scenario should be skipped in test_name ""...
34adc91987c86c8f8af2243f0d414c7d00eaa748
41,898
import argparse def parse_args(): """ Parse input arguments """ parser = argparse.ArgumentParser(description='Visualization crop results') parser.add_argument('--annotation', dest='annotation', help='annotation file path', default='', ...
08200c6f2d17e036567a6c9ba878c8b22bdbb76a
41,899