content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import List def update_sample_group_attachments(user: User, sample_group: SampleGroup, samples: List[Sample]) -> SampleGroup: """ Make the only samples attached to a group those in sample_ids :param user: :param sample_group: :param samples: :return: """ if is_write_permitt...
fe94c1a6552578c8e2f3c432a2c0750f189c3b96
3,618,672
import requests def get(url, params, proxies, headers): """Send a request with the GET method.""" response = requests.get(url, params=params, proxies=proxies, headers=headers) return response
a481a91e5f3fc71f88de8d84efaac3dd666c302e
3,618,675
from typing import Union from typing import List def _parse_input(ip: Union[List, str], network: str = '255.255.255.255', workers: int = default_processes): """ convert the ip, network into a structure containing address/masks """ # if this is list split it into worker tasks if isinstance(ip, list): ...
a53eafeeb63a0bfdfc08dc4a51a8276f68faf9cc
3,618,676
from typing import Union from typing import Any async def send( bot: "Bot", event: Event, message: Union[str, Message, MessageSegment], at_sender: bool = False, reply_message: bool = False, **params: Any, ) -> Any: """้ป˜่ฎคๅ›žๅคๆถˆๆฏๅค„็†ๅ‡ฝๆ•ฐใ€‚""" event_dict = event.dict() params.setdefault("det...
0eb27892ee3e0c712e881b4afba7a3ebb45ad72c
3,618,677
def remove_duplicate_vertices_cmd(): """ Remove duplicate vertices a CityJSON file. Only the geometry vertices are processed, and not those of the textures/templates. """ def processor(cm): print_cmd_status('Remove duplicate vertices') cm.remove_duplicate_vertices() retur...
193efbabe27b571b31207e0693a373cca0f77960
3,618,678
def account_ids_equal(account_id_a, account_id_b): """ Compare two account IDs while discarding the account prefix :return: Whether the account IDs are equal :rtype: bool """ return account_id_a[-60:-8] == account_id_b[-60:-8]
4f26d7db93fa06ce834487d1e6876c8fe8602b18
3,618,679
def action_from_trinary_to_env(action) -> int: """ Maps trinary model output to int action understandable by env """ assert action in (0, 1, 2), f'Wrong action: {action}' return { 0: 0, 1: 2, 2: 5 }[action]
e2a7cd3d6c018a7112e2304f2910781b665a8247
3,618,681
def hex_value(image): """ Get the dice value of a hex. :param image: The game image. :return: An int of the hex value or None if a invalid value is found. """ grey = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) _, thresh = cv2.threshold(grey, 200, 255, cv2.THRESH_BINARY_INV) value_contour = f...
f45555a0909d4fb091b34e159cb46e8d704fe816
3,618,682
def get_market_name(market: str = None) -> str: """ ์ž…๋ ฅ๋œ ๊ฐ’์— ๋Œ€ํ•œ ๋งˆ์ผ“์˜ ์ข…๋ฅ˜๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜ Parameters ---------- market: str ๋งˆ์ผ“์— ๋Œ€ํ•œ ์•ฝ์–ด ํ˜น์€ ๋งˆ์ผ“์˜ ํ’€๋„ค์ž„ Returns ------- str ์ž…๋ ฅ๋œ ๊ฐ’์— ๋Œ€ํ•œ ๋งˆ์ผ“ ํƒ€์ž… Raises ------ ValueError ์ž…๋ ฅ๋œ ๊ฐ’์— ๋Œ€ํ•œ ๋งˆ์ผ“์˜ ํƒ€์ž…์„ ์•Œ ์ˆ˜ ์—†์„๋•Œ """ if market: ...
c7c60dce972be5aa07dfc19046b769d64524fe8d
3,618,684
def _get_registered_typelibs(match='HEC River Analysis System'): """ adapted from pywin32 # Copyright (c) 1996-2008, Greg Stein and Mark Hammond. """ # Explicit lookup in the registry. result = [] key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, "TypeLib") try: num = 0 ...
d4c809c95f4e4b6ace59bda6cb4199cd8d7170fd
3,618,685
def contact(): """ Function is invoked when requests is made to url: dommainname/contact :return: a rendered template for the about page """ # Accesses the contact form and renders it in the contact html file # Submits the filled form and sends the values in a mail to a configured e...
1a74ae188f1131d16e53414b5a03c09ba3cc63d1
3,618,686
import re def convert_rst_formatting(text): """ Convert rst syntax for formatting to markdown in a given text. """ # Remove :class:, :func: and :meth: markers. To code-links and put double backquotes # (to not be caught by the italic conversion). text = _re_func_class.sub(r"[``\1``]", text) ...
c2d5fce2a8cc1b3efc764af917b8c6a69b6097dc
3,618,687
def get_setup_file(): """Serve the SSDP setup file.""" out = "<?xml version=\"1.0\"?>\n" + \ "<root xmlns=\"urn:schemas-upnp-org:device-1-0\">\n" + \ "<specVersion>\n" + \ "<major>1</major>\n" + \ "<minor>0</minor>\n" + \ "</specVersion>\n" + \ "<URLB...
961924ce9ebb77b92fb31e587f80aca31cc30c11
3,618,688
def ofxPluginPath(): """ nuke.ofxPluginPath() -> String list List of all the directories Nuke searched for OFX plugins in. @return: String list """ return list()
9a8b7b3f69047818e7a3a31e0ff8bca50e57ed4c
3,618,689
def index_sentence_with_vocabulary(sentence, word2id, sequence_length=None, knowledge_path=None): """index sentence with vocabulary, return list of index""" # print("index_sentence_with_vocabulary:",knowledge_path) result_list = tokenize_sentence(sentence, knowledge_path=knowledge_path) result_list = re...
6d5535e85861b8ca869b17c8d1b0f54bd600e71a
3,618,690
import logging def set_android_token(request): """ Android's push notification tokens. Not sure why I can't find this function in the Android code. """ user = get_user(request) tokens = MUserNotificationTokens.get_tokens_for_user(user.pk) token = request.POST['token'] logging.use...
bcde1c1a25d9e37c84c254bdd225616fb223f237
3,618,691
import hashlib def file_md5(file_path: str) -> str: """Compute the md5 hex digest of a binary file with reasonable memory usage.""" md5_hash = hashlib.md5() with open(file_path, 'rb') as f: while True: data = f.read(65536) if not data: break md5_...
ac0576e901ca3205f824a599566e628ee29f5a7c
3,618,692
def get_parameters(model, unique_variance=False): """ Returns the true parameters of a given model. :param model: Model ID. :param unique_variance: indicates whether the variance should be unique :return: Mixture weights, means and covariances. """ if model == Model.M1: return get_p...
96e7fc6f82e673f62690409e9a4bf19354d13e83
3,618,693
import json import time def collection(request, *args, **kwargs): """ REST main collection request handler. **Supported HTTP methods:** * GET * DELETE * PUT * POST :param request: Request object :param args: arguments :param kwargs: Dictionary (keyword arguments). Known kwar...
de46656e8a67272225f902179f4b01d4cd3e982c
3,618,694
from .centrography import mean_center import numpy def _(shape: numpy.ndarray): """ Handle point arrays or bounding boxes """ if shape.ndim == 2: return mean_center(shape).squeeze() elif shape.ndim == 1: assert shape.shape == (4,) xmin, ymin, xmax, ymax = shape ret...
af866f85419d9a0d0cb9857f2cf4e7047afb38cb
3,618,695
import math def mkt(vdf, column: str, ts: str, p=1000, alpha: float = 0.05): """ --------------------------------------------------------------------------- Mann Kendall test (Time Series trend). \u26A0 Warning : This Test is computationally expensive. It is using a CROSS JOIN during the comput...
f78c3acb1eba4a854b7542e01bc3b7704a96140d
3,618,696
def where2d(image): """ numpy.where for 2D matrices. :param image: Input images :return: Coordinate list where image is non-zero >>> where2d(np.array([[ 0, 0, 0], ... [ 0, 1, 1], ... [ 0, 0, 0]])) array([[1, 1], [1, 2]]) """ ...
be6041c0f4e7bd1ff6d96b1828a4d0982fc8458c
3,618,698
def continue_prompt(message=''): """Continue prompt to verify that a user wants to continue or not. This prompt's purpose is to prevent accidental changes that are difficult to reverse. Keyword Args: message (str): The message to display to the user Returns: bool: If the user want...
1c8ec8a222976ebf8d02f5690b52da75c2b20f81
3,618,699
def split_validation(dataset, val_fraction, _rnd): """Randomly split a dataset into two non-overlapping new datasets. Arguments: dataset (Dataset): Dataset to be split val_fraction: Fraction of dataset that should be in the validation split _rnd: Random state to determine sp...
59e084a9b434e6890d24c74df9104a949528f85d
3,618,700
def pl_to_eng(unit: str) -> str: """Converts Polish terminology to English""" switcher = { "pikinier": "spear", "miecznik": "sword", "topornik": "axe", "lucznik": "archer", "zwiadowca": "spy", "lekki kawalerzysta": "light", "lucznik na koniu": "marcher", ...
7d9634c554cc84663b1c7fb787b070d535747d36
3,618,702
def is_meta_resource_type_mutable(context, meta_resource_type): """Return True if the meta_resource_type is mutable in this context.""" if context.is_admin: return True if context.owner is None: return False # (lakshmiS): resource type can exist without an association with # namesp...
54e6e1333c8e3875efd2f1c049eb92962a2fe3e9
3,618,703
def has_at_least_one_key(*keys): """Validator that at least one key exists.""" def validate(obj): """Test keys exist in dict.""" if not isinstance(obj, dict): raise vol.Invalid('expected dictionary') for k in obj.keys(): if k in keys: return obj ...
f9744c73616915881487104752d647fd31740478
3,618,704
import requests from datetime import datetime import pandas def get_site_data(site_code, parameter_code, as_dataframe=True, start_date=None, end_date=None, dam_site_location='head'): """Fetches site's parameter data Parameters ---------- site_code : str The LCRA site code (fo...
0138f1bee656e7731fea1d6c12559656ddb9416c
3,618,706
def get_auth_realm(url, auth_info, scheme=None): """Determine an authentication realm identifier from a HTTP response. Examples -------- Robustly determine a realm identifier for any URL:: >>> url, props = probe_url('https://fz-juelich.sciebo.de/...') >>> get_auth_realm(url, props.get('a...
ec8000ae28c8d8a52afbba8004937a709980f59b
3,618,708
def is_ok(resp: Response) -> bool: """ is_ok returns True is the API responded with 200 and the content type is JSON. """ return ( resp.headers["content-type"] == "application/json" and resp.status_code == codes.ok )
08690068ed3da58b030373afb9e86f0196504511
3,618,709
def pretty_size(size, sep: str = ' ', lim_k: int = 1 << 10, lim_m: int = 10 << 20, plural: bool = True, floor: bool = True) -> str: """Convert a size into a more readable unit-indexed size (KiB, MiB) :param size: integral value to convert :param sep: the separator char...
3357067ed4686ab450e90e64257104d143481805
3,618,710
def export_summary(request, qid, answer_filter=None): """ For a given questionnaire id, generate a CSV containing a summary of answers for all subjects. qid -- questionnaire_id answer_filter -- custom filter for the answers. If this is present, the filter must manage access. """ if answer_fi...
2227f006907d0ab47f2fe44c178eb2323e3bab98
3,618,711
def get_net(config): """Given the configuration, call a function to create the network object.""" if 'Six_Bus' in config.env_name: return six_bus(config.vn_high, config.vn_low, config.length_km, config.std_type, config.battery_locations, config.init_soc, con...
71eaedc994d8b77331140c16e4346d2afcee63e6
3,618,712
from typing import List import tokenize def last_bracket(tokens: List[tokenize.TokenInfo], index: int) -> bool: """Tells whether the given index is the last bracket token in line.""" return only_contains( tokens[index + 1:], NEWLINES.union({tokenize.COMMENT}), )
a6114e4a3e8a604a6e971e0e874bfa498236c1db
3,618,713
from typing import Tuple import time def run_kernel_pca(X_train: np.ndarray, X_test: np.ndarray, kernel: str, d: int, sigma: float ) -> Tuple[np.ndarray, float]: """ Run Kernel PCA experiment. Parameters -------...
6dec1fc9a3de6db8b4a25a803b180c4dec600dac
3,618,714
def lint(path_list, excludes=''): """Runs pylint on all files in path list and returns results dictionary CATCHES: AssertionError - raised or thrown by _lint_file due to unexpected pylint output Args: path_list ------ a list of pathlib.Path objects representin...
7bf708fbc37fe4e9598c19ee65c8b4549096ce36
3,618,715
import warnings def reduce_array(x, reduction='mean', axis=2, weights=None): """ Auxiliary method to perform one of the following operations: nanmean, nanmax, nanmedian, nanmin, nanstd, and, or, wmean. Args: ---- x: `ndarray` input array in which to perform the operation reduction...
6ef06a5aeceeda598c8101569c741a996172c274
3,618,716
def jacobi_weights(roots, n, alpha, beta): """Calculate the weight of each root Args: n: the order of the polynomial alpha: the alpha parameter in Jacobi polynomials beta: the beta parameter in Jacobi polynomials """ jacobi_check(n, alpha, beta) jacobi_roots_check(roots, n, ...
59b19b6915b4d7510b5e618bb2363365f3326069
3,618,717
def _get_current_unhelpful(old_formatted): """Gets the data for the past week and formats it as return value.""" final = {} cursor = connection.cursor() cursor.execute( """SELECT doc_id, yes, no FROM (SELECT wiki_revision.document_id as doc_id, SUM(limitedvo...
370106bb07235cfe3c46abb0ae10339933660afd
3,618,718
import re def enforceStringFormat(prompt, regex = None, minLength = None, maxLength = None): """ Enforces a string at a prompt Args: prompt: String for user input prompt regex: regular expression the string should conform to minLength: minimum valid string length maxValue:...
cbf9f98bd82a1237b168fec58665cd7cad03300f
3,618,719
def render_hist( df: pd.DataFrame, x: str, meta: ColumnMetadata, plot_width: int, plot_height: int, ) -> Figure: """ Render a histogram """ if is_dtype(meta["dtype"], Nominal()): tooltips = [ (x, "@x"), ("Count", "@count"), ("Label", "@label"), ] ...
a9808fe2fb4b3e2c052ada04cf30f60e685de818
3,618,720
def describe(a, axis=0, ddof=0, bias=True): """ Computes several descriptive statistics of the passed array. Parameters ---------- a : array_like Data array axis : int or None, optional Axis along which to calculate statistics. Default 0. If None, compute over the whole ...
2024bd904227bb8a0b1c298afb3430c58a4cda1e
3,618,722
import typing def get_translated_text( text: typing.Optional[typing.Union[str, typing.Dict[str, str]]], language_code: typing.Optional[str] = None, default: str = '' ) -> str: """ Return the text in a given language from a translation dictionary. If the language does not exist in ...
31f87023edc8bb8103a3b48b5dd515f75c9d00a8
3,618,723
import requests import re def proc_imgur_url(starturl): """ Process an imgur link """ # If imgur is not in the link, skip it if "imgur.com" not in starturl: return starturl finishedurl = [] regex = r"href\=\"https://i\.imgur\.com\/([\d\w]*)(\.jpg|\.png|\.gif|\.mp4|\.gifv)" tr...
0a026c2473ebfd827439049c1a50e5678c26a638
3,618,724
def handler(service, action): """ Handler method for service operations. """ cmd = 'systemctl {} {}'.format(action, service) return sudo(cmd, pty=False)
daefe974fa3b1c02ff926ae682b50ebc95d82399
3,618,725
from typing import Dict from typing import List from pathlib import Path import yaml def write_commands_instructions( commands_instructions: Dict[str, List[str]], scene_path: Path, index: int ) -> Path: """*Deprecated, use `write_yaml_instructions` instead.* Writes a command instruction `yaml` file. ...
1a0cc75b9bcf269133b799f1abe4b507b2f42c16
3,618,727
import re def replace_simultaneous(s: str, r0: str, r1: str) -> str: """ Replace all instances of `r0` in `s` with `r1` and vice versa. This method does the replacements simultaneously so that, e.g., if you call `replace_simultaneous("apple banana", "apple", "banana")` the result will be `"banana...
bcfe2d13fb3b0c3156e866954d6ddf1a0a02e9fc
3,618,728
def statement_uri_query(db, needle): """Filter Statements by searching for mathich uris. Return value can be used as subquery. """ Statement = db.entities["Statement"] query = orm.select(st for st in Statement for uri in st.uris if uri.uri == needle) return query
c188c968bd705295f111dd06f2ee69e909b799bc
3,618,732
def partition_into_cells(mesh): """ Resolve all-intersections of the input mesh and extract cell partitions induced by the mesh. A cell-partition is subset of the ambient space where any pair of points belonging the partition can be connected by a curve without ever going through any mesh faces. A...
73bb6d9fab212399ae7c9f30431e1ec97aacfdd4
3,618,733
def reshape_2d_scan_for_axis(scan, axis): """Reshape 2d scan for given axis into an actual 2d object. This reshapes images with shape `(398, 1, 430)` into shape `(398, 430)` etc.""" axis = axis_str_to_int(axis) scan = np.copy(scan) if axis == 1: scan = scan.reshape((scan.shape[0], ...
8c246df3f6dad749f31c7b79bf253626d7ea4d83
3,618,734
from typing import Optional from typing import List from typing import Collection def get_positive_samples_in_source_plate(source_plate_uuid: str) -> Optional[List[SampleDoc]]: """Attempt to get a source plate's Result=Positive samples. Arguments: source_plate_uuid {str} -- The source plate UUID for ...
aa47759dd04cd7283de78b068c845c60c26ca8ce
3,618,735
def server_is_exception(server, new_channel): """ Check if server is an exception """ if smtools.CONFIGSM['maintenance']['exception_sp']: for key, value in smtools.CONFIGSM['maintenance']['exception_sp'].items(): if key == new_channel: for server_exception in value: ...
741a29c92a80a31c65a7a278523ef9dc540319ea
3,618,736
def get_coin_symbol_by_index(coin_index): """ Retrieves a coin SYMBOL when passed a coin INDEX Returns: String """ coin_symbol = coin_symbol_by_index.get(coin_index) if coin_symbol is not None: return coin_symbol # need to do a real lookup coins_reverse = global_enum...
d77ceec886bfa1d437c1b99a62b018c743aa9bf7
3,618,737
from dateutil import tz def _parse(data): """Recursively convert a json into python data types""" if not data: return [] elif isinstance(data, (tuple, list)): return [_parse(subdata) for subdata in data] # extract the nested dict. ex. {"tournament": {"url": "7k1safq" ...}} d = {i...
ebc3c61f358d80f08db506a0465f47f4b449211f
3,618,738
def get_speed(x, y): """ Compute speed at each frame from XY coordinates, somehow its missing for paws in database """ rawspeed = ( np.hstack([[0], np.sqrt(np.diff(x) ** 2 + np.diff(y) ** 2)]) * 60 ) return convolve_with_gaussian(rawspeed, 9)
4159e1e5d92f9f7278963d177d4d8a22ac2874a3
3,618,739
def calculate_iv_curve(effective_irradiance, temperature, module_parameters, ivcurve_pnts=200): """ :param effective_irradiance: :param temperature: :param module_parameters: :param ivcurve_pnts: :return: """ photocurrent, saturation_current, resistance_series, re...
ca9ace009ad2564f7d678695aa29170cbb86d579
3,618,740
def fsa(C,u10,SP,T,*,slp=1.0,gas=None,param="W14",rh=1): """ DESCRIPTION ------------- Diffusive gas flux across the air-sea interface in mol m-2 s-1 F = k (C - Ceq_slp) INPUTS: ---------- C Surface dissolved gas concentration [mol m-3 == mmol L-1] u10...
45c4110c59103e278fb0b4b69b6c1735a6adfa2b
3,618,742
def calc_cos(v_i,v_j): """ Calculate the cos theta between two vectors """ return np.dot(v_i/np.linalg.norm(v_i),v_j/np.linalg.norm(v_j))
243e43a20a25ec5a162344f4e10c5df9f2d1d66e
3,618,744
def retry_http(response): """Retry on specific HTTP errors: * 429: Rate limited to 50 reqs/minute. Args: response (dict): Dynatrace API response. Returns: bool: True to retry, False otherwise. """ retry_codes = [429] code = int(response.get('error', {}).get('code', 200)) ...
f45f6e9239d78cfa6ad0ec397e3a5b4a58a655f5
3,618,746
def _box_cox_transform(values, standard=True): """ Performs the Box-Cox transformation, over different ranges, picking the optimal one w. respect to normality. """ a = sp.array(values) if standard: vals = (a - min(a)) + 0.1 * sp.var(a) else: vals = a sw_pvals = [] lambdas...
1d56fe5cc9a985d5092198fb4d5a8d4f49e3e4d4
3,618,747
def bst_check(now=None): """ Determine whether the specified date lies within the British Summer Time period. Args: n (tuple): An 8-tuple indicating the request date (see http://docs.micropython.org/en/latest/library/utime.html?highlight=localtime#utime.localtime). Returns: ...
41c54bb8b717ec1999ae234e4eaa626e699c3caf
3,618,748
def local_genus_symbol(self, p): """ Returns the Conway-Sloane genus symbol of 2 times a quadratic form defined over ZZ at a prime number p. This is defined (in the Genus_Symbol_p_adic_ring() class in the quadratic_forms/genera subfolder) to be a list of tuples (one for each Jordan component p^...
5b2068a074bd13f0931e84ab29c8c7071abc2235
3,618,749
def extract_events(line, ngram_base = 'words', ngram_size = 1, outcomes_provided = True, not_symbol_pattern = not_symbol_pattern_en, remove_weird_words = False, sep_words = "#", sep_ngrams = '_', mark_word_boundary = True, lowercase = True, remove_duplicates =...
cfae4a2ba22e0428f7cbca7ee97b3ab0230e75bb
3,618,750
from typing import List import re def reduce_parenthesis(text_in: str) -> List[str]: """ reduce parenthesis Called recursively. Removes one layer of parenthesis and breaks the string into parts. Parameters ---------- text_in: str Returns ------- list_text: list[str] Example...
6d86d6b8140b55658df2efc51131059006935493
3,618,751
import types from typing import Any def set_obj_from_module(module: types.ModuleType, obj_name: str, value: Any) -> Any: """Traverses the object name and returns the last (rightmost) python object.""" if obj_name == '': return module obj = module parts = obj_name.replace('/', '.').split(".") last = part...
3058b6b8a414bea00004db9edde4f1d19fc013ef
3,618,752
def _sparsify_matrix_kernel(matrix_input, epsilon=1): """ The matrix sparsification procedure. See https://www.researchgate.net/publication/221462839_A_Fast_Random_Sampling_Algorithm_for_Sparsifying_Matrices :param matrix_input: a matrix to be sparsified :param epsilon: approximation constant. :ret...
21c8d7becdcc88881639544065b3c7ba9976cf75
3,618,753
def __bit_string_to_int(BitStr): """Transforms a string of the form '01001001' into an integer which represents this byte. TESTED <frs> """ BitStr = BitStr.replace(".", "") BitArray = map(lambda x: x, BitStr) BitArray.reverse() n = 0 sum = 0 for bit in BitArray: if bit...
ca6a4f420c3d2a8f9bb200384b4a7318db6daa44
3,618,754
def expensesByTail(update: Update, context: CallbackContext): """ Start the flow for listing the previous N expenses """ text = ("Please select an option or type in the number of most recently recorded expenses to show.") reply_markup = reply_markups.backnHomeInlineMarkup context.bot.send_me...
ccb52af03fc29c11b1adab7e42ea8fbeccbcaeb1
3,618,757
def include_categories(f): """Return an object with all categories (decorator).""" @wraps(f) def decorated_function(*args, **kwargs): categories = c.query(Category).all() # pass along the categories object to the next function kwargs['categories'] = categories return f(*args,...
eccf595221d785065b2eaa7780fe7e776215e7e9
3,618,758
def shuffle_array(*args): """ Shuffle the given data. Keeps the relative associations arr_j[i] <-> arr_k[i]. Params ------ args: (numpy arrays tuple) arr_1, arr_2, ..., arr_n to be shuffled. Return ------ X, y : the shuffled arrays. """ # Assert that there is at least on...
119ab466ca5b73964d248cd3689b6583b859b066
3,618,759
def circular_wetted_perimeter(angle, diameter): """Returns circle wetted perimeter. :param angle: angle in radians from angle_in_partial_filled_pipe function :param diameter: diameter of pipe [m] """ return angle * diameter
e24cc0839eb3bf78e65f6b9b99b34bf87f77b2cf
3,618,760
import re def openapi_endpoint_name_from_rule(rule): """Utility function to generate the Open API endpoint name. It replace '/users/<user_id>' with the OpenAPI standard: '/users/{user_id}'. """ name = rule.rule for argument in rule.arguments: openapi_name = f"{{{argument}}}" name...
262ad76302e76017bb88cf469add1c71e0452ea0
3,618,761
def _fix_axes(tensors, axes, allow_negative): """Makes all axes positive and checks for out of bound errors.""" axes = [ axis + tensor.shape.ndims if axis < 0 else axis for tensor, axis in zip(tensors, axes) ] if not all( ((allow_negative or (not allow_negative ...
f3861809c2150e3d069fdba6930ef8a1e7f870da
3,618,762
import yaml def yaml_loader(filepath: str) -> dictionary: """ Loads a yaml file specified by the filepath and returns it as a dictionary :param filepath: A string containing the filepath to load :return: A dictionary containing the contents of the yaml file """ with open(filepath, 'r') as file...
f7a18969604a612d006326e7ce8639150c72c3af
3,618,764
import torch def new_deit_tiny_patch16_224(pretrained=False, **kwargs): """ the same as vit_base_patch16_224 """ default_kwargs = { 'embed_dim': 192, 'num_heads': 3, } default_kwargs.update(_cfg) default_kwargs.update(kwargs) vit = VisionTransformer(**default_kwargs) ...
c61810b371de6ec442030e8300a1500e5f0f316c
3,618,765
def calc_rgb_each_hue_dEz_base( hue, cusp, focal_point_l, chroma_num, delta_Ez, color_space_name, luminance): """ Parameters ---------- hue : float hue angle (0.0-360) focal_point_l : float lightness value of the focal_point. chroma_num : int the number of...
233acbd65cbd366ef324154037cc0219dc24cd4a
3,618,766
def page_not_found(error): """Error 404: Page not found """ return render_template('page_not_found.html'), 404
2514700e2a920bdaa58e7d9b559cc37bcde85b0a
3,618,767
def bigram(words, score_fn=BigramAssocMeasures.likelihood_ratio, n=500,freq=1): """ tmp_words=[] for w in words: tmp_words.append(w) words=tmp_words """ if len(words)<=0: return {} tmp_dict={} for w in words: tmp_dict[w]=1 if len(tm...
eef36c1153d50e8a22e6d4ecff7ca8622682ad2b
3,618,768
def sample(sample_type="const", a=None, b=None, *, random_state: np.random.RandomState = None): """ Example ------- >>> sample(sample_type="const",a=5,random_state=np.random.RandomState()) 5 >>> isinstance(sample(sample_type="randint",a=1,b=10,random_state=np.random.RandomState()),int) True ...
f6c0c4e64bea83a88f9dc0debff9cdf1c2caa2ed
3,618,769
def adam_consensus(trees): """Search Adam Consensus tree from multiple trees. :Parameters: trees : list list of trees to produce consensus tree. """ clades = [tree.root for tree in trees] return BaseTree.Tree(root=_part(clades), rooted=True)
44c80015c2ac437168c3cd3b03ea1fe101e9cdcb
3,618,770
from shapely import wkb from shapely import wkt def decode_geometry(ewkb): """Decode encoded wkb into a shapely geometry""" # it's already a shapely object if hasattr(ewkb, 'geom_type'): return ewkb if ewkb: try: return wkb.loads(ba.unhexlify(ewkb)) except Exceptio...
24a714618e243281cc13e05056ec0d9280c19ce3
3,618,771
def mask(): """Example mask for testing.""" filename = '$GAMMAPY_EXTRA/datasets/exclusion_masks/tevcat_exclusion.fits' return SkyImage.read(filename, hdu='EXCLUSION')
1a339f1ff8db704a73183ebc52123b49710ef691
3,618,772
def parse_filepaths(fp, studies=None): """ Summary ------- Function to parse filepath and optional study names into a format readable for the calsim_toolkit read/write functions. """ # Check that inputs provided are compatible and zip data into list. if isinstance(fp, str) and (isinstan...
17e6a14967aea1275bf1562ca691dfdb2c1f16d0
3,618,774
def is_dunder(attr_name: str) -> bool: """ Retuns whether the given attr is a magic/dunder method. :param attr_name: """ return attr_name.startswith("__") and attr_name.endswith("__")
b3a1f10e9fc7fd5c7dbb930be977a814e6b0c37d
3,618,775
from textwrap import dedent def doc(descriptor, indent=0): """ Format ``doc`` attribute of ``descriptor``. If doc is ``None`` returns warning admonition. If ``indent`` argument is specified, the result will be indented by the number of spaces. """ if descriptor.doc is None: result = dedent(""" ...
da03ecbce1ee740e00ccee0f260827a29b106a62
3,618,776
def draw_box(im, np_boxes, labels, threshold=0.5): """ Args: im (PIL.Image.Image): PIL image np_boxes (np.ndarray): shape:[N,6], N: number of box, matix element:[class, score, x_min, y_min, x_max, y_max] labels (list): labels:['class1', ..., 'classn'] ...
d3aa7dbee52a75ff32beda069762faeb07e81854
3,618,777
def get_mnist_default_transform(): """ The default transform come with data augmentation """ return transforms.Compose([ transforms.Pad(2), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) ])
e89fe8c8568122de8acb605a994c8292ad3feb94
3,618,778
def HideUnusedScalarBars(view=None): """Hides all unused scalar bars from the view. A scalar bar is used if some data is shown in that view that is coloring using the transfer function shown by the scalar bar.""" if not view: view = active_objects.view if not view: raise ValueError (...
2d00e824b756878d0f7d8630f76ee3d341f24514
3,618,779
def validate_serial(req_data): """Verify serial in data validates Args: req_data (dict): request with serial and possibly models Returns: object: None if all ok, or json response (bad) """ with _global_lock: sim_type = sirepo.template.assert_sim_type(req_data['simulationTyp...
d67c11fac10e48677910927b0b0c0267d9f24318
3,618,781
def read_megares_annotations(annotations_file): """Read MEGARes annotations. """ annotations = pd.read_csv(annotations_file, index_col=0) return annotations.to_dict()
94011a9f3fa9a298e7204f93dd5ca844621306b7
3,618,783
def risings_and_settings(ephemeris, target, topos, horizon_degrees=-34.0/60.0, radius_degrees=0): #? """Build a function of time that returns whether a body is up. This returns a function taking a :class:`~skyfield.timelib.Time` argument returning ``True`` if the bodyโ€™s altazimuth ...
5a39a904f496d83287b2c03a7d09fc5301eef8e9
3,618,784
from metric import all_metrics def get_all_metric_names(): """Return a list of all metric names.""" return all_metrics.keys()
facfd75c7ff4368522a8b204532b26f80180a9d1
3,618,785
def getRootLogger(): """ Return the root logger. Note that getLogger('') now does the same thing, so this function is deprecated and may disappear in the future. """ return root
78f350cdb4ecb0beeb31a4e8e2af0b5ea8974bd7
3,618,787
def trajectories_and_new_observations_steps( traj_not_updated, remaining_new_observations, next_nid, return_trajectories_queue, sep_criterion, mag_criterion_same_fid, mag_criterion_diff_fid, angle_criterion, orbfit_limit, max_traj_id, ram_dir, store_kd_tree, run_metri...
035a23058e626a4856c80ccea96cdef9568794ec
3,618,788
import torch def ft_flow(flow: nn.ModuleList, x: torch.Tensor): """Pass `x` through (forward) through each layer in `flow`.""" # if torch.cuda.is_available(): # f = f.cuda() for layer in flow: x, logdet = layer.forward(x) return x.detach()
0aeb522e2789e74156be8e51798fdf388bebc50a
3,618,790
def recurse(): """return (sum, value)""" child_count = next(it) metadata_count = next(it) if child_count == 0: total_value = total_sum = sum(islice(it, metadata_count)) return total_sum, total_value total_sum = total_value = 0 child_values = [] for _ in range(child_count): ...
3c3bbf7156785b7bad7c5936ac86aec489bd3cb9
3,618,791
def load_yaml(filename='config.yml', logger=None): """ Convenience wrapper around toolchest.yaml::parse to allow you to parse a file by path+name :param filename: A yaml file to be parsed :param logger: Optional logger for potential errors :return: A dictionary formed out of the yaml data "...
0a5dd7160247a0cb2476a1cdbb25ea3a2698a587
3,618,792
def generate_seq(length): """ Generates a sequence of given length using black magic Sequence is a string of AGCT """ global VALUES seq = [] intseq = np.floor(np.random.rand(length) * 4) for i in range(length): seq.append(VALUES[intseq[i]]) return ''.join(seq)
c87d64a9f5461a928ad08f1aaed3031b219c41c8
3,618,794
def find_roles(dbs, role_name=None, page_no=1, filter_sys=False): """ ่ง’่‰ฒๅˆ—่กจ :param dbs: :param role_name: :param page_no: :param filter_sys: :return: """ roles = dbs.query(SysRole.role_id, SysRole.role_name, SysRole.role_desc, ...
f5139998847762a611fbda95e15ccd17242d8a11
3,618,795
def invalid_data_response(request_serializer): """ Returns the error message depending on missing/invalid data in serializer. """ return Response({'detail': request_serializer.errors, 'data': {}}, status=status.HTTP_400_BAD_REQUEST)
8703c851968879fdccb65f637c9c13b258d121bb
3,618,796