content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def combine(main_busytime_list, merging_list): """ given two lists of busytimes, returns list of busytimes that have events of the same day together """ merged = [ ] days = { } current_date = '' #this creates the dates dict for busytime in main_busytime_list: if busytime['date'] ...
978946353dd4d7a57b57e66693a5d396f6e8d7f6
72,300
def update_speed(row_speed, column_speed, rows_direction, columns_direction, row_speed_limit=2, column_speed_limit=2, fading=0.8): """Update speed smootly to make control handy for player. Return new speed value (row_speed, column_speed) rows_direction — is a force direction by rows axis. Possible values: ...
e17e8e7d5ecd8b1f0e4679ca3d5e70f8b99aadac
72,301
def oc(*args, **kwargs): """ Run 'sh.oc' and print the command, show output, catch errors, etc. Optional kwargs: _reraise: if ErrorReturnCode is hit, don't exit, re-raise it _exit_on_err: sys.exit(1) if this command fails (default True) _silent: don't print command or resulting stdo...
6b6c90a3aaf8d1d89c6abe7a9b6ee84765c8bad5
72,302
def label_to_membership(targets, num_classes=None): """Generate a true membership matrix, and assign value to current Pi. Parameters: targets (np.ndarray): matrix with one hot labels Return: Pi: membership matirx, shape (num_classes, num_samples, num_samples) """ targets = one_hot...
9681fa8639b9403ec2e5b7637c5df0af571e6fe4
72,303
def open_fits(fitsfilename, n=0, header=False, ignore_missing_end=False, precision=np.float32, verbose=True): """Loads a fits file into a memory as numpy array. Parameters ---------- fitsfilename : string Name of the fits file. n : int It chooses which HDU to open....
ccb8c91ab2c1ca20d590028a4865e58d02baf0fe
72,304
def create_masked_lm_predictions(tokens, masked_lm_prob, max_predictions_per_seq, num_already_masked, vocab_words, rng, do_whole_word_mask=False): """Creates the predictions for the masked LM objective.""" assert 0 < len(tokens) <= 512, str(len(tokens)) cand_indexes = [] ...
e30ba2438ffcdf8d1c154b90bdac1a9f106eaf10
72,305
def get_user_id(username): """Convenience method to look up the id for a username.""" try: rv = User.select().where(User.username == username).get() except User.DoesNotExist: rv = None return rv
5bda6c59c6864d03755e4dd3330a925c56ba546a
72,306
def performSA( initLabels, initRegionList, initRegionSpatialAttr, threshold_array, weight, distance_matrix, threshold, alpha, tabuLength, max_no_move, ): """...Needs a short description... Parameters ---------- initLabels : ... init...
a0c971fd0cb29309e954bd8bd720840cd1ea5907
72,307
def partition(data, threshold=0.5, verbose = False): """Partitions data into training and test sets. Assumes the last column of data is y. Parameters ---------- data : numpy ndarray, or pandas.DataFrame Data to partition into training and test sets. threshold : float Determi...
7231dacd783b13f45d0591908653694bc08bd669
72,308
def preprocess_data(closing_data): """Preprocesses data into time series. Args: closing_data (pandas.dataframe): dataframe with close values of tickers Returns: pandas.dataframe: dataframe with time series """ # transform into log return log_return_data = pd.DataFrame() tickers = [column_heade...
475722431583c1299a209df8c6b69ef7b0d1270e
72,309
def map_sinh(process): """ """ return map_default(process, 'sinh', 'apply')
39e91c99e95f244b2a7c08ba4949caefcdbbb930
72,310
from typing import Mapping from typing import Hashable from typing import Callable from typing import Union def xarray_block_reduce( obj: T_DataArray_or_Dataset, block_sizes: Mapping[Hashable, int], reduction_function: Callable, cval: float = np.nan, coord_func: Union[str, CoordFunc] = coarsen_coo...
f82cc61e9a0b6afb6167b47a58d105119a125d80
72,311
def GroupNorm(x, group=32, gamma_initializer=tf.constant_initializer(1.)): """ More code that reproduces the paper can be found at https://github.com/ppwwyyxx/GroupNorm-reproduce/. """ shape = x.get_shape().as_list() ndims = len(shape) assert ndims == 4, shape chan = shape[1] assert chan...
f4fd603fc35f8b17881f60088b74f5176970e9ce
72,312
import traceback def get_min_max_json(request): """ Returns a JsonResponse with min and max values :param request: :return: """ if request.method == 'POST': try: post_values = unravel_post(request.POST) values = get_min_max(model=post_values.model, ...
89f700e8d420c978bb00ccee2bba25026b531706
72,313
def regional_get_more(page, per_page, kindtype, status, merge): """ 分页获取指定 votype 下的 ValueObject 信息 """ if merge > 0: return_method = lambda vos: [vo.merge() for vo in vos] else: return_method = 'model' qry = Regional.get_qry(kindtype=kindtype, status=status) rdata = get_page_re...
b3650a5f9dc2c29f52fd7c739162d49e50307a88
72,314
from typing import List def chunked_conj(chunk_size=32) -> Fn: """ Like `conj` but buffers values into chunks and calls `conj` with chunks. Returns a function which will conjoin in batches for the specified `chunk_size`. To be used with tranducers. Must complete the fuction (call with 1 arg) to g...
84ebffaa6914711cb8bd6eb61dd16b9f47f0a945
72,315
def _make_final_gr(x): """Apply function to do graduation rates""" race, sixyrgr, sixyrgraah, comments = x first_gr = sixyrgraah if race in ["B", "H", "M", "I"] else sixyrgr if comments == "Posse": return (first_gr + 0.15) if first_gr < 0.7 else (1.0 - (1.0 - first_gr) / 2) else: ret...
600157433efe8a1689d81c2e17114c1578c43c21
72,316
def truncate_pad(line, num_steps, padding_token): """Truncate or pad sequences. Defined in :numref:`sec_machine_translation` """ if len(line) > num_steps: return line[:num_steps] # Truncate return line + [padding_token] * (num_steps - len(line))
2e9da312e50cea4bc2015612fa5aaccc66d3f704
72,317
def sparsenet264(**kwargs): """ SparseNet-264 model from 'Sparsely Aggregated Convolutional Networks,' https://arxiv.org/abs/1801.05895. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.torch/models' ...
8b8a3b8cc3e78c04dc190458effd0e4de46bf9bd
72,318
from typing import Callable def rmsle(series1: TimeSeries, series2: TimeSeries, intersect: bool = True, reduction: Callable[[np.ndarray], float] = np.mean) -> float: """ Root Mean Squared Log Error (RMSLE). For two time series :math:`y^1` and :math:`y^2` of length :math:`T`, it ...
eb66e6a618c9f3a3373bbf57d66523cada197fb1
72,319
def extract(infile,filter="(tcp or udp or gre)",extension="", ip_layer=False): """Extract flows from given pcap file. Parameters ---------- infile : string Path to input file. filter : string Filter condition, which is the same with wireshark extensio...
660733e97caaaf11d58008f3214d9cf218f958ba
72,320
import requests def check_hash(h): """ Do the heavy lifting. Take the hash, poll the haveibeenpwned API, and check results. :param h: The sha1 hash to check :return: The number of times the password has been found (0 is good!) """ if len(h) != 40: raise ValueError("A sha1 hash should be 30 characters.") h = ...
965dd75b5da095bc24ce6a6d733b271d9ec7aa80
72,321
import collections import json def _encode_log(namespace, time_ms, event_type, key, value, metadata): """Encodes an MLEvent as a string log line. Args: namespace: provides structure, e.g. "GPU0". time_ms: milliseconds since unix epoch. event_type: one of: 'INTERVAL_START', 'INTERVAL_END', 'POINT_IN_T...
61de4ace883fe63ed3868487d73ea7288e44de75
72,322
import re def load(path, mode='r', encoding='cp932'): """ otoiniを読み取ってオブジェクト生成 """ # otoiniファイルを読み取る path = path.strip('"') with open(path, mode=mode, encoding=encoding) as f: lines = [line.strip() for line in f.readlines()] # Otoクラスオブジェクトのリストを作る otoini = OtoIni() for line...
224939573e3e31cffbd21b0defba5d6effe4b83b
72,323
def RF_get_feature(path): """ 获取apk特征集 :param path: :return: """ feature_list = get_permissions(path)+get_apis(path) feature_list = list(set(feature_list)) return list(feature_list)
7cbecd5396c1e69f9f20a4ee7f53303b866884d2
72,324
def create_unet_new(config, metrics=None): """ Does not work so far!!! :param config: :param metrics: :return: """ unet = Unet(config, metrics) loss_f = config.get('LOSS_FUNCTION', keras.losses.categorical_crossentropy) unet.compile(optimizer=get_optimizer(config), loss=loss_f, metri...
80dbac4ca81a1c216e342ac47411563ec48f63ed
72,325
import argparse def create_parser(prog_name): """Parse command line flags added to `rest_api` command. """ parent_parser = create_parent_parser(prog_name) parser = argparse.ArgumentParser( parents=[parent_parser], formatter_class=argparse.RawTextHelpFormatter) parser.add_argument...
7bac1a9175c8135d2f93c91cbc1dccd760ad1eee
72,326
def make_frequency_matrix(sequence_dict): """Makes list of base frequencies per position - Skips any position where the maximum base is a '-'' or 'N' :param sequence_dict - count of each base per position: :returns frequency_matrix - list of dictionaries: """ frequency_matrix = [] base_pos...
820f4387f778429890cb961c2ca76aa51a01d250
72,327
def create_ipv6_filter_rule(container_ip, bridge, proto, container_port): """return a iptables v4 filter rule for forwarding a host port to a container IP:port""" return '-A FORWARD -d {container_ip} ! -i {bridge} -o {bridge}' \ ' -p {proto} -m {proto} --dport {container_port}'\ ' -j ACCEP...
903e43c285c14e20aeb74133c3a9da14b21997b6
72,328
import re def is_applicable_python_file(rel_path: str) -> bool: """ Determines if a file should be included in incremental coverage analysis. Args: rel_path: The repo-relative file path being considered. Returns: Whether to include the file. """ return rel_path.endswith('.py')...
a890ceaee78cc6a09cd3055dab0573d352d81166
72,329
def get_field_hint(config, field): """Get the hint given by __field_hint__ or the field name if not defined.""" return getattr(config, '__{field}_hint__'.format(field=field), field)
0d374daf93646caf55fe436c8eb2913d22151bbc
72,330
def optimal_epsilon_integral(): """Fit optimal choice of epsilon for integral representation. The integrand of int_0^pi P(eps, a, b, x, phi) * dphi can exhibit oscillatory behaviour. It stems from the cosine of P and can be minimized by minimizing the arc length of the argument f(phi) =...
6d00fb2982b9210bf0aad1c67b88187a80cb0d7a
72,331
def strikethrough(text): """Return the text, with strikethrough IRC formatting. Note: This is a relatively new addition to IRC formatting conventions. Use only when you can afford to have its meaning lost, as not many clients support it yet.""" return ''.join([CONTROL_STRIKETHROUGH, text, CONTROL_S...
1842fd3eeaf552f465a795969f67f3b3dce2440b
72,332
def get_energy_level(sound, win_len): """ Calculate energy signal of an audio object Args: sound: AudioSegment object with the audio signal win_len: length of the window for the energy calculations Returns: energy: the energy of the signal """ loudness = list([]) len...
70c693cef7f7e5cbe2ff6187312db3df97c7677e
72,333
from galpy.potential import evaluateplanarPotentials from galpy.potential import PotentialError from galpy.potential import RZToplanarPotential def vesc(Pot,R): """ NAME: vesc PURPOSE: calculate the escape velocity at R for potential Pot INPUT: Pot - Potential instances or ...
fe5b3aead92acd6777a0babf71683e48a38c3df5
72,334
def match_major_version(semantic_version, major_version): """ :param semantic_version: (str) :param major_version: (int) """ parts = semantic_version.split(".") major = parse_int(parts[0]) return major_version == major
ebd3ec1fc2cb035f7e79f5027dd0a0aea890c43d
72,335
import re def escape_re(strg: str) -> str: """ Returns the string with all regular expression special characters escaped. TODO: Remove this function in favor of re.escape() """ # assert isinstance(strg, str) # re_chars = r"\.^$*+?{}[]()#<>=|!" # for esc_ch in re_chars: # strg = st...
df30603e374a277500cfb268d1a905ed84ca88c5
72,336
def array2tensor(z, dtype=tf.float32): """Converts numpy arrays into tensorflow tensors. Keyword arguments: z -- numpy array dtype -- data type of tensor entries (default float32) """ if len(np.shape(z)) == 1: # special case where input is a vector return tf.cast(np.reshape(z, (np.sh...
4f8e2bb6a2f5a49ac257f14bbfbf3657d9df156c
72,337
def _splitSentencesInternalRawString(body, name): """Splits a raw string.""" docLength = len(body) docName = name doc = nlp(unicode(body)) # Necessary in Python2.7 #doc = nlp(body) # Necessary in python3.6 sentences = [] for sent in doc.sents: text = sent.text span = (sent.st...
b658b49aedfed3431f39ab7471427428ab787326
72,338
def Fourier_series_approx(x_range, fx, n_deg): """ This function is used to create the Fourier series which be truncated fourier_f(x) = sum(2*cn*exp(j*n*x/L)) where cn is the Fourier coefficience """ y = fx(x_range) period = 2*np.pi time = x_range ...
173679e7260c1b9860a001a8b50229780a13f95f
72,339
def btc(value): """Format value as BTC.""" return f"{value:,.8f}"
1d883384a6052788e8fa2bedcddd723b8765f44f
72,340
def parse_sbd_devices(options): """Returns an array of all sbd devices. Key arguments: options -- options dictionary Return Value: devices -- array of device paths """ devices = [str.strip(dev) \ for dev in str.split(options["--devices"], ",")] return devices
d706efd6a456e2279b30492b634e018ebd8e873f
72,341
from src.praxxis.sqlite import sqlite_notebook from src.praxxis.display import display_notebook def search_notebook(args, library_db, current_scene_db, query_start, query_end): """searches and displays loaded notebooks""" search_term = args.term notebooks = sqlite_notebook.search_notebooks(library_db, se...
4f36f3b4fd3f1057b729cbe6d4ef6bdcdf5e8b0a
72,342
from typing import Mapping import pandas def create_attribute_types_dataframe(attribute_types: Mapping) -> pandas.DataFrame: """ Creates a pandas.Dataframe from a Mapping of attribute_types str:field=str:attribute_type :param attribute_types: Mapping str:field=str:attribute_type :return: pandas.DataF...
7e7276542cb9a96f3aaa697cad3eba744527f98f
72,343
from typing import List from typing import Iterator def _center_provider(contexts: 'List[Acronym]', min_freq: int, max_rank: int) -> Iterator[str]: """ Provide unlimited center words for a given list of contexts. :param contexts: :param min_freq: :param max_rank: :return:...
17e3d46d3e1dcf90a50e3680c8218d25603bf8bf
72,344
def generateJopekMethodE(loaded_data, n_samples, q_std, node_std, e_std, peri_std, incl_std, show_plots=True, get_more_data=False): """ Generate synthetic orbits using the Jopek & Bronikowska (2016) method E approach. Arguments: loaded_data: [2D ndarray] numpy array containing the input data, colu...
c176c215656672b351ff7a1a5f4724134ea0d2bb
72,345
def pull_from_js(content, key): """Pull a value from some ES6.""" # we have to parse fucking ES6 because ES6 cannot natively import fucking JSON return list(filter(lambda x: f"{key}:" in x, content.split("\n")))[0].split('"')[1]
0b5f7fae68e1f5d376c22cd18a6799c4c76a71f7
72,346
def multi_category_focal_loss2(gamma=2., alpha=.25): """ focal loss for multi category of multi label problem 适用于多分类或多标签问题的focal loss alpha控制真值y_true为1/0时的权重 1的权重为alpha, 0的权重为1-alpha 当你的模型欠拟合,学习存在困难时,可以尝试适用本函数作为loss 当模型过于激进(无论何时总是倾向于预测出1),尝试将alpha调小 当模型过于惰性(无论何时总是倾向于预测出0,或是某一个固定的常数,说...
bb9ab631280dd4425c9517ee25e204b0f31712f4
72,347
import time def nagios_from_file(results_file): """Returns a nagios-appropriate string and return code obtained by parsing the desired file on disk. The file on disk should be of format %s|%s % (timestamp, nagios_string) This file is created by various nagios checking cron jobs such as check-rab...
02697105ad5e9d01dd0eb504e232314f4d15a6a9
72,348
import math def _width2wing(width, x, min_wing=3): """Convert a fractional or absolute width to integer half-width ("wing"). """ if 0 < width < 1: wing = int(math.ceil(len(x) * width * 0.5)) elif width >= 2 and int(width) == width: # Ensure window width <= len(x) to avoid TypeError ...
38bdb809167b19b0ef5c7fad6858d2f7016ec310
72,349
def parse_timecode_str(s: str) -> Timecode: """Parses a timecode from all the numeric digits in s.""" digits = _NON_DIGIT_PATTERN.sub("", s) # Remove non-digits. digits = f"{int(digits):08}" # Zero pad to 8 digits. if len(digits) != 8: print_error_exit(f"Invalid timecode pattern '{s}'") h...
35ce4e572e3f2064f09cb37305ed83aa5ca88cf2
72,350
def probplot( data, ax=None, axtype="prob", yscale="log", xlabel=None, ylabel=None, bestfit=False, scatter_kws=None, line_kws=None, return_results=False, ): """ Probability, percentile, and quantile plots. Parameters ---------- data : sequence or array-like ...
cdd5c8031cce44df9a2225eca7d501cf63f299aa
72,351
from typing import Tuple def concatenate(data, axis): """Concatenate the input tensors along the given axis. Parameters ---------- data : Union(List[relay.Expr], Tuple[relay.Expr]) A list of tensors. axis : int The axis along which the tensors are concatenated. Returns --...
acafe6c2ed70f97e0e88312a5d5c71dae73f1f2e
72,352
def mb_bl_ind(tr1, tr2): """Returns the baseline index for given track indices. By convention, tr1 < tr2. Otherwise, a warning is printed, and same baseline returned. """ if tr1 == tr2: print("ERROR: no baseline between same tracks") return None if tr1 > tr2: print("WARN...
7d1bc958ca9928f54e51935510d62c45f7fc927f
72,353
def run_cardiac_segmentation(img, settings=CARDIAC_SETTINGS_DEFAULTS): """Runs the atlas-based cardiac segmentation Args: img (sitk.Image): settings (dict, optional): Dictionary containing settings for algorithm. Defaults to default_settings. Returns: ...
0c6fa36b5525f4ddc19d891f2f86d17f3683ab60
72,354
from pathlib import Path def check_installed(installed="/media/mmcblk0p1/installed"): """Check if LNCM-Box is installed""" if Path(installed).is_file(): with open(installed, "r") as file: lines = file.readlines() for line in lines: print(line) return Tru...
31f73b8927e0a23c6d70ab13791ead9cf5d55b8c
72,355
def L(s, o, N=5): """ Likelihood input: s: simulated o: observed output: L: likelihood """ # s,o = filter_nan(s,o) return np.exp(-N*np.sum((s-o)**2)/np.sum((o-np.mean(o))**2))
05cb084ce392c009d69b172a72b8b13d9faad8bf
72,356
def decipher(string): """ 1. Record the index of the matched letter 2. Go back to correspond to the original ALPHABET 3. print """ ans = '' for i in s: # W L L H A j = string.find(i) # 0 15 15 11 4 for ch in range(len(ALPHABET)): if j == ch: ans ...
8356cd82021f8166a526cb5cec1efad6cf3ddfa9
72,357
def sliding_window(image_width,image_height, patch_w,patch_h,adj_overlay_x=0,adj_overlay_y=0): """get the subset windows of each patch Args: image_width: width of input image image_height: height of input image patch_w: the width of the expected patch patch_h: the height of the e...
42af883927a72f313eb7804e9d99bd6ec37fa7f3
72,358
from typing import Tuple def process_rows(df: pd.DataFrame) -> Tuple[pd.DataFrame, int, int, int]: """ Create various counts of rows of a dataframe. Drop duplicate rows. Parameters ---------- df : pd.DataFrame The input dataframe. Returns ------- df : pd.DataFrame ...
626dfe150128ad1e27708bfe2ac5b98f2c30e03e
72,359
from FuXi.Rete.RuleStore import Formula from FuXi.Rete.AlphaNode import AlphaNode def ExtendN3Rules(network, horn_clause, constructNetwork=False): """ Extends the network with the given Horn clause (rule) """ rt = [] if constructNetwork: ruleStore = network.ruleStore lhs = BNode() ...
03ad35d45264a84a25a42a76c7458adc08fc861d
72,360
import getpass def main(args: list, pipe: bool) -> Result: """ # TODO: Add docstring for manpage """ args, parser = parse_args(args) if parser.error_message: if not args.version: return output(f"{__COMMAND__}: {parser.error_message}", pipe, success=False) if args.version:...
c520a29143fbe6ca2d12921170e01786ad3e68a6
72,361
def generate_2d_neighbors(input_tensor, dilation=2): """Generate a feature map of 2D neighbors. Note: This op makes 8 (# of neighbors) as the leading dimension so that following ops on TPU won't have to pad the last dimension to 128. Args: input_tensor: A float tensor of shape [height, width, channels]. ...
a7d14fe83b552f990b64b06ef8e4545cfaf11a87
72,362
def datetime_format_to_js_datetime_format(format): """ Convert a Python datetime format to a time format suitable for use with the datetime picker we use, http://www.malot.fr/bootstrap-datetimepicker/. """ converted = format replacements = { '%Y': 'yyyy', '%y': 'yy', '%m'...
a037146b17aae21831bc4c76d4500b12bc34feba
72,363
import os import configparser def load_security_setting(): """Load security settings.""" home = os.environ['HOME'] config_file = os.path.join(home, ".vega/vega.ini") if not check_risky_files([config_file]): return False cfg = configparser.ConfigParser() cfg.read(config_file) config...
c82c3fafc7b5b65a6ba2769970f54ce2dd564af5
72,364
import typing def search( apikey: str, query: str = "", limit: int = DEFAULT_LIMIT, exchange: str = "" ) -> typing.List[typing.Dict]: """ Query FMP /search/ API. Search via ticker and company name. :param apikey: Your API key. :param query: Whole or fragment of Ticker or Name of company. ...
977fd6ebb129a311249042ebe310b8fb5fddbabf
72,365
import click import subprocess def _join(client, network): """Join the given network. Args: client (two1.server.rest_client.TwentyOneRestClient) an object for sending authenticated requests to the TwentyOne backend network (str): the name of the network being joined. D...
3e735faac3b70c77cb97bafa46f35aa69b81847d
72,366
import numpy def malletmodel2ldamodel(mallet_model, gamma_threshold=0.001, iterations=50): """ Function to convert mallet model to gensim LdaModel. This works by copying the training model weights (alpha, beta...) from a trained mallet model into the gensim model. Args: mallet_model : Trained...
c00bc1ece7171c58bea33e5738afee3a0374f310
72,367
def get_sample_counts(tree_sequence, st): """ Returns a list of the sample node counts for the specified tree. """ nu = [0 for j in range(st.get_num_nodes())] for j in range(tree_sequence.get_num_samples()): u = j while u != _tskit.NULL: nu[u] += 1 u = st.get_...
5d0aa413466ceb0ce7e41074680b434a9e663c30
72,368
def mgls(freqs): """ """ if Globals.ar: fitting_coeffs, A_matrix = mMGLS_AR.mdim_gls(Globals.time, Globals.rv, Globals.rv_err, freqs, Globals.params, Globals.nar, Globals.time[0]) #model = mMGLS_AR.model(Globals.time, Globals.rv, freqs, fitting_coeffs, Globals.params) #chi2 = mMGLS_A...
26c9ce981eb616565e1a795a4fe247f84ae1e17e
72,369
def get_physical_wwpns(adapter, force_refresh=True): """Returns the active WWPNs of the FC ports across all VIOSes on system. :param adapter: pypowervm.adapter.Adapter for REST API communication. :param force_refresh: The value discovered by this method is cached. If force_refres...
93131e889d7e059e72fbed0cbd1ff5f2e606ee15
72,370
def _data_aug(image, box, jitter, hue, sat, val, image_input_size, max_boxes, max_trial=10, device_num=1): """Crop an image randomly with bounding box constraints. This data augmentation is used in training of Single Shot Multibox Detector [#]_. More details can be found in data augmentatio...
f969448f44de730616d3ddee0e90b187d7ad2083
72,371
def get_metric_info(f): """Return metric type and metric name as tuple. results/*_div/*/*/effect_sizes.tsv """ path_parts = PurePath(f).parts return path_parts[2], path_parts[3]
8420ac8663c423414153e786c49e854801d3ed0b
72,372
def donation(f): """This decorator passes donate request """ return add_response_headers({'BTC': '1aeuaAijzwK4Jk2ixomRkqjF6Q3JxXp9Q', "Patreon": "patreon.com/jarbasAI", "Paypal": "paypal.me/jarbasAI"})( ...
2ad516b45d3ba1e6d6752fc9b0c2846281e36285
72,373
def collect_reuters_financials(universes=None, sids=None, force=True): """ Collect Reuters financial statements from Interactive Brokers and save to database. This data provides cash flow, balance sheet, and income metrics. Parameters ---------- universes : list of str, optional li...
6699563ddde7759f73794312e8df4f5f31434dae
72,374
def do_admins(bot, msg, **kwargs): """ Return the usernames of those who currently have admin priviledges over the bot receiving this message. """ channel = kwargs.get('event').get('channel') bot.post_msg( text='My admins are: {admins}'.format( admins=', '.join([bot.format_us...
fdd7ec3cbca1ab68de4a7d653d52b95d9f254b66
72,375
def api_get_document(project_id): # noqa: F401 """Retrieve documents in order of review. After these documents were retrieved, the queue on the client side is updated. This resuest can get triggered after each document classification. Although it might be better to call this function after 20 requ...
5eb291aa5bb7f2cffb674764440262fee9bdd1f0
72,376
def bray_curtis_distance_0(x_list, data_list): """ :param x_list : [(x0, y0), (x1, y1), (x2, y2), ..., (xn-2, yn-2), (xn-1, yn-1)] data_list : [x_list_0 (same data structure as x_list), x_list_1, x_list_2, ..., x_list_n-2, x_list_n-1] :return: bcd_list """...
ee61ac9b55d1ff264a7bdc6ccb2f17ca8b9164e8
72,377
def get_sigma(maj_error, min_error, pos_angle, radio_ra, radio_dec, opt_ra, opt_dec, opt_ra_err, opt_dec_err, additonal_error=0.6): """ Get the combined error between an elongated radio source and an optical source. Input: * maj_error: error in the ...
aa8dfac1fa55a19c99aea7113813a8be74f95fb8
72,378
def layer_sizes(X, Y): """ Arguments: X -- input dataset of shape (input size, number of examples) Y -- labels of shape (output size, number of examples) Returns: n_x -- the size of the input layer n_h -- the size of the hidden layer n_y -- the size of the output layer """ ...
0f790d3cafe746f1f01f79782c41747c0a89c3a6
72,379
def measure_optimise(budget, liste): """ measures run time.""" return knap_sack_optimise(budget, liste)
d20d8010e1dbf66e57e56a80332345200064ac59
72,380
def delete_cloudformation_stack(stack_id, aws_config): """ Delete a CloudFormation stack. :param unicode stack_id: The AWS cloudformation stack ID. :param dict aws_config: environment variables to be merged with the current process environment before running the ``aws`` sub-command. :return...
41df0166bad64afaa9da143b05971f64ef0753f6
72,381
from typing import Type from typing import List from typing import Dict def _get_device_info(cls: Type[ophyd.Device]) -> List[Dict]: """ Get Device information that can easily be rendered as a table. Parameters ---------- cls : ophyd.Device subclass """ if not issubclass(cls, ophyd.Device...
8bd170cd11aea75344c91285a0c6f7db3c677e75
72,382
import os def screenshot_fa_peaks(fa, peaks, directory='.'): """ Compute 3 view screenshot with peaks on FA. Parameters ---------- fa : string FA filename. peaks : string Peak filename. directory : string Directory to save the mosaic. Returns ------- n...
048bc652c3968783bf70f837a5701828ab92e56a
72,383
def make_data(current_data): """ Formats the given data into the required form """ x = [] n = len(current_data) for i in range(n - 1): x.append(current_data[i]) x.append(1) return x, current_data[n - 1]
04ff4ba93445895451c4c710e7aae59b9787a07d
72,384
def _process_centroids(k, num_features, observations, comm): """ Helper method to distribute provided k if necessary and resolve whether or not the input is seeded. Returns ------- centroids : Replicated MPIArray Array of cluster centroids generated from provided set of observations. ...
9985936817a5ff097448b25eb0e1c45abc9ab480
72,385
def create_issue(self, request, form): """ Create a new issue. This view is only visible by a publisher. """ layout = Layout(self, request) if form.submitted(request): issue = Issue() form.update_model(issue) request.session.add(issue) request.message(_("Issue adde...
b3bf32095d35a5948a943aea664d1361713493b8
72,386
def average_over_dictionary(mydict): """ Average over dictionary values. """ ave = sum([x for x in mydict.values()])/len(mydict) return ave
584e8cb073c298b3790a96e2649dbacfd5716987
72,387
from datetime import datetime def login(): """ form = LoginForm() if request.method == 'POST': if form.validate_on_submit(): {} return render_template('auth/login.html', form=form) """ form = LoginForm() user = User.authenticate(form.email.data, form.password.data) ...
5948324df10c14cf6c16036bea847064688945c2
72,388
from typing import Optional from typing import Dict from typing import Union from pathlib import Path import logging import tqdm def prepare_mls( corpus_dir: Pathlike, output_dir: Optional[Pathlike] = None, opus: bool = True, num_jobs: int = 1, ) -> Dict[str, Dict[str, Dict[str, Union[RecordingSet, Su...
cd31b43b9e86e2516b4cc389d45daeff59470927
72,389
def _project_partial_joint_monotonicity(weights, lattice_sizes, joint_monotonicity, constraint_group): """Applies exact joint monotonicity projection to given constraint group. Algorithm details: For the joint monotonicity projection, we follow a similar approach to the ...
b166b23ddb8889fc3725d3a21331c62eef1b3135
72,390
def mae(forecasted, observed, average_axis=None): """ Calculate MAE :param forecasted: Forecast array :param observed: Observation array :param average_axis: The axis to average. `None` for averaging all axes. :return: MAE array """ stats = np.nanmean(np.abs(forecasted - observed), axis...
d9968dfb0c1e5e15e0b8a5534d77ce65a39217a5
72,391
def get_datanodes_list(): """Function for getting the datanodes identities from the configuration file. Parameters ---------- None Returns ------- conf['datanodes'] --> list, the list of the datanodes """ return conf['datanodes']
a0207676e4f42cde46333de60a6192535fb05c42
72,392
from datetime import datetime import dateutil def is_later(timestamp, period): """Return true if the current time > timestamp + period. Checks if the timestamp given is later than the current time + the period given in seconds. Attributes: timestamp -- integer, EPOCH. period -- integer, seco...
73d51bbb0294094107d7a2ee4068dcd753d01b4d
72,393
def parse_puzzle(puzzle, digits='123456789', nulls='0.'): """ Parses a string describing a Sudoku puzzle board into a dictionary with each cell mapped to its relevant coordinate, i.e. A1, A2, A3... """ # Serialise the input into a string, let the position define the grid location and .0 can be empty positions # ...
874bf52f708faf483c2b18118cad2c4fd7305c78
72,394
import os def schema_activity(arch): """ Check the activity view against its schema :type arch: etree._Element """ global _activity_validator if _activity_validator is None: with misc.file_open(os.path.join('mail', 'views', 'activity.rng')) as f: _activity_validator = etree.R...
2e976060db1946fe1146ed7657e5844140c93825
72,395
def visualize(history, regret_periods=None, time_labels=None, model_labels={}, style_algs={}, ax=[None, None, None], params=["lam"], subset_time=None, legend=True): """ Visualize online learning losses, weights, and parameters. Args: history (History): online learning History object regret...
954d64687b803dbac68fcb34ed03e404e5d1436f
72,396
def import_read_depth( gene, depth_of_coverage ): """ Import read depth data for target gene. Parameters ---------- gene : str Gene name. depth_of_coverage : str or pypgx.Archive Archive file or object with the semantic type CovFrame[DepthOfCoverage]. Returns ...
ac9437cf92a120728276adb6748ff65497318f2e
72,397
from typing import Any from typing import Callable from typing import Dict def authenticate(jwthenticator_server: str) -> Any: """ Wrapper function to verify user performing the request is authorized. The function extracts the JWT token from the header and verifies it against an jwthenticator serv...
3b6b38db3c1b0605839e89195dabb0b33ea997b2
72,398
def concat_complex(list_complex, width_in_bits, imreOrder=True): """ Concatenates the real and imaginary part into one integer. The specifed width counts for both the real and imaginary part. Real part is mapped on the LSB. Imaginary part is shifted to the MSB. """ # PD if imreOrder: ...
831275da0695a477f9f75da1e238f231ea8d39df
72,399