content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def apply_tweet_text_preprocessing(text: str) -> str: """Make Text Preprocessor object and apply some basic techniques to preprocess tweet text. Args: - text(str) Returns: - preprocessed_text(str) Note: - We opt for lemmatizing in this use case, just that the example output looks...
11230c2a33719997b2315fcbdfc778db6d3b4f5d
49,007
def addheader(datasets): """ The columns of the pandas data frame are numbers this function adds the column labels Parameters ---------- datasets : list List of pandas dataframes """ header = get_header() for i in range(0, len(datasets)): datasets[i].columns = header...
9e7ba2bbdca8ceaabdba1cd4f8647a78d0fd05d5
49,008
def gain_filt(b, a): """Step response from filter (used as initial conditions later) Parameters ---------- b: ndarray filter coefficients a: ndarray filter coefficients Returns ------- zi : ndarray step response as a vector """ # max. length of coefficie...
e23cb2d572ee780b464e8537732d428440082d4f
49,009
def vax_pacient(ime, priimek, cepivo): """Funkcija v bazi popravi podatek o cepljenu dolocenega pacienta. Ce osebe ni v bolnici, je nemoremo cepiti. Pravice ima samo zdravnik.""" return None
e9628a857fee3918b9ad3c6ed4293933c970e30c
49,010
import pickle def read_results_pickle(path): """Reads a resultset from a pickle file. Parameters ---------- path : str The file path from which results are read Returns ------- results : ResultSet The read result set """ with open(path, 'rb') as pickle_file: ...
cf725e210637e73d19b1c1dce21aae48e99d4782
49,011
def get_sample_mean(values: list) -> float: """ Calculates the sample mean (overline x) of the elements in a list :param values: list of values :return: sample mean """ sample_mean = sum(values) / len(values) return sample_mean
182befe514f406340f0b1f37e892ad1add1f0ed2
49,012
def _encode_raw_complex(data, prm): """ Encode raw complex data.""" payload, content_type = prm.encode_raw(data) return ResultAlt(payload, identifier=prm.identifier, content_type=content_type)
eb2bb0324c6311188dc817d1d02beb14891b2466
49,013
def polyfill_integers(generator, low, high=None, size=None, dtype="int32", endpoint=False): """Sample integers from a generator in different numpy versions. Parameters ---------- generator : numpy.random.Generator or numpy.random.RandomState The generator to sample from. I...
b4061e8ec7cb9927bbe4fcce1c847aecdc10052b
49,014
def rotate(points, rot_vecs): """Rotate points by given rotation vectors. Rodrigues' rotation formula is used. Args: points (array): points to rotate rot_vecs (TYPE): rotation vector Returns: TYPE: rotated points """ theta = np.linalg.norm(rot_vecs, axis=1)[:, np.newax...
d9ee1909294ef0a4bed65076c6b59e2ae5cc24ec
49,016
from typing import Optional def sigU(backend: Optional[BackendType] = None, dtype: Optional[DtypeType] = None) -> tn.Tensor: """ Pauli 'up' matrix. Args: backend: The backend. dtype : dtype of data. Returns: U : The Pauli U matrix, a tn.Tensor. """ vals = [[0., 1], [0...
24c30dede5bca7d13914f1fcea41964a220550d7
49,017
def add_trapeziums(dfmmodel, principe_profielen_bov_df, principe_profielen_ben_df, closed=False): """Add trapezium profiles on branches with missing crosssections.""" #siebe 22-6-2021: nu twee dataframes: een voor bovenstrooms een voor benedenstoomse zijde tak xs = dfmmodel.crosssections for branch in x...
e4dd88ef18b9592b9539b14618342861be4d9ac6
49,018
def get_one_uniform_value(value_range_or_upper_bound, lower_bound=0): """ return a random value from a specified interval or [0, 1] :param value_range_or_upper_bound: list or upper and lower limits or float of upper bound :param lower_bound: float, lower limit :return: single float value """ ...
15670fc685a74a2d2f1e4d8f4ed5494b05c5500e
49,019
def efficientnet_b2c(in_size=(260, 260), **kwargs): """ EfficientNet-B2-c (like TF-implementation, trained with AdvProp) model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, de...
65b371db5995994cfcaf473c55a33f6401b05661
49,020
def tapis_user(token: str = Depends(tapis_token)): """Get Tapis user profile for the provided token.""" try: t = _client(token) except BaseTapyException as exc: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Token was not valid: {0}".format(exc...
d0d0ffb1fbca24fdeeb30071f4dfb3c2d6d8c657
49,021
import numpy def get_device(arg=None): """Gets the device from ID arg or given chainer's. :class:`~pycuda.gpuarray.GPUArray`. Args: arg: Value to specify a GPU device. Returns: Device object specified by given ``arg``. The rule of device selection is following. ===========...
32050a1ca6139167c77aebcce62ea3a2a4f49db0
49,022
def find_node_named_graph(dataset, node): """ Search through each graph in a dataset for one node, when it finds it, returns the graph it is in :param dataset: :param node: :return: """ if isinstance(node, rdflib.Literal): raise RuntimeError("Cannot search for a Literal node in a dat...
d4366c09313d3fba90ba84e0ca9805689dc76bab
49,024
def iqr(data_list): """ Interquartile range of the data Inputs: data_list - a list of floats Outputs: val - The interquartile range of the data """ n = count(data_list) cnt = n//2 if cnt ==0: return 'NaN' data_list.sort() l_half = data_list[:cn...
30e801164c6d0d07943276f58892c8ea1a3188df
49,025
def _get_prediction(outputs): """Checks if multiple outputs were provided, and selects""" if isinstance(outputs, (list, tuple)): return outputs[0] return outputs
f6565614c3d43ca15c1b52025469561fe61ae5ab
49,026
def plot_gb_mean_errorbar(df_m, df_s): """ In: df_m: results of df.groupby().mean() renamed to have mean in col names df_s: result of df.groupby().std() renamed to have std in col names Returns: list of CustomVis objects """ # tog = df_m.join(df_s, lsuffix=" (mean)", rsu...
fc2f5f6702db5842ebef98a90865629d678409c3
49,027
def bot_answer(user_input): """ This function checks if the user input exists in the database and returns an answer. If the user input does not exists, it searches for for something similar to the user input and returns an answer. """ answer = switchboard.DB_getQanswer(user_input) if ans...
2b1edd6d7df7774184bcd8463629a1bf6befe1fd
49,029
def _setTextContent(df, txt_id, txt_content): """ Set the arbitrary text content. Args: df: DataFrame-initial information. txt_id: str-the text id. txt_content: str-the text content. Returns: df_temp: DataFrame-information after updates. """ df_TextDa...
7b9dcad59012a7b64fbd11ecb5ac85bd0d122dc8
49,030
import requests def sheet(request, ally_id): """ Alliance sheet """ request_alliance = requests.get(GLOBAL_URL+f"/{ally_id}", headers=global_headers(request)) if request_alliance.status_code != 200: return render_error(request_alliance) return render(request, "alliance/sheet.html",{ ...
4c79fb99910e1070976fd5a57726449ae76b66a0
49,031
import math def initWindKernel(direction, speed, c1): """ Function to generate the kernel for wind probabilities to apply into the lattice transitions. This version is for Moore's neighborhood only parameters ---------- direction: int, float Respect to a horizontal axis, the angl...
fff03981ccc730ecd6ec5ab793287ce356770fd5
49,032
import difflib import pprint def pprint_diff(first, second, first_name='first', second_name='second'): """Compare the pprint representation of two objects and yield diff lines.""" return difflib.unified_diff( pprint.pformat(first).splitlines(), pprint.pformat(second).splitlines(), fromfile=first...
5c88916b47cfa970d6ab15caa650540d2dab3c3b
49,033
def declare_variable(name, shape, initializer): """Helper to create a variable.""" return tf.get_variable(name=name, shape=shape, initializer=initializer, dtype=tf.float32)
0d0a99dca5e0cd4e33c2e540fcd88eb22b6b9bf6
49,034
def delete_live_instance(live_instance_id=None): """ Delete a live streaming instance :param live_instance_id: :return: boolean """ url = get_api_base() + '/livestream/%d' % live_instance_id return RestClient.delete(url=url, headers=create_headers())
57aa52b3e636a15878c945a3aa163d4780f6cc72
49,036
def inc(i): """Increments number. Simple types like int, str are passed to function by value (value is copied to new memory slot). Class instances and e.g. lists are passed by reference.""" i += 1 return i
2959f0a2d57891821a159a4a51c1b146c0cb0395
49,038
def test_linkedlist_bind(): """Test monadic bind of LinkedList Laws alone don't guarantee the desired behavior """ def f(x): return Cons(x + 100, lambda: Cons(x + 200, lambda: Nil)) xs = Cons(10, lambda: Cons(20, lambda: Nil)) expected = Cons( 110, lambda: Cons( ...
73aa30e4c98fa8bdbe2725af2d3c7892bb6a0e88
49,039
def SoftmaxCrossEntropy(inputs, axis=1, normalization='FULL', **kwargs): """Compute the softmax cross entropy with given logits and one-hot labels. **Type Constraints**: *float32* Parameters ---------- inputs : sequence of Tensor The inputs, represent [logits, labels]. axis : int, opti...
7652e6fb561e1692fa2c82eb525d7a84fd4f2f34
49,040
def checkForDonorWithRegion(op, graph, frm, to): """ Confirm donor mask exists and is selected by a SelectRegion :param op: :param graph: :param frm: :param to: :return: @type op: Operation @type graph: ImageGraph @type frm: str @t...
640f55f23474456d1937719aef0a846cee9f2407
49,041
def simulate_lognormal(mu_lim, sigma_lim, count_lim): """Simulates log normal data of a specified size Parameters ---------- mu_lim : list, float The limits for selecting a mean for the log normal distributions sigma_lim : list, float The limits for selecting a standard deivation fo...
abf8f69ee16cf5d23b10b60ab5bee6d3d1b95715
49,044
import re def extract_video_id(string): """Extract what looks like a YouTube video id from a string""" if len(string) == 11: return string matches = re.search("v?=(.{11})", string) if matches is not None: return matches.group(1) matches = re.search(r"youtu\.be/(.{11})", string) ...
30b680f48b6e9101492e29ff76f5bed1703a37d2
49,045
def get_visible_cards(cards1, cards2): """Return a list of the intersection of cards1 and cards2; call only on visible cards!""" return [card for card in cards1 if card['name'] in names(cards2)]
4728b942e9900c9810e8d1865143f38b4631dcc1
49,046
def phases_exponential_fit(phases_points, t, X, one_order): """ :Authors: Chuankai Cheng <chuankai@usc.edu> and J. Cameron Thrash <thrash@usc.edu> :License: MIT :Version: 1.0 :Date: 2021-03-17 :Repository: https://github.com/thrash-lab/sparse-growth-curve """ all_starting_time=phases_poi...
eb42c72792fc2c75bf93543fb1403a3a9b5b518d
49,047
def ascii(value): """Return the string of value :param mixed value: The value to return :rtype: str """ return '{0}'.format(value)
11cf1af6567c53a5583d8bdcb6da2431f6b79ba9
49,048
def find_closest_date(date, list_of_dates): """ This is a helper function that works on Python datetimes. It returns the closest date value, and the timedelta from the provided date. """ match = min(list_of_dates, key = lambda x: abs(x - date)) delta = match - date return match, delta
57f9ecbf764539fcea495057ba4b908df700b8db
49,050
def FormatDateTime(duration): """Return RFC3339 string for datetime that is now + given duration. Args: duration: string ISO 8601 duration, e.g. 'P5D' for period 5 days. Returns: string timestamp """ # We use a format that preserves +00:00 for UTC to match timestamp format # returned by containe...
2511ec74047451de444de1a9719b6223f9e17e94
49,051
def is_depth(da, loc="any"): """Tell if a data array is identified as depths Parameters ---------- da: xarray.DataArray Return ------ bool See also -------- is_lon is_lat is_altitude is_level is_time xoa.cf.CFCoordSpecs.match """ return xcf.get_cf_s...
1173a05380c363de23c5cda1523cdbaadae6c29f
49,052
def num_bits_64(i): """Counts the bits in a given integer. >>> num_bits_64(7) 3 >>> num_bits_64(8) 1 >>> num_bits_64(0b1100110000000000000000000000000) 4 """ # & here converts negative integers to unsigned representation first, # so we get the correct number of bits. return bin(i & BITS_64).count...
14e63fdc57754f38be4b072f950743e25ee78b90
49,053
def replace_str_index(text, index=0, replacement=''): """ Utility function :param text: :param index: :param replacement: :return: """ return '%s%s%s' % (text[:index], replacement, text[index + 1:])
a09aa93b6bb567731e77d5b7b91504cf88142fb5
49,054
from datetime import datetime def from_timestamp(timer: int) -> datetime.datetime: """ Converts timestamp to `datetime.datetime` """ return datetime.datetime.utcfromtimestamp(timer)
060932589dc87795e324dfa96208745875c05932
49,057
from typing import Any def arg(name: str, value: Any) -> str: """ >>> arg("x", 1) '`x`: <builtins.int> 1' """ return f"{tick(name)}: {val(value)}"
19d4e979aa86fdec0a5e69c972a9cc4b1c5c2226
49,058
from collections import Counter def solve_part_one(id_list: list) -> int: """ Calculates the checksum for a list of IDs :param id_list: Python list containing a list of ID strings :return: Checksum as defined by the problem """ twos, threes = 0, 0 for id in id_list: id_counter = C...
a4fe4d7b8205492e132175199121f3ed5a58b7b9
49,059
def search(lookup): """ Search for a reference on arXiv.org given a lookup string. Since the arXiv.org api can return mutiple references for a single query, this function raises an error in the case that more than one reference was returned. :param lookup: String with the lookup to search for on ar...
3b9b9d5578d2a94fc9a5148b2eb7f4d1ac45f4fa
49,060
def id_in_use(id_key, id_key_value, dict): """ Return true if an ID is already in use. """ for value in dict.values(): if value[id_key] == id_key_value: return True return False
c2f731396eecd8b58cfd381b06e9a7f127fe960a
49,061
def is_prerelease(version_str): """ Checks if the given version_str represents a prerelease version. """ return any([c.isalpha() for c in version_str])
c6454bb350b2c4e55dbc271f23253aa2e3472802
49,062
def _wrap_with_after(responder, action, action_args, action_kwargs, is_async): """Execute the given action function after a responder method. Args: responder: The responder method to wrap. action: A function with a signature similar to a resource responder method, taking the form ``...
e8351d6d46ea863f4c58761016e9cbf0ee64a3de
49,063
def text_analysis(request: dict = Body(..., examples=analysis_examples), #index: str = Path(default='country') ): """ The *analyze* endpoint allows you test out how your data will be analyzed and indexed. The default behaviour is for your search terms to be analyz...
d03b54fb354c11adbb2d9c362ceea3b7d65171b1
49,064
import re def class_name_to_resource_name(class_name: str) -> str: """Converts a camel case class name to a resource name with spaces. >>> class_name_to_resource_name('FooBarObject') 'Foo Bar Object' :param class_name: The name to convert. :returns: The resource name. """ s = re.sub('(.)...
b0ac6692c441b0f4cfca4a9b680dc612552795f4
49,065
def datetime_to_date(dt, org): """ Convert a datetime to a date using the given org's timezone """ return dt.astimezone(org.timezone).date()
92565cf65b0c485e6f8649a9a47619f516d0fd35
49,066
def raw_updates(): """Test 5: Database Updates""" connection = dbraw_engine.connect() try: num_queries = request.args.get('queries', 1, type=int) if num_queries < 1: num_queries = 1 if num_queries > 500: num_queries = 500 worlds = [] rp = part...
c582fc5e76c9c137f31a64c38f050a2361264ca9
49,067
import numpy def correlate(x1, x2, mode='valid'): """ Cross-correlation of two 1-dimensional sequences. For full documentation refer to :obj:`numpy.correlate`. Limitations ----------- Input arrays are supported as :obj:`dpnp.ndarray`. Size and shape of input arrays are supported to be eq...
ca0d71b6479eb0b62c98feb038a8b6525f8b92dd
49,068
def virtual_machine_names_to_container_names(configuration): """ convert virtual machine names to container names using configuration Args: configuration: user final configuration Returns: list of container name in array """ return [ "{0}_{1}".format( configu...
aba3ceab55d8af5041d6d784cea64a464b2d6bf5
49,069
def index(): """For testing the application on the browser during development""" return jsonify({'message': 'This is the home page'})
e0898c8062a7677ae46cae4c76e01be5b4fb7327
49,070
import requests def current_server_id() -> str: """Helper to get the current server id""" rsp = requests.get("http://localhost:10000/api/servers") if rsp.status_code != 200: raise ValueError("Failed to fetch current server id") return rsp.json()['current_server']
8ec4efcc0eeea0b5b62ce5446aece5abdf6fbd66
49,071
def mean_std_cross_val_scores(model, X_train, y_train, **kwargs): """ Returns mean and std of cross validation Parameters ---------- model : scikit-learn model X_train : numpy array or pandas DataFrame X in the training data y_train : y in the training data Retu...
5d298927a54513448c5205b3013cda3352ffaa7e
49,073
def needs_dataset(*names, default=None): """ Decorator for skipping methods when the needed atomic data is not available """ non_ion_datasets = ['abundance', 'ip', 'ioneq'] names = [f'_{n}' if n not in non_ion_datasets else f'{n}' for n in names] def decorator(func): @wraps(func) ...
a51c26102e88ed29f3ad8c07df88712d71aa52ad
49,074
def linkcode_resolve(domain, info): """Oddly this function is required for the linkcode extension.""" if domain != "py": return None if not info["module"]: return None filename = info["module"].replace(".", "/") return "https://github.com/farisachugthai/dynamic_ipython/%s.py" % file...
6f4517a977b468847d1888eafeb5c3eb8698a160
49,075
def _read_airports_file(input_file=None): """Read the airports file.""" if input_file is None: input_file = get_test_data('airport-codes.csv', as_file_obj=False) df = pd.read_csv(input_file) station_map = pd.DataFrame({'id': df.ident.values, 'synop_id': 99999, 'la...
4647f4ac849d2596ad38190c0d3c95b8fc10174a
49,077
from typing import List from typing import Dict def out_edge_node_mapper( nodes: List[GraphVizNode] ) -> Dict[str, List[GraphVizNode]]: """ A function that maps a published topic to the publisher node @params: nodes: The list of nodes of the graph @return: A dictionary where the key is t...
90c3caa538a91f806b0e5d9b0b7b919f7e9a3bb3
49,078
def CircularHarmonicCaDihedralConstraints(a,b,c,d,value,tol): """ Returns properly formated string for declaring harmonic dihedral angle constraints between CA carbons of resiedues a, b, c and d at angle "value", and "tol" standard deviation. Angles of 0 and 360 are treated as being next to each oth...
e48df4a25c27d7cf235623db9072b1d465d027c1
49,079
import torch def create_sample(G, sample_size, z_size, seed): """ Create a sample. returns ------- A set saple z. """ torch.manual_seed(seed) fixed_z = np.random.uniform(-1, 1, size=(sample_size, z_size)) fixed_z = torch.from_numpy(fixed_z).float() if gpu_available: ...
97decfa125743417c122b7c7ebdc719b1ba0478d
49,081
def get_data_day(data: pd.DataFrame) -> np.array(int): """Get weekday/weekend designation value from data. :param pd.DataFrame data: the data to get day of week from. :return: (*np.array*) -- indicates weekend or weekday for every day. """ return data["If Weekend"]
4b4cf9a4ad78970a1066626855d545f88b88bd34
49,082
def next_mesh_data_loader_uuid(): """Return the next uuid of a mesh data loader.""" global mesh_data_loader_counter mesh_data_loader_counter = (mesh_data_loader_counter + 1) % (1 << 60) return mesh_data_loader_counter
e2f9550aeafa263e7d626591e9b487095e8427d2
49,083
def log(input_t): """ Element-wise natural logarithm. """ return log_op(input_t)
72f4f358715a5e83f826654d7702cbbc89d995f9
49,085
def guess_gender(name): """ Given a person's name guess their gender. Returns either ``'m'`` or ``'f'``. """ names = name.split() if names[0] == 'Sankt': first_name = names[1] else: first_name = names[0] try: return _GENDER_EXCEPTIONS[first_name] except KeyEr...
ce8b3ae3bd188cd843e127246221d44e220e72ac
49,087
def index(): """Return the main page.""" restaurants = ["amelie_nyc", "lovemama_nyc", "upstate_nyc"] return render_template("index.html", restaurants=restaurants)
a3c7c583acf154a5f792811ea652c2bc38d204b7
49,088
def stefan_boltzmann(radius, temperature): """Calculate the luminosity for a spherical blackbody following from Stefan-Boltzmann. Parameters ---------- radius: float The radius of the sphere. temperature: float The temperature of the blackbody. Returns ------- lum: ...
60f6452e25af443f2a8f1f94ec1408a833f5a818
49,089
def put_keys_in_numerical_order(keys): """ Takes a list of hookup keys in the format of prefix+number:revision and puts them in number order. Returns the ordered list of keys """ keylib = {} n = None for k in keys: colon = k.find(':') for i in range(len(k)): try: ...
43807dc85b0485c6339697c45a19016b2dabeb25
49,090
def parse_input() -> list[int]: """ Parses the input and returns a list of depth measurements. """ with open(INPUT_FILE, "r") as f: return [int(line) for line in f]
caed6904f676c25e07d2e2d29b427cf140625880
49,091
def apply_smoothing(image, kernel_size=5): """ kernel_size must be postivie and odd """ return cv2.GaussianBlur(image, (kernel_size, kernel_size), 0)
65adc5abfc97c5c0a71a37ad12c8721bb0a38188
49,092
def convert_trie_to_flat_paths(trie, prefix=None): """Converts the directory structure in the given trie to flat paths, prepending a prefix to each.""" result = {} for name, data in trie.iteritems(): if prefix: name = prefix + "/" + name if len(data) and not "results" in data: ...
78313b1bfaad06c3364e78b8a0d460ba7aabec38
49,093
def build_cptp_data(db_path, db_name): """Builds training sets files for the SPMF library. Training sets files created using the DB. A training set file in the format expected by the java SPMF library: ' -1 ' between each number within a sequence and ' -2' to end a sequence (see `SPMF/CPT+ docs <http:/...
2cc5bd75c2ddc9a707284f79e8ad3417ebd01d73
49,094
def reflection_matrix( point: np.ndarray, normal: np.ndarray ) -> np.ndarray: """ Return matrix to mirror at plane defined by point and normal vector. Reference: https://en.wikipedia.org/wiki/Transformation_matrix#Reflection_2 """ normal = unit_vector(normal[:3]) M = np.identity(4) ...
43ea429e1616c30a83de5c5428ecbf13106f576d
49,095
def draw_hexagon(image=None, coordinates=None, radius=None, thickness=None, color_hex=None, radius_dot=None, color_dot=None, polygon_bool=None, draw_dots_bool=None): """ Generate a regular hexagon on a given image canvas with dots along the edge :param image: Pillow/PIL Imag...
d2f89cafba758b2a1f398c314b288a802f919268
49,096
def tsem(a, limits=None, inclusive=(True, True), axis=0, ddof=1): """ Compute the trimmed standard error of the mean. This function finds the standard error of the mean for given values, ignoring values outside the given `limits`. Parameters ---------- a : array_like array of value...
ae612ffe5a124ebfbb5df125e56db10c9b653665
49,097
def _parse_ligand_sdf(input_file): """ Function to parse a series of ligands - return RDKit mols. :param input_file: the file to parse :param input_type: the type of ligands :return: the molecules parsed """ mols = Chem.SDMolSupplier(input_file) return mols
949d81a8224dd30a464ea1da1201457be9e6304e
49,098
from typing import Union from typing import Type from typing import Dict from typing import List def get_anomalies_confidence_interval( ts: "TSDataset", model: Union[Type["ProphetModel"], Type["SARIMAXModel"]], interval_width: float = 0.95, in_column: str = "target", **model_params, ) -> Dict[str,...
2268fce74eeb57c99954cc33a6b4278badf2dcb9
49,099
def wrap_numbers(input_dict, name): """Given an `input_dict` and a function `name`, adjust the numbers which "wrap" (restart from zero) across different calls by adding "old value" to "new value" and return an updated dict. """ with _wn.lock: return _wn.run(input_dict, name)
fd7c26d5c756f5d2ecad3d56d3235ade1801847d
49,103
def dict_remove_empty(d): """remove keys that have [] or {} or as values""" new = {} for k, v in d.iteritems(): if not (v == [] or v == {}): new[k] = v return new
40d6b4f2e3e20cee3885efb9fe3d60fafe9a4169
49,105
def sigmoid_activation(x): """Commpute the sigmoid activation value for a given input. Args: x (array): input data point Returns: float: sigmoid activation value """ return 1.0 / (1 + np.exp(-x))
66d268ee430a0c9aadce05ca4d61735c681d01ac
49,108
def read(f, normalized=True): """MP3 to numpy array""" a = pydub.AudioSegment.from_mp3(f) y = np.array(a.get_array_of_samples()) if a.channels == 2: y = y.reshape((-1, 2)) if normalized: return a.frame_rate, np.float32(y) / 2**15 else: return a.frame_rate, y
30b3ee110e8bbc582f6f85b3c81294f1e904cb7d
49,109
def GeneticModel03(x,y, popSize, iters, mutsPerKid, dbkids=False, natCouples=1 ,clonekids=0): """ This is an hybrid model from Model01 and Model02. Params: x(np.array): x coordinate array. y(np.array): y coordinate array. popSize(int): Size of the population. ...
ccb2ed0d613137eaec95800d8f97a68dc4a04095
49,112
def show_img(img, ax=None, vmin=None, vmax=None, interpolation=None, title_=None, cbar_orientation='horizontal', plot_colormap='jet', plot_size=(12,7), sig_digits=2, plot_aspect=None, ...
60ff9aeaea2d497edfa4615fafe22b49418a89bb
49,113
def downscale_mean(arr, red): """ Downscale an image by the local mean Parameters ---------- arr: 2D numpy.array Array to reduce red: int, or couple Factor by how much the array is reduced. If couple, the first factor reduces in x, and the second in y. ...
6b521a2b2266352dca1684c200d9884c8cb18f40
49,114
def H(qbit: QbitVal) -> Gate: """ Hadamard gate. :param qbit: parameter. :return: Gate. """ root2 = 1 / Sqrt(Real(2)) return Gate('H', [qbit], H_matrix, mapping=lambda q: QbitVal((q.alpha + q.beta) * root2, ...
0a8c577ad9a390915c34448b12c9eb17aeaf126f
49,115
def run_svm_one_vs_rest_on_MNIST(): """ Trains svm, classifies test data, computes test error on test set Returns: Test error for the binary svm """ train_x, train_y, test_x, test_y = get_MNIST_data() train_y[train_y != 0] = 1 test_y[test_y != 0] = 1 pred_test_y = one_vs_rest_sv...
77ec0ff16e0ecdaceb4c28ca576e9e98c480480c
49,116
def check_expEstimates(theta, deltaT, binSize, T, numTrials, data_mean, data_var,\ maxTimeLag, numTimescales, numIter = 500, plot_it = 1): """Preprocessing function to check if timescales from exponential fits are reliable for the given data. Parameters ----------- the...
da36783ee989ae4ee1936d77e4f4beb2db99ec83
49,118
from typing import Union from typing import cast def scale_unscaled_ramp(rmin: Union[int, float, str], rmax: Union[int, float, str], unscaled: RAMP_SPEC) -> RAMP_SPEC: """ Take a unscaled (normalised) ramp that covers values from 0.0 to 1.0 and scale it linearly to cover the provided range. :param rm...
e80f437f6c8085f75ebf98293cbe838e44886af4
49,121
def get_class_name(obj): """ Returns the name of the class of the given object :param obj: the object whose class is to be determined :return: the name of the class as a string """ return obj.__class__.__name__
93be3acf545376dc1df43684da75a59e967d2b2f
49,122
def encode_bytes(bytes): """Encodes bytes as Base64 unicode string.""" return b64encode(bytes).decode('utf-8')
149ca9b94512f2bc830c20943c495ee711b3cd51
49,123
def get_starcheck_catalog_at_date(date, starcheck_db=None, timelines_db=None): """ For a given date, return a dictionary describing the starcheck catalog that should apply. The content of that dictionary is from the database tables that parsed the starcheck report. A catalog is defined as applying, in t...
d9aa25b9d55ce8510ab1b8004766efba26535f07
49,124
def result_aggregator(aggregator_fn: ResultAggregatorFn): """Transform previous aggregate and list of results into an aggregated single result. Called by load model function Args: aggregator_fn (ResultAggregatorFn): Aggregator function """ def wrapper(fn): set_scenario_attribute(fn...
6b8dd6a8b277b862d4ed4dd5082891a610e47b94
49,125
def convert_to_ipa(phrase, specialized=True): """Takes a piece of text and transibes it to the International Phonetic Alphabet (IPA). Note: some changes to transcription were made depending on the system, to not have these changed, set <specialized> to false. """ conversions = { "oʊ":...
ee823df010f55db7967116061c4fe75222d8c137
49,126
def lower_walls_plumed(*args, **kwargs): """A restraint that is zero if the argument is below a certain threshold. The restraint potential energy is given by kappa * ((arg - at + offset) / eps)**exp if arg - at + offset is less than 0, and 0 otherwise. Parameters ---------- arg : tor...
051ac9282dae1b163f745818db9c5c3b7d3728d6
49,127
import json def export_nearby_wells( req: WellsExport ): """ finds wells near to a point fetches distance data using the Wally database, combines it with screen data from GWELLS and filters based on well list in request """ point_parsed = json.loads(req.point) export_wells = r...
c406e0a995a4b2d639b7bd47989d613fec0fd802
49,129
def is_pod_not_running(pod_name, deployment_target=None, pod_number=0, verbose=True): """Returns True if the given pod is in "Running" state, and False otherwise.""" json_path = "{.items[%(pod_number)s].status.phase}" % locals() status = get_pod_status(pod_name, json_path, deployment_target=deployment_tar...
ec6d0bfe6687daab6c4fe9d4ac75855362ef6c50
49,130
def _bciPercentileBias(replicates,allData,alpha): """Simple percentile CI with bias correction""" #The jackknife, the bootstrap and other resampling plans #(See page 118) #https://statistics.stanford.edu/sites/default/files/BIO%2063.pdf alpha = alpha/2 #get z for the bias and the desired alpha...
159838547e2af1f48302258a34b2bd41625074dd
49,131
from typing import Dict from typing import List from typing import Callable from typing import Iterator def create_orth_variants_augmenter( level: float, lower: float, orth_variants: Dict[str, List[Dict]] ) -> Callable[["Language", Example], Iterator[Example]]: """Create a data augmentation callback that uses...
2a97c42d1e7a84d4afcdcdc5e62993bca7192d3f
49,132
def create_magnitude_spectrum(image): """Creates a magnitude spectrum from image params: image: A numpy ndarray, which has 2 or 3 dimensions (BGR) return: A numpy ndarray, which has 2 dimensions """ image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) dft = cv2.dft(np.float32(image), flags=cv...
0664a5236bb08bbd5604e885aec158ad29b5c8fd
49,133