content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def signup() -> Response | str | tuple[dict[str, str | int], int]: """Sign up""" # Bypass if user is logged in if current_user.is_authenticated: return redirect(url_for("home")) # Process user data try: # Return template if request.method is GET assert request.method != "GE...
9496c11a9015b69c7cf2f89d19a45f93405f5dfe
3,640,981
import copy def evaluate_all_configs(hparams, agent_model_dir): """Evaluate the agent with multiple eval configurations.""" def make_eval_hparams(hparams, policy_to_action, max_num_noops): hparams = copy.copy(hparams) hparams.add_hparam("num_agents", hparams.eval_num_agents) hparams.add_hparam("policy...
107fb692adec1ce7dbb580c30e3e7b0402874054
3,640,982
from typing import Tuple def shape(a: Matrix) -> Tuple[int, int]: """ Returns the num of rows and columns of A """ num_rows = len(a) num_cols = len(a[0]) if a else 0 # number of elements so columns in first element if it exists return num_rows, num_cols
24ef9045e86b6027f76ddf57bf5eba44553798c5
3,640,983
def solve(A, b): """ :param A: Matrix R x C :param b: Vector R :return: Vector C 'x' solving Ax=b >>> M = Mat(({'a', 'b', 'c', 'd'}, {'A', 'B', 'C', 'D'}), { \ ('a', 'A'): one, ('a', 'B'): one, ('a', 'D'): one, \ ('b', 'A'): one, ('b', 'D'): one, \ ('c', 'A'): one, ('c', 'B')...
b25a762ee8f8229d1bc573c828a7151770d3240c
3,640,984
def token_groups(self): """The groups the Token owner is a member of.""" return self.created_by.groups
9db411660db1def09b8dc52db800ca4c09a38cce
3,640,985
import requests def get_html_content_in_text(url): """ Grab all the content in webpage url and return it's content in text. Arguments: url -- a webpage url string. Returns: r.text -- the content of webpage in text. """ r = requests.get(url) return r.text
fd8ddc992f34c186051ca8985ffb110c50004970
3,640,986
def subscribe(): """Subscribe new message""" webhook_url = request.form.get("webhook_url") header_key = request.form.get("header_key") header_value = request.form.get("header_value") g.driver.subscribe_new_messages(NewMessageObserver(webhook_url, header_key, header_value)) return jsonify({"succe...
97a47fb298bbc0bac3e333037210556525dd837f
3,640,987
def SegAlign(ea, alignment): """ Change alignment of the segment @param ea: any address in the segment @param alignment: new alignment of the segment (one of the sa... constants) @return: success (boolean) """ return SetSegmentAttr(ea, SEGATTR_ALIGN, alignment)
c0c380e194fbed43b87be81108eecf864809c447
3,640,988
import requests def create_bitlink(logger, headers='', long_url='google.com'): """ Функция создает короткие ссылки из длинных :param logger: logger object :param headers: Generic Access Token сформированнный на сайте :param long_url: Ссылка которую надо укоротить :return: созданная короткая сс...
be5c7882a8577c8d406412c790f3d5fbcbd11019
3,640,989
import numpy def compute_neq(count_mat): """ Compute the Neq for each residue from an occurence matrix. Parameters ---------- count_mat : numpy array an occurence matrix returned by `count_matrix`. Returns ------- neq_array : numpy array a 1D array containing the neq ...
e3d738eb1c8ed58a3c4d4a4efc5323930d03be1f
3,640,990
import optparse def _GetOptionsParser(): """Get the options parser.""" parser = optparse.OptionParser(__doc__) parser.add_option('-i', '--input', dest='inputs', action='append', default=[], help='One or more inp...
e1ec0530357ad3bebbac80c86b9d9b1010e6688c
3,640,991
def spikalize_img(experiment, image, label): """ Transform image to spikes. Spike with poisson distributed rate proportional to pixel brightness. :param experiment: :param image: :param label: :return: """ image_shape = np.append(np.array(experiment.timesteps), np.array(image.shape)) ...
7159334b40c3841977a0772ac25c71a934d268ac
3,640,992
def update_security_schemes(spec, security, login_headers, security_schemes, unauthorized_schema): """Patch OpenAPI spec to include security schemas. Args: spec: OpenAPI spec dictionary Returns: Patched spec """ # login_headers = {'Set-Cookie': # ...
1ecb5cc3a121fc151794e4e24cd4aca4bc07ce46
3,640,993
def get_geckodriver_url(version): """ Generates the download URL for current platform , architecture and the given version. Supports Linux, MacOS and Windows. :param version: the version of geckodriver :return: Download URL for geckodriver """ platform, architecture = get_platform_architectu...
9d71728c551c67e86a61c3b870728bc70cad48ba
3,640,994
def get_graph_size(depth: int): """returns how many nodes are in fully-equipped with nodes graph of the given depth""" size = 1 cur_size = 1 ln = len(expand_sizes) for i in range(min(ln, depth)): cur_size *= expand_sizes[i] size += cur_size if ln < depth: size += cur_siz...
00f2a2ce714550785e99c0d193f47df05cc30b68
3,640,995
def inherits_from(obj, parent): """ Takes an object and tries to determine if it inherits at *any* distance from parent. Args: obj (any): Object to analyze. This may be either an instance or a class. parent (any): Can be either instance, class or python path to class. R...
9d7e0665b4e4fe2a3f7c136436a2502c8b72527c
3,640,996
from typing import Optional def load_df_from_googlesheet( url_string: str, skiprows: Optional[int] = 0, skipfooter: Optional[int] = 0, ) -> pd.DataFrame: """Load a Pandas DataFrame from a google sheet. Given a file object, try to read the content as a CSV file and transform into a data frame....
adfcff1968eccfa44640b5e9a7e3143703284dfb
3,640,997
def decomp(bits, dummies=default_dummies, width=default_width): """Translate 0s and 1s to dummies[0] and dummies[1].""" words = (dummies[i] for i in bits) unwrapped = ' '.join(words) return wrap_source(unwrapped, width=width)
a6540cc90412b9e72b62c57fe6828b45ad5df593
3,640,998
def get_word_node_attrs(word: Word) -> WordNodeAttrs: """Create the graph's node attribute for a `Word`. Build an attribute dict with the word's features. Note that we're using the term `Word` instead of `Token` to be closer to the implementation of these data structures in stanza. From stanza's docume...
143a00206cfa8d98419f2d0e21e1013ea6dd02ab
3,640,999
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
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
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 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
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
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
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
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