content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_world_trans(m_obj): """ Extracts the translation from the worldMatrix of the MObject. Args: m_obj Return: trans """ plug = get_world_matrix_plug(m_obj, 0) matrix_obj = plug.asMObject() matrix_data = oMa.MFnMatrixData(matrix_obj) matrix = matrix_data.matrix() ...
72d1459b32ba2d27f60e9445fa9513ab6cfbf3e4
3,628,261
def isip46(value): """Assert value is a valid IPv4 or IPv6 address. On Python < 3.3 requires ipaddress module to be installed. """ import ipaddress # requires "pip install ipaddress" on python < 3.3 if not isinstance(value, basestring): raise ValidationError("expected a string, got %r" % va...
a511048469ec231667735e7c3028807c0faf90a9
3,628,263
def wrap_with_arctan_tan(angle): """ Normalize angle to be in the range of [-np.pi, np.pi[. Beware! Every possible method treats the corner case -pi differently. >>> wrap_with_arctan_tan(-np.pi) -3.141592653589793 >>> wrap_with_arctan_tan(np.pi) 3.141592653589793 :param angle: Angle as nu...
351e230eac5b5650ddefb22075709f0b4c185761
3,628,264
import re def get_params(proto): """ get the list of parameters from a function prototype example: proto = "int main (int argc, char ** argv)" returns: ['int argc', 'char ** argv'] """ paramregex = re.compile('.*\((.*)\);') a = paramregex.findall(proto)[0].split(', ') #a = [i.replace('cons...
37841b2503f53353fcbb881993e8b486c199ea58
3,628,265
def _preprocess(state, mode='min-max-1'): """ Implements preprocessing of `state`. Parameters ---------- state : np.array 2D array of features. rows are variables and columns are features. Return ------ (np.array) : same shape as state but with transformed variables """ ...
90d6f0efd4c9de6b6b8639680d8a1809d6ef7962
3,628,266
def _parse_basic_txt_scorefile(file, epoch_len=pysleep_defaults.epoch_len): """ Parse the super basic sleep files from Dinklmann No starttime is available. :param file: :return: """ dict_obj = {"epochstages": [], "epochoffset": 0} for line in file: temp = line.split(' ') ...
6ad11f2258fac4951d81152788318e33f1b204e9
3,628,267
import math def DominantModeStructured(amps, dt, N = 250): """ Compute the period and amplitude of the dominant mode in an even data series. """ def Omegas(ts): return [2.0 * math.pi / t for t in ts] nScans = len(amps) times = [i * dt for i in range(nScans)] tMin = 2.0 * dt tMax = nScan...
9df963b51117a579df63dcdf76120c58b5bc5cdc
3,628,268
def decode_record(record, name_to_features=name_to_features): """Decodes a record to a TensorFlow example.""" example = tf.io.parse_single_example(record, name_to_features) # tf.Example only supports tf.int64, but the TPU only supports tf.int32. # So cast all int64 to int32. for name in list(example.keys()):...
559950a440d2f86e3ae3a4def5c431912b9b37a3
3,628,269
def have_color(parent, is_levels=False): """Checks that the color directories have images. Args: parent: class instance is_levels (bool, optional): Whether or not to use full-size (False) or level_0 images (True). Returns: dict[str, bool]: Map of color directories and w...
cb8d1ad7a8d9927fa48bfecc37e21015910415d2
3,628,271
from typing import Match import re def _IsType(clean_lines, nesting_state, expr): """Check if expression looks like a type name, returns true if so. Args: clean_lines: A CleansedLines instance containing the file. nesting_state: A NestingState instance which maintains information about ...
eb7be397e2d4e583ac3a63293c467a78cb8dbba7
3,628,272
import requests def return_figures(countries=country_default, start_year=1990, end_year=2014): """Creates four plotly visualizations using the World Bank API # Example of the World Bank API endpoint: # arable land for the United States and Brazil from 1990 to 2015 # http://api.worldbank.org/v2/countries/usa;...
a739a5ed2a5bd2033fc0f5b6e818773a9ac972c2
3,628,273
def generate_info(kd: KnossosDataset) -> dict: """Generate Neuroglancer precomputed volume info for a Knossos dataset Args: kd (KnossosDataset): Returns: dict: volume info """ info = {} info["@type"] = "neuroglancer_multiscale_volume" info["type"] = None info["...
a0f6c23cb99f77eff7fff61dfc67a56dbd6fb8a5
3,628,274
from typing import Callable from typing import Concatenate from typing import Awaitable from typing import Coroutine from typing import Any def plugwise_command( func: Callable[Concatenate[_T, _P], Awaitable[_R]] # type: ignore[misc] ) -> Callable[Concatenate[_T, _P], Coroutine[Any, Any, _R]]: # type: ignore[mi...
564dfeff805ecc89a8e69b5c5c605f5a0e3c790e
3,628,275
def order_parsed_fields(parsed, types, names=None): """Order parsed fields using a template file.""" columns = {} fields = {} ctr = 0 types = add_names_to_types(names, types) for group, entries in types.items(): for field, attrs in entries.items(): header = False ...
3752f8cbd13e410f3c548243df31149c9a0c3e86
3,628,276
def cvSeqSort(*args): """cvSeqSort(CvSeq seq, CvCmpFunc func, void userdata=None)""" return _cv.cvSeqSort(*args)
d3c6d6b4f0840a02614396e3b0fff43694a2ffd1
3,628,277
def dice_coef_fn(y_true, y_pred, axis=1, eps=1e-6): """Calculate the Dice score.""" intersection = tf.reduce_sum(input_tensor=y_pred * y_true, axis=axis) union = tf.reduce_sum(input_tensor=y_pred * y_pred + y_true * y_true, axis=axis) dice = (2. * intersection + eps) / (union +...
ece185fd9464172db51c9fcd2ea434593a9576e9
3,628,278
import collections def gram_counter(value: str, gram_size: int = 2) -> dict: """Counts the ngrams and their frequency from the given value Parameters ---------- value: str The string to compute the n-grams from gram_size: int, default= 2 The n in the n-gram Returns ------...
21a55bf89ddad13f40af9f25ac5aeb759089dc82
3,628,280
import json def check(request): """SQL检测按钮, 此处没有产生工单""" sql_content = request.POST.get('sql_content') instance_name = request.POST.get('instance_name') instance = Instance.objects.get(instance_name=instance_name) db_name = request.POST.get('db_name') result = {'status': 0, 'msg': 'ok', 'data'...
28181f1d22c905beb292d37029c21f05a2ae5c14
3,628,282
def div_ext( ticker: str, viewer: viewers.Viewer = bootstrap.VIEWER, ) -> pd.DataFrame: """Сводная информация из внешних источников по дивидендам.""" df = viewer.get_df(ports.DIV_EXT, ticker) return df.loc[bootstrap.START_DATE :]
53b8931cd6e2a11022c56fe8e6649042dcd17cf9
3,628,283
def is_pyside(): """ Returns True if the current Qt binding is PySide :return: bool """ return __binding__ == 'PySide'
9d69660ac223f124e49e86b19c44b4bc52fa2964
3,628,284
from pm4py.algo.filtering.ocel import activity_type_matching from typing import Dict from typing import Collection def filter_ocel_object_types_allowed_activities(ocel: OCEL, correspondence_dict: Dict[str, Collection[str]]) -> OCEL: """ Filters an object-centric event log keeping only the specified object typ...
9c25a9262827885547c8096de0ca511f1ca6cfa5
3,628,285
def parse_sources_data(data, origin='<string>', model=None): """ Parse sources file format (tags optional):: # comments and empty lines allowed <type> <uri> [tags] e.g.:: yaml http://foo/rosdep.yaml fuerte lucid ubuntu If tags are specified, *all* tags must match the current co...
c278d19fc96d847ef5d8e17dfd6b5dc98633613a
3,628,287
import inspect def list_module_public_functions(mod, excepted=()): """ Build the list of all public functions of a module. Args: mod: Module to parse excepted: List of function names to not include. Default is none. Returns: List of public functions declared in this module "...
d27dc869cf12701bcb7d2406d60a51a8539a9e1b
3,628,288
from typing import Iterable import ctypes def twovec( axdef: Iterable[float], indexa: int, plndef: Iterable[float], indexp: int ) -> ndarray: """ Find the transformation to the right-handed frame having a given vector as a specified axis and having a second given vector lying in a specified coordi...
cdb18fc69bd29eb64191adbd1dd01c8201e4c0eb
3,628,289
def translate_marker_and_linestyle_to_Plotly_mode(marker, linestyle): """<marker> and <linestyle> are each one and only one of the valid options for each object.""" if marker is None and linestyle != 'none': mode = 'lines' elif marker is not None and linestyle != 'none': mode = 'lines+markers' elif marker is n...
53de94176afe47f5a9b69e7ad676853b4b19a8db
3,628,290
import json def handle_exception(err): """for better error handling""" # start with the correct headers and status code from the error response = err.get_response() # replace the body with JSON response.data = json.dumps({ "code": err.code, "name": err.name, "description":...
d6990ef6295206618d50faaaa2c8aea9cdb076e9
3,628,291
def strRT(R, T): """Returns a string for a rotation/translation pair in a readable form. """ x = "[%6.3f %6.3f %6.3f %6.3f]\n" % ( R[0,0], R[0,1], R[0,2], T[0]) x += "[%6.3f %6.3f %6.3f %6.3f]\n" % ( R[1,0], R[1,1], R[1,2], T[1]) x += "[%6.3f %6.3f %6.3f %6.3f]\n" % ( R[2,0]...
2d7ec1bf2ebd5a03472b7b6155ed43fdcc71f76a
3,628,292
def _scale_log_and_divide(train, val, scaler="log_and_divide_20"): """First apply a log transform, then divide by the value specified in scaler to sequences train and val. Parameters ---------- train : np.ndarray Training dataset val : np.ndarray Validation dataset scaler: s...
ba3ccdae25e50cf6855f56fe56f366daf4b37212
3,628,293
def extract_classes(document): """ document = "545,32 8:1 18:2" extract_classes(document) => returns "545,32" """ return document.split()[0]
b7e8fed3a60e3e1d51a067bef91367f960e34e6b
3,628,294
def general_value(value): """Checks if value is generally valid Returns: 200 if ok, 700 if ',' in value, 701 if '\n' in value""" if ',' in value: return 700 elif '\n' in value: return 701 else: return 200
5cf8388294cae31ca70ce528b38ca78cdfd85c2c
3,628,295
def _cast_to(matrix, dtype): """ Make a copy of the array as double precision floats or return the reference if it already is""" return matrix.astype(dtype) if matrix.dtype != dtype else matrix
9625311c0918ca71c679b1ac43abe67f2a4b0f2d
3,628,296
def wire_mask(arr: np.ndarray, invert: bool = False) -> np.ndarray: """ Function ---------- Given an 2D boolean array, returns those pixels on the surface Parameters ---------- arr : numpy.ndarray A 2D array corresponding to the segmentation mask invert : boolean (Default = Fals...
f3a49ad458c17f021c8bcb30c78464fccbde8b71
3,628,297
def reverse_str(string): """ Base case: length of string Modification: str slice """ if len(string) == 1: return string return reverse_str(string[1:]) + string[0]
eb0d27816e8fe54f1136f4a507478f40a3354d72
3,628,298
def check_drf_token(request, format=None): """ Return `{"status": true}` if the Django Rest Framework API Token is valid. <!-- :param request: :type request: :param format: :type format: :return: :rtype: --> """ token_exists = Token.objects.filter(key=request.data["token...
38e62e8d3ac11bfba5fffb73bf727164ed63133d
3,628,299
from typing import Type from re import T def load_instance(alfacase_content: DescriptionDocument, class_: Type[T]) -> T: """ Create an instance of class_ with the attributes found in alfacase_content. """ alfacase_to_case_description = get_case_description_attribute_loader_dict(class_) case_values...
5436c17f856461eac54b71018596c86e735c6ab5
3,628,300
def number_scenarios(scenes): """ Add a 'scenario_number' and 'scenario_name' variable to each scenario. The hash table for each scenario is altered! """ count = 0 for scene in scenes: scene[1]['scenario_name'] = scene[0] scene[1]['scenario_number'] = count count += 1 ...
5b3391e2113142bed49d8bcdb7c6fe4b1e0ab8cc
3,628,302
def trimscan_corner_plot(det, element, ranges, chips=range(16)): """ """ pixels = det.get_pixels() labels = [r'$a_0$', r'$a_1$', r'$a_2$', r'$a_3$', r'$a_4$', r'$a_5$'] data = [] # Loop over pixels and do the analysis for index in range(len(labels)): fit_data = [] ...
0e14c703d3d2d7a8160a51845f25db70a14d3f91
3,628,303
def find_key_value_in_list(listing, key, value): """ look for key with value in list and return dict :param listing: :param key: :param value: :return: dict_found """ # for l in listing: # if key in l.keys(): # if l[key] == value: # print("l[key = ", v...
642d8e43cbfbeef9bc014c85085c7027380156e2
3,628,304
def request_test_suite_started(etos, activity_id): """Request test suite started from graphql. :param etos: Etos Library instance for communicating with ETOS. :type etos: :obj:`etos_lib.etos.ETOS` :param activity_id: ID of activity in which the test suites started :type activity_id: str :return...
9bd0f8ba7a0846be440ece1d1d7e4c7335c05dcc
3,628,305
import six def cast_env(env): """Encode all the environment values as the appropriate type. This assumes that all the data is or can be represented as UTF8""" return {six.ensure_str(key): six.ensure_str(value) for key, value in env.items()}
b7adfbd20a95f3b2ff24f36f578a869317165c49
3,628,306
def contingency_table(seg, gt, ignore_seg=[0], ignore_gt=[0], norm=True): """Return the contingency table for all regions in matched segmentations. Parameters ---------- seg : np.ndarray, int type, arbitrary shape A candidate segmentation. gt : np.ndarray, int type, same shape as `seg` ...
6eb0835b92e9552d3686271dc00bd136fd873779
3,628,307
import logging def create_object_detection_training( train_object_detection_model_request: TrainImageModel, ): """[Train a Object Detection Model in AutoML GCP] Args: train_object_detection_model_request (TrainImageModel): [Based on Input Schema] Raises: error: [Error] Returns: ...
0944b898b9fdf8395ddd17f8f2e9d0c36a559c94
3,628,308
def jwt_authentication(secret, exc=exceptions.PermissionDenied()): """ Provide authentication for a view that must have a valid JWT token for the provided secret key :param secret: The secret key that validates the jwt token provided in the request headers :param exc: The exception to throw if the token...
4e82b8eb4288092f769797571851555e6fcdef77
3,628,309
def strategy_regret(meta_games, subgame_index, ne=None, subgame_ne=None): """ Calculate the strategy regret based on a complete payoff matrix for PSRO. strategy_regret of player equals to nash_payoff in meta_game - fix opponent nash strategy, player deviates to subgame_nash Assume all player...
c4514746d523084e8978861af2a5369d9fe2a1e8
3,628,310
def convert_int_to_form(num: int, form_num: int) -> int: """Converts decimal integer to specified form number. Supports conversion to octal and binary forms. """ output = 0 bin_digits = [] while num > 0: num, r = divmod(num , form_num) bin_digits.insert(0, r) num_digits =...
28a81a277baaefbb8ed27970bee1afb13d3cdde1
3,628,311
def less_equal(x, y, cond=None): """ This OP returns the truth value of :math:`x <= y` elementwise, which is equivalent function to the overloaded operator `<=`. """ helper = MpcLayerHelper("less_equal", **locals()) if cond is None: cond = helper.create_variable_for_type_inference(dtype...
37cefd3c85265d73635f1b2de1c8c778dc9ece08
3,628,312
def _expiration(timeout, time_format=None): """ Return an expiration time :param timeout: When :param time_format: The format of the returned value :return: A timeout date """ if timeout == "now": return time_util.instant(time_format) else: # validity time should match l...
174f0395d9a748dd6bc47c4aa836cd4aa402c39e
3,628,313
def get_vgg_model(image_size, num_classes): """Get VGG16 model""" inputs = Input(shape=[*image_size, 3]) model = VGG16( include_top=False, weights="imagenet", classes=num_classes, input_tensor=inputs, classifier_activation=None, ) model.trainable = False ...
17a6198a2d2186771ba1ee7c8442acc6c552d021
3,628,315
def random_weights(n_i: int, n_j: int, axis: int = 0, seed: int | None = None) -> ndarray: """Generate random weights for producer-injector gains. Args ---- n_i : int n_j : int axis : int, default is 0 seed : int, default is None Returns ------- gains_guess: ndarray """ ...
67d420db30a703d33174af9238d71fc8f68fd61f
3,628,316
def ensure_session(session=None): """If session is None, create a default session and return it. Otherwise return the session passed in""" if session is None: session = boto3.session.Session() return session
5d53bd3bd6a6d61f75cc3680d0618889fb14394f
3,628,317
def reset(label): """ @api {delete} /:label Reset counter @apiName ResetCounter @apiGroup Counter @apiParam {String} label Counter label. @apiSuccess {Number} counter Zero value. """ store.delete(label) return jsonify(counter=0)
6834b33246ff8994525cd3781e72602497d1d381
3,628,318
def remove_duplicates(df, by=["full_text"]): """ Remove duplicates from raw data file by specific columns and save results in file with name given. """ boolean_mask = df.duplicated(subset=by, keep="first") df = df[~boolean_mask] return df
dfe99259a90280b346290dd2c880ab51e443e036
3,628,319
def tex_parenthesis(obj): """Return obj with parenthesis if there is a plus or minus sign.""" result = str(obj) return f"({result})" if "+" in result or "-" in result else result
356a3886d27d431e90de2a76e6590481ad85f05e
3,628,321
def swap_target_nonterminals(target): """ Swap non-terminal tokens. :param target: List of target tokens :return: List of target tokens """ return ['X_1' if token == 'X_0' else 'X_0' if token == 'X_1' else token for token in target]
56e91df1a513ee5dad1071337463e039ded57a86
3,628,322
def validate_nd_array(x): """Casts x as a numpy array of the original input shape.""" # Get shape and cast as 1d x, shape = _get_shape_and_return_1d_array(x) # Return to original shape x = x.reshape(shape) return x
007ad923f9e1e712a6bdcbd659a8d257a6383cb8
3,628,323
def _expandaliases(aliases, tree, expanding, cache): """Expand aliases in tree, recursively. 'aliases' is a dictionary mapping user defined aliases to revsetalias objects. """ if not isinstance(tree, tuple): # Do not expand raw strings return tree alias = _getalias(aliases, tree...
4c104aab5c20510f5a87a719139c33db7c23d657
3,628,324
def to_svd_numpy(numpy_array, compress_rate): """ We transform an image to its SVD representation: U x D x V^T. We return as output for each channel X, 2 channels with values: U x D, and V^T. The initial size is n^2, the final size is: 2np :param numpy_array: the input image :param compress_rat...
e407ffdb2049c248b2ea51b5ecb240628d94f508
3,628,326
def _get_login_player_name(html): """ 指定されたHTMLからログインユーザー名を抽出する。 :param html: 投票ページのHTML :type html: str :return: ログインユーザー名 :rtype: str """ # ログインユーザー名を返却する soup = bs4.BeautifulSoup(html, 'html.parser') player_name_box = soup.find('div', {'class': 'player_name_box'}) if play...
a6aaa72a92ae8dcefacfe4db042148aa69f24443
3,628,327
from datetime import datetime def get_max_streak(submissions): """ Get the maximum of all streaks @param submissions (List of tuples): [(DateTime object, count)...] @return (Tuple): Returns streaks of the user """ streak = 0 max_streak = 0 prev = curr = None total_sub...
f021647e028475e66c548773fc9d1571e6f3b251
3,628,328
import requests def check_node_reachable(context): """ Returns whether the specified node IP is reachable and informs user """ chat_id = context.job.context['chat_id'] user_data = context.job.context['user_data'] if 'is_node_reachable' not in user_data: user_data['is_node_reachable']...
f8ab268d38cbd98cb8de017bd944d26f5ba746be
3,628,329
def padZeros(numberString, numZeros, insertSide): """Return a string padded with zeros on the left or right side.""" if insertSide == 'left': return '0' * numZeros + numberString elif insertSide == 'right': return numberString + '0' * numZeros
d0c2d08a392e4792b13a64d076c8fb6aff1572cb
3,628,330
def stations(): """ Return a JSON list of stations from the dataset.""" # Create our session (link) from Python to the DB session = Session(engine) station_list = session.query(Measurement.station, Station.name, func.count(Measurement.station)).\ filter(Measurement.station == St...
adda327b3fba5dacfedde07fd14f1fca1955f945
3,628,331
def eval_sot_accuracy_robustness(results, annotations, burnin=10, ignore_unknown=True, videos_wh=None): """Calculate accuracy and robustness over all tracking sequences. Args: ...
e5aeb63919ecab3d82c60688066b434a65b7442c
3,628,332
def spares_kdt_compute_mean_std_v2(res_dicts, spaces, arch_key='eval_arch', perf_key='eval_perf', use_hash=False, sort_best_model_fn=None): """ Just compute the average sKdT Parameters ---------- res_dicts : list dict of running, multiple seed run contains inside arch_key : str, optional ...
bacb3b8283ed9a54268d9d5b0fea78b410bd90e6
3,628,333
def roi_proposal(rpn_cls_prob_reshape, rpn_bbox_pred, H, W, ANCHOR_PER_GRID, ANCHOR_BOX, TOP_N_DETECTION, NMS_THRESH, IM_H, IM_W): """ clip the predict results fron rpn output appply nms proposal topN results as final layer output, no backward operation need here """ box_probs = np.reshape(rpn_c...
871c5d81f047ecaa8fd5d08ec3bbd22f83059062
3,628,334
def mi_gg(x, y, biascorrect=True, demeaned=False): """Mutual information (MI) between two Gaussian variables in bits I = mi_gg(x,y) returns the MI between two (possibly multidimensional) Gassian variables, x and y, with bias correction. If x and/or y are multivariate columns must correspond to sampl...
2e2614f233c42e27d2b53d6761c1069d04c66f39
3,628,335
import math def build_lifegame_model(n, **kwargs): """ build a MIP model for a stable game of life configuration chessboard is (n+1) x (n+1) :param n: :return: """ assert n >= 2 assert Model.supports_logical_constraints(), "This model requires logical constraints cplex.version must be 1...
74c615639d8a45bf6ff6ab055f0e7189ace1be07
3,628,337
def get_wofs_values(landsat_dataset): """classifies a landsat scene using the wofs algorithm :param landsat_dataset: xarray with dims 'latitude','longitude' containing data from a landsat scene :return: xarray dataset containing wofs classification values """ # landsat dataset needs dim 'time' for w...
e069da04de9800fe61f3416f981ec386cb8e1f2a
3,628,338
def readdirs(DIR): """Implementation of perl readdir in list context""" result = (DIR[0])[DIR[1]:] DIR[1] = len(DIR[0]) return result
98d9b588704ea2820b14ba2c5542ea0a619a02ce
3,628,339
def expandChunk(layout, typesize, shape_json, chunk_min=CHUNK_MIN, layout_class='H5D_CHUNKED'): """ Extend the chunk shape until it is above the MIN target. """ if shape_json is None or shape_json["class"] == 'H5S_NULL': return None if shape_json["class"] == 'H5S_SCALAR': ...
1d43c21629b77b5cdc0ab6ac35397729f8f96d89
3,628,340
def remove_domestic(images: pd.DataFrame, reset_index: bool = True) -> pd.DataFrame: """ Removes images where the identification corresponds to a domestic species. See wiutils/_domestic for a list of the genera considered as domestic. Parameters ---------- images : DataFrame DataFra...
a2038a36c6fbd6f0492c1abb8afc34919b6ecc4c
3,628,341
def compute_cyclepoints(sig, fs, f_range, **find_extrema_kwargs): """Compute sample indices of cyclepoints. Parameters ---------- sig : 1d array Time series. fs : float Sampling rate, in Hz. f_range : tuple of (float, float) Frequency range, in Hz, to narrowband filter t...
c748b4f52dac249cf1021a9902e533a3cf485c6f
3,628,342
def behav_data_inverted(df): """ Flips the dimensions that need inverting Faster than using is_inverted_dim """ # Apparently groupby with categorical dtype is broken # See https://github.com/pandas-dev/pandas/issues/22512#issuecomment-422422573 df["class_"] = df["class_"].astype(str) inv...
69ad0d4cea1a12b2dd8dc256c77b13f1002ae6b8
3,628,343
def _resample_event_obs(obs, fx, obs_data): """ Resample the event observation. Parameters ---------- obs : datamodel.Observation The Observation being resampled. fx : datamodel.EventForecast The corresponding Forecast. obs_data : pd.Series Timeseries data of the eve...
1c66ae124aaa2e732c7d0ec3e733ae2b5caaa6cb
3,628,344
def project_raw_gw( raw_waveforms, sample_params, waveform_generator, ifo, get_snr=False, noise_psd=None, ): """Project a raw gravitational wave onto an intterferometer Args: raw_waveforms: the plus and cross polarizations of a list of GWs sample_params: dictionary of GW...
d7f1d652baae37f402e0ea520600ffe7423fac75
3,628,345
def threshold(weights, delta_size): """ Sample for threshold minimizing pixel changes. """ return min((abs(added_pixel_count(weights,i) + delta_size), i) for i in np.linspace(10**-2,10**-7,40))[1]
01c00a55938df949c42299384b2574a07de8e3ff
3,628,346
def davenport_matrix(B = None, covariance_analysis = False, **attitude_profile_kwargs): """Compute the Davenport matrix for a given attitude profile. Accepts either an attitude profile matrix or the arguments for the attitude_profile_matrix() funct...
5cb1e7b2fe81c0a985f1189f4786fa7be42cf378
3,628,347
def _arg_raw(dvi, delta): """Return *delta* without reading anything more from the dvi file""" return delta
041cfaaf23c6e229b60d5278e8cf27352e078a65
3,628,348
from typing import Sequence import struct async def write_mapInfoReply(maps: Sequence[BeatmapInfo]) -> bytearray: """ Write `maps` into bytes (osu! map info). """ ret = bytearray(len(maps).to_bytes(4, 'little')) # Write files for m in maps: ret.extend(struct.pack('<hiiiBbbbb', m.i...
f601c7898acd7c94890fb26679d1814ecdd5cce2
3,628,349
def getPolarPoints2(x, y, center): """Convert list of cartesian points to polar points The returned points are not rounded to the nearest point. User must do that by hand if desired. Parameters ---------- x : (N,) :class:`numpy.ndarray` List of cartesian x points to convert to polar domain...
f6f3ebed82eac397c26f2c20ce23a4e8cf19e3b1
3,628,350
def to_bytes(binary_string: str) -> bytes: """Change a string, like "00000011" to a bytestring :param str binary_string: The string :returns: The bytestring :rtype: bytes """ if len(binary_string) % 8 != 0: binary_string += "0" * ( 8 - len(binary_string) % 8 ) # fill...
83dda243e27d7f7988d520c0455e43d1937d5447
3,628,351
def choose_best_assembly_name(assembly_names): """ Given a list of reference genome names returns the best according to the following criteria: 1) Prefer Ensembl reference names to UCSC 2) Prefer reference names with higher numbers in them. Parameters ---------- assembly_names :...
fc111677f5dfc0e3b10e14e74ac096fd0f22dbfb
3,628,352
def user_follow(request): """ This one is VERY similar to the <image_like> func in app-image/views. There are only two options after all (well, true for some cases) :D """ user_id = request.POST.get('id') action = request.POST.get('action') if user_id and action: ...
7b4956ec002aea512758ba34a260b24bfd5622d8
3,628,353
def module_patch_twin(connectionId, twin): # noqa: E501 """Updates the device twin # noqa: E501 :param connectionId: Id for the connection :type connectionId: str :param twin: :type twin: dict | bytes :rtype: None """ if connexion.request.is_json: twin = Twin.from_dict(...
1b712264c5723a44a2fa0328ac7621cf090585b7
3,628,354
def rgbToHsv(r, g, b): """ Converts an RGB color value to HSV. Conversion formula adapted from http://en.wikipedia.org/wiki/HSV_color_space. Args: r, g, b (int): red, green, and blue values between 0 and 255 inclusive Returns: Array [hue, saturation, value] hue between 0 and 36...
5d7e40dc8f5deba686bcca29da3b5ea2d7d9f37c
3,628,355
def assign_from_checkpoint(model_path, var_list): """Creates an operation to assign specific variables from a checkpoint. Args: model_path: The full path to the model checkpoint. To get latest checkpoint use `model_path = tf.train.latest_checkpoint(checkpoint_dir)` var_list: A list of (possibly par...
f318ee5cc923ef147e5c937b74d44c3af101a405
3,628,356
def _read_tmpfd(fil): """Read from a temporary file object Call this method only when nothing more will be written to the temporary file - i.e., all the writing has already been done. """ fil.seek(0) return fil.read()
08648325e7e0e9bcd543d3238cb4630ac284f6ed
3,628,357
def eigenvalues_and_eigenvectors(a: Matrix, epsilon=eps, max_iterations=1000) \ -> (TransposedVectorView, Matrix): """Eigenvalues|vectors with QR factorization""" assert is_symmetric(a) a_k = a.copy() v_k = Matrix.identity(a.size()[0]) for i in range(max_iterations): if almost_upper_...
987d65f65bc95dd6acad1dc86061e2b036437a4c
3,628,358
def evens(input): """ Returns a list with only the even elements of data Example: evens([0, 1, 2, 3, 4]) returns [0,2,4] Parameter input: The data to process Precondition: input an iterable, each element an int """ result = [] for x in input: if x % 2 == 0: result.a...
8a219f8815d95a18bea148eaae117f3356a77d4b
3,628,359
def _setup_output_skip_keys(args): """reduce tensors pulled from data files to save time/space """ if (args.subcommand_name == "dmim") or (args.subcommand_name == "synergy"): skip_keys = [] elif (args.subcommand_name == "mutatemotifs"): skip_keys = [ DataKeys.ORIG_SEQ_PWM_HIT...
20a5d95f8ee811aeba4dea47eb58339264241a5e
3,628,360
from typing import List def create_example(speakers: List[List[nparr]]) -> nparr: """ :param speakers: a list of speakers where each item is a list of microphones where each contains a sound file padded to a consistent length :return: matrix of size [features(freq),file_len(time),(mic_num-1)*2] which ...
21c81d8f0f60e24ace3eca4f3a205604da98b3df
3,628,361
def SaveNumSummary(doc:NexDoc, filename): """Saves the summary of numerical results to a text file with the specified name.""" return NexRun("SaveNumSummary", locals())
b51924a149d96043d4c8e9397063b8ff419db11f
3,628,363
def get_binary_balanced_purity_ranges(preds, class_labels, bin_size, total_class_counts): """ Get balanced purity for each class, for each range of probabilities, for binary classifier. Return dict. of class names to balanced purity at each prob threshold (10 thresholds) :param preds: List of Numpy row...
5389e44f3605ca344572483c6cbbc1f40a8b3ef7
3,628,364
def bond_symmetry_numbers(xgr, frm_bnd_key, brk_bnd_key): """ symmetry numbers, by bond the (approximate) symmetry number of the torsional potential for this bond, based on the hydrogen counts for each atom It is reduced to 1 if one of the H atoms in the torsional bond is a neighbor to the special ...
931a147e690ea5d2aa7564a353f9a18aa2be5a43
3,628,365
import html def make_header_layout(): """The html layout for the dashboard's header view.""" return html.Div( id="header", className="header", children=[ html.Div(id="title", className="header--project", children="rubicon-ml"), html.Div( id="lin...
3dfd4587242c305ebeb1239b976556952f6c5601
3,628,368
def quimbify(data, qtype=None, normalized=False, chopped=False, sparse=None, stype=None, dtype=complex): """Converts data to 'quantum' i.e. complex matrices, kets being columns. Parameters ---------- data : dense or sparse array_like Array describing vector or operator. qtype :...
7392d51f35b2728e3f475de2e4180b2c4fd586b1
3,628,369
def _check_insert_data(obj, datatype, name): """ Checks validity of an object """ if obj is None: return False if not isinstance(obj, datatype): raise TypeError("{} must be {}; got {}".format( name, datatype.__name__, type(obj).__name__)) return True
057d0124db3f304e7efd4093510c663f5383af63
3,628,370
def create_importance_sampling( baddr: GBAPOMDPThroughAugmentedState, num_samples: int, minimal_sample_size: float ) -> belief_types.BeliefUpdate: """Creates importance sampling Returns a rejection sampling belief update that tracks ``num_samples`` particles in the ``baddr``. Basically glue between ...
c13e4f921e9d0ac32561b43d2a4b445e7633b2e9
3,628,371
import csv def maps(): """ VALUES TO EDIT: """ name_to_open_file = "act_comercial.csv" """ END OF VALUES TO EDIT """ full_path_to_open_file = "static/databases/" + name_to_open_file with open(full_path_to_open_file) as csv_file: reader = csv.DictReader(csv_file) all_commercial_...
1c01b46f72ff32a8fb083b6973464388e1b270c7
3,628,372
from typing import Optional def improved_land_choice(context: Context) -> Optional[int]: """ Play untapped land if needed, then ramp, then draw, then randomly choose a playable card """ hand = context.zones["hand"] mana = context.mana gold = context.gold playable_cards = context.playable_c...
343b283d8c6938f00ce36a1077c244734016ef8d
3,628,373