content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def numpy_bbox_to_image(image, bbox_list, labels=None, scores=None, class_name=[], config=None): """ Numpy function used to display the bbox (target or prediction) """ assert(image.dtype == np.float32 and image.dtype == np.float32 and len(image.shape) == 3) if config is not None and config.normalized_m...
c9070cb917e376357363f99e9d951d84e3274684
3,641,000
import json def loads(text, template=None, colored=None, comments=None, **kwargs): """ Deserialize `text` (a `str` or `unicode` instance containing a JSON document supporting template references `{$.key}`) to a Python object. :param text: serialized JSON string :type text: str :param template...
fb128bc0c5cea6074d1ae43634d06853f05010e1
3,641,001
def AsyncSleep(delay, name=None): """Pause for `delay` seconds (which need not be an integer). This is an asynchronous (non-blocking) version of a sleep op. It includes any time spent being blocked by another thread in `delay`. If it is blocked for a fraction of the time specified by `delay`, it only calls `sl...
c6ccb12aa7e27a28591ac5282b0e78baa68df9df
3,641,002
def palide(string, length, ellipsis="...", pad=" ", position=1.0, left=False): """ A combination of `elide` and `pad`. """ return globals()["pad"]( elide(string, length, ellipsis=ellipsis, position=position), length, pad=pad, left=left)
be14ecb386ef7d49a6c85514bb5bee93d482be3d
3,641,003
def get_email_adderess(email_addr): """ Return dict from opalstack for given email address, or None """ mails = get_request("mail/list/") for record in mails['mails']: if record['address'] == email_addr: return get_request("mail/read/{}".format(record['id'])) return None
f31ae883b40da8b9ddf743744a3611dd0968e787
3,641,004
def GK3toUTM(ea, no=None, zone=32): """Transform Gauss-Krueger zone 3 into UTM (for backward compatibility).""" return GKtoUTM(ea, no, zone, gkzone=3)
aeab5433c8a676f862c9271f62a574bff2f74444
3,641,005
from typing import Optional def get_all_predictions( model: nn.Module, dataloader: DataLoader, device: _Device, threshold_prob: Optional[float] = None, decouple_fn: Optional[_DecoupleFnTest] = None, ) -> _TestResult: """ Make predictions on entire dataset and return raw outputs and opt...
e2d04376a935a1acd1d2e0645209cb865997669e
3,641,006
def plot_perf_stats(returns, factor_returns): """ Create box plot of some performance metrics of the strategy. The width of the box whiskers is determined by a bootstrap. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanat...
f948c29df18bc93d08fd6ad1b366db310b4bf8c2
3,641,007
def create(user): """ This function creates a new user in the database based on the passed-in user data. :param user: User to create in database :return: 201 on success, 400 on bad postal code, 406 on user exists """ username = user.get("username", None) postalcode = user.get("post...
2b3a64211fd66c7fbe93f51aecbceab6675f5b99
3,641,008
def show_profile(uid): """ Return serializable users data :param uid: :return String: (JSON) """ user = get_user_by_id(uid) return jsonify(user.serialize)
cb8bc7934575b99b6098a911c4dc7ad9fb1b7a48
3,641,009
def degree_correlation(coeffs_1, coeffs_2): """ Correlation per spherical harmonic degree between two models 1 and 2. Parameters ---------- coeffs_1, coeffs_2 : ndarray, shape (N,) Two sets of coefficients of equal length `N`. Returns ------- C_n : ndarray, shape (nmax,) ...
10dea06b6e1f9a1c4202f3478523fe7bdcc8ab6e
3,641,010
import cdr_cleaner.args_parser as parser def parse_args(): """ Add file_path to the default cdr_cleaner.args_parser argument list :return: an expanded argument list object """ help_text = 'path to csv file (with header row) containing pids whose observation records are to be removed' addition...
f5f89a55799ceee801b06a51e902cdd252068e50
3,641,011
def name(model): """A repeatable way to get the formatted model name.""" return model.__name__.replace('_', '').lower()
3d9ca275bfbfff6d734f49a47459761c559d906e
3,641,012
from typing import List from typing import Optional def render_fields( fields: List[Field], instance_name: Optional[str] = None ) -> List[str]: """Renders fields to string. Arguments: fields: The fields to render. instance_name: The name of model instance for which...
ba75827eac0ccea3e68259e27274feea17121cb2
3,641,013
def get_primary_tasks_for_service(service_arn): """Get the task ARN of the primary service""" response = ecs.describe_services(cluster=cluster, services=[service_arn]) for deployment in response['services'][0]['deployments']: if deployment['status'] == 'PRIMARY': return get_tasks_for_tas...
113e3ab3a20646d20caf08a6e1dfc4d546d2d950
3,641,014
import os import requests def post_to_slack(alarm_name, reason, config): """ Send message text to slack channel INPUTS: * alarm_name - subject of the message * reason - message text """ # get params from config file proxy_server = config['proxy_server'] if proxy_server !=''...
d8561a764c9e125e8d918c86fbc96413529933fc
3,641,015
def load_data(csv_file): """ @type csv_file: string @param csv_file: path to csv file Loads data from specified csv file @rtype: pandas.DataFrame @return: DataFrame from csv file without Month column """ return pd.read_csv(csv_file).drop('Month', 1)
5a458c104d763e431f0faf63a98bf4a59fd7902c
3,641,016
def nearest(array,value): """ Find the index of the array that is close to value Args: array (array): array to be tested value (float): value to be tested Returns: int: index """ return (np.abs(array-value)).argmin()
5197d0cae968557b519d1fa4025d2b834d7065c5
3,641,017
def fine_tune_model(trainX: np.ndarray, trainy: np.ndarray, cv: int = 5) -> SVC: """Receives training set and run a grid search to find the best hyperparameters. It returns the best model, already trained. Args: trainX (np.ndarray): train array containg embedding images. trainy (np.ndarray...
d493a0b0023f57116858878163b81463c1a7166e
3,641,018
from datetime import datetime import numpy def get_empty_array_year(year=datetime.now().year, start_end=True, variable_list=['TEST', ], variable_list_dtype=None, record_interval='HH'): """ Allocates and returns new empty record array for given year using list of dtypes (or variable labels as 8byte floats ...
d703ddc41233125b2b426c0423b0a3dcb85f73a0
3,641,019
def validate_geojson(data): """ Validate geojson """ if not (isinstance(data, dict)): return False if not isinstance(data.get('features'), list): return False gj = geojson.FeatureCollection([geojson.Feature(f) for f in data['features']]) return gj.is_valid
c48dfb76ff6d0255299f3913a644edff679b1a1a
3,641,020
from pathlib import Path import time def run_wps(conn, config_wpsprocess, **kwargs): """ primary function to orchestrate running the wps job from submission to download (if required) Parameters: ----------- conn: dict, Connection parameters Example: conn = {'domain': '...
d629939aaa32399a52a2f8ed1b0c8b5e94206f29
3,641,021
from chat.models import Chat from ct.models import Role def get_redirect_url(user): """ Analyse user and redirect: Instructor: onboarding is disabled - to /ctms/ onboarding is enabled and not achieved needed percent - to /ctms/onboarding/ onboarding is enabled and...
28faf82e8b22eb3602ba70e00a97a97ae50d93a1
3,641,022
def _ds_to_arrraylist( ds, bands, time_dim, x_dim, y_dim, percentile_stretch, image_proc_func=None ): """ Converts an xarray dataset to a list of numpy arrays for plt.imshow plotting """ # Compute percents p_low, p_high = ds[bands].to_array().quantile(percentile_stretch).values array_list ...
85b05277cf874a32eb006045437eee8ae02ce0ef
3,641,023
import six import binascii def derive_key(secret, salt, iterations=1000, keylen=32): """ Computes a derived cryptographic key from a password according to PBKDF2. .. seealso:: http://en.wikipedia.org/wiki/PBKDF2 :param secret: The secret. :type secret: bytes or unicode :param salt: The salt ...
04adaf71f3f9cf94e602029a242fedd037a40187
3,641,024
import imp import os def pseudo_import( pkg_name ): """ return a new module that contains the variables of pkg_name.__init__ """ init = os.path.join( pkg_name, '__init__.py' ) # remove imports and 'from foo import' lines = open(init, 'r').readlines() lines = filter( lambda l: l.startswith...
5982282d545c361d5198459073498ce5cba740a8
3,641,025
import torch def calc_params_l2_norm(model: torch.nn.Module, bf16: bool): """Calculate l2 norm of parameters """ # args = get_args() if not isinstance(model, list): model = [model] # Remove duplicate params. params_data = [] for model_ in model: for param in model_.parameters()...
399fc47296ac1ba3398dd5be834358f5ef50c9a4
3,641,026
def gradient_descent(f,init_val_dict, learning_rate=0.001, max_iter=1000, stop_stepsize=1e-6,return_history=False): """ Gradient Descent finding minimum for a single expression INPUTS ======= f: expression init_val_dict:dictionary containing initial value of variables learning_rat...
ba9edd1b41b7ac8e2e1d14b0a2958b7fe07bcf2a
3,641,027
from typing import Dict from typing import Any def gcp_iam_organization_role_permission_remove_command(client: Client, args: Dict[str, Any]) -> CommandResults: """ Remove permissions from custom organization role. Args: client (Client): GCP API client. args (dict): Command arguments from X...
42f56361d36b4fa0fbdea09031923235a0a3eb47
3,641,028
import socket def get_hostname(ipv) -> str: """ Get hostname from IPv4 and IPv6. :param ipv: ip address :return: hostname """ return socket.gethostbyaddr(ipv)[0]
e7d660dc3c5e30def646e56fa628099e997145be
3,641,029
import torch def load_model(): """ Load CLIP model into memory. Will download the model from the internet if it's not found in `WAGTAIL_CLIP_DOWNLOAD_PATH`. """ device = torch.device("cpu") model, preprocess = clip.load("ViT-B/32", device, download_root=DOWNLOAD_PATH) return model, device,...
deebe0a5d5edb82b34d386771367ab65aaf6cb4b
3,641,030
from traceback import format_exception def exception_response(ex: Exception): """Generate JSON payload from ApiException or Exception object.""" if not ex: app.logger.error("Function received argument: None!") return __make_response( 500, { "error" : "...
d3b8d58d3214d3543cea5135a46455fc824b78d7
3,641,031
def check(pack, inst): """ A function to check if an instruction is present in the packet Input: - pack: The packet to be checked - inst: The instruction Output: Returns True if the instruction is present in the packet else Fase """ inst_key = getPacketKey(inst[0]) for key ...
905fb2061b2fd5c129cdb0903ef84184c55844af
3,641,032
import os def find_invalid_filenames(filenames, repository_root): """Find files that does not exist, are not in the repo or are directories. Args: filenames: list of filenames to check repository_root: the absolute path of the repository's root. Returns: A list of errors. """ errors ...
c207442e08fa7a2188ab8e792ee76d596b4f19f0
3,641,033
def get_score(true, predicted): """Returns F1 per instance""" numerator = len(set(predicted.tolist()).intersection(set(true.tolist()))) p = numerator / float(len(predicted)) r = numerator / float(len(true)) if r == 0.: return 0. return 2 * p * r / float(p + r)
115a4847e3d991f47415554401df25d72d74bb2f
3,641,034
def check_ratio_argv(_argv): """Return bool, check optional argument if images are searched by same ratio""" # [-1] To avoid checking 3 places at one, this argument is always last return bool(_argv[-2] in ARGV["search by ratio"] and _argv[-1] in ARGV["search by ratio"])
23a677af4042fcc3616a25378af4e7721971de56
3,641,035
def binary_erosion(input, structure = None, iterations = 1, mask = None, output = None, border_value = 0, origin = 0, brute_force = False): """Multi-dimensional binary erosion with the given structure. An output array can optionally be provided. The origin parameter controls the placement of th...
06de7142d7eca9ca3f5712f76318215950f4c710
3,641,036
def chord_to_freq_ratios(chord): """Return the frequency ratios of the pitches in <chord> Args: chord (tuple of ints): see <get_consonance_score>. Returns: list of ints: """ numerators = [JI_NUMS[i] for i in chord] denoms = [JI_DENOMS[i] for i in chord] denominator = get_lc...
4811a6b69e6fd646adf5dc7e7a31a23be8fa6708
3,641,037
import torch def proto_factor_cosine(local_proto, global_proto): """ [C, D]: D is 64 or 4 """ # factor = 1 norm_local = torch.norm(local_proto, dim=-1, keepdim=False) norm_global = torch.norm(global_proto, dim=-1, keepdim=False) # [C] factor_refined = torch.sum(local_proto*global_proto, di...
6e9f7540ec1339efe3961b103633f5175cb38c49
3,641,038
def urlparse(d, keys=None): """Returns a copy of the given dictionary with url values parsed.""" d = d.copy() if keys is None: keys = d.keys() for key in keys: d[key] = _urlparse(d[key]) return d
91cd40ef294443431a772ec14ef4aa54dab34ea8
3,641,039
import numpy import math def doFDR(pvalues, vlambda=numpy.arange(0,0.95,0.05), pi0_method="smoother", fdr_level=None, robust=False, smooth_df = 3, smooth_log_pi0 = False): """modeled after code taken from http://genomics.princeton.edu/storeylab/qvalu...
17919d989ca07b4fb87930141cef3ce392b66ad4
3,641,040
def sequence(ini, end, step=1): """ Create a sequence from ini to end by step. Similar to ee.List.sequence, but if end != last item then adds the end to the end of the resuting list """ end = ee.Number(end) if step == 0: step = 1 amplitude = end.subtract(ini) mod = ee.Number(ampl...
cca23fd00ddf1237a95a53b7f6a3f1bc264f84da
3,641,041
def kBET_single( matrix, batch, k0=10, knn=None, verbose=False ): """ params: matrix: expression matrix (at the moment: a PCA matrix, so do.pca is set to FALSE batch: series or list of batch assignemnts returns: kBET observed rejection rate ...
42ecfb9dee65806a25e92764ea7c1ef54316be02
3,641,042
from typing import Tuple import numpy def get_eye_center_position(face: Face) -> Tuple[numpy.int64, numpy.int64]: """Get the center position between the eyes of the given face. Args: face (:class:`~.types.Face`): The face to extract the center position from. Returns: Tuple[:d...
562dca1971996e8d7497d146aa7ccefcb3ce8006
3,641,043
def esc_quotes(strng): """ Return the input string with single and double quotes escaped out. """ return strng.replace('"', '\\"').replace("'", "\\'")
25956257e06901d4f59088dd2c17ddd5ea620407
3,641,044
def gen_fake_game_data(): """Creates an example Game object""" game = Game( gameday_id='2014/04/04/atlmlb-wasmlb-1', venue='Nationals Park', start_time=parser.parse('2014-04-04T13:05:00-0400'), game_data_directory='/components/game/mlb/year_2014/month_04/day_04/gid_2014_04_04_atl...
415c85eb0ba4e03c135ab56791177ebb634ea5e3
3,641,045
def unsafe_load_all(stream): """ Parse all YAML documents in a stream and produce corresponding Python objects. Resolve all tags, even those known to be unsafe on untrusted input. """ return load_all(stream, UnsafeLoader)
f6307614e776b221ec22b063680f34f5e2ddf789
3,641,046
import os def random_name(url, type): """ 对文件或文件夹进行随机重命名(防止产生因同名而无法重命名的问题)(具体类型则根据所给的文件类型type决定,用户调用相应的方法后type自动赋值) :param url: 用户传入的文件夹的地址 :return: 返回文件夹中所有文件或文件夹重命名之前的名字的列表 """ if not os.path.exists(url): url=resource_manager.Properties.getRootPath() + resource_manager.getSeparator(...
d251765704be00291361085a6665858b09543fc8
3,641,047
import sys import array def peakdet(v, delta, x = None): """ Converted from MATLAB script at http://billauer.co.il/peakdet.html """ maxtab = [] mintab = [] if x is None: x = arange(len(v)) v = asarray(v) if len(v) != len(x): sys.exit('Input vectors v and x must have ...
fdd21aeded390f5b8a71823f195548f8977aefe0
3,641,048
def jaccard(set1, set2): """ computes the jaccard coefficient between two sets @param set1: first set @param set2: second set @return: the jaccard coefficient """ if len(set1) == 0 or len(set2) == 0: return 0 inter = len(set1.intersection(set2)) return inter / (len(set1) + le...
9a99c6c5251bdb7cb10f6d3088ac6ac52bb02a55
3,641,049
from typing import Dict from typing import Any import json def create_cluster_custom_object(group: str, version: str, plural: str, resource: Dict[str, Any] = None, resource_as_yaml_file: str = None, secrets: Secrets = N...
38b24e9bbb0c5e2e24789b1d06984b338582b7a2
3,641,050
import os import sys import pprint import tempfile import yaml def normalize_flags(flags, user_config): """Combine the argparse flags and user configuration together. Args: flags (argparse.Namespace): The flags parsed from sys.argv user_config (dict): The user configuration taken from ...
88609f2307f9147387a0419292b427e46c08d7e5
3,641,051
import json def get_fast_annotations(): """ Title: Get Fast Annotations Description : Get annotations for a list of sequences in a compressed form URL: /sequences/get_fast_annotations Method: GET URL Params: Data Params: JSON { "sequences": list of str ('ACGT') ...
fe8c043128c80c885f0e6d424fb8a6e8eafe171b
3,641,052
def to_numeric(arg): """ Converts a string either to int or to float. This is important, because e.g. {"!==": [{"+": "0"}, 0.0]} """ if isinstance(arg, str): if '.' in arg: return float(arg) else: return int(arg) return arg
e82746e1c5c84b57e59086030ff7b1e93c89a8ec
3,641,053
def get_kde_polyfit_estimator(samples, N=100000, bandwidth=200, maxlength=150000, points=500, degree=50): """多項式近似したバージョンを返すやつ 一応両方かえす""" f = get_kde_estimator(samples, N, bandwidth) x = np.linspace(1, maxlength, points) z = np.polyfit(x, f(x), degree) return (lambda x: np.where(x<=maxlength, np.pol...
72801a8be25826ef42ab700e5cae742ed59fcea4
3,641,054
def read_tracker(file_name): """ """ with open(file_name, "r") as f: return int(f.readline())
9d1f43b8f833b5ca86c247760ae79e18f33aa019
3,641,055
def MixR2VaporPress(qv, p): """Return Vapor Pressure given Mixing Ratio and Pressure INPUTS qv (kg kg^-1) Water vapor mixing ratio` p (Pa) Ambient pressure RETURNS e (Pa) Water vapor pressure """ return qv * p / (Epsilon + qv)
71d7ee564d07292ef4831bf39e54f51071b7d7dd
3,641,056
def sigmoid_derivative(dA, cache): """ Implement the backward propagation for a single SIGMOID unit. Arguments: dA -- post-activation gradient, of any shape cache -- 'Z' where we store for computing backward propagation efficiently Returns: dZ -- Gradient of the cost with respect to Z ...
6b45e722bc48b4cf60170de267c235d0943d022c
3,641,057
from typing import Counter def part2(lines, rounds=100): """ >>> data = load_example(__file__, '24') >>> part2(data, 0) 10 >>> part2(data, 1) 15 >>> part2(data, 2) 12 >>> part2(data, 3) 25 >>> part2(data, 4) 14 >>> part2(data, 5) 23 >>> part2(data, 6) 28...
ff33f249628b1dec33f7ea886f5423012914fc4c
3,641,058
def binary_search( items, target_key, target_key_hi=None, key=None, lo=None, hi=None, target=Target.any, ): """ Search for a target key using binary search and return (found?, index / range). The returned index / range is as follows according to t...
c0539322c0a2dd9cd3b53fa65bf6ecf28840546e
3,641,059
def func_real_dirty_gauss(dirty_beam): """Returns a parameteric model for the map of a point source, consisting of the interpolated dirty beam along the y-axis and a sinusoid with gaussian envelope along the x-axis. This function is a wrapper that defines the interpolated dirty beam. Parameter...
2a0da2176f67a9cd9dd31af48b987f7f3d9d8342
3,641,060
def shortest_path(graph, a_node, b_node): """ code by Eryk Kopczynski """ front = deque() front.append(a_node) came_from = {a_node: [a_node]} while front: cp = front.popleft() for np in graph.neighbors(cp): if np not in came_from: front.append(np) came_from[np] = [came_from[cp], ...
6c2f04282eac52fcad7c4b15fa23753373940d6b
3,641,061
def rank_compute(prediction, att_plt, key, byte): """ - prediction : predictions of the NN - att_plt : plaintext of the attack traces - key : Key used during encryption - byte : byte to attack """ (nb_trs, nb_hyp) = prediction.shape idx_min = nb_trs min_rk = 255 ...
a21a5fbf5db64cab1fe87ed37c4a9770f5ccd9f8
3,641,062
def purelin(n): """ Linear """ return n
493c4ae481702194fe32eec44e589e5d15614b99
3,641,063
def arrayDimension(inputArray): """Returns the dimension of a list-formatted array. The dimension of the array is defined as the number of nested lists. """ return len(arraySize(inputArray))
4d98b76ce6f5aeae9a8171918a78c31ef75dd33e
3,641,064
from datetime import datetime def process_data(records, root) -> bool: """Creates the xml file that will be imported in pure.""" for record in records: item_metadata = record["metadata"] # If the rdm record has a uuid means that it was imported from pure - REVIEW if "uuid" in item_met...
3e78792c2f147cb56ac502d783fb2a1e3346be53
3,641,065
def hopcroft(G, S): """Hopcroft's algorthm for computing state equivalence. Parameters ---------- G : fully deterministic graph S : iterable one half of the initial (bi)partition Returns ------- Partition """ sigma = alphabet(G) partition = Partition(list(G)) p1...
a841dc0a77bb82a27937b20a7335c399ff9b53f5
3,641,066
import logging def TVRegDiff(data, itern, alph, u0=None, scale='small', ep=1e-6, dx=None, plotflag=_has_matplotlib, diagflag=True, precondflag=True, diffkernel='abs', cgtol=1e-4, cgmaxit=100): """ Estimate derivatives from noisy data based using the Total Variation Regularized ...
b4497f4ac6d09f5240f551f6d25077d2e7624af2
3,641,067
def replaceidlcode(lines,mjd,day=None): """ Replace IDL code in lines (array of strings) with the results of code execution. This is a small helper function for translate_idl_mjd5_script(). """ # day # psfid=day+138 # domeid=day+134 if day is not None: ind,nind = dln.where( (l...
fd8a2bc9a374c36e7973cfc01d38582e25ce9438
3,641,068
import torch import tqdm def test( model: nn.Module, classes: dict, data_loader: torch.utils.data.DataLoader, criterion: nn.Module, # scheduler: nn.Module, epoch: int, num_iteration: int, use_cuda: bool, tensorboard_writer: torch.utils.tensorboard.SummaryWriter, name_step: str,...
306b43730554492d1d541be1a8c8d4c202b932f4
3,641,069
import torch def get_grad_spherical_harmonics(xyz, l, m): """Compute the gradient of the Real Spherical Harmonics of the AO. Args: xyz : array (Nbatch,Nelec,Nrbf,Ndim) x,y,z, distance component of each point from each RBF center l : array(Nrbf) l quantum number m : array(...
a01b529f98276e41fa3ed8c9934db770979d8702
3,641,070
import os def send_photo(self, user_ids, filepath, thread_id=None): """ :param self: bot :param filepath: file path to send :param user_ids: list of user_ids for creating group or one user_id for send to one person :param thread_id: thread_id """ user_ids = _get_user_ids(self, user_ids...
8a03bfced7d9fd6d9d837fa2db10b760e31db3f7
3,641,071
from typing import List from typing import Union import re def references_from_string(string: str) -> List[ Union[InputReference, TaskReference, ItemReference] ]: """Generate a reference object from a reference string Arguments: string {str} -- A reference string (eg: `{{inputs.exampl...
4e28d082e7fc638470b2f4753e6283d9630be073
3,641,072
def arrange_images(normalized_posters, blur_factor, blur_radius): """ Arranges images to create a collage. Arguments: norm_time_posters: tuple(float, PIL.Image) Normalized instances of time and area for time and posters respectively. blur_factor: Number of times to a...
e3d4dc90c8ff4ec435061a3507423cd8c5f7c6d4
3,641,073
def make_text(text, position=(0, 0, 0), height=1): """ Return a text object at the specified location with a given height """ sm = SpriteMaterial(map=TextTexture(string=text, color='white', size=100, squareTexture=False)) return Sprite(material=sm, position = position, scaleToTexture=True, scale=[1,...
19daad7ae7f93ce1a4f06596fe2799c8e9701b72
3,641,074
import copy def get_features(user_features, documents, ARGS, BOW = False, Conversational = False, User = False, SNAPSHOT_LEN = False, Questions = False, COMMENT_LEN = True): """ Generates Features: Type of Features: - BOW: bag of words features - Conversational: features extracted...
b200c9783661db13bfecb76eee18f39bc67301b6
3,641,075
import time import traceback def incomeStat(headers): """ 收益统计 :param headers: :return: """ time.sleep(0.3) url = f'https://kd.youth.cn/wap/user/balance?{headers["Referer"].split("?")[1]}' try: response = requests_session().get(url=url, headers=headers, timeout=50).json() print('收益统计') pri...
8c023314835ab46b354ae0d793d6de3694711a65
3,641,076
def t_matrix(phi, theta, psi, sequence): """ Return t_matrix to convert angle rate to angular velocity""" if sequence == 'ZYX': t_m = np.array([[1, np.sin(phi)*np.tan(theta), np.cos(phi)*np.tan(theta)],\ [0, np.cos(phi), -np.sin(phi)],\ [0, np.sin(phi)/np.cos(...
65c5595cc286a442777651f888a6e3fee032ba21
3,641,077
def point_in_fence(x, y, points): """ 计算点是否在围栏内 :param x: 经度 :param y: 纬度 :param points: 格式[[lon1,lat1],[lon2,lat2]……] :return: """ count = 0 x1, y1 = points[0] x1_part = (y1 > y) or ((x1 - x > 0) and (y1 == y)) # x1在哪一部分中 points.append((x1, y1)) for point in points[1:]...
bb25f399eadf818fbafdeee6c8adbb1254a579f7
3,641,078
def parse_prior(composition, alphabet, weight=None): """Parse a description of the expected monomer distribution of a sequence. Valid compositions: * None or 'none' No composition sepecified * 'auto' or 'automatic' Use the typical average distribution for proteins and an equipr...
50795a21231138bb3576a50a3791d9136264754e
3,641,079
def get_queues(prefix=None): """ Gets a list of SQS queues. When a prefix is specified, only queues with names that start with the prefix are returned. :param prefix: The prefix used to restrict the list of returned queues. :return: A list of Queue objects. """ if prefix: queue_iter...
c459cad66561d887abdcc40157fea09481e267c7
3,641,080
def _genNodesNormal(numNodes=None, center=None, standardDeviation=None): """ Generate randomized node using Normal distribution within a bounding area Parameters ---------- numNodes: int Required, number of nodes to be generated centerLat: float, Required Latitude of the center point centerLon: float, Requi...
62d7f44056621786a1b796bfe85df4eac0ec9574
3,641,081
def util_test_normalize(mean, std, op_type): """ Utility function for testing Normalize. Input arguments are given by other tests """ if op_type == "cpp": # define map operations decode_op = c_vision.Decode() normalize_op = c_vision.Normalize(mean, std) # Generate dataset...
43fe33a124a8d52252738697eccd4775edb6e4b8
3,641,082
def calc_sub_from_constant(func, in_data, **kwargs): """[SubFromConstant](https://docs.chainer.org/en/v4.3.0/reference/generated/chainer.functions.add.html) See the documentation for [AddConstant](#addconstant) """ return _calc(func, in_data, **kwargs)
d40fcf668c2dc8e0c7d889d2cf145de208cc0ae6
3,641,083
import torch def mask_distance_matrix(dmat, weight_bins=weight_bins): """ Answer: yep, a larger weight is assigned to a pair of residues forming a contact. I assigned 20.5, 5.4, 1 to the distance 0-8, 8-15, and >15, respectively, for residue pairs (i, j) where |i-j| >=24. These numbers were derived fr...
4d8ca64834b6de9e4dd0077278cb4a687f7cf33e
3,641,084
def get_output(): """Return the set output setting.""" return _output
4332661d333d4ca2c364761b35bb2d9ed0b9d302
3,641,085
def cash_grouped_nb(target_shape, cash_flow_grouped, group_lens, init_cash_grouped): """Get cash series per group.""" check_group_lens(group_lens, target_shape[1]) out = np.empty_like(cash_flow_grouped) from_col = 0 for group in range(len(group_lens)): to_col = from_col + group_lens[group] ...
3a7978493503cbae4fc867d8ca864193d913f33f
3,641,086
def agreement(): """Input for Accepting license """ form = LicenseForm() if form.validate_on_submit(): gluu_settings.db.set("ACCEPT_GLUU_LICENSE", "Y" if form.accept_gluu_license.data else "N") return redirect(url_for(wizard_steps.next_step())) with open("./LICENSE", "r") as f: ...
e213d9ce33014b03fd97fdd3991eb72c52e3e9e7
3,641,087
import torch def rotmat2quat(mat: torch.Tensor) -> torch.Tensor: """Converts rotation matrix to quaternion. This uses the algorithm found on https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion , and follows the code from ceres-solver https://github.com/ceres-solver/ceres-solver/blob/master/in...
470d2890eb5c07dff1fdc3de7d347fc86dd3fd1e
3,641,088
def equalize(image): """ Equalize the image histogram. This function applies a non-linear mapping to the input image, in order to create a uniform distribution of grayscale values in the output image. Args: image (PIL image): Image to be equalized Returns: image (PIL image), Eq...
5283609b316452da5aa9969e999dcdeb4de26b2b
3,641,089
def validate_output(value): """Validate "output" parameter.""" if value is not None: if isinstance(value, str): value = value.split(",") # filter out empty names value = list(filter(None, value)) return value
f00773674868ebde741f64b47fdc3372ad6a1e7d
3,641,090
def dummy_img(w, h, intensity=200): """Creates a demodata test image""" img = np.zeros((int(h), int(w)), dtype=np.uint8) + intensity return img
a416753d8aa8682aef2b344f7de416139c9ed33a
3,641,091
def getHandler(database): """ a function instantiating and returning this plugin """ return Events(database, 'events', public_endpoint_extensions=['insert'])
e42e69b379e2053437ac75fe3fe8fc81229579c1
3,641,092
import logging def RegQueryValueEx(key, valueName=None): """ Retrieves the type and data for the specified registry value. Parameters key A handle to an open registry key. The key must have been opened with the KEY_QUERY_VALUE access right valueName The name of the registry ...
5cceedabfaef44040067424696d13eb8d0f15550
3,641,093
def read_molecules(filename): """Read a file into an OpenEye molecule (or list of molecules). Parameters ---------- filename : str The name of the file to read (e.g. mol2, sdf) Returns ------- molecule : openeye.oechem.OEMol The OEMol molecule read, or a list of molecules i...
420ba85dc768435927441500fe8005e3f009b9af
3,641,094
def euler(derivative): """ Euler method """ return lambda t, x, dt: (t + dt, x + derivative(t, x) * dt)
08d636ec711f4307ab32f9a8bc3672197a3699d9
3,641,095
def detect_encoding_type(input_geom): """ Detect geometry encoding type: - ENC_WKB: b'\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00H\x93@\x00\x00\x00\x00\x00\x9d\xb6@' - ENC_EWKB: b'\x01\x01\x00\x00 \xe6\x10\x00\x00\x00\x00\x00\x00\x00H\x93@\x00\x00\x00\x00\x00\x9d\xb6@' - ENC_WKB_HEX: '01010000000000000...
4361abf695edad5912559175bd48cfa0bad92769
3,641,096
import os def GetFilesToConcatenate(input_directory): """Get list of files to concatenate. Args: input_directory: Directory to search for files. Returns: A list of all files that we would like to concatenate relative to the input directory. """ file_list = [] for dirpath, _, files in os.wal...
f8e2805b94171645ef9c4d51ded83a8f2f9e7675
3,641,097
def unet_weights(input_size = (256,256,1), learning_rate = 1e-4, weight_decay = 5e-7): """ Weighted U-net architecture. The tuple 'input_size' corresponds to the size of the input images and labels. Default value set to (256, 256, 1) (input images size is 256x256). The float 'learning_rate...
f091627475f13985e33f2960afd4b0136e9d10f4
3,641,098
from re import T def std(x, axis=None, keepdims=False): """Standard deviation of a tensor, alongside the specified axis. """ return T.std(x, axis=axis, keepdims=keepdims)
ad3c547d19507243ec143d38dd22f9fc92becffb
3,641,099