content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def wilson_primality_test(n: int) -> bool: """ https://en.wikipedia.org/wiki/Wilson%27s_theorem >>> assert all(wilson_primality_test(i) for i in [2, 3, 5, 7, 11]) >>> assert not all(wilson_primality_test(i) for i in [4, 6, 8, 9, 10]) """ return ((factorial_lru(n - 1) + 1) % n) == 0
809415a5bd5a4ee4c19cc41a4616e91e17574a09
18,100
def project_from_id(request): """ Given a request returns a project instance or throws APIUnauthorized. """ try: pm = ProjectMember.objects.get( user=request.user, project=request.GET['project_id'], ) except ProjectMember.DoesNotExist: raise APIUna...
d23daddfacf736b835bdd10594d99dd4d4e5a0fe
18,101
from typing import Union import logging from typing import Optional from typing import Tuple import os def addRotatingFileHandler(logger: Union[logging.Logger, str], fName: Optional[str] = None, dirPath: Optional[str] = None, fmt: Option...
3d8acc71a4be116cbf075ecc20d5221e48b127fd
18,102
def make_beampipe_from_end(pipe_aperture, pipe_length, loc=(0, 0, 0), rotation_angles=(0, 0, 0)): """Takes an aperture and creates a pipe. The centre of the face of aperture1 will be at loc and rotations will happen about that point. Assumes the aperture is initially centred on (0,0,0) Args: ...
a3b85995165ac2b11d9d6d0014b68356996e97b9
18,103
import urllib def encode_string(value): """Replace and encode all special characters in the passed string. Single quotation marks need to be doubled. Therefore, if the string contains a single quotation mark, it is going to be replaced by a pair of such quotation marks. """ value = value.replace(...
a6e30e834eb9b4d1d5882b7b24eec0da28ed5f4c
18,104
async def make_json_photo(): """Photo from web camera in base64. """ img, _ = get_png_photo() if img: result = {"image": png_img_to_base64(img)} else: result = {"error": "Camera not available"} return result
d498d8d47a995125f0480c069b1459156875f2b7
18,105
def near_field_point_matching(source, position, size, k, lmax, sampling): """Decompose a source into VSHs using the point matching method in the near field Returns p_src[2,rmax] Arguments: source source object position position around which to decompose ...
32772b6cc15ea4f96a2356969118e3e339bb9382
18,106
from typing import Any from typing import Union from typing import List from typing import Dict from typing import Type def Option( default: Any = MISSING, *, name: str = MISSING, description: str = MISSING, required: bool = MISSING, choices: Union[List[Union[str, int, float]], Dict[str, Union...
a344edbcdbc4211adebd072f0daaf20a6abc657e
18,107
def inverse(f, a, b, num_iters=64): """ For a function f that is monotonically increasing on the interval (a, b), returns the function f^{-1} """ if a >= b: raise ValueError(f"Invalid interval ({a}, {b})") def g(y): if y > f(b) or y < f(a): raise ValueError(f"Invalid...
5d0b3c990d20d486f70bff2a5569920134d71ea1
18,108
def gmof(x, sigma): """ Geman-McClure error function """ x_squared = x ** 2 sigma_squared = sigma ** 2 return (sigma_squared * x_squared) / (sigma_squared + x_squared)
63448c03e826874df1c6c10f053e1b1e917b6a98
18,109
import tqdm def download_data(vars): """ function to download data from the ACS website :param: geo_level (geoLevel object): which geophical granularity to obtain for the data vars (string): a file name that holds 3-tuples of the variables, (in the format returned by censusdat...
a333eb2565736a6509cc3760de35fae8bc020c5e
18,110
def oddify(n): """Ensure number is odd by incrementing if even """ return n if n % 2 else n + 1
dee98063cb904cf462792d15129bd90a4b50bd28
18,111
from typing import List import re def method_matching(pattern: str) -> List[str]: """Find all methods matching the given regular expression.""" _assert_loaded() regex = re.compile(pattern) return sorted(filter(lambda name: re.search(regex, name), __index.keys()))
b4a4b1effcd2359e88022b28254ed247724df184
18,112
def update_binwise_positions(cnarr, segments=None, variants=None): """Convert start/end positions from genomic to bin-wise coordinates. Instead of chromosomal basepairs, the positions indicate enumerated bins. Revise the start and end values for all GenomicArray instances at once, where the `cnarr` bi...
f42780517cde35d2297620dcaf046ea0a111a7b9
18,113
async def respond_wrong_author( ctx: InteractionContext, author_must_be: Member | SnakeBotUser, hidden: bool = True ) -> bool: """Respond to the given context""" if not ctx.responded: await ctx.send( ephemeral=hidden, embeds=embed_message( "Error", ...
a39e3672dd639e0183beb30c6ebfec324dfc96de
18,114
def ParseFloatingIPTable(output): """Returns a list of dicts with floating IPs.""" keys = ('id', 'ip', 'instance_id', 'fixed_ip', 'pool',) floating_ip_list = ParseNovaTable(output, FIVE_COLUMNS_PATTERN, keys) for floating_ip in floating_ip_list: if floating_ip['instance_id'] == '-': floating_ip['insta...
691d9c0525cee5f4b6b9c56c4e21728c24e46f48
18,115
import os def build_entity_bucket(config, server): """プロジェクト構成ファイルからエンティティバケットを構築するファクトリ関数 Args: config (str): ファイル名 server (str): サーバ名 Returns: (Server, EntityBucket): サーバとエンティティバケットを返す """ server_, entity_bucket = Parser().parse(config, server, context=os.environ) r...
f3b3ac3b32760922c9e61e162db5688e06132836
18,116
def test_logging_to_progress_bar_with_reserved_key(tmpdir): """ Test that logging a metric with a reserved name to the progress bar raises a warning. """ class TestModel(BoringModel): def training_step(self, *args, **kwargs): output = super().training_step(*args, **kwargs) self....
827719942bed424def0753af9c4b6757b5f6cdf0
18,117
def cdf_inverse(m, alpha, capacity, f, subint): """ This function computes the inverse value of a specific probability for a given distribution. Args: m (mesh): The initial mesh. alpha (float): The probability for which the inverse value is computed. capacity (float): The capaci...
cb0609a1f5049a910aaec63b9d6ed311a1fdc263
18,118
def concatenation(clean_list): """ Concatenation example. Takes the processed list for your emails and concatenates any elements that are currently separate that you may wish to have as one element, such as dates. E.g. ['19', 'Feb', '2018'] becomes ['19 Feb 2018] Works best if the lists are simi...
59b727f21e663f2836f6fe939f4979e9f7484f62
18,119
def add_pattern_bd(x, distance=2, pixel_value=1): """ Augments a matrix by setting a checkboard-like pattern of values some `distance` away from the bottom-right edge to 1. Works for single images or a batch of images. :param x: N X W X H matrix or W X H matrix. will apply to last 2 :type x: `np.nda...
1f545a472d6d25f23922c133fb0ef0d11307cca1
18,120
import sys import hashlib def calc_md5_sign(secret, parameters): """ 根据app_secret和参数串计算md5 sign,参数支持dict(建议)和str :param secret: str :param parameters: :return: """ if hasattr(parameters, "items"): keys = list(parameters.keys()) keys.sort() parameters_str = "%s%s%s"...
f13cd469a86942c011f3d419a4a2cf89c79cf2df
18,121
def tokenize(string): """ Scans the entire message to find all Content-Types and boundaries. """ tokens = deque() for m in _RE_TOKENIZER.finditer(string): if m.group(_CTYPE): name, token = parsing.parse_header(m.group(_CTYPE)) elif m.group(_BOUNDARY): token = ...
0121f9242a5af4611edc2fd28b8af65c5b09078d
18,122
def query(obj,desc=None): """create a response to 'describe' cmd from k8s pod desc and optional custom properties desc """ # this is a simplified version compared to what the k8s servo has (single container only); if we change it to multiple containers, they will be the app's components (here the app is a singl...
bce425c503c3c779c6f397020061ccee3150b562
18,123
def binary_cross_entropy(preds, targets, name=None): """Computes binary cross entropy given `preds`. For brevity, let `x = `, `z = targets`. The logistic loss is loss(x, z) = - sum_i (x[i] * log(z[i]) + (1 - x[i]) * log(1 - z[i])) Args: preds: A `Tensor` of type `float32` or `float64`. ...
f16441fe921b550986604c2c7513d9737fc230b3
18,124
from django.core.files.uploadedfile import InMemoryUploadedFile, TemporaryUploadedFile import os import json import requests import base64 import time def upload_and_rec_beauty(request): """ upload and recognize image :param request: :return: """ image_dir = 'cv/static/FaceUpload' if not ...
0088f8bc5ddaba461ea74a4d156c577b231cab96
18,125
def weld_standard_deviation(array, weld_type): """Returns the *sample* standard deviation of the array. Parameters ---------- array : numpy.ndarray or WeldObject Input array. weld_type : WeldType Type of each element in the input array. Returns ------- WeldObject ...
763b96ef9efa36f7911e50b313bbc29489a5d5bd
18,126
def dev_to_abs_pos(dev_pos): """ When device position is 30000000, absolute position from home is 25mm factor = 30000000/25 """ global CONVFACTOR abs_pos = dev_pos*(1/CONVFACTOR) return abs_pos
74800f07cdb92b7fdf2ec84dfc606195fceef86b
18,127
import torch def model_predict(model, test_loader, device): """ Predict data in dataloader using model """ # Set model to eval mode model.eval() # Predict without computing gradients with torch.no_grad(): y_preds = [] y_true = [] for inputs, labels in test_loader: ...
0b43a28046c1de85711f7db1b3e64dfd95f11905
18,128
def calc_precision_recall(frame_results): """Calculates precision and recall from the set of frames by summing the true positives, false positives, and false negatives for each frame. Args: frame_results (dict): dictionary formatted like: { 'frame1': {'true_pos': int, '...
7389050a73a1e368222941090991883f6c6a89b7
18,129
import logging def patch_fixture( scope="function", services=None, autouse=False, docker_client=None, region_name=constants.DEFAULT_AWS_REGION, kinesis_error_probability=0.0, dynamodb_error_probability=0.0, container_log_level=logging.DEBUG, localstack_verison="latest", auto_re...
304c3fbf99d943cb44e5b2967c984612fa5ca6dc
18,130
def euler_to_quat(e, order='zyx'): """ Converts from an euler representation to a quaternion representation :param e: euler tensor :param order: order of euler rotations :return: quaternion tensor """ axis = { 'x': np.asarray([1, 0, 0], dtype=np.float32), 'y': np.asarray([0, ...
ff5a848433d3cb9b878222b21fc79f06e42ea03f
18,131
def setnumber(update,context): """ Bot '/setnumber' command: starter of the conversation to set the emergency number """ update.message.reply_text('Please insert the number of a person you trust. It can be your life saver!') return EMERGENCY
5faa4d9a9719d0b1f113f5912de728d24aee2814
18,132
def mean_ale(covmats, tol=10e-7, maxiter=50, sample_weight=None): """Return the mean covariance matrix according using the AJD-based log-Euclidean Mean (ALE). See [1]. :param covmats: Covariance matrices set, (n_trials, n_channels, n_channels) :param tol: the tolerance to stop the gradient descent ...
0df7add370bda62e596abead471f3d393691f62c
18,133
def get_affiliate_code_from_qstring(request): """ Gets the affiliate code from the querystring if one exists Args: request (django.http.request.HttpRequest): A request Returns: Optional[str]: The affiliate code (or None) """ if request.method != "GET": return None a...
173b8f7ed3d202e0427d45609fcb8e9332cde15b
18,134
def get_gifti_labels(gifti): """Returns labels from gifti object (*.label.gii) Args: gifti (gifti image): Nibabel Gifti image Returns: labels (list): labels from gifti object """ # labels = img.labeltable.get_labels_as_dict().values() label_dict = gifti...
3a4915ed50132a022e29cfed4e90905d05209484
18,135
def get_temporal_info(data): """Generates the temporal information related power consumption :param data: a list of temporal information :type data: list(DatetimeIndex) :return: Temporal contextual information of the energy data :rtype: np.array """ out_info =[] for d in ...
308640fec7545409bfad0ec55cd1cc8c941434d2
18,136
def html_url(url: str, name: str = None, theme: str = "") -> str: """Create a HTML string for the URL and return it. :param url: URL to set :param name: Name of the URL, if None, use same as URL. :param theme: "dark" or other theme. :return: String with the correct formatting for URL """ i...
74a0d3eabce4f0a53e699567e25c9d09924e3150
18,137
def get_logger_messages(loggers=[], after=0): """ Returns messages for the specified loggers. If given, limits the messages to those that occured after the given timestamp""" if not isinstance(loggers, list): loggers = [loggers] return logger.get_logs(loggers, after)
d2c8ef6dc8f1ec0f4a5f7a1263b829f20e0dfa8b
18,138
def __dir__(): """IPython tab completion seems to respect this.""" return __all__
d1b0fe35370412a6c0ca5d323417e4e3d1b3b603
18,139
def run_iterations(histogram_for_random_words, histogram_for_text, iterations): """Helper function for test_stochastic_sample (below). Store the results of running the stochastic_sample function for 10,000 iterations in a histogram. Param: histogram_for_ran...
59bd4cefd03403eee241479df19f011915419f14
18,140
def GetFootSensors(): """Get the foot sensor values""" # Get The Left Foot Force Sensor Values LFsrFL = memoryProxy.getData("Device/SubDeviceList/LFoot/FSR/FrontLeft/Sensor/Value") LFsrFR = memoryProxy.getData("Device/SubDeviceList/LFoot/FSR/FrontRight/Sensor/Value") LFsrBL = memoryProxy.getData("De...
555c5cb1f6e68571848410096144a3184d22e28a
18,141
def norm(x, y): """ Calculate the Euclidean Distance :param x: :param y: :return: """ return tf.sqrt(tf.reduce_sum((x - y) ** 2))
67766f9e3c3a510a87eff6bdea7ddf9ec2504af3
18,142
def expand_key(keylist, value): """ Recursive method for converting into a nested dict Splits keys containing '.', and converts into a nested dict """ if len(keylist) == 0: return expand_value(value) elif len(keylist) == 1: key = '.'.join(keylist) base = dict() ...
ac8b4bac9b686396d5d117149fb45b8bde2ac238
18,143
def _linear_sum_assignment(a, b): """ Given 1D arrays a and b, return the indices which specify the permutation of b for which the element-wise distance between the two arrays is minimized. Args: a (array_like): 1D array. b (array_like): 1D array. Returns: array_like: Indi...
eeecff894e8bf29de66fa2560b8fdadbf3970d6d
18,144
def get_ingredients_for_slice_at_pos(pos, frame, pizza, constraints): """ Get the slice of pizza with its ingredients :param pos: :param frame: :param pizza: :param constraints: :return: """ def _get_ingredients_for_slice_at_pos(_pos, _frame, _pizza, _max_rows, _max_cols): if...
db1083695d6f9503b3005e57db47c15ac761a31d
18,145
def merge_data_includes(tweets_data, tweets_include): """ Merges tweet object with other objects, i.e. media, places, users etc """ df_tweets_tmp = pd.DataFrame(tweets_data) # Add key-values of a nested dictionary in df_tweets_tmp as new columns df_tweets = flat_dict(df_tweets_tmp) for ...
db8e8560bdb80bd4a57d4f0d69031e944511633f
18,146
def stringify(context, mapping, thing): """Turn values into bytes by converting into text and concatenating them""" if isinstance(thing, bytes): return thing # retain localstr to be round-tripped return b''.join(flatten(context, mapping, thing))
c4c4503160cab3ff6a78e2fb724fd283011ce0e7
18,147
import logging import json def extract_from_json(json_str, verbose=False): """A helper function to extract data from KPTimes dataset in json format :param: json_str: the json string :param: verbose: bool, if logging the process of data processing :returns: the articles and keywords for each article ...
b05120eee45a887cee5eac68febffe96fcf8d305
18,148
def split_data(data, split_ratio, data_type=DATA_TYPE_1): """ split data by type """ data_type_1 = data[data['LABEL'] == data_type] data_type_2 = data[data['LABEL'] != data_type] train_set = data.sample(frac=split_ratio, replace=False) test_set = data[~data.index.isin(train_set.index)] ...
2653ea65bbc6fa2c7c0db9ab29890f57d5254d3f
18,149
from typing import Set import os def _get_mtimes(arg: str) -> Set[float]: """ Get the modification times of any converted notebooks. Parameters ---------- arg Notebook to run 3rd party tool on. Returns ------- Set Modification times of any converted notebooks. """...
c19e7ba43f6fb1d776f10e39f9fa46d05c947c72
18,150
def sparse_amplitude_prox(a_model, indices_target, counts_target, frame_dimensions, eps=0.5, lam=6e-1): """ Smooth truncated amplitude loss from Chang et al., Overlapping Domain Decomposition Methods for Ptychographic Imaging, (2020) :param a_model: K x M1 x M2 :param indices_target: K...
9a2b7c0deb2eba58cebd6f7b2198c659c1915711
18,151
from typing import Dict from typing import Any from typing import List def schema_as_fieldlist(content_schema: Dict[str, Any], path: str = "") -> List[Any]: """Return a list of OpenAPI schema property descriptions.""" fields = [] if "properties" in content_schema: required_fields = content_schema...
b691e74ac36a0f3904bd317acee9b9344a440cdb
18,152
def shrink(filename): """ :param filename: str, the location of the picture :return: img, the shrink picture """ img = SimpleImage(filename) new_img = SimpleImage.blank((img.width+1) // 2, (img.height+1) // 2) for x in range(0, img.width, 2): for y in range(0, img.height, 2): ...
fad3778089b0d5f179f62fb2a40ec80fd3fe37d1
18,153
def eh_menor_que_essa_quantidade_de_caracters(palavra: str, quantidade: int) -> bool: """ Função para verificar se a string é menor que a quantidade de caracters informados @param palavra: A palavra a ser verificada @param quantidade: A quantidade de caracters que deseja verificar @return: Retorna T...
827469606b0b93b78b63686465decbbbc63b9673
18,154
import rasterstats as rs def buffer_sampler(ds,geom,buffer,val='median',ret_gdf=False): """ sample values from raster at the given ICESat-2 points using a buffer distance, and return median/mean or a full gdf ( if return gdf=True) Inputs = rasterio dataset, Geodataframe containing points, buffer dista...
8efde64c0ee49b11e484fd204cf70ae5ae322bf9
18,155
import re def extract_int(str, start, end): """ Returns the integer between start and end. """ val = extract_string(str, start, end) if not val is None and re.match('^[0-9]{1,}$', val): return int(val) return None
ec08c15592ea7e7ab9e4a0f476a97ba2127dda85
18,156
import re def get_pg_ann(diff, vol_num): """Extract pedurma page and put page annotation. Args: diff (str): diff text vol_num (int): volume number Returns: str: page annotation """ pg_no_pattern = fr"{vol_num}\S*?(\d+)" pg_pat = re.search(pg_no_pattern, diff) try:...
d9ca1a760f411352d8bcbe094ac622f7dbd33d07
18,157
def check_diamond(structure): """ Utility function to check if the structure is fcc, bcc, hcp or diamond Args: structure (pyiron_atomistics.structure.atoms.Atoms): Atomistic Structure object to check Returns: bool: true if diamond else false """ cna_dict = structure.analyse.pys...
ae082d6921757163cce3ddccbca15bf70621a092
18,158
from typing import Optional from typing import Union from typing import Dict from typing import Any from typing import List from typing import Tuple def compute_correlation( df: DataFrame, x: Optional[str] = None, y: Optional[str] = None, *, cfg: Union[Config, Dict[str, Any], None] = None, dis...
a8fb7f4e6cf34d584aba8e8fa9a7a7703fad8bad
18,159
def radix_sort(arr): """Sort list of numberes with radix sort.""" if len(arr) > 1: buckets = [[] for x in range(10)] lst = arr output = [] t = 0 m = len(str(max(arr))) while m > t: for num in lst: if len(str(num)) >= t + 1: ...
517ab99483ac1c6cd18df11dc1dccb4c502cac39
18,160
import logging import os def du(path, *args, **kwargs): """ pathに含まれるファイルのバイト数を取得する。 :param str path: パス :rtype: int :return: """ # 変数を初期化します。 _debug = kwargs.get("debug") logger = kwargs.get("logger") if not logger: logger = logging.getLogger(__file__) b...
91b5927da5748e242c47eea2735c5ec3f00f2a5b
18,161
def resampling(w, rs): """ Stratified resampling with "nograd_primitive" to ensure autograd takes no derivatives through it. """ N = w.shape[0] bins = np.cumsum(w) ind = np.arange(N) u = (ind + rs.rand(N))/N return np.digitize(u, bins)
2f3d6ae173d5e0ebdfe36cd1ab6595af7452c191
18,162
import torch def integrated_bn(fms, bn): """iBN (integrated Batch Normalization) layer of SEPC.""" sizes = [p.shape[2:] for p in fms] n, c = fms[0].shape[0], fms[0].shape[1] fm = torch.cat([p.view(n, c, 1, -1) for p in fms], dim=-1) fm = bn(fm) fm = torch.split(fm, [s[0] * s[1] for s in sizes]...
bee6d8782b372c0fb3990eefa42d51c6acacc29b
18,163
def get_RF_calculations(model, criteria, calculation=None, clus="whole", too_large=None, sgonly=False, regionalonly=False): """ BREAK DOWN DATA FROM CALCULATION! or really just go pickle """ print(f'{utils.time_now()} - Criteria: {criteria}, calculation: {calculation}, clus: {clus}, sgonly: {sgonly}...
34b44b3a525bd7cee562a63d689fc21d5a5c2a4a
18,164
def preprocessing_fn(inputs): """tf.transform's callback function for preprocessing inputs. Args: inputs: map from feature keys to raw not-yet-transformed features. Returns: Map from string feature key to transformed feature operations. """ outputs = {} # tf.io.decode_png function cannot be appli...
88d2cdc03a3b762ba21d41205ec37ad674ed20b1
18,165
from plugin.helpers import log_plugin_error import importlib import pkgutil def get_modules(pkg, recursive: bool = False): """get all modules in a package""" if not recursive: return [importlib.import_module(name) for finder, name, ispkg in iter_namespace(pkg)] context = {} for loader, name,...
96c48ae86a01defe054e5a4fc948c2f9cfb05660
18,166
def TransformOperationHttpStatus(r, undefined=''): """Returns the HTTP response code of an operation. Args: r: JSON-serializable object. undefined: Returns this value if there is no response code. Returns: The HTTP response code of the operation in r. """ if resource_transform.GetKeyValue(r, 'st...
e840575ccbe468e6b3bc9d5dfb725751bd1a1464
18,167
import warnings def split_record_fields(items, content_field, itemwise=False): """ This functionality has been moved to :func:`split_records()`, and this is just a temporary alias for that other function. You should use it instead of this. """ warnings.warn( "`split_record_fields()` has be...
256efc34bced15c5694fac2a7c4c1003214a54c5
18,168
from typing import cast from typing import Dict import os def flask_formats() -> Response: """Invoke formats() from flask. Returns: Flask HTTP response """ envs = cast(Dict[str, str], os.environ) return _as_response(formats(envs, _as_request(flash_request), envs.get("FLASK_ENV", "prod")))
b672e512f13fef232409632d103c89726980aba8
18,169
import scipy import numpy def prony(signal): """Estimates amplitudes and phases of a sparse signal using Prony's method. Single-ancilla quantum phase estimation returns a signal g(k)=sum (aj*exp(i*k*phij)), where aj and phij are the amplitudes and corresponding eigenvalues of the unitary whose phases...
50bbcd05b1e541144207762052de9de783089bad
18,170
def _check_alignment(beh_events, alignment, candidates, candidates_set, resync_i, check_i=None): """Check the alignment, account for misalignment accumulation.""" check_i = resync_i if check_i is None else check_i beh_events = beh_events.copy() # don't modify original events = np.z...
e4508e90f11bb5b10619d19066a5fb51c36365b3
18,171
def user_info(): """ 个人中心基本资料展示 1、尝试获取用户信息 user = g.user 2、如果用户未登录,重定向到项目首页 3、如果用户登录,获取用户信息 4、把用户信息传给模板 :return: """ user = g.user if not user: return redirect('/') data = { 'user': user.to_dict() } return render_template('blogs/user.html', data=da...
cb8d9c2081c8a26a82a451ce0f4de22fc1a43845
18,172
def build_config_tests_list(): """Build config tests list""" names,_,_,_ = zip(*config_tests) return names
df190ec4926af461f15145bc25314a397d0be52b
18,173
import sys import re def get_layer_type_from_name(name=None) : """ get the layer type from the long form layer name """ if name is None : print("Error get_layer_type_from_name - Bad args - exiting...") sys.exit(1) #print(name) phase, layer_name = name.split(' ') layer_type = ...
8baf34c563c1de64ad6e7f8a6f5ee8f84be5a36a
18,174
def annotate_filter(**decargs): """Add input and output watermarks to filtered events.""" def decorator(func): """Annotate events with entry and/or exit timestamps.""" def wrapper(event, *args, **kwargs): """Add enter and exit annotations to the processed event.""" funcna...
e1ce16e46f17948bdb1eae3ac8e5884fe6553283
18,175
def cplot(*args,**kwargs): """ cplot - Plot on the current graphe This is an "alias" to gcf().gca().plot() """ return(gcf().gca().plot(*args,**kwargs))
b7725569d19520c0e85f3a48d30800c3822cdac2
18,176
from datetime import datetime def need_to_flush_metrics(time_now): """Check if metrics need flushing, and update the timestamp of last flush. Even though the caller of this function may not successfully flush the metrics, we still update the last_flushed timestamp to prevent too much work being done in user ...
a2f50927a61eecee9448661f87f08a99caa4a22c
18,177
import os def path_to_url(path): """Return the URL corresponding to a given path.""" if os.sep == '/': return path else: return '/'.join(split_all(path))
da8044b026ec1130d5d5eaa8a083a3da56bae0e0
18,178
def create_instances_from_lists(x, y=None, name="data"): """ Allows the generation of an Instances object from a list of lists for X and a list for Y (optional). All data must be numerical. Attributes can be converted to nominal with the weka.filters.unsupervised.attribute.NumericToNominal filter. ...
310d72cb9fe5f65d85b19f9408e670426ebf7fdd
18,179
def jitdevice(func, link=[], debug=None, inline=False): """Wrapper for device-jit. """ debug = config.CUDA_DEBUGINFO_DEFAULT if debug is None else debug if link: raise ValueError("link keyword invalid for device function") return compile_device_template(func, debug=debug, inline=inline)
363b48390cfbef9954d714cf3c7900d26693a09c
18,180
def median_filter_(img, mask): """ Applies a median filer to all channels """ ims = [] for d in range(3): img_conv_d = median_filter(img[:,:,d], size=(mask,mask)) ims.append(img_conv_d) return np.stack(ims, axis=2).astype("uint8")
2d7909b974572711901f84806009f237ecafaadf
18,181
def replace_lines(inst, clean_lines, norm_lines): """ Given an instance and a list of clean lines and normal lines, add a cleaned tier and normalized if they do not already exist, otherwise, replace them. :param inst: :type inst: xigt.Igt :param clean_lines: :type clean_lines: list[dict...
39f3fdcd40eafd32e071b54c9ab032104fba8c7c
18,182
from pathlib import Path def get_html(link: Link, path: Path) -> str: """ Try to find wget, singlefile and then dom files. If none is found, download the url again. """ canonical = link.canonical_outputs() abs_path = path.absolute() sources = [canonical["singlefile_path"], canonical["wget_...
3624e3df219cc7d6480747407ad7de3ec702813e
18,183
def normalization(X,degree): """ A scaling technique in which values are shifted and rescaled so that they end up ranging between 0 and 1. It is also known as Min-Max scaling ---------------------------------------- degree: polynomial regression degree, or attribute/feature number """ ...
9cdef8b4b7e7a31523311ce6f4a668c6039ad2a1
18,184
def get_tags_from_match(child_span_0, child_span_1, tags): """ Given two entities spans, check if both are within one of the tags span, and return the first match or O """ match_tags = [] for k, v in tags.items(): parent_span = (v["start"], v["end"]) if parent_relation(child_...
c7ad037d2c40b6316006b4c7dda2fd9d02640f6e
18,185
def _rfc822_escape(header): """Return a version of the string escaped for inclusion in an RFC-822 header, by ensuring there are 8 spaces space after each newline. """ lines = header.split('\n') header = ('\n' + 8 * ' ').join(lines) return header
1a3cd02b057742db00ed741c40947cf4e19d1a86
18,186
import socket def getCgiBaseHref(): """Return value for <cgiBaseHref/> configuration parameter.""" val = sciflo.utils.ScifloConfigParser().getParameter('cgiBaseHref') if val is None: val = "http://%s/sciflo/cgi-bin/" % socket.getfqdn() return val
62b5bc3d528c6db64ff8899c2847d2b0ecb4021d
18,187
import copy import os def _add_remote_resources(resources): """Retrieve remote resources like GATK/MuTect jars present in S3. """ out = copy.deepcopy(resources) for prog, info in resources.items(): for key, val in info.items(): if key == "jar" and objectstore.is_remote(val): ...
faac0cb96ed7cbe712d67e2d095dfb1fcbba8f99
18,188
def dijkstra(gph: GraphState, algo: AlgoState, txt: VisText, start: Square, end: Square, ignore_node: Square = None, draw_best_path: bool = True, visualize: bool = True) \ -> [dict, bool]: """Code for the dijkst...
cbc69734278e7ab4b0c609a1bfab5a9280bedee4
18,189
import sys import os import importlib def calc_window_features(dict_features, signal_window, fs, **kwargs): """This function computes features matrix for one window. Parameters ---------- dict_features : dict Dictionary with features signal_window: pandas DataFrame Input from whic...
47edcbaec41bb3b5fb2d0c3713d3b5c23b0f3521
18,190
def nowIso8601(): """ Returns time now in ISO 8601 format use now(timezone.utc) YYYY-MM-DDTHH:MM:SS.ffffff+HH:MM[:SS[.ffffff]] .strftime('%Y-%m-%dT%H:%M:%S.%f%z') '2020-08-22T17:50:09.988921+00:00' Assumes TZ aware For nanosecond use instead attotime or datatime64 in pandas or numpy ...
c5290e5a60f708f19d1cecf74c9cd927b4750ca3
18,191
def get_trip_data(tripdata_path, output_path, start=None, stop=None): """ Read raw tripdata csv and filter unnecessary info. 1 - Check if output path exists 2 - If output path does not exist 2.1 - Select columns ("pickup_datetime", "passenger_coun...
3aca0b89d1e747ae1ea3e5ea9f3fa0d63a5b9447
18,192
import urllib def _qparams2url(qparams): """ parse qparams to make url segment :param qparams: :return: parsed url segment """ try: if qparams == []: return "" assert len(qparams) == 4 num = len(qparams[0][1]) path="" for i in range(num): ...
ac416dd0dac87210fef5aa1bea97a60c84df60cf
18,193
import itertools def confusion_matrix(y_pred: IntTensor, y_true: IntTensor, normalize: bool = True, labels: IntTensor = None, title: str = 'Confusion matrix', cmap: str = 'Blues', show: bool =...
744642cde03696f6ecbccc6f702e3f9a3cb67451
18,194
def from_smiles(smiles: str) -> Molecule: """Load a molecule from SMILES.""" return cdk.fromSMILES(smiles)
a5315eeb9ffadff16b90db32ca07714fe1573cda
18,195
from typing import Dict from typing import Any def parse_template_config(template_config_data: Dict[str, Any]) -> EmailTemplateConfig: """ >>> from tests import doctest_utils >>> convert_html_to_text = registration_settings.VERIFICATION_EMAIL_HTML_TO_TEXT_CONVERTER # noqa: E501 >>> parse_template_con...
adea58fd8e8a16ec4fd48ef68aa2ff1c6356bd0d
18,196
import json def stringify_message(message): """Return a JSON message that is alphabetically sorted by the key name Args: message """ return json.dumps(message, sort_keys=True, separators=(',', ':'))
ccd51481627449345ba70fbf45d8069deca0f064
18,197
import numpy as np def compute_similarity_transform(X, Y, compute_optimal_scale=False): """ A port of MATLAB's `procrustes` function to Numpy. Adapted from http://stackoverflow.com/a/18927641/1884420 Args X: array NxM of targets, with N number of points and M point dimensionality Y: a...
10da3df241ec140de86b2307f9fc097b4f926407
18,198
def simplefenestration(idf, fsd, deletebsd=True, setto000=False): """convert a bsd (fenestrationsurface:detailed) into a simple fenestrations""" funcs = (window, door, glazeddoor,) for func in funcs: fenestration = func(idf, fsd, deletebsd=deletebsd, setto000=setto000) i...
b72e73a22756e80981d308b54037510354a5d327
18,199