content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Union from typing import IO from typing import Any from typing import Optional import yaml def from_file( file: Union[IO[str], str], *, app: Any = None, base_url: Optional[str] = None, method: Optional[Filter] = None, endpoint: Optional[Filter] = None, tag: Optional[Filt...
3dc7ea5805fa82648c98878de02d6d37b6e432c2
35,400
def rand_score_choice(): """ 返回一个看似合理分布的成绩 :return: int """ score_choice = [randint(50, 80), randint(40, 60), randint(60, 80), randint(60, 80), randint(70, 90), randint(80, 100)] return choice(score_choice)
b34492746048c3ea42ab927b1d4be11bba810419
35,401
def getExactFreePlaceIndexForCoordinate(freePlaceMap, x, y): """ Returns the Exact Value for a given Coordinate on the FreePlaceMap :param freePlaceMap: The generated FreePlaceMap :param x: The X Coordinate on the FreePlaceMap :param y: The Y Coordinate on the FreePlaceMap :return: The Indexvalu...
4af9dec9163bd505f944f02db55a2dcfa80cb434
35,402
from typing import Optional async def get_bc_history(start_time: Optional[str] = None, end_time: Optional[str] = None, isp: Optional[str] = ''): """ ## **param**: start_time: 开始时间(可选参数) str 默认 当前时间前一月 end_time: 结束时间(可选参数) str 默认 当前时间 isp: ...
11dd27f17f4ba61fcd01332bff6a520a8373c415
35,403
def get_member_class(resource): """ Returns the registered member class for the given resource. :param resource: registered resource :type resource: class implementing or instance providing or subclass of a registered resource interface. """ reg = get_current_registry() if IInterfac...
50278b01b11760ccd38025389c2558737d73c7a4
35,404
def split_on_text(row): """Spliting original text into million character blocks for Spacy""" val = round(row['original_text_length'] / 1000000) final_texts = [] count = 1000000 counter = 0 for i in range(0, val): if (count + 1000000) > row['original_text_length']: final_texts...
678377650df3ca49cfb0d4404382589e32e3c6ae
35,405
from datetime import datetime import argparse def valid_date(s): """ validate passed date and throw exception if it is not valid """ try: return datetime.datetime.strptime(s, "%Y-%m-%d") except ValueError: msg = "Not a valid date: '{0}'.".format(s) raise argparse.ArgumentTypeError(...
d660f18402a24bf0d3866bbe43b1a10234410f80
35,406
def make_child_node(parent_node, action, state): """ Construct an child search node """ return SearchNode(state, parent_node, action)
4f7f0d91cbf7384c81c801adb1273e3c9c7c2916
35,407
def get_number(number): """ Repeats back a number to you --- operationId: getPetsById parameters: - name: number in: path type: string description: the number responses: 200: description: Hello number! """ return "Hello {}!".format(numbe...
22d6c8a7a5b3a8ff946e4dccaf5876134a0293cd
35,408
def get_user_by_id(uid, session=None): """Get user by id.""" with session_scope() as session: return session.query(User)\ .filter(User.id == uid)\ .first().to_json()
6273d51340b837bf12afa6eb3c77a03af88eacba
35,409
def make_grayscale(img: np.ndarray) -> np.ndarray: """Turns BGR image into grayscale.""" if len(img.shape) == 3 and img.shape[2] == 3: return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) else: return img
7fd184948d671ce501dc3a6e9396de0a5601d9a7
35,410
def GetKM3NeTOMGelAbsorptionLength(): """ A function to return the absorption length the gel of an KM3NeT OM Note: The file hit-ini_optic.f has three different datasets for this absorption length! However in the file hit.f it always is initialized with the same (gel_id=1). Thus this one is ...
2fc250b636a3d20baac3a3a28de4604132fe2ab1
35,411
def align_frontiers_on_bars(frontiers, bars): """ Aligns the frontiers of segments to the closest bars (in time). The idea is that frontiers generally occurs on downbeats, and that realigning the estimation could improve perfomance for low tolerances scores. Generally used for comparison with techni...
ef1f3d62a36065f64d31c4e4d7f6ce07045e2e5e
35,412
def sudo_command(cmd, user=None, password=None, extraopts=None): """Run a command with sudo and return the output, a tuple of (stdout, stderr). """ proc = sudo(cmd, user=user, password=password, extraopts=extraopts) return process.run_process(proc)
605372faca312b95f3c62244dde371e7550b72cc
35,413
def FK42FK5Matrix(t=None): """ ---------------------------------------------------------------------- Purpose: Create a matrix to precess from B1950 in FK4 to J2000 in FK5 following to Murray's (1989) procedure. Input: t, a Besselian epoch as epoch of observation. Returns: Transformation matrix M...
711ae31af8d6b0e55d940a3dd75cdc724c46e80c
35,414
def _rec_superdense(packet): """ Receives a superdense qubit and decodes it. Args: packet (Packet): The packet in which to receive. Returns: dict: A dictionary consisting of decoded superdense message and sequence number """ receiver = packet.receiver sender = packet.sender ...
f8f20554170b0549d71d0ed666dbea987148791f
35,415
def _high_bit(value): """returns index of highest bit, or -1 if value is zero or negative""" return value.bit_length() - 1
1bd783593ae7d5b15cc56c8a8db5c86798fd8c9f
35,416
import re from bs4 import BeautifulSoup def parse_round(bsoup, rnd, gid, airdate): """Parses and inserts the list of clues from a whole round.""" round_id = "jeopardy_round" if rnd == 1 else "double_jeopardy_round" r = bsoup.find(id=round_id) # The game may not have all the rounds if not r: ...
19cc79523de901ae773f5c808795c8c160291310
35,417
def on_end_validation(func): """ The :func:`on_end_validation` decorator is used to initialise a :class:`.Callback` with :meth:`~.Callback.on_end_validation` calling the decorated function Example: :: >>> import torchbearer >>> from torchbearer import Trial >>> from torchbearer.cal...
d58ac5f6cb4e2da08480e5ac9a18ec425b5f4946
35,418
from typing import Any from typing import List def transpose_checker( attrs: Any, args: List[relay.expr.Expr], op_name: str ) -> bool: # pylint: disable=unused-variable """Check if transpose is supported by TensorRT.""" if get_tensorrt_use_implicit_batch_mode() and int(attrs.axes[0]) != 0: logger...
fb5a3d0cbade224d269a1ca5bc54d86cff9ca6a1
35,419
from pathlib import Path def project_root() -> Path: """Returns project root folder.""" return Path(__file__).parent
7296e26ab57a3adcbde65df7ed5f1976ff3b84ca
35,420
def qual(obj): """ Return fully qualified name of a class. """ return u'{}.{}'.format(obj.__class__.__module__, obj.__class__.__name__)
5b9779935b84a8bb3653cc9fc2c627dda5dd0e7f
35,421
def treefactorial(high: int, low: int=None) -> int: """Pure Python factorial, no imports by Daniel Fischer @stackoverflow.com Daniel Fischer says algorithm is old. """ if high < 2: return 1 if low is None: return treefactorial(high, 1) if low + 1 < high: mid: int= (low + ...
eda784b853ca7305d4206a54b911c1b10e645587
35,422
import argparse import logging import sys from pathlib import Path def parse_args(): """ Parses command line :return: Dictionary with different options """ global LOGGER # pylint: disable=global-statement values = {} values['input_paths'] = [] values['recurse'] = False values['sh...
d9e2141b972969613c8be8a3b45a1acf93cc3039
35,423
import os def find(file_filter=None, output=None): """ finds files """ # find base directory path = os.getcwd() directories = [] for root, _, files in os.walk(path): # filter out hidden files and files that dont end in the extension for file in files: if extract_exten...
85f4457f7178ad9c3d357cd9922dad4910f345bc
35,424
import math def squarish_factors(x): """Returns the closest pair of factors of x. Parameters ---------- x : int Examples -------- >>> squarish_factors(20) (5, 4) >>> squarish_factors(36) (6, 6) >>> squarish_factors(53) (53, 1) >>> squarish_factors(0) (0, ...
a5d7cb9983d86d755622fd4bc9e495d7271d7719
35,425
def get_evidence(row: pd.Series) -> Evidence: """Return evidence for a Statement. Parameters ---------- row : Currently investigated row of the dataframe. Returns ------- : Evidence object with the source_api, the PMID and the original sentence. """ pmid = s...
bc54b6850957a7ab4a1e37289f17f04fc24ee25d
35,426
def _add_new_sheet(spreadsheet_id, title): """ Add new sheet to spreadsheet Return: False - Failed to add sheet True - Add sheet success """ global service # Todo: Format sheet column when new sheet is created # Column A: Type DATE # Column C: Type STRING # Request define ...
908de75b1bbbd9a957a0aaa843c41fca9aa0bf9e
35,427
def config_bgp(dut, **kwargs): """ config_bgp(dut = DUT1, router_id = '9.9.9.9', local_as='100', neighbor ='192.168.3.2', remote_as='200', config = 'yes', config_type_list =["neighbor"]) config_bgp(dut = DUT1, local_as='100', remote_as='200', neighbor ='2001::2', config = 'yes', config_type_list =["neighbor"] ...
744e96daded519308dfc7a5c3d665ba94cfc6bc5
35,428
def get_single_notification(session, notification_id): """Helper method to extract a single notification from notification table.""" return session.execute(text("""SELECT * FROM public.notification WHERE id='{0}'""".format(notification_id)))...
9041a3c91806764379997d79c5355cc84463f57c
35,429
import re def register(): """Registration form handler.""" def fail_validate(msg): flask.flash(msg, 'danger') return flask.redirect(flask.url_for('home')) username = request.form.get('username', '') if not re.match(r'[A-Za-z0-9_]+$', username): return fail_validate('Invalid username.') if model...
940f0478e17a4e02abdd6c8fded7d683a5c93f34
35,430
def default_reply(event, message): """Default function called to reply to bot commands.""" return event.unotice(message)
3c83d8abaea0f4c968db25fff51185bb6c32d26e
35,431
async def list_products(): """API for listing all the products.""" return await paginate(ProductGinoModel.query)
7befee2e20a2b849bbde7ddee521b8b935f6930d
35,432
def shortest_path_between_atoms(gra, key1, key2): """ shortest path between a pair of atoms """ return shortest_path_between_groups(gra, [key1], [key2])
0af0439794db7d6a2025fe28782ceff2da6575f3
35,433
import copy def _safe_divide(num, denom, replace=0): """Safe division when elements in the denominator might be zeros. Returns the division of the numerator by the denominator, but replaces results which have a zero in the denominator by a specified value. The default is to replace bad divisions with...
14a1f42104b98dccf865de7e6c3e17892f8aeb65
35,434
def making_change(amt: int, coins: list) -> int: """Iterative implementation of the making change algorithm. :param amt (int) : Amount, in cents, to be made into change. :param coins (list) : List of coin denominations :return (int) : Number of different combinations of change. """ # calc[i...
188496f5db4252fa27f153d0a0379031847c669d
35,435
from io import StringIO def pdf_to_text(pdf): """Return extracted text from PDF. Warning: This function can be slow... up to 300ms per page This function does not perform optical character recognition. Args: pdf: bytestring of PDF file Returns: str of text extracted from `pdf` contents. """ # ...
46f1b186a73a929f3053b35f94428e30804ab907
35,436
def pendulum_sunny(p): """sunny constraint for gravity Pendulum""" return np.abs(p[:, 1])<0.5
85fa7f94e803aac0d291030837f048d933283035
35,437
def PGetSkyModel (inUVSelfCal): """ Return the member sky model returns ImageMosaic inUVSelfCal = Python UVSelfCal object """ ################################################################ # Checks if not PIsA(inUVSelfCal): raise TypeError("inUVSelfCal MUST be a Python Obit UVSe...
d1dc418e46074958684c04b7431ee84ec0260f4b
35,438
def CGaussFilter_DImage_getGaussianFuncValue(dX, dY, dSigma): """CGaussFilter_DImage_getGaussianFuncValue(dX, dY, dSigma) -> double""" return _ImageFilters.CGaussFilter_DImage_getGaussianFuncValue(dX, dY, dSigma)
eeaf4dd66c795b6803efae2a386301c04e3e05b6
35,439
def get_credstash_config(key): """Retrieves a single secret from AWS via credstash, assumes the string returned is a list of newline-separated export statements export FOO='some-hush-hush-info-here' export BAR='some-other-secret-here' and parses these lines into a configuration dictionary. Ar...
afa2a858098860edc6179a046302119eee305b49
35,440
from typing import List def aggregate_stats(stats: List[deephol_stat_pb2.ProofStat] ) -> deephol_stat_pb2.ProofAggregateStat: """Merge a list of proof log statistics. Args: stats: List of individual proof log statistics. Returns: Aggregated proof statistics. """ result = deeph...
f15be64b3a2d8fb811aeeea2ccd57f5baa092e63
35,441
import functools import types def logged(message=None): """Logs the invoked function name and arguments.""" # TODO: Options - prevent sub @logged to output anything # TODO: Message - allow to specify a message # TODO: Category - read/write/exec as well as mode # [2013-10-28T10:18:32] user@host [sudo|user] [R/W] ...
db15c0c7a94f729f1f50afcccb4d905e483c1ca7
35,442
from typing import Optional from typing import Mapping from typing import Any from typing import List from pathlib import Path def get_requires_for_build_wheel( config_settings: Optional[Mapping[str, Any]] = None ) -> List[str]: """ Returns an additional list of requirements for building, as PEP508 string...
3681a08ec22887baa4aafac592059512442913a3
35,443
def fisher(high_vals: pd.Series, low_vals: pd.Series, length: int = 14) -> pd.DataFrame: """Fisher Transform Parameters ---------- high_vals: pd.Series High values low_vals: pd.Series Low values length: int Length for indicator window Returns ---------- df_ta...
9d6c8ff0d76c6121f418768503b68e7b596dcc89
35,444
def is_extension_supported(request, extension_alias): """Check if a specified extension is supported. :param request: django request object :param extension_alias: neutron extension alias """ extensions = list_extensions(request) for extension in extensions: if extension['alias'] == ext...
f8886d992724ef4ad0aa9c9c9ac25361b489d7dd
35,445
def _linear_wcs_fit(params, lon, lat, x, y, w_obj): # pragma: no cover """ Objective function for fitting linear terms. Parameters ---------- params : array 6 element array. First 4 elements are PC matrix, last 2 are CRPIX. lon, lat: array Sky coordinates. x, y: array ...
ac20744d7c52112290711a02a5c14a64d9525108
35,446
from imblearn.over_sampling import RandomOverSampler def resample(feature_index, labels, balance='auto'): """use oversampling to balance class, after split of training set.""" ros = RandomOverSampler(ratio=balance) feature_index = np.array(feature_index).reshape(-1, 1) resampled_index, _ = ros.fit_s...
4a061fe44da53caf6263a66042398562ac8149f0
35,447
from typing import Callable def dal_resolver(ctx, request_path): """ This function resolves a dal method call to its underlying service """ service_or_method = None for (path, service_or_method) in resolve(ctx, request_path): if not ( service_or_method and isinstance(servic...
3d5fb3bd019988ec43ca3d4514c8df2f7935287d
35,448
import re import operator import itertools def guess_key_size(ciphertext, max_key_size=40): """Given sentence xored with short key, guess key size From: http://trustedsignal.blogspot.com/2015/06/xord-play-normalized-hamming-distance.html Args: ciphertext(string) max_key_size(int) R...
99977ba81ebcb2f2e581164753f7ab363a9fd2e9
35,449
def AddWorkerpoolCreateArgs(parser): """Set up all the argparse flags for creating a workerpool. Args: parser: An argparse.ArgumentParser-like object. Returns: The parser argument with workerpool flags added in. """ return AddWorkerpoolArgs(parser, update=False)
db86e56ee95feb4b71cf2e209820e85e2985c688
35,450
def table_dispatch(kind, table, body): """Call body with table[kind] if it exists. Raise an error otherwise.""" if kind in table: return body(table[kind]) else: raise BaseException, "don't know how to handle a histogram of kind %s" % kind
18d827baeabbca8d27848ea87a067328fe82d16a
35,451
def compute_dot_sim_matrix(node_features): """Compute edge scores with dot product.""" sim = tf.matmul(node_features, tf.transpose(node_features, perm=[1, 0])) return sim
7eb1e67a01f29d064f9e21ffdbdaf516b42b35a4
35,452
import pickle def load_param_file(filename): """ Loads a saved parameter dictionary from filename. """ return pickle.load(open(filename))
1a6de4fba9f55bf6cbd108f4613f3778094ab410
35,453
def get_data_definitions(report_schedule_id, startDate, endDate): """ Takes a report schedule id and returns a dictionary/json of the necessary data definitions to be used by the transformation layer. """ # Setup the dictionary/json object d = dict() d["Meta"] = dict() d["ReportInfo...
9420610ee19a38807c61bdc9a079836aab1f64da
35,454
def strip_block_comments(text: str) -> str: """ Remove any block-style comments from a text. """ return strip_comments(text, [(COMMENT_BLOCK_PATTERN, None)])
4389bb137aa3fde7a033113646327920118911ca
35,455
import torch def optim_solver(grad, diff, radius, device, gamma=2): """ Solver for the optimization problem presented in Proposition 1 in https://arxiv.org/abs/2002.12718 """ lamda, mhlnbs_dis = compute_mahalanobis_distance(grad, diff, radius, device, gamma) lamda_lower_limit = range_lamda_low...
20971bea92ca13caa4df6204e24750c616fd4805
35,456
def send_sms(domain, contact, phone_number, text, metadata=None, logged_subevent=None): """ Sends an outbound SMS. Returns false if it fails. """ if phone_number is None: return False if isinstance(phone_number, int): phone_number = str(phone_number) phone_number = clean_phone_nu...
751111ce8db4d07d1021b30cd295b7062b6209a4
35,457
def u_diff(Exact, U_pred, x, t, nu, beta, rho, seed, layers, N_f, L, source, lr, u0_str, system, path, relative_error = False): """Visualize abs(u_pred - u_exact).""" fig = plt.figure(figsize=(9, 5)) ax = fig.add_subplot(111) if relative_error: h = ax.imshow(np.abs(Exact.T - U_pred.T)/np.abs(E...
cd08143e645da60be284520af4db8f6f1eef4be8
35,458
import binascii import os def Seq(sequence, annotations=None, block_length=10, blocks_per_line=6, style=DEFAULT_STYLE): """ Pretty-printed sequence object that's displayed nicely in the IPython Notebook. :arg style: Custom CSS as a `format string`, where a selector for the top-level `...
d1217eae5ccb681088d8019b2ece7c51a36e5573
35,459
def boundary_condition(): """ Factory associated with DirichletBC. """ return DirichletBC()
d547a86687bab9f2c87ca28f0f1eb5429f4892d7
35,460
def upgrade_available(): """ Detect if a new kernel version is available in the repositories. Returns True if a new kernel is available, False otherwise. CLI Example: .. code-block:: bash salt '*' kernelpkg.upgrade_available """ return _LooseVersion(latest_available()) > _LooseVer...
95d7f6558d060f64066a56b38336981a515e1dba
35,461
import os def get_testcases(problem): """ Gets testcases for problem, which are then displayed if user is Apprentice. :param problem: id of problem :return: array of testcases """ testcases_dir = os.path.join(os.popen('echo $CG_FILES_TESTCASES').read().strip(), problem) testcases_...
ed6eedac3be57368a79af79692802ebe93d9a5ff
35,462
def ss_error(observed_values, estimated_values): """Sum of squared error function.""" sse = np.sum((observed_values - estimated_values) ** 2) return sse
f049643ac58e3cac2fc436b75508976121adaff7
35,463
def _generate_gherkin_feature_files( gherkin_templates: list, properties_list: list[dict] ) -> list[TemplateOutputFile]: """ Compile templates with variable properties information. Args: gherkin_templates: templates to generate against. (Should only be one template) properties_list: a l...
37c833b85df5c9ed01cab3a9f9f38304808c2ab3
35,464
import paramiko import sys def sync_configs(units: tuple[str, ...], shared: bool, specific: bool) -> None: """ Deploys the shared config.ini and worker specific config.inis to the workers. If neither `--shared` not `--specific` are specified, both are set to true. """ logger = create_logger( ...
f7fa0f4e1a76b168f97d2d428d40de4b03a43029
35,465
import base64 def _get_base64(data: str) -> str: """Base 64 encodes data.""" ebytes = base64.b64encode(data.encode("utf-8")) estring = str(ebytes, "utf-8") return estring
a7bd3080dba077077d96602eb35142db32b003de
35,466
from datetime import datetime def parse_datetime(value): """Parses a string(ISO_8601) and return a datetime.datetime base UTC, or parse datetime.datetime base other timezone and return a datetime.datetime base UTC timezone """ if isinstance(value, datetime.datetime): if not value.tzinfo: ...
271556ab449bef15461a8d5086187724c9492d2f
35,467
def _dev_http_archive_impl(ctx): """Implementation of the http_archive rule.""" if not ctx.attr.url and not ctx.attr.urls: fail("At least one of url and urls must be provided") if ctx.attr.build_file and ctx.attr.build_file_content: fail("Only one of build_file and build_file_content can be ...
53d363db0af163965bc4b3b8331cf89bf91a1518
35,468
def setSortGroups(sortGroups=None): """ Return the sorting groups, either user defined or from the default list """ if sortGroups is None: # Default groups return [('-inf', '+inf'), ('-inf', 100), (101, '+inf')] else: sortGroups.insert(0, ('-inf', '+inf')) return sortGr...
f2e8cff00fe70627e81dcc0ce576f56e4d289228
35,469
def attach_clipped_regions_to_surface(surface, clipped, center): """Check the connectivty of a clipped surface, and attach all sections which are not closest to the center of the clipping plane. Args: surface (vtkPolyData): clipped (vtkPolyData): The clipped segments of the surface. ...
0ddb832a8fa29c7167301d8dde116734e59268da
35,470
def ubuntu_spec(**kwargs): """Ubuntu specs.""" # Setup vars from kwargs builder = kwargs['data']['builder'] builder_spec = kwargs['data']['builder_spec'] distro = kwargs['data']['distro'] version = kwargs['data']['version'] bootstrap_cfg = 'preseed.cfg' # https://github.com/mrlesmithj...
fca2605c5b10f86519ef5ca952ab340e1f5560f2
35,471
def ds_as_cds(dataset): """ Converts Vega dataset into Bokeh ColumnDataSource data """ if len(dataset) == 0: return {} data = {k: [] for k, v in dataset[0].items()} for item in dataset: for k, v in item.items(): data[k].append(v) data = {k: np.asarray(v) for k, v ...
41db6678bedfd23bbf43aaf281d9d7c0afd87ee6
35,472
def genPubKey(privkey): """ 生成公钥 """ bio=BIO.MemoryBuffer(privkey) key=EVP.load_key_bio(bio, util.no_passphrase_callback) return key.get_rsa().as_pem()
d750b136c2d79ff83261d3ac3ae104cc72d30428
35,473
def CI_calc(mean, SE, CV=1.96): """ Calculate confidence interval. :param mean: mean of data :type mean: float :param SE: standard error of data :type SE: float :param CV: critical value :type CV:float :return: confidence interval as tuple """ try: CI_down = mean - C...
be548e1ac1313f9e25428f4925399be27949f8ef
35,474
def bivecvec_invariants(q): """Calculates rotation-invariant attributes of a (vector, trivector) quantity. Returns a 2D output: the norm of the vector and the trivector. """ result = [custom_norm(q[..., :3]), q[..., 3:4]] return tf.concat(result, axis=-1)
43beda8a485ad56c5e7ba764dbd15757edd9653b
35,475
import subprocess def run(cmd): """Run a command on the command line.""" proc = subprocess.Popen(['sh', '-c', cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) stdout, stderr = proc.communicate() return proc.ret...
f7978e59044cf7aebc76355536c3e3fa1d08b729
35,476
from typing import Optional from typing import Sequence def resolve_margins(margins: Optional[Sequence[float]]) -> Tuple4f: """ Returns the box margins in CSS like order: top, right, bottom, left. """ if margins is None: return 0, 0, 0, 0 count = len(margins) if count == 4: # CSS: top, ri...
9411f7064b78247c73a6f7701fe916ce9a78b85a
35,477
def check_cookie_auth(api_key, required_scopes): """ Although OpenAPI explicitly supports JWT - we don't enforce this - simply use it as a quick way to mock the behaviour of a more advanced system :param api_key: :param required_scopes: :return: the decoded security token """ try: ...
29c502a4895b7dfcbe1002bd6d6c7739a3718b96
35,478
from typing import Any async def validate_input( hass: core.HomeAssistant, data: dict[str, Any] ) -> dict[str, Any]: """Validate the user input allows us to connect.""" session = async_get_clientsession(hass, verify_ssl=data[CONF_VERIFY_SSL]) protocol = "https" if data[CONF_SSL] else "http" url =...
23687106fb590105dc412d1a1d90ea6958be0828
35,479
def resize_cube(cube, shape): """Return resized cube with the define shape""" zoom = [float(x) / y for x, y in zip(shape, cube.shape)] resized = sp.ndimage.zoom(cube, zoom) assert resized.shape == shape return resized
491272f81b02f1b92c0c4f886b956f3b8e48efc2
35,480
import torch def load_image_from_cifar(image_id): """This is to load the image from CIFAR numpy and pre-process. :param image_id: An integer as the image id to load from CIFAR. :return img: A PyTorch Tensor. """ image = CIFAR[image_id] image = image / 255.0 # Normalize image = torch.fro...
d235df286f0629312ff39967845b0b744eb8d531
35,481
def valueToCharacter(value): """ Returns the respective character for a value. Returns 'highest' character if no match is found Args: value ([int]): Value that should be mapped to a character Returns: [char]: Respective character for the given value """ for bar_threshold in BA...
c5df1d0185f0ab775eda8f573253d399824cbb98
35,482
import gc def pickle_loads(inbox): """ Deserializes the first element of the input using the pickle protocol. """ gc.disable() obj = cPickle.loads(inbox[0]) gc.enable() return obj
38ce6a33b3313d97ffa021dde93d68e0387d1f69
35,483
def NOT_TENSOR_FILTER(arg_value): """Only keeps a value if it is not a Tensor or SparseTensor.""" return not arg_value.is_tensor and not arg_value.is_sparse_tensor
14eb28c1824f58bd7ef6ad1da96922891114fe5a
35,484
def rod_3D(x, gm=None, median=None, scaler1=None, scaler2=None): """Find ROD scores for 3D Data. note that gm, scaler1 and scaler2 will be returned "as they are" and without being changed if the model has been fit already. Parameters ---------- x : array-like, 3D data points. gm: list (defa...
df3347689aef695ff9ab1a8b8853310f14ff9828
35,485
def check_if_neighbors_match(src_neighbor, trg_neighbor): """Check if any source and target neighbors match and return matches Args: src_neighbor (list): Source Neighbor List trg_neighbor (list): Target Neighbor List Returns: list: Matching of neighbors. """ matching = {} ...
c4d91ffca1f175e9964ca67c8b2200b1848b56d9
35,486
def build_torch_optimizer_for_bert(model, opt): """ no_decay = ["bias", "LayerNorm.weight"] encoder_params = [ { "params": [p for n, p in model.encoder.named_parameters() if not any(nd in n for nd in no_decay)], "weight_decay": 0.0, }, { ...
20672e152874d51908855afcf46b26d0a4f5501e
35,487
def docker_compose(command): """ Run a docker-compose command :param command: Command you want to run """ with env.cd(env.project_dir): return env.run("docker-compose -f {file} {command}".format(file=env.compose_file, command=command))
9e51fdacb42057ab607ec00b563db4973ede7e96
35,488
def _get_event_id(oracle_cursor): # -> (int) """gets the event_id to be used for updating the NR history :oracle_conn : a Cx_Oracle connection to the NRO database :returns (int): a valid NRO event_id to be used for updating NRO records """ oracle_cursor.execute("""select event_seq.NEXTVAL from dua...
ee524bb3c4819e9cb614219900be4695219d046f
35,489
from typing import List def matches_ground_truth( candidate: MissionTrace, truth: List[MissionTrace], tolerance_factor: float = 1.0 ) -> bool: """ Determines whether a given trace, referred to as the candidate trace, is approximately equivalent to a set of ground truth trac...
b293c520edbb2f3d5567450c152db74373f896e4
35,490
import pickle def broken_model(): """Create a non-functional model object.""" r = MockRedis() r.set("1.2.0", pickle.dumps("lol")) return lambda: r
a1dee18e86f61263f629b8b20ceb75e0f55585d3
35,491
def _envFile(self, s, *args, **kw): """Same as Environmet.File but without expanding $VAR logic """ if SCons.Util.is_Sequence(s): result=[] for e in s: result.append(self.fs.File((e,) + args, kw)) return result return self.fs.File((s,) + args, kw)
9d388255faaa71705dc555c0d3349ef0f334c86d
35,492
def xception_model(num_classes, pretrained=True, **kwargs): """Constructs a xception model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ encoder = AlignedXception(num_classes=1000) # encoder = pretrainedmodels.models.xception() if pretrained: sta...
f9b3167d0f569230119904eb10c6a0627c44da1d
35,493
def lwdown(atemp,clouds): """Call signature:: lwd = lwdown(atemp,clouds) estimate downward (incoming) radiation in long wave wave band from air temperature according to Parkinson and Washington (1979), A Large-Scale Numerical Model of Sea Ice, JGR, 84(C1), 311-337. INPUT: atemp :: air temp...
b80838371a14363dd0f78dc329718e408882a1ff
35,494
def render_volume(workspace, cutoff=None, solid_color=(1., 1., 1.), style='surface', origin=(0., 0., 0.), window_size=(1920, 1200), opacity=1., background=(0.3, 0.3, 0.3), show_grid=True, plot_directly=True, show_axes=True, show_outline=True, cmap='gray', add_to_plot=None, notebook=F...
6bddc01d467041170cdd42e9f2d4f0334fe2e151
35,495
def cutoff_list(a,feature=int(0)): """ for list a, apply function cutoff to each element """ for i in range(len(a)): a[i]=cutoff(a[i],feature=feature) return a
fe13bf9cc4f097b22911e247ed6ab468552a365b
35,496
def carla_location_to_pose(carla_location): """ Convert a carla location to a icv pose See carla_location_to_icv_point() for details. pose quaternion remains zero. :param carla_location: the carla location :type carla_location: carla.Location :return: a icv pose :rtype: geometry_msgs.m...
60e3a0cf2075d0d1cdfe631225a8de21718b068f
35,497
def estimate_biases(model_dat, ymdat): """numerical optimize modification indicators for equations, one at a time""" tau = model_dat["xdat"].shape[1] biases = zeros(model_dat["ndim"]) biases_std = zeros(model_dat["ndim"]) for bias_ind in range(model_dat["ndim"]): # compute biases bi...
513f79d37426f6dc3889ee4de0b9c510273bfabe
35,498
def _get_l10n_term(term: str) -> str: """get localized term when possible from an predictable string input Args: term (str): the term, example: vkg.attr.descriptionem Returns: str: if possible, the term on user language. It will fallback to the term itself """ ...
9a4f31db69c1bbc82832bb4987097b68ba97ac8b
35,499