content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def FilterKeptAttachments( is_description, kept_attachments, comments, approval_id): """Filter kept attachments to be a subset of last description's attachments. Args: is_description: bool, if the comment is a change to the issue description. kept_attachments: list of ints with the attachment ids for a...
89732832db557835a5dea1ef10229bfdd809d304
3,642,841
import piaplib.book.__main__ import piaplib.book.__main__ def main(argv=None): """The main event""" try: if 'piaplib.book.__main__' not in sys.modules: else: piaplib.book.__main__ = sys.modules["""piaplib.book.__main__"""] if piaplib.book.__main__.__name__ is None: raise ImportError("Failed to import pi...
61ce42c99b933f95596e6cde788890984f270fee
3,642,844
from datetime import datetime def today() -> date: """ **today** returns today's date :return present date """ return datetime.datetime.now().date()
b5c7b19d9ff02993ab63de2bebd3d7bcdd24da59
3,642,845
def get_word_size(word,font_size): """get's the dimansions of any given word for any giving font size""" Font=ImageFont.truetype(FONT, font_size) return Font.getsize(word)
5742f9ee4377d2f251f75acdfceb1c8c1884fde1
3,642,846
def get_id(asset, **kwargs): """Get an asset by the unique id. The key for the id must have 'id' in the name in the kwargs. Example:: get_id(Foo, foo_id=1) # works get_id(Foo, foo=1) # TypeError """ id_key = next(_parse_id(kwargs), None) if id_key is None: raise Typ...
d4c1864acca7aecaed91f550359e7d9541f0de2f
3,642,847
def put_study_document(request): """PUT method for editing an existing study. Adds "resource_type" -> "study" then calls generic `put_document`. See `finish_write_operation` for description of the response. """ request.matchdict['resource_type'] = 'study' return put_document(request)
244cfecf0f87187334ab599a477e1e3459f549c6
3,642,848
def create_command(input_file, columns_to_use, column_separator, output_file): """ This function creates the linux command to filter the columns and creating the output file :param input_file: A valid file path to raw data file :param columns_to_use: Indexes of the columns that needs to be filtered out ...
e14d88bf843190890827d2a157d02faf60917800
3,642,849
def _new_data_generated(dataset, datagen): """ Function to put augmented data in directories :param dataset: The path for the specified directory :param datagen: The augmented data :return: The new data to use for model """ new_data = datagen.flow_from_directory( dataset, tar...
659edb0eb32e5609c8a0ff11814c5c0d317b134c
3,642,850
def findOutNode( node, testFunc, fallback=... ): """ get node and all its parents, inner to outer order """ for out_node in getOutNodes( node ): if testFunc( out_node ): return out_node if fallback is not ...: return fallback raise Exception( 'cannot find out node' )
73a7f88dee12dd82edecaf173b6fecb48b2ce86b
3,642,851
import logging def lookup_cpe(vendor, product, cpe_type, cpe_table, remap): """Identify the correct vendor and product values for a CPE This function attempts to determine the correct CPE using vendor and product values supplied by the caller as well as a remapping dictionary for mapping these values...
5a6e2e735daa50d3d2a19022db002ebfc647335c
3,642,852
def main(): """main function of git learning """ return 'Google git'
a7296a18657643188ef58131fe012df6543f808e
3,642,853
import numpy import signal def SSIM(img1, img2, cs_map=False): """Return the Structural Similarity Map corresponding to input images img1 and img2 (images are assumed to be uint8) This function attempts to mimic precisely the functionality of ssim.m a MATLAB provided by the author's of SSIM ...
6fe795ac4818ec06db7ed3cd66f52a169dccbc24
3,642,854
def covariance(prices: np.ndarray) -> np.ndarray: """Calculate covariance matrix. Args: prices: Prices of market data. Returns: Covariance matrix. """ Q = np.cov(prices.T, ddof=0) return np.array(Q)
d0870a9ba6fdf58a0d4242f4c1638de7f05b738a
3,642,855
def fiveplates_clean_design_file(field, designID): """ string representation of targets_clean file for field within fiveplates_field_files zip file. Parameters ---------- field : str identifier of field, e.g. 'GG_010' """ return f'{field}_des{designID}_targets_clean.txt'
c6e5c60ad08aa3e4162700f3d48e58d35a57486e
3,642,856
import itertools def setup_figure(diff=False): """Set diff to True if you want an additional panel showing pair-wise differences in accuracy""" fig = plt.figure(figsize=(2*3.385, 2*3)) # two column figure for bio-informatics plt.subplots_adjust(left=0.15, bottom=0.1, right=0.98, top=0.93, wspace=0.05, hspace=0...
6c28eb8fd9f633029fad707bdfee8806fa6a3b72
3,642,857
def load_axon_morphometrics(morphometrics_file): """ :param morphometrics_file: absolute path of file containing the morphometrics (must be .csv, .xlsx or pickle format) :return: stats_dataframe: dataframe containing the morphometrics """ # If string, convert to Path objects morphometrics_f...
b89bdac95660fd6c6e84bfcace4125d2840347ca
3,642,858
def get_input_costs( inputs, cost_class="monetary", unit="billion_2015eur", mapping=COST_NAME_MAPPING, **kwargs ): """ Get costs used as model inputs """ costs = {} for var_name, var_data in inputs.data_vars.items(): if "costs" not in var_data.dims or not var_name.startswith("cost"):...
02671abda50889bd51fb91a5629b718882434745
3,642,859
import gettext def render_template(language, context, data, template): """Renders HTML display of metadata XML""" env = Environment(extensions=['jinja2.ext.i18n'], loader=FileSystemLoader(context.ppath)) env.install_gettext_callables(gettext, ngettext, newstyle=True) template_f...
6c19a53c1038681c2f5f4d014ec4ed2aae9a50af
3,642,860
def ht_26(): """Making one Hash table instance with 26 key val pairs inserted.""" ht = HashTable() count = 1 for char in letters: ht.set(char, count) count += 1 return ht
8ab9d1b887da2c9719a1b23d2817b66827b7cc3c
3,642,861
import time def get_session(uuid): """ Api.get_session method returns: [uuid, users, payload, state, ts] 200 -- session created 400 -- wrong arguments 403 -- wrong authorization 404 -- session not found 500 -- internal error """ conn = conn_get() session = database.get_ses...
5657a53dc60b8d8743ccaac79041208c11caa07c
3,642,862
from typing import Iterable import io def fetch_data( indicator: WorldBankIndicators, country_names: Iterable[str], fill_missing=None ) -> pd.DataFrame: """ Fetch data from the market_data_cache collection (not to be confused with the market_quote_cache collection) and ensure the specified countries a...
8f0778aa28acb4fefeaf1d889d1650994357a787
3,642,863
from . import authinfos def _(dbmodel, backend): """ get_backend_entity for Django DbAuthInfo """ return authinfos.DjangoAuthInfo.from_dbmodel(dbmodel, backend)
fa0529b038e4321b2f7e535afb82d16455ef4853
3,642,864
def wavelen_diversity_doppler_est(echo, prf, samprate, bandwidth, centerfreq): """Estimate Doppler based on wavelength diversity. It uses slope of phase of range frequency along with single-lag time-domain correlator approach proposed by [BAMLER1991]_. Parameters ...
d1fe5cb45b9e850fe4da83700fc061e715c76502
3,642,865
def _parse_line(line): """ Parse node string representation and return a dict with appropriate node values. """ res = {} if 'leaf' in line: res['is_leaf'] = 1 res['leaf_val'] = _parse_leaf_node_line(line) else: res['is_leaf'] = 0 res['feature'], res['threshold']...
014c6d2e9d61798d55af2725b79ff404f9aa7ff3
3,642,866
from typing import Optional def generate_richcompare_wrapper(cl: ClassIR, emitter: Emitter) -> Optional[str]: """Generates a wrapper for richcompare dunder methods.""" # Sort for determinism on Python 3.5 matches = sorted([name for name in RICHCOMPARE_OPS if cl.has_method(name)]) if not matches: ...
cbbc66a22ee61ed869331fbecd59eb615588fd48
3,642,867
def display_credentials(): """ Function that displays all saved credentials """ return Credentials.display_credentials()
09e474a5b76ae3224571cf9d2d05ea5811e7fbf1
3,642,868
def render_diff_report(): """ Render a summary of the diffs found and/or changed. Returns a string. Dependencies: config settings: action, templates, report_order globals: diff_dict, T_NAME_KEY modules: nori """ if nori.core.cfg['action'] == 'diff': diff_report = ...
da02e6b9dee4424d217d0f0839938a1aff9250df
3,642,869
def get_step_handler_for_gym_env(gym_env_name: str, cfg: Configuration) -> StepRewardDoneHandler: """Return an example step handler for the given gym environemtn name, that uses the given config file.""" if gym_env_name == 'Acrobot-v1': handler = AcrobotStepHandler(cfg) elif gym_env_name == 'Ca...
51164ee7c3da5184f221d1e658c7e1ddc73585de
3,642,870
import traceback def get_module(mod_name): """Import module and return.""" try: return import_module(mod_name) except ImportError: logger.error('Failed to import module "%s".' % mod_name) logger.error(traceback.format_exc()) raise
7cb81ff17f3d49bee3d53549e415c14ff4c13512
3,642,872
def sort_ranks(ranks): """Sort ranks by MAIN_RANKS order. Parameters ---------- ranks Ranks to sort Returns ------- Sorted ranks """ ret = False ranks = list(ranks) if not isinstance(ranks, list) else ranks if len(ranks) > 0: ret = [rank for rank in VA...
e86b985a83153c46f53d7d31f849d1c5c10a6d66
3,642,873
def formalize_rules(list_rules): """ Gives an list of rules where facts are separeted by coma. Returns string with rules in convinient form (such as 'If' and 'Then' words, etc.). """ text = '' for r in list_rules: t = [i for i in r.split(',') if i] text +=...
d8fbb024f38ae097efa42f95efe6b5d3b5adbd71
3,642,874
def filenames_to_labels(filenames, filename_label_dict): """Converts filename strings to integer labels. Args: filenames (List[str]): The filenames of the images. filename_label_dict (Dict[str, int]): A dictionary mapping filenames to integer labels. Returns: ndarray: Integer labels """ re...
7dad11665aa3858dac7cd91757367f4ab72629cb
3,642,875
def load_model(): """ 保存した提供されているモデルを読み込む Returns ---------- model 提供されたmodel tokernizre 提供されたヤツ(よくわかってない) """ with open(MODEL_DIR + 'model.pickle', 'rb') as f: model = pick.load(f) with open(MODEL_DIR + 'tokenizer.pickle', 'rb') as f: tokenizer = pic...
abea695c9e56af585e37694b8a022b8634ccfe79
3,642,876
from datetime import datetime def post(post_id): """View function for post page""" # Form object: `Comment` form = CommentForm() # form.validate_on_submit() will be true and return the # data object to form instance from user enter, # when the HTTP request is POST if form.validate_on_subm...
28a5e611e370a33a609cabb4d3ec827284911ccc
3,642,877
def pipe(val, *funcs): """Pipe a value through a sequence of functions I.e. ``pipe(val, f, g, h)`` is equivalent to ``h(g(f(val)))`` >>> double = lambda i: 2 * i >>> pipe(3, double, str) '6' """ if not funcs: raise PipeNotGivenAnyFunctions if any_is_async(funcs): return...
c2815c7842df2a1d1e07a628b613da0a8ffd35f5
3,642,878
def do_query(method, query, values): """Executes a query on a DFP API method, returning a list of results.""" # Trap exceptions here instead of in caller? statement = dfp.FilterStatement(query, values) data = [] while True: response = method(statement.ToStatement()) if 'results' in response: d...
3b53e992e4cb49b1814593147826f3d3b4e2bfa8
3,642,879
def markdown_format(text): """ The outside param 'name' is similar to "tag" (in 'usage') which it'll determines how you use it, e.g. {{ THING | FILTER }}. Just a reminder for tag, {% my_post_count %} for filter, {{ post.body | truncatewords:30 }} ...
663781e441b305a26bb0d85fb45302539159aa92
3,642,880
from typing import Iterable from typing import List def group_by_instance_type( jobs: Iterable[JobConfiguration], ) -> List[List[JobConfiguration]]: """ Group job-configuration into different queues depending on which instance each job should be run. This returns a list of the different queues. >...
8c9baf76de4089972c87f7f71b66abec236e23d3
3,642,882
import scipy def integral_func(phi, th1, n): """ Used in computing the continuous hypersphere cap intersection below. """ return np.sin(phi)**(n-2) * scipy.special.betainc( (n-2)/2 , 1/2, 1-( (np.tan(th1))/(np.tan(phi)) )**2 )
f086da8f5086d13abfced0c05b41d419d4e7d6b0
3,642,883
def test_model(image_path, class_names, img_height, img_width): """测试你的模型""" img = keras.preprocessing.image.load_img(image_path, target_size=(img_height, img_width)) # 将图片加载为PIL格式 input_array = keras.preprocessing.image.img_to_array(img) # 将PIL映像实例转换为Numpy数组 input_array = np.array([input_array]) # 来...
5f661c231dbc459e9e6d24f9ddeecbed15dc0e0d
3,642,884
def order(order_id,complete): """ Charge completion return URL. Once the customer is redirected back to this site from the authorization page, we search for the charge based on the provided `order_id`. """ return render_template( "complete.html", order_id=order_id, comp...
c7d7d385c23ef24748d5b4e847aaf9acd2212cbd
3,642,885
import logging def load_dimension_subdag( parent_dag_name, task_id, redshift_conn_id, *args, **kwargs): """ A python function with arguments, which creates a dag :param parent_dag_name: imp ({parent_dag_name}.{task_id}) :param task_id: imp {task_id} :param redshift_...
d68348b51aef7ad38999b2383f41721a178af451
3,642,886
from typing import List def standardize_measurements_lastref(measurements: List[Measurement], remove_ref: bool = True) \ -> List[Measurement]: """ Sets the standardization of all measurement to the Reference Measurement before """ last_null_meas = None clean_measurements = [] for measurement ...
34c73375fcada6a19e9c7e876b252f44fc6f9415
3,642,890
from typing import get_args import torch def build_train_valid_test_data_iterators( build_train_valid_test_datasets_provider): """XXX""" args = get_args() (train_dataloader, valid_dataloader, test_dataloader) = (None, None, None) print_rank_0('> building train, validation, and test datasets ...
1bf5c79519df289f88ab5372c6ccb963a77ce5cd
3,642,892
def width(): """Get console width.""" x, y = get() return x
a6090038a4c97e215e57e0f7966ec41c09682f90
3,642,894
import yaml def load_yaml_config(path): """returns the config parsed based on the info in the flags. Grabs the config file, written in yaml, slurps it in. """ with open(path) as f: config = yaml.load(f, Loader=yaml.FullLoader) return config
0ee100a6e4d25881f8b8ab4ced723f600e878e28
3,642,895
def home(request): """View function for home page of site.""" return laboratorio_list(request)
a06bcbdb2b7edb79ee1d30cd69329742b24f2f49
3,642,897
def scan_armatures(context): """ scans the selected objects or the scene for a source (regular) armature and a destination (Make Human) armature """ src = ( scan_for_armature(context.selected_objects) or scan_for_armature(context.scene.objects) ) dst = ( s...
a613c39767280919a684dcf8eaa4e537ffc2ebb3
3,642,898
def populate_instance(msg, inst): """ :param msg: contains the values to use to populate inst. :param inst: message class instance to populate. :return: an instance of the provided message class, with its fields populated according to the values in msg """ return _to_inst(msg, type(inst).__name_...
7a148629ad178be632c9388fc536e7fea02c44ed
3,642,899
def create_event(type_, source): """Create Event""" cls = _events.get(type_, UnknownEvent) try: return cls(type=type_, **source) except TypeError as e: raise TypeError(f'Error at creating {cls.__name__}: {e}')
263fc768d94db5ae9cb0acb8565c01337ffb56c6
3,642,901
from typing import Iterable from typing import Callable from typing import List from typing import Awaitable import asyncio def aggregate_policy( policies: Iterable[PermissionPolicy_T], aggregator: Callable[[Iterable[object]], bool] = all ) -> PermissionPolicy_T: """ 在默认参数下,将多个权限检查策略函数使用 AND 操作符连接并返回单...
c0fa2ef66ba71deba88ca4e9debbb521ba49fe82
3,642,905
def optionally_load_system_paasta_config( path: str = PATH_TO_SYSTEM_PAASTA_CONFIG_DIR, ) -> "SystemPaastaConfig": """ Tries to load the system paasta config, but will return an empty configuration if not available, without raising. """ try: return load_system_paasta_config(path=path) ...
7309d28ab156572d1b3cdbf347d4979f3ee607d8
3,642,906
def get_sage_bank_accounts(company_id: int) -> list: """ Retrieves the bank accounts for a company in Sage One **company_id** The Company ID """ config = get_config() # Get the config sage_client = SageOneAPIClient(config.get("sageone", "url"), config.get("sageone", "api_key"), config.get("sage...
a3684d5a3b06944ba297f95b5498d61f7281c40c
3,642,907
def compute_fstar(tarr, mstar, index_select, index_high, fstar_tdelay): """Time averaged SFH that has ocurred over some previous time period fstar = (mstar(t) - mstar(t-fstar_tdelay)) / fstar_tdelay Parameters ---------- tarr : ndarray of shape (n_times, ) Cosmic time of each simulated snap...
89ef08ee08f41fa6b7931ebdbbb3611bda6346ae
3,642,908
def notification_error(code: str, search_id: str, status_code, message: str = None): """Return to the event listener a notification error response based on the status code.""" error = CALLBACK_MESSAGES[code].format(search_id=search_id) if message: error += ' ' + message current_app.logger.error(...
6522023ad36f7164a2c721493d38d3cc0b5d4690
3,642,909
def arccos(x: REAL) -> float: """Arc cosine.""" return pi/2 - arcsin(x)
1829e6d777c32172afee7e8608d5d1034458660f
3,642,911
import requests def isLinkValid(test_video_link): """def isLinkValid(test_video_link): -> test_video_link check if youtube video link is valid.""" try: data = requests.get("https://www.youtube.com/oembed?format=json&url=" + test_video_link).json() if data == "Not Found": retu...
0af4f8c1d05f2b98d046d63d5eaf39f679a37818
3,642,912
import time import calendar def _strptime(data_string, format='%a %b %d %H:%M:%S %Y'): """Return a 2-tuple consisting of a time struct and an int containing the number of microseconds based on the input string and the format string.""" for index, arg in enumerate([data_string, format]): if not...
bd222fde85a3db2bdad28394f001ed74b1d68622
3,642,913
def to_simple_rdd(sc, features, labels): """Convert numpy arrays of features and labels into an RDD of pairs. :param sc: Spark context :param features: numpy array with features :param labels: numpy array with labels :return: Spark RDD with feature-label pairs """ pairs = [(x, y) for x,...
87afaae6214bedbde60d46e21d8ea82d644a0ca1
3,642,914
def add_decimal(op1: Decimal, op2: Decimal)-> Decimal: """ add :param op1: :param op2: :return: """ result = op1 + op2 if result > 999: return float(result) return result
d05501daf67845eb339c7103fad02c7d0e2f8dc9
3,642,915
def freenas_spec(**kwargs): """FreeNAS specs.""" # Setup vars from kwargs builder_spec = kwargs['data']['builder_spec'] bootstrap_cfg = None builder_spec.update( { 'boot_command': [ '<enter>', '<wait30>1<enter>', 'y', ...
ffe666fd48b6d545e44389ae0413bc1f0c29c44e
3,642,917
def checksum(routine): """ Compute the M routine checksum used by ``CHECK1^XTSUMBLD``, implemented in ``^%ZOSF("RSUM1")`` and ``SUMB^XPDRSUM``. """ checksum = 0 lineNumber = 0 with open(routine, 'r') as f: for line in f: line = line.rstrip('\r\n') lineNumber += 1 # ignore the second ...
ca93bbf29967a90b22de007f84ba5ec3898a4f1a
3,642,918
def nusdas_parameter_change(param, value): """ def nusdas_parameter_change() """ # Set argtypes and restype nusdas_parameter_change_ct = libnus.NuSDaS_parameter_change nusdas_parameter_change_ct.restype = c_int32 nusdas_parameter_change_ct.argtypes = (c_int32,POINTER(c_int32)) icond...
cea9011eb807c6281c9e3d07b640860ee085d1ad
3,642,919
def validate_retention_time(retention_time): # type: (str) -> str """Validate retention_time. If -1, return string, else convert to ms. Keyword arguments: retention_time -- user configured retention-ms, pattern: %d%h%m%s%ms Return: retention_time -- If set to "-1", return it """ if ret...
8f7c701f7e2f2e8e5fa708fef80f04804964928c
3,642,920
import re def is_sale(this_line): """Determine whether a given line describes a sale of cattle.""" is_not_succinct = len(this_line.split()) > 3 has_price = re.search(r'[0-9]+\.[0-9]{2}', this_line) return bool(has_price and is_not_succinct)
382da3d9a1690950e64a29c6f2fcd54e062eb600
3,642,921
def extract_policy(env, v, gamma = 1.0): """ Extract the policy given a value-function """ policy = np.zeros(env.env.nS) for s in range(env.env.nS): q_sa = np.zeros(env.env.nA) for a in range(env.env.nA): q_sa[a] = sum([p * (r + gamma * v[s_]) for p, s_, r, _ in env.env.P[s][a]])...
2342a531e0fa29e4b7bb1946aa30cbe8b739b688
3,642,922
def generate_parameters(var): """ Defines a distribution of parameters Returns a settings dictionary var is an iterable of variables in the range [0,1) which we can make use of. """ var = iter(var) model={} training={} settings = {'model':model, 'training':training} # ma...
8336a7cb19db62fa95b3b0d131f2ca6f0e919e39
3,642,923
def sourceExtractImage(data, bkgArr=None, sortType='centre', verbose=False, **kwargs): """Extract sources from data array and return enumerated objects sorted smallest to largest, and the segmentation map provided by source extractor """ data = np.array(data).byteswap().newbyteord...
6fec63cc6e154f874ae3a46a373fb2d7ceff2423
3,642,924
from typing import Optional def convert_one_fmt_off_pair(node: Node) -> bool: """Convert content of a single `# fmt: off`/`# fmt: on` into a standalone comment. Returns True if a pair was converted. """ for leaf in node.leaves(): previous_consumed = 0 for comment in list_comments(leaf...
1ebbb67406a5d1de4e51c5a516b15750b0205567
3,642,926
def validate_uuid4(uuid_string): """ Source: https://gist.github.com/ShawnMilo/7777304 Validate that a UUID string is infact a valid uuid4. Luckily, the uuid module does the actual checking for us. It is vital that the 'version' kwarg be passed to the UUID() call, otherwise any 32-characterhex strin...
56bf751cddd412ddc234f371a17019ee9192aefe
3,642,927
def check_sp(sp): """Validate seasonal periodicity. Parameters ---------- sp : int Seasonal periodicity Returns ------- sp : int Validated seasonal periodicity """ if sp is not None: if not is_int(sp) or sp < 1: raise ValueError("`sp` must be a p...
475a56584915bc4b67663b3460959ca5e807ae06
3,642,928
def api_error_handler(func): """ Handy decorator that catches any exception from the Media Cloud API and sends it back to the browser as a nicely formatted JSON error. The idea is that the client code can catch these at a low level and display error messages. """ @wraps(func) def wrapper(*a...
6e03a5dc081a5aed7436a948194965d1e61504d4
3,642,929
def gen_data(data_format, dtype, shape): """Generate data for testing the op""" input = random_gaussian(shape, miu=1, sigma=0.1).astype(dtype) head_np = input if data_format == "NC1HWC0": channel_dims = [1, 4] elif data_format == DEFAULT: channel_dims = [1] else: channel_...
6fbc40b4879abec7a2f30c7f763102f51215e079
3,642,930
from typing import Any import pydantic import functools import inspect import pathlib import copy def clean_value_name(value: Any) -> str: """Returns a string representation of an object.""" if isinstance(value, pydantic.BaseModel): value = str(value) elif isinstance(value, float) and int(value) =...
24635521ee8bd94324c0b29384ba0f0b39060244
3,642,931
def add_line_analyzer(func): """A simple decorator that adds a function to the list of all functions that analyze a single line of code.""" LINE_ANALYZERS.append(func) def wrapper(tokens): return func(tokens) return wrapper
538b6495be88d47b49efcd3ac28bd0b291810587
3,642,932
import hashlib def decode_account(source_a): """ Take a string of the form "xrb_..." of length 64 and return the associated public key (as a bytes object) """ assert len(source_a) == 64 assert source_a.startswith('xrb_') or source_a.startswith('xrb-') number_l = 0 for charac...
5d083adcdd2f64c03c6a2e454b74b4d911381132
3,642,933
def update_epics_order_in_bulk(bulk_data: list, field: str, project: object): """ Update the order of some epics. `bulk_data` should be a list of tuples with the following format: [{'epic_id': <value>, 'order': <value>}, ...] """ epics = project.epics.all() epic_orders = {e.id: getattr(e, ...
948bfaa6e165ac401cfa0244ee6c1b0bcd813493
3,642,934
def calc_precision(output, target): """calculate precision from tensor(b,c,x,y) for every category c""" precs = [] for c in range(target.size(1)): true_positives = ((output[:, c] - (output[:, c] != 1).int()) == target[:, c]).int().sum().item() # print(true_positives) false_positives...
c35c500c786539578c46a8e8c4f6517bf30b4525
3,642,935
def upper_credible_choice(self): """pick the bandit with the best LOWER BOUND. See chapter 5""" def lb(a,b): return a/(a+b) + 1.65*np.sqrt((a*b)/((a+b)**2*(a+b+1))) a = self.wins + 1 b = self.trials - self.wins + 1 return np.argmax(lb(a,b))
20cefd0796f52a78d03b2d38cb74c532a07ec20c
3,642,936
import uuid def get_unique_id(): """ for unique random docname :return: length 32 string """ _id = str(uuid.uuid4()).replace("-", "") return _id
4cf99a919bd0e9672f0b186626df0532cacebaf4
3,642,938
def callback(): """ Step 3: Retrieving an access token. The user has been redirected back from the provider to your registered callback URL. With this redirection comes an authorization code included in the redirect URL. We will use that to obtain an access token. """ # Grab the Refresh and Ac...
76c4bec2c7c2a3433d4ab7665fca9d6829083626
3,642,939
def load_azure_auth() -> AzureSSOClientConfig: """ Load config for Azure Auth """ return AzureSSOClientConfig( clientSecret=conf.get(LINEAGE, "client_secret"), authority=conf.get(LINEAGE, "authority"), clientId=conf.get(LINEAGE, "client_id"), scopes=conf.getjson(LINEAGE, ...
4e7eb1886da496c465db95aa2cee2aec4a107d78
3,642,940
def get_map_zones(map_id): """Get map zones. .. :quickref: Zones; Get map zones. **Example request**: .. sourcecode:: http GET /zones/map/1 HTTP/1.1 **Example response**: .. sourcecode:: json [ { "id": 1, "p1": [0, 0, 0], "p2": [25...
89e60a0fd2e0e2b743aa54cf1debe67e5f860a13
3,642,941
def rgb2he_macenko(img, D=None, alpha=1.0, beta=0.15, white=255.0, return_deconvolution_matrix=False): """ Performs stain separation from RGB images using the method in M Macenko, et al. "A method for normalizing histology slides for quantitative analysis", IEEE ISBI, 2009. dx.doi.org...
bfe19ef7882ac713534d28c0d636bda086cf95c6
3,642,942
import inspect from typing import Any import functools from typing import OrderedDict import torch def validated(base_model=None): """ Decorates an ``__init__`` method with typed parameters with validation and auto-conversion logic. >>> class ComplexNumber: ... @validated() ... def __...
af599bff5aa5d1efeb44297c117685609842a212
3,642,943
from pathlib import Path def make_header_table(fitsdir, search_string='*fl?.fits'): """Construct a table of key-value pairs from FITS headers of images used in dolphot run. Columns are the set of all keywords that appear in any header, and rows are per image. Inputs ------ fitsdir : string or...
3d5d10b73a8e76abedcf85ef97a9854920996a0a
3,642,944
def cars_to_people(df,peoplePerCar=1.7,percentOfTransit=.005): """ args: demand dataframe, people/car float, % of transit floats returns: people demand dataframe by terminal and arrival/departure """ columns = ['Arrive_A','Arrive_B','Arrive_C','Arrive_D','Arrive_E', 'Depart_A','Depart...
54672baacf10683a3d7224ee8672e08ee1574b30
3,642,946
import re def get_dup_key_val(errmsg): """Return the duplicate key referenced in an error message. Parameters ---------- errmsg : |str| A pymongo `DuplicateKeyError` message. Returns ------- |dict| The key(s) and value(s) of the duplicate key. Example ------- ...
14cbf0f51a89c4b76c5a1d363e2ef1dfe994ede6
3,642,947
def worker(vac_flag,cache_dict,mylock): # Used in multiprocess_traditional_evaluate() #20220204 """thread worker function""" this_key = tuple(vac_flag.squeeze().cpu().numpy()) if(this_key in cache_dict): print('Found in cache_dict') [total_cases, case_rate_std] = cache_dict[this_key] el...
d88e92c7cd3c5bf85389e83440dc7752719d66c0
3,642,948
from kubernetes import client as k8s_client from typing import Optional from typing import Dict def use_k8s_secret( secret_name: str = 'k8s-secret', k8s_secret_key_to_env: Optional[Dict] = None, ): """An operator that configures the container to use k8s credentials. k8s_secret_key_to_env specifies a ...
2e88ad765322752ba7417d865f0ea60879c4bafe
3,642,949
def reorder_point(max_units_sold_daily, avg_units_sold_daily, max_lead_time, avg_lead_time, lead_time): """Returns the reorder point for a given product based on sales and lead time. The reorder point is the stock level at which a new order should be placed in order to avoid stock outs. Args: max_...
876544b5bce39342fb753f6a1bf33913fae6e33d
3,642,951
def get_total_value_report(total_value): """"TBD""" # Total value report currency = CURRENCY slack_str = "*" + "Total value report" + "*\n>>>\n" slack_str = slack_str + make_slack_etf_chain_total(total_value, currency) """ sendSlackNotification('etf', slack_str, "ETF Notification", ':chart_w...
be1a9ff18c2faf37ae7b58be34f15eb454c72d62
3,642,952
def verify_count_responses(responses): """ Verifies that the responses given are well formed. Parameters ---------- responses : int OR list-like If an int, the exact number of responses targeted. If list-like, the first two elements are the minimum and maximum (inclusive) range ...
63fbd00bc26fee8eb960f389d5d56178e90ff7ae
3,642,953
def _subtract(supernet, subnets, subnet_idx, ranges): """Calculate IPSet([supernet]) - IPSet(subnets). Assumptions: subnets is sorted, subnet_idx points to the first element in subnets that is a subnet of supernet. Results are appended to the ranges parameter as tuples of in format (version, first...
a7c738b5ddab1ed896677a011029a00af5779bcd
3,642,954
def commiter_factory(config: dict) -> BaseCommitizen: """Return the correct commitizen existing in the registry.""" name: str = config["name"] try: _cz = registry[name](config) except KeyError: msg_error = ( "The commiter has not been found in the system.\n\n" f"T...
0e001652e0698efe981bf7dfe0cc69ce337e6f97
3,642,955
def get_s3_items_by_type_from_queue(volume_folder): """ Load redis queue named "volume:<volume_folder>", and return dict of keys and md5s sorted by file type. Queue will contain items consisting of newline and tab-delimited lists of files. Returned value: {'alto': [[s3_key, md5]...
7afece0e2f1f8d0863873f1ef987790c2eb1dad3
3,642,958
def strip_spectral_type(series, return_mask=False): """ Strip spectral type from series of string Args: series (pd.Series): series of object names (strings) return_mask (bool): returns boolean mask True where there is a type Returns: no_type (pd.Series): series without spectral ...
65b91749742b229637819582b1158554b1a457ea
3,642,959
def already_in_bioconda(recipe, meta, df): """ Does the package exist in bioconda? """ results = _subset_df(recipe, meta, df) build_number = int(meta.get_value('build/number', 0)) build_results = results[results.build_number == build_number] channels = set(build_results.channel) if 'bioc...
0a7402e85a36f2f97a36a91bc379077f01ab22f5
3,642,960
def expand_groups(node_id, groups): """ node_id: a node ID that may be a group groups: store group IDs and list of sub-ids return value: a list that contains all group IDs deconvoluted """ node_list = [] if node_id in groups.keys(): for component_id in groups[node_id]: no...
4c4b9c569a85396f201c589635b6ecea3807ddc2
3,642,961
def _preservation_derivatives_query(storage_service_id, storage_location_id, aip_uuid): """Fetch information on preservation derivatives from db. :param storage_service_id: Storage Service ID (int) :param storage_location_id: Storage Location ID (int) :param aip_uuid: AIP UUID (str) :returns: SQLA...
a4ab7d6fc011c3ffc3678388b221514f38ecb5db
3,642,962