content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def authority_b(request, configuration, authority_a): """ Intermediate authority_a valid_authority -> authority_a -> authority_b """ authority = configuration.manager.get_or_create_ca("authority_b", hosts=["*.com"], ...
ac9ec3c33e06ba506efe51f4ceafa96cfe91f761
19,500
def derive(pattern): """ Calculate the first derivative pattern pattern. Smoothes the input first, so noisy patterns shouldn't be much of a problem. """ return np.gradient(smooth_pattern(pattern))
4f2bdbb34f4d36427b3d9c1effff4d13a7d41552
19,501
def gaussian(nm, a, x0, sigma): """ gaussian function """ gaussian_array = a * np.exp(- ((nm - x0) ** 2.0) / (2 * (sigma ** 2.0))) return gaussian_array
2c8ba6bb93565ff9ae79f0a0b6643994730bb672
19,502
def list_to_filename(filelist): """Returns a list if filelist is a list of length greater than 1, otherwise returns the first element """ if len(filelist) > 1: return filelist else: return filelist[0]
32a88235196e104fa043d2b77af1f09d4e9164e9
19,503
from datetime import datetime import six def _get_expiration_seconds(expiration): """Convert 'expiration' to a number of seconds in the future. :type expiration: int, long, datetime.datetime, datetime.timedelta :param expiration: When the signed URL should expire. :rtype: int :returns: a timesta...
3eb2c56211b3cfab8f35634b83ef8c77e4ea2221
19,504
import click def parse_encoding(format_, track, supplied_encoding, prompt_encoding): """Get the encoding from the FLAC files, otherwise require the user to specify it.""" if format_ == "FLAC": if track["precision"] == 16: return "Lossless", False elif track["precision"] == 24: ...
d56ad0d15176a963e62a33d4b4cd799d1e68281e
19,505
import os import stat def check_core_dump_setting(): """ checking os core dump setting is right """ errors = [] ret, out = run_shell('ulimit -c') limit = out.strip('\n').strip() if limit != 'unlimited': errors.append(f'core dump file setting limit="{limit}" is incorrect, should se...
e2735badead3f03b0c35d0fecb157b8a1f8d82db
19,506
def disaggregate(model, mains, model_name, num_seq_per_batch, seq_len, appliance, target_scale, stride=1): """ Disaggregation function to predict all results for whole time series mains. :param model: tf model object :param mains: numpy.ndarray, shape(-1,) :param model_name: name...
2053e9dc74d188ab41dbeb2fc1af8cd4bbd6dfae
19,507
import pathlib from pathlib import Path def set_path_to_file(categoria: str) -> pathlib.PosixPath: """ Receba uma string com o nome da categoria da lesgilação e retorna um objeto pathlib.PosixPath """ fpath = Path(f"./data/{categoria}") fpath.mkdir(parents=True, exist_ok=True) return fpath
98455978e695d34deb27dc59807e06f1a4daff96
19,508
def transpose_nested_dictionary(nested_dict): """ Given a nested dictionary from k1 -> k2 > value transpose its outer and inner keys so it maps k2 -> k1 -> value. """ result = defaultdict(dict) for k1, d in nested_dict.items(): for k2, v in d.items(): result[k2][k1] = v ...
39f8faa319063ac533b375c5ae0ac1c10a8fd770
19,509
def auth_code(): """ Функция для обработки двухфакторной аутентификации :return: Код для двухфакторной аутентификации :rtype: tuple(str, bool) """ tmp = input('Введи код: ') return tmp, True
8b0ae26cfdd1aa9f7b9c7a0433075494fe354185
19,510
from typing import cast def graph_file_read_mtx(Ne: int, Nv: int, Ncol: int, directed: int, filename: str,\ RemapFlag:int=1, DegreeSortFlag:int=0, RCMFlag:int=0, WriteFlag:int=0) -> Graph: """ This function is used for creating a graph from a mtx graph file. compared with t...
7babe91d1daad745a94ea542ebda0cff9eaedf4b
19,511
def _get_uri(tag, branch, sha1): """ Set the uri -- common code used by both install and debian upgrade """ uri = None if tag: uri = 'ref/' + tag elif branch: uri = 'ref/' + branch elif sha1: uri = 'sha1/' + sha1 else: # FIXME: Should master be the default...
33f2662a8c6e9ad61136e357af495fc47d7c9dfc
19,512
def compute_inliers (BIH, corners): """ Function: compute_inliers ------------------------- given a board-image homography and a set of all corners, this will return the number that are inliers """ #=====[ Step 1: get a set of all image points for vertices of board coords ]===== all_board_points = [] for ...
431e5e82e127f404b142940de79c8bed79021423
19,513
def plotPayloadStates(full_state, posq, tf_sim): """This function plots the states of the payload""" # PL_states = [xl, vl, p, wl] fig8, ax11 = plt.subplots(3, 1, sharex=True ,sharey=True) fig8.tight_layout() fig9, ax12 = plt.subplots(3, 1, sharex=True, sharey=True) fig9.tight_layout() ...
56018bbb5dfaca76dae62940c572aacfef31ad1e
19,514
def draw(p): """ Draw samples based on probability p. """ return np.searchsorted(np.cumsum(p), np.random.random(), side='right')
84b087c9eb6bfdac4143a464399f85cad0169000
19,515
import functools def _autoinit(func): """Decorator to ensure that global variables have been initialized before running the decorated function. Args: func (callable): decorated function """ @functools.wraps(func) def _wrapped(*args, **kwargs): init() return func(*args,...
b39242a9f600a7bbeaf43d73ae3529dcad9c3857
19,516
from datetime import datetime def export_testing_time_result(): """ Description: I refer tp the answer at stockoverFlow: https://stackoverflow.com/questions/42957871/return-a-created-excel-file-with-flask :return: A HTTP response which is office excel binary data. """ target_info = reques...
ab0505449361b036ed94eb919a3c876a8776b839
19,517
def profile_view(user_request: 'Queryset') -> 'Queryset': """ Функция, которая производит обработку данных пользователя и выборку из БД вакансий для конкретного пользователя """ user_id = user_request[0]['id'] area = user_request[0]['area'] experience = user_request[0]['experience'] sala...
6ec9a6c00cead62c2d30dcb627a575b072bcde60
19,518
def config_vrf(dut, **kwargs): """ #Sonic cmd: Config vrf <add | delete> <VRF-name> eg: config_vrf(dut = dut1, vrf_name = 'Vrf-test', config = 'yes') eg: config_vrf(dut = dut1, vrf_name = 'Vrf-test', config = 'no') """ st.log('Config VRF API') if 'config' in kwargs: config = kwargs['...
9d6d7e85762610103277345d1e12d4ef2c3f3d9f
19,519
def _worker_command_line(thing, arguments): """ Create a worker command line suitable for Popen with only the options the worker process requires """ def a(name): "options with values" return [name, arguments[name]] * (arguments[name] is not None) def b(name): "boolean op...
945e9da452b438b08aacbf967b93f10f717c5003
19,520
from typing import Optional def get_endpoint(arn: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetEndpointResult: """ Resource Type Definition for AWS::S3Outposts::Endpoint :param str arn: The Amazon Resource Name (ARN) of the endpoint. """ __ar...
518fbd1ca92373bcbea5d10a44605b4990242d02
19,521
import sys def solveConsLaborIntMarg( solution_next, PermShkDstn, TranShkDstn, LivPrb, DiscFac, CRRA, Rfree, PermGroFac, BoroCnstArt, aXtraGrid, TranShkGrid, vFuncBool, CubicBool, WageRte, LbrCost, ): """ Solves one period of the consumption-saving m...
cc54bdcd8a94b6bd65c459603db7921100c28ef5
19,522
def append_child(node, child): """Appends *child* to *node*'s children Returns: int: 1 on success, 0 on failure """ return _cmark.node_append_child(node, child)
70770596cf470987ff20abbe94f8b97c0050f86a
19,523
def run_chain(init_part, chaintype, length, ideal_population, id, tag): """Runs a Recom chain, and saves the seats won histogram to a file and returns the most Gerrymandered plans for both PartyA and PartyB Args: init_part (Gerrychain Partition): initial partition of chain chaintype (Str...
5b6db6ede5e8b7c8bcc46f91131fafed22741775
19,524
def cliquenet_s2(**kwargs): """CliqueNet-S2""" model = cliquenet(input_channels=64, list_channels=[36, 80, 150, 120], list_layer_num=[5, 5, 6, 6]) return model
6b99b3575d9bd245aea615eedbffa95ca7fd3076
19,525
def decConvert(dec): """ This is a number-word converter, but for decimals. Parameters ----- dec:str This is the input value numEngA: dict A dictionary of values that are only up to single digits frstDP: int The first decimal place scndDP: int The second decimal place Returns...
dedfb67448e4bd2402acb4c561ebb4669d7bc58d
19,526
import os def train_model(base_model, training_dataset, validation_dataset, output_dir, loss=None, num_epochs=100, patience=20, learning_rate=1e-4): """ Train a model with the given data. Parameters ---------- base_model training_dataset validation_dataset ...
5b6fdf7e7e63c0dbdbe62ecb401dad4b790075d1
19,527
import time def fit(data, weights, model_id, initial_parameters, tolerance=None, max_number_iterations=None, \ parameters_to_fit=None, estimator_id=None, user_info=None): """ Calls the C interface fit function in the library. (see also http://gpufit.readthedocs.io/en/latest/bindings.html#python) ...
54c0f3a740589509d908e8c68625e33dccfbe1f8
19,528
import json def json_get(cid, item): """gets item from json file with user settings""" with open('data/%s.json' %cid) as f: user = json.load(f) return user[item]
dedb369aba555ca5359e291bc39504dd4b14a790
19,529
from . import __version__, status_show_server def debug_info(): """ This function varies version-by-version, designed to help the authors of this package when there's an issue. Returns: A dictionary that contains debug info across the interpret package. """ debug_dict = {} debug_dict["in...
4d751d245d6d5bf48680bcd217675f0a6df44d49
19,530
import random def adaptive_monte_carlo(func, z_min, z_max, epsilon): """ Perform adaptive Monte Carlo algorithm to a specific function. Uniform random variable is used in this case. The calculation starts from 10 division of the original function range. Each step, it will divide the region which has the l...
7735c9e3df1ddfb912dd9a2dfcf01699a56262d8
19,531
import scipy.stats def compute_statistics(measured_values, estimated_values): """Calculates a collection of common statistics comporaring the measured and estimated values. Parameters ---------- measured_values: numpy.ndarray The experimentally measured values with shape=(number of data p...
cde9fd0094a6d8330f552ec98c11647c0a76bc42
19,532
def num_encode(n): """Convert an integer to an base62 encoded string.""" if n < 0: return SIGN_CHARACTER + num_encode(-n) s = [] while True: n, r = divmod(n, BASE) s.append(ALPHABET[r]) if n == 0: break return u''.join(reversed(s))
bd0f34122fa490cfafea2a5b60d6a919a7a8c253
19,533
import torch def hard_example_mining(dist_mat, labels, return_inds=False): """For each anchor, find the hardest positive and negative sample. Args: dist_mat: pytorch Variable, pair wise distance between samples, shape [N, N] labels: pytorch LongTensor, with shape [N] return_inds: whether to ...
d3e36f7c7088b1a1d457869701c99d2c2013a283
19,534
import os def failure_comment(request, comment_id): """Отклоняет отзыв с указанием причины""" user = request.user comment = Comment.objects.get(recipient_user=user.id, id=comment_id, failure=False) form = AcceptForm(request.POST or None, initial=model_to_dict(comment), instance=comment) if form.is...
745b10d95ea6fec68a14cfcf28eba9315af0c64c
19,535
from typing import Optional from typing import cast from typing import Sized def CodedVideoGrain(src_id_or_meta=None, flow_id_or_data=None, origin_timestamp=None, creation_timestamp=None, sync_timestamp=None, rate=Frac...
5ab51dbbcaaff04f9c56434998d49434aec6f58e
19,536
def test_log_likelihood(model, X_test, y_test): """ Marginal log likelihood for GPy model on test data""" _, test_log_likelihood, _ = model.inference_method.inference( model.kern.rbf_1, X_test, model.likelihood.Gaussian_noise_1, y_test, model.mean_function, model.Y_metadata) return test_log_...
61c04b4b3cb12472769699f37601154398df0959
19,537
from airfs._core.io_base_raw import ObjectRawIOBase from airfs._core.io_base_buffered import ObjectBufferedIOBase from airfs._core.io_random_write import ( ObjectRawIORandomWriteBase, ObjectBufferedIORandomWriteBase, ) def test_object_buffered_base_io(): """Tests airfs._core.io_buffered.Object...
e72324d158ae9dfc8b859e5ce055230da83819fe
19,538
def fov_geometry(release='sva1',size=[530,454]): """ Return positions of each CCD in PNG image for a given data release. Parameters: release : Data release name (currently ['sva1','y1a1'] size : Image dimensions in pixels [width,height] Returns: list : A list of [id, x...
a7e118ed223a91d5e939b24baa8bbfb0858064b9
19,539
def parse_descriptor(desc: str) -> 'Descriptor': """ Parse a descriptor string into a :class:`Descriptor`. Validates the checksum if one is provided in the string :param desc: The descriptor string :return: The parsed :class:`Descriptor` :raises: ValueError: if the descriptor string is malforme...
b82c04f6cdc6d4e9b5247463e6fcbdcf12c5ffc7
19,540
def HHMMSS_to_seconds(string): """Converts a colon-separated time string (HH:MM:SS) to seconds since midnight""" (hhs,mms,sss) = string.split(':') return (int(hhs)*60 + int(mms))*60 + int(sss)
f7a49ad5d14eb1e26acba34946830710384780f7
19,541
import os def create_check_warnings_reference(warnings_file): """Read warnings_file and compare it with the warnings the compiler actually reported. If the reference file is missing we just check that there are any warnings at all.""" if not os.path.isfile(warnings_file): return check_missing_...
d556225616005125e7e8e772f1f48705e4c1186c
19,542
def fetch_user_profile(user_id): """ This function lookup a dictionary given an user ID. In production, this should be replaced by querying external database. user_id: User ID using which external Database will be queried to retrieve user profile. return: Returns an user profile corresponding to th...
c9ee521dc909f865232ec5d39b456bafd0c996dc
19,543
def _replace_token_range(tokens, start, end, replacement): """For a range indicated from start to end, replace with replacement.""" tokens = tokens[:start] + replacement + tokens[end:] return tokens
2848a3ad2d448e062facf78264fb1d15a1c3985c
19,544
def softmax_loss_vectorized(W, X, y, reg): """ Softmax loss function, vectorized version. Inputs and outputs are the same as softmax_loss_naive. """ # Initialize the loss and gradient to zero. loss = 0.0 dW = np.zeros_like(W) num_train = X.shape[0] num_classes = W.shape[1] num_dimensions = X.shape[...
27232f9988f98359dab225a47c04a9d4799a38b1
19,545
def norm(a): """normalizes input matrix between 0 and 1 Args: a: numpy array Returns: normalized numpy array """ return (a - np.amin(a))/(np.amax(a)-np.amin(a))
6c246926b8a5c91ea5a674447679a7d1cf7a2c8e
19,546
def collect_path(rf, method="quick", verbose=True): """ Collect paths from RandomForest objects. This function is the most time-consuming part. Output: A list of outputs from get_path_to_max_prediction_terminal_node. """ n_tree = len(rf) result = [] if method == "quick": ...
d2ecb0f277eafb483d38376278635f1143c5e7f2
19,547
def calculate_variance(beta): """ This function calculates variance of curve beta :param beta: numpy ndarray of shape (2,M) of M samples :rtype: numpy ndarray :return variance: variance """ n, T = beta.shape betadot = gradient(beta, 1. / (T - 1)) betadot = betadot[1] normbetad...
179ae9dde0979f909525c44c94ea11ded7a776d5
19,548
def get_datastore_mo(client, soap_stub, datacenter_name, datastore_name): """ Return datastore managed object with specific datacenter and datastore name """ datastore = get_datastore(client, datacenter_name, datastore_name) if not datastore: return None datastore_mo...
f759dccd61caa7cd290a2a00b0ebbcb80dc8fa7e
19,549
def _merge_dictionaries(dict1: dict, dict2: dict) -> dict: """ Recursive merge dictionaries. :param dict1: Base dictionary to merge. :param dict2: Dictionary to merge on top of base dictionary. :return: Merged dictionary """ for key, val in dict1.items(): if isinstance(val, dict): ...
322cd1e3cf01d97ebc8ecb450772ca328afee121
19,550
def integrate_profile(rho0, s0, r_s, r_1, rmax_fac=1.2, rmin_fac=0.01, r_min=None, r_max=None): """ Solves the ODE describing the to obtain the density profile :returns: the integration domain in kpc and the solution to the density profile in M_sun / kpc^3 """ G = 4.3e-6 # u...
af139c2f8211f11d2a71e1da73ebdd3f9f6c4fe7
19,551
def create_eval_dataset( task, batch_size, subset): """Create datasets for evaluation.""" if batch_size % jax.device_count() != 0: raise ValueError(f"Batch size ({batch_size}) must be divisible by " f"the number of devices ({jax.device_count()}).") per_device_batch_size = batc...
4446f322d38a736942125a9427db1e68bb008e5e
19,552
def rad2deg(angle): """ Converts radians to degrees Parameters ---------- angle : float, int Angle in radians Returns ------- ad : float Angle in radians Examples -------- >>> rad2deg(pi) 180.000000000000 >>> rad2deg(pi/2) ...
e8bdc1d914c139d7d3847223ecfb8b0399eda5ca
19,553
def center_crop(im, size, is_color=True): """ Crop the center of image with size. Example usage: .. code-block:: python im = center_crop(im, 224) :param im: the input image with HWC layout. :type im: ndarray :param size: the cropping size. :type size: int :param is...
ac280efd4773613f08632fe836eecc16be23adf8
19,554
def read_json(file_path: str) -> Jelm: """reads from a json file path""" with open(file_path) as fp: dump = fp.read() return reads_json(dump)
a3166cbe3bc98478a89574af7493a740826ab366
19,555
def fillCells(cell_bounds, rdx, rdy, rdbathy, dlim=0.0, drymin=0.0, drymax=0.99, pland=None, rotated=False, median_depth=False, smc=False, setadj=False): """Returns a list of depth and land-sea data to correspond with cell bounds list""" print('[INFO] Calculating cell depths...
b40a8c3d5171c40cebf397b93e697dfaef1820ec
19,556
def mark_item_complete(todo: TodoAndCompleted, idx: int) -> TodoAndCompleted: """ Pop todo['todo'][idx] and append it to todo['complete']. Parameters ---------- todo : TodoAndCompleted A dict containing a to-do list and a list of completed tasks. idx : int Index of an item to mo...
a1efac8801fa8af3b93352dbb3ce8790b29a99f2
19,557
import six import math import warnings def spatial_pyramid_pooling_2d(x, pyramid_height, pooling_class=None, pooling=None): """Spatial pyramid pooling function. It outputs a fixed-length vector regardless of input feature map size. It performs pooling operation to the inpu...
fd64c335afe43a35a8917cf8079ae41d410f9dc4
19,558
from typing import OrderedDict async def retrieve_seasons_and_teams(client, url): # noqa: E999 """ Retrieves seasons and teams for a single player. """ doc = await get_document(client, url) teams = doc.xpath( "//table[@id='stats_basic_nhl' or @id='stats_basic_plus_nhl']" + "/tbody...
b68d95a46b5f036ec53826fa0321273b168d2261
19,559
def array_match_difference_1d(a, b): """Return the summed difference between the elements in a and b.""" if len(a) != len(b): raise ValueError('Both arrays must have the same length') if len(a) == 0: raise ValueError('Arrays must be filled') if type(a) is not np.ndarray: a = np...
b82a6e36bdfe2757bc1a86bb4d95c156ac847474
19,560
def data_len(system: System) -> int: """Compute number of entries required to serialize all entities in a system.""" entity_lens = [entity.state_size() + entity.control_size() for entity in system.entities] return sum(entity_lens)
8ebc98e713052dd215ffaecfd5338535e4662bd2
19,561
def keep_row(row): """ :param row: a list for the row in the data :return: True if we should keep row; False if we should discard row """ if row[_INDICES["Actor1CountryCode"]] in _COUNTRIES_OF_INTEREST or \ row[_INDICES["Actor2CountryCode"]] in _COUNTRIES_OF_INTEREST: return True ...
5124583806c02034c0c11518b25639ebd61aaccf
19,562
def _grad_shapelets(X, y, n_classes, weights, shapelets, lengths, alpha, penalty, C, fit_intercept, intercept_scaling, sample_weight): """Compute the gradient of the loss with regards to the shapelets.""" n_samples, n_timestamps = X.shape # Derive distances between s...
fb16c9aaaf06ae322f9781d8089fd084fc7d299a
19,563
from typing import List import requests def get_tags_list(server_address: str, image_name: str) -> List[str]: """ Returns list of tags connected with an image with a given name :param server_address: address of a server with docker registry :param image_name: name of an image :return: list of tags...
3c20ef85f77689cdbc25a131bbe1f1cc1431528a
19,564
def build_graph(graph_attrs, meta_data, nodes, edges): """ Build the Graph with specific nodes and edges. :param graph_attrs: dictionary with graph attributes :param nodes: list of nodes where each node is tuple (node_name, type, attrs) nodes=[ ('input', 'Parameter'...
9238da38d6b8d65f9bff7c344d2fe8d4ed71dc90
19,565
from typing import Callable from typing import Any import pickle def cached_value(func: Callable[[], Any], path) -> Any: """ Tries to load data from the pickle file. If the file doesn't exist, the func() method is run and its results are saved into the file. Then the result is returned. """ if ex...
b74c9b79cf74c32c5d1befaad293cdc2dbf3b5c3
19,566
def expensehistory(): """Show history of expenses or let the user update existing expense""" # User reached route via GET if request.method == "GET": # Get all of the users expense history ordered by submission time history = tendie_expenses.getHistory(session["user_id"]) # Get the...
15ce57d9b246fd81bc8f38fcda11330de3ff50a5
19,567
def resize(a, new_shape): """resize(a,new_shape) returns a new array with the specified shape. The original array's total size can be any size. """ a = ravel(a) if not len(a): return zeros(new_shape, a.typecode()) total_size = multiply.reduce(new_shape) n_copies = int(total_size / len(a)) ...
fcbce959a0ff6bd31a269be89b50956ccc6f6883
19,568
def rotate180(image_np): """Rotates the given image by 180 degrees.""" if image_np is None: return None return np.fliplr(np.flipud(image_np))
d851314620d527b6c33e19389b5fc19035edcdb3
19,569
import requests def proxy_view(request, url, domain=None, secure=False, requests_args=None, template_name="proxy/debug.html"): """ Forward as close to an exact copy of the request as possible along to the given url. Respond with as close to an exact copy of the resulting response as possible. If...
29c06a332f533227202cb8a0287adf1c7d01a3da
19,570
def poll_for_staleness(id_or_elem, wait=10, frequency=1): """Use WebDriverWait with expected_conditions.staleness_of to wait for an element to be no longer attached to the DOM. :argument id_or_elem: The identifier of the element, or its element object. :argument wait: The amount of seconds to wait befor...
bd96a71795869817e1a284a1671645b503fcd223
19,571
def check_y(y, allow_empty=False, allow_constant=True): """Validate input data. Parameters ---------- y : pd.Series allow_empty : bool, optional (default=False) If True, empty `y` raises an error. allow_constant : bool, optional (default=True) If True, constant `y` does not raise...
570aa15347377bddbe96919cc1560157905c91ce
19,572
def preprocess_features(features): """Row-normalize feature matrix and convert to tuple representation""" rowsum = np.array(features.sum(1), dtype=float) r_inv = np.power(rowsum, -1).flatten() r_inv[np.isinf(r_inv)] = 0. r_mat_inv = sp.diags(r_inv) features = r_mat_inv.dot(features) return s...
dba875e19918cb11bae31a575f35d79519d2d897
19,573
import http import socket import ssl def CheckReachability(urls, http_client=None): """Check whether the hosts of given urls are reachable. Args: urls: iterable(str), The list of urls to check connection to. http_client: httplib2.Http, an object used by gcloud to make http and https connections. De...
9d16e7be2bcc8a1f887a7f86dc464d44de681088
19,574
def dataset_prediction_results(dataset, event, model_factory_fn=pohmm_factory, min_history=90, max_history=None, out_name=None): """ Obtain predictions for each model. Create stratified folds Train on 1-n_folds. Use the last fold to make predictions for each event """...
4e11a6e3b144c4b37529465c3517481666bebd78
19,575
def num(value): """Parse number as float or int.""" value_float = float(value) try: value_int = int(value) except ValueError: return value_float return value_int if value_int == value_float else value_float
a2ea65c2afa0005dbe4450cb383731b029cb68df
19,576
def __format_event_start_date_and_time(t): """Formats datetime into e.g. Tue Jul 30 at 5PM""" strftime_format = "%a %b %-d at %-I:%M %p" return t.strftime(strftime_format)
4db0b37351308dfe1e7771be9a9ad8b98f2defa6
19,577
def collect_properties(service_instance, view_ref, obj_type, path_set=None, include_mors=False): """ Collect properties for managed objects from a view ref Check the vSphere API documentation for example on retrieving object properties: - http://goo.gl/erbFDz Args: ...
39abeff44fefc6b93284b7ec10e66a8a224ce73d
19,578
from typing import Optional def to_all_gpus( cpu_index: faiss.Index, co: Optional['faiss.GpuMultipleClonerOptions'] = None ) -> faiss.Index: """ TODO: docstring """ n_gpus = faiss.get_num_gpus() assert n_gpus != 0, 'Attempting to move index to GPU without any GPUs' gpu_index = faiss...
58619c3745078004a97225d2091154f6ab140814
19,579
from typing import List from typing import MutableMapping def parse_template_mapping( template_mapping: List[str] ) -> MutableMapping[str, str]: """Parses a string template map from <key>=<value> strings.""" result = {} for mapping in template_mapping: key, value = mapping.split("=", 1) result[key] ...
49eb029a842be7c31d33444235452ecad4701476
19,580
import os def isGZ(fn): """ Tests whether a file is gz-compressed. :param fn: a filename :type fn: str :returns: True if fn is gz-compressed otherwise False """ assert os.path.exists(fn) with open(fn, 'rb') as fi: b1, b2 = fi.read(1), fi.read(1) return b1 == b'\x1f' a...
d71fe08a10554eae2909287a1c19dadf795a4592
19,581
def select_dim_over_nm(max_n, max_m, d, coef_nd, coef_md, coef_nm, coef_n, coef_m, rest, max_mem): """Finds the optimal values for `n` and `m` to fit in available memory. This function should be called for problems where the GPU needs to hold two blocks of data (one of size m, one of size n) and one kernel...
a4a824ab19a5d102461d565312ec9874a8c4e513
19,582
import os def _file_extension(filename): """Return file extension without the dot""" # openbabel expects the extension without the dot, but os.path.splitext # returns the extension with it dotext = os.path.splitext(filename)[1] return dotext[1:]
10c328d3b4670aef021c90a28f704b154be8ca5e
19,583
import os import uuid def atomic_tmp_file(final_path): """Return a tmp file name to use with atomic_install. This will be in the same directory as final_path. The temporary file will have the same extension as finalPath. It the final path is in /dev (/dev/null, /dev/stdout), it is returned unchanged...
4d4589a1808195c707ecf77d6bc8d9fdd2a487f1
19,584
def hzAnalyticDipoleF(r, freq, sigma, secondary=True, mu=mu_0): """ 4.56 in Ward and Hohmann .. plot:: import matplotlib.pyplot as plt from SimPEG import EM freq = np.logspace(-1, 6, 61) test = EM.Analytics.FDEM.hzAnalyticDipoleF(100, freq, 0.001, secondary=False) p...
94e38e60f1da4abc47c9210683815bc9f0085727
19,585
def _compute_net_budget(recarray, zonenamedict): """ :param recarray: :param zonenamedict: :return: """ recnames = _get_record_names(recarray) innames = [ n for n in recnames if n.startswith("FROM_") or n.endswith("_IN") ] outnames = [ n for n in recnames if n.starts...
e5e14bef5663af22f5547e36b305f858de372232
19,586
def bg_white(msg): """ return msg with a white background """ return __apply_style(__background_colors['white'],msg)
1e5aca8b0e506420b921c6833704aa32ba0c599f
19,587
def read_image_from_s3(bucket_name, key): """S3 to PIL Image""" s3 = boto3.resource('s3') bucket = s3.Bucket(bucket_name) object = bucket.Object(key) response = object.get() return Image.open(response['Body'])
6d7e62e007b493f1d124c07ab0b19abe9c6bc308
19,588
import typing from typing import Counter def count_indra_apis(graph: BELGraph) -> typing.Counter[str]: """Count the APIs reported by INDRA.""" return Counter( api for _, _, d in graph.edges(data=True) if ANNOTATIONS in d and 'INDRA_API' in d[ANNOTATIONS] for api in d[ANNOTATION...
9743f59cd51506fe1157397a4096f48b3258afcc
19,589
import numpy def integrate_sed(wavelength, flambda, wlmin=None, wlmax=None): """ Calculate the flux in an SED by direct integration. A direct trapezoidal rule integration is carried out on the flambda values and the associated wavelength values. Parameters ---------- wavelength: A ...
e2fd2c3905bba104f8d4bc376cd56585b40332bf
19,590
def computeMSSIM(groundTruth, recovered): """ Compute Mean Structural SImilarity Measure (MSSIM) between the recovered and the corresponding ground-truth image Args: :param groundTruth: ground truth reference image. numpy.ndarray (Height x Width x Spectral_Dimension) :param ...
a8f24531de784d3ada684b7a5841c8a5a247c6ff
19,591
def test_cache_memoize_ttl(cache, timer): """Test that cache.memoize() can set a TTL.""" ttl1 = 5 ttl2 = ttl1 + 1 @cache.memoize(ttl=ttl1) def func1(a): return a @cache.memoize(ttl=ttl2) def func2(a): return a func1(1) func2(1) assert len(cache) == 2 key1,...
87d274517c6166db6d174281e6785809e45609b8
19,592
def queues(request): """ We get here from /queues """ return render("queues.html", request, { "queuelist" : request.jt.queues()})
b8f09a074ef496a9b51d001ec8441305b51ea933
19,593
def shorten_str(string, length=30, end=10): """Shorten a string to the given length.""" if string is None: return "" if len(string) <= length: return string else: return "{}...{}".format(string[:length - end], string[- end:])
d52daec3058ddced26805f259be3fc6139b5ef1f
19,594
def A2cell(A): """Compute unit cell constants from A :param A: [G11,G22,G33,2*G12,2*G13,2*G23] G - reciprocal metric tensor :return: a,b,c,alpha, beta, gamma (degrees) - lattice parameters """ G,g = A2Gmat(A) return Gmat2cell(g)
ddec7e3f70ee2de4963f67155bda5ee8743d418d
19,595
from typing import Any def update_user_post( slug: str, post: schemas.PostCreate, db: Session = Depends(get_db), current_user: schemas.User = Depends(get_current_active_user), ) -> Any: """ Update a user Post if its owner """ post_data = get_post(db, slug) if post_data is None: ...
629e580924a676cd74e728e31df6467367763a0e
19,596
from backend.caffe.path_loader import PathLoader def loadNetParameter(caffemodel): """ Return a NetParameter protocol buffer loaded from the caffemodel. """ proto = PathLoader().importProto() net = proto.NetParameter() try: with open(caffemodel, 'rb') as f: net.ParseFromString...
2b0a12cb479ed1a9044da587c1673fc5f3f89e6b
19,597
def extract_keywords(header, *args): """ For a given header, find all of the keys and return an unnested dict. """ try: header = pvl.load(header) except: header = pvl.loads(header) res = {} # Iterate through all of the requested keys for a in args: try: ...
2d1313befa8779b5b8f6efc686f92fd213c7dfa5
19,598
import os def plot_parcel_stats_profile(fnames, figure="save", fmt="png", **kwargs): """ Plot parcel statistics """ n = len(fnames) labels = kwargs.pop("labels", n * [None]) dset = kwargs.pop("dset", "aspect-ratio") no_xlabel = kwargs.pop("no_xlabel", False) beg = kwargs.pop("begin", ...
c77a5bdfdb696311835b194bf29034dbd9c07b39
19,599