content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def convert_shape_to_tensor(shape, name=None): """Convert a static shape to a tensor.""" if isinstance(shape, (tuple, list)) and not shape: dtype = tf.dtypes.int32 else: dtype = None return tf.convert_to_tensor(shape, dtype=dtype, name=name)
abd5bfad082095c4f954fa6412b15f7dcb7a5fa8
61,660
from ezdxf.lldxf.validator import is_dxf_file, is_binary_dxf_file from ezdxf.tools.codepage import is_supported_encoding from ezdxf.lldxf.tagger import binary_tags_loader from typing import Union from pathlib import Path def readfile( filename: Union[str, "Path"], encoding: str = None, errors: str = "surr...
e398610ab0e8ceb1647399eb3db9bb07c358f6c0
61,661
def mock_subprocess_run(*args, **kwargs): """Mock calls to subprocess by routing them to the right mock""" command = args[0][1] if command == "show": return mock_pip_show(*args, **kwargs) elif command == "freeze": return mock_pip_freeze(*args, **kwargs)
da7b24cef209c1d4d56e55609d3c318d9895d470
61,662
def kick(ips, tau): """Kick operator. """ ips.set_acc(ips) if ips.include_pn_corrections: return kick_pn(ips, tau) return kick_n(ips, tau)
d47e826c0bb8f066fcae25e4ba871d38905f51b0
61,663
def replace_extension(filename, new_extension, add_to_end=False): """Replaces the extension in the filename with the new_extension.""" dot = filename.rfind(".") if dot < 0 or filename[dot + 1:] == new_extension or add_to_end: filename_base = filename else: filename_base = filename[:dot] ...
75b04c37dffb3dd92f3fe12295b18efb52dfa2ef
61,664
from bs4 import BeautifulSoup def wrap_with_tag(html: str, document_wrapper_class: str) -> str: """ Wraps a string of HTML with a div using a given wrapper class Args: html (str): The HTML to be wrapped document_wrapper_class(str): The class with which to wrap the HTML Returns: ...
075cf4ef818eb38f2b0a8a16c76fcc5cc11cdec9
61,665
def slave_entry(slave, programs, filesystems): """ Template tag {% slave_entry slave programms %} is used to display a single slave. Arguments --------- slave: Slave object programs: Array of programs Returns ------- A context which maps the slave object to slave an...
7449eec9d906bfe74245cbdec2a76fd7a2fc8157
61,666
from dateutil import tz import logging def initialize_free(begin_datetime,end_datetime): """ initialize the free time """ #Generates the free time array every date from user defined time ini_free = [] datetime_diff = end_datetime - begin_datetime #Initialize the free date and time free_end_datetime = arrow....
a85e8058375baafb734852be02234c13c3eef415
61,667
def get_scatter_xy(x, y): """ Generate scatterplot with auxiliaries by given columns `x` and `y`. The return is JSON in vega-lite schema. """ df = pd.DataFrame({"x": x, "y": y}) return get_scatter(df)
f782c5efb6a884b0be0816f49f50b31cb99eb0d4
61,668
def extractor(data, cell_type, conditions, cell_type_key="cell_type", condition_key="condition"): """ Returns a list of `data` files while filtering for a specific `cell_type`. # Parameters data: `~anndata.AnnData` Annotated data matrix cell_type: basestring s...
397ec9fa41ae6686e85754aac75c43fab19e817b
61,669
def get_depth_to_slice(image_instance, depth='auto'): """ Parameters ---------- image_instance: ImageInstance An image depth: str|tuple One of {'auto', 'time', 'zStack'} or a tuple containing {'time', 'zStack'} in any order. Which field to read for getting the depth. Returns ...
44d7854db735d3ba077dc61f23a9cf771560748f
61,670
def cfd(signal, fraction, delay=1, threshold=0): """Constant Fraction Discriminator :param np.array signal: the input from the digitizer :param float fraction: the fraction, from 0 to 1 :param float delay: the delay of the CFD :param float threshold: the threshold :return np.array edge_indices:...
25308beffeb29211bd7d6f2f85e16bc621206c1e
61,671
import json def cluster_list_by_ids(realm): """ this function returns the doc matching the cluster id """ cluster = Cluster(ES) account = Account(ES) account_email = json.loads(request.cookies.get('account'))["email"] cluster_ids = request.args.getlist('ids[]') if account.is_active_realm_mem...
9bed8e1b98453d357ea9a406f05e41b8144d527f
61,672
def dreadSkull(Z, p=None, Z0=None, ET=None): """ par_set['zoom'] = 0.4 Args: Z: a real or complex number p: a real of complex number Returns: Z: the result (complex) p[0] MATLAB: Z = (-Z)^(-exp(Z^x)^(exp(Z^x)^(-exp(Z^x)^(exp(Z^x)^(-exp(Z^x)^(exp(Z^x)^(-...
678e0b782a3fb55529ef4afcf35e1207facc5d14
61,673
def rescale_sound(snd_array, rescale): """Rescale the sound with the provided rescaling method (if supported). Args: snd_array (array): The array containing the sound data. rescale ({'standardize', 'normalize', None}): Determines type of rescaling to perform. 'standardize' will divide by the max valu...
ccb8f970d14da59b18eb74118260c33d48c1b7ba
61,674
import logging def count_total_molecules(filename: str) -> int: """Counts number of molecules in a file""" logging.info("Counting total molecules in file %s", filename) total = 0 ifs = oechem.oemolistream(filename) mol = oechem.OEMol() while oechem.OEReadMolecule(ifs, mol): total += 1 ...
ed376769e5468c8d8943e9ab370c69981df69363
61,675
from pathlib import Path def get_and_mark_bundle_cache_version(bundle_base: str, *, previously_bundled: bool) -> int: """ Check and return the bundle cache version. The marker filename is `.bundle_cache_version`. :param str bundle_base: The bundle directory ...
74ab1584b60ffb77dbb3709d01ea4df00a448ea4
61,676
def order_details(order_id): """Shows details of an order. arguments: order_id - id of the order Requires administrator privileges. """ order = Order.get_by_id(order_id) return render_template('order/order_details.html', order=order)
0b59f1ee859129343902c4ac8e326f56b823a680
61,677
def simulate_Poisson(intensity, region=(0, 1), seed=None): """ Provide points that are distributed by a uniform Poisson point process within the boundaries given by `region`. Parameters ---------- intensity : int, float The intensity (points per unit region measure) of the point process ...
5d93a40bf032037e362d857f0bad8e56fec9c78f
61,678
def mdown(context,text): """ Exported version of mdown. """ return _mdown(text)
24efeee8241304335cce0b93421b84e5f5f32dba
61,679
def sample_bernoulli(mean: np.ndarray) -> np.ndarray: """Samples from a bernoulli distribution with `mean`. Args: mean (np.ndarray): Mean of the bernoulli distribution. Returns: np.ndarray: Returns the drawn samples. Example: >>> # Sample from a bernoulli distribution with mea...
9615c38c02f3cd941183bdbdeb187df80bc4d1b3
61,680
import torch import test def construct_and_train(name='last_model', dataset='cifar10', model='vgg', resume=False, epochs=100, lr=0.1, batch_size=128, momentum=0.9, weight_decay=5e-4, comp=False, noscale=False, memory=False, mnorm=False, mback=False, norm_ratio=False): ...
8a75691fd8be9f4d1a35f7f307adb18079276e8c
61,681
import click def command(*args, **kwargs): """ A helper for decorating commands a-la `click.command`, but pulling the help string from `<function>.__doc__` by default. Also allows the use of custom arguments, which are stored on the command, as in "adoc_examples". """ disable_opts = kwarg...
929ac24a4c70e920fc0b238f6ccf98bed1750266
61,683
def haversine(lon1, lat1, lon2, lat2): """ Calculate the great circle distance between two points on the earth (specified in decimal degrees). Use of Euclidean distance in calculating geographical distance is rarely, if ever, recommended. """ # convert decimal degrees to radians lon1, la...
34dc735d350bba7a33c47cf69d009a2022ee6af2
61,684
import asyncio async def async_setup(hass, config): """Set up the Ais Files platform.""" # register services @asyncio.coroutine async def async_remove_file(call): if "path" not in call.data: return await _async_remove_file(hass, call.data["path"]) @asyncio.coroutine ...
69429f377e0c375b56527ded9d0d7623e4d8d3bf
61,685
def _background(cmd, sockname="dtach"): """ Run tasks in background Make sure dtach is installed. """ return run('dtach -n `mktemp -u /tmp/%s.XXXX` %s' % (sockname, cmd))
05d4c6fcc83d1aaa2552c8594450c80bd47c3acc
61,686
def isinrectbnd(x: int, y: int, xmin: int, ymin: int, xmax: int, ymax: int) -> bool: """Checks if the x and y values lie within the rectangular area defined by xmin, ymin and xmax, ymax Args: x, y: (x,y) coordinates to test xmin, ymin: min (x, ...
3f67de8669a258a554a8754786579517a07bc321
61,687
def get_column_combinations(columns, k=5): """ Returns all possible combinations using k columns. """ results = combinations(columns, k) return results
0bab7b7d9377526d4ac98b6464d4e65435edd7a1
61,688
import binascii def crc_srec(hexstr): """Calculate the CRC for given Motorola S-Record hexstring. """ crc = sum(bytearray(binascii.unhexlify(hexstr))) crc &= 0xff crc ^= 0xff return crc
835da45b3407e2fb32e8a715d465647ea9b86805
61,689
import torch def get_masks(slen, lengths, causal, padding_mask=None): """ Generate hidden states mask, and optionally an attention mask. """ alen = torch.arange(slen, dtype=torch.long, device=lengths.device) if padding_mask is not None: mask = padding_mask else: assert lengths....
828dea2c33420a9e038e739e979d3c8ab211dfef
61,690
def every_other(x, name=None): """Drops every other value from the tensor and returns a 1D tensor. This is useful if you are running multiple inputs through a model tower before splitting them and you want to line it up with some other data. Args: x: the target tensor. name: the name for this op, defa...
848d1050435ba014f627e372cdaea6b637667e35
61,691
def clock_in(client_id, employee_id, project_id=None): """ Clock in an employee. Args: client_id: The ID of the client the employee works for. employee_id: The ID of the employee who is clocking in. project_id: The ID of the project the employee i...
f895328c624cf94c1e1929ec21770e69546ba174
61,694
def draw_region(img): """Driver function for the user to draw a rectangle Parameters ---------- img : numpy.dnarray image to draw a rectangle on Returns ------- array coordinates of the rectangle the user has draw """ while True: # displaying the image ...
f40a13f33e438de146d52ea1a8f9e71dec55e79a
61,695
def tn_category_columns_builder(features): """Builds tensornet category feature columns.""" columns = {} for slot in set(features): columns[slot] = tn.feature_column.category_column(key=slot) return columns
74d166b31f4aa229d6340c852052a3bef4c202d7
61,696
def removepackages(pkgnames, forcedeletebundles=False, listfiles=False, rebuildpkgdb=False, noremovereceipts=False, noupdateapplepkgdb=False): """ Our main function, called by installer.py to remove items based on receipt info. """ if pkgnames == []: mun...
7165d5d26ffce126d529104a589790878ac21693
61,698
def _estimate_sigma_kth( X: np.ndarray, Y: np.ndarray, percent: float = 0.3 ) -> np.ndarray: """Private function to compute kth percent sigma.""" # compute distance matrix dists = pdist_squareform(X, Y) # find the kth distance sigma = kth_percent_distance(dists=dists, k=percent) return sigm...
6f3c93e521eb75af55a7d764caea7d99722356c3
61,699
def get_uploads_from_model(instance, attr): """Replaces attachment files from model to a given location, returns list of opened files of dict {file:'file',date:date,name:'filename'}""" ats = [] files = getattr(instance, attr) for fl in files.all(): ats.append({"file": File(fl.file)...
5de237811454c1c62634576dfdcd79bd51d13211
61,700
import pathlib def check(root: pathlib.Path = pathlib.Path(".")): """Checks that all toml files parse and that values match the template value types.""" possible_templates = list(root.glob("*.template.toml")) if len(possible_templates) > 1: raise ValueError("Only one template supported") i...
4ef6b98aa7306bf5db92d94b2deaa269f4ea7470
61,701
def remove_prefix(string: str, prefix: str): """ Removes a prefix from a string if present. Args: string (`str`): The string to remove the prefix from. prefix (`str`): The prefix to remove. Returns: The string without the prefix. """ return string[len(prefix) :] if stri...
598e1b9b863d342e757e54cf94035da63e3ace1f
61,702
import functools def input_handling(func): """Decorator that handles input naming for interpolations.""" @functools.wraps(func) def wrapper_input_handling(*args, **kwargs): # unpack args phi, theta, target_theta_levels, phi_dim, theta_dim, target_dim = args # pop kwargs used for...
9aa73218776d9ffa29d878036825c906fc428521
61,703
def get_params(opt_over, net, net_input, downsampler=None): """ Returns parameters that we want to optimize over. :param opt_over: comma separated list, e.g. "net,input" or "net" :param net: network :param net_input: torch.Tensor that stores input `z` :param downsampler: :return: """ ...
b8a3c26b5307c0ba584e3841a2d98f337c618bf8
61,705
def _top_k(distance_profile, k, exclusion_zone, option): """ Finds top k discords or motifs given an exclusion zone. The exclusion zone acts as a buffer between a found index on the left and right hand side. For example, if you set the exclusion zone to 4 and a motif or discord was found at index ...
922439992b77bf5852f37d8241c803fc04e05040
61,706
def coa_nonirrigated_cropland_fba_cleanup(fba, **kwargs): """ When using irrigated cropland, aggregate sectors to cropland and total ag land. Doing this because published values for irrigated harvested cropland do not include the water use for vegetables, woody crops, berries. :param fba: :return: ...
7e7495afef48fb7e772ecc92b76d22a82a6049c7
61,707
def write_tlv(data: dict): """Convert a dict to TLV8 bytes. NB: This simple implementation assumes all values are bytes! """ tlv = b"" for key, value in data.items(): tag = bytes([int(key)]) length = len(value) pos = 0 # A tag with length > 255 is added multiple tim...
e0da4f6374507e4f5b83b48826b7d7f31fd47dd5
61,708
import torch def stensor(data, stable_dims=(), dtype=None, device=None, requires_grad=False, pin_memory=False): """ Constructs a STensor from input data and a partition index placement Args: data: Initial data for the stensor. Can be a list, tuple, NumPy ``ndarray``, scal...
0c3307a94f341fa698e5b620b711089d5c9c3f4d
61,709
def mulmat(X,Y): """ Multiplies a matrix X to a matrix Y NOTE: Does no checks any matrix sizes. Parameters ---------- X(list) : The X list as matrix Y(list) : The Y list as matrix Returns ------- list : Result multiplied matrix X*Y """ result = matrix(len(X), len(Y[0])...
887e7c7c7563abb636affb9c5634fb7f9a7fe0fe
61,710
import math def softplus(x): """Softplus activation function Args: x (float): input value Returns: float: output value """ try: return math.log(1 + math.exp(x)) except OverflowError: return 0 if x < 0 else 1
637f5bb5b504c2215e7213bbce06e937f13ea080
61,711
def _find_corners(cluster, cluster_type, n_fast=12, threshold_fast=0.1, method='suppression'): """ find 2 corners in the cluster Method: 'farthest' from the center of mass 'largest' between all the corners """ # Find the corners with the corner_fast method # Be sure there are no holes i...
68f87879c0fe923cb7ca196b202bc97de65924d9
61,712
def is_admin(identity=None): """Returns True if |identity| (or current identity if None) is an admin. Admins are identities belonging to 'administrators' group (see model.ADMIN_GROUP). They have no relation to GAE notion of 'admin'. See 'is_superuser' for asserting GAE-level admin access. """ return is_gr...
0939eeea105c70ed5632e0e9b69243b4c3df4f76
61,713
def create_parser(): """ :return: """ parser = ArgumentParser(add_help=True, parents=[get_parent_parser()]) parser.add_argument( "--scenario_id", help="The scenario ID. Required if " "no --scenario is specified.", ) parser.add_argument( "--scenario", help="Th...
9545faf73a4416bd4ac32d5e94de9c6b41ea2280
61,714
from typing import Optional from typing import Any def nested_get(dct: dict, *keys: str) -> Optional[Any]: """Multi-level get helper function.""" for key in keys: dct = dct.get(key, {}) return dct if dct else None
cd881389157d67365793240e1e2e0b39f4bc1726
61,715
def data_preprocess(filename, mode='Train', training_data=None): """ :param filename: str, the filename to be read into pandas :param mode: str, indicating the mode we are using (either Train or Test) :param training_data: DataFrame, a 2D data structure that looks like an excel worksheet :return: Tuple(data, label...
115efaa45ff4abaf0d6a6b59eb7fa6fcdf28db82
61,716
from typing import Optional from typing import Any def scatter( hist: BootstrapHistogram, ax: Optional[MplAxes] = None, **kwargs: Any ) -> Any: # """ Scatter plot of the bootstrap samples. The scatter-point x-coordinate within a bin drawn from a uniform random distribution. Parameters -----...
a06ec1ef4b68108a85e31e41b9b1e139d515662d
61,717
def get_ml_eng(): """ Returns a started matlab engine. The engine is started and set to the correct directory for Monocap. The startup code for Monocap is then run to ensure all necessary files are added to the path. Returns ------- eng : engine.matlabengine.MatlabEngine ...
86856231111efef6d9fccc3d9fed6cb526d490ca
61,718
def train_test_data(dataframe, target_variable_name, train_size=.8, random_state=42): """ Returns dataframes of training and test sets Use this function if implementing cross validation with sklearn :param dataframe: pandas.DataFrame :param target_variable_name: str :param train_size: float from...
373494f59c1a68d8504fd13f8d028bdd478f37a2
61,719
def only_moto(request): """Return True if only moto ports are to be used for mock services.""" return request.config.option.only_moto
1ab211925a411d4999a22e77d819da88b4477ed6
61,721
def get_nframes(video_name, last_frame, nframes = 10): """ Extracts nframes from video to create training batches. :param video_name: absolute path to video :param last_frame: frame of interest :param nframes: number of frames to take :return: array of size nframes x width x height x RGB, with ...
adb00d890a2c2c5e2d4fabe0e2d6dc25e18766ab
61,722
def validate_permissions( hass, minimum_permissions, token_path=DEFAULT_CACHE_PATH, filename=TOKEN_FILENAME ): """Validate the permissions.""" permissions = get_permissions(hass, token_path, filename) if not permissions: return False for minimum_perm in minimum_permissions: permissi...
ccbf14b17a78410f775ecd38d2a762bab5179271
61,724
def find(sub_str, target_str): """[summary] 字符串查找 Arguments: sub_str {str} -- substring target_str {str} -- target string Returns: bool -- if substring is found in target string """ return sub_str in target_str # in operator用的是Boyer–Moore算法,最坏情况O(mn), 最好情况O(n/m) ...
d26e4ad79eaf913d81126d7647036b857de5ed6d
61,725
def _source_step(func): """ Transform a iterator factory to a pipeline source :Warning: The step ignores its in_queue and only writes to the out_queue. :Parameters: `func` : callable iterator :Return: New step class :Rtype: ``type`` """ class _SourceStep(AbstractStep): ...
dc8a6e53add8c24075a96a2a3e1b188f51903ae5
61,726
import math def num_to_thaiword(number: int) -> str: """ This function convert number to Thai text :param int number: an integer number to be converted to Thai text :return: text representing the number in Thai :rtype: str :Example: >>> from pythainlp.util import num_to_thaiword ...
77e7021cfc36886b76af9c5ae93c0d4c40dfa005
61,727
def check_faces_in_caption(photo): """Checks if all faces are mentioned in the caption.""" comment = photo.comment if photo.getfaces() and not comment: return False for face in photo.getfaces(): parts = face.split(" ") # Look for the full name or just the first name. if (...
eed03439df84a1ddd4cb7bcbb269af7c60adfcb5
61,729
def create_light_sensor(): """ Create a new light sensor. :return: New sensor object. """ temp = build.Light() temp.current_value = float(input("\n" + Lang["< Insert current value >"] + "\n\n>>")) clear() temp.sampling_freq = float(input("\n" + Lang["< Insert sampling frequency >"] + "\n...
52a2f9316401c62215e55f8f9249c84ae9bfde9a
61,731
def prcs_blast_rslts_xml(filepath, args): """ Processes the blast results stored in an xml file and then scrapes online databases for ec numbers. :param filepath: The filepath of the blast results xml file. :param args: A python dictionary of command line arguments :return: The results of ...
5fa2365a99f50bdce6a5f5a5f3a6cfed4e5b8dc6
61,732
from typing import Any from typing import IO from typing import List from re import A import abc def wait(*l: Fiber[Any, Any, Any]) -> IO[R, E, List[Result[R, A]]]: """ Wait until these Fibers finish. Return the list of Result in the same order. :param l: :return: """ if len(l) == 1 and is...
205130d88643f29b3bd7f6d8b6609fd18700aa4d
61,736
def mp_move_files(multiprocessing_pool_vars): """ Moves the file as given with multiprocessing_pool_vars (iterable) multiprocessing_pool_vars: [filename, from_dir, to_dir] :param multiprocessing_pool_vars: :returns: list """ filename = multiprocessing_pool_vars[0] from_dir = multiprocessing_...
d8bf3fbd1cd77aff75a259ee311ab1a29ca6ab7b
61,737
import json def add ( data ): """Process JSON string to add to data set""" if util_json_bad(data): raise BadJsonError(data) return t = json.loads(data, strict=False) name = t["dataset"] keys = t["keys"] values = t["values"] if util_key_bad(keys): raise BadKey...
9182f0cfa77231b02d4f7f70e68c8989c73d7fed
61,738
def LfromS(seq): """ Compute Schroder function value L from a given sequence. This performs the calculation by plodding through the algorithm given in the paper. Humans can easily recognize the relation between elements of S and length of runs of 0s or 1s in the binary representation of L. Knowing that, the...
6adf8c0b6f8e12d7e6a79efcb38c628ef0b29031
61,739
import numpy def negative_binary_f_two(func, c, x, y): """Test negative values as input to func as second argument.""" x = x + (-4) z = func(c, x) z = numpy.clip(z, 0, 63).astype(numpy.int32) + y return z
aec636cbf7c8733ce5584381d8be5bd25cf7d167
61,740
def prop_test(data, prop_0, alternative = 'equal', alpha = 0.05): """ This function is used to implement the prop_test Input params: data (dataframe of boolean): dataframe restricted to the specified column to evaluate prop_0 (float) : values of the alternative testing ...
5b0094d6cf53e4709fe379196a6c8a80670d4d45
61,743
from re import T def task(): """ RESTful CRUD controller """ tablename = "project_task" table = s3db[tablename] # Custom Method to add Comments s3mgr.model.set_method(module, resourcename, method="discuss", action=discuss) statuses = resp...
b6c4e613a042cebc029023f309e0b55df5b45525
61,744
def interpret_where_clause( interpreter, speaker, where_d, memory_type="ReferenceObject", ignore_self=False ): """ where_d is a sentence (nested dict/list) of the recursive form COMPARATOR, TRIPLE, or {CONJUNCTION, [where_clauses]} where each CONJUCTION is either "AND", "OR", or "NOT" """ ...
3f8e24ffe3cb44fe9c96d7535c1b9ee381979210
61,746
def generate_point(): """ X: [tRexX,tRexY,speed,obsX,obsY] Y: [passReward,jumpReward] """ X = np.array([ np.random.normal(23,1), # tRex X np.random.uniform(0,90), # tRex Y np.random.uniform(6,12), # speed np.random.uniform(-50,700), # obs1 X np.rando...
13a8482247e0b1f58f8fb7dce317c2ade9e9f04b
61,747
import torch def nms (boxes, nms_thresh): """ None Max Separetion """ if len (boxes) == 0: return boxes det_confs = torch.zeros (len (boxes)) for i in range (len (boxes)): det_confs [i] = 1 - boxes [i][4] _, sortIds = torch.sort (det_confs) out_boxes = [] for i in range (...
6d2d152a87f5f595a541ca03d870e8a89de671db
61,748
def _compute_coords(shape, xyz_resolution=1, origin='center'): """Returns the real_coordinates of an image with the given shape at the given resolution as a single numpy array of shape (*shape, len(shape)).""" axes = _compute_axes(shape, xyz_resolution, origin) meshes = np.meshgrid(*axes, indexing='i...
7d460c7ed6a5c292eb732be4e9d2a58c2298d16b
61,749
def read_db_config(filename=CONFIG_FILE, section=DBTYPE): """ Read database configuration file and return a dictionary object :param filename: name of the configuration file :param section: section of database configuration :return: a dictionary of configuration parameters """ # create parser an...
e6a2837f2d11389e6f2680041f73de0fa17dc5af
61,750
import requests def send_message_to_telegram(msg='hi'): """in: str, out: str""" METHOD_NAME = 'sendMessage' for my_id in TELEGRAM_ID_LIST: data_to_send = { 'chat_id': my_id, 'text': msg } header = { 'Content-Type': 'application/x-www-form-urlen...
5818d863b5abd8bc3640c135528320953c74ea3e
61,751
import json def get_track_info(item_id): """ A function that gets track name information from item id :param item_id: the item id to find :return: the String type name of track """ f = open(str(dir_path) + r"/metadata/json/track.json", encoding="utf-8") data = json.load(f) try: ...
1a444ae09dc3a9966039f9a226a4d9630e7c207d
61,753
from typing import Dict from typing import Any def find_class(klass, dictionary: Dict[str, Any]): """ Given a dictionary, find the best-fit class among the subclasses of the supplied class. """ dictionary_keys = key_strings_from_dict(dictionary) classes = all_visible_subclasses(klass) clas...
9c6736467aec269f83033cc3da2e457e1ff094a1
61,754
def get_text_channel( guild: discord.Guild, *text_channel_names: str ) -> discord.TextChannel: """ Get the first text_channel found in @names or raise an Exception. """ for name in text_channel_names: text_channel = discord.utils.get(guild.text_channels, name=name) if text_channel: ...
b3ae871d341608a10c6c70fb3da907e4fb56797a
61,755
def use_snippets(document, position): """ Determine if it's necessary to return snippets in code completions. This returns `False` if a completion is being requested on an import statement, `True` otherwise. """ line = position['line'] lines = document.source.split('\n', line) act_lines...
1cf60c6979e374a478d69802b9c89c68de635033
61,757
import random def contest(other): """contests human ability""" return random.randint(1, 20) > round(other.advantage / 5)
a87cc2ffc7d01f493d99b3808735f7954847caaa
61,758
def rs(hass): """Return CommandCover instance.""" return cmd_rs.CommandCover( hass, "foo", "command_open", "command_close", "command_stop", "command_state", None, )
04e7e846a019dd4b47fb93ac12b857013713043a
61,759
def _preprocess_arguments(domain, funcs, config): """ Preprocess domain arguments and configuration file. """ # Preprocess config argument converted_cp_to_euclidean = False if isinstance(config, str): config = load_config_file(config) if domain is None: domain = config.domain # The function if con...
a2193d83d2301e240ac35c6276e9cffc77600913
61,760
def load_simulated_gaussian(partition='complete', **kwargs): """ Synthetic data with a Gaussian (non-linear) log-risk function. For more information, see [#katzman1]_ as well as the accompanying README. Parameters ---------- partition: string Partition of the data to load. ...
1fdb49ee518a94b3d1f0dbb0ad9aff740a865439
61,761
def encode_target(target): """Apply one-hot-encoding to encode target values. Author: Jernej Vivod (vivod.jernej@gmail.com) Args: target (numpy.ndarray): target variable values. Returns: numpy.ndarray: one-hot-encoded target variable values. """ # Encode data using one-hot-e...
4e07eec0f8210bd686ea390f04c1e276abfad7fd
61,764
def build_auth_args(request): """ 组装认证信息 """ # auth_args 用于ESB身份校验 auth_args = {} if request is None: return auth_args ignore_fields = ["rtx"] for key, value in get_oath_cookies_params().items(): if value in request.COOKIES and key not in ignore_fields: auth_...
b15ccdd81d2d23ffa196d074ac391344b22e9561
61,766
def check_mean_greater(alpha, N, mean, n): """ H0: m <= m_0 H1: m > m_0, where m_0 = N.mean Returns True if H0 is rejected in favor of H1, and False if cannot reject H0. :param object N: distribution. """ assert(0 < alpha < 1.0) # significance level assert(n > 0) # sample size ...
9af7f75716b82067230c88a76b40b731e19449cd
61,768
def list_even(obj): """ Return a list of all even integers in obj, or sublists of obj, if obj is a list. If obj is an even integer, return a list containing obj. Otherwise return en empty list. @param int|list obj: possibly nested list of ints, or int @rtype: list[int] >>> list_even(...
8b94f8983f9c8d19163de875089697f6cdab8114
61,769
def get_output_data_file(given_filename, run_directory, application_name): """ Get the csv file where results will be written. This method checks if the user defined a custom filename. If not, it returns the default. Important: if the file exists, it will be overwritten. :param given_filename: the f...
bab5f5410d138aebb8a065201665b35edb1bcbb0
61,770
def encrypt(backup: str, password: str) -> str: """Encrypts a database backup Pararameters:\n backup (str): name of the database backup password (str): encrypting password Returns:\n str: cryptogram of the encryption None: an error ocurred """ ...
a3b0db8db360a2bb99af7aa4cdc727f4293be7e5
61,771
def operator_as_argument(statement): """This looks at various possible fixes when the bad token is an operator. The following cases are considered: 1. operator instead of comma 2. operator instead of equal sign """ if not statement.bad_token.is_operator() or statement.prev_token == "def": ...
95ec70aff8c27f626b258ad0d21d9fecfa6347d4
61,772
async def api_req_add(req: Request, data: Body, authorized: bool = Depends(verify_token)): """Добавить данные в бд""" if authorized: try: return {"status_code": 200, "result": DB._add_data(authorized, data)} except: raise HTTPException(status_code=500, detail="Ошибка серв...
794a8c17889ef55d0e4ba10e080e1e2911f50acc
61,773
async def infer_Jinv(self, engine, x): """Infer the return type of primitive `Jinv`.""" return await compute_jinv_type(x)
498fa68608aa5e0655c84bdf305af75e7565b531
61,774
from typing import Sequence def count_increases_pairwise(readings: Sequence[int]) -> int: """Count the number of times a reading increases.""" counter = 0 for previous_reading, current_reading in iterate_window(readings, 2): if current_reading > previous_reading: counter += 1 ret...
1ec02d072d5c654f684403cab10058dc6f42bc53
61,776
def load_repository_url() -> str: """Return repository URL.""" return load_repository().remote().url.split(".git")[0]
38c62540dc8e765f2aaec59764a29beacc11eaaa
61,777
def calibrate_box(bbox, reg): """校准box 参数: bbox:pnet生成的box reg:rnet生成的box偏移值 返回值: 调整后的box是针对原图的绝对坐标 """ bbox_c = bbox.copy() w = bbox[:, 2] - bbox[:, 0] + 1 w = np.expand_dims(w, 1) h = bbox[:, 3] - bbox[:, 1] + 1 h = np.expand_dims(h, 1) reg_m = np.hstack([w,...
9829a856cd1c0bbf4becd9436e423384e40b8c35
61,778
import random def get_random_testcases(input_directory, max_testcases): """Returns list of |max_testcases| testcases.""" testcases_list = get_testcases(input_directory) return random.SystemRandom().sample(testcases_list, max_testcases)
3f1736bbea946372f20b6b26cdb8a2ab1ca39f95
61,779
def ppo_sharpe_port(cov=None, pre=None, as_dense=True): """ Max Sharpe ratio portfolio using cov-implied returns :param cov: Covariance matrix :param pre: Precision matrix :param as_dense: If false, will return weights in dict formet :return: np.array of weights """ return pp...
2712ba9a61a3005963c60352f00455cb00200c56
61,780
def constraints_from_table(table, power_spectrum, boxlen): """Load a table containing constraints and convert it into a list of Constraint objects. Also needs the power spectrum of the CRF that you're going to build, because it needs to determine the spectral parameters. Finally, we need the boxsize (i...
de9930b7e108717a944637f0b8e2ef6b627c3d4a
61,782