content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def add_days_worked(start, days): """adds date but try to only take days worked into account""" step = get_step(start) weeks, plus = divmod(days, 5) end = start + ((weeks * 7) + plus) * step if weekday(end) >= 5: # saturday or sunday end += (2 * step) end += len([x for x in get_national_...
03471a792b7da2bd7b0bef24141ad73e19d4a56d
3,596,865
def generate_path(start, end, grid, d_move): """ (tuple, tuple, Grid object, bool) -> list of tuple Return the shortest path from start to end through the grid """ path = [start] point = start while point != end: point = next_point(point, grid, d_move) path.append(point) ...
340e486e824896ba81412b402d2c84b7dfdb047d
3,596,866
import logging def db_real_delete_for_testing_purpose(user_id): """Physically employee records based on requested parameters. This function will really delete record for teseting purpose, use with care, as per the requirement, the delete function will not be physically delete the record. Args: ...
379b922beffdfd99f742b3f5b3dd2f168e209e4c
3,596,867
def average_fields(names, var): """ given list of filenames and var, generate average field """ # open each file, and add the field data # to our averaged array for name in names: d = vtk.vtkExodusIIReader() d.SetFileName(name) d.UpdateInformation() d.SetPoi...
c0eefa063cdf07733db411609d5a8c7345ba740f
3,596,868
def constrained_solve_gmres(L,f,R,g,ind,tol=1e-5): """Constrained GMRES Solve ====== Uses preconditioned [GMRES](https://en.wikipedia.org/wiki/Generalized_minimal_residual_method) to solve the equation \\(Lx=f\\) subject to \\(Rx=g\\) on a contraint set. Parameters ---------- L : (n,n) num...
c5ebfe76df78477197dabfd97a8eb81b9fb8a1fe
3,596,869
def get_digits_data(n: int) -> np.ndarray: """ Read the digits dataset from UCI through the scikit-learn helper function. The dataset contains the flattened grayscale pixel values from 8x8 images of handwritten digits. Parameters ---------- n : int Maximum number of data points ...
009f2bbac16c2c2c879d13f6a86368eec931f1e3
3,596,870
def _PreprocessCommentByCond( cnxn, cond, _project_ids, services, _harmonized_config): """Preprocess a commentby=emails cond into commentby_id=IDs, if exact.""" return _PreprocessExactUsers( cnxn, cond, services.user, [query2ast.BUILTIN_ISSUE_FIELDS['commentby_id']])
57c1a37704ad3145d3549a8c368bfb90b193024a
3,596,871
from typing import Tuple def split_and_trim( current_indices: list[int], probs: np.array, split_idx: int, threshold: float ) -> Tuple[list[int], list[int]]: """splits the segment at the specified index and trims the resulting segments Args: indices (list[int]): the indices of the segment frames i...
c3d4255240d832399a771538328fac512aa477a9
3,596,872
def get_thread_pool_max_workers(): """Get the number of thread pool max workers.""" return int(KytosConfig().options["daemon"].thread_pool_max_workers)
24f1f592a9dc794aaeaa0590c388cf259c27c662
3,596,873
def ilcm(a, b): """Computes integer least common multiple of two numbers. """ if a == 0 and b == 0: return 0 else: return a * b // igcd(a, b)
eb8bb8b5cb0f4086a8b640e2e05c08c23dc24e19
3,596,874
def watch_running(zkclient, cell_state): """Watch running instances.""" @exc.exit_on_unhandled @zkclient.ChildrenWatch(z.path.running()) def _watch_running(running): """Watch /running nodes.""" cell_state.running = set(running) for name, item in cell_state.placement.items(): ...
9984e52b2f26fa5ce0cd373a3ec8260ff94f26e7
3,596,875
from bs4 import BeautifulSoup def parse(response, option): """ Function to extract data from html schedule :return: Parsed html in dictionary """ soup = BeautifulSoup(response.content, 'html.parser') title_blue_original = soup.find("font", {"color": "#0000FF"}).text.strip() if option !=...
2c0baadc8121ad527171177d06a18fcdb391db03
3,596,876
def compare_sheet(left_sheet, right_sheet, output_sheet, threshold): """ Compare two excel sheet objects. Return output sheet. :param left_sheet: first sheet to compare (left) :param right_sheet: second sheet to compare (right) :param output_sheet: resulting sheet object :param threshold: numer...
3044a92ebc331db327d4882b6b69fc902b0313a9
3,596,877
def flatten_bipartite_densitymatrix(bipartite_tensor): """ Flatten a bipartite state density matrix to a rank-2 matrix. :param bipartite_tensor: density matrix (rank-4) for the bipartite system :return: flatten rank-2 density matrix :type bipartite_tensor: numpy.ndarray :rtype: numpy.ndarray ""...
b8731996371d1330563b1dc6573a2565233c3363
3,596,878
import types import numpy def hpat_pandas_series_median(self, axis=None, skipna=True, level=None, numeric_only=None): """ Pandas Series method :meth:`pandas.Series.median` implementation. .. only:: developer Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_median1 ...
19e40ad7dec4eb17da496e82cf58451fadcec0e0
3,596,879
def next_time_open(location): """ Returns the next possible OpeningHours object, or False if the location is currently open or if there is no such object. """ obj, ts = utils.next_time_open(location) return obj
db4db3878b07e4b652aec058137724a436b70f31
3,596,880
import random def test_random_intervals(interval_len=16): """Tests randomly generated interval of length interval_len""" random.seed(0) intervals = list(generate_range(interval_len)) return run_intervals(intervals)
56635eabc639fae954b6bfefd92be4dc181d1b40
3,596,881
from typing import Dict from typing import Any def module() -> Dict[str, Any]: """ Returns: The schema for the `module` block """ data = { "type": "list", "schema": { "type": "dict", "schema": { "module_type": { "type"...
036e9e7b0e719ad90c9da45a002d792415c8e315
3,596,882
import numpy def pred_probs(f_pred_prob, prepare_data, data, iterator, verbose=False): """ If you want to use a trained model, this is useful to compute the probabilities of new examples. """ """ DO NOT USE. NOT MAKE ANY SENSE IN THIS CASE """ n_samples = len(data[0]) probs = numpy.zeros((n_sa...
4d24d2bf46be84357e63f05939b64dfb07980685
3,596,883
def get_token(url: str, scopes: str, credentials_dir: str) -> dict: """ Get access token info. """ tokens.configure(url=url, dir=credentials_dir) tokens.manage('lizzy', [scopes]) tokens.start() return tokens.get('lizzy')
2fa481e01c47de007a6aa844a7bf17ec8d9dd86d
3,596,886
def rgb_conv_stem(inputs, num_frames, filters, temporal_dilation, bn_decay: float = rf.BATCH_NORM_DECAY, bn_epsilon: float = rf.BATCH_NORM_EPSILON, use_sync_bn: bool = False): """Layers for a RGB stem. Args:...
027205ef1575ed7b647b979d761059a18ab7dfad
3,596,887
def mocked_response_create(*args, **kwargs): """Mock MaksuPalvelu responses based on provider url""" class MockResponse: def __init__(self, data, status_code=200): self.json_data = data self.status_code = status_code def json(self): return self.json_data ...
835c8c7949f7948e560c1709ab11ca61866d07a9
3,596,888
def randomPricing(N, s_radius): """ Returns Uniformly random prices from constraint-set S, when S = ball. Args: N (int): Number of products. s_radius: radius of ball S. """ rand_mag = np.random.uniform(low=0.0, high=s_radius) # random magnitude return( rand_mag *...
1f694719e148d58013236a8399500f4308bbdbdf
3,596,890
import uuid def remap_cols(ou_to_df): """Canonicalize the column names and add unique identrifiers for all the original DataFrames. Parameters ---------- ou_to_df : dict[str, DataFrame] Dictionary of raw DataFrames. Returns ------- dict[str, DataFrame] Dictionary of remap...
6bfb3142b394c49f90ed63393c5c4138f25c217c
3,596,891
def _instance_name_from_url(instance_url): """Extract instance name from url.""" return instance_url.split('/')[-1]
e64bc076be9480a04821e9a9a79f13e25fadad35
3,596,892
def nots(): """matches !guard, where guard is either a paranthesis or a Beq""" yield not_sign g = yield par ^ bools # type: ignore return Not(g)
d5f6bcb7594297e022fec600c9230e5d3aae9fc7
3,596,893
def get_train_test_lst(dataset: pd.DataFrame, init_train_len: int, test_len: int, split_perc: float) -> list: """ Get list of train and test sets :param dataset: dataset to use :param init_train_len: length of first train set :param test_len: usual length of test set (could be shorter for last test ...
eb4278dbae53256eafcc129f99d7c3386faebbe4
3,596,894
def create_method_config(request, responses): """ Creates a method config object, stitching together the request and reponses that are passed in :param request: a request config object. :param responses: a list of response config objects :return: a method config object """ return ApiGateway...
be1cd3d895af8462926fd60d3e6d705ff11675bb
3,596,895
from typing import Union def decrypt(receiver_sk: Union[str, bytes], msg: bytes) -> bytes: """ Decrypt with receiver's secp256k1 private key Parameters ---------- receiver_sk: Union[str, bytes] Receiver's private key (hex str or bytes) msg: bytes Data to decrypt Returns ...
b0deb682cd50201d910ec301e8a07d08f583a01f
3,596,896
def face_verify(args, command_line_parameters, external_dependencies = [], external_fake_job_id = 0): """This is the main entry point for computing face verification experiments. You just have to specify configuration scripts for any of the steps of the toolchain, which are: -- the database -- the preprocessing...
ea27510338fba41f6ec05ea082fc0ae32b4c6e6b
3,596,897
def graph_wearout(devices: dict) -> str: """ This function displays the drives' percent_used metric. """ values = {} config = dict( graph_title='NVMe disks wearout', graph_category='disk', graph_info='The graph shows nvme disks wearout (percentage_used)', graph_args='--base 1...
86b823c2127072012556b9c0ed0d295ea151fd21
3,596,898
def lnlik_C(yerr): """ constant term of the log likelihood expression """ lnC = -0.5 * len(yerr) * np.log(2 * np.pi * yerr ** 2) return lnC
ec8897164482ad304ef6e3c2c0d36e29688ff208
3,596,899
import logging def NodeVolumes(): """List all volumes on this node. @rtype: list @return: A list of dictionaries, each having four keys: - name: the logical volume name, - size: the size of the logical volume - dev: the physical device on which the LV lives - vg: the volume group to...
63709f5a394ceb40e3772285dc6051c63b17ec22
3,596,901
def random(limits, ndoe): """ Function define the experiment by randomly picking points in the designspace :param limits: Numpy array representing the limit of the desingn-space :type limits: Numpy array :param ndoe: Number of points to be sampled in the design-space :type ndoe: Integer ...
044a571fb17dd14a6f9ceed5d87ddda04dd35ed3
3,596,902
def draw_result_on_frame(frame:np.ndarray, gesture_id:int): """In-place draw gesture name on frame Parameters ---------- frame: np.ndarray dtype uint8, shape (H, W, 3) gesture_id: int gesture id """ if gesture_id == 0: # no gesture ...
cfe9971f3ce35a7dda1abf2e72feeadd8788d00d
3,596,903
import socket def get_hostname_from_address(ip_address): """ Return the DNS name for an IP address or an empty string if any error occurred. """ socket.setdefaulttimeout(0.5) try: return socket.gethostbyaddr(str(ip_address))[0] except (socket.herror, socket.gaierror): retur...
7ef678eb40dbc3c8f765adc633abd7ffcd8cd644
3,596,904
def all_bert_finetune_squad11(m:Manager)->BertSquad: """ Finetune BERT on Squad-1.1 dataset """ squadref=all_squad11_tfrecords(m) return bert_finetune_squad11(m,squadref)
7562fc3c822928df974cba361e3257bd31387fd5
3,596,905
def dbsession(request, app) -> Session: """Create a test database and database session. Connect to the test database specified in test.ini. Create and destroy all tables by your Initializer configuration. Performs SQLAlchemy table initialization for all models connected to ``websauna.system.model.meta.Bas...
cbc35449f3fe7d1d77c24f2c182d0471324acd9b
3,596,906
def prune_event(event): """ Returns a pruned version of the given event, which removes all keys we don't know about or think could potentially be dodgy. This is used when we "redact" an event. We want to remove all fields that the user has specified, but we do want to keep necessary information like ...
9ee35802efe2e82e4df3897bea9eb80984c79007
3,596,907
def calculateGC(seq): """Take a sequence as input and calculate the GC %""" gc = round((seq.count("G")+seq.count("C")) / len(seq) * 100, 2) return gc
ed0c863c31214de970d0d0efd81206084b4bfbcf
3,596,908
def get_route_name(request): # type: (Request) -> str """Get a route name from URL Dispatch or Traversal.""" if request.matched_route: return str(request.matched_route.name) return 'no-matched-route'
d7603501cb45a822ede18b93b63cfa902c48ee05
3,596,909
def df_p(x: str, group: str, df: pd.DataFrame, hue: str = None, agg_func: str = 'mean', agg: bool = False, n_quantiles: int = 10): """ returns a DataFrame with the p value. See hypothesis testing. :param x: name of column to evaluate :param group: name of grouping column :param df: pandas D...
6cb4ffc4f3b7c8d638d4cf98a7729d8df5a55cb7
3,596,911
def build_machine(system_info, core_resource=Cores, sdram_resource=SDRAM, sram_resource=SRAM): """Build a :py:class:`~rig.place_and_route.Machine` object from a :py:class:`~rig.machine_control.machine_controller.SystemInfo` object. .. note:: Lin...
5dea236c8048f2bf301fa427afbfef2b850df827
3,596,913
def flatten_selector_hierarchy(selector_hierarchy: []) -> []: """ For a given list of items we unpack them to an extended list of objects that can be manipulated by BaseSelector.flatten_hierarchy(..) Parameters ========== selector_hierarchy: [ BaseSelector, LabeledSelector, ...
bedc9fa7756c14b4eae1b6304d17a2a7e3ad39e7
3,596,915
def forget_set(bot, update, session, chat, user): """Forget every usage of the set of the previously posted sticker.""" if chat.current_sticker is None: return "You need to send me a sticker first." usage_file_ids = session.query(StickerUsage.sticker_file_id) \ .join(Sticker) \ .fil...
aba5650921c57d78fe61e6a35f230b797ac296ce
3,596,916
import re def strip_html_comments(text): """Strip html comments from text (which doesn't need to be valid HTML)""" return re.sub(r"<!--(.|\s|\n)*?-->", "", text)
4ac4c2061520a8ecdafe77884a1bae9196bc4e21
3,596,917
import json def entity_data(request): """ """ site = request.matchdict['code'] claims, site = verify_access(request, site=site) e = Entity(request) summnote, fullnote = e.data() responseBody = "{ \"summnote\":" + json.dumps(summnote) + ", \"fullnote\": " + json.dumps(fullnote) + "}" respo...
d6349d91629f05dcefc679978882a25c296a86a4
3,596,918
def find(f, seq): """Return first item in sequence where f(item) == True""" for item in seq: if f(item): return item
ed81de35efd2144b45d404ba6e0c8b42cfa337fe
3,596,919
def normal_to_uniform(x): """normal_to_uniform converts a given vector x with normal distribution (0, I) into a vector with uniform distribution. x: [float] * len(x) returns: [float] * len(x) """ length = len(x) output = scipy_norm.cdf(x) for i in range(length): limi...
f48582bf78ff62d10c33685c6dbd32c4aeb10776
3,596,920
import click def cli_option_quiet(func): """ Decorator for adding a reusable CLI option `--quiet`/'-q'. """ # noinspection PyUnusedLocal def _callback(ctx: click.Context, param: click.Option, value: bool): ctx_obj = ctx.ensure_object(dict) ctx_obj["quiet"] = value return v...
4249c71b38d24693b0064157dc313d5798d1529b
3,596,923
def setup_tdl_kernel(tdl_mode, kwargs): """Temporal kernel interface.""" if tdl_mode == 'OSD': tdline = OneStepDelayKernel() elif tdl_mode == 'EWS': tdline = ExponentiallyWeightedSmoothingKernel(kwargs['tdl_alpha']) return tdline
303be491b5eeffa2b45b2c72f6d392f2f97b66b1
3,596,925
def nodeIsDmgr( nodename ): """Return true if the node is the deployment manager""" return nodeHasServerOfType( nodename, 'DEPLOYMENT_MANAGER' )
db7cbc3c78e0bcbaa00659d3555540a4ee1257da
3,596,926
import numpy import multiprocessing import pandas def parallelize_df(df, func, n_cores=4): """Run a function parallely on a pandas dataframe. Source: https://towardsdatascience.com/make-your-own-super-pandas-using-multiproc-1c04f41944a1 """ df_split = numpy.array_split(df, n_cores) with multi...
99fcd50553465645bcbcb01b5f05b3c2062141f8
3,596,927
def alarm(duration=250): """ Red alarm; flashing bright red to dark red. :param int duration: The duration between hi/lo brightness,in milliseconds. :returns: A list of transitions. :rtype: list """ transitions = [ HSVTransition(0, 100, duration=duration, brightness=100), H...
b7785eff64b4e83d66fb72f6655dcb1d93baab93
3,596,928
def add_sparsity_gap(sparse_key, non_sparse_key, now_epoch_info, **kwargs): """Get sparse loss / non_sparse_loss.""" try: sparse_loss = find_value(now_epoch_info, sparse_key) non_sparse_loss = find_value(now_epoch_info, non_sparse_key) except AssertionError as e: # logging.warning(f"...
d50a4f6961239ec72e5ddc12bb3cb9b75cb50675
3,596,930
def supports_download(ixload: IxlApp) -> bool: """ Returns True of server supports download, else False. :param ixload: IxLoad server. """ return not ixload.is_remote or ixload.api.connection.ixload_version >= '8.50.115.333'
0aff232dd930daeb9cd7ad891101597f7b870272
3,596,931
from pydicom.dataelem import empty_value_for_VR from typing import Any from typing import Optional from typing import Union from typing import Type def convert_to_python_number(value: Any, vr: str) -> Any: """When possible convert numeric-like values to either ints or floats based on their value representatio...
fa0444a60945fca0f411aec3d6dcdd31ffcb81e3
3,596,932
def upper(inter): """Return the upper bound of an interval.""" return __pos(inter, 1)
2a8c38df876592154ca642523f93ffa3b7d837e8
3,596,933
import torch def _compute_alphas(x, c_world): """ Computes barycentric coordinates of x in the frame c_world. Args: x: Batch of 3-dimensional points of shape `(minibatch, num_points, 3)`. c_world: control points in world coordinates. """ x = F.pad(x, (0, 1), value=1.0) c = F.pa...
b17dddcae016deca783a627df2ad5f931ac9ff8c
3,596,934
def bartlett(n, normalize=1): """Bartlett window Parameters ---------- n : int Window length normalize : int, optional Normalization flag (0) don't normalize (1) normalize by power (2) normalize by magnitude Default is 1. Returns ...
e3c3788656b91dce555d5609a84f3c94d2adcf53
3,596,935
def locations(request): """Show all locations.""" locations = Location.objects.order_by('date_added') locations = locations.exclude(desc='world') context = {'locations': locations} return render(request, 'locations.html', context)
f1fa31f370bbfa19138ef9dfa6da0d71a28c4572
3,596,936
import torch def predict_mask_loss(net, img_pillow, num_patch, patch_size, bin_thresh=0.2, thresh_num_pixel=1, flag_mask_edge=False, flag_mask_inner=False, flag_equalizer=False): """ Predict if the pillow image have the defect under investigation Args: ------ net: pytorch net ...
c0bb621f8075e133135b0033be3cdba601a0e081
3,596,937
import re def indent_string(s, indent=12): """ Add the given number of space characters to the beginning every non-blank line in `s`, and return the result. """ # This regexp matches the start of non-blank lines: return re.sub('(?m)^(?!$)', indent*' ', s)
cf9603be231749f55e4a29c92c90b9139515894c
3,596,938
def generate_password(self): """ a function that generates password randomly """ auto_password = Credentials.generate_password(self) return auto_password
9c3065668c04b2d9fcf06b5318642759f44df0be
3,596,939
def detection_performance(regressor, X, Y, outf): """ Measure the detection performance return: detection metrics """ num_samples = X.shape[0] l1 = open('%s/confidence_TMP_In.txt' % outf, 'w') l2 = open('%s/confidence_TMP_Out.txt' % outf, 'w') y_pred = regressor.predict_proba(X)[:, 1] ...
a7d81dde423e10a4b4d8c8bfec99ac79718ea40a
3,596,940
def Get_Mono_Char_Strain( source, method="SPA", freq=None, f_gw_frame="observer", pn_frame="observer", out_frame="observer", inc=None, ): """Calculates the characteristic strain from a slowly evolving (monochromatic) binary black hole Parameters ---------- source: object ...
91230a193311fa93f7fd2824e3ac4e2b0a601745
3,596,941
def is_fused_matmul(node: NodeDef, activation: MaybeText = None) -> bool: """Return whether a node is a fused matmul operation with given activation """ return is_fused_op(node, 'MatMul', activation)
02b2114bf4c1abcd7d48b1eb855fc83c50bdfb5f
3,596,942
def get_movie_in_db_by_id(sapo_id): """Gets movie from database given its ID""" return db.movie.find_one({'sapo_id': sapo_id})
1c00e5701400ea511376fb189973ff2c45faaf05
3,596,943
def rename(**kwargs): """Rename one or more columns, leaving other columns unchanged Example usage: diamonds >> rename(new_name=old_name) """ def rename_columns(df): column_assignments = {old_name_later._name: new_name for new_name, old_name_later in kwargs.items()} return...
0f4c87795f663a9cab8867c4b856ef75e59e2102
3,596,944
import tempfile import shutil def zip_folder(folder: Text) -> Text: """Create an archive from a folder.""" zipped_path = tempfile.NamedTemporaryFile(delete=False) zipped_path.close() # WARN: not thread-safe! return shutil.make_archive(zipped_path.name, "zip", folder)
b6de66be401926e584b5e68c12247222fcbda1a3
3,596,945
def CV_ELEM_SIZE1(*args): """CV_ELEM_SIZE1(int type) -> int""" return _cv.CV_ELEM_SIZE1(*args)
d8adee3bf707a2525463497352eb69a0cc41d6e4
3,596,946
def inpaint_mean(x: TensorLike, mask: TensorLike) -> TensorType: """Fill the image x at the locations where mask is 0 with the mean value of the image.""" mean = tf.ones(tf.shape(mask)) * tf.reduce_mean(x) return x * mask + mean * (1 - mask)
58492c239038316cd99ced0526f337975cc4433b
3,596,947
def part_2(steps): """Function which calculates the solution to part 2 Arguments --------- Returns ------- """ max_dist = 0 for ii in range(len(steps)): dist = part_1(steps[:ii]) if dist > max_dist: max_dist = dist return max_dist
1f1dbe46fd573e0d6984f6170bbb190929e48e18
3,596,948
from typing import Tuple def _get_values_or_raise(series_a: TimeSeries, series_b: TimeSeries, intersect: bool) -> Tuple[np.ndarray, np.ndarray]: """ Returns the numpy values of two time series. If intersect is true, considers only their time intersection. ...
24eccb62db2927dce311c8df211a0287cc73e23c
3,596,949
def status_of_ec2_instance(config, instance_id): """ Get the status of an ec2 instance Parameters ---------- config : dict configuration instance_id : str instance id Returns ------- dict with instance status or None if can return None if the instance has jus...
0a2d2f92c1ad90bfb1ee79abdcc0f1ac7bb7bfcf
3,596,950
def gen_sta(a): """Generate three statistics. Arg: a: feature matrix Return: t = [mu, sd, tail], where dim(t) = 18*3 = 54 """ t = list(range(len(a) * 3)) for i in range(len(a)): t[i] = np.mean(a[i]) t[i + len(a)] = np.std(a[i]) t[i + len(a) * 2] = np.size(...
47568270f2ebb133221a5f86cac1e8e7e13ad420
3,596,951
from re import S from typing import Counter def aggregate_noises_by_edge(sample_gdf: gpd.GeoDataFrame, log: Logger) -> pd.DataFrame: """Calculates edge-level noise attributes (noises & noise_sources) from sampling points. e.g. noises = { 45: 13.2, 50: 22.1 }, noise_source = 'train' & noise_sources = { 'road':...
b6b7d87bde01866b4203d730c3578f9cf324fea3
3,596,952
def get_label_n(y, y_pred, n=None): """Function to turn raw outlier scores into binary labels by assign 1 to top n outlier scores. Parameters ---------- y : list or numpy array of shape (n_samples,) The ground truth. Binary (0: inliers, 1: outliers). y_pred : list or numpy array of sha...
d84fb9d7841b27c265e83c64c5229959e9000520
3,596,953
def parcels_arg_tuple(dimensions): """Return Parcels triplet for given dimensions dictionary""" dims = { "xt": np.array([25, 75, 125]), "xu": np.array([50, 100, 150]), "yt": np.array([30, 40, 50, 60]), "yu": np.array([35, 45, 55, 65]), } shape = (2, 4, 3) parcels_v...
0d12ba95534122c135cf8b67554ab6182423398b
3,596,954
from datetime import datetime def datetime_to_string(value, format=None): """ Transform datetime object in a string with input format :returns: formatted datetime :rtype: str """ if format is None: format = "%Y-%m-%dT%H:%M:%S.%f%z" if django_settings.USE_TZ else "%Y-%m-%dT%H:%M:%S.%f" if not isin...
9f1a76b3cdec312e19ab7532aaa60969b6851ee4
3,596,955
def is_partial(self: JSONClassObject) -> bool: """This property indicates this object is not a full version of the item it represents in the database. Only part of fields are fetched from the database. """ return self._is_partial
071bba571621353410658b005ebb295cd55a7ebd
3,596,956
def check_nanos(original_question): """Check if original_question from new Nanos survey.""" if original_question in NANOS_QUESTIONS: # Return int as will be stored as BOOL (alias for TINYINT(1))in MySQL return 1 return 0
2d4c0dd5ff18a11b06dd45a73d325bdd31156f82
3,596,957
def add_facility_id_unit_id_epa(df): """ Harmonize columns that are added later. The datapackage validation checks for consistent column names, and these two columns aren't present before August 2008, so this adds them in. Args: df (pandas.DataFrame): A CEMS dataframe Returns: ...
408d3e6d548834c8b1ceadd13f2711dbbecfcf87
3,596,958
def get_type_res_list(org_id, all=True): """ Liste der in org_id verfuegbaren Typen (Kategorien) und Ressourcen [ [typ, [res1, res2, ...], nres] ... ] Wenn all!=True: nur die Typen, in denen Ressourcen definiert sind """ ret = [] for t in get_type_list(org_id): r_t = [] for r in get_resource_list(...
16407e314e0c4e220ec9ca710ac7003ca665a9ae
3,596,959
import math def R_ac(R_dc, grouping=1, d_c=None, s=None, material='aluminum', shape='round', arrangement='stranded', treatment='untreated', f=60, prox_method='IEC_287', pipe_correction=1): """ Compute AC Resistance of a conductor cable based on DC Resistance, accounting for skin and proximity effects. ...
243002f7371358f3f674f97ab3efad8d50b16792
3,596,960
import scipy def get_ZXY_data(Data, zf, xf, yf, FractionOfSampleFreq=1, zwidth=10000, xwidth=5000, ywidth=5000, filterImplementation="filtfilt", timeStart=None, ...
683ab5edab27943e532581df002e26ff48c8aef1
3,596,961
def pytest_namespace(): """ Add the following functions to the pytest namespace: - :func:`get_index_doctree` - :func:`assert_issue_xref` """ return dict((f.__name__, f) for f in (assert_issue_xref, assert_issue_pending_xref))
c3822858b329a36320dd21db0f106c6e9a6ae730
3,596,962
def qtrfit(numpoints, defcoords, refcoords, nrot): """Find the best-fit quaternion. Find the quaternion, q, [and left rotation matrix, u] that minimizes .. math:: | qTXq - Y | ^ 2 [|uX - Y| ^ 2] This is equivalent to maximizing .. math:: Re(q^T X^T q Y) The left rotation matri...
91285de8e293fa71b0c111effa21f9bfcc8d52ba
3,596,963
def serialize_messages(messages): """JRPC serialization Method that serializes an array of messages as read from the database through a query. :param messages: The message objects as read from the database :return: JSON serialiazible array """ serial_messages = [] for m in messages: ...
02f8574f6599d2f89095a81173d6daa9c983cc2d
3,596,964
def _get_normalized_data(case): """helper method for ``_get_fringe_data``""" #def _get_normalized_data(result_case): #(obj, (i, name)) = result_case #case = obj.get_result(i, name) if case is None: return None if len(case.shape) == 1: normi = case else: assert isinstance...
eaa0fa0df35970e2e11c643b2ec2f9e628d777f7
3,596,965
import torch def safe_cumprod(x, *args, **kwargs): """Computes cumprod of x in logspace using cumsum to avoid underflow. The cumprod function and its gradient can result in numerical instabilities when its argument has very small and/or zero values. As long as the argument is all positive, we can ins...
4cdaecee6c1cbbe8424893fc132a2b748a314a44
3,596,966
def trcnam(index): """trcnam(SpiceInt index)""" return _cspyce0.trcnam(index)
166b79d16ca04e0c23a27cc07fff1bb880ce206c
3,596,967
def predictability(S,N, inital_guess = 0.5): """Finds the value of the predictability for a process with an entropy rate S and a vocabulary size N.""" # explodes for small values of N or large values of S :( try: f = lambda Pi : S + Pi*np.log2(Pi) + (1 - Pi)*np.log2(1 - Pi) - (1 - Pi)*np.log2(N-1) ...
358f347587e8e6bf3f41243050de72015421a527
3,596,968
import scipy def get_signal(wavpath, emphasize=True, pre_emphasis=0.97): """ Gets signal and sample rate from wav file. If emphasize is True https://www.quora.com/Why-is-pre-emphasis-i-e-passing-the-speech-signal-through-a-first-order-high-pass-filter-required-in-speech-processing-and-how-does-it-work/ans...
d9dbfb678a41fdf4bf8db274ee849c27a3bf51cc
3,596,969
def auto_flushing_queued_client(request, blank_transport): """A Riemann client using the StringIO transport and AutoFlushingQueuedClient with max_delay=300 and max_batch_size=5000""" client = riemann_client.client.AutoFlushingQueuedClient( transport=blank_transport, max_delay=300, ...
21b601dcfceff9a2381a1b5d27abfffed43ae3a0
3,596,970
import optparse def comma_separated_callback(*, is_valid_func=lambda v: True, error_msg="{invalid} is not an allowed value"): """ Return an optparse callback for comma-separated args. Default value is not processed. Usage:: my_callback = comma_separated_callback( ...
3b7c1de63a7a29f0fc2f4a6ae7445d6e05075d32
3,596,972
import tqdm from datetime import datetime def k_symmetric(Nbin): """A function that calculates the symmetric part of the diffusivity tensor for every time gap up to 60 days""" pi=np.pi #Data paths: Path_data = '/Users/tychobovenschen/Documents/MasterJaar2/Thesis/data/' File_data = 'interpolated_gl...
370c00289d495cfbf5ee333623d1ed2662827b1e
3,596,973
def max_pool(x, kernel_size, stride, padding, name): """ :param x: :param kernel_size: :param stride: :param padding: :param name: :return: """ return tf.nn.max_pool(x, ksize=[1, kernel_size, kernel_size, 1], strides=[1, stride, stride, 1], padding=padding, ...
7c60a1167287d3daf398c208bc4bc8e1425a2980
3,596,974
def get_huc12_results(id, analysis_acres, total_acres): """Get results for NatureScape dataset for a given HUC12. Parameters ---------- id : str HUC12 ID analysis_acres : float area of HUC12 summary unit less any area outside SE Blueprint total_acres : float area of HUC1...
75bb025af9387b66e6bfdb739100dbdbfc51653f
3,596,975
def vector_rejection(a, b): """ Return the vector rejection from vector a onto vector b See: * https://en.wikipedia.org/wiki/Vector_projection Args: :a: vector to be projected :b: vector onto which a is projected Returns: :a2: vector rejection """ a1 = vec...
558ac1ef3ba0f8d95096f3aae87f77cc8a0c1d89
3,596,976