content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def security_group_exists(self, sg_id=None, name=None): """ Checks if a security group already exists on this connection, by name or by ID. :param boto.ec2.EC2Connection self: Current connection. :param string sg_id: ID of the security group to check. Default : None. :param string name: Name of the...
042cd05a550b139b3441613269f59a27ad028ea1
62,487
def FCS2CorrSplit(data, dwellTime, listOfG=['central', 'sum3', 'sum5', 'chessboard', 'ullr'], accuracy=50, split=10): """ Chunk SPAD-FCS trace into different parts and calculate correlation curves ========== =============================================================== Input Meaning -------...
346f0ee5be3f825e593a40276f2228569ff3bfc7
62,488
from typing import Optional from typing import Sequence def get_log_saved_searches(compartment_id: Optional[str] = None, filters: Optional[Sequence[pulumi.InputType['GetLogSavedSearchesFilterArgs']]] = None, log_saved_search_id: Optional[str] = None, ...
d4d8b0b8f8cc38f85fdd8d31e9f596e60a9d1ce8
62,490
def repeat(x, nTimes, assertAtLeastOneRep=False): """ Repeat x nTimes times. Parameters ---------- x : tuple or Circuit the operation sequence to repeat nTimes : int the number of times to repeat x assertAtLeastOneRep : bool, optional if True, assert that nTimes > 0. ...
fd03fa160625d9690aeda6bc5313f5af5999bc4a
62,491
import json import torch def load_model(directory, model_version=None): """ Returns model, data_loader and mask_descriptor of trained model. Parameters ---------- directory : string Directory where experiment was saved. For example './experiment_1'. model_version : int or None ...
af6799f2b43e666638c44c89a5550ff8357d0b2a
62,492
def load_data(file_name: str) -> dict: """Reads all data in h5 file ``file_name`` and returns them as a `dict`.""" with h5py.File(file_name, 'r') as data_file: q_values = np.array(data_file.get('q_values')) reflectivity = np.array(data_file.get('reflectivity')) labels = pd.read_hdf(fil...
f5fc95a47eb7edd039fab3040a18b37d3c8641dc
62,493
def pixel_scale(y): """Function (from WFC3 paper), to determine max and min scale for given ycen""" # Add or subtract 150 from y to account for impact # of vertical scan on y position. min = 0.0028*(y-150) + 44.68 max = 0.0026*(150+y) + 45.112 out = np.asarray([min,max]) return out
27845ec93ea212a12df680faba02e515bde048ba
62,494
def sbe43(calib, P, K, T, S, V): """NOT TESTED IS THIS IN ITS-90? DOES IT MATTER? SBE equation for converting SBE43 engineering units to oxygen (ml/l). SensorID: 38 Parameters ---------- calib : dictionary calib is a dict holding Soc, Voffset, Tau20, A, B, C, E P : array-like ...
30bc9b73bcef840e045b22dcc67d402a3dca61f7
62,497
def get_approximate_cloud_underside(qc, z_tol=100.0): """ Using 3D condensate field `qc` create a 2D array representing the underside height of the lowest cloudy point per column """ z_cloud_underside = qc.zt.where(qc > 0.0).min(dim="zt") m = z_cloud_underside < z_tol + z_cloud_underside.min() ...
5605531095b47e9552ca00b852188f4189bf43fe
62,498
def getDivisionByID(xStarts: [int], yStarts: [int], idDivision: int, divisionSize=1024): """ Return x and y starting and ending coordinates for a specific division :param xStarts: the x-axis starting coordinates :param yStarts: the y-axis starting coordinates :param idDivision: the ID of the divisio...
f82fd932eefd2560567117f96fdb7fc165a9bda7
62,499
def vulncircles(): """ Vulnerability Circles shows critical vulnerabilities based on a scientifically proven formula involving CVSS score, metrics, counts and accounts """ response.title = "%s :: Vulnerability Circles" % (settings.title) response.files.append(URL(request.application, 'static', '...
f6ab1b49848b6fb51d239d64eadb5555f3e0dc38
62,500
def get_nodal_load(load): """ """ if isinstance(load, (list, tuple)): try: load = check_list_units(load) load = load[:6] except AttributeError: load = check_list_number(load, steps=6) elif isinstance(load, dict): load = check_point_dic(load) el...
75f5c8add21562649025f4554ea94742337bd19b
62,502
def dowhile(interp, lst, test): """ DO.WHILE instructionlist tfexpression command. Repeatedly evaluates the ``instructionlist`` as long as the evaluated ``tfexpression`` remains TRUE. Evaluates the first input first, so the ``instructionlist`` is always run at least once. The ``tfexpression`...
c3e0f91f9e1b4abd257fb3a2f84c3ea9de1e7275
62,503
def calc_t1(element): """Calculate the first tangential vector for the given element based on type and normal vector.""" n_0, n_1, n_2 = element.n_v t1_v = np.array([-n_2, 0.0, n_0]) if abs(n_0) > abs(n_1) \ else np.array([0.0, -n_2, n_1]) return norm_vector(t1_v)
06d59afbb317a928959027cd1ba59efc2e3b322d
62,504
import re def get_ds_id_from_auto(auto): # type: (str) -> Optional[str] """ Fetch the ID from an auto block """ tokens = re.search(r'options *: *(.+?) *(=|$|\})', auto, re.IGNORECASE) ds_id = None # type: Optional[str] if tokens is not None: try: ds_id = tokens.group(1)...
e866b0f4fb7c9882bbe94ba7548d184e680bab9d
62,505
def unperson_page_wizard(*pages): """ @login_required @unperson_page_wizard('url_or_name', ...) def view_func(request): pass Directs any User without Person through a series of pages before letting them perform this view. """ assert len(pages) >= 1 def outer(view_func): ...
a8757ad2f8b64da5628b5817fb862ae0a46cdd40
62,506
import codecs def eval_escapes(s): """ Given a string, evaluate escape sequences starting with backslashes as they would be evaluated in Python source code. For a list of these sequences, see: https://docs.python.org/3/reference/lexical_analysis.html This is not the same as decoding the whole str...
ea01ab39275ddf7bd9f326bb9d505325f768efff
62,507
def _select_and_apply_random_policy(policies, image): """Randomly selects an augmentation policy and applies it to the image. Taken from third_party/cloud_tpu/models/efficientnet/autoaugment.py. Args: policies: A list of possible policies to sample from. image: A uint...
feaa17bc96f747304625c6e21122e685850b2941
62,508
def compose_user_full_name_from_object(user): """ Return user's full name representation for the views from the user object. Needed because of unrequired first and last names. """ return compose_user_full_name(user.username, user.first_name, user.last_name)
5218353a7ec9e7a2e639293577907167b504b91f
62,509
def let_syntax(tree, *, args, syntax, expander, **kw): """[syntax, expr/block] Introduce local **syntactic** bindings. **Expression variant**:: let_syntax[lhs << rhs, ...][body] let_syntax[lhs << rhs, ...][[body0, ...]] Alternative haskelly syntax:: let_syntax[[lhs << rhs, ...] i...
8d2312a66888c290c75833243cb291fa5e8de325
62,510
def calculate_orientation_error(desired, current): """ Optimized function to determine orientation error borrowed from robosuite. thanks, robosuite. """ def cross_product(vec1, vec2): S = np.array(([0, -vec1[2], vec1[1]], [vec1[2], 0, -vec1[0]], [-vec1[1], vec1[0], 0])) return np.dot(S, vec2) ...
22e48f461e146df15a5af266a2b1ef4d42467988
62,511
def is_broadcast(number): """Check whether the number is the broadcast address. Broadcast addresses are meant to be received by all nodes in a network.""" number = compact(number) return number == 'ff:ff:ff:ff:ff:ff'
4c505adfe6a4db32580225ea4b9b1405b581db88
62,512
def create_user(email, password='test', **kwargs): """ Create a user with the given ``email``. :param email: The ``email`` of the user. :param password: Defaults to ``test``. :param kwargs: Extra attributes for :class:`trix.trix_core.models.User`. Examples:: from trix.project.develop....
5c0afe3c493bfc606ffd89d32881e3294d6631d4
62,514
def to_int(x, error=0): """Convert argument to int.""" try: return int(x) except (ValueError, TypeError): return error
2c363a1d9125e396a76007d9986748b98130e1ab
62,515
from typing import Callable import functools def setting_method(func: Callable): """ このメソッドを設定用メソッドとする """ func.setting_method = True @functools.wraps(func) def inner(self, *args, **kwargs): result = func(self, *args, **kwargs) self._progress_of_settings[func.__name__] = True r...
ed809b6358f92a71774cb5db146f8e9dbf5c02b5
62,516
def CntDegNodes(*args): """ CntDegNodes(PNEANet Graph, int const & NodeDeg) -> int Parameters: Graph: TPt< TNEANet > const & NodeDeg: int const & """ return _snap.CntDegNodes(*args)
b1a2d696dc0cab82cfbffe01cece7f9db0d42494
62,517
def get_req_id(feature_id: str): """ Return the id matched in an id string. Format should be similar to #24 """ req_id = match("^#?([0-9])+$", feature_id) assert req_id, "**Feature request id's must either be a number or follow `#<id>`**" return int(req_id.group(1)) - 1
ccc85c1d71f2fa255a9a795ce53d2a29dc57f4a3
62,518
def apply_format(data_frame, column_names, format_method): """Apply a formatting function to a DataFrame column and return. Simplify applying format modifications to the data stored in columns of `data_frame`. Check if the parameters are of the right type, apply `format_method` to the columns of `data_...
af8f09d57e1f48da79c576ae542bfc5cc6cd837b
62,519
from typing import List def sample_keys() -> List[Key]: """ A pytest fixture for generating a list of sample ``Key`` objects. """ return [ Key("foo"), Key("bar", subkeys=[Key("baz", default=1), Key("quux")]), Key("quuz", default=1, subkeys=[Key("corge", default=True)]), ...
72b43da025d07fd5ae9a4c039d5be09797bf62aa
62,521
def _scalar_add_tensor(x, y): """ Number is added to tensor. Args: x (Number): x y (Tensor): The dtype is same as x. Returns: Tensor, has the same dtype as x. """ return F.tensor_add(x, y)
093317d8b29669d1449c3eeca3cca3aeb9bd2c97
62,522
def custom_func_movingaverage(populator, days, center_cell, date_cell, match_cell, template_cell, target_cell, **kwargs): """Get an Excel formula that will calculate the moving average centered on a cell. Parameters ---------- days : int | str The number of days for the moving average. cent...
0fc47cbb72cd68fccb3b04ddacea7bf327968eb2
62,523
def conv2d(x, W): """conv2d returns a 2d convolution layer with full stride.""" return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='VALID')
e413517fe9c5767b3340e0304f67e17a3f1616de
62,524
def _get_ppa_info_from_launchpad(owner_name, ppa_name): """ Idea from softwareproperties.ppa. Uses urllib2 which sacrifices server cert verification. This is used as fall-back code or for secure PPAs :param owner_name: :param ppa_name: :return: """ lp_url = "https://launchpad.net/...
12e2d6c2211dc2274e7947edba1338d94ede708a
62,526
def readPvs(pvs, **kwargs): """ returns a list of (value, length, timestamp) """ timeout = kwargs.get("timeout", CA_TIMEOUT) niter = kwargs.get("niter", 3) # avoid double read in case pvs has duplicates. tmp = dict([(pv, None) for pv in pvs]) tmppvs = tmp.keys() for i in range(nite...
e667782272aa4efb36cef349bae79f16991305d8
62,527
import re def is_valid_email(email): """ Validate email parameter is a valid formatted email address :param email: string containing email address :return: True if email is valid otherwise False """ if not email: return False return bool(re.match("^.+@(\[?)[a-zA-Z0-9-.]+.([a-zA-Z]...
6e5474126b2c342a8d6699d07fb816618dc60562
62,528
import json def is_valid_json(json_str:str)->bool: """Check if the given string is valid json string Return true if json is valid """ try: json.loads(json_str) except ValueError: return False return True
6ff60d74cee8f252bd7914b78a0c3df3d3bece5f
62,529
from pathlib import Path from typing import Callable from typing import Any import logging def cache_decorator_factory(cache_dir: Path, hash_f: Callable) -> Callable: """ Creates a cache decorator. Parameters ---------- cache_dir : Path Path, where function output are save and read from. ...
5feb838ebd5fb27ef3d1309d7c9b5f973e2978fb
62,530
from operator import not_ from operator import and_ from operator import or_ def extract_mutex_rules( typeset: Typeset, output_list: bool = False, ) -> LTL | tuple[list[str], Typeset]: """Extract Mutex rules from the Formula.""" rules_str = [] rules_typeset: Typeset = Typeset() for mutex_gro...
3b5dad6c1a1b996fcb0579a16400a67c5e86f67e
62,531
def get_all_contests(platforms, time): """Gets all the contests and writes it to standard output""" contests_data = get_contests_data() active_contests = contests_data["active"] upcoming_contests = contests_data["pending"] platform_filter = get_platform_filter(platforms) contests_data = [contest for conte...
6e791cf6604717696120031e57d88cc2501b8850
62,532
def _GenerateInputs(emitter, registers, lanes_count, input_address, stride): """.""" inputs = [] last_address_register = input_address for i in range(lanes_count): if not i: inputs.append(input_address) else: address_register = registers.GeneralRegister() inputs.append(address_register...
3344826f6d36ff5a9e689e63693ba6e556ede47c
62,534
def remove_special_characters(value, remove_spaces=True): """ Removes all special characters from a string, so only [a-Z] and [0-9] stay. :param value: The value where the characters need to be removed from. :type value: str :param remove_spaces: If true the spaces are also going to be removed. ...
a4c94b1aa52c6169610cb839f95d8163ab48c13b
62,536
def isascii(s): """Return True if there are no non-ASCII characters in s, False otherwise. Note that this function differs from the str.is* methods in that it returns True for the empty string, rather than False. >>> from bridgedb.util import isascii >>> isascii('\x80') False >>> isascii('...
fca7863de21639818e074507e016574a957ff250
62,537
def shellavg(data, center=None, rad=None, portion=False, stdev=False, avg=True, weight=None): """ Average data over bins of spherical shells. Parameters ---------- data : `np.ndarray` Three-dimensional data array. center : `tuple`, shape `(3,)`, optional ...
2691c7bf335342cc53c5be222e5fc15c944d4a52
62,538
def connectivity(bodies, ee): """ Builds the connectivity matrices. SS[i, k] +1 = the i-th body is connected to the k-th body -1 = i-th body self-connection (always present) 0 = no connection between i-th and k-th bodies SE[i] list of bodies wit...
19c9f49741b2b59587d4c599f018fd873b851f00
62,539
import typing def actives(apikey: str) -> typing.List[typing.Dict]: """ Query FMP /actives/ API :param apikey: Your API key. :return: A list of dictionaries. """ path = f"actives" query_vars = {"apikey": apikey} return __return_json(path=path, query_vars=query_vars)
2f5e6e1cc1a4214fd5acb3b5e6c5fae820181a9f
62,540
def echoview(calfile, channel): """ Read calibration parameters from an echoview calibration file Args: calfile (str): path/to/calibration_file. channel (int): channel you want to read. Returns: object with calibration parameters """ # create ob...
dec1272cd2b913b5364c45dce7ba300017267a02
62,541
def create_mne_raw_object(fname, read_events=True): """Create a mne raw instance from csv file""" # Read EEG file data = pd.read_csv(fname) # get chanel names ch_names = list(data.columns[1:]) # read EEG standard montage from mne montage = read_montage('standard_1005', ch_names) ch_ty...
ddc05c7e6032309364f9a56f0921dfff2c35adfd
62,542
async def request_one_batch(batch_seq="!"): """ Make a batch query request. Typically POST to query endpoint. """ http_client = AsyncHTTPClient() body = urlencode({'q': get_random_terms()}) response = await http_client.fetch( URL, method="POST", body=body, raise_error=False, ...
bd1bb44f083f65e6d905ee573ec8a7361b0914a7
62,543
def safe_execute(default, exception, function, *args): """ Inline Try/Except Parameters ---------- default : Object value returned in case of failure exception : Exception type of exception you want to catch function : function the function to execute args ...
aae61410c96741985cc2e03786bbc5c69ad80fa8
62,544
def kernel_s_yz1(y, x, z, zc, yp, xp, zp): """ Kernel for yz-component of stress in the infinite space domain (1st system) """ # Y = y - yp # X = x - xp # Z = z - zp Y = yp - y X = xp - x Z = zp - z rho = np.sqrt(Y ** 2 + X ** 2 + Z ** 2) kernel = ( safe_log(X + rho) ...
02e76d3cfdb49a91358b50c52e9fe3118a08383d
62,545
import time def create_task_id(): """ Creates new task ID. It is probably not too safe, but now it is current time with big precision. It will be refactored later. """ return str(int(round(time.time() * 10**9)))
641b9cd2715c1ef065f0e1a8c71c09a8a880dbe2
62,546
def to_square_matrix(idxs, sims, symmetrize=False): """Return a full square matrix from our internal sparse representation. Parameters ---------- idxs : np.ndarray array of indices to the original setlist, for each pair of elements for which similarities were computed. sims : np.nda...
6e32f4bc4890cab28dbb95672abc02311dd9bdc1
62,547
def column_length(list_of_tags): """ Given a list of tags(strings), method returns the length of the longest tag key(string) :param list_of_tags: list of tags of the form {'Key': key, 'Value': value} :return: length of longest tag (string) """ list_of_keys = list_of_keys_of(list_of_tags) ...
d3cdca8dde5305407f4ad4a25ff16e67fd644b74
62,548
def voltage_evq(energy,charge): """Usage: voltage_evq(energy, charge)""" return energy/charge
d8a347cd69e9a822bf8ac7c91437b60cabf2bb33
62,549
def create_permissions_mapping(User, GroupData): """Create mapping permissions to users and potential new group name.""" mapping = {} users = User.objects.filter(user_permissions__isnull=False).prefetch_related( "user_permissions" ) for user in users: permissions = user.user_permissi...
8b42e3430ee475209bfc01aca21b7cf3d76590f9
62,551
def post_new(request): """新建文章""" if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user # 开始处理标签 ptags = request.POST['tags'].strip() all_tags = [] ...
16120f4a7ee8b0d56f54847722a5524a1dfcd7e3
62,552
def fJy_to_flambda(wavelength, fJy): """ Convert a FJy vs lamnda spectrum to Flambda vs lambda Parameters ---------- wavelength: list-like of floats The wavelengths in Angstrom. fJy: list-like of floats The FJy flux density in Jy Returns ------- flambda: ...
c3698f70b91f976b831753355ff979a2c656a55f
62,553
import tokenize def build_model(): """Creates a GridSearchCV pipeline for the model. Parameters include unigram and bigram, minimum and maximum document frequency, and the classifier. Args: None Returns: sklearn.pipeline.Pipeline: The GridSearchCV pipeline. """ pipeline = P...
bb05cee9eafacf0762330a4df950786cadfcaeb9
62,554
def discretized_space(low_bound, up_bound, steps): """ Discretization of the real interval [low_bound, up_bound] into a sample space with steps many points """ step_size = (up_bound - low_bound) / steps points = [] for i in range(steps): #p = low_bound + i * step_size p = low_bound +...
60722737d9ccc7cfc68b0fbf719360ca6496bf0b
62,555
def optimally_solve_sub_instance(sub_instance: SubInstance, init_solution: Solution = None): """ This function solves in an optimal manner a sub-instance of the original problem by formulating it as a MIP problem and the solving it with the Python-MIP library. Args: sub_instance (SubInstance):...
6ba641a21e1f3ef02c0cd24e1143c3a3cda4bee3
62,556
def tree_init_three_nodes_right(): """Init binarySearch uneven.""" return BinarySearchTree([4, 5, 6])
e66317fc830db97de84d165b378b5bfc83d72ded
62,557
import torch def estimate_translation(joints_3d, joints_2d, pts_mnum=4,focal_length=600, proj_mats=None, cam_dists=None,img_size=np.array([512.,512.])): """Find camera translation that brings 3D joints joints_3d closest to 2D the corresponding joints_2d. Input: joints_3d: (B, K, 3) 3D joint locations ...
39f4ddeb2c70cc9152723b0c6caf22315e762d10
62,558
def run_kolmogorov_smirnov(dist1, dist2, alternative='two-sided'): """ Compute the Kolmogorov-Smirnov statistic on 2 samples. See https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.ks_2samp.html :param list dist1: sequence of 1-D ndarray (first distribution to compare) drawn from a continuous...
ea3b5c3ecb8c26931a6bc30ee0a4253f9b0f5917
62,559
def cached_BCH_term(product_formula: SymmetricProductFormula, order: int) -> Operator: """Attempt to load a stored BCH_term for product_formula from disk. If it isn't there, compute it and store it. The directory that is searched is indicated in the environment-variable $DATA_DIR, ...
3385a1116ad0796bbbf6b7f7ea59e28b13f96098
62,560
def run(timeout: float = 2.0): """ check Check if each webshell is alive. eg: check {timeout=2.0} """ if not exists("webshell.log"): print(color.red("No webshell.Log")) return 0 with open("webshell.log", "r") as f: lines = f.readlines() for index, line in ...
ea16a578b28791c7edee12f3334306a6c8c3bf81
62,561
def check_url(url: str) -> str: """Check and fix url provided.""" flag = False if not validators.url(url): logger.warning(" url (%s) is not valid", url) logger.info("We try to fix it.") flag = True f_url = furl(url) if f_url.host is None and f_url.scheme is None: # ...
c394b1d140c1e142cab03036014d3d9f995d21d8
62,563
def f_rosenbrock(x): """ Define the benchmark Rosenbrock function. :param numpy.ndarray x: The function's argument array. :return: The evaluated function at the given input array. :rtype: float """ dim = len(x) f = 0.0 for i in range(dim-1): left_term = 100....
cd6d0a94dabd094ff4835d28d4d0b651a0f620e1
62,564
def linear(x: float, target: float, span: float, symmetric = False) -> float: """Create a linearly sloped reward space. Args: x (float): Value to evaluate the reward space at. target (float): The value s.t. when x == target, this function returns 1. span (float): The value s.t. when x >= target ...
b443d42ec2686830668d1287db9a8e8fda3f5df1
62,565
from typing import List from typing import Tuple def serialize(deal: Deal) -> bytes: """ Convert a Deal to a binary representation. Use two bits for each card to represent the Direction which holds that card. Two more bits encode the Direction that delt, and two final bits to encode vulnerability. :pa...
1a62b87a159c0868bb2b1a5d359db411f122a968
62,566
def _extract_identifiers(entries): """ Extracts a unique list of identifiers from a group of identifiers that follow the PSI-MITAB format, e.g. ['intact:EBI-476586', dip:DIP-33878N']. Parameters ---------- entries : array-like An array of identifiers. Returns ------- list ...
9f2d2ec668e1b15875ca031b6918d334681c53c3
62,567
def lark_to_non_null_type_node(tree: "Tree") -> "NonNullTypeNode": """ Creates and returns a NonNullTypeNode instance extracted from the parsing of the tree instance. :param tree: the Tree to parse in order to extract the proper node :type tree: Tree :return: a NonNullTypeNode instance extracted...
dacbecf1895bea84b7097be31d87f37906468d34
62,568
from typing import Tuple def parse(arg: Tuple[str, str, str, str]) -> Tuple[str, str]: """Two Register Instructions Parser.""" return (arg[2], arg[3])
55aa9f69712845bd8d3c2b399e43d26363d372d9
62,569
def nearest(origin, tessellation, col): """ Brute force approach to find, for each point in a geodataframe, the nearest point into another geodataframe. It returns a Pandas Series containing the value in col for each matching row. :param origin: GeoDataFrame :param tessellation: GeoDataFrame :pa...
bb9b78b36bde55e9c0ca315205f24d16b21ddf9e
62,570
def get_synchronized_timed_loop(control_loop_period, player, iterations_per_update=100,): """ Creates an instance of SynchronizedTimedLoop. Returns the timed loop instance and an empty sleep function that can be used to make execution halt ...
5b60d5df38cd849dbd7ee965e17031c0a933517f
62,571
def geometry_pose_multiply(pose_a, pose_b): """ Multiply one pose with another Parameters: * pose_a (Pose): The first pose * pose_b (Pose): The second pose Return (Pose): The result of the multiplication """ geom_util = GeometryUtil(node = PyriSandboxContext.node) T_a = geom_uti...
144c2a5750a5927d9160aff7e6252ba4eb791801
62,572
def parse_data(gfs_grb2_df: pd.DataFrame, envelope_gdf: gpd.GeoDataFrame): """Read in a GFS GRB2 file and bound it by a geodataframe of envelopes. Returns: gpd.GeoDataFrame: GeoDataFrame of related GFS points. """ df = gfs_grb2_df # Assert that there are no rows which are not poly types in ...
82d827a8981e8fbb9dd02cb63a4efd89b6a04f7a
62,573
def parse_flask_rule(rule: str): """Parses a flask rule (URL), and returns an openapi compatible version of the url""" parsed_rule = [] index = -1 while index < len(rule): index += 1 if index > len(rule) - 1: break char = rule[index] if char != "<": ...
bb4b788887d4f3336d88e4d1d81bab04fa37f67a
62,574
def get_collection_id(collection): """Return id attribute of the object if it is collection, otherwise return given value.""" return collection.id if type(collection).__name__ == "Collection" else collection
11585f4022b1ff32a4b84b73a5135896b2544126
62,575
def get_monitor_form(endpoint, default_value): """ Return a form with the endpoint as a variable """ form = MonitorLevel(request.form) form.monitor.default = default_value form.monitor.label = endpoint form.process() return form
8e910315a32651bdab5695ae18b1aa284956fb63
62,576
import scipy def calibrate(latticeClass, latticeSize, eta, fallerClass, posfile=None): """Performs a calibration of the fitting parameter. latticeClass = the class of lattice to calibrate for latticeSize = size of lattice eta = viscosity fallerClass = the class of faller to calibrate for """ ...
8de7af0e420acab69b99c430f7b18206b4cf03cf
62,577
def computeNormalizationMatrix(X): """ Compute a matrix M which maps a set of points X to their 'normalized' form Xnorm, i.e. Xnorm = unhom(M * hom(X)) where the mean Euclidean distance of the of points in Xnorm is sqrt(2) and the centroid of the points is the origin. For more on why ...
450e963e9a1bf3ad02b678b48d89c6da2b8492d3
62,578
import torch def bce_loss(logits: torch.Tensor, targets: torch.Tensor, weights: torch.tensor) -> torch.Tensor: """Cross entropy loss for binary classification. Args: logits: NAM model outputs targets: Binary class labels. Returns: Binary Cross-entropy loss between model predictions and...
c598ac8a85a61f9b79d7a1ce3fa5edf03fee28c0
62,579
from typing import Tuple from typing import List def play_game(color: Color, weight: float) -> Tuple[float, int, float]: """Plays a game using the default MCTS AI and specified weight factor. Args: color: the enumerated Color that moves first. The color with the new weight value is always Bl...
ac0049a82c0ec427f6fa3bc1a3520b7eabe832f6
62,581
def get_service_group(): """Returns a ServiceGroup factory with defaults: name='Test Service Group'""" def _get_service_group(name="Test Service Group"): service_group_instance = ServiceGroup(name=name) return service_group_instance return _get_service_group
d4b6cb498db09ba0bf781924cec2dd54c9fcafd2
62,583
def EncoderBlock(d_feature, d_feedforward, n_heads, dropout, mode): """Transformer encoder block. The input to the encoder is a pair (embedded source, mask) where the mask is created from the original source to prevent attending to the padding part of the input. Args: d_feature: int: depth of embedding...
2022e7bd0d343c819b107b6881f1487648b5c5e8
62,584
def _get_events(resource_id, start_date, end_date, resource_type): """Create a list of events.""" events = {} if resource_type == 'host': leases = _get_leases_from_host_id(resource_id, start_date, end_date) elif resource_type == 'floatingip': leases = _get_leases_from_fip_id(resource_id,...
2b301fc54a8834301a66090064e2a2e922810071
62,585
def parse_table_schema(json, precise_float): """ Builds a DataFrame from a given schema Parameters ---------- json : A JSON table schema precise_float : bool Flag controlling precision when decoding string to double values, as dictated by ``read_json`` Returns -...
eec0dc84c70948e099539d8ebbc40407541318a4
62,586
def killfunc(): """Parses the kill function.""" def cull_seps(graft): return graft[0] or graft[1] def breakdown(tokens): if len(tokens) > 6: return AthTokenStatement(tokens[-4], tokens[1]) else: return AthTokenStatement(tokens[-4], [tokens[0]]) return ( ...
bb9dccd1cd60312c7fd02eca364dda32bf9d6253
62,588
def load_events(file_path): """Load the EventAccumulator object to get data from event files. Args: file_path: Path to the event files. Returns: A loaded tensorboard....event_accumulator.EventAccumulator object. """ ea = event_accumulator.EventAccumulator(file_path) ea.Reload() return ea
3199c42f06497dd75367f438ceb40c1b293d12bf
62,589
def update_rankk(a, c=None, UPLO='U', transpose_type='T', sym_out=True, workers=1, **kwargs): """ Compute symmteric rank-k update, with broadcasting Parameters ---------- a : (..., N, K) or (..., K, N) array Input array. If `transpose_type` is 'N', `a` should be shape ...
a27dcf96d58ea357e15dde76e5f5c035a7778fdc
62,590
def first_non_empty(items): """ Return first non empty item from the list. If nothing is found, we just pick the first item. If there is no item, we return the whole form (defaulting to []). """ if items: for it in items: if it: return it return item...
93dce672b5a28c094b8916c535aac2ae3622e890
62,591
def qwc_complement_adj_matrix(binary_observables): """Obtains the adjacency matrix for the complementary graph of the qubit-wise commutativity graph for a given set of observables in the binary representation. The qubit-wise commutativity graph for a set of Pauli words has a vertex for each Pauli word, ...
514fbab887d32d5d6ebcf683cc7736e2224c6f2d
62,592
import logging def is_notification_queue_empty(): """ Checks if the notification queue is empty Returns: boolean -- Flag representing if the notification queue is empty """ queue_arn_parts = config.DeploymentDetails.sqs_arn.split(sep=':') queue_name = queue_arn_parts[len(queue_arn_parts) ...
a53118a85aaca91ec73f452440be5e657e8e1118
62,593
def sum_up(group): """ Creates an aggregate by sum using the required column headers """ return group.aggregate(dict((h, ['sum']) for h in head))
36fac7b0c33ea9e4ad8cd32d109954c6077bf7d2
62,594
def format_keys(obj, max_width): """ Format the keys of a dictionary of keybindings as text for display. Formats multiple keybindings on each line within the max_width Parameters: obj (:class:`pwbem.CIMInstanceName`): Instance name from which keybindings are to be extracted for f...
0c61f3be039f3978f1e5b1cd4ccf7587dfc11885
62,595
from typing import Any def delete_path( *, db: Session = Depends(deps.get_db), id: int, current_user: models.User = Depends(deps.get_current_active_user), ) -> Any: """ Delete an path. """ path = crud.path.get(db=db, id=id) if not path: raise HTTPException(status_code=404, ...
2428fb9de2a4655a4b579a733d5eae0f01d7fdce
62,596
from datetime import datetime def datetoInt(dateIn,begin,both=False): """ Calculates the integer of a date from a reference date :param dateIn: date :param begin: reference date :param both: if set to True both the int and the string of the date are returned :return: interger value of a date,...
10a01814ef87fa6c69a75ca3a3f3020af877904e
62,597
def maintenance_get_verified_thread(): """ Function to quickly get the Reddit ID of the latest verification thread on startup. This way, the ID of the thread does not need to be hardcoded into Ziwen. :return verification_id: The Reddit ID of the newest verification thread as a string. """ verif...
fee53cda50afb50f6625ce698d27a12c76d8fc95
62,598
def signout(): """ Sign out request @return: redirect back to sign in """ if "username" in session: session.pop("username") return redirect(url_for('signin'))
db974642ffc417ab2ea2438fc3d172e98d8a8f3c
62,599
from typing import Optional def does_table_exist(database: str, table: str, boto3_session: Optional[boto3.Session] = None): """Check if the table exists. Parameters ---------- database : str Database name. table : str Table name. boto3_session : boto3.Session(), optional ...
efa45b5d7ffbf6281046deb6f838e2188a06a194
62,600