content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def has_phrase(message: str, phrases: list): """ returns true if the message contains one of the phrases e.g. phrase = [["hey", "world"], ["hello", "world"]] """ result = False for i in phrases: # if message contains it i = " ".join(i) if i in message: result = True return result
f56fcc261e21c538f1f23b811e14ae29d92f3038
3,603,613
def _homogeneous_matrix(matrix=np.identity(3), offset=np.zeros(3)): """ Combine transformation matrix and translation vector for dimension d into homogeneous (d+1, d+1) transformation matrix to be used with homogeneous coordinates. Parameters ---------- matrix : array-like of int or float with ...
69d9c2759eb19a6f97b44c8f40431ad20126f811
3,603,614
def einstein_relation(universe, input_time='ps', input_length='au', length='cm', time='s'): """ Compute the (time dependent) diffusion coefficient using Einstein's relation. .. math:: D\left(t\\right) = \\frac{1}{6Nt}\\sum_{i=1}^{N}\\left|\\mathbf{r}_{i}\left(t\\right) ...
697518ef6ce29332f219fae9b8577c590059a7dc
3,603,615
import warnings def flatten_reply(reply): """Flatten node replies. Convert from a list of replies in this format:: [{'a@example.com': reply}, {'b@example.com': reply}] into this format:: {'a@example.com': reply, 'b@example.com': reply} """ nodes, dupes = {}, s...
4cd32da49df926eea82acda70bf4a4cf053b9ca9
3,603,616
from joblib import dump def knn_predictor(audio_feats): """ similar_song_ids, visual_df = knn_predictor(audio_features) """ # from sklearn.pipeline import Pipeline # Scale the data with standard scaler # pipeline = Pipeline([('encoder', StandardScaler()), # ('model', ...
6af767dd06e0d3890eef0aba98ed44f602abfeaf
3,603,617
def perform_dependency_parsing(doc_text: str, spacy_language_model): """ First phase of processing from the second part of the series. Parses a document using SpaCy's depdendency parser, then converts the outputs of the parser into a Pandas DataFrame using Text Extensions for Pandas. """ re...
ba4bcab8ef1dc126bf7e027eac4ac025b2245fde
3,603,619
from typing import Optional def substringBetween(s: str, left: str, right: str) -> Optional[str]: """Returns substring between two chars. Returns""" try: return (s.split(left))[1].split(right)[0] except IndexError: return None
5cda5bc57fe1f65053dffb047bef0b34e0a39a2b
3,603,620
from typing import List from typing import Optional from typing import Union from typing import Tuple def fit( model: pyhf.pdf.Model, data: List[float], *, minos: Optional[Union[str, List[str], Tuple[str, ...]]] = None, goodness_of_fit: bool = False, custom_fit: bool = False, ) -> FitResults: ...
00a411a8f6fd29ae48f3d71573ea9cd616a970e5
3,603,621
def get_all_plans(db: orm.Session = Depends(get_db)): """Retrieves all existing plans Args: db (orm.Session, optional): [description]. Defaults to Depends(get_db). Returns: [dict]: key value pair of the following keys: message (str): success message data (List[plan_...
234a112ddf4125a0ae9cca056972dab02495b2b9
3,603,622
def build(config, main_prog, startup_prog, mode): """ Build a program using a model and an optimizer 1. create feeds 2. create a dataloader 3. create a model 4. create fetchs 5. create an optimizer Args: config(dict): config main_prog(): main program ...
5ae652716cc92c54be419ffb8fd0bb4c12ffae19
3,603,623
def variables_from_file(filename: str, variables: _PyTree): """ Loads the variables of a variational state from a `.mpack` file. Args: filename: the file containing the variables. Assumes a .mpack extension and adds it if missing and no file exists. variables: An object variable...
28c5f606a16a4af1507712056fcbae4716be8434
3,603,624
import logging def get_campaign_data(ad_account: adaccount.AdAccount) -> {}: """Retrieves the campaign data of the ad account as a dictionary Args: ad_account: An ad account for which to retrieve the campaign data Returns: A dictionary with {campaign_id: {'name': 1, 'attributes': {}}} fo...
b4638222f6020a79eb0004bcde135a90b03f749c
3,603,625
def label(row, structure_row, prefixes): """ Function to create and return a tuple of Turtle property and Turtle object for a given label Parameters ---------- row : Series row from structure_to_keep pandas series from generator ie, row[1] for row in iterrows() ...
80de4a686cd07197d1c82494f81390a93022e597
3,603,626
def is_in_dimension(cloud_array): """ check if the cloud segment is of required dimension i.e mxmxm""" max_dim = np.amax(cloud_array, axis=0) min_dim = np.amin(cloud_array, axis=0) return all((max_dim-min_dim) < BOX_SIZE), (max_dim, min_dim)
1326206647e15b0e02b44a232cf370871fdb8cd6
3,603,628
def default_image_path(hass: HomeAssistant, config_entry: ConfigEntry) -> str: """Return value of the default image path Returns the default path based on logic (placeholder for future code) """ # Return the default return "custom_components/mail_and_packages/images/"
cf29851a3c639b5676591456ce10d86e3c9b6a20
3,603,630
def check_output(solution: str, output: str) -> bool: """Check if program's output is correct. Parameters ---------- solution Sample output taken from BOJ. output Output from program run. Returns ------- bool True if correct, False if wrong. """ solution...
66d35952d892842bd1b47329bfa7b77e0a878a51
3,603,631
def get_ida_bg_color(): """ Get the background color of an IDA disassembly view. ----------------------------------------------------------------------- The necessity of this function is pretty silly. I would like lighthouse to be color-aware of the user's IDA theme such that it selects reasonable...
4249dc51d91bc960eedd76b639258e06ef6a64f0
3,603,632
def obtener_cantidad_vuelos_pais_en_ciudad_en_rango_anios(PaisDestino, CiudadDestino, AnioInicio, AnioFin): #OK """ Dado un pais, una ciudad y un rango de años obtiene la cantidad total de vuelos que llegan a esa ciudad durante esos años Dado un pais, una ciudad y un rango de años obtiene la cantidad total ...
38d12f17a842ef431327655a0068acfcf71c4a64
3,603,634
from typing import Sequence def bit_array_to_int(bit_array: Sequence[int]) -> int: """ Converts a bit array into an integer where the right-most bit is least significant. :param bit_array: an array of bits with right-most bit considered least significant. :return: the integer corresponding to the bit...
d902a8e3db7b65ad348ef86cbfac371361aedd58
3,603,635
def download_trajectory_data_rep_site(): """Download REPEATED SITE probe displacement data from Alyx Downloads the most up-to-date data from Alyx for all repeated site recordings, including their channel positions, and the orthogonal points of each channel from the planned trajectory. Sa...
e83765f86711fa74eb06bdfc97baff10df440254
3,603,636
def clip_args(func, arg1, arg2, bounds=(0., 1.)): """ Clip the arguments to bounds Return the results of the function where the clipped arguments have been used. Arguments below the lower bound are set to the lower bound and the arguments above the upper bound are set to the upper bound. Param...
249b5fed30fd050da570ef5276f826c071457935
3,603,637
def distance_p2p(points_src, normals_src, points_tgt, normals_tgt): """Computes minimal distances of each point in points_src to points_tgt. Arguments: ---------- points_src (numpy array): source points normals_src (numpy array): source normals points_tgt (numpy array): target point...
31c2bc839e1eb7b8f16b946a81fe3cc768390574
3,603,638
from typing import VT from typing import List def match_pivot(g: BaseGraph[VT,ET]) -> List[MatchPivotType[VT]]: """Does the same as :func:`match_pivot_parallel` but with ``num=1``.""" return match_pivot_parallel(g, num=1, check_edge_types=True)
051a9af33ac81844a23cb2c56cb14eccfd13e6c2
3,603,639
import math def euclidean_distance(p1, p2): """Calculate the euclidean distance of two 2D points. >>> euclidean_distance({'x': 0, 'y': 0}, {'x': 0, 'y': 3}) 3.0 >>> euclidean_distance({'x': 0, 'y': 0}, {'x': 0, 'y': -3}) 3.0 >>> euclidean_distance({'x': 0, 'y': 0}, {'x': 3, 'y': 4}) 5.0 ...
8cdc0e0534b2ed9272832fc0f977b9aa0e594c65
3,603,640
def run_performance_test(ops, inputs, run_backward=True, dtype='float32', ctx=mx.cpu(), profiler='native', warmup=10, runs=50): """Run operator benchmark for given operator or list of operators, ops, with the given inputs. Returns benchmark results as a list of...
c087916947fe5e3e32dfa1e25c776e85af9f9378
3,603,641
def increment(name, num_shards, delta=1, do_transaction=True, use_memcache=True): """ Increment the value for a given sharded counter. This will create the counter if it does not exist. Args: name: The name of the counter. num_shards: the number of shards in the counter """ retu...
ff64fe730c641e5fb606978ccb144f7ab62eef5f
3,603,642
def parse_date_string(date_string): """ Parse date string into datetmie object. """ if not date_string.isdigit(): raise ex.ExcalValueError("Input date must be numbers") length = len(date_string) convert_string = None if 0 < length <= 2: year = dt.date.today().strftime("%Y")...
1f198530c430df2f8d59c02a0e61bc1fb9789cbc
3,603,643
def conflict(soup): """ Find the conflict notes in footnote tag """ conflict = None try: conflict = extract_node_text(soup, "fn", attr = "fn-type", value = "conflict") except KeyError: return None return conflict
962793ea5fb255264ae880407e55369d2827ae3f
3,603,644
import warnings def load_fits_spectrum(fname, ext=None, iraf_obj=None): """ Flexible inference of spectral data from FITS files. The function allows to read a large number of spectral formats including FITS tables, multi extension FITS ImageHDUs, or IRAF like arrays Parameters ---------- ...
5fd13c8f1e92c8996d59e58cfc12020e6c87e8ac
3,603,645
import re def read_raw_dictfile(filename, language): """Read from unformatted dictfile: eliminate extra spaces and parens, insert a tab. Return a list of word,pron pairs.""" S = [] with open(filename) as f: for line in f: words = re.split(r"\s+", line.rstrip()) S.appen...
a8c95c87551119a89bd2c686be35b3a3aba3f567
3,603,646
def make_grid_prw(grid_pwx, data_prw_obs, data_rsnstcsnorm_obs): """Grid rsnstcsnorm based on prw grid.""" gridded_rsnstcsnorm_obs = np.zeros(len(grid_pwx), dtype=float) for jjj, bincenter in enumerate(grid_pwx): index_obs = np.where((data_prw_obs >= bincenter - 1.0) & ...
8166cde8037826f29cd6b60c1d333b6e51da6864
3,603,647
def backup_l3_attribute_map(): """Return a backup of the original l3 attribute map.""" return dict((res, attrs.copy()) for (res, attrs) in l3.RESOURCE_ATTRIBUTE_MAP.iteritems())
f5649e7cc52404051bd8df15d75cf32496d560ad
3,603,648
import zlib def zlib_handler(method): """ Prepare hash method and seed depending on CRC32/Adler32. :param method: "crc32" or "adler32". :type method: str """ hashfunc = zlib.crc32 if method == "crc32" else zlib.adler32 seed = 0 if method == "crc32" else 1 return hashfunc, seed
46e9d91e5ebe92f3b5b24f138ae693368128ce09
3,603,649
def hex_dump(string): """Dumps data as hexstrings""" return ' '.join(["%0.2X" % ord(x) for x in string])
7c0286c57387c5b8f6a79e2a9350eb54e480465a
3,603,650
def _nova_error_message(msg_type, message, status_code, request): """ Set the response code on the request, and return a JSON blob representing a Nova error body, in the format Nova returns error messages. :param str msg_type: What type of error this is - something like "badRequest" or "itemNot...
781b57a8b87316a49529e6b03fd19d4d391ac4c7
3,603,651
def get_operands_dtype(operands): """ Return the data type name of the tensors. """ dtype = operands[0].dtype if not all(operand.dtype == dtype for operand in operands): dtypes = set(operand.dtype for operand in operands) raise ValueError(f"All tensors in the network must have the sa...
cda67513ea8ca9f7ea663d232a5358fad8f8597d
3,603,652
def bmpToGDS(bmp, width, height, layer, datatype, black=0): """ Args: bmp: A string refering to the file location of the BMP file width: Physical Width (X) of the bmp image specified in micrometers height: Physical Height (Y) of the bmp image layer: Layer the bmp file should be ...
86e90b6ece1e7e648ea24f570c0f901e570d3e61
3,603,653
def get_j(xi, j=0): """ 得到小数定标标准化的j """ if xi / float(10 ^ j) <= 1: return j else: return get_j(xi, j+1)
975a74d70ceeba80debfadf171f6c32316cd7d7b
3,603,654
def get_shortest_path_waypoints_old(planner, origin, destination): """Return a list of waypoints along a shortest-path Uses A* planner to find the shortest path and returns a list of waypoints. Useful for trajectory planning and control or for drawing the waypoints. Args: planner: carla.macad_...
bb6cfdeb139c6c10cbd4fd8c4d0dc31083ecc2d6
3,603,655
def delete_container(client, resource_group_name, name, **kwargs): """Delete a container group. """ return client.delete(resource_group_name, name)
d69c3fbd89ce684942af4980ca9931908b12db6a
3,603,656
def translate_x(image, pixels): """Equivalent of PIL Translate in X dimension.""" image = tfa.image.translate(image, tf.constant([-pixels, 0], dtype=tf.float32)) return image
691444a857aa0b0103fd9aee8fa3735f04cfe605
3,603,657
def clean_input(): """ Make sure we're not getting bad data from the front end, format data to be machine readable """ if empty(request.form.get('password', '')): abort(400) if empty(request.form.get('ttl', '')): abort(400) time_period = request.form['ttl'].lower() if ti...
f6bf819d3b4bf5ea94c8346edd0719b6dfb11336
3,603,658
def nullspace_torques(mass_matrix, nullspace_matrix, initial_joint, joint_pos, joint_vel, joint_kp=10): """ For a robot with redundant DOF(s), a nullspace exists which is orthogonal to the remainder of the controllable subspace of the robot's joints. Therefore, an additional secondary objective that does no...
c18a6deac63d835b5392af84c0becddcaf322b49
3,603,659
def general_net(feat_model, identity_model, img_shape): """Returns a keras Model for training with classification and metric learning losses Args: feat_model: keras Model for feature extracting identity_model: keras Model for classification img_shape: tuple specifying (h,w) Retu...
88c029800347daf45c649be31a74525ea5390d53
3,603,660
def aga_contract_graph(adata, min_group_size=0.01, max_n_contractions=1000, copy=False): """Contract the abstracted graph. """ adata = adata.copy() if copy else adata if 'aga_adjacency_tree_confidence' not in adata.uns: raise ValueError('run tool aga first!') min_group_size = min_group_size if min_g...
93db3555722b8af7be0ac2764462d8440f543841
3,603,661
def put_method(method): """Annotation for a callable method specifying that it is a PUT method.""" return MethodStub(Method.Put, method)
afac5a2ed79183054381c3179db2edca1fc7a2c8
3,603,662
from typing import Union def get_difference_of_maxs(uni_ts: Union[pd.Series, np.ndarray]) -> np.float64: """ :return: The absolute difference between the maximums of the first and the second halves of a given univariate time series. """ mid = int(len(uni_ts) / 2) return np.abs(get_max...
c8e3c973ee25144a139c430ef07ea0d0d8255645
3,603,663
def generateMap(height, width): """ Generates the obstacle map as input for path planning using Half Plane equations (with clearance). Parameters: height: int Height of the obstacle map width: int Width of the obstacle map ...
81d70f86f41f678eb3a97549ea4de345f535e8f2
3,603,664
import re def export_filters(filename='filters.json', base_url=DEFAULT_BASE_URL, *, overwrite_file=True): """Saves filters to file in JSON format. Args: filename (str): Full path or path relavtive to current working directory, in addition to the name of the file. Default is "filters.json". ba...
611acec06867d2ecf873295cda905bff218086d8
3,603,665
import json def transformation(): """ Example: { "sentence_tokens": [ "show", "me", "the", "cheapest", "round", "trips", "from", "dallas", "to", "baltimore" ] } ...
c25b6912c3b0eab593ab0122a4f0098bc6f37e29
3,603,666
def TimeEvolution(time, hamiltonian): """ Time evolve a hamiltonian Converts the Hamiltonian to an instance of the pyQuil Pauliterms and returns the time evolution operator. This method mirrors the ProjectQ TimeEvolution interface. :param [float, int] time: time to evolve :param QubitOperator ...
1dcb22e524a54276676f31c4c5696c64cecf4176
3,603,667
from typing import Any from typing import Optional from typing import Iterator from typing import Tuple from typing import Sequence def distribute( df: Any, batch_size: Optional[int] = None, **kwargs: Any ) -> Iterator[Tuple[Sequence[HOST_T], Any, Optional[Sequence[Text]]]]: """Fetch SNMP ...
1a0b44545e0930b79972faaafe8ce86b0b252168
3,603,668
def train(train_loader, model, criterion, optimizer, epoch,current_iteration,rewire_period,DeepR_temperature,threshold): """Train for one epoch on the training set""" batch_time = AverageMeter() losses = AverageMeter() data_time = AverageMeter() top1 = AverageMeter() top5 = AverageMeter() ...
29334828e059ea63b27e6b5f435751db0a8f5042
3,603,669
def get_feature(internel_layer, layers, filters, batch_norm=False): """Get VGG feature body as stacks of convoltions.""" for i, num in enumerate(layers): for j in range(num): internel_layer = sym.conv2d( data=internel_layer, kernel_size=(3, 3), padding=(1, 1), ...
37670dd6204dc96531b645f68f25f67f5ce3f2dc
3,603,670
def unmatched_places(w, open, close): """ Given a word ``w`` and two letters ``open`` and ``close`` to be treated as opening and closing parentheses (respectively), return a pair ``(xs, ys)`` that encodes the positions of the unmatched parentheses after the standard parenthesis matching proc...
cfd2a50c50cecc6fcc08d4fd95df56ad503fa4d2
3,603,671
from typing import Callable def apply(grid: Grid, func: Callable[[Point], Point]) -> Grid: """Apply a pointwise function to all points of a grid Args: grid (Grid): Grid to apply function to func (callable): Pointwise transformation function Returns: Grid: Transformed grid """...
74e940d4fa1694a4a2dbd01bca8fa0d138f0ba1e
3,603,672
def _clip(n: float) -> float: """ Helper function to emulate numpy.clip for the specific use case of preventing math domain errors on the acos function by "clipping" values that are > abs(1). e.g. _clip(1.001) == 1 _clip(-1.5) == -1 _clip(0.80) == 0.80 """ sign = n / abs(n...
78308e70a405b3b3d94827c00705e8842b242cde
3,603,673
def proper_permutation(a): """ Computes the permutation matrix `P` such that all [n:t,n:t] submatrices of `P a P` are invertible. Parameters ---------- a : numpy.ndarray A symmetric binary matrix with ones along the diagonal. Returns ------- numpy.ndarray """ t = len(a)...
1d4050a473aec25c28532e03b8fdcfbc03c019e9
3,603,674
from scipy import interpolate def cmap_whitezero(cmap,N,Nwhites,pos): """Whites out middle index of a colormap from the continuous colormap cmap. cmap: colormap instance, eg. cm.jet. N: Number of colors. Nwhites: Number of whites pos: Position for white bar; if -1, will place in middle ...
4e8de7fed03fe0834ccff4d28364f8b37f222b51
3,603,675
import time import json def get_response_with_refreshed_jwt_cookies(request, user): """ Generates the response and resets the JWT related cookies in the response for the given user. """ cookie_settings = standard_cookie_settings(request) response = JsonResponse({}) _create_and_set_jwt_cookies(...
f990ce589b494f0e43cceabcfa26aa19a0e920be
3,603,676
def _batch_stitch(features, mean_length=4.0, stddev=2.0): """Stitches a batch of single-step data to a batch of multi-step data.""" batch_size = common_layers.shape_list(features['task'])[0] num_sequences = tf.maximum( tf.to_int32(tf.to_float(batch_size) / mean_length), 1) lengths = tf.random.truncated_no...
ffb1f4e3eb04e7223e32c5436bae3fe5478e74db
3,603,677
def bay_name_patch_data(name=data_utils.rand_name('bay')): """Generates random baymodel patch data :param name: name to replace in patch :returns: BayPatchCollection with generated data """ data = [{ "path": "/name", "value": name, "op": "replace" }] return baypatch...
eb30368a933e32bd0fa37223be9bdece2a6e4ab3
3,603,678
import json def generate_dataset_jtable(request, option): """ Generate the jtable data for rendering in the list template. :param request: The request for this jtable. :type request: :class:`django.http.HttpRequest` :param option: Action to take. :type option: str of either 'jtlist', 'jtdelete...
e2e5302f1c64970d6b0271da436dae65a9e29125
3,603,679
def make_field(obj_type): """Create a Field subclass out of some obj_type. This works for any obj_type that subclasses OODict or FieldsSequence. """ if issubclass(obj_type, OODict): class OODictField(ObjectField): """Field subtype that is stored as a dict in the backend and ...
3ae47d9c61c7b099afc24273fe7eaaf81451328b
3,603,680
import torch def get_dataloader_training(paths, training_params, batch_size, device=None, uuid=None, caching_mode=None): """ Args: paths (dict): I/O paths training_params (dict): conatains various training parameters batch_size (int) ...
175428e435ee1afd49f1f725014002406b58dd98
3,603,681
import shutil def hpc_batch_detect() -> str | None: """ Assuming a known job batching system, we will create a template for the user to verify and then the user will run. """ batcher = None if shutil.which("qsub"): batcher = "qsub" return batcher
99c3b6d7dc9fe332b7cf027d53ca172c1776890f
3,603,683
def HLRBRep_LineTool_IntervalContinuity(*args): """ :param C: :type C: gp_Lin :rtype: GeomAbs_Shape """ return _HLRBRep.HLRBRep_LineTool_IntervalContinuity(*args)
55ce7570c2a7ef1844e4c46f0866f6a3f381557f
3,603,685
def reproject_modis_wgs84(dataset, method = 2): """ A sample function to reproject and resample a GDAL dataset from within Python. The idea here is to reproject from one system to another, as well as to change the pixel size. The procedure is slightly long-winded, but goes like this: 1. Set up ...
cd7b8569204e154040c7426fafeef74a4031fca6
3,603,686
def etminan(C, Cpi, F2x=3.71): """Calculate the radiative forcing from CO2, CH4 and N2O. This function uses the updated formulas of Etminan et al. (2016), including the overlaps between CO2, methane and nitrous oxide. Reference: Etminan et al, 2016, JGR, doi: 10.1002/2016GL071930 Inputs: ...
e867ea6b5c715c6b1dbe6e4ac091c587798dedcb
3,603,688
def validate_and_normalize_address(address): """ Return normalized address if the address is a valid ip or hostname. Otherwise raise ValueError Exception. The hostname is normalized to all lower case. IPv6-addresses are converted to lowercase and fully expanded. RFC1123 2.1 Host Names and Nubme...
55f4baa68adff62831a6ae56e3ca734fb88c3b9e
3,603,689
import torch import io def create_torch_cnn(): """Create a torch CNN for testing purposes Jit traces the torch Module for storage in RedisAI """ n = Net() producer_forward_input = torch.ones(1, 1, 3, 3) # Trace a module (implicitly traces `forward`) and construct a # `ScriptModule` with ...
39651a028f00e10f0fa4e5f5ca6c9c7707f63e8f
3,603,691
def cradmin_create_archiveimage_tag(context, archiveimage, imagetype, css_class='', fallbackoptions=None): """ Creates an ``<img>`` tag from the given cradmin archiveimage. The URL is generated using :meth:`.cradmin_transform_image_using_imagetype`. The alt-tag is generated from ``archiveimage.scr...
868c8aa0070977f98d03f5afbfa127655c913fde
3,603,693
def extract_key(msk: MasterSecretKey, identity: bytes) -> SecretKey: """Extract secret key for an identity. Key extraction is done by first mapping the identity into G_1 using H_1 and then raising this group element to the secret exponent α, i.e, H_1(identity)^α. """ return SecretKey(map_identity(...
837a09cb0602634fd6f111141a6c1eb680df6b6d
3,603,694
from typing import List def is_cmd_path_installed() -> bool: """Detects if the path is already installed.""" all_paths: List[str] = win32_path_manip.read_user_path() return BIN_DIR in all_paths
cfcd288e650face161fcedc63545dbdd5c692f6f
3,603,695
def getDefaultFetcher(): """Return the default fetcher instance if no fetcher has been set, it will create a default fetcher. @return: the default fetcher @rtype: HTTPFetcher """ global _default_fetcher if _default_fetcher is None: setDefaultFetcher(createHTTPFetcher()) return...
03ad0606294103336e1653f499e041f560f63f7b
3,603,696
def get_choices_from(raw_type_annotation: RawTypeAnnotation) -> Choices: """ Helper function to extract allowed values from a literal/enum like type. Use case: Forward as `choices=...` argument to argparse. """ type_annotation = TypeAnnotation(raw_type_annotation) while type_annotation.get_und...
3c088ed8908314e47bfc1273262beb7ccf47dd00
3,603,697
def residuals(p, y, x): """Residual for calculating rate coefficient.""" A, b, E = p err = y - calc_rate_coeff(p, x) return err
35436c6a2b903cc1b5dc899ee1119f15307debbd
3,603,698
import enum def dictToMongoStorable(data, logger=None, verbose=True, dollarEscape="__mongostorabledollar__", normalizeKeys=True, normalizeEnums=True, normalizeBigInts=True, convertTuples=True, convertSets=True): """ This function convert all set() in list() and all "." in keys will be replaced by ...
48b5aebd94940316bab2867fc5e7b58abea95ec6
3,603,699
def scrollableChild(x,y,l,e = None): """ Finds a child of l that is scrollable. Useful when there is a scrollable element in another scrollable element """ if e is None: e = getXmlElement(l) if e is None: # Unexpected scroll... return None else: bounds = B...
ad89c96063448b36b2c1acd5445af2e359eac7d0
3,603,700
def extract_lod_cmd(lod): """ Extract only one LoD for a dataset. To use on datasets having more than one LoD for the city objects. For each city object, it keeps only the LoD passed as parameter, if a city object doesn't have this LoD then it is deleted. """ def processor(cm): utils...
9099e534652e96785a6169b40b5ec350b0961eaf
3,603,701
import math def line_intersect(pt1, pt2, ptA, ptB): """ Taken from https://www.cs.hmc.edu/ACM/lectures/intersections.html this returns the intersection of Line(pt1,pt2) and Line(ptA,ptB) returns a tuple: (xi, yi, valid, r, s), where (xi, yi) is the intersection r is the scalar multiple such ...
73ffd9674302f3be7b0edd9cdddd95df198919cb
3,603,702
import html def dash_higher_derivatives_problem( solver: HigherDerivativesSolver, render_latex_url: str = r"https://render.githubusercontent.com/render/math?math", ): """ Helper function to print higher derivatives problem. """ assert isinstance( solver, HigherDerivativesSolver ),...
6dadc04b8682a597d5ab0fb5e28c5c10562c0d5b
3,603,703
def find_last_index(doc): """ Returns: int The last cursor index (loc) of the template document. """ body = extract_body(document=doc) contents = body["content"] last_index = contents[-1]["endIndex"] return last_index - 1
1e0e9412d21c2f5ae1541ba698ec6e1e36eb1205
3,603,704
def getLeftWheelCost(robotState, leftTorque): """ :type robotState: numpy.ndarray """ v = robotState[3] omega = robotState[4] return abs(leftTorque * ((v + (b*omega)) / r))
316c4ac1288c11453a9d5c159185dd0398b1c0bd
3,603,705
def ihfft(a, n=None, axis=-1, norm=None): """Computes the inverse FFT of a signal that has Hermitian symmetry. Parameters ---------- a : array_like Input array. n : int, optional Length of the inverse FFT, the number of points along transformation axis in the input to use. I...
3378b51b35e536ca3c523f51fbd29fefee201686
3,603,706
from geonode.contrib.exif.utils import exif_extract_dict def document_detail(request, docid): """ The view that show details of each document """ document = None try: document = _resolve_document( request, docid, 'base.view_resourcebase', _PE...
dbd14a7773758d5d913d74abaaaca614250cef50
3,603,707
def get_rel_path_translations_csv(lang=None): """Return the path to the file containing the extra phrases.""" return get_rel_path_phrases(dir_name=_DIR_PHRASES_CSV, lang=lang)
5f0369bfde4fdbc6e22e8b43f8d9cf064d9f58ba
3,603,708
def qubitoperator_to_pauli_sum(qubit_op: QubitOperator) -> cirq.PauliSum: """ Convert QubitOperator to PauliSum object. Args: qubit_op (QubitOperator): operator to convert. Returns: pauli_sum (PauliSum): cirq PauliSum object. Raises: TypeError: if qubit_op is not a QubitOp...
19076f09a5d04ea37379a7627e915678dd3c3bda
3,603,709
def de_sort(vals, inds): """ De-sort an array of values vals that were sorted according to the indices inds. Args: vals (ndarray): a 1-D array to de-sort. inds (ndarray of int): the sorting indices. Returns: ndarray: the de-sorted array. """ # Create the de-sorted structu...
4f79e82a9ddaf0f727bdb183eda56201ea3cb2ec
3,603,710
def render_icon(icon): """ Render a Bootstrap glyphicon icon """ return '<span class="glyphicon glyphicon-{icon}"></span>'.format(icon=icon)
4fcc501cbea07d3dbe99f35f63dc39c8f629c4c4
3,603,711
import types def task__package_mkdir_deb_iso_root() -> types.TaskDict: """Create the Debian packages root directory on the ISO.""" return targets.Mkdir( directory=constants.REPO_DEB_ROOT, task_dep=['_package_mkdir_iso_root'] ).task
55eddf3fc3f24b5e016d66064e6c9f90cea1e318
3,603,712
def _add_bias_category(row): """A function to add the bias category based on the bias motivation. To be used with pandas.DataFrame.apply(). """ row['BIAS_CATEGORY'] = _BIAS_CATEGORY_MAP.get(row['BIAS_DESC'], 'MultipleBias') return row
c5d680243aee53eee06882ddd997a8d08e92027a
3,603,714
def new_trident(game_state): """ A composite component representing a Sword item. """ c = Composite() set_item_components(c, game_state) set_melee_weapon_component(c) c.set_child(Description("Trident", "A long stick with a with three sharp points at one end." ...
925e40882876def4dda52cab2d5407d0fbcece4b
3,603,715
import binascii def hex_to_bytes(hex_repn: str) -> bytes: """ Convert a hexidecimal string representation of a block of bytes into a Pyton bytes object. This function is the inverse of bytes_to_hex. hex_to_bytes('F803') -> b'\xf8\x03' """ return binascii.unhexlify(hex_repn)
2c456a353e1cce75998d1b2dd9b077af962ee41d
3,603,717
import re def get_text_url_base(content): """Return base URL to full text based on the content of the landing page. Parameters ---------- content : str The content of the landing page for an rxiv paper. Returns ------- str or None The base URL if available, otherwise None...
c679e9e1e8b074f7fea3aaf9eb256542e20a4d7d
3,603,718
def calculateMatchValue(incompleteObject, knownObject): """Calculate an integer match value, scoring +1 for each match""" matchvalue = 0 for catkey, catval in incompleteObject.items(): if knownObject[catkey] == catval: matchvalue += 1 return matchvalue
bd0efa089fa9edc2e290a46ca7e18b3d22bd1594
3,603,719
def LCS1(a, b, i, j): """ LCS recursion """ if i >= len(a) or j >= len(b): return 0 elif a[i] == b[j]: return 1 + LCS1(a, b, i+1, j+1) else: return max(LCS1(a, b, i+1, j), LCS1(a, b, i, j+1))
0b1819ee67dd6fc60e66b8c2b83f79c062a149db
3,603,720
def HRNR(noisy_stft, TSNR_spectrum, TSNR_gains, noise_estimation, NL="max"): """ Reconstructs the signal by re-adding phase components to the magnitude estimate :param noisy_stft: stft of original noisy signal :param TSNR_spectrum: clean stft returned by TSNR :param TSNR_gains: gains of each stft fr...
e6256dc3b03824de194548c3803bbbfc56c3311b
3,603,721
def range_factory(policy, sym): """Factory function for creating MLS range objects.""" if not enabled(policy): raise exception.MLSDisabled if isinstance(sym, Range): assert sym.policy == policy return sym elif isinstance(sym, qpol.qpol_mls_range_t): return Range(policy,...
e8efe9592a5d4a5caa46c929053f8450ec657436
3,603,723
def get_contents_dir(node): """Return content signatures and names of all our children separated by new-lines. Ensure that the nodes are sorted.""" contents = [] for n in sorted(node.children(), key=lambda t: t.name): contents.append('%s %s\n' % (n.get_csig(), n.name)) return ''.join(content...
147d26ae5fca9540a081feef495dfa4bb0fca8eb
3,603,724