content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_cognates(wordlist, ref): """ Retrieve cognate sets from a wordlist. """ etd = wordlist.get_etymdict(ref=ref) cognates = {} if ref == "cogids": for cogid, idxs_ in etd.items(): idxs, count = {}, 0 for idx, language in zip(idxs_, wordlist.cols): ...
bf64ecb8f2182dba06f0b28b384c0e66ba78d49e
3,649,300
def get_actress_string(_movie, s): """Return the string of the actress names as per the naming convention specified Takes in the html contents to filter out the actress names""" a_list = get_actress_from_html(_movie, s) actress_string = '' # if javlibrary returns no actresses then we'll just say wh...
bf9bd07bfc6c3e5bac87c52f4c6cba113a607b2d
3,649,301
def get_lessons_of_day(day): """ Returns the lessons as a string for the given day webelement :param day: day webelement :return: dictionary with day as key and list with lessons as value """ day_lessons = [] to_iterate = day.find_elements_by_class_name('event-content') to_iterate.reve...
47b3ba18fd530ac8e724eb91e4b4d2886a008ac5
3,649,302
import sys def version_map_to_rst(full_version, version_family, ver_map): """ Return a version of the version map that is suitable for printing. """ none_found_msg = '* No SIMP Mapping Data Found for "' + full_version + '"' # Easy cop out if not ver_map: return none_found_msg simp_relea...
b43fc5e363598f9ffb396b842da7fceafc413cdc
3,649,303
def resize_cluster(checkpoint, new_size, debug=True): """Resize cluster to given size. Inputs: checkpoint: A scalar tensor of type string, new peers should be able to restore to this checkpoint. new_size: A scalar tensor of type int32, the new cluster size. Returns: A pair of scalar...
da9a2a86e5856cffd99947d824994bbda7bfebb3
3,649,304
def ising_hamiltonian(n_qubits, g, h): """ Construct the hamiltonian matrix of Ising model. Args: n_qubits: int, Number of qubits g: float, Transverse magnetic field h: float, Longitudinal magnetic field """ ham_matrix = 0 # Nearest-neighbor interaction spin_coupling = ...
f485ac686001c0d9790276f19f5ba79b6de8db9c
3,649,305
import shutil def test_main( mock_building_parser, mock_return_logger, config_dict, db_connection, monkeypatch, test_dir, ): """Test main()""" def mock_parser(*args, **kwargs): parser = Namespace( cache_dir=(test_dir / "test_outputs" / "test_outputs_uniprot"), ...
5155b914d1f0320abc7991b7cc86e30664e75b53
3,649,306
def _slots_from_params(func): """List out slot names based on the names of parameters of func Usage: __slots__ = _slots_from_signature(__init__) """ funcsig = signature(func) slots = list(funcsig.parameters) slots.remove('self') return slots
fc55665a2bfa0ee27545734699f8527af5d57e6d
3,649,307
import time import requests import re def gnd_to_wd_id(gnd_id): """ Searches for a Wikidata entry which contains the provided GND ID. Outputs the Wikidata ID (if found). --------- gnd_id : str GND ID of entity. Returns ----------- str. """ url = 'https://query....
acf482aa05eac7c5307529643f30b7ef6880c55b
3,649,308
from typing import Optional def get_instance_category(entry) -> Optional[str]: """Determines the instance category for which the entry was submitted. If it does not match the config of any instance category, returns None. """ instance_categories = RidehailEnv.DIMACS_CONFIGS.ALL_CONFIGS ...
ad1208f1bbc93b3579eb1e82f0752671d856f501
3,649,309
def extendheader(table, fields): """ Extend header row in the given table. E.g.:: >>> import petl as etl >>> table1 = [['foo'], ... ['a', 1, True], ... ['b', 2, False]] >>> table2 = etl.extendheader(table1, ['bar', 'baz']) >>> table2 +...
352fc187e5778f415221b73c179cff496da9b8a5
3,649,310
def get_teamcount(): """Get a count of teams.""" #FINISHED FOR SASO teamlist = get_list_of_teams() return len(teamlist)
512dd11ff27600d91a8e6ee461b3f1e761604734
3,649,311
def make_adjacencyW(I, D, sigma): """Create adjacency matrix with a Gaussian kernel. Args: I (numpy array): for each vertex the ids to its nnn linked vertices + first column of identity. D (numpy array): for each data the l2 distances to its nnn linked vertices ...
4e310c5677d66b7fef66db5f96eda1c9bf8efdc7
3,649,312
def blackbody2d(wavelengths, temperature): """ Planck function evaluated for a vector of wavelengths in units of meters and temperature in units of Kelvin Parameters ---------- wavelengths : `~numpy.ndarray` Wavelength array in units of meters temperature : `~numpy.ndarray` ...
168c9e951350e3c93ef36cf95ec3e7a335d06102
3,649,313
def bookShop(): """ Este programa resuelve el siguiente ejercicio: Book Shop Link: https://cses.fi/problemset/task/1158 Este programa retorna el máximo número de páginas que se pueden conseguir comprando libros dados el precio y páginas de los libros disponibles y la cantidad de dinero disponible. """ ...
52f2b3ca84c7d6db529f51e2c05ad4767d4466c7
3,649,314
import mpmath def pdf(x, nu, sigma): """ PDF for the Rice distribution. """ if x <= 0: return mpmath.mp.zero with mpmath.extradps(5): x = mpmath.mpf(x) nu = mpmath.mpf(nu) sigma = mpmath.mpf(sigma) sigma2 = sigma**2 p = ((x / sigma2) * mpmath.exp(-(x...
b2d96bc19fb61e5aaf542b916d06c11a0e3dea46
3,649,315
import typing def get_310_prob(score_prob_dct: dict) -> typing.Dict[str, float]: """get home win, draw, away win prob""" prob = {} result_dct = get_score_pairs(0) type_dict = ['home_win', 'draw', 'away_win'] for i in type_dict: prob[i] = get_one_prob(score_prob_dct, result_dct, i) s...
c003e75796b6f3e67d6558f59492a9db065c6a51
3,649,316
def load_project_data(storage): """Load project data using provided open_func and project directory.""" # Load items and extractors from project schemas = storage.open('items.json') extractors = storage.open('extractors.json') # Load spiders and templates spider_loader = SpiderLoader(storage) ...
c0f8e2b339a21bf4f73dcba098e992e550005098
3,649,317
import json def home(): """ Route to display home page and form to receive text from user for speech synthesis. """ form = TextToSpeechForm() # Instantiates a client client = texttospeech.TextToSpeechClient() # Get the language list voices = client.list_voices() voice_codes_list ...
626dc2cde1dc326034772acb8b87cb35621c3e3f
3,649,318
def load_c6_file(filename, is_radar): """ Loads ice scattering LUTs from a file (based on Yang et al., JAS, 2013). Parameters ---------- filename: str The name of the file storing the Mie scattering parameters is_radar: bool If True, the first LUT column is treated as the freque...
c07256fde7ab5eac577caae2289a5d3d0dff583e
3,649,319
import typing import click import copy def gwrite(document: vp.Document, output: typing.TextIO, profile: str): """ Write gcode or other ascii files for the vpype pipeline. The output format can be customized by the user heavily to an extent that you can also output most known non-gcode ascii text fil...
d5a28fa7542db297d97c6252021bc4f103dea05d
3,649,320
import json import os def create_datasets(dataset, num_valid=0, max_epochs=1, batch_size=128, cache=True, **kwargs): """ Takes `.tfrecord` files and creates `tf.data.Dataset` objects. If `dataset` is `hdfs://<path>/data/` or `hdfs://<path>/data.tfrecord`, then there should also be a JSON file called `hdfs://...
b0f266aed455aad4143df048eac0fca2b8a0a1a1
3,649,321
def user_int(arg): """ Convert a :class:`~int` to a `USER` instruction. :param arg: Int that represents instruction arguments. :return: Fully-qualified `USER` instruction. """ return str(arg)
df3f72eac3de12b4c8cbb1ccee5305dc43837bc3
3,649,322
def timezoneAdjuster(context, dt): """Convinience: new datetime with given timezone.""" newtz = ITimezoneFactory(context) return dt.astimezone(newtz)
ba75bad6b8edfbc3198aad0adc0b1250626b9ce7
3,649,323
def make_adder(n): """Return a function that takes one argument k and returns k + n. >>> add_three = make_adder(3) >>> add_three(4) 7 """ def adder(k): return k + n return adder
64808cb857f7bd17c8c81bfd749ed96efcc88a9f
3,649,324
def IsWritable(Feature): """IsWritable(Feature) -> Writable Parameters: Feature: str Return value: Writable: ctypes.c_int""" if _at_camera_handle is not None: return _at_core_lib.AT_IsWritable(_at_camera_handle, Feature) != AT_FALSE else: raise AndorError('Andor libr...
bfe4ff1b93595e8b8df11193e04e13b8bd6c39d9
3,649,325
import torch from typing import Union from typing import Tuple def groupby_apply( keys: torch.Tensor, values: torch.Tensor, bins: int = 95, reduction: str = "mean", return_histogram: bool = False ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: """ Groupby apply for torch tensors Args: ...
711acc0cf2eb30e978f7f30686dbf67644d51fb0
3,649,326
def cube(x): """return x^3""" return x*x*x
df9aa4330b7cfb1946b3c403935c864a2e7fae7a
3,649,327
def get_candidados(vetor): """Retorna o dado dos candidatos""" lista_retorno = [] for i in vetor: lista_retorno.append(candidatos[int(i)]) return lista_retorno
259b921db5d3840ea220b9690f4eca1b84c2d98d
3,649,328
import copy def get_fmin_tree(f_df, tree): """ """ f = f_df[f_df['F4ratio']>=0].reset_index() t = copy.deepcopy(tree) i=0 for node in t.traverse(): if node.children: l = node.children[0] r = node.children[1] lleaves = l.get_leaf_names() ...
78da92675edfa2d8b9fd75591d104fbdb6adb369
3,649,329
def primes(n): """ Returns a list of primes < n """ n = int(n) sieve = [True] * n for i in np.arange(3, n ** 0.5 + 1, 2, dtype=int): if sieve[i]: sieve[i*i::2*i]=[False]*((n-i*i-1)//(2*i)+1) return [2] + [i for i in np.arange(3,n,2) if sieve[i]]
91af8e025c688e3b09638c8f00ca67a358e7137d
3,649,330
def H_TP(Z, T, P): """ Enthalpy defined by temperature and pressure (reference state at 300 K and 1 bar) Z - array of molar composition T, P - temperature and pressure Units are specified above """ H = RP.ABFLSHdll('TP', T, P*100, Z, 2).h - RP.ABFLSHdll('TP', 300, 100, Z, 2)....
36078f63478f7582e462f92d991a9941f07308c9
3,649,331
import os from pathlib import Path def is_root() -> bool: """ Checks whether the current user is root (or, on Windows, an administrator). """ if os.name == 'nt': try: _dummy = list((Path(os.environ.get('SystemRoot', 'C:\\Windows')) / 'Temp').iterdir()) return True ...
b6fb87fd0a8daab882e506aa5e289d83eb61c242
3,649,332
def test_fallback_round_with_input_n_not_int(): """ Feature: JIT Fallback Description: Test round() in graph mode with input x is not int. Expectation: TypeError. """ @ms_function def foo(): x = round(10.123, 1.0) return x with pytest.raises(TypeError) as ex: foo(...
3acef5aeaf1fdc40b66e0eede3f6df9d76bb5b9b
3,649,333
def validate_netmask(s): """Validate that a dotted-quad ip address is a valid netmask. >>> validate_netmask('0.0.0.0') True >>> validate_netmask('128.0.0.0') True >>> validate_netmask('255.0.0.0') True >>> validate_netmask('255.255.255.255') True >>> validate_netmask(BROADCAST)...
9462f27dc53ad907c8b6ef99db7a09631ca7157b
3,649,334
def translate(): """ A handler for translating given english word which about digit to chinese character Return: - `JSON` .. code-block # message = isError ? reason : "OK" # output = isError ? '' : <TRANSLATION> { message: string, output: str...
5e40a724e6d183151f155ec3e951ec6098a92016
3,649,335
def create_matrix_sars_overlap_between_networks(networks_summary_df, networks_dict): """ Creates matrix where element (i,j) quantifies the number of common SARS-Cov-2 partners in networks i and j divided by the total number of SARS-Cov-2 partners in both networks Args: networks_summary_df: data...
4b1d7c36e0781e7875f99cb7ac366ca3063cb77f
3,649,336
from typing import Tuple def load_forcings_gauge_metadata(path: str) -> Tuple[float, float, float]: """ Loads gauge metadata from the header of a CAMELS-USE forcings file. Parameters ---------- path: str Path to the forcings file. Returns ------- tuple (gauge latitude...
c91c3bafb83709967d6dd480afd8e53ac9f94445
3,649,337
def transition(measure, N, **measure_args): """ A, B transition matrices for different measures measure: the type of measure legt - Legendre (translated) legs - Legendre (scaled) glagt - generalized Laguerre (translated) lagt, tlagt - previous versions of (tilted) Laguerre with slightly...
8a701ace9b0d73e8f27062084dbf78711b8b4185
3,649,338
import numpy import pandas def interpolate_coord(df, xcol, ycol, step, distcol='d'): """ Interpolates x/y coordinates along a line at a fixed distance. Parameters ---------- df : pandas.DataFrame xcol, ycol : str Labels of the columns in ``df`` containing the x- and y-coords, ...
6ac736a4f82ffd7c0b3b45027bf7ab17b5d7d71c
3,649,339
def oven_cook_setting_to_str(cook_setting: OvenCookSetting, units: str) -> str: """Format OvenCookSetting values nicely.""" cook_mode = cook_setting.cook_mode cook_state = cook_mode.oven_state temperature = cook_setting.temperature modifiers = [] if cook_mode.timed: modifiers.append(STA...
02d339b82c8dbfb34f4bb6cc968fee83496df04e
3,649,340
def print_location(location: Location) -> str: """Render a helpful description of the location in the GraphQL Source document.""" return print_source_location( location.source, get_location(location.source, location.start) )
2c6f0f5e475fdbb14060b55f5698a2548720cc01
3,649,341
def run_metrics(ground_truth, simulation, measurement_name,users=None,repos=None): """ Run all of the assigned metrics for a given measurement. Inputs: ground_truth - DataFrame of ground truth data simulation - DataFrame of simulated data measurement_name - Name of measurement corresponding to...
733a04165853cb76f84bd15ff8f38585224ec039
3,649,342
def checkTrue(comment,res,update=True): """ This method is a pass-through for consistency and updating @ In, comment, string, a comment printed out if it fails @ In, res, bool, the tested value @ In, update, bool, optional, if False then don't update results counter @ Out, res, bool, True if test ...
4f8c0cf99921477e7187178d5576f2df03881417
3,649,343
def compute_votes( candidates, voters, voter_id, node_degree_normalization, ): """Comptue neighbor voting for a given set of candidates and voters Arguments: candidates {np.ndarray} -- genes x cells normalized expression for candidates voters {np.ndarray} -- genes x cells norma...
a04e4030b01d1188830a1ad2f55419d732afa432
3,649,344
def drop_second_col(in_list): """ Drop line info, convert into list """ ret = [] log.debug("Drop second col from %r", in_list) for x in in_list: y = x.split(":") lineless = y[0:1] + y[2:] log.debug("Add lineless list: %r", lineless) ret.append(lineless) return ret
31e358bb2e9c29a9b654aead961bc2634b5acd70
3,649,345
def _precompute_cache(x, y, num_classes): """Cache quantities to speed-up the computation of L2-regularized least-sq.""" # Whiten mean = jnp.mean(x, axis=0, keepdims=True) std = jnp.std(x, axis=0, keepdims=True) + 1e-5 x = (x - mean) / std # Add a constant feature for the bias, large so it's almost unregul...
b357620b7f2883182a33f040b2f7d82e0205bcaa
3,649,346
def show_user(): """Return page showing details: walks, landmarks rated, scores.""" user = User.query.filter_by(user_id=session.get('user_id')).first() ratings = user.ratings # import pdb; pdb.set_trace() walks = user.walks # for walk in walks: # origin = Landmark.query.filter(La...
ddcfed7ac98576cd6273bef5937f1ffbc4e3ecb9
3,649,347
def DesignCustomSineWave(family_list, how_many_gen, amp, per, shift_h, shift_v, show=False, print_phase_mse=False, return_phases=False): """ "Grid Search" Approach: Create sine waves with unknown amp, per, shift_h and shift_v in combinatorial manner and align famili...
5905a25b5be585303f5dbeaf42174a2a7be4879e
3,649,348
def RadarRngEq(G, beam_el, filename): """Prints SNR, will be modified for other uses later SNR = (pt*g^2*lambda_^2*sigma)/((4*pi)^3*k*temp_s*nf*l*r^4) pt = power transmitted - Watts freq = radar freq - Hz gain = antenna gain - db (default = 45) sigma = RCS - m^2 BW = bandwidth - Hz NF =...
bbfb8c24034e0252b6a9ab652f4cc02adfd647ef
3,649,349
def get_environment_names(): """Return a list of defined environment names, with user preference first.""" envlist = [r[0] for r in _session.query(models.Environment.name).order_by(models.Environment.name).all()] # move user preference to top of list userenvname = _config.userconfig.get("environmentnam...
0348738aa0bf3ea2df3783e2308b185e95292215
3,649,350
def plot(direction, speed, **kwargs): """Create a WindrosePlot, add bars and other standard things. Args: direction (pint.Quantity): wind direction from North. speed (pint.Quantity): wind speeds with units attached. **bins (pint.Quantity): wind speed bins to produce the histogram for. ...
f5020da6946b0242bea826d166bb32b83547bc40
3,649,351
def convert_floor(node, **kwargs): """Map MXNet's floor operator attributes to onnx's Floor operator and return the created node. """ return create_basic_op_node('Floor', node, kwargs)
476ff140cde55db2d489b745a08a7257576e3209
3,649,352
async def get_qrcode_login_info(): """获取二维码登录信息""" url = f"{BASE_URL}qrcode/auth_code" return await post(url, reqtype="app")
93f131cdfcf6cd7b18d126cd32c7836e10a67870
3,649,353
def get_global_free_state(self): """ Recurse get_global_free_state on all child parameters, and hstack them. Return: Stacked np-array for all Param except for LocalParam """ # check if the child has 'get_local_free_state' method for p in self.sorted_params: if isinstance(p, (param.Param,...
29c2a397261dddb92b718a57ba4ec3747d1ce661
3,649,354
def case_activity_update_type(): """ Case Activity Update Types: RESTful CRUD Controller """ return crud_controller()
4722001b25857bd56d1470334551c8bbe085f18e
3,649,355
def dftregistration(buf1ft,buf2ft,usfac=100): """ # function [output Greg] = dftregistration(buf1ft,buf2ft,usfac); # Efficient subpixel image registration by crosscorrelation. This code # gives the same precision as the FFT upsampled cross correlation in a # small fraction of the computat...
1cd8cd37efebea29da1086b998e98a334697e2d4
3,649,356
def parametrize_simulations(args): """Parametrize simulations""" if args.type == INSTANCE_COUNTS: return instance_count_sims(args) if args.type == FEATURE_COUNTS: return feature_count_sims(args) if args.type == NOISE_LEVELS: return noise_level_sims(args) if args.type == SHUFF...
ad592e64cbf7fa8ae79ccb753a1fd87db85e1f11
3,649,357
from typing import Union def connect(base_url: Union[str, URL], database_id: int = DJ_DATABASE_ID) -> Connection: """ Create a connection to the database. """ if not isinstance(base_url, URL): base_url = URL(base_url) return Connection(base_url, database_id)
aac724326f0f6e487caf8d614265c8028bae4e79
3,649,358
def micore_tf_deps(): """Dependencies for Tensorflow builds. Returns: list of dependencies which must be used by each cc_library which refers to Tensorflow. Enables the library to compile both for Android and for Linux. Use this macro instead of directly declaring dependencies on Tensor...
b4c8786df978a536f1adf1384209f0a0b663c100
3,649,359
def de_bruijn(k, n): """ de Bruijn sequence for alphabet k and subsequences of length n. """ try: # let's see if k can be cast to an integer; # if so, make our alphabet a list _ = int(k) alphabet = list(map(str, range(k))) except (ValueError, TypeError): ...
7e39d51bccbbb42bdda0594fa8c7077d4f2af1a1
3,649,360
def append_artist(songs, artist): """ When the songs gathered from the description just contains the titles of the songs usually means it's an artist's album. If an artist was provided appends the song title to the artist using a hyphen (artist - song) :param list songs: List of song titles (onl...
b3fbda311849f68ab01c2069f44ea0f694365270
3,649,361
def pose2pandas(pose: pyrosetta.Pose, scorefxn: pyrosetta.ScoreFunction) -> pd.DataFrame: """ Return a pandas dataframe from the scores of the pose :param pose: :return: """ pose.energies().clear_energies() scorefxn.weights() # neccessary? emopts = pyrosetta.rosetta.core.scoring.methods...
71c3342f86138f28411302da271ca0fb252727d2
3,649,362
def rantest(seed,N=100): """get some random numbers""" buff = np.zeros(N,dtype=np.double) ct_buff = buff.ctypes.data_as(ct.POINTER(ct.c_double)) sim.rantest(seed,N,ct_buff) return buff
4764968f8b0c46ab58b0b2710f4a0764a417f51c
3,649,363
def tf_efficientnet_b0_ap(pretrained=False, **kwargs): """ EfficientNet-B0 AdvProp. Tensorflow compatible variant """ kwargs['bn_eps'] = BN_EPS_TF_DEFAULT kwargs['pad_type'] = 'same' model = _gen_efficientnet( 'tf_efficientnet_b0_ap', channel_multiplier=1.0, depth_multiplier=1.0, pretrained=pre...
4cbd2d791301c4001f9bd07da0357550ea93f585
3,649,364
import torch def pi_del( shape, y_tgt_star, pad_symbol=0, plh_symbol=0, bos_symbol=0, eos_symbol=0, Kmax=100, device="cpu", ): """Operations and states to edit a partially deleted version of y_star back to y_star.""" # shape = B x N x M # y_tgt_star : B x M shape = list...
edbd9c40de5b8d5639bfa382d90071e7405aa062
3,649,365
from typing import Dict from typing import Any import logging def create_service_account(project_id: str, service_account_name: str, role_name: str, file_name: str) -> Dict[str, Any]: """Create a new service account. Args: project_id: GCP project id. service_account_name: The s...
48bcd081cef0eb76be5412febb76e05266a12968
3,649,366
def test_ode_FE(): """Test that a linear u(t)=a*t+b is exactly reproduced.""" def exact_solution(t): return a*t + b def f(u, t): # ODE return a + (u - exact_solution(t))**m a = 4 b = -1 m = 6 dt = 0.5 T = 20.0 u, t = ode_FE(f, exact_solution(0), dt, T) diff ...
992aaf22b89a235b7ab5505225a8f3ff4f34ae10
3,649,367
def file_finder(): """ This function allows to the user to select a file using the dialog with tkinter. :return path_name :rtype str the string of the path_name file. """ root = Tk() root.title("File Finder") root.geometry("500x400") root.attributes("-topmost", ...
2da5df55010e8edbd5975fe527ad4780ce6e69e9
3,649,368
def htm_search_cone(IndexFile_data,Long,Lat,Radius,Ind=None,Son_index=np.arange(2,6),PolesLong_index=np.arange(6,11,2),PolesLat_index=np.arange(7,12,2)): #print('I am running htm_search_cone') """Description: Search for all HTM leafs intersecting a small circles Input :-Either a table of HTM data or an...
2b202f943264cc979c4271c41fca2386a3b2b14f
3,649,369
import platform import re import os import ctypes def getHostOsVersion(): """ Returns the host OS version. This is platform.release with additional distro indicator on linux. """ sVersion = platform.release(); sOs = getHostOs(); if sOs == 'linux': sDist = ''; try: ...
a539e0f6a5b4b46e1a02159d89615b3bc7612e24
3,649,370
import os def archived_changes(archivedir='./edi_requests/', scope='knb-lter-jrn', dedup=True, parsedt=False): """ Load archived PASTA change records from xml files and parse into dataframe. Options archivedir path to archive directory string ('./edi_requests') scope ...
febc96889eb113b8a006894b9b8642c83108db48
3,649,371
def get_missing_columns(missing_data): """ Returns columns names as list that containes missing data :param missing_data : return of missing_data(df) :return list: list containing columns with missing data """ missing_data = missing_data[missing_data['percent'] > 0] missing_...
80feccec6148a417b89fb84f4c412d9ea4d0dd37
3,649,372
def read(request): """Render the page for a group.""" pubid = request.matchdict["pubid"] slug = request.matchdict.get("slug") group = models.Group.get_by_pubid(pubid) if group is None: raise exc.HTTPNotFound() if slug is None or slug != group.slug: url = request.route_url('grou...
8376c94a4ffe6569cd7531d18427fbfd57629031
3,649,373
import time import copy import tqdm import torch from typing import OrderedDict def train_model( model, device, train_data_loader, valid_data_loader, criterion, optimizer, scheduler, num_epochs=5): """ training Parameters -------------- model : DogClassificationModel ...
c12929a8aec02031f8d293f5347beaeb5dc6d759
3,649,374
from src.dialogue_system.agent.agent_with_goal_3 import AgentWithGoal as AgentWithGoal3 import json import time import pickle def run(parameter): """ The entry function of this code. Args: parameter: the super-parameter """ print(json.dumps(parameter, indent=2)) time.sleep(2) slo...
75e9fd2204e2e3e0aa7101e9656c23617fb56099
3,649,375
from typing import Iterable def convert( value: str, conversion_recipes: Iterable[ConversionRecipe[ConvertResultType]]) -> ConvertResultType: """ Given a string value and a series of conversion recipes, attempt to convert the value using the recipes. If none of the recipes declare the...
a6f1162f4069a3846636ad95cecde0b3ba3601a8
3,649,376
def get_function_name(fcn): """Returns the fully-qualified function name for the given function. Args: fcn: a function Returns: the fully-qualified function name string, such as "eta.core.utils.function_name" """ return fcn.__module__ + "." + fcn.__name__
ae186415225bd5420de7f7b3aef98480d30d59f8
3,649,377
def clean_cases(text): """ Makes text all lowercase. :param text: the text to be converted to all lowercase. :type: str :return: lowercase text :type: str """ return text.lower()
9b0c931336dbf762e5e3a18d103706ddf1e7c14f
3,649,378
def root(): """Refreshes data in database""" db.drop_all() db.create_all() # Get data from api, make objects with it, and add to db for row in df.index: db_comment = Comment(user=df.User[row],text=df.Text[row]) # rating = df.Rating[row] db.session.add(db_comment) db.sessi...
0731926301cd981cc9278964cb313a35bcfb4f43
3,649,379
from sys import flags import contextlib def construct_grammar(grammar_string, allow_sub_grammar_definitions=False, default_flags=flags.DEFAULTS): """ Function which accepts a user-defined grammar string and returns an instance of Grammar representing it. Inputs: grammar_string - The user-defined grammar ...
86a4d217c05d8e4c583b7927ee8735086fcf0a83
3,649,380
def bond_value_to_description(value): """bond_value_to_description(value) -> string Convert from a bond type string into its text description, separated by "|"s. The result are compatible with OEGetFPBontType and are in canonical order. """ return _get_type_description("bond", _btype_flags, val...
2eeb333334740ed9cdad28b43742c7a2274885bc
3,649,381
def read_set_from_file(filename): """ Extract a de-duped collection (set) of text from a file. Expected file format is one item per line. """ collection = set() with open(filename, 'r', encoding='utf-8') as file_: for line in file_: collection.add(line.rstrip()) return c...
ba71ed4fb6e85cf5156d35a85245058bb3711f9b
3,649,382
def filter_0_alleles(allele_df, allele_num=2): """Drop alleles that do not appear in any of the strains. """ drop_cols = [] for col in allele_df.columns: if allele_df[col].sum()<allele_num: drop_cols.append(col) allele_df.drop(drop_cols, inplace=True, axis=1) return allele_df
9b76152d6e6fc200c2d80d4721122d3958642286
3,649,383
def gradient_of_rmse(y_hat, y, Xn): """ Returns the gradient of the Root Mean Square error with respect to the parameters of the linear model that generated the prediction `y_hat'. Hence, y_hat should have been generated by a linear process of the form Xn.T.dot(theta) Args: y...
73a46197f90cf1b9c0a90a8ce2d2eae006c6d002
3,649,384
def is_commit_in_public_upstream(revision: str, public_upstream_branch: str, source_dir: str): """ Determine if the public upstream branch includes the specified commit. :param revision: Git commit hash or reference :param public_upstream_branch: Git branch of the public upstream source :param sour...
6f7259f8e3a1893a7fbd41914df37e42fed73c7b
3,649,385
def align_down(x: int, align: int) -> int: """ Align integer down. :return: ``y`` such that ``y % align == 0`` and ``y <= x`` and ``(x - y) < align`` """ return x - (x % align)
8144309badf601999f4c291ee3af5cfbd18397ea
3,649,386
from pathlib import Path import os def read_config_file(config_id: str = "sample_config") -> ConfigType: """Read a config file Args: config_id (str, optional): Id of the config file to read. Defaults to "sample_config". Returns: ConfigType: Config object """ project_...
199f15c7e81cde04c1122e6439082f474fe6577a
3,649,387
def null(): """return an empty bit buffer""" return bits()
53b7e87648c33ab1072651ee6ef6bfb3fe92da8d
3,649,388
def find_coherent_patch(correlations, window=11): """Looks through 3d stack of correlation layers and finds strongest correlation patch Also accepts a 2D array of the pre-compute means of the 3D stack. Uses a window of size (window x window), finds the largest average patch Args: correlations ...
27bc06ec5e73d854c094f909fdf507fad38168f3
3,649,389
def test(): """HI :)""" return 'Hi!'
626b2ffcfc3f60dcd5456efa2d61a3ed18d428d8
3,649,390
from typing import Optional def soft_sign(x: ArrayLike, *, constant: Optional[bool] = None) -> Tensor: """Returns the soft sign function x / (1 + |x|). Parameters ---------- x : ArrayLike Input data. constant : boolean, optional (default=False) If ``True``, the returned tensor is...
3142e8bedeec12071d87b0248d760eccf12c9eee
3,649,391
def get_vdfdx(stuff_for_time_loop, vdfdx_implementation="exponential"): """ This function enables VlaPy to choose the implementation of the vdfdx stepper to use in the lower level sections of the simulation :param stuff_for_time_loop: (dictionary) contains the derived parameters for the simulation ...
538548a2d2d39b83ad74ac052c3c1a51895357d2
3,649,392
def worker(args): """ 1. Create the envelope request object 2. Send the envelope """ envelope_args = args["envelope_args"] # 1. Create the envelope request object envelope_definition = make_envelope(envelope_args) # 2. call Envelopes::create API method # Exceptions will be caught by...
79891142b34da8d9d5aacc4d55ab7f65198a4116
3,649,393
import glob import csv def write_colocated_data_time_avg(coloc_data, fname): """ Writes the time averaged data of gates colocated with two radars Parameters ---------- coloc_data : dict dictionary containing the colocated data parameters fname : str file name where to store th...
2e786c6df8a617f187a7b50467111785342310c5
3,649,394
from datetime import datetime import pytz import sys def get_method(client, request, xslt_code, operation, current_date=datetime.datetime.now(pytz.timezone('US/Pacific')).strftime("%Y-%m-%dT%H:%M:%S"), print_to_console=False, count=100, add_response_filter=True): """ :param clien...
ce380651571f5a5a0e3021ecbdd582d1a65db0f2
3,649,395
def _min(group_idx, a, size, fill_value, dtype=None): """Same as aggregate_numpy.py""" dtype = minimum_dtype(fill_value, dtype or a.dtype) dmax = np.iinfo(a.dtype).max if issubclass(a.dtype.type, np.integer)\ else np.finfo(a.dtype).max ret = np.full(size, fill_value, dtype=dtype) if fill_val...
a11d1e5bcf0c3aca81cdc6081fc0dfd186fa499e
3,649,396
def find_word(ch, row, boggle_lst, used_positions_lst, current, ans): """ :param ch: int, index for each character in a row :param row: int, index for each row in the boggle list :param boggle_lst: list, list for all rows :param used_positions_lst: tuple, index of ch and row that indicates the position of an used ...
c896c4b4ac7b6816d0d4a35135ea2c87891f214e
3,649,397
def lazy_tt_ranks(tt): """Returns static TT-ranks of a TensorTrain if defined, and dynamic otherwise. This operation returns a 1-D integer numpy array of TT-ranks if they are available on the graph compilation stage and 1-D integer tensor of dynamic TT-ranks otherwise. Args: tt: `TensorTrain` object. ...
6792b269c9c27dc7ad83202b7920f44ae8ee3ff8
3,649,398
def word_errors(reference, hypothesis, ignore_case=False, delimiter=' '): """Compute the levenshtein distance between reference sequence and hypothesis sequence in word-level. :param reference: The reference sentence. :type reference: str :param hypothesis: The hypothesis sentence. :type hypoth...
11473b01bd222c4550403afb07303a14cd123720
3,649,399