content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import re def is_valid_hostname(hostname): """Convert domain label into IDN ACE form (handles internationalized domains and regular (ascii) domains""" hostname = from_unicode(hostname).to_text() # stackoverflow.com/a/2532344/1707152 if len(hostname) > 255: return False if hostname[-1]...
1232173f1c2a2fde4cf2dda5fe1741656c5aca71
52,179
def delBlank(strs): """ Delete all blanks in the str. """ ans = "" for e in strs: if e != " ": ans += e return ans
a6155af200918819055533057f63b4b44c8dd508
52,180
def jdcnv(year, month, day, hour): """Convert Gregorian time (UTC) to Julian Date Input: year = year (scalar int) month = month 1-12 (scalar int) day = day 1-31 (scalar int) hour = fractional hour (scalar double) Output: julian = Julian Date (scalar double) Origina...
33f577c95a3e44f7f9ad3002ca170fa0b55ac147
52,181
def get_all_people(): """ You can hit the resource name without an ID to get a listing of all of that resource """ resp = session.get(GHIBLI_URL + "people") people = [Person(**json_person) for json_person in resp.json()] return people
80dd9c5bd3103f7a09a8e5a5a55a26572865f996
52,182
import itertools def generate_preset_test_translations(dimensions=3): """Generates a set of translations.""" permutations = itertools.product([0.1, -0.2, 0.5, 0.7, 0.4, -0.1], repeat=dimensions) return np.array(list(permutations))
3aee3411cf0493f7a103c2366c7e55cd46012b6b
52,183
def closest_precise_locator_for(element: WebElement, root: WebElement = None): """Builds the most precise locator which matches `element`. If `element` does not have a role, return a semantic locator which matches the closest ancestor with a role. "Precise" means that it matches the fewest other elements, whil...
1177ce673212e33cdc6400f9d01470e8e60e97ad
52,184
import re def splitn(s, n): """split string s into chunks no more than n characters long""" parts = re.split("(.{%d,%d})" % (n, n), s) map(parts.remove, [""] * parts.count("")) return parts
3f0f697f54515e26f98bc08b53cb4d39952ed128
52,185
def skinHasImage(image): """ Returns ``True`` if the image file exists in the skin. :param image: string - image filename .. note:: If the media resides in a subfolder include it. (eg. home-myfiles\home-myfiles2.png). You can use the above as keywords for arguments. example:: exi...
f64af64c4d18298fe56ebff8388d6fc3020ff5e1
52,187
def is_date(string, fuzzy=False): """ return whether the string can be interpreted as a date """ try: parse(string, fuzzy=fuzzy) return True except ValueError: return False
4330c82967845abb3390005c6a47dbe069f9a2ca
52,188
from pathlib import Path import copy def known_good_image_archive(request, tmp_path: Path) -> TypingKnownGoodImageArchive: """Provides 'known good' metadata for a local image that can be modified.""" path_destination = tmp_path.joinpath(request.param["resource"]) path_source = get_test_data_path(request, ...
86ed5e4afb1f4cc500adffc06b9c2dd8a5827787
52,189
import csv def LoadMOS(mos_csv): """Load a csv file withMOS scores. Args: mos_csv: Path to a csv file that has degraded and MOS. Returns: Dictionary with filename keys and MOS values """ mos_dict = {} with open(mos_csv, 'r') as csvfile: mos_reader = csv.reader(csvfile) for row in mos_rea...
e98cbf93e3bc889a31a98ff32a9f9189a850a55f
52,190
from edge.models import Genome def import_gff(name, fn): """ Creates a new genome using the specified GFF file. name: Name of genome fn: path to GFF file """ if Genome.objects.filter(name=name).count() > 0: raise Exception('There is already a genome named "%s"' % (name,)) g = Ge...
5bc16276278bc4f1559e48d4450a24cccf114024
52,191
import unicodedata def url_is_invalid_unicode(url_string): """ Check for unicode control characters in URL """ for x in str(url_string): if unicodedata.category(x)[0] == "C": return True return False
d1a3974b24023c46a337c7e17718e00aa5916c7d
52,193
import functools def fn_with_custom_grad(grad_fn, use_global_vars=False, use_entire_scope=False): """Decorator to create a subgraph with a custom gradient function. The subgraph created by the decorated function is NOT put in a Defun and so does not suffer from the limitations of the Defun (all subgraph o...
48563bc9cb940853378f3b24193fd67a3daa903f
52,194
import logging def _monkey_patch_dataset_method(strategy): """Monkey-patch `strategy`'s `make_dataset_iterator` method.""" def make_dataset(self, dataset): logging.info('Using pure synthetic data.') with self.scope(): if self.extended._global_batch_size: # pylint: disable=protected-access r...
7f60d5a941aa300d65c777844e208800b9760b08
52,195
def _xvert(cls, result_item, generate_links=True): """ converts the response object into Json :param generate_links: if True, it will add the HATEOAS links to the response :param result_item: the actual item which will get converted :return: """ if isinstance(result_item, Model): mo...
97bdc45550393f096f3187edb1d90e111b423901
52,196
def Gamma_correction(low_frequency, alpha=0.5): """ Adjust the coefficient of low frequency component using Gamma correction. :param low_frequency: the low frequency component of the image calculated with Shearlet transformation. :param alpha: adjustment factor with a range from 0 to 1, in addition, it ...
5d750ab117dc6dc0f2f1906e84c793fa98aa12b4
52,197
def assign_first_visit(df: DataFrame, column_name_to_assign: str, id_column: str, visit_date_column: str) -> DataFrame: """ Assign column to represent number of participants in household Parameters ---------- df column_name_to_assign id_column visit_date_column """ window = Windo...
254a8d50bc844fc83bd02552d0224d6fbfc6ecec
52,198
import msgpack def _msgpack_ext_pack(x): """Msgpack encoders for custom types.""" if isinstance(x, complex): return msgpack.ExtType(_MsgpackExtType.native_complex, msgpack.packb((x.real, x.imag))) if isinstance(x, jax.ShapedArray): return msgpack.ExtType(_MsgpackExtType.shaped...
514447f98ca4855b14a70e962fa01033d39b3842
52,199
import re def convert_s3_label_to_bytes(s3_size: str) -> int: """convert 12MiB to 12 * 1024**2""" match = re.match(r"([0-9.]+)(\w+)", s3_size) if match: return int(float(match.groups()[0]) * 1024 ** LABELS_POWER[match.groups()[1]]) return -1
161c494b53322737b39e8dd3e8ec3226797abc59
52,200
import networkx as nx import tabix def ld_prune(df, ld_beds, snvs=None): """ Prune set of GWAS based on LD and significance. A graph of all SNVs is constructed with edges for LD >= 0.8 and the most significant SNV per connected component is kept. Parameters ---------- df : pandas.Dat...
dde8f3ac2b1cb3ef265b1986d61f8ee474b199a6
52,201
def perm_to_string(p): """ Convert p to string, slightly more compact than list printing. """ s = "(" for x in p: s = s + "%2d "%x s += ")" return s
d5922275b7e0b677957309e1bab5f3b9b1ff0cb7
52,202
def pg_capital(s : str) -> str: """ If string contains a capital letter, wrap it in double quotes returns: string """ if '"' in s: return s needs_quotes = False for c in str(s): if ord(c) < ord('a') or ord(c) > ord('z'): if not c.isdigit(): needs_...
bfb928b88e837c78ddd46f7d231217442ef4e24c
52,203
def get_client(host, port=None, username=None, password=None, tenant=None, auth_url=None, auth_strategy=None, auth_token=None, region=None, is_silent_upload=False, insecure=False): """ Returns a new client heat client object based on common kwargs. ...
a01bd41b2f61f6c993589e16484f2175877588be
52,204
def ht_syn_one(): """Hash table of words and their synonyms.""" ht = HashTable(10) # import pdb; pdb.set_trace() ht.set('fond', 'enamored') ht.set('wrath', 'anger') ht.set('diligent', 'employed') ht.set('outfit', 'garb') ht.set('guide', 'usher') return ht
b1ec5ca5a59f1cda737540e7c383217d2c54e733
52,205
import string def escape_bytes(bytes_): """ Convert a bytes object to an escaped string. Convert bytes to an ASCII string. Non-printable characters and a single quote (') are escaped. This allows to format bytes in messages as f"b'{utils.escape_bytes(bytes)}'". """ res = "" for byte i...
c1a6c2875824d8576e7d9c349f19548e2c3313e8
52,207
import six def _minimize_towers(tower_specs, optimizer): """Aggregate and apply gradients for computed losses.""" grad_lists = {} for tower_spec in tower_specs: with ops_lib.device(tower_spec.loss.device): for grad, var in optimizer.compute_gradients(tower_spec.loss): if grad is not None: ...
530f8d4a2b1dca5591bc612ac57a82be99bcbb2d
52,208
def shrink_dimensions(width, height, max_dimension): """ Resize dimensions so max dimension is max_dimension. If dimensions are too small no resizing is done Args: width (int): The width height (int): The height max_dimension (int): The maximum size of a dimension Returns: ...
60d4a6ec9b310f7c22f341f1309b4677c3617fd2
52,209
def relu_backward(dA, cache): """ This function implements the backward propagation for a single Relu unit @params dA = post-activation gradient, of any shape cache = Retrieve cached Z for computing backward propagation efficiently Returns: dZ = Gradient of the cost with respect to Z ...
f1847b8b7a24798437b2862c0fba806376121df8
52,210
def keccak256(value): """Thin wrapper around keccak function.""" return HexBytes(keccak(value))
581b621d8fc5b4a1e4643a6cd18176226cda2fdc
52,211
def slerp(pt1, pt2, intervals): """Spherical linear interpolation. Args: pt1: Array of points. When interval is 0, the result is pt1. pt2: Array of points. When interval is 1, the result is pt2. intervals: Array of intervals at which to evaluate the linear interpolation ...
eba8087a0733cff54a382b294cfe946d90453967
52,212
def make_cumvalues(xvalues): """ Takes a Pandas dataframe with one column as input value. Tries to create a cumulative series. """ newvalues = 0.0 * xvalues dx = xvalues.diff() dxpos = dx mask = -xvalues.diff() > 0.9 * xvalues nrsteps = len(dx.loc[mask]) lapidx = np.cumsum((-dx + a...
8aeb6e360ddf53a3ce612659da597e8e378c48ee
52,213
def payment_success(request): """ Renders status page after donation passed successfully." """ return render(request, 'payment_success.html')
a9ca900213fbe57495c6100e68839b68ff38ccb6
52,214
def should_workfile_tool_start( project_name, host_name, task_name, task_type, default_output=False ): """Define if host should start workfile tool at host launch. Default output is `False`. Can be overridden with environment variable `OPENPYPE_WORKFILE_TOOL_ON_START`, valid values without case sensiti...
14dc2293633b7acd151e17cdec6691dd3cb7e947
52,215
def create(): """ $ curl -i -X POST -H "Content-Type: application/json" -d '{"username":"user","password":"python"}' http://localhost:5000/api/user """ username = request.json.get("username") password = request.json.get("password") if username is None or password is None: abort(400) #...
9c99eff1c84c26527e5605b286d207a39c37e489
52,216
def display_hour_range_dash(value): """ Function that just calls the display_hour_range function. This function is decorated by the Dash Application decorator. Such an arrangement is used as unit testing decorated functions is complex. """ display = display_hour_range(value) return displa...
03f4100d0deb0a6eb185da0480aa1d91b78ca07a
52,217
def sample_ingredient(user, name='Cinnamon'): """membuat dan mengembalikan sampel ingredient""" return Ingredient.objects.create(user=user, name=name)
bc6627c0d485d78f0d2158664eef4dd4191ac1b5
52,218
def _get_np_complex_dtype(float_dtype): """ Get equivalent complex type given current float dtype """ if float_dtype == np.float32: return np.complex64 elif float_dtype == np.float64: return np.complex128 else: return np.complex256
c5b342f5ddf95e63acaa2a3559fd4d373a1aa63c
52,219
def ResizePad(mask, image_shape): """ Resize and Pad mask back to original shape -- reverse action of CropResize for masks """ if mask.shape == image_shape: return mask h, w = image_shape side = min(h, w) mask = cv2.resize(mask, (side, side), interpolation=cv2.INTER_NEAREST) ...
b5bf84ff35e169a2533d78000ce83a73d760cef8
52,220
def read(filename, *args, **kwds): """Loads a graph from the given filename. This is just a convenience function, calls L{Graph.Read} directly. All arguments are passed unchanged to L{Graph.Read} @param filename: the name of the file to be loaded """ return Graph.Read(filename, *args, **kwds)
49d2b2503b93808e1db8ea487db49553e603023a
52,221
def create_instance_from_template_with_overrides( project_id: str, zone: str, instance_name: str, instance_template_name: str, machine_type: str, new_disk_source_image: str, ) -> compute_v1.Instance: """ Creates a Compute Engine VM instance from an instance template, changing the machine...
32f75a8a5de539ef5ab000c028cd91469fbfac90
52,222
from typing import List from typing import Union from typing import Callable import torch def evaluate(model: Module, dataloader: DataLoader, metrics: List[Union[str, Callable]], prepare_batch: Callable = lambda x: x, loss_fn: Callable = None, prefix: s...
32ef765a8d2a33da627f3c0839425ba3e305c931
52,225
def ensureGrayscale(np_image, info=False): """Ensures that given image is in grayscale Keyword argument: np_image -- image as NumPy array Return: np_image as grayscale image """ isConverted = False if len(np_image.shape) == 3: if np_image.shape[2] == 3: np_image = ge...
88349603b8b71064805fa9c24534745c10acaaa6
52,226
from typing import List def load_unlabelled(filename: str) -> List: """Helper function to load unlabelled dataset for unsupervised training. Args: filename (str): filename of dataset Returns: List: list of dataset by line. """ data = [] with open(filename, "r") as F: ...
e88f94457763e6b291b850e6fe6374935dae7015
52,227
import six def is_key_attribute(df, attr, verbose=False): """ Check if an attribute is a key attribute Args: df (pandas dataframe): Input dataframe attr (str): Attribute in the pandas dataframe verbose (bool): Flag to indicate whether warnings should be printed out Returns: ...
c73697e72bf553f6d7114edcf014960b976f9db3
52,228
def break_rest(time, flux, flux_err, cadences): """ Breaks up the non-signal cases into bite-sized cadence-length chunks. Parameters ---------- time : np.ndarray Array of time. flux : np.ndarray Array of fluxes. flux_err : np.ndarray Array of flux errors. cade...
2255f2aed7184c86590c66964eee92e37e5e8ef9
52,229
def login_required(fn): """ login required as decorator """ @wraps(fn) def decorated_view(*args, **kwargs): if not 'user' in session or session['user'] == None: return redirect(url_for("login")) return fn(*args, **kwargs) return decorated_view
31f017429275ed8c89017ef9b43906d84b97a301
52,230
def addAge(data, ages): """ The new format in CMD v3.2 does not include the commented line with the 'Age' value, and the logAge column is rounded to 3 decimal places so this value it can not be taken from there. Add this line back to each age for each metallicity file. """ data = data.spli...
e9c6145dd424ed2149d950246172004bea24d2ca
52,231
def group_spans(article_id, span_intervals): """ Groups together spans from the same article """ dictionary = dict.fromkeys(article_id, span_intervals) spans = {} for key, value in dictionary.items(): spans.setdefault(key, []) spans[key].append(value) return spans
3be0f2cb8b07a9fef7f116171b81829a86301a04
52,232
def conjugate_gradient_solve(a_mat, b_mat, tol=1e-10): """Returns `X` such that `A * X = B`. Uses Conjugate Gradient to solve many linear systems of equations with the same matrix `a_mat` and multiple right hand sides provided as columns in the matrix `b_mat`. Args: a_mat: a Symmetric Positive Definite ...
6346dc3b2398a8d919188396c22399f7ca5a47ea
52,233
def list_lateral_movement_template_command(client: Client) -> CommandResults: """Retrieve a list of all lateral movement templates. Args: client (Client): Cymulate client. Returns: CommandResults: A CommandResults object that is then passed to 'return_results', cont...
a2eab8e97fdb2e2291a5f4994c2d2d410e6eb06b
52,234
def create_download_response_zip(file_format: str, experiment: Experiment) -> \ FileResponse: """Creates a FileResponse containing a ZIP with all data of the provided experiment, in the desired format. """ # Create the zip using the desired methods if file_format == 'raw': zip_file = _c...
f5ec26f4c0ff6c349f265e0b5eb23815048c5583
52,235
def ids_to_names(ven_id, ven_name, dev_id, dev_name): """Uses an internal lookup table to return canonical names when known. Returns: tuple(vendor name, device name). """ m = _VENDOR_MAPPING.get(ven_id) if not m: return ven_name, dev_name return m[0], m[1].get(dev_id, dev_name)
098748c5efec05065e0f3b6853d4a5e22b636658
52,236
def pixel_matrix_from_hash(hash_value): """Sets pixels of the image to on or off based on hash value. Args: hash_value (int): The hash value of the username of user Returns: np.array: A symmetric black and white pixel map matrix """ pixel_matrix = np.zeros((5,5)) # first 25 cha...
72b96cbae28e23278979f110288486a202b4ff91
52,238
def portfolio_vol(weights, covmat): """ Weights to vol Turns lists,arrays into float volatility figure Last updated 24/12/2020 """ if isinstance(weights, list): weights = np.array(weights) return (weights.T @ covmat @ weights) ** 0.5
e3c15f3e2b657afd78ab9f750010172fe1b146ac
52,239
def _get_fargs(func, no_self=False, no_varargs=False): # pragma: no cover """ Same as putil.pinspect.get_function_args """ is_parg = lambda x: (len(x) > 1) and (x[0] == '*') and (x[1] != '*') is_kwarg = lambda x: (len(x) > 2) and (x[:2] == '**') par_dict = signature(func).parameters # Mark position...
12446caff85ee70787e05abdbb255c178c90a059
52,242
def new_game_nd(dimensions, bombs): """ Start a new game. Return a game state dictionary, with the 'dimensions', 'state', 'board' and 'mask' fields adequately initialized. Args: dimensions (tuple): Dimensions of the board bombs (list): Bomb locations as a list of lists, each an ...
fd307b5f2bf619dcec6bcca2289f2a57bafad537
52,243
from typing import Any def deprecation_versions(): """Create a list of valid version for deprecation entries, current+4""" major, minor = [int(version) for version in __version__.split('.')[0:2]] return Any(*['{0}.{1}'.format(major, minor + increment) for increment in range(0, 5)])
e2e860d3cdb6d13e4fba01396b8e37a0b38f4518
52,244
def fitness_score(individual: list) -> int: """ Calculate the fitness score of an individual @param individual: @return: score: int """ score = 0 for row in range(Constants.NUMBER_OF_QUEENS.value): col = individual[row] for other_row in range(Constants.NUMBER_OF_QUEENS.value)...
24718331231d71ac67773faf4c2c24957c98ecee
52,245
import platform def get_main_dir_path(): """ returns the path to the main speech directory for mac and linux depending on the OS """ # checks if I am on my local (mac) or a VM (linux) system = platform.system() if system == 'Linux': path_prefix = '/home/dzubke/awni_speech/speech/' ...
0038bb8360e5431a3be9ecbd375e1c7f2f0e196a
52,246
import json def get_id_set(id_set_path: str) -> dict: """ Parses the content of id_set_path and returns its content. Args: id_set_path: The path of the id_set file Returns: The parsed content of id_set """ with open(id_set_path, 'r') as id_set_file: id_set = json.load(...
244495603bf423324ef4b3ffe4b1fdc3ca7fdf74
52,248
async def update_recipe_category(category: str, new_category: CategoryIn, session: Session = Depends(generate_session)): """ Updates an existing Tag in the database """ try: return db.categories.update(session, category, new_category.dict()) except Exception: raise HTTPException(status.HTTP...
bc864f0c7c1945a5271363345c024e00ace25500
52,249
import traceback def get_station_id(pool, latitude, longitude, station_type) -> str: """ Retrieve station id :param pool: database connection pool :param latitude: :param longitude: :param station_type: StationEnum: which defines the station type such as 'CUrW', 'WRF' :return: str: sta...
60c08d3b9db51bd505e516be97beb0f31a8933d3
52,250
def get_bgp_summary( device, address_family=None, vrf=None, rd=None, all_summary=False ): """ Get neighbors from show bgp summary command Args: device ('obj'): Device object address_family ('str'): address family vrf ('str'): vrf name all_summary ('bool')...
f1a1dc06e8ae8224aaf69e38e005f0dcb9f3649b
52,251
def give_stats(list_of_scores, list_of_dates, selected_date, over_all): """returning the stats of a list of scores""" if not over_all: total = 0 ctr = 0 best = 9999 worst = 0 for score in list_of_scores: if score[0].text == list_of_dates[selected_date].text: ...
21c2c88a931c4595e0134d3bff8e37120655ebd7
52,252
def get_structure_AlN(): """Set up AlN primitive cell Al N 1.0 3.1100000000000000 0.0000000000000000 0.0000000000000000 -1.5550000000000000 2.6933390057696038 0.0000000000000000 0.0000000000000000 0.0000000000000000 4.9800000000000000 Al N 2 2 ...
1f4f7ad8ad6ce381d5dfe3dcc61e3feeb0b84ae7
52,254
def transpose(transform, df, dicts): """Transposes the given dataframe""" df = df.reset_index().set_index('index').T.reset_index() df.columns = df.iloc[0] return (df[1:], dicts)
fc80a8a471ddf4af4329dc069b45d442f5bab0a0
52,255
def format_label_value(*values): """ Construct a label value. If multiple value components are provided, they are joined by underscores. """ return '_'.join(values)
46bb4e968577c95d5dd0df8b9687efbfdcc0568e
52,256
import logging def get_ticker_from_user(): """ This function prompts a user for an input, and returns it as the ticker :return: """ logging.info('Prompting user to enter a ticker symbol') print('Note: Data up to 1 month from today will be fetched from Yahoo Finance') return raw_input('Ente...
c5e90df462e0845883e7c54e6582f6bcf53a4502
52,257
def get_failed_info(res): """获取失败用例信息""" intf_summary_list, full_summary_list = res failed_intf_dic = {} for system_dic in intf_summary_list: if system_dic['failCaseNum'] == 0: continue for intf_dic in system_dic['children']: if intf_dic['failCaseNum'] == 0: ...
cb038319617f82a36fcc9ce5b45abac20fac89d7
52,258
def _singularity_prefix( singularity_cmd=DEFAULT_SINGULARITY_COMMAND, sudo=DEFAULT_SUDO, sudo_cmd=DEFAULT_SUDO_COMMAND, **kwds ): """Prefix to issue a singularity command.""" command_parts = [] if sudo: command_parts.append(sudo_cmd) command_parts.append(singularity_cmd) retu...
b781ed66901696b5cc06406824c68193f34e712c
52,260
def set_country(request, response, country_code): """Set region instance.""" info = get_cookie(request) if country_code and Country.objects.filter(country=country_code): info["country_code"] = country_code set_cookie(request, response, info) return True else: return Fals...
ed7d521b3168519477c82c5423c37f2eced7dccb
52,262
from typing import Union from typing import Sequence from typing import List def filter_from_strings(filter_strings: Union[str, Sequence[str]]) -> StringFilter: """Create a string filter from a sequence of input strings. Each string in the sequence can have the following format: - `ALL`: Accept all strin...
46ec071adbb8096863065179731bdc9dbcb5e798
52,263
def get_data_train_in_candidates(): """ Return artificial datasets when train_in_candidates = True """ sent_idx_to_idx = {} # Manually set alias map alias2wpids = { 'alias1': [["Q1", 10], ["Q4", 6]], 'multi word alias2': [["Q2", 5], ["Q1", 3], ["Q4", 2]], 'alias3': [["Q1", 30]]...
1a320b464daee656487a6c7511ab6576dcbfa686
52,264
def first_true(iterable, default=False, pred=None): """Returns the first true value in the iterable. If no true value is found, returns *default* http://docs.python.org/3.4/library/itertools.html#itertools-recipes """ return next(filter(pred, iterable), default)
de983517cfcc5d7ac57551e7ac57952fb7f69ec2
52,265
def _fHN(phi, const, lamb, omega, alpha, beta, gamma, S, K, t, r, real=True): """ real=True to return fstarHN, real=False to return fHN """ # Internal Function: # Model Parameters: gamma = gamma + lamb + 1 / 2 lamb = -1 / 2 sigma2 = (omega + alpha) / (1 - beta - alpha * gamma ** 2) ...
b8c2552f04bf650284fc1fc19086c561447ba012
52,266
def build_season_div(num, nomen, season): """ Build the string for the HTML div representing an entire season """ txt = SEASON_START % {'season': str(num), 'name': nomen} for episode_num in sorted(season.keys()): txt += build_episode_row(season[episode_num]) txt += SEASON_END return txt
445469a592f7a8902c4d6a22b080d30e4ba1c579
52,267
def create_batch_groups(test_groups, batch_size): """Return batch groups list of test_groups.""" batch_groups = [] for test_group_name in test_groups: test_group = test_groups[test_group_name] while test_group: batch_groups.append(test_group[:batch_size]) test_group =...
70de6428ab94a104b8a2573e2dc920a55712351a
52,268
import itertools def _random_menu(update, context): # pylint: disable=unused-argument """Present the user the comic options""" comics = database_query("SELECT name FROM sources") buttons = [InlineKeyboardButton(f"{name}", callback_data=name) \ for name in itertools.chain.from_iterable(comics)] ...
0214acaa908ae0ecc8010e9012a707c30a88f33b
52,269
def pr_hr_series(): """Return hourly time series.""" def _pr_hr_series(values, start="1/1/2000"): coords = pd.date_range(start, periods=len(values), freq=pd.DateOffset(hours=1)) return xr.DataArray( values, coords=[coords], dims="time", name="pr",...
ad891960b7dabe135708d98164f36cff70b4096c
52,271
def calculate_derivative(contour_points, target_index): """ Calculates derivative. Calculates the derivative of the current point(contour_points[target_index]) and returned it. Args: contour_points:: [RPoint, RPoint, ...] RContour's points(RPoint objects) to be derivative. ...
fa942868f0b4841a96417ac2a28a8ab200832be9
52,272
def _get_timeout(value): """ Turn an input str or int into a float timeout value. :param value: the input str or int :type value: str or int :raises ValueError: :returns: float """ maximum_dbus_timeout_ms = 1073741823 # Ensure the input str is not a float if isinstance(value, ...
b8205cb34b90b856b4dda2a028f801b4cd70d7b4
52,273
def addScriptTestsTo(TestClassFactory, tests): """Add all the tests to the test class""" TestClass = TestClassFactory() for idx in range(len(tests)): setattr(TestClass, "test%d" % idx, getScriptTestMethod(tests[idx])) return TestClass
7ae1780004ae13ec05fa9d45fb6b99ac525d778e
52,274
def _latest_snapshot_path(experiment_name): """Return the latest pkl file""" return osp.join(DATA_DIR, "%s.latest" % (experiment_name))
6d1030b2140c28a2049741a38c91a9dd40a853ad
52,275
import json def lambda_handler(evt, ctx): """AWS Lambda entrypoint""" try: return awsgi.response(app, evt, ctx) except Exception as err: print(f'{err}') return { 'statusCode': 500, 'body': json.dumps({ 'message': 'internal server error', }) }
863841f416390415f7c3d2f6fc8d1b574ea50b49
52,276
import xml def get_next_pid(custom_xml): """Get highest pid from XML file.""" maxPid = 0 e = xml.fromstring(custom_xml) for prop in e: if 'pid' in prop.keys(): thisPid = int(prop.get('pid')) if maxPid < thisPid: maxPid = thisPid return str(maxPi...
3e3c351415d8b24ec51cb541ba588ed2604b9b4c
52,277
def pad_input_ids_msmarco(input_ids, max_length, pad_on_left=False, pad_token=0): """An original padding function that is used only for MS MARCO data.""" padding_length = max_length - len(input_ids) padding_id = [pad_token] * padding_length if padding...
dc75d5d72e4e1633301ff083936e08420ef17883
52,278
def get_child_context(xml_node: XmlNode, parent_node: Node, _: RenderingContext) -> RenderingContext: """Return""" return RenderingContext({ 'parent_node': parent_node, 'node_globals': InheritedDict(parent_node.node_globals), 'xml_node': xml_node })
32d1dd184e86561895d22882ff3551a152363830
52,279
def generate_map(lat, lon): """ Generate a map object for a given set of latitude and longtitude """ distances = _distance_from_coordinates(lat, lon) # Sort distances in ascending order sorted_distances = sorted(distances) split_distances = sorted_distances[:2 * app.config["NUM_OF_HOTSPOTS"]...
a43ea1955ca2e22d6ce0c94d71323136fe01b04a
52,280
def build_grid_ds_tf(sorted_keys, num_cells, batch_size, name=None): """ Method to build a fast access data structure for point clouds. Creates a 2D regular grid in the first two dimension, saving the first and last index belonging to that cell array. Args: sorted_keys: An `int` `Tensor` of shape `[N]`, t...
ecb8c71bbf0f5782371c8c816c733692ede2b46d
52,281
def check_class(module_name, class_name, packages=None, pip_args=None): """ Checks whether a class is present in the specified module and (tries to) install if packages have been provided. :param module_name: the module to check :type module_name: str :param class_name: the name of the class to che...
feaca6bb43bebba4e80784b196cb50a0977b6fa6
52,282
def getsyncat(word): """Returns a list of all syntactic categories of the word as strings or an empty list if no results.""" syncats = ', '.join(list(SYNCAT_ORDER.values())) tup = (word.upper(),) c.execute('''SELECT {0} FROM syncat WHERE word=?'''.format(syncats), tup) result = c.fetchone() re...
ed91a2ad01616e720b11a6a436304dcdcac39898
52,283
def prompt_for_instances(ecs_instances, asg_contents, scale_down=False, sort_by="launch_time"): """ sorts the instances into an order that tries not to cause an AZ imbalance when removing instances. Also, prompts the user if there are issues. @param ecs_instances: list of ECSInstance() objects @para...
6f553330e84dc824ddd9f75cd7f4fb03c19211f6
52,284
def classifier_extra_metrics(features, labels, predictions): """Returns extra metrics to use with classifier.""" if 'logistic' in predictions: return { 'my_mean_prediction': tf.compat.v1.metrics.mean(predictions['logistic']), 'my_mean_age': tf.compat.v1.metrics.mean(featu...
6999ddc6257b7a65c9b71d3ce8e57de2cdce62da
52,285
def getAnswer(x,input_string): """Iegūst mainīgajam x vērtību 1 vai 2, parādot tekstu input_string. Ja ievadīta nepareiza vērtība, tad tiek paradīta kļūdas ziņa.""" while True: try: x = int(input(input_string)) if x < 1: raise ValueError elif x > 2: r...
66f8b1cccef5fb710713f1c6498248dd0f3517ea
52,286
import requests def get_model_version_uri(project_id: int, model_id: Text, version: Text) -> Text: """Get model version URI. Args: project_id {int}: project id model_id {Text}: model id (name) version {Text}: model version Returns: Text: path to model package for model vers...
946c5a1b9b5dabf6350bc3c6c3167d5d8389fea4
52,287
def _depc_factory(name, cache_dir): """DependencyCache factory for the examples Args: name (str): name of the cache (e.g. 'annot') cache_dir (str): name of the cache directory """ cache_dpath = HERE / cache_dir controller = DummyController(cache_dpath) depc = DependencyCache( ...
5b7eab9882e43b27ca4e58dace32e1dbe9b3d5bd
52,288
def nx_to_pandas(g): """ Convert directed multigraph stored as NetworkX MultiDiGraph into Pandas DataFrame. Parameters ---------- g : networkx.MultiDiGraph Directed multigraph to convert. Returns ------- df_node : pandas.DataFrame Node attributes. The NetworkX identifie...
344d0ee7dce5885a2f73709fefbe916cc0dbe125
52,289
def get_case_properties(patient, importer): """ Returns case name and dictionary of case properties to update Raises ConfigurationError if a value cannot be deserialized using the data types given in a column mapping. """ name_columns = importer.name_columns.split(' ') case_name = ' '.join(...
28e6bfc7d052f6d289b8984ca2d455e6e32d0a24
52,290
def review_log(request, type, ctype_id, obj_id): """ Display list of record changes and allow user to select status (approved/not approved) """ current_user = request.user log_list = LogEntry.objects.filter(content_type_id=ctype_id, object_id=obj_id) if type == 'user': # exclude chang...
087ba64d4bc829a66b0a4e35a68d5abebcb0c760
52,291