content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import math import random def interim_move_helper(stats, c): """ Function to return a key for the interim move helper :param stats: List of stats :param c: Exploration parameter :return: Function for interim move helper to use as a key """ top = math.log(sum(stat[0] for stat in stats)) ...
03326eeea8ce0d155675caea8e5d78c2f9ab34c4
625,222
import os def page_to_html_path(page): """Given a page target, return partial path for an output `.html`.""" source_path = page.sources_relative_to_buildroot()[0] return os.path.splitext(source_path)[0] + ".html"
d2dd9d89b4f2925833828ad76d238519ea486a70
625,223
def make_terms_from_string(s): """turn string s into a list of unicode terms""" u = s return u.split()
1b4a3d2587f5edeefb4c91449a0700caf9d9aa91
625,224
def requires(*methodList): """ Optional decorator for shard functions to list any dependencies. If a shard uses methods it does not provide/import, it should declare them using this function or by setting the __requiresMethods attribute manually. If this attribute is not present, it wi...
fd7c1f6da0c3f3e0b29bd1dbc67d4c0265d43063
625,225
def read_input(): """ Reads input from stdin, shutting down logging and exiting if an EOFError occurs :return: input read """ try: return input() except EOFError as eof: raise SystemExit(eof)
740997e4279778c8d2417e87f99fc8ac18f924de
625,226
def _convert_tensor_base(tensor_data): """Convert tensor object to dict.""" tensor_data_dict = { 'dtype': tensor_data.dtype, 'shape': tensor_data.shape, 'data_size': tensor_data.data_size } return tensor_data_dict
54cfd44546b880f9f429636e30e6a12c1ad437b8
625,227
def get_qual_name(o, lower=False): """ Returns the qualified name of an object o. """ if not isinstance(o, type): o = o.__class__ if lower: return o.__qualname__.lower() else: return o.__qualname__
166672a8242a6d388d46e707155363d13f09b066
625,228
def _CreateAptPkgRepo(messages, repo_name): """Create an apt repo in guest policy. Args: messages: os config guest policy api messages. repo_name: repository name. Returns: An apt repo in guest policy. """ return messages.PackageRepository( apt=messages.AptRepository( uri='http:/...
9d1eea651d71b494cb165681a7eaf8f105245799
625,229
def python_social_auth_shim(pipeline_func): """Shim layer decorator for django-social-auth to python-social auth migration pipeline complete wasn't passing the request object, but the strategy object instead """ def wrapped(strategy, *args, **kwargs): if not kwargs.get('request'): re...
e2cd1cd56070b0630b03ba4c007f138a88766056
625,230
import json import hashlib def md5(param: str, len=32) -> str: """ 计算对象或者字符串的MD5值 @param param: @return: """ if type(param) != 'str': param = json.dumps(param) return hashlib.md5(param.encode()).hexdigest()[0:len]
4280665acf50d364f8d8f7a29ff09c7d1f2682a6
625,231
def _get_defines(header): """ Returns list of define statements Parameters ---------- header : str CppHeader Returns ------- defines : list List of define directive strings """ defines = [] for inc in header.defines: defines.append(f'#define {inc}') ...
a21d5268c73a5ee57ca9aebab89b77eaa95add5d
625,232
import torch import math def affine_quant_func(x, k, lower_bound, upper_bound): """ Quantize input variables via affine methods. input type: TensorT, int, float, float output type: float, TensorT, int Returns: - delta: magnitude of quantized values; - quant_idx: same shape wi...
f4a7a17692c3e44ab3c129bd9eef1218b89e4986
625,234
def get_hertz(reg, key): """Returns the hertz for the given key and register""" return int(reg * 2 ** (key / 12))
5a5945036f3538e313ab6932f800f7c050b8395d
625,235
def cpf_int_validation(cpf: int) -> bool: """ Validation CPF integer. Args: cpf (int): CPF. Returns: bool: If CPF real True else False. """ clean_cpf = str(cpf).zfill(11) digito = {} digito[0] = 0 digito[1] = 0 a = 10 total = 0 for c in range(0, 2): ...
415808dc469b58fef3676665a933b43427a449f8
625,236
import os import requests def lookup(country): """Look up covid-19 stats for country.""" # if user has not provide any country, look for all data if country == "WORLD": url = "https://covid-19-data.p.rapidapi.com/totals" # Contact API try: querystring = {"format": "js...
79a6376e71e9497d47f9accc6f36d44685f0ad24
625,238
import math def parent(level, idx): """ Return the parent of a given healpix pixel (in nested format) :param level: Resolution level :param idx: Index at the given level :return: Tuple (lvl, idp) including the level and the index of the parent pixel """ assert idx < 12 * 2 ** (2 * level) ...
d933089ab56baa8e692981ebda2741421f91a8a6
625,239
from typing import List import re def _split_strip_string(string: str) -> List[str]: """Split the string into separate words and strip punctuation.""" string = re.sub(r"[!()*+\,\-./:;<=>?[\]^_{|}~]", " ", string) string = re.sub(r"[\'\"\`]", "", string) return re.sub( r"([A-Z][a-z]+)", r" \1"...
08bb28277b00f4c178a87f96c9df8b31c4b7273b
625,240
from typing import Optional from typing import Any def clean_csv_value(value: Optional[Any]) -> str: """Escape a couple of things that postgres won't like""" if value is None: return r'\N' return str(value).replace('\n', '\\n')
934d9e3ce39b418df5a1ef88028a33859417c8f7
625,243
def get_address_type(ip_type): """ Return the address type to reserve. """ if ip_type in ['GLOBAL', 'REGIONAL']: return 'EXTERNAL' return 'INTERNAL'
ef0674f82a82936b940ad2a0ddbda597ec0434c5
625,244
def ss_to_index(ss): """Secondary structure symbol to index. H=0 E=1 C=2 """ if ss == "H": return 0 if ss == "E": return 1 if ss == "C": return 2 assert 0
e239d7a257c0380ada1205fb6ef1d9fdc77aebef
625,245
import random import string def random_alphanumeric(length=5, upper_case=False): """Generate a random alphanumeric string of given length :param length: the size of the string :param upper_case: whether to return the upper case string """ if upper_case: return ''.join(random.choice( ...
d9072421639d629516911b72b451905d08063cc9
625,247
def provided(*args): """checks if given flags are specified during command line usage""" if any(flag is not None for flag in args): return True
e6a0fc800dacedb852adc3042f859435f5a6b464
625,248
def split_with_index(x_matrix, y_vector, indexer): """ :param x_matrix: :param y_vector: :param indexer: :return: """ x_indexed, y_indexed = x_matrix.loc[indexer], y_vector.loc[indexer] return x_indexed, y_indexed
8e45cc2cf08f4cce1ea74aacb388eb6a9e704735
625,249
import copy def filter_not_done(exp_list, inclusion_list, exclusion_list): """ remove any unwanted experiments, and keep only those desired :param exp_list: list of experiments from find_not_done :param inclusion_list: list of substrings of experiment names if substring in experiment name we k...
cd6d15d056d8e8552e80a6d0a79924053ca2ab71
625,250
def multi1(vals): """ This will either return the common value from a list of identical values or the single character '?' """ uniq_vals = list(set(vals)) num_vals = len(uniq_vals) if num_vals == 0: return None if num_vals == 1: return uniq_vals[0] if num_vals > 1: ...
82738cabd851d9ae49546b08700b1b0f532175f7
625,251
from subprocess import Popen, PIPE def getstatusoutput(cmd): """ Executes a shell command on the platform using subprocess.Popen and return a tuple of the status and stdout output. """ # Set stdout and stderr to PIPE because we want to capture stdout and # prevent stderr from displaying. p...
6e7a0bc44f713ac32b0fe94277d953622bf2283b
625,252
import torch def calculate_neighbor_angles(R, id3_i, id3_j, id3_k): """Calculate angles for neighboring atom triplets""" Ri = R[id3_i] Rj = R[id3_j] Rk = R[id3_k] R1 = Rj - Ri R2 = Rk - Ri x = torch.sum(R1 * R2, dim=-1) y = torch.cross(R1, R2) y = torch.norm(y, dim=-1) angle = ...
0ba4a4d88c9bbdd0836a0bdcf9b6231b47df92b9
625,253
import math def orbitalspeed_vrt(radius,time): """Usage: orbitalspeed_vrt(radius of orbit, time taken)""" return (2*(math.pi)*radius)/time
799e178bf13ac4018c249fc9c10d37ae09b73f82
625,254
def ternary(value, result_true, result_false): """ Implements a ternary if/else conditional. """ return result_true if value else result_false
dfe9fa86b4304520b8995f73e8718b4882b65734
625,255
def square(x): """ Squares given number """ return x ** 2
d08f1a4d006d9ff3cd1cc2c0aa75e1db3a1a197a
625,256
def flatten_dict(tree, parent_key='', sep=' '): """ Recursively flatten a nested dictionary into a single level whose keys are phrases. For example, given the following dict: ..code-block:: python { 'my': { 'git': { 'branch': 'master' ...
9929772d1eb382fdafe6e890bb34e76c361ee160
625,257
def rmse(target, mask, pred): """ :param target: HxW :param mask: HxW of {0,1} :param pred: HxW :return: """ assert target.shape == mask.shape == pred.shape, f'{target.shape, mask.shape, pred.shape}' if mask.sum() == 0: return 0 else: mask = mask.byte() if has...
5e3675e465a80cda3e4d42c931bff10381498112
625,258
import random def play_game_stay(stage): """Compare random choice to choice list. Return 1 for Win. 0 for Loss.""" player_guess = random.randint(0, 2) if stage[player_guess] == 'Cadillac': state = 1 else: state = 0 return state
28e4bc379052c40a1e62b014e7b4ef1c26ee2d6d
625,259
import re def detect_timestamp_format(timestamp): """ Given an input timestamp string, determine what format is it likely in. :param string timestamp: the timestamp string for which we need to determine format :return: best guess timestamp format """ time_formats = { 'epoch': re.compile(r'^[0-9]{10...
20eb2f8fc2f14525b64e3ee66d776f29a3907e88
625,260
def rounds(): """Prompt user. Return number of rounds as integer. """ while True: try: return int(input("Type the number of rounds to play and press enter: ")) except ValueError: print("Sorry, that\'s invalid input. Try again: ") raise
7182b020aab8fe894e7da04081037e1300d16d69
625,261
import io def read_img_bin(img_fn): """Get image binary from an image file. Args: img_fn: image file path. Returns: image binary data as bytes. """ with io.open(img_fn, "rb") as f: img_bin_bytes = f.read() return img_bin_bytes
05b7b049a0778da8dc7b28b0b478022cb41be95a
625,262
def calculate_common_period(a_times, b_times): """ Calculate the common period between two time series. Parameters ---------- a_times, b_times: numpy arrays of numpy datetime64s Arrays of datetimes. Returns ------- start_time: the latest of the two series start times. finis...
96d511179e46364863c6b45c60e239ae6c959417
625,263
import os def get_image_name(path): """ Returns name of generated docker image. Parameters ---------- path : str Path to .tar.by2 package build by conda-build """ assert path.endswith('.tar.bz2') pkg = os.path.basename(path).replace('.tar.bz2', '') toks = pkg.split('-')...
c507ed11f1238eb1f4057b64cd786a1386cc66fa
625,264
def operation_1(request): """ This will be in description """ return {"docstrings": True}
8d9de8583bf7ddb111e40ac95ace2e2c17aad002
625,266
def gmean(fdatagrid): """Compute the geometric mean of all the samples in a FDataGrid object. Args: fdatagrid (FDataGrid): Object containing all the samples whose geometric mean is wanted. Returns: FDataGrid: A FDataGrid object with just one sample representing the geom...
02b8f32f8bef9ce017fdae71bbc9db12d36360b4
625,267
def isWithinUnitedStates(latitude, longitude): """Returns true if the latitude longitude pair is roughly within the boundaries of the United States. Returns false otherwise""" return (25 < latitude and latitude < 50) and (-127 < longitude and longitude < -65)
ca1ea79dbf221895b16d3a6dd04e217eb1f88262
625,268
import bz2 import gzip def file_open(filename, mode="r"): """ Open a file, and if you add bz2 to filename a compressed file will be opened """ if "bz2" in filename: return bz2.open(filename, mode + "t") if "gz" in filename: return gzip.open(filename, mode + "t") return open(filenam...
416f6d5c5eee68810c735a65093c97bbb38ab90f
625,269
def _extract_hidden_state(state, cell_type): """extract hidden state""" return state.h if "lstm" in cell_type else state
0e1d4764626028267748cc7deed65f8236fa0b2c
625,270
from typing import Union def _get_optional_type(type_): """Check if a type is an ``Union`` permitting ``None``. For ``Optional``-like unions permitting only ``None`` and another type, returns the other type. For other ``None``-permitting unions, returns ``True``. For everything else, returns ``False``. ...
d727bd47d0edeb5ef208d63b8270fbafa2955ac2
625,271
import subprocess import shlex def get_ip(): """ Use a DNS server to get the host's external IP. """ # https://unix.stackexchange.com/a/81699 cmd = "dig +short myip.opendns.com @resolver1.opendns.com" proc = subprocess.Popen( shlex.split(cmd), stdout=subprocess.PIPE, s...
a9244d884d0d75a276bba1c027bbedde8ade663f
625,272
def timestamp2date(ts): """ Converts Timestamp object to str containing date """ date = ts.date().strftime("%Y-%m-%d") return date
972173fce1120db8e71b4ae5ff4347191b4c876f
625,273
def hide_tokens(request): """ Hide tokens in a request """ if 'context' in request: [request['context']['tokens'].update({key: '*****'}) for key in (request['context']['tokens'] if 'tokens' in request['context'] else [])] return request
74712dd3143304c0ea6947259c598f408be6d37f
625,274
import time def time_delta_now(t_start: float) -> str: """ Convert the difference of the given timestamp and now into a human readable timestring. Args: t_start (float): Start timestamp. Returns: Human readable timestring of time passed between `t_start` and now. """ a = t_sta...
86e54939cddb8d262649780644dec2678fcb85f1
625,275
import subprocess def exec_command_all(*cmdargs, **kwargs): """ Wrap creating subprocesses Return tuple (exit_code, stdout, stderr) of the invoked command. """ proc = subprocess.Popen(cmdargs, bufsize=-1, # Default OS buffer size. stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwa...
c5bd77af7ef5ddc9ae6cc7ef0eac80dbda0a7791
625,276
from typing import OrderedDict def _get_sorted_participants_by_type(mur): """ Returns the participants in a MUR sorted in the order of most important to least important """ SORTED_PARTICIPANT_ROLES = [ "Primary Respondent", "Respondent", "Previous Respondent", "Trea...
752e8dfca39d6865c193c68374766d896fc5245f
625,277
import math def convert_kelvins_to_rgb_bartlett(color_temperature: float) -> tuple: """ Convert Kelvin temperature to black body emission RGB color using approximation by Neil Bartlett Author used the ideas of Tanner Helland and came up with a slightly better approximation Source: http://www.zombiepro...
8f71ae983c8db7fbc5be764c6d763d7ffa3d8a99
625,278
from typing import Tuple def stats2gamma(mu, sigma) -> Tuple[float,float]: """convert mean and sd of any distribution into gamma alpha and beta. """ alpha = mu*mu/sigma/sigma beta = mu/sigma/sigma return(alpha, beta)
adafcdee01c2909f329d00b390bfb7e9c8211dcb
625,279
def remove_leading_spaces(data): """ Remove the leading spaces (indentation) of lines of code :param data: input data as a list of files, where each file is a list of strings :return: input data with leading spaces removed """ for i in range(len(data)): for j in range(len(data[i])): ...
092b5bf59b9202a045a9d0739a0e79d0d7923b38
625,280
def reverse(s: str) -> str: """ For a string s return the reversed string s[::-1]. """ return s[::-1]
2e56beb19f839e3304b58ab31c3f2ddf831e48c9
625,282
def decodeToString(toDecode): """ This function is needed for Python 3, because a subprocess can return bytes instead of a string. """ try: return toDecode.decode('utf-8') except AttributeError: # bytesToDecode was of type string before return toDecode
06cb8ce00edc159fe8a8f01700ba7c3813dac5cc
625,283
def get_db_connection_tz(cursor): """ Return time zone of the Django database connection with which the specified cursor is associated. """ cursor.execute("SHOW timezone;") return cursor.fetchall()[0][0]
4a0adac1ee4c47073b67af743a41b77ba10f5df6
625,284
import math def probability_to_bayeselo(probability): """ Takes a probability: P['win'], P['loss'] Returns elo, draw_elo """ assert (0 < probability['win'] < 1 and 0 < probability['loss'] < 1) elo = 200 * math.log10( probability['win'] / probability['loss'] * (1 - probability['...
33bf719798ad5bec4d93ff463df0f20963b321d1
625,286
def hex_to_bin(hex_value) -> str: """ Convert all hex digits to binary representation, with leading zeroes """ bin_len = 4*len(hex_value) # 4 bits per hex return "{0:0{width}b}".format(int(hex_value, 16), width=bin_len)
259c67a5ce3b8437645ec2b28075843b7656ec1d
625,287
import socket def get_unused_port(): """ Get an empty port for the Pyro nameservr by opening a socket on random port, getting port number, and closing it [not atomic, so race condition is possible...] Might be better to open with port 0 (random) and then figure out what port it used. """ so = ...
7a40e7f336b8077dd11d65f81e4f068f3419bc3d
625,288
from typing import Dict from typing import Any from typing import List def handle_price_rows( card_data: Dict[str, Any], card_uuid: str ) -> List[Dict[str, Any]]: """ This method will take the card data and convert it, preparing for SQLite insertion :param card_data: Data to process :param car...
8f33bdcef0b6cc048199dd7c12f680b8886e164b
625,291
def center_trim(tensor, reference): """ Trim a tensor to match with the dimension of `reference`. """ if hasattr(reference, "size"): reference = reference.size(-1) diff = tensor.size(-1) - reference if diff < 0: raise ValueError("tensor must be larger than reference") if diff...
4d0d60e39be95ad1d1c78c1e40fd896a612190d8
625,292
def get_grade_suffix(grade): """ Select correct ordinal suffix """ ordinal_map = {1: 'st', 2: 'nd', 3: 'rd'} teens_map = {11: 'th', 12: 'th', 13: 'th'} return teens_map.get(grade % 100, ordinal_map.get(grade % 10, 'th'))
c2e35bf60e46708dd086f190005a479ce02b0ff2
625,293
import os def to_png_fn(fn): """ Append png as filename postfix """ directory, filename = os.path.split(fn) basename, ext = os.path.splitext(filename) return basename + ".png"
c9ea85390533c62dbc3f3d336351bac738b47ffe
625,294
def zif_bank_code(zif_pinout: list): """ Return a list encoding even/odd ZIF pins in the data acquisition order. Empirically, this has been useful for finding differential offsets in array maps (although the ZIF even-/odd-ness tends to overlap with other pin breakouts). >>> print(zif_pintout(zif_by...
195e8a96c1a2aa985c3e87563ed298aded4a6517
625,296
import copy def ramsey(graph_adt): """Ramsey algorithm to approximate the maximum independent set""" #base case of the recursion if graph_adt.order()==0: return [] #select a random vertex #this can be optimized by selecting the vertex with the smallest degree selected=graph_adt.v...
aaa03a335d8f0663ee70d89cde93ebb6ac750084
625,297
def parse_pattern(seq: str): """ A function to substitute RegEx in the sequence string sequence: A string that contains a comma seperated numbers and patterns returns: A string after replacing the patterns with a specific regex """ _RE1 = r'(\+|-)?\d+' _RE2 = '.+' # Clear seq from space...
f83d17c02eac20cfeaaac5ddd1910b7ed91a3586
625,298
def GIS(op): """A test util function to generate the gradient name for input.""" return [s + '_grad' for s in op.input]
fa8cb8dd31607fee824f1b2d2e42e0d6ba548f04
625,299
import os def split_prompt(prompt): """Split an input string of the form 'string:float' into three returned objects: string, float, -inf Args: prompt (string): String of the form 'string:float' E.g. 'a red boat:1.2' Returns: text (str): The substring from prompt prior to the colon, e.g. ...
736d84f43f936ea1044360de2009171581d3a771
625,300
import re def get_url_re(): """ Generate a URI validation regexp. Slightly modified from Django's URL validation https://github.com/django/django/blob/master/django/core/validators.py """ ul = '\u00a1-\uffff' # unicode letters range (must be a unicode string, not a raw string) # IP patter...
ed00d5dd2339e51a53f6ba0dcbfb9c9a8cfe0a01
625,301
import pathlib def gef_makedirs(path: str, mode: int = 0o755) -> pathlib.Path: """Recursive mkdir() creation. If successful, return the absolute path of the directory created.""" fpath = pathlib.Path(path) if not fpath.is_dir(): fpath.mkdir(mode=mode, exist_ok=True, parents=True) return fpath....
88915dfcbafc51e4066c6491b60f56c028ee1814
625,302
def convert_line_graph_path(path: list) -> list: """ Converts the given shortest path for the line graph into the min cost path in the original path. In principle, this means extracting the nodes in the right order from the given line graph path. The given line-graph path looks like: (n1, n2), (n3, n4) ...
d8c9ff0a5e41ae18d95af1919ffab3cf6c7e8869
625,303
def replace_first(base, old, new): """Replace the first substring with new string""" return base.replace(old, new, 1)
dc8746532ed6f0a3f85b16e77836824ffe9bc16a
625,304
def parse_nuclide(nuclide: str) -> str: """ Parses a nuclide string from e.g. '241Pu' or 'Pu241' format to 'Pu-241' format. Not this function works for both radioactive and stable nuclides. Parameters ---------- nuclide : str Nuclide string. Returns ------- str Nucl...
685d41a4007c09da33cc19919c0aa3b8191442fe
625,305
import os def sumDirectorySize(path): """ Calculate the total size of all the files under |path|. """ total = 0 def reraise(e): raise e for root, dirs, files in os.walk(path, onerror=reraise): for f in files: total += os.path.getsize(os.path.join(root, f)) retur...
51d7f1a519315b1789bc72bbc3d15401b55c28b6
625,306
import os def _no_path(macro_file): """Everything is run in the same folder so no full path is needed""" bp, fn = os.path.split(macro_file) return fn
9503c1d9476bf6f48da792de09daea3d58bdd1e6
625,307
from pathlib import Path from typing import List import json def read_geometries(file_name: Path) -> List[str]: """Read the geometries from ``file_name``.""" with open(file_name, 'r') as f: gs = json.load(f) return gs
d5cb15ce95e381fb357cbb7498f81a23ad9354c3
625,308
from typing import OrderedDict def make_OrderedDict(dictionary): """ Makes an OrderedDict from given dictionary already containing keys and values. Parameters: dictionary : dictionary Any kind. Returns: ordered_dict : OrderedDict The ordered dict version of th...
415d1d669704b02923dfbdb05485f95c46abfed1
625,309
import torch def bbox_cxcywh_to_xyxy(bbox): """Convert bbox coordinates from (cx, cy, w, h) to (x1, y1, x2, y2). Args: bbox (Tensor): Shape (n, 4) for bboxes. Returns: Tensor: Converted bboxes. """ cx, cy, w, h = bbox.split((1, 1, 1, 1), dim=-1) bbox_new = [(cx - 0.5 * w), (c...
8af287f1bcf1d4b26ed8c6bbc2aab9b45d6b730d
625,310
def name_combine(prod_names): """writing a function to join the list, from a tuple to a string""" for i in range(len(prod_names)): names_list = print(''.join(prod_names[i][0]), ''.join(prod_names[i][1])) return names_list
5d4aca2d706bf0ed4ab5bbc9e9036d7c7123d7c8
625,311
def factorial(num): """ This function calculates factorial of a number recursively. n! = n*(n-1)*(n-2)*...*2*1 Parameters ---------- num : uint64 Input positive integer to calcuate factorial. Returns ------- uint64 Factorial of input positive integer. """ ...
e2e145c73ab1cbf647fbea97f84f8e93d701983d
625,312
def _encode_string(s: str) -> bytes: """ Encode a python string into a bencoded string. """ return f"{len(s)}:{s}".encode("utf-8")
7d9d3c7c12a1ca1d0d18f4d8649ebb0fea7a9c0b
625,313
import math def droop_quota(number_of_votes, number_of_seats): """The `Droop quota`_ for Single Transferable Vote tabulation. A candidate whose vote total meets this quota wins a seat. .. _`Droop quota`: https://en.wikipedia.org/wiki/Droop_quota """ return math.floor(number_of_votes / (number_of_...
b46516e008f8bbc9b723dc84eff7c63025950736
625,315
def _get_downcast_field(class_reference): """Get the downcast field name if set, None otherwise.""" return getattr(class_reference, "__deserialize_downcast_field__", None)
6851aaf6889c0a9e2441f0a59b2d12e6e4a50ce0
625,316
def solution(X, A): """ For this task, we simply need to record where the leaves have fallen. As soon as we have a bridge, we cross. """ # initialise variables to keep track of the leaves leaves = [False] * X leaves_count = 0 for idx, val in enumerate(A): # leaf has fallen on ...
62115eb815360d6cf381f1db54313ba502f6aba6
625,317
from pathlib import Path def validate_config_file_path(cfg_path: Path) -> Path: """Locate the configuration file.""" if not cfg_path.is_file(): raise OSError(f"Config not found at {cfg_path!r}") return cfg_path
11cdc7e69bd4248a5bfb1ca2cb21e33cca63d289
625,318
def prefixes(s: str): """ Returns the prefixes of the string given in parameter """ return (s[:i] for i in range(len(s) + 1))
9408a961dd2784dbb9f5c404ec0c6a35a9a25304
625,319
def countBobs(txt): """Function tha counts how many "bob" strings are in the sentence txt = string return: int """ c = 0 txt = txt.upper() for i in range(len(txt)): k = i + 3 if (txt.find("BOB",i,k) != (-1) ): c+=1 return c
fff53934fcc13d9daf0ba502b6a5e1b65c14b6f9
625,320
def get_linux_vms_for_endpoint(coriolis, source_endpoint, source_options=None): """ Returns a list of the names/IDs of Linux VMs on a source endpoint """ vms = coriolis.endpoint_instances.list( source_endpoint, env=source_options) return [vm for vm in vms if vm.os_type == 'linux']
a84cd4c34f830bc0eef195def852cf3f87f01e17
625,321
import math def get_exponential_weighting_function(base=math.e): """ Returns a function that weights its input by raising the ``base`` to the power of the input; see :ref:`selection-strategy` :param base: the base to raise to the power of the input :type base: int/float :returns: a exponential function ""...
50bb8c775bd66a684f14b3f910eecf56fa6c072c
625,323
def filter_by_shapeloc(df, n0_loc, n1_loc, n2_loc=None): """Filters all results with the same `n0_loc * n1_loc`. This implies shapeK_loc has same no. of points. This is a weak check and the shapeK_loc may not have the same shape. Make sure all shapes are estimated and tested apriori using: >>> flu...
7420eaefe7aa3a7b701f6f0476b2aebfdbf7784a
625,324
def get_dim_inds(generalized_tensor): """ Returns a tuple 0..length, where length is the number of dimensions of the tensors""" return tuple(range(len(generalized_tensor.shape)))
0df852b109431c33511736c3527086eedf9c4c75
625,325
def request_method_predicate(self, obj, request): """match request method. Predicate for :meth:`morepath.App.view`. """ return request.method
1852ec8f8b0391b3191eeeddf8f240b16f4ff570
625,326
def valid_state(floors): """Check if state is valid.""" for floor in floors: machines = set(x[0] for x in floor if x[1] == 'M') generators = set(x[0] for x in floor if x[1] == 'G') unshielded_machines = machines - generators if generators and unshielded_machines: retu...
e078685d5426f87d99cc3736780d2b731e375237
625,327
import requests def create_http_reader(url): """ Simple reader for an HTTP resource. """ def http_reader(): return requests.get(url).content return http_reader
384457e603222d7a2fd23d08c1a1c72a7dd718f0
625,328
import io def generate_generic_error_message(exception: Exception, lineno: int) -> str: """ Generate a generic error message in the following format: { exception.__class__.__name } in line { lineno }: { str(exception) } """ buffer = io.StringIO() buffer.write('\n') buffer.write(excep...
9a5b04dd20451d0a3b0868a75f8e8be46e367086
625,329
def explain(server_inst): """ to_string() for server instance """ if server_inst is not None: withmsg = "with " + str(server_inst.wsize) + " MPI process" if server_inst.wsize > 1: withmsg += "es." else: withmsg += "." return "[ID: " + str(server_inst.sid) ...
048869852285eca5c10b17e67a45c1792c5c798c
625,330
def get_Theta_star_hs_in_d_t(Theta_star_NR_d_t): """(19) Args: Theta_star_NR_d_t: 日付dの時刻tにおける負荷バランス時の非居室の室温(℃) Returns: 日付dの時刻tにおける負荷バランス時の熱源機の入口における空気温度(℃) """ return Theta_star_NR_d_t
c1b5d9534278fb7e787532931175d705a4f3a707
625,331
import requests import json def list_repos(server): """ 列出指定用户在Git服务器上拥有的所有的仓库(owner) :param server: Git服务器配置 :return: 仓库列表 """ server_type = server['type'] api = server['api'] username = server['username'] token = server['token'] headers = server['headers'] # 定义最终返回的所有仓库...
06e4c4f318150ae37b6e852e5eb744aee5aa3dc4
625,332
import platform import os def setTitleIcon(tkinstance): """Detect the platform and set the appropriate title bar icon. If OS can't be detected, or no appropriate icon file is present, no icon is set""" osStr = platform.system() pathRoot = os.path.dirname(__file__) iconsDir = "icons" if(...
11fd76a8da882acb05db552e633c13d8c489bd8c
625,333
def subset_records(response): """Filter to subset SPC archive and only save a subset of records.""" data = response['body']['string'] index = 0 # Grab whole lines up to this maximum size while index < 4096: index = data.find(b'\n', index + 1) if index == -1: index = 409...
41e039d4db8e6006414cd3805ffef22ee52a88ee
625,334