content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _order_points(pts: np.ndarray) -> np.ndarray: """Extract top left. top right, bottom left, bottom right of region Args: pts (np.ndarray[Tuple]): The coordinate of points Returns: np.ndarray: The coordinate of points. """ x_sorted = pts[np.argsort(pts[:, 0]), :] left_most =...
46dfb8a8e042929b2475bda2b01b39e5d871e02d
2,100
import logging import math def to_image(obj): """ allgemeine funktion zum anschauen von allen objekttypen (work in progress) gibt image (numpy arry),description zurück description sagt, was alles gemacht wurde um bild darzustellen """ descr = "" if (tf.is_tensor(obj)): obj = obj.numpy() logger...
4ae3be9758a647bbe2d0d2fedc080992840ab124
2,101
import os import sys import logging import re import signal def start(): """ Start the daemon. """ ret = 0 cfg = 'ludolph.cfg' cfg_fp = None cfg_lo = ((os.path.expanduser('~'), '.' + cfg), (sys.prefix, 'etc', cfg), ('/etc', cfg)) config_base_sections = ('global', 'xmpp', 'webserver', '...
f6bb0a41bda524e20d9d2aec25a09259d8c7514b
2,102
import re def matchPP(a_string): """assumes a_string is a string returns re match object if it finds two consecutive words that start with P, else returns None""" pattern = "[P|p]\w+\s[P|p]\w+" result = re.search(pattern, a_string) return result
c46eb4e0380a54cc36db0dc8969d17d65a546bf3
2,103
def setBoth(s1, s2): """ Sets both servo motors to specified number of degrees Args: s1, s2 (number): degrees for left and right servos respectively must be between -90 and 90 and will be rounded Raises: Exception if s1 or s2 is not a number Returns: None...
16385e9a8ad23011e9c10f66677afb703f6d19ed
2,104
import json def transfer_shfe_future_hq(date, file_path, columns_map): """ 将每天的数据统一标准 :return: pd.DataFrame 统一标准后的数据 """ ret = pd.DataFrame() data = json.loads(file_path.read_text()) hq_df = pd.DataFrame(data['o_curinstrument']) total_df = pd.DataFrame(data['o_curproduct']) bflag...
4e90164f96d4c5018774c0ad8d4deda7fa6dbeec
2,105
def comp_material_bsdf(arg_material_one:bpy.types.Material, arg_material_two:bpy.types.Material) -> bool: """指定マテリアルのBSDFノードを比較する 受け渡したマテリアルの出力ノードに接続されたプリシプルBSDFノードを比較する 比較対象の入力端子のデフォルト値が有効、かつ、全て同一の場合、Trueを返す Args: arg_material_one (bpy.types.Material): 比較マテリアル1 arg_material_two (bpy....
884c38c93ea4fd0c6907da0d2e5025a0980bed50
2,106
def run_filters(): """Runs filters ('PAINS', 'ZINC', 'BRENK', 'NIH')for molecule selected. Saves the information to the global molecule_info dict and returns the information as its own dict. Pass R Group IDs as queries: /filters?r1=A01&r2=B01 :returns: A json dictionary of the molecule, indexed ...
e1bc4719d412a73a7860f49978d47c459dc34d70
2,107
def read_template(engine, template_name): """Read template string from file and get path.""" template_file = get_template_file(engine, template_name) template_string = template_file.read_text() return template_string, template_file.parent
3dc55309df1575d2af2e4794e03e2ba4ccd166a2
2,108
def get_qbert_v3_url(qbert_url, project_id): """Keystone only hands out a v1 url I need v3.""" qbert_v3_url = "{0}/v3/{1}".format(qbert_url[0:-3], project_id) return qbert_v3_url
423e1f7a601f4ecafbc7d52d1f95fd59195f193e
2,109
def gen_all_holds(hand): """ Generate all possible choices of dice from hand to hold. hand: sorted full yahtzee hand Returns a set of tuples, where each tuple is sorted dice to hold """ # start off with the original hand in set set_holds = set([(hand)]) # now iterate with all...
5c8af5040f619fabef56918d399b5a1cab8893a4
2,110
def sndrcv(*args, **kwargs): # type: (*Any, **Any) -> Tuple[SndRcvList, PacketList] """Scapy raw function to send a packet and receive its answer. WARNING: This is an internal function. Using sr/srp/sr1/srp is more appropriate in many cases. """ sndrcver = SndRcvHandler(*args, **kwargs) retu...
6918dbf09bef672b95bab83126e6e4c0ec99e3bf
2,111
from typing import Optional def get_by_name(db_session: Session, *, name: str) -> Optional[Action]: """Return action object based on action name. Arguments: db_session {Session} -- SQLAlchemy Session object name {str} -- action name Returns: Optional[Action] -- Returns a Action o...
fb8c758d401fe09a36b3d2687a0e8e886edac594
2,112
def langstring(value: str, language: str = "x-none") -> dict: """Langstring.""" return { "langstring": { "lang": language, "#text": value, } }
dca23a329cfc87d8cfa52cd2b009ce723b7d2270
2,113
def chinese_half2full(): """Convert all halfwidth Chinese characters to fullwidth . Returns: """ def string_op(input_str:str): rstring = "" for uchar in input_str: u_code = ord(uchar) if u_code == 32: u_code = 12288 elif 33 <= u_code ...
e89a6314a57192e62b32e1f7e044a09700b5bb73
2,114
def euclidean_distance(p1, p2): """ Returns the Euclidean Distance of a particular point from rest of the points in dataset. """ distance = 0 for i in range(len(p1)-1): distance += (p1[i]-p2[i])**(2) return sqrt(distance)
dd06e44659fdd06972bd6a660afeb313de81c6fe
2,115
import argparse def get_arguments(): """Parse command line arguments""" parser = argparse.ArgumentParser(description="""A simple popup calendar""") parser.add_argument( "-p", "--print", help="print date to stdout instead of opening a note", action="store_true", ) ...
7e7940001679e05f137798d127f54c9ab7512a63
2,116
def img_histogram(file): """ Returns an image's histogram in a combined RGB channel and each individual channel as an array of 256 values. A 0 means that a tonal value is the max and 255 means there are 0 pixels at that value. """ with Image.open(file) as img: histogram = img.histogram()...
1f210316e752328190978f908143dd40c9ef6ba4
2,117
def absModuleToDist(magApp, magAbs): """ Convert apparent and absolute magnitude into distance. Parameters ---------- magApp : float Apparent magnitude of object. magAbs : float Absolute magnitude of object. Returns ------- Distance : float The distance resu...
a7d98ff479114f08e47afefc97a1119f5e8ff174
2,118
import base64 def decoded_anycli(**kwargs): """ Return the decoded return from AnyCLI request - Do not print anything :param kwargs: keyword value: value to display :return: return the result of AnyCLI in UTF-8 :Example: result = cli(url=base_url, auth=s, command="show vlan") deco...
223c4f9aabfef530896729205071e7fb8f9c8301
2,119
def job_results_html(request): """ Used for testing the update with debug toolbar. """ response = job_results(request) return render(request, 'ci/ajax_test.html', {'content': response.content})
eed4b66d8227f8256847484d2dc01f4dcd3b3afa
2,120
import pandas def open_mcrae_nature_cohort(): """ get proband details for McRae et al., Nature 2017 McRae et al Nature 2017 542:433-438 doi: 10.1038/nature21062 Supplementary table S1. """ data = pandas.read_excel(url, sheet_name='Supplementary Table 1') data['Individual ID'] += '|DDD...
8485fdc09c92bab20fc380a14f549f028be950b7
2,121
def copia_coords_alineadas(align1,align2,coords_molde,PDBname): """ Devuelve: 1) una lista con las coordenadas de coords_molde que se pueden copiar segun el alineamiento align1,align2. 2) una estimacion del RMSD segun la curva RMSD(A) = 0.40 e^{l.87(1-ID)} de Chothia & Lesk (1986) """ aanames = { "A":"ALA",...
48c730b43dd7059b6a6d7a068d884ecd27d3820e
2,122
def get_amati_relationship(value='o'): """ Return the Amati relationship and it's 1 sigma dispersion as given by Tsutsui et al. (2009). :param value: a string that can be 'o', '+', or '-'. The default is set to 'o' for the actual Amati relationship. '+' gives the upper bound of uncertainty and '-' gives the lower...
f7618f812dca45640376177383af2443085b6246
2,123
def load(name, final=False, torch=False, prune_dist=None): """ Returns the requested dataset. :param name: One of the available datasets :param final: Loads the test/train split instead of the validation train split. In this case the training data consists of both training and validation. :retu...
38f379076ba6f5562ab818113b319276f84bd081
2,124
def is_paragraph_debian_packaging(paragraph): """ Return True if the `paragraph` is a CopyrightFilesParagraph that applies only to the Debian packaging """ return isinstance( paragraph, CopyrightFilesParagraph ) and paragraph.files.values == ['debian/*']
726cd3d8c7cdfd14a55dc8bc9764cc9d037b1b63
2,125
def update_b(b, action_prob, yr_val, predict_mode): """Update new shape parameters b using the regression and classification output. Args: b: current shape parameters values. [num_examples, num_shape_params]. action_prob: classification output. [num_actions]=[num_examples, 2*num_shape_params] ...
ba8535d538ae0e0ac44c452f2fbe94a686b8e5a1
2,126
def setup(args): """ Create configs and perform basic setups. """ cfg = get_cfg() add_config(args, cfg) cfg.merge_from_file(args.config_file) cfg.merge_from_list(args.opts) cfg.merge_from_list(['MODEL.BUA.EXTRACT_FEATS',True]) cfg.merge_from_list(switch_extract_mode(args.extract_mode...
9dd4495a13c64d4832b889abdf94ffd01133c92a
2,127
def _earth_distance(time='now'): """ Return the distance between the Sun and the Earth at a specified time. Parameters ---------- time : {parse_time_types} Time to use in a parse_time-compatible format Returns ------- out : `~astropy.coordinates.Distance` The Sun-Earth ...
c8646b7e2aa9b821a9740235d5cc263623bd0ec0
2,128
async def DELETE_Link(request): """HTTP method to delete a link""" log.request(request) app = request.app group_id = request.match_info.get('id') if not group_id: msg = "Missing group id" log.warn(msg) raise HTTPBadRequest(reason=msg) if not isValidUuid(group_id, obj_cla...
193d6cb86a820a7492c768aad0a0e22fac76198f
2,129
def format_image(image): """ Function to format frame """ if len(image.shape) > 2 and image.shape[2] == 3: # determine whether the image is color image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) else: # Image read from buffer image = cv2.imdecode(image, cv2.CV_LOAD_IMA...
1649814cddab0037f89936d1a39af44d8d5203d9
2,130
def cpu_stats(): """Return various CPU stats as a named tuple.""" ctx_switches, interrupts, syscalls, traps = cext.cpu_stats() soft_interrupts = 0 return _common.scpustats(ctx_switches, interrupts, soft_interrupts, syscalls)
afdc9e95ba5d0b7760a1bbdf505b85f3fb0a0b7d
2,131
def chi_squared(source_frequency, target_frequency): """Calculate the Chi Squared statistic by comparing ``source_frequency`` with ``target_frequency``. Example: >>> chi_squared({'a': 2, 'b': 3}, {'a': 1, 'b': 2}) 0.1 Args: source_frequency (dict): Frequency map of the text you are...
f076e78bc283a0f1ab8c2cd80a4a441ca1fb2692
2,132
def has_reacted(comment, user, reaction): """ Returns whether a user has reacted with a particular reaction on a comment or not. """ if user.is_authenticated: reaction_type = getattr(ReactionInstance.ReactionType, reaction.upper(), None) if not reaction_type: raise template.T...
8cf537b204ae13c844e80a14b29f11e36d69097b
2,133
import requests def structure_query(compound, label='pyclassyfire'): """Submit a compound information to the ClassyFire service for evaluation and receive a id which can be used to used to collect results :param compound: The compound structures as line delimited inchikey or smiles. Optionally a...
cd7c0558dd61f493187169cea3562c96f63634d2
2,134
def ParseExistingMessageIntoMessage(message, existing_message, method): """Sets fields in message based on an existing message. This function is used for get-modify-update pattern. The request type of update requests would be either the same as the response type of get requests or one field inside the request ...
7c2e4d10be831106834aa519f4abed945ca85589
2,135
def create(*, db_session, ticket_in: TicketCreate) -> Ticket: """Creates a new ticket.""" ticket = Ticket(**ticket_in.dict()) db_session.add(ticket) db_session.commit() return ticket
644bcccc56c8fd97ec3c888f6e38c1fc2afc3585
2,136
def blur(img): """ :param img: SimpleImage, an original image. :return: img: SimpleImage, image with blurred effect. """ blank_img = SimpleImage.blank(img.width, img.height) for y in range(img.height): for x in range(img.width): blurred = blank_img.get_pixel(x, y) ...
9a7ac5085aea610a26a626e1d53bd243de19ad9e
2,137
def trans_pressure(src, dest="bar"): """ >>> """ return trans_basic_unit(src, dest, "pressure")
120888c024e6158a6e26ab699f7f4b5583cbf243
2,138
import subprocess def run_cmd(command: list) -> None: """Run `command` using `subprocess.Popen()`.""" show_info(f"Command: {' '.join(command)}") if DRY_RUN: show_info("Dry run mode enabled - won't run") else: try: proc = subprocess.Popen(command, stdout=subprocess.PIPE) ...
3c17796f9d758c42989b594ed2796e1834f4ea2e
2,139
def test_accelerated_bypass_method_against_old(c_ctrl_rr): """Confirm that my changes to the bypass method maintain the same result as the old method""" OLD_HTCONSTS = dassh.region_rodded.calculate_ht_constants(c_ctrl_rr) def _calc_coolant_byp_temp_old(self, dz): """Calculate the coolant temper...
db6660b8ddc2f7ea409f7b334e4e161fceb743b2
2,140
from pathlib import Path def retrieve_config(): # TODO: is this being used? """Retrieve configuration data. Args: None Returns: dict: The dictionary with configuration settings """ config = {} # go 2 layer up util_path = Path(__file__).parents[3] config_path = util_...
3b1519e7e8caa29878aaecabeb098d166bcf763c
2,141
import logging def vraec18(pretrained=False, **kwargs): """Constructs a _ResAE-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = _VRAEC(_VariationalBasicBlock, [2, 2, 2, 2], **kwargs) if pretrained: try: model.load_state_di...
6b5e5a5d812b20c30bac3f81289a553bdc4884d4
2,142
import zlib def encode_zip(data): """Zip-compress data. Implies base64 encoding of zip data.""" zipped = zlib.compress(data) return encode_b64(zipped)
aa048125edd67a411715bf748bf832a6e6d7104f
2,143
def create_class_mask(img, color_map, is_normalized_img=True, is_normalized_map=False, show_masks=False): """ Function to create C matrices from the segmented image, where each of the C matrices is for one class with all ones at the pixel positions where that class is present img = The segmented image ...
97452e568d0a29b438a61fc96d90231a318e919b
2,144
import itertools def reconstruct_grid(mask, ds_dl): """ Reconstruction of 2d grid. Args: mask (ndarray): land mask used. ds_dl (ndarray): trained model prediction. """ landmask = np.argwhere(np.isnan(mask)) empty = np.zeros((ds_dl.shape[0], mask.shape[0], mask....
4d220e0d4ae96ee1ddc55e53f21f2a35d920b03e
2,145
def conv_kernel_initializer(shape, dtype=None): """卷积核初始化 和 tf.variance_scaling_initializer最大不同之处就是在于,tf.variance_scaling_initializer 使用的是 truncated norm, 但是却具有未校正的标准偏差,而这里使用正态分布。类似地,tf.initializers.variance_scaling使用带有校正后的标准偏差。 Args: shape: 卷积核的shape dtype: 卷积核的dtype Returns: 经过初始...
f7fd5665aeb8eb592a5f1f0f1785dfd84c9d8d98
2,146
def prediction_func(data, g_data, grid_search, param_list): """Function for using dataset to train a model and predicting prices for a generated data. Parameter search is done using RandomizedSearchCV since it is computationally more efficientcompared to GridSearchCV. In param_list, learning_rate,...
b747578879054947e91e5285b82cf3e07fa313da
2,147
def thv_to_zxy(theta, h): """Convert coordinates from (theta, h, v) to (z, x, y) space.""" cos_p = np.cos(theta) sin_p = np.sin(theta) srcx = +RADIUS * cos_p - h * sin_p srcy = +RADIUS * sin_p + h * cos_p detx = -RADIUS * cos_p - h * sin_p dety = -RADIUS * sin_p + h * cos_p return srcx, ...
64370dc6c4060a718506a243414afdd698881147
2,148
from datetime import datetime def get_most_stale_file(logpath=DEFAULT_PATH): """ returns the filename of the file in the fileset that was least recently backed up and the time of the last backup """ oldest_name = "" oldest_date = datetime.max for fstat in get_fileset_statlist(): la...
e0000847513ffeb97b8df0c26941ca4e3380f09d
2,149
from typing import Mapping from typing import Dict import re import logging def get_instances(context: models.Context) -> Mapping[str, Instance]: """Get a list of Instance matching the given context, indexed by instance id.""" instances: Dict[str, Instance] = {} if not apis.is_enabled(context.project_id, 'comp...
10f4eae30b0a5c752c45378574ba4620bd859320
2,150
def UploadChanges(): """Upload changes, don't prompt.""" # TODO(jfb) Using the commit queue and avoiding git try + manual commit # would be much nicer. See '--use-commit-queue' return ExecCommand(['git', 'cl', 'upload', '--send-mail', '-f'])
3f1f3cb4a4a6250540079c614167300921a9cded
2,151
def svn_fs_delete_fs(*args): """svn_fs_delete_fs(char const * path, apr_pool_t pool) -> svn_error_t""" return _fs.svn_fs_delete_fs(*args)
6e1f34d82899fc257c723990c55853b35f0b06d3
2,152
from re import T def translate_output(_output, n_classes, is_binary_classification=False): """ Gets matrix with one hot encoding where the 1 represent index of class. Parameters ---------- _output : theano.tensor.matrix Output sample. n_classes : int Number of classes (or size of...
03137e6b0704477a69211d454ee5e05a5ab02636
2,153
import os import sys def get_agent_config_vars(): """ Read and parse config.ini """ if os.path.exists(os.path.abspath(os.path.join(__file__, os.pardir, 'config.ini'))): config_parser = ConfigParser.SafeConfigParser() config_parser.read(os.path.abspath(os.path.join(__file__, os.pardir, 'config....
52ff56e7a21e7a3d81fe05b9fd5f4a447971b129
2,154
def _sphere_point_to_uv(point: Point) -> Vec2d: """Convert a 3D point on the surface of the unit sphere into a (u, v) 2D point""" u = atan2(point.y, point.x) / (2.0 * pi) return Vec2d( u=u if u >= 0.0 else u + 1.0, v=acos(point.z) / pi, )
c0eb4abb1ebc55f74b908a85f0cb94f71a528c32
2,155
import tqdm def generate_formula_dict(materials_store, query=None): """ Function that generates a nested dictionary of structures keyed first by formula and then by task_id using mongo aggregation pipelines Args: materials_store (Store): store of materials Returns: Nested dic...
ae232c806972262029966307e489df0b12d646f5
2,156
import os def default_config(): """Provides a default configuration file location.""" return os.path.expanduser('~/.config/discogstagger/discogs_tagger.conf')
2b86700484916ea2f6c47935ec8a43aa0d920184
2,157
def truncate(wirevector_or_integer, bitwidth): """ Returns a wirevector or integer truncated to the specified bitwidth :param wirevector_or_integer: Either a wirevector or and integer to be truncated :param bitwidth: The length to which the first argument should be truncated. :return: Returns a tuncate...
7ff6d22061944f4202bc69dfde109c1cead20972
2,158
def pcoef(xte, yte, rle, x_cre, y_cre, d2ydx2_cre, th_cre, surface): # Docstrings """evaluate the PARSEC coefficients""" # Initialize coefficients coef = np.zeros(6) # 1st coefficient depends on surface (pressure or suction) if surface.startswith('p'): coef[0] = -sqrt(2*rle) e...
43cc56ec7f29267678ebbc3572633e5073cda117
2,159
import psutil def cpu_usage(self, max_cpu_percentage=80): """Limit max cpu usage """ if psutil.cpu_percent() < max_cpu_percentage: hevlog.logging.debug('[cpu usage] {}%'.format(psutil.cpu_percent())) return True else: hevlog.logging.debug('[cpu usage] {}%'.format(psutil.cpu_per...
c4213ed768351a5d9e4e8a14bd951a5eb9f3b2ef
2,160
from datetime import datetime import time import math import os def search_fromCSV(Data,holy_array, bookmark = 0): """ holy array: array of words that is going to be compared with Twitter's text data """ print("Initializing crawler") WINDOW_SIZE = "1920,1080" chrome_options = Options() ch...
01b98fd2650a4ebbdb7ce1e9a995483e8b40357f
2,161
def iscircular(linked_list): """ Determine whether the Linked List is circular or not Args: linked_list(obj): Linked List to be checked Returns: bool: Return True if the linked list is circular, return False otherwise """ slow_runner = linked_list.head fast_runner = linked_lis...
04f86497dae2a2ee77afd37f13bdba8e18ae52b9
2,162
def shape_extent_to_header(shape, extent, nan_value=-9999): """ Create a header dict with shape and extent of an array """ ncols = shape[1] nrows = shape[0] xllcorner = extent[0] yllcorner = extent[2] cellsize_x = (extent[1]-extent[0])/ncols cellsize_y = (extent[3]-extent[2])/nrows i...
957b59e7f464901a5430fd20ab52f28507b55887
2,163
def build_encoder(opt, embeddings): """ Various encoder dispatcher function. Args: opt: the option in current environment. embeddings (Embeddings): vocab embeddings for this encoder. """ if opt.encoder_type == "transformer": return TransformerEncoder(opt.enc_layers, opt.rnn_...
73b379545aeeb3226ea019cad0a692b00cd7630b
2,164
import glob import os def load_rendered_images_object_type(resources_path, n_channels, mode="render"): """ Import images from the resources dir with certain number of channels :param resources_path: Dir path from were images are fetched :param n_channels: Number of colors for the images :return: ...
b3aca205c0b5c07a115504bf233dafc12b41ca5e
2,165
def efficientnet_b3b(in_size=(300, 300), **kwargs): """ EfficientNet-B3-b (like TF-implementation) model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (300, 300) ...
1d7e0bffe67f9d2f340563b21e1f995201877165
2,166
import logging def logged(class_): """Class-level decorator to insert logging. This assures that a class has a ``.log`` member. :: @logged class Something: def __init__(self, args): self.log(f"init with {args}") """ class_.log= logging.get...
cd58e355151ab99aa1694cbd9fb6b710970dfa19
2,167
def TableInFirstNSStart(builder): """This method is deprecated. Please switch to Start.""" return Start(builder)
5ea3cf66842eaf026a36bb241c277076cc8650b8
2,168
def dicom_to_nifti(dicom_input, output_file=None): """ This is the main dicom to nifti conversion function for ge images. As input ge images are required. It will then determine the type of images and do the correct conversion :param output_file: filepath to the output nifti :param dicom_input: dir...
0b77d190c2379e9b2ad5fbf9217e1604a7df8bc9
2,169
def lot_vectors_dense_internal( sample_vectors, sample_distributions, reference_vectors, reference_distribution, metric=cosine, max_distribution_size=256, chunk_size=256, spherical_vectors=True, ): """Efficiently compute linear optimal transport vectors for a block of data provid...
d7f9eaad6b7292f2c28621f361094a88e7deb8a6
2,170
import rasterio as rio def load( filename, rsc_file=None, rows=None, cols=None, band=1, **kwargs, ): """Load a file, either using numpy or rasterio""" if rsc_file: rsc_data = load_rsc(rsc_file) return load_stacked_img(filename, rsc_data=rsc_data, rows=rows, cols=cols) ...
873933b80b7e87f64b10ad74cc8ed25238a93fb3
2,171
def simple_scan_network(): """ Do a simple network scan, which only works if your network configuration is 192.168.1.x """ base_ip = "192.168.1." addresses = ['127.0.0.1'] for index in range(1, 255): addresses.extend([base_ip + str(index)]) return addresses
b0f19ae1c98678e87d270b308b5359df9a6a4d30
2,172
import os import argparse def check_valid_file_or_folder(value): """verifies filename exists and isn't a link""" if value is not None: if not os.path.isfile(value) and not os.path.isdir(value): raise argparse.ArgumentTypeError("{} does not exist or is not a file/folder.". ...
bd6a2149f1092c28d634caf8eb6110b32fc2b5a8
2,173
def channel_lvlv_2jet(): """ Mostly based on table 8 of the combination paper for the uncertainties and table 9 for the event counts. """ channel = ROOT.RooStats.HistFactory.Channel( "HWWlvlv2Jet" ) container.append(channel) channel.SetData(55) background = ROOT.RooStats.HistFactory.Sample("background") backgr...
f60609a0bf6f22dc850fcb52c4a19b6bae737abc
2,174
def vtkVariantStrictEquality(s1, s2): """ Check two variants for strict equality of type and value. """ s1 = vtk.vtkVariant(s1) s2 = vtk.vtkVariant(s2) t1 = s1.GetType() t2 = s2.GetType() # check based on type if t1 != t2: return False v1 = s1.IsValid() v2 = s2.IsV...
cb529c35f6dfc7e20fcff79d5c38b41bd43f1292
2,175
def is_network_failure(error): """Returns True when error is a network failure.""" return ((isinstance(error, RETRY_URLLIB_EXCEPTIONS) and error.code in RETRY_HTTP_CODES) or isinstance(error, RETRY_HTTPLIB_EXCEPTIONS) or isinstance(error, RETRY_SOCKET_EXCEPTIONS) or ...
647d10b257b1cb7f78243629edd2b425104f1787
2,176
import torch def predict(model, X, threshold=0.5): """Generate NumPy output predictions on a dataset using a given model. Args: model (torch model): A Pytroch model X (dataloader): A dataframe-based gene dataset to predict on """ X_tensor, _ = convert_dataframe_to_tensor(X, []) ...
57b6137cc8f7e0753e6438432f56b471717a5d88
2,177
def color_image( img: np.ndarray, unique_colors=True, threshold=100, approximation_accuracy=150 ) -> np.ndarray: """ This function detects simple shapes in the image and colors them. Detected figures will be also subscribed in the final image. The function can detect triangles, quadrilateral, and c...
5637febc69dcc2b3e641f0d79f2e21c6dc7d04ec
2,178
from pathlib import Path def restore_model(pb_path): """Restore the latest model from the given path.""" subdirs = [x for x in Path(pb_path).iterdir() if x.is_dir() and 'temp' not in str(x)] latest_model = str(sorted(subdirs)[-1]) predict_fn = predictor.from_saved_model(latest_model) return pr...
bded95b196081e19ca1c70127871abb99d3526d0
2,179
import math def _generate_resolution_shells(low, high): """Generate 9 evenly spaced in reciprocal space resolution shells from low to high resolution, e.g. in 1/d^2.""" dmin = (1.0 / high) * (1.0 / high) dmax = (1.0 / low) * (1.0 / low) diff = (dmin - dmax) / 8.0 shells = [1.0 / math.sqrt(dm...
52fa4309f2f34a39a07d8524dd7f226e3d1bae6a
2,180
from typing import Optional from typing import Tuple def add_ports_from_markers_square( component: Component, pin_layer: Layer = (69, 0), port_layer: Optional[Layer] = None, orientation: Optional[int] = 90, min_pin_area_um2: float = 0, max_pin_area_um2: float = 150 * 150, pin_extra_width: ...
68858a17b5187e064232f0c101ddf9c4e812c233
2,181
def P(Document, *fields, **kw): """Generate a MongoDB projection dictionary using the Django ORM style.""" __always__ = kw.pop('__always__', set()) projected = set() omitted = set() for field in fields: if field[0] in ('-', '!'): omitted.add(field[1:]) elif field[0] == '+': projected.add(field[1:]) ...
d88a428f5eae1e57bd3b5ddf0d31e6e7c122c27d
2,182
def get_page_url(skin_name, page_mappings, page_id): """ Returns the page_url for the given page_id and skin_name """ fallback = '/' if page_id is not None: return page_mappings[page_id].get('path', '/') return fallback
6ead4824833f1a7a002f54f83606542645f53dd6
2,183
import textwrap def get_paragraph_head(source, maxlength, bullet_num=-1, bullet=False): """Return the paragraph text of specific length, optionally prefix a bullet. Args: source(str, PreProcessed, etree._Element) maxlength(int) Kwargs: bullet(bool): False by default, otherwise pre...
ef809d355b8f3495b1ad337e399ad7e243784049
2,184
def create_form(erroneous_form=None): """Show a form to create a guest server.""" party_id = _get_current_party_id_or_404() setting = guest_server_service.get_setting_for_party(party_id) form = erroneous_form if erroneous_form else CreateForm() return { 'form': form, 'domain': set...
2d8e9cd6597e4ccb1b9f39d77cca45b354d99371
2,185
def apply(task, args, kwargs, **options): """Apply the task locally. This will block until the task completes, and returns a :class:`celery.result.EagerResult` instance. """ args = args or [] kwargs = kwargs or {} task_id = options.get("task_id", gen_unique_id()) retries = options.get(...
600bc142ca8d96bd020db5cb82103169d255d970
2,186
from typing import Optional from typing import Callable def exp_post_expansion_function(expansion: Expansion) -> Optional[Callable]: """Return the specified post-expansion function, or None if unspecified""" return exp_opt(expansion, 'post')
6d49f5e40b7c900470a5c84b37d9da1666b217c2
2,187
def return_(x): """Implement `return_`.""" return x
6557a37db2020bdbb0f9dcf587f2bd42509ff937
2,188
import os def _resolve_link(path): """Internal helper function. Takes a path and follows symlinks until we either arrive at something that isn't a symlink, or encounter a path we've seen before (meaning that there's a loop). """ paths_seen = [] while islink(path): if path in paths_see...
16e0912628d0170fb510ebe6655c55211633c160
2,189
def create(platformDetails): """ This function creates a new platform in the platform list based on the passed in platform data :param platform: platform to create in platform structure :return: 201 on success, 406 on platform exists """ # Remove id as it's created automatically ...
a6b27d6b530ccc11134a001ac3b49c6cb89475a3
2,190
def _execute_cell(cell, shell, iopub, timeout=300): """ Execute an IPython Notebook Cell and return the cell output. Parameters ---------- cell : IPython.nbformat.current.NotebookNode The IPython Notebook cell to execute. shell : IPython.kernel.blocking.channels.BlockingShellChannel ...
0893611a9693ffd62bcedd5a718bc4cab144357d
2,191
def VD_A_DF(data, val_col: str = None, group_col: str = None, sort=True): """ :param data: pandas DataFrame object An array, any object exposing the array interface or a pandas DataFrame. Array must be two-dimensional. Second dimension may vary, i.e. groups may have different lengths. ...
ee4b94c9a47d8e15e182c010ffdb954f2ccec4bb
2,192
def getR2(y, y_fitted, chi=None): """ calculates the coefficient of determination R^2 for `y_fitted` as prediction for `y` over a region marked by chi>0 defined by R^2=1 - S_res/S_tot with S_res=int(chi*(y-y_fitted*1)**2, S_tot=int(chi*(y-m(y)*1)**2), m(y)=int(chi*y)/...
8ec0837d2d8443279af4142c8b8407b0b03af06a
2,193
def basis(d, point_distribution='uniform', symbolic=True): """ Return all local basis function phi as functions of the local point X in a 1D element with d+1 nodes. If symbolic=True, return symbolic expressions, else return Python functions of X. point_distribution can be 'uniform' or 'Chebyshev...
0f369ab22a12588e10826e894142a1dd115a5aa9
2,194
def provide_batch_fn(): """ The provide_batch function to use. """ return dataset_factory.provide_batch
9ec34fb430dab0a17461f3002f1acbbd94b6e637
2,195
def mergeSort(li): """Sorts a list by splitting it to smaller and smaller pieces (until they only have one or less elements) and then merges it back using the function ``merge()``. >>> mergeSort([1, 2, 3, 4, 5]) [1, 2, 3, 4, 5] >>> mergeSort([5, 4, 3, 2, 1]) [1, 2, 3, 4, 5] >>> mergeSor...
c0f38ff6779bb24ebb081b5b76661189fa2767bc
2,196
import sys import random def mcplayout(pos, amaf_map, disp=False): """ Start a Monte Carlo playout from a given position, return score for to-play player at the starting position; amaf_map is board-sized scratchpad recording who played at a given position first """ if disp: print('** SIMULATION *...
d451c195f6596c1325487e277b052b83cfae85dc
2,197
def test_colour_ranges(fake_readme, monkeypatch): """ Whatever number we provide as coverage should produce the appropriate colour """ readme_file = "README" def fake_readme_location(*args, **kwargs): return os.path.join(TESTS_DIR, readme_file) monkeypatch.setattr(__main__, "readme_lo...
0614cfa9d33e1d5f3112a79198c7fd2e762f4e3d
2,198
def remove_partitions( cube, store, conditions=None, ktk_cube_dataset_ids=None, metadata=None ): """ Remove given partition range from cube using a transaction. Remove the partitions selected by ``conditions``. If no ``conditions`` are given, remove all partitions. For each considered dataset, only...
0bede6d99e34edce32f42d9f78104ee3fdc45456
2,199