content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import FreeCAD import Part def fix_rectangle_sketch(): """Return unit square sketch function object.""" def aux_rectangle_sketch(x_length=1, y_length=1, x_start=0, y_start=0): """Helper function to drop a simple unit square sketch. The segments are carefully ordered. """ v...
08c87e930704033b3f04018f5aa51f8918bc6b15
73,904
def get_batch_data(cur_samples, is_training=False): """ Returns the training samples and labels as numpy array """ batch_src_max_len, batch_trg_max_len = get_max_len( cur_samples) # call get_max_len(): find the max length of src and target per batch batch_trg_max_len += 1 # may be EOS rela...
9c0e96d3bb891c2281321e91f53cc8a5e8029537
73,905
from typing import Any import dataclasses import yaml def human_repr(o: Any) -> str: """Convert the given object to a meaningful representation. The output is similar to YAML. """ if dataclasses.is_dataclass(o): return str(o) if isinstance(o, ArgsMixin): return format_args_mixin(...
66c5812f5563e431629eb2591ba36ef90859f4a9
73,906
def chi_squared_independence_test(arr, convert_to_table=False, yates_correction=False): """ Chi Squared Test of Independence Answers the question: Did these data come from different distributions? Or are the differences due to chance? You'll notice on a 2x2 contingency table, the p-value is the same a...
9b0e923dfc38a3ec9524ab64604a5d81d53adb4a
73,907
def binarize_output(out): """Get (0, 1) array from a batch of vectors, using threshold at half their mean""" out_mean = np.mean(out, axis=out.ndim - 1) # noinspection PyArgumentList threshold = (out_mean.max() - out_mean.min()) / 2 return np.where(out_mean > threshold, 1, 0)
64c06b0d3d60fb1b604197214872b03e2e4d2917
73,908
import inspect def get_callable_parameters(callable_: callable): """Given a callable object (functions, lambda or methods) get all it's parameters, each parameter annotation (a: str, b: int), default value (a=1, b=2) and kind (positional, keyword, etc). If no annotation or default value None. Example: def say_...
e9f232b209087ecaf77b5d82d1ac19f43bf937cb
73,910
def index(request): """Timesheet entry view utilizes Form defined in models.py""" if request.method == 'POST': form = TimesheetForm(request.POST) if form.is_valid(): form.save() else: return render(request, 'timesheets/index.html', {'form': form}) return rend...
695eb551df7d88c3bdcd5ad4e98a8de47d4c5b98
73,911
import collections import functools def get_config(): """Generates the config for the experiment.""" name = 'graph_indep_binary_new' n_stages = 20 shape = 2 scale = 0.5 tol = 0.001 alpha = 0.2 beta = 0.5 langevin_batch_size = 100 langevin_step_count = 200 langevin_step_size = 0.0005 epsilon = ...
3e3a2a68d7e003587b07c5a9ece01829c0985ede
73,912
def calc_aca_from_targ(targ, y_off, z_off, si_align=None): """ Calculate the PCAD (ACA) pointing attitude from target attitude and Y,Z offset (per OR-list). :param targ: science target from OR/Obscat (Quat-compliant object) :param y_off: Y offset (deg, sign per OR-list convention) :param z_off:...
3ccd1611df9a0b6c8f42a9e627b27872be36a63c
73,915
def generate_anchor_bases(base_size, ratios, scales): """ Generate all anchors bases :param base_size: :param ratios: :param scales: :return: """ # generate same shapes on every location px, py = (base_size - 1) * 0.5, (base_size - 1) * 0.5 anchor_bases = [] for r in ratios:...
a7cc8e5c61dbba41bce45719376e7320edcf0f20
73,916
def get_gallery_images(context): """ Returns a list of img related objects selected as 'gallery' """ try: obj = get_context_object(context) return obj.image_set.filter(img_type='gallery') except: return []
edb239ab0e3cabcac6d2ec1681412cff43a2b7ba
73,917
def getdata(fn, *args, **kwargs): """Get the FITS data. Small wrapper around `astropy.io.fits.getdata` to auto-determine the FITS extension. This will return the data associated with the image. >>> fits_fn = getfixture('solved_fits_file') >>> d0 = getdata(fits_fn) >>> d0 array([[2215, ...
7c716417fce16331b831d5db461e69a04ad73bb6
73,918
def get_community_repo() -> Repository: """Return main mock repo.""" return Repository( name="mock-qiskit-terra-with-success-dev-test", url="https://github.com/MockQiskit/mock-qiskit-wsdt.terra", description="Mock description for repo. wsdt", licence="Apache 2.0", labels=...
5544dac45514b6468571444294ea469f400d5a8c
73,919
from typing import Dict from typing import Any import pickle def serialize_dlv2_checkpoint(dlv2_checkpoint: Dict[str, Any]) -> bytes: """ Handling the checkpoint conversion from DataLoader V2 format to bytes format. """ return pickle.dumps(dlv2_checkpoint)
ae5c42d0daea42e61ff77c8b52aba30586657e7c
73,920
def generate_otb_mat_cell(res, gts): """ Creates the MAT content. Args: res: Nx4 array: predicted bounding boxes. gts: Nx4 array: ground truth bounding boxes. Returns: A MAT cell to be saved. """ attr_dict = {} attr_dict['res'] = res attr_dict['type'] = 'rect' attr_di...
5d11e18cbe88bf20776062cc48adbff76b3cd6f3
73,921
def get_random_cohort(course_key): """ Helper method to get a cohort for random assignment. If there are multiple cohorts of type RANDOM in the course, one of them will be randomly selected. If there are no existing cohorts of type RANDOM in the course, one will be created. """ course = courses...
4fdf161d15f7f48f84549c13cf8e56858f36d6d0
73,922
def read_multi_tiff(path, start_z=None, stop_z=None): """ path - Path to the multipage-tiff file returns images stacked on axis 0 """ try: img = Image.open(path) if start_z is not None: img_itr = ImageSequence.Iterator(img) img_itr.position = start_z ...
7b5ce0ea1806f834c1f40b7131a7e680c8921f29
73,923
def Outputs(running_info): """ Convenience proxy function to allow returning the outputs generated by a process """ if isinstance(running_info, Future): # Create the correct information from the future rinfo = RunningInfo(RunningType.PROCESS, running_info.pid) return Action(rinfo...
482822bcb2af40986c223efbe2b44b8ebd069ee3
73,924
import json def authenticate_url(): """ :return: """ crate_logger.info("authentication flow initiated.") bottle_app.oauth = setup_oauth(r_c, conf_obj, store_tokens_callback) auth_code = bottle.request.POST.get("code") return json.dumps( [ el.decode(encoding="utf-8", er...
f8c206bbeff74a633521c959b6034fd7f2194041
73,926
def load_placer_with_does(filepath, defaults={"do_permutation": True}): """ load placer settings Args: filepath: a yaml file containing the does and placer information Returns: a dictionnary of DOEs with: { doe_name1: [(component_factory_name, parameters), ...] ...
6dd0b9c69405036428d48fa03605c90c3f8094d8
73,927
def validate_login(username=None, password=None): """ Validate Credentials """ # False if Invalid Credentials return bool(username == DASH_USERNAME and password == DASH_PASSWORD)
15b0ca74c9a47a23ffb6fd2e8ea8cc243fc525ea
73,928
def modify_correlation_clusters(correlation_matrix, N_realizations, N_trials, N_exc, N_cluster): """ Modifies the correlation matrix to between only clusters :param correlation_matrix: correlation matrix :param N_realizations: number of realizations :param N_trials: number os trials per realizations :param N_exc:...
44f029b32a242d727a170635274c58221dcfc987
73,929
def net_heating( dlw_sfc: xr.DataArray, dsw_sfc: xr.DataArray, ulw_sfc: xr.DataArray, ulw_toa: xr.DataArray, usw_sfc: xr.DataArray, usw_toa: xr.DataArray, dsw_toa: xr.DataArray, shf: xr.DataArray, surface_rain_rate: xr.DataArray, surface_temperature: float = _FREEZING_TEMPERATURE...
1df9239cd494e99acc19efeded6becb85f11ab43
73,930
def diff_struct(o1, o2): """Return difference of structs. If their type differs, returns (o1,o2) (old value/new value) If they are lists, returns diff_seqs(o1,o2) If they are tuples, returns diff_seqs(o1,o2) If they are dicts, returns diff_dicts(o1,o2) """ if o1 is o2: return False ...
06abd8d4810b0204f2f14216791f11732757459a
73,931
import math def calculate_free_offers(item, quantity, basket): """removes discounted items from basket""" discounted_price_total = 0 quantity_remaining = quantity for q, free_item_basket in free_offer_table[item].items(): free_multiples = math.floor(quantity_remaining / q) print(free...
5dfe25ceaaf93998bfe0512bd40ae50871b85909
73,932
def GetGroupList(setting): """ Get all avilable group definition from setting @return: configargparse.parse_args() result """ groups = set() for name in setting: dev = setting[name] format_, group = GetFieldDef(dev, fields="format_, group") if group is not N...
d95f68d25cec9fdba54e13098e4f66656246ef7f
73,935
def _reduced_form_vectors(box_vectors): """Get reduced vectors from vectors. Adapted from HOOMD-Blue's documentation on periodic boundary conditions: https://hoomd-blue.readthedocs.io/en/stable/box.html """ v1 = box_vectors[0, :] v2 = box_vectors[1, :] v3 = box_vectors[2, :] lx = np.li...
5300af6f8ad2ff39432d86dc0de99f46a6c938a6
73,936
def process_list_data_sources(data): """ Returns a Pandas DataFrame from the API call. :return: A pandas DataFrame. """ lines = [{'name': x, 'description': y} for x, y in data] return pd.DataFrame(lines)
16b0513ed8d809632eaa5b9f30d838be3cc9dd27
73,937
def to_geojson(shapes, buildings): """Converts the shapes into geojson. This function will combine the burn scar region and buildings into geojson. Burn scar polygon in red, buildings polygon all in blue.""" #append burn scar region polygons to geojson if type(shapes) == list: results = ({ ...
fb0d417ab3c049d4b89e14dea1f15a3f40f42803
73,939
def logout(request): """ 退出 :param request: :return: """ request.session.clear() return redirect('/login.html')
8f9426e84a9db34eb61dd7acec4f26f87f4c2121
73,940
def demo(span=27.4, period=12.345678, mean=17, amplitude=1.0): """ Demonstration of the TESS noise calculator, by default on a faint and highly-variable star. """ # create times at a half hour spacing t = np.arange(0, span, 0.5 / 24.0) n = len(t) # create a (perfectly smooth) noiseless...
444339d19d9f50b46eee305ae4def4f60f4f65f6
73,941
def approx_kde(data, bins=500, bw=0.075): """A fast approximation to kernel density estimation.""" stds = 3 #use a gaussian kernel w/ this many std devs counts, be = np.histogram(data, bins=bins) db = be[1]-be[0] pad = 0.5*bins*bw*stds*db pbe = np.arange(db, pad, db) x_out = np.concatenate((...
04dd6e0c4abe286b49933c1bb41ec9d18d793e47
73,942
def moving_average_convergence_divergence( df: pd.DataFrame, window_slow: int = 26, window_fast: int = 12, window_signal: int = 9 ) -> pd.DataFrame: """ This function is a trend-following momentum indicator that shows the relationship between two moving averages at different windows: The MACD is usually...
52d2511af5a73b55290acd18d38917eea19ff6e6
73,943
import numpy def label_ids(array): """ Returns (sorted ndarray of) unique positive elements of array. Made obsolete by segment.extractIds? """ # get all unique elements and keep those that are positive all = numpy.unique(array) pos = all.compress(all>0) return pos
10158dbfea6e5512ee3d81f6c51cfb7a3828bdf1
73,944
def getMeltCurveData(excelFile, sampleData): """ Grabs melt curve data & merges w/ sample-specific information """ meltData = parseQuantStudioSheet(excelFile, "Melt Curve Raw Data") meltData.dropna(thresh = 3, inplace = True) strCols = ['Well', 'Well_Position'] intCols = ['Reading'] flo...
97c8e3accb1703103561942bfcf4ec2e11d14a6c
73,945
def cast_to_complex(tensor): """Casts a floating-point tensor to the corresponding complex dtype. In other words, cast `float32` to `complex64` and `float64` to `complex128`. If the tensor is already complex, it retains its type. Args: tensor: A `Tensor`. Returns: The cast tensor. """ return tf...
3ad2c01b11ce599cf01fbc92f1aed0569afdb8f0
73,946
def vyhodnot(pole): """1-D piškvorky se hrají na řádku s dvaceti políčky. Hráči střídavě přidávají kolečka (o) a křížky (x).""" if 'xxx' in pole and 'ooo' in pole: return '!' elif 'xxx' in pole: return 'x' elif 'ooo' in pole: return 'o' elif '-' not in pole: retu...
c647d7f5891ba50d495a0aae5ead57b83594969d
73,947
import re def get_product(title): """Extract protein product from sequence title. Parameters ---------- title : str original title which reads "product [organism]" Returns ------- str product Notes ----- NCBI protein product xyz [organism] """ title =...
7754e3b90f2119716e64c6a3f60e82c5a6cf8033
73,948
def split_and_save( audio, destination, prefix, clip_duration=5, clip_overlap=1, final_clip=None, dry_run=False, ): """ Split audio into clips and save them to a folder Arguments: audio: The input Audio to split destination: A folder to write clips to ...
3cd7993dd25e437c3a455290cf339525683b4520
73,949
def get_manager(): # noqa: E501 """Returns display # noqa: E501 :rtype: List[Rotator] """ return render_template("manager.html")
18859f509cd9330cd6617cf3dada833f8329b198
73,950
from sklearn.model_selection import StratifiedKFold def sklearn_kfold(xys: np.array, n_splits: int=5, shuffle: bool=False, random_state: int=None): """ StratifiedKFold of sklearn, 留一K折交叉验证数据获取 Args: xys: np.array, corpus n_splits: int, number of folds. must be at least 2. shuffle: ...
9a58ed9bd0998efbd91104973d772008626394ba
73,951
def phone_brands(df): """ >>> import pandas as pd >>> df = pd.read_csv(r'../data.csv') >>> phone_brands(df) {'others': 1912, 'Huawei': 1977, 'LG': 622, 'Apple': 2910, 'Xiaomi': 1491, 'Samsung': 4738, 'Motorola': 584, 'OPPO': 542, 'Vivo': 575} """ brands = {} brands['others'] = 0 # ge...
19bc556d0882d5efa73f88f4f58f8090f6ed3fe1
73,952
def get_c_type_from_numpy_dtype(dtype_specified): """ Get the ctype corresponding to a given numpy.dtype :param: dtype_specified - the numpy.dtype :return: the ctype corresponding the the dtype_specified. None unable to match """ typemap = {} for t in (c_byte, c_s...
57c3bf6104c0c68e9c1986ce9f5809937b36abb9
73,953
def geometric_sum(n): """ calculate the geometric sum of n-1 :param n: :return: """ if n < 1: return 1 else: return 1 / (pow(2, n)) + geometric_sum(n - 1)
6e482e16fdbbc833ef56e72779fcfbab155cbfcb
73,954
def choose_display(): """ prompt user to choose scale bar display """ choices = ["d","theta","both"] temp_choice = "false" while temp_choice not in choices: temp_choice = input("Please choose the scale to display.\nd, theta, both\n") if temp_choice not in choices: ...
8f03dbfbbf250881ecb6a27e4de332bdac4dfcd2
73,955
from ucscsdk.mometa.aaa.AaaDomainGroup import AaaDomainGroup def locale_domaingroup_assign(handle, locale_name, name, domaingroup_dn="domaingroup-root", descr=None, **kwargs): """ assigns a locale to domaingroup Args: handle (UcscHandle)...
990f1d14df59dbac011ae2f0ad0c2c9dc1efc69e
73,956
def f_activation(z): """ Numerically stable version of the sigmoid function (reference: http://fa.bianp.net/blog/2019/evaluate_logistic/#sec3.) """ a = np.zeros_like(z) idx = (z >= 0.0) a[idx] = 1.0 / (1.0 + np.exp(-z[idx])) idx = np.invert(idx) a[idx] = np.exp(z[idx]) / (1.0 + np....
9bfb48642988519ce74c0b2f2aa9c8b6cc99cac2
73,957
def getAllCombinations(cond_): """Returns all possible combinations of features for training on""" lst = [ "total_bytes", "max_bytes", "1->2Bytes", "2->1Bytes", "1->2Pkts", "2->1Pkts", "total_pkts", "number_ms", "pkt_ratio", "time_s...
9d4324170dcb21779290398ad744dec32fff30be
73,958
def model_12(GPUS = 1): """ two dense layers: 1000, 800 """ model = Sequential() model.add(Convolution3D(60, kernel_size = (3, 3, 3), strides = (1, 1, 1), input_shape = (9, 9, 9, 20))) # 32 output nodes, kernel_size is your moving window, activation function, input shape = auto calculated model.add(BatchNormali...
73ee7710831e4739e668df7d6844e74df64c93a0
73,959
def _tensor_to_jax(value: Tensor) -> DeviceArray: """Converts a PyTorch Tensor into a Jax DeviceArray.""" tensor = torch_dlpack.to_dlpack(value) tensor = jax_dlpack.from_dlpack(tensor) return tensor
ee666be90a332de6dc0798cf9fce8f672b1e0f1f
73,960
def profile(column: Column): """ Performs summary of single column object Parameters: column: Column object to profile Outputs: profile dataframe """ col_full = ".".join((column.ds_name, column.name)) profile_init = pd.DataFrame.from_dict(column.get_summary(), orient="index")...
7098a80e07c6a89f79687308d73584d102f237f8
73,961
def make_rmg_database_object() -> RMGDatabase: """ Make a clean RMGDatabase object. Returns: RMGDatabase A clean RMG database object. """ rmgdb = RMGDatabase() return rmgdb
7cc195b48e64a6472bd4b7f3d4b55974a390b2f4
73,962
def edit_application(request, club_name): """Edits current application for a club with an updated statement""" club_applied = Club.objects.get(club_name=club_name) application = Application.objects.get(user=request.user, club=club_applied) form = ApplicationForm(instance=application) if request.meth...
be0c7687d0458e8df8f969de9457978ae22d762b
73,963
def reverse_bits(n, width=8): """Reverse bit order (not the fastest way)""" b = '{:0{width}b}'.format(n, width=width) return int(b[::-1], 2)
d001babf6d3219ff9de7994e2719ebafe9561208
73,965
def xf_screenname(name): """Insure user screen name is prefixed with '@'.""" return '@' + name if name[0] != '@' else name
6229a22907c4b1c11b75f5cd0218e056d46111eb
73,966
import ast def p_pyatom_dict(p, kv_pairs=2): # [key: value, ...], [:] """pyatom : LBRACKET dictents RBRACKET pyatom : LBRACKET COLON RBRACKET""" if kv_pairs != ':': keys, values = map(list, zip(*kv_pairs)) else: keys, values = [], [] return lambda: ast.Dict(keys, values)
81a50745298106c9919c080629851fb57b5f1d1f
73,968
import json def GetComment(request): """ 接收畅言的评论回推, post方式回推 :param request: :return: """ arg = request.POST data = arg.get('data') data = json.loads(data) title = data.get('title') url = data.get('url') source_id = data.get('sourceid') if source_id not in ['message']: ...
02af6f8d96d8eb4a9ae8d2849b726a3c97c73cb6
73,969
def IsInsitu(): """Returns True if executing in an insitu environment, else false""" global ActiveDataDescription if vtkInSituInitializationHelper.IsInitialized(): # Catalyst 2.0 return True # Legacy Catalyst return ActiveDataDescription is not None
ee0c01f32c3ec3c14eab8426c2781c17451aba10
73,970
def CreateBackup(backup_ref, description=None, labels=None, retain_days=None, delete_lock_days=None, client=None): """Creates a backup resource by calling Backup for GKE service and returns a LRO.""" if client is None: client =...
cdef7e750231d970c4267c2490a6ee46116ce232
73,971
def test_materializer_source_execution_parameter_changes_when_materializer_changes(): """Tests that changing the step materializer changes the materializer source execution parameter.""" @step def some_step() -> int: return 1 class MyCustomMaterializer(BuiltInMaterializer): pass ...
fd502a40e9b34189ebdb7f499270e1f1b74bc7fc
73,973
import math def coefficients(deriv, acc): """ Calculates the finite difference coefficients for given derivative order and accuracy order. Assumes that the underlying grid is uniform. This function is available at the `findiff` package level. :param deriv: int > 0: The derivative order. ...
64c2bf67fb3e8fa0c46219021c5106ad9cbb3edd
73,974
from typing import List from typing import Dict from typing import Any def compare_numbers_subset( record_1: List[Dict], record_2: List[Dict], options: Dict[str, Any] ) -> Dict[str, Any]: """One set of numbers must be a complete subset of the other without leading zeroes. """ meta = {'function': '...
cd55bdf2da9c8aca478cb1a5fae4e13649a38f98
73,975
def add_join_id_column(spark_session, df_src, df_weights, src_col_name, weights_col_name): """ :param spark_session: the spark session :param df_src: spark datafarme which need to be updated with join_id :param df_weights: spark datafarme with weights_col_name and 'join_id' :param src_col_name: ...
85e30ab799ade621a37e33ebbbea6659c8e72565
73,976
def c(*args: str) -> str: """Joins all strings together""" return "".join(args)
d3361fa1e62814b9023aaa219f0f38131d20a778
73,977
def WaveformQuality_ClassName(): """WaveformQuality_ClassName() -> char const *""" return _DataModel.WaveformQuality_ClassName()
aa22f1f200ea2cee8b1339d9bf4460b90b0f05c5
73,978
def diff_matrix_permutation(node_tuples, ref_axis): """Return a :mod:`numpy` array *permutation* of integers so that:: diff_matrices[ref_axis] == diff_matrices[0][permutation][:, permutation] .. versionadded:: 2020.1 """ ntup_index_lookup = {nt: i for i, nt in enumerate(node_tuples)} if r...
0cb8eac86f86e993d7120e838049595237fd367b
73,979
import torch def separation_loss_p(x, delta): """Computes the separation loss. Args: xyz: [batch, num_kp, 3] Input keypoints. delta: A separation threshold. Incur 0 cost if the distance >= delta. Returns: The seperation loss. """ bs = x.size(0) num_kp_p = x.size(1) t1_p ...
f277c84ecd14fe50b967937bb8b4f8d5f2b98118
73,981
def resize_image(img): """ Resizes an image into four different sizes. Parameters ---------- img: A `PIL.Image` to be resized. Returns ------- A list of four resized `PIL.Image`s. """ width, height = img.size larger_dimension = width if width > height else height scale...
ccc9ccda435e93de35a9c6afc024c7b0057c3de0
73,982
def match_reqs(reqs_str: str): """ Match the requests string. Extract the request operations and the possible version string. """ if not reqs_str: raise ValueError("input string is empty.") if ',' in reqs_str: reqs_map = map(str.strip, reqs_str.split(',')) reqs = list(re...
2323eae43645d4287ca0b25324ba9eee47bcbcf0
73,984
from typing import Iterator from typing import Mapping import json import time def json_success_handler(results: Iterator[Mapping]) -> str: """A success handler which returns results in a JSON-formatted response. Args: results: The results of all checks which were executed for a checker. ...
4c2db51f412864135e4d89ce386e2b78eeaab3da
73,985
def scan_object( uri, resource, partial_path ): """ Scans an object for a matching URI Args: uri: The URI to find resource: The object to scan partial_path: An array of strings containing the path discovered for the current resource Returns: True if there's a match; Fal...
f52d754b38da43ef345596353ae96009d9bf89fb
73,986
def sp_batch_map_coordinates(inputs, coords): """Reference implementation for batch_map_coordinates""" coords = coords.clip(0, inputs.shape[1] - 1) mapped_vals = np.array([ sp_map_coordinates(input, coord.T, mode='nearest', order=1) for input, coord in zip(inputs, coords) ]) return m...
4cdee840b878b09588a9df31c56eedb422d1b567
73,987
def func_xy_ab_args(x, y, a=2, b=3, *args): """func. Parameters ---------- x, y: float a, b: int args: tuple Returns ------- x, y: float a, b: int args: tuple """ return x, y, a, b, args, None, None, None
663517ea56949bdcc72bc92278aa667d614f0311
73,988
def limit(iterator, n=None): """Produce a limited stream of values from an iterator. If `n` is 0 or None, don't limit the iterator at all. :param iterator: An iterator of values. :param n: The maximum number of values to produce. :yield: The first (at most) `n` values from the iterator. """ ...
757669e4f6b28efcd5e811e64c416d87312d2e39
73,989
def mc_eta_to_m1m2(mc, eta): """Convert eta to m2 and m1 >= m2.""" if eta <= 0.25 and eta > 0.: root = np.sqrt(0.25 - eta) fraction = (0.5 + root) / (0.5 - root) m1 = mc * (pow(1 + 1.0 / fraction, 0.2) / pow(1.0 / fraction, 0.6)) m2 = mc * (pow(1 + fraction, 0.2) / pow(fraction, ...
b0e5ec1ee42fc618b974d5f6d6a8deb62d2c110e
73,990
def create_notebook(body): # noqa: E501 """create_notebook :param body: :type body: dict | bytes :rtype: ApiNotebook """ if connexion.request.is_json: body = ApiNotebook.from_dict(connexion.request.get_json()) # noqa: E501 api_notebook = body error = store_data(api_noteboo...
fc0219b7ffde4d091ca5af02f7f3b0ed5959bcfe
73,992
def find_second_pair(n, min_pair_found): """Finds a second pair of pentagonal m, m<n so that P[m] + P[n] in P and P[n] - P[m] in P""" for m in range(n-1, 0, -1): pair = m, n if min_pair_found and D_tuple(pair) > D_tuple(min_pair_found): return None if S_tuple(pair) in P a...
d875049036fe62d80208a14a2941424d1dc50f1b
73,993
def scatter_points(region, size, random_state=None, extra_coords=None): """ Generate the coordinates for a random scatter of points. The points are drawn from a uniform distribution. Parameters ---------- region : list = [W, E, S, N] The boundaries of a given region in Cartesian or geo...
793c4c219acf424f2bba1523e983619d45f56318
73,995
def GenerateRgbToHsvColorMap(): """ Generate a map from all Animal Crossing RGB colors to their respective HSV values """ mapping = {} for hsv_color in GenerateHsvACColors(): mapping[HsvToRgb(hsv_color)] = hsv_color return mapping
69a67f0b67a66ac934ae9b97c9533c4800feb6e9
73,996
def create_hparams(flags): """Create training hparams.""" return contrib_training.HParams( # Data src=flags.src, tgt=flags.tgt, train_prefix=flags.data_dir + flags.train_prefix, test_prefix=flags.data_dir + flags.test_prefix, vocab_prefix=flags.data_dir + flags.vocab_prefix, ...
3d36986a96a3e8f2f57ecbcc847652deaa3a5177
73,997
from typing import List from typing import Dict def load_mappings() -> List[Dict[str, str]]: """Load the mappings table.""" return _load_table(get_resource_file_path("mappings.tsv"))
54036ff66ea140c0b85af889166e51d5d23f3ecd
73,998
def atribuir_ponto(dificuldade): """ Esta função cria um arquivo de texto contendo o score do usuário e também realiza a operação de adição de pontos do score do mesmo. Caso o arquivo contendo o score do usuário não exista, ele cria um novo, porém este é inicializado em 0. :param dificuldade: Modo d...
e5df9054dcb871c8455e16e73910d7d2937189a3
73,999
def _trigonal_prism(): """ Returns ------- list of scitbx.matrix.col """ return _concatenate( [i + col([0, 0, 1]) for i in _trigonal_plane()], [i + col([0, 0, -1]) for i in _trigonal_plane()], )
812f586003c87a1376b9e298796b248b888be5e5
74,000
def get_lorenz_data(n_ics, noise_strength=0): """ Generate a set of Lorenz training data for multiple random initial conditions. Arguments: n_ics - Integer specifying the number of initial conditions to use. noise_strength - Amount of noise to add to the data. Return: data - Di...
8eb9d2d341cd94d445fa74a8fc914634f28dbab7
74,001
def flatten_set(curset): """ Flatten until we have a set of vector3d objects. """ newset = set() for c in curset: if isinstance(c,vector3d): newset.add(c) else: newset.update(flatten_set(c)) return newset
9fa633dd9b03aca753978d5adce52c1176eebd93
74,002
def send_post(url, data=None, headers=None): """Send HTTP POST request via ``requests`` module.""" return send_any("POST", url, data=data, headers=headers)
6a451f7b8b5658357c160ea6eee87f74483716ea
74,004
def remove_sensitive_data_from_data_diff(unsafe_data_diff): """Removes 'before' and 'after' data for fields that are sensitive, such as social security number and driver's license number """ safe_data_diff = {} unsafe_changed_keys = [] for label, values in unsafe_data_diff.items(): if la...
ac5165aefc3ee6bd7db732e2a084fe793b849996
74,005
def json_return(code, message = '', data ={}): """ 將資料轉換成dict作為API回傳的統一格式 :param code: :param message: :param data: :return: """ return {'data': data, 'msg':message, 'code': code}
70134c28c54d910c634c0ffd14b2416072ec730a
74,006
import warnings def dialog(message, timeout=0, buttons=DIALOGBUTTON_OK): """ Display a message box with an OK button. This method is equivalent to `MSGBOX(message, BTN_OK)` in UWSC. Parameters ---- message: str Dialog messages timeout: int The dialog timeout. buttons: int Button flags. ...
0c7dc7ee2900e3bc7d267e6cb17524646ed84b43
74,007
def _encode_mantissa_as_bitstring(mant): """ This is expecting an integer. The purpose of this function is to return the bit_string representation of the mantissa. The length of the string is 52 characters long and is meant to be combined with the 11 bit exponent and 1 sign bit to form a 64 bit st...
80c55419c724b7230de5f4ff492ec4af25c99a75
74,008
def depth(self, symbol: str, **kwargs): """Get orderbook GET /fapi/v1/depth https://binance-docs.github.io/apidocs/futures/en/#order-book Args: symbol (str): the trading symbol Keyword Args: limit (int, optional): limit the results. Default 500; valid limits:[5, 10, 20, 50, 100, 5...
31f3edaf58629772b3dabc02c7e96f3014038870
74,009
def mnist_train_labels_file(): """ Train images of MNSIT. :return: filepath :rtype: str """ return data_file('mnist/train_labels', HDF5_EXT)
10f37546248aebbae9a6665071da21f8a021e7d4
74,010
def connect_to_database(): """ Connect to a database Return: Cursor for db operations """ try: database = psycopg2.connect("dbname=news") cursor = database.cursor() except psycopg2.Error as err: print("Failed to connect to the PSQL database: \n", err) ret...
59c959fba5c9cd303abfd1f714a16c33a57b967e
74,012
def quadratic_formula(a, b, c): """Solve the quadratic equation 0 = a*x**2 + b*x + c using the quadratic formula.""" if a == 0: return [-c / b, np.nan] disc = b**2-4 * a * c disc_sqrt = disc**0.5 den = 2 * a roots = [(-b+disc_sqrt) / den, (-b-disc_sqrt) / den] return roots
765092d59c3fe5d8fd9a63d9238cb5b3c5662d5e
74,013
from datetime import datetime def get_data( ticker: str, limit: int, subreddits: list, before: str, after: str, minimum_upvote: int ) -> pd.DataFrame: """ Retrieve submissions from RedditAPI using predefined parameters Args: ticker (str): ticker to search for l...
6e97a28b2abe100f3221e2fda374ccf9dbc0ec42
74,014
def plot_regional_yw(wk_recent_regional_agg_df, regional_acc_color_pal): """ Plot Year Week graph across KPI and Regional account. Parameters ---------- wk_recent_regional_agg_df : pandas.core.frame.DataFrame Filtered grouped_summary_df obtained from get_regional_summary_df(). regional_...
de9ab1436d9dab7adfefb656e6100403ddcde6b2
74,015
from typing import Counter def get_kl(a, b): """ Computes the KL divergence """ epsilon = 0.00000001 c1 = Counter(a) total1 = sum(c1.values()) + len(c1) * epsilon c1c = [(c1[cat] + epsilon) / total1 for cat in sorted(c1.keys())] c2 = Counter(b) total2 = sum(c2.values()) + len(c1) ...
d57b5d55bd6f9032dd48f193ff89194f1aed92d1
74,016
import copy def convert_quantity(x_in, to_unit, factor=1.): """Check if astropy quantity and apply conversion factor Parameters ---------- x_in : float or quantity input to_unit : astropy.units unit unit to convert to factor : float Factor to apply if input is not a qu...
dda40b7de4fab15131c764585e28b79b35cb54bc
74,017
from typing import List def source_type_exclusion_criterion(source_types: List[str]) -> BinaryExpression: """Criterion to exclude sources that are of the given type.""" return DataSource.type.not_in(source_types)
1188c35bdd51fa3121c776d7f25cbd16104390f5
74,018
def detect_publisher(extras): """ Detect publisher by package extras :param extras: dict :return: str """ publisher = None if 'publisher' in extras and extras['publisher']: publisher = strip_if_string(extras['publisher']) for i in range(1, 6): key = 'publisher_' + str(i...
0ec0fc199f29ee4c372616f1819ae8454361a9f5
74,019