content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_celsius(temperature_in_fahrenheit): """ Returns the temperature in Celsius of the given Fahrenheit temperature. For example, this function returns XXX when given YYY. Type hints: :type temperature_in_fahrenheit: float """ return (temperature_in_fahrenheit - 32) * (5 / 9)
501b5c3c6c7fe9792fd12cabbae71eddfbc34f58
46,644
def solve_f35d900a(x): """ Difficulty: High The Problem: The input grid is a rectangular (list of lists) matrix with variable shape, with numbers ranging from 0 to 9. (inclusive). Different colors of the color spectrum are represented by the integers. The task is to identi...
da779b86563f684b6e8b00c7f229a0985e504e40
46,645
def config_fixture(hass): """Define a config entry data fixture.""" return { CONF_USERNAME: "user@email.com", CONF_PASSWORD: "password", }
7c14083c8254f367ec93e1b5e111f0502969b59a
46,646
import scipy def erfc(x): """ Complimentary error function, with handling of Quantity objects Only Dimensionless quantities can be handled erfc(x) = 1 - erf(x) """ if isinstance(x, Quantity): return scipy.special.erfc(x.to("").magnitude) else: return scipy.special.erfc(x)
a5cb49b658252227b9b3fcd34ec8107bd399545d
46,647
import bz2 import json import codecs def json_exporter(data, filepath, compress=True): """Export a file to JSON. Compressed with ``bz2`` is ``compress``. Returns the filepath of the JSON file. Returned filepath is not necessarily ``filepath``, if ``compress`` is ``True``.""" if compress: filepath...
dcdb9026b302c3bec6b6a7215cee0498a8655a61
46,649
def is_linear(x, y): """ Returns True if molecule is linear (largest eigenvalue almost equivalent to second largest) """ x = x - np.mean(x, axis=0) y = y - np.mean(y, axis=0) L, Q = sorted_eigh(build_F(x, y)) if L[0]/L[1] < 1.01 and L[0]/L[1] > 0.0: return True else: ...
e1316292474a23b9ee04bafac47c08ed47b02b43
46,650
import math def _realroots_quadratic(a1, a0): """gives the real roots of x**2 + a1 * x + a0 = 0""" D = a1*a1 - 4*a0 if D < 0: return [] SD = math.sqrt(D) return [0.5 * (-a1 + SD), 0.5 * (-a1 - SD)]
ad61307a09b9f5cbf444f0bd75448b39b09b2e96
46,651
def add_column(recarray, name, val, index=None): #Stolen from Ska.Numpy """ Add a column ``name`` with value ``val`` to ``recarray`` and return a new record array. :param recarray: Input record array :param name: Name of the new column :param val: Value of the new column (np.array or list) ...
92f05bfe58da4c1b37a9309d7aff624d422e2163
46,652
def gunning_fog_index(n_words, n_polysyllable_words, n_sents): """https://en.wikipedia.org/wiki/Gunning_fog_index""" return 0.4 * ((n_words / n_sents) + 100 * (n_polysyllable_words / n_words))
aeb295edfa563027952f6a934636487e04b2b266
46,653
import imageio def makeGIF(FF_input, start_frame=0, end_frame =255, ff_dir = '.', deinterlace = True, print_name = True, optimize = True, Flat_frame = None, Flat_frame_scalar = None, dark_frame = None, gif_name_parse = None, repeat = True, fps = 25, minv = None, gamma = None, maxv = None, perfield = False, data_type=...
077d238fac7fe9861eba05ff2128266a1ac4ad80
46,654
def russell_rao( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: """Russel-Rao similarity Russell, P. F., & Rao, T. R. (1940). On habitat and association of species of anopheline larvae in south-eastern Madras. Journal of the Malaria Institute of India, ...
6d5be97809f94bb217f60f5490c0accbb2dda76e
46,655
def _generate_windows_body(hooks): """Generate Windows specific functions. At the moment it implements load_impls_from_library, class destructor, and an utility function to convert from utf8 to wide-strings so we can use the wide family of windows functions that accept unicode. """ # generate d...
27597f8556cdb4383179245a423a45a72324e2ae
46,656
def get_binary(img_gray): """ Get binary threshold filter of image. """ thresh = cv2.threshold(img_gray, 128, 255, cv2.THRESH_BINARY)[1] thresh = thresh[:, :, np.newaxis] return thresh
4353d807fc5d015a772ee138e358be3d24d1cba7
46,657
def bt_rr(weights, bounds): """ LP-based OBBT using ReLU relaxation. The procedure is named RR in the paper. Assuming that NN model has K-1 hidden layers with ReLU activation and 1 linear output layer Variables are named as x_i_j, where i is the layer number, and j is the unit number (of layer i) ...
675abbd09569e70ee313ae430f0fe4e896c8537c
46,658
def energy(sig: _Array) -> _Array: """Total energy of time domain signal. Args: sig: Time domain signal. Returns: Energy along fist axis. """ if not _np.isfinite(sig).all(): raise ValueError('Input ``sig`` contains NaNs or infinite values.') return _np.sum(_np.square(_...
b102bf559e8c087f8fe2125c3e319dd1438b227f
46,659
def _compute_expected_shocks(dense_key_to_choice_set_in_period, optim_paras): """Compute an array with the expected value of the shocks.""" n_wages = len(optim_paras["choices_w_wage"]) exp_shocks = np.zeros(len(optim_paras["choices"])) var = np.diag(optim_paras["shocks_cholesky"].dot(optim_paras["shock...
b270b1507f930a4e91ac1dbc5fe61013f9f7ad53
46,660
import logging def a_star(graph, start, goal): """ this thing does not work :( """ # pdb.set_trace() logger.setLevel(logging.INFO) queue = [ [start] ] step = 0 logging.info("START: %s" % start) logging.info("GOAL: %s" % goal) def a_star_sort(path1, path2): l1 = path_length...
b0ffc567845c1c0ba15d6a7c1848af67de5e1230
46,661
def _preprocessor_public(X_raw): """Data preprocessing function. This function prepares the features of the data for training, evaluation, and prediction. Parameters ---------- X_raw : ndarray An array, this is the raw data as downloaded Returns ...
58ddca1808edffcd0020feb46735ff6302f56df7
46,662
def alreadyHasEntry(oldClassString, og): """ Return true if there is already an owl:Class with the old id""" namespace = oldClassString.split(':')[0] if namespace == 'http': target = rdflib.URIRef(oldClassString) print('OLD CLASS ID IS A URL', oldClassString) else: try: ...
482dbd7c62bff21dae9b9c563ca86fb9b5fab560
46,663
def loadTLE(tle_file, satlst=None): """ load TLE from file """ with open(tle_file, 'r') as f: satlist = [] for l1 in f: l2 = f.readline() l3 = f.readline() norad_id = l2[2:8] if satlst is not None: if norad_id in satlst: ...
1c33f3673a25fc5f052ebef1fbf193e8762ef509
46,664
from typing import Optional from typing import Dict from typing import Any def bake(schema_name: str, config: Optional[Dict[str, Any]] = None) -> str: """ Links the directive to the appropriate schema and returns the SDL related to the directive. :param schema_name: schema name to link with :param...
d2a58c0272ddeb6c39e7f1b78c56dd4c953ca9f0
46,665
def cents_to_ratio(c): """Cents to pitch ratio.""" return np.power(2, c/1200.0)
018e7c962f77e3f25c1778fee2bdc5cb02adc27b
46,666
def get_prev_frames(ind, path): """ for this index return the closest previous frame which is non none :param ind: input index :param path: :return: frame and the count """ cur_ind = ind - 1 count = 1 while (path[cur_ind] is None and cur_ind >0): count = count + 1 cur...
ddb48419e07a85c6c8d62eb4b034d6c5f2210a39
46,667
def test_metric_get(test_flask_client): """Tests the GET method""" with mock.patch("bluebird.api.resources.metrics.utils", wraps=utils) as utils_patch: sim_proxy_mock = mock.Mock() utils_patch.sim_proxy.return_value = sim_proxy_mock # Test no providers available sim_proxy_moc...
8d5a058b78ecb4d1e2703f16d99616fc87404bcb
46,668
from typing import Dict from typing import Any async def create_remove_vote(res: Response, vote: VoteBaseModel) -> Dict[str, Any]: """create or remove a Vote from Vote table Args: vote (VoteBaseModel): vote to create or remove Returns: Dict[str, Any]: vote created """ response ...
16c44d03a3ea9dc976091429b1d077cb043ef767
46,669
def delete_file(app_id, file_name, mode): # type: (int, str, bool) -> bool """ Call to delete_file. :param app_id: Application identifier. :param file_name: File name reference. :param mode: Delete mode. :return: The deletion result. """ return _COMPSs.delete_file(app_id, file_name, mod...
dac37c86de329ab39212589826c606dd0b6d210d
46,670
def update_consumer_view(request): """ Updates a consuemr on ``POST`` request and returns the consumer update form for ``GET`` request. .. http:get:: /consumer/update Gets the consumer update form whose primary key matches the query parameter ``pk``. **Example request**:...
d2a797fde068c7570611cac2d0943247b9c8726b
46,671
def LastValueMinMaxQuantize(inputs, min_var, max_var, bit_width, is_training, mode, name_scope="LastValueMinMaxQuantize"): """Last value float scale q...
ae73bb701f3abfe6ef2a859880db60b5b39db63b
46,672
def wikitext103_local_cluster4k(): """Routing attention on sequence length 4k.""" hparams = wikitext103_local4k() hparams.local_num_heads = 8 hparams.sparsity_cluster_num_heads = 8 hparams.sparsity_cluster_attention_window = 512 hparams.sparsity_cluster_size = 8 hparams.share_qk = True return hparams
3a256772c521f8ba17d4dd795d9d204d1fb7de46
46,674
def log10(pred, depth): """ Mean log10 Error (LOG10) """ return np.absolute(np.log10(pred) - np.log10(depth)).mean()
9a228d8179e3aa4530b70dac202ba57fc7549f3a
46,675
def test_plan_built_on_method(hook): """ Test @sy.meth2plan and plan send / get / send """ hook.local_worker.is_client_worker = False x11 = th.tensor([-1, 2.0]).tag("input_data") x21 = th.tensor([-1, 2.0]).tag("input_data") device_1 = sy.VirtualWorker(hook, id="device_1", data=(x11,)) ...
12ecce26ee149a690abcc8a7e41651e5d8273092
46,676
def get_proto_deserializer(proto_class): """ Return a proto deserializer that takes in a proto type to deserialize the serialized msg stored in the RedisState proto """ def _deserialize_proto(serialized_rule): proto_wrapper = RedisState() proto_wrapper.ParseFromString(serialized_rule...
4c509dccea826169c396510ef7f80cbf5fcf9b18
46,677
import requests import json import logging def last_failed(url, job_type): """Return last failed job for a specified job type.""" # query query = { "query": { "bool": { "must": [ { "terms": { "s...
567e5ef7afaa460e7fb91e09fa74d2d011cb2cdb
46,678
def p2pkh_address_to_pubkey_hash(address): """ Takes a P2PKH address (starting with a 1, m or n symbol) and extracts its HASH160 hash (used as a public key hash). :see: https://en.bitcoin.it/wiki/List_of_address_prefixes :param address: P2PKH public address :returns: HASH160 hash of the ...
95b6237b1c4a2492ab7283f104f2e6590b05eedc
46,679
from typing import Optional def get_dashboard(dashboard_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDashboardResult: """ Resource schema for AWS::IoTSiteWise::Dashboard :param str dashboard_id: The ID of the dashboard. """ __args__ = di...
bf5092d6c78edc6523c95ec1ffba79f86dec1924
46,680
def resize_intrinsics(intrinsics, target_size): """Transforms camera intrinsics when image is resized. Args: intrinsics: 1-d array containing w, h, fx, fy, x0, y0. target_size: target size, a tuple of (height, width). Returns: A 1-d tensor containing the adjusted camera intrinsics. """ with tf.n...
7216522da6a681d836171d16beb1507523bf4331
46,681
def fix_spaces_inside_quotes(text, quote='``'): """ >>> test = '''\ :meth:`update` accepte soit un autre objet dictionnaire ou un iterable de\ paires clé / valeur (comme tuples ou d'autres iterables de longueur deux).\ Si les arguments de mots clés sont spécifiés, le dictionnaire est alors mis\ ...
cafb4dd7d15c4ab1a2cd252352d33b9aa20e4bca
46,683
def toGoatLatin(S): """ :type S: str :rtype: str """ count=1 sentences=S.split() for i in range(len(sentences)): if sentences[i][0].lower() in "aeiou": sentences[i]+="ma"+count*"a" else: sentences[i]=sentences[i][1:]+sentences[i][0]+'ma'+count*"a" count+=1 return " ".join(sentences)
ebc1e567dfa60436aea14412d7b347d8481f8b0a
46,684
def __prepare_line(string, dir_source, replace_string): """ Prepare the line before it is being written into the content file """ if not replace_string == None: string = string.replace(dir_source, replace_string) return string
cbec6deab5c66960c5e8d57b52392e4ed3cf2b3d
46,685
def create_adjacency_matrix(graph): """ Creating a sparse adjacency matrix. :param graph: NetworkX object. :return A: Adjacency matrix. """ index_1 = [edge[0] for edge in graph.edges()] + [edge[1] for edge in graph.edges()] index_2 = [edge[1] for edge in graph.edges()] + [edge[0] for edge in...
220a5465faa35c726008c7c4acf10c48bc44bb12
46,686
def count_trainable_parameters(): """Counts the number of trainable parameters in the current default graph.""" tot_count = 0 for v in tf.trainable_variables(): v_count = 1 for d in v.get_shape(): v_count *= d.value tot_count += v_count return tot_count
2e576db2be0815c770fdeea24bcf21d5d9353732
46,687
def create_diagram(start_from=None, kind="default", in_notebook=True): """Visually create a diagram. Parameters ---------- start_from : list, optional Starting coordinates (list of (x, y) tuples). By default uses a triangle. kind : str Can be one of "default", "x-marked". in_not...
f99f4b7445c4d55f784892bc5294a29087be7b5c
46,688
def extractsignalpdata(signalp_file_name,main_dic,translator_dic,n_termin_dict): """ This function reads an abridged signalp file, parses the signalp data and adds the information in the (?) column to the main class. """ for line in open(signalp_file_name,'r'): #Filter out title and s...
2dc701d542c2a089fdf510de10885a89172fbd7b
46,689
def mosaic_template( endpoint: str, mapbox_access_token: str = "", mapbox_style="satellite" ) -> str: """Rio-viz viewer.""" return f"""<!DOCTYPE html> <html> <head> <meta charset='utf-8' /> <title>Cogeo-Mosaic Viewer</title> <meta name='viewport' content='initial-scale=1,maxi...
9bb5e23caca6ce347ba56f3792ff8a130bbec423
46,690
def write_smiles(molecule, default_element='*', start=None): """ Creates a SMILES string describing `molecule` according to the OpenSMILES standard. Parameters ---------- molecule : nx.Graph The molecule for which a SMILES string should be generated. default_element : str Th...
f1e13af728bdc8e1f13e6853d089ed3ce9b856e8
46,691
def find_closest_raster(return_period,aoi_col='AoI_RP{}y_unique',depth_col='RP{}_max_flood_depth'): """ Find the closest AoI and Flood raster column name for given return period Arguments: *return_period* (float): Return period of the flood for which to find the nearest inundation raster *a...
177041afc9a52d4942ab4095b7383cfc8e17652b
46,692
def svn_diff_fns_invoke_datasource_get_next_token(*args): """svn_diff_fns_invoke_datasource_get_next_token(svn_diff_fns_t _obj, void diff_baton, svn_diff_datasource_e datasource) -> svn_error_t""" return _diff.svn_diff_fns_invoke_datasource_get_next_token(*args)
9d9b0dd2ac2214c05cc7af5e1fca5f804b1feb5b
46,693
def _is_bn_diff_doctypes(dyad): """Check if a dyad is between two different doctypes. Args: dyad (tuple): two-item tuple where each item is a dict which represents a document Returns: ind (bool): True if the dyad is between two different doctypes """ if dyad[0]["doctype"] != dyad[...
2480cbca808164b2fec14fd13808cf5ebfb0dcc3
46,694
import operator def selectcontains(table, field, value, complement=False): """Select rows where the given field contains the given value.""" return selectop(table, field, value, operator.contains, complement=complement)
29753f270791a3187bf0a2a87fc5ec6b379178ed
46,695
def with_path_to(q, value, info, union=False, name='with_path_to'): """This will traverse any (any meaning any paths specified in the path generation heuristic which prunes some redundant/wandering paths) from the source entity to the given target type where it will apply a given query. This filter...
68c9ceddf0a9b2bcc5d39262f5f7d94deb47e4db
46,696
from typing import Dict from typing import List import urllib from bs4 import BeautifulSoup import logging def get_links(entry: Dict, html_data: Text) -> List[urllib.parse.ParseResult]: """Extract any links from the html""" links = [] soup = BeautifulSoup(html_data, "html.parser") if soup: li...
b3c1fc02c145387b3d4e639ff9fa0ff594953e55
46,697
def conjgrad (A, b, x = None, iterations = 10**6, epsilon = 10**(-10)): """ Méthode du gradient conjugué. ----------------------------- Entrée: A matrice symétrique définie positive. b vecteur colonne. (optional) x vecteur initial de la suite. ...
62708a3d3dfd8afc20cf1b43fcff92614b0c3392
46,698
from datetime import datetime import binascii def is_valid(token): """Checks if the token is valid. Args: token (str): Token Returns: Boolean: True or false """ if len(token) < 64: return False now = datetime.now().timestamp() time = token[22:][:20] decode_tim...
ea1b28d2a04f3d72a0388c41feeb2bd764a78239
46,701
def shared_dataset(filename): """Returns the training-, validation- and test-datasets as shared variables""" train_set, valid_set, test_set = load_dataset(filename) train_x, train_y = shared_variables(train_set, 'Training') valid_x, valid_y = shared_variables(valid_set, 'Validation') test_x, test_y...
71ff6a10845720f0eb2bb6f7f9035574cb52970d
46,702
def _stats_print(good_noise, good_gains, good_fit, test_chans): """Generate a simple set of statistics for the test and print them to screen. """ print("\nFilter statistics:") good_chans = [1] * len(test_chans) Nact = len(test_chans) # Number of active channels if good_noise is not None: ...
31044ffd6966a0e7d910bcafa92616de36ce4e81
46,703
def text(): """make text files""" return build('text', 'The text files are in {}.')
b066b813722be90c69eae68972cf33475c5f0023
46,704
import requests def upload2ipfs(file_path: str) -> str: """Upload to ipfs using local port. IPFS node must be running locally. Run: $ ipfs daemon Args: nft_path (str): path to metadata file """ with open(file_path, "rb") as f: nft_binary = f.read() ipfs_endpoint = "http://...
4fdb53d4d6d61b1784673be6d84cb7ba41fc84a5
46,705
def rotateImage(imgdata, org_corners): """ """ rotation = calculateRotation(org_corners.ul, org_corners.ur) rot_img = skimage.transform.rotate(imgdata, rotation, resize = True, preserve_range = True) return rot_img
c4649b964a99345b62b4b53184efe5757639f0e2
46,706
def mean_absolute_scaled_error(y_true: ArrayLike, y_pred: ArrayLike) -> float: """Compute the mean absolute scaled error (MASE). MASE is computed by comparing mean absolute error of the predictions to the mean absolute error obtained from a lag-1 forecast. Args: y_true: the actual values. ...
7931d81f952e692f1b14f578ee93182b3289074d
46,707
def GetCloudBasePath(): """Returns the folder within the Makani bucket where all databases live.""" return 'gs://gcp-public-data-makani-deps/deps/turbsim_databases'
40091d491fdc3960cc5aa08e0ca58ae0cf2009aa
46,708
import json def create_entity(station: WeatherStationTuple) -> dict: """ Conversion from input data to desired properties and types """ entity = Entity() entity.provider = 'bom' entity.country = 'Australia' entity.country_code = 'AU' entity.state = station.state entity.site = station.site...
2e6398490afdee43a5d8d43c58634ffdff7bc3dd
46,709
def line(char='-', length=48): """Generates a string of characters with a certain length""" return ''.join([char for _ in range(length)])
32de8abb95ab7e73912e2b37f0996361ed181c5b
46,710
import collections def dict_update(d, u): """Recursive update dictionary""" for k, v in u.items(): if isinstance(v, collections.Mapping): d[k] = dict_update(d.get(k, {}), v) else: d[k] = v return d
bf49b0e4a8f35595a2258aaadcad231d8b9325da
46,711
def _handle_tracking(request, response): """Handles the share tracking logic so that users get their number of shares increased when someone downloads Firefox mobile via their user page.""" if not _has_parent_cookie(request): parent_username = _add_share_from_cookies(request) # Set a 'par...
f491e44253face9148aaf4f4e09cb122c4b495b6
46,712
def prompt_yn(msg, default=None): """ Prompts the user for a y/n response. default param should be either 'y' or 'n' Returns True if 'Y' and False if 'N' """ if default is True: default = 'y' elif default is False: default = 'n' if default == 'y' or default is True: ...
f5df7d5bf32153dd1a0e34b26997aabd683066f8
46,713
def noise_for_example(x, extent=1000, intensity=0.1, rng=None, **kwargs): """ Add noise to x. Just for demonstration. Arguments: extent -- number of points to add noise at intensity -- scale parameter of half-normal distribution; samples from this distribution will be added at each nois...
55a76ea075f6f36d874293ee8aacbd1419fd1e32
46,714
def datasets_loader(conf, train=True, dev=True, test=True): """ simple wrapper for unified interface of datasets loaders """ fmt = conf.pop("fmt") if fmt == "kaldi_ra": return kaldi_ra_datasets_loader(conf, train, dev, test) else: raise ValueError("dataset format %s not supported...
d82f097e00cffc31ee53ac1a57635a1fcc871990
46,717
import json def remove_existing_datasets(viable_datasets, connection): """Remove the viable datasets that are already existing datasets.""" for dataset_type in viable_datasets: for container, datasets in viable_datasets[dataset_type].items(): actually_viable_datasets = [] for ...
889a87d144c795b1bfe40aaad92ca1b36c64b3b3
46,718
import logging def group_by_size(input_tensors, bytes_per_pack): """Groups `input_tensors` into chunks of `bytes_per_pack`. The method preserves the original order of `input_tensors`. The grouping is best effort, each pack could have more or less bytes than `bytes_per_pack`. It only groups values with known ...
9ab5805898678b1541f116e5ef5ae1b9a1c42791
46,719
def np_emd_loss(y_true, y_pred, reduction_axis=None, num_bins=327, **kwargs): """Earth Mover Distance between two waveforms Parameters ---------- y_true : np.ndarray A tensorflow tensor defining the true waveform shape: [batch_size, num_bins] y_pred : np.ndarray A tensorflow...
d5c70b35d466d8c62efb31c91cef87da5eebd076
46,720
def adapters(text): """ Parse lines of text into a list of adapters (represented by their joltage), supplemented by the outlet (0) and your device (maximum + 3). """ adapters = list(sorted(map(int, text.splitlines()))) adapters = [0] + adapters + [max(adapters) + 3] return adapters
cb5aa44963506e8d0ea6aa0aeb89d094bfbb0bc8
46,721
def assign_bonds_to_groups(tors, group): """ | **Description:** Make a group for each torsion bond and keep track of how many members Finally it returns the biggest group. **Input:** - Tors: atoms with torsions - Group: Atoms grouped by proximity **Output:** - output: li...
8147c016efe435f46b587bc86e6fab713375bb70
46,722
def _build_generator_map(): """Build a map of sdtype to data generator. Output: dict: A mapping of sdtype (str) to a list of data generators (rdt.tests.datasets.BaseDatasetGenerator). """ generators = defaultdict(list) for generator in BaseDatasetGenerator.get_subcl...
4660f8b84f1a048942e519d188b17bac10903b1f
46,723
import re def get_ignore_unknown_patterns(): """ Fetch the value of the setting that tells us what unknown overrides we should ignore in reports. The regular expressions from the settings file (if any) are compiled in the returned list. When the setting is a boolean, the result is either an empty...
5437159c9bddbc80585e31156d0740108df2dcca
46,725
def test_dal_method_middleware(): """ Verify that when calling a method on a service off the DAL, the method middlewares run, in the correct order and run before the method itself is called. We deliberately do not use the DalMethodResolverMiddleware here, because we are testing middleware call...
71f43002001b5c4bb2b43f72ac29ab4bae9e6159
46,727
def chain_functions(fun_first: tp.Callable[..., tp.Union[tp.Tuple[tp.Tuple, tp.Dict], tp.Dict, tp.Tuple]]) -> tp.Callable: """ A decorator to chain function calls. This function is expected to return: * a 2-tuple [tp.Tuple, tp.Dict] - args and k...
e78f42d30fb788751703f1b56bafd485b27c1a0e
46,728
from typing import Union import types from typing import List from typing import Tuple from typing import Set def find_variables( expr: Union[types.Constraint, List[types.Constraint], Tuple[types.Constraint]] ) -> Set[core.Symbol]: """Find variables in constraints.""" if not isinstance(expr, (list, tuple)): ...
d9b737260b1c2b5d25f6718530ed74245c76abfd
46,729
def _number_of_neighbors(i, j, height, width, state): """ Counts the number of LIVE neighbors of the cell in position (i, j). :param i: Row of the cell. :param j: Column of the cell. :param height: Height of the input state. :param width: Width of the input state. :param state: A game state...
cb88e81fb7124ef6c97de75cfecef5b11767da14
46,730
def _format_cpu_memory(container_group): """Format CPU and memory. """ containers = container_group.get('containers') if containers is not None and containers: total_cpu = 0 total_memory = 0 for container in containers: resources = container.get('resources') i...
1e1db12afd45a6d0634a6d9f701f3c3bb7bc9570
46,731
def create_category(name): """ Create a new category :param name: :return object: """ category = Category(name=name) session.add(category) session.commit() return category
512092a2b3c3c9fd4a912f99dbfe35a8645d228e
46,732
def logpost_negb(state,params): """ Compute log-posterior density values; this function assumes the likelihood is a product of negative-binomial distributions Parameters ---------- state: python list or numpy array model parameters params: dictionary detailed settings for...
0b88b2f39f70d7cd07f8cfbd9a8434f56ba306ad
46,733
import functools def matcher(callable_or_names, names=None): """ Implicitly registers it with function's __name__, "be_a_dog": @matcher def be_a_dog(x): return type(x) == dog Explicitly registers it with names "be_a_dog" and "be_canine" @matcher("be_a_dog, be_canine") def whatev...
6e79149c45ba32576d9fa7cde373d14279c401e9
46,735
def update_tree( tree: EmptyTree, oid: str, current_user: User = Depends(get_current_active_user) ): """ Update tree DB entry """ print(tree) try: selected_tree = TreeDB.objects.get(id=oid) selected_tree.species = tree.species if tree.species else selected_tree.species s...
49ac41202d2b6471574a55cacfcf746b646437b3
46,736
def get_queue_jobs(queue_name): """Get the jobs by status of a Queue. Args: queue_name (str): The RQ Queue name Returns: dict: Number of jobs by job status Raises: redis.exceptions.RedisError: On Redis connection errors """ queue = Queue(queue_name) return { ...
a5ba497545955ad5bb42406cf289d69f05b1101a
46,737
def update_lengths(lengths, eoses, idx): """Update the length of a generated tensor based on the first EOS found. This is useful for a decoding situation where tokens after an EOS can be something other than EOS. This also makes sure that a second generated EOS doesn't effect the lengths. :param l...
bad4dce46e498da09400673abacebdba8db5ddae
46,738
def delete_widget_config(id_): """Deletes a widget :param id: ID of the widget to delete :type id: str :rtype: tuple """ widget_config = WidgetConfig.query.get(id_) if not widget_config: return "Not Found", 404 else: session.delete(widget_config) session.commit(...
74e9e1568cbbcfe825dc936699682db270aa0125
46,739
def detail_view(request): """ Directs user to the detail template """ try: symbol = request.matchdict['symbol'] except KeyError: return HTTPNotFound() try: query = request.dbsession(Account) stock_detail = query.filter(Account.username == request.authenticated_us...
aa45381bce120007a6fd957b0d3c433ec0fa3303
46,740
def is_right_censored(lc, frange): """ Returns true if the light curve is cutoff on the right. """ return len(lc['t0'])-1 in frange
de2e81605db2dc2a5f073d8400e2e8ee1b46f199
46,741
def neural_net_learning_rate_input(): """ Return a Tensor for the learning rate """ return tf.placeholder(tf.float64, name="learning_rate")
3d7e21cafd617b69aafa439c238f9d16c0eb28b4
46,742
def decode_csr(b64der): """ Decode JOSE Base-64 DER-encoded CSR. :param str b64der: The encoded CSR. :rtype: `cryptography.x509.CertificateSigningRequest` :return: The decoded CSR. """ try: return x509.load_der_x509_csr( jose.decode_b64jose(b64der), default_backend()) ...
0eb7dd2acd8cd8a210969e0ea1d2e99ecca07a97
46,743
def retrieve_span(task, task_id): """Helper to retrieve an active `Span` stored in a `Task` instance """ weak_dict = getattr(task, CTX_KEY, None) if weak_dict is None: return else: return weak_dict.get(task_id)
74d003e9b2a019a8b0b1527952dabcb8a21f6e2b
46,744
def check_data(func): """Decorator function for checking possible exceptions during extraction. Args: func (obj): function used in try-except block Except: (str) : in case of exception assigns '-' for the missing data. """ def inner(line): try: return func(line)...
b9dad9ff8adbee9f8307c4c61fc2d5e1918092e2
46,745
def fscale(ns, si=1, one_sided=False): """ numpy.fft.fftfreq returns Nyquist as a negative frequency so we propose this instead :param ns: number of samples :param si: sampling interval in seconds :param one_sided: if True, returns only positive frequencies :return: fscale: numpy vector contain...
f6cf820c184651396c3fc61a366391c9d03f086b
46,746
def get_features_from_files( data_dir, features_ext='.proc.c3d-avg.npy', test_split=[], classes=None, max_elements=13320): """ Creates and executes mPyPl pipe to load feature vectors from serialized files and returns a preprocessed data stream that can be further used with respect to...
f53f0781a6108e8e31ba75613c007368b095fdfb
46,747
import json import hashlib def crypto_hash(*args): """ Return a SHA-256 hash of the given arguments """ stringified_args = sorted(map(lambda x: json.dumps(x), args)) joined_data = "".join(stringified_args) return hashlib.sha256(joined_data.encode("utf-8")).hexdigest()
3c4329a6e99826a15e52e2921040045697ce5aa0
46,748
def vectorized(csm, e, h, r0, rm, kj): """ Uses Numpys fast array operations, distributed via the mkl-package. Those oparations are already optimized and use all available physical cores. """ nFreqs = csm.shape[0] nGridPoints = r0.shape[0] beamformOutput = np.zeros((nFreqs, nGridPoints), np.comp...
15c2fb6a9f7f8551314d0a0e9c219308dc7b2741
46,749
def is_empty_line(line: str) -> bool: """Checks whether a line is empty.""" return line.strip("\n").strip("\t").strip() == ""
ad58cc78e5f25353419682343c34c21e2679304d
46,750
def to_host_list(value): """Space separated list of FQDNs.""" return value.split()
85740e6e90096d5711022a7ae18b919673899b36
46,751
import click def drop_prediction_column(data_path, group_name, column_name, yes=True): """ Deletes prediction columns in a h5py file if the columns exist. Including 'mean' and 'std' columns. """ n_del = 0 with h5py.File(data_path, "r+") as f: if group_name not in f.keys(): ...
9ac7e06ddcf71af87b383ecefe5f3aac1a0e2159
46,752
def create_indep_noise_weight_matrix(Nbm, Knoise, gamma, g, w): """create a weight matrix for Nbm * Knoise sources projecting to Nbm targets with a fixed indegree of Knoise. no shared inputs are allowed, hence each target receives uncorrelated input of the sources are uncorrelated. """ Nnoise ...
4760fcf51d9418243df7ecb9027d81b77dd85a00
46,753