content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def piece_together_fourth(Dp, Wp): """ Take the skew and symmetric parts of a algorithmic tangent and piece them back together """ sym_id = 0.5*(np.einsum('ik,jl', np.eye(3), np.eye(3)) + np.einsum('jk,il', np.eye(3), np.eye(3))) skew_id = 0.5*(np.einsum('ik,jl', np.eye(3), np.eye(3)) - np.einsum('jk,il', n...
fc386d688f0e571b3b184621885be100b5cd2306
3,625,005
def to_ragged_seq_set(data): """Convert dataset from mapping/array of sequences to lists of mappings of sequences.""" # data is a dict if is_mapping(data): new_data = {} for name, datum in data.items(): if not is_sequence_set(datum): # all sequences must at le...
5b8cce9846d861c564a23a77fe8a7ae03e3cdf8a
3,625,006
def get_atoms_list(mmtf_dict): """Creates a list of atom dictionaries from a .mmtf dictionary by zipping together some of its fields. :param dict mmtf_dict: the .mmtf dictionary to read. :rtype: ``list``""" return [{ "x": x, "y": y, "z": z, "alt_loc": a or None, "bvalue": b, "occupancy": o, ...
3b5f29362c077585ebc659b8d8a9ff5d60908ead
3,625,007
import traceback def register_augmentation(name): """Registers an augmentation. This decorator allows vertview to instantiate an augmentation from a configuration file. To use it, apply this decorator to an AugmentationBase2D subclass, like this: .. code-block:: python @register_augmentation(...
601ea1df05997ba46687d4e8e828be1254c3b29d
3,625,008
def get_os_fingerprint(data): """ Get the most accurate OS fingerprint for the given Data object, if any. :param data: Data object to query. :type data: Data :returns: Most accurate OS fingerprint. If no fingerprint is found, returns None. :rtype: OSFingerprint | None """ # Ge...
baca5b40cff177d8534f68d2334698852937caf2
3,625,009
def ring(symbols, domain, order=lex): """Construct a polynomial ring returning ``(ring, x_1, ..., x_n)``. Parameters ========== symbols : str, Symbol/Expr or sequence of str, Symbol/Expr (non-empty) domain : :class:`~diofant.domains.domain.Domain` or coercible order : :class:`~diofant.polys.po...
d26eaf26d2b4c87c5b6e70d87dbf0b4bae80aace
3,625,010
def trimesh_swap_edge(mesh, u, v, allow_boundary=True): """Replace an edge of the mesh by an edge connecting the opposite vertices of the adjacent faces. Parameters ---------- mesh : :class:`compas.datastructures.Mesh` Instance of mesh. u : int The key of one of the vertices of ...
43f150bb52b1f4a9180f6c40a9d420fbe5e67e30
3,625,011
def perc_col_nans(col): """ Returns the percent of NaNs of a specific column in the dataset. Parameters: col (pandas Series): Column in the dataset Returns: col_perc_nans (float): Percent of NaNs in col """ col_perc_nans = count_col_nans(col) / len(col) return...
66db913b1299a280e867ff05bd8e438c25c03861
3,625,012
def get_string(key): """ Get localized string. First, try language as set in config. Then, try English locale. Else - raise an exception. :param key: string name :return: localized string """ lang = strings.get(Config.BOT_LANGUAGE) if not lang: if not strings.get("en"): ...
90089fbe8bbbdfc0f1aa6560197489cbfb76f41a
3,625,014
def prompt_vial_range(): """Prompt user for first and last vial of run""" first_ic_vial = int(input('First IC vial? ')) last_ic_vial = int(input('Last IC vial? ')) return first_ic_vial, last_ic_vial
bf5cf536c0aae3808bf16dd6d87a9d83bfbdab04
3,625,015
from collections import defaultdict def getFollowupPhotometry(candidate, djangoRawObject = None, conn = None): """Use the query followupPhotometryQuery but organise the data for plotting""" # We need to create a dictionary of filters which contain arrays of the data. # It's messy to do this from scratch,...
d4f496360cdfde82f4dc81bb199374606929137f
3,625,017
def generate_random_map( size=6, p=0.7, num_pseudo_rewards=0, only_optimal_pseudo_rewards=True ): """Generates a random valid map (one that has a path from start to goal) :param size: size of each side of the grid :param p: probability that a tile is empty :param num_pseudo_rewards: number of tiles ...
b50ce1575e0b8715b0ac4f271f3cf741e8a22b6f
3,625,018
def approx_count_distinct(col, rsd=None): """Returns a new :class:`Column` for approximate distinct count of ``col``. >>> df.agg(approx_count_distinct(df.age).alias('c')).collect() [Row(c=2)] """ sc = SparkContext._active_spark_context if rsd is None: jc = sc._jvm.functions.approx_count...
7e7736db6c1ecf7d7b2476fd13f5698498aa3cff
3,625,019
def private_mean(x, epsilon, sum_sensitivity): """ Computes a private mean with privacy budget epsilon using the given sensitivity. :param x: Vector over which the mean will be computed. :param epsilon: The privacy budget. :param sum_sensitivity: The sensitivity of the sum calculation. :ret...
3b400c17e1fa9b899d1b322291459724cd6cece8
3,625,021
from vtk import vtkImageData def make_child_dataset(dataobject): """Creates a child dataset with the same size as the reference_dataset. """ new_child = vtkImageData() new_child.CopyStructure(dataobject) input_spacing = dataobject.GetSpacing() # For a reconstruction we copy the X spacing from ...
a7e460f21564559f4731df76c978eac3a951dbe7
3,625,022
def calc_residuals(Amat,Bvec,coeffs,perconf=False): """Calculate residuals and other performance metrics""" residuals = [] matmul = Bvec - Amat*coeffs residuals = matmul*627.51 r2 = 1-sum(residuals**2)/sum((Bvec*627.51)**2) rel_MAE = sum(abs(residuals))/sum(abs(Bvec*627.51)) if perconf: ...
fbeb72688f4e58dcca85b425be2ef0460a3cfcac
3,625,023
def bucket_by_sequence_length(data_reader, example_length_fn, bucket_boundaries, bucket_batch_sizes, trainer_nums, trainer_id): """Bucket entries in dataset by lengt...
4adfe4f0780b4e97934b6715ab9227e3647a2592
3,625,024
from typing import Any from typing import Dict def get_overridable_parameters(config: Any) -> Dict[str, param.Parameter]: """ Get properties that are not constant, readonly or private (eg: prefixed with an underscore). :param config: The model configuration :return: A dictionary of parameter names an...
9dbe89416d4dd0f232f3f714fc652bcb18ec80cc
3,625,025
def compute_score(sent, sents): """Computes the average score of sent vs the other sentences (the result of sent vs itself isn't counted because it's 1, and that's above UPPER_BOUND)""" if not len(sent): return 0 return sum(compare_sents_bounded(sent, sent1) for sent1 in sents) / float( ...
ba3e0a16551daba922e87de6698f8e95494b01cd
3,625,026
def computeCentroids(X, idx, K): """ returns the new centroids by computing the means of the data points assigned to each centroid. It is given a dataset X where each row is a single data point, a vector idx of centroid assignments (i.e. each entry in range [1..K]) for each example, and K, the n...
d21a5acd3ba481a9864a016dcfe79b629147f788
3,625,027
def async_track_time_interval_backoff(hass, action, intervals) -> CALLBACK_TYPE: """Add a listener that fires repetitively at every timedelta interval.""" if not iscoroutinefunction: _LOGGER.error("Action needs to be a coroutine and return True/False") return if not isinstance(intervals, (l...
be7d3619b9ddc8336251fb50196a74ab9f58c36b
3,625,028
import shlex def grr_grep(line): """Greps for a given content of a specified file. Args: line: A string representing arguments passed to the magic command. Returns: A list of buffer references to the matched content. Raises: NoClientSelectedError: Client is not selected to perform this operatio...
28c771f12d162e667009241cdba2f2e485736599
3,625,029
def convertMCFOSTdataToJy(data, wavelength, spatialUnit = 'arcsec', spatialResolution = None): """Convert data in MCFOST units into Jansky/pixel or Jansky/arcsec^2: Input: data: 2D array, MCFOST-generated data. wavelength: float, wavelength of the data to be converted in micron. spatial...
20e493989513e4e08e9211f7a6f7d606817aaa44
3,625,030
def defaults(dict=None): """ Adds a set of default values to the settings registry. These can and will be updated by any settings modules in effect, such as the Settings Manager. If dict is None, it'll return the current defaults. """ if dict: _defaults.update(dict) else: re...
8b7423d0fdbbd522a01e04cd77e6aca863951e9a
3,625,031
def send_email(email_subject, recipient, message, config = None): """Send an email using SendGrid.""" try: config = current_app.config except: config = config sender = sendgrid.SendGridClient(config['SENDGRID_API_KEY']) email = sendgrid.Mail() email.set_subject(email_subjec...
18c20e086ddacc719898f2ad3e3a03f5c560d0fb
3,625,033
import wsgiref def simulate_request(app, method='GET', path='/', query_string=None, headers=None, content_type=None, body=None, json=None, file_wrapper=None, wsgierrors=None, params=None, params_csv=False, protocol='http', host=helpers.DEFAULT_HOST, ...
15950c9b880ac791454bd64becf176aec0ab4d99
3,625,035
def rcnn_encode(bboxes, targets): """ :param bboxes: (N, 4) bounding boxes of [x0, y0, x1, y1] :param targets: (N, 4) target ground truth boxes of [x0, y0, x1, y1] :return: deltas """ bw = bboxes[:, 2] - bboxes[:, 0] + 1.0 bh = bboxes[:, 3] - bboxes[:, 1] + 1.0 bx = bboxes[:, 0] + 0.5 *...
919395705dd20e6872fac21ab8abf52a04ff8167
3,625,036
def mera_ansatz_parameters(num_qubits, depth, value): """Returns a Parameters object for the MERA Tensor network ansatz. Args: num_qubits : int Number of qubits in the parameterized circuit. depth : int [must equal log2(num_qubits)] Number of "hyperlayers" in MERA netwo...
8e491189527a95686c99a10da1527ec321c48036
3,625,039
def gaussianfilter(N, alpha, Ts, Fs): """ Generates a gaussian filter (FIR) impulse response. Parameters ---------- N : int Length of the filter in samples. alpha: float Roll off factor (Valid values are [0, 1]). Ts : float Symbol period in seconds. ...
8f3ce2f3aa155dcf3163f6a252b98aa506137013
3,625,040
def minimal_copy(ds: Dataset) -> Dataset: """Make reduced copy with only the attributes needed for a QueryResult""" res = Dataset() for attr in chain.from_iterable(chain(req_elems.values(), opt_elems.values())): val = getattr(ds, attr, None) if val is not None: setattr(res, attr,...
f0df04aa6e1a5447b7e6caf0a489cc89a7de9423
3,625,041
import numpy as np import io import torch def read_txt_embeddings(logger, path): """ Reload pretrained embeddings from a text file. """ word2id = {} vectors = [] # load pretrained embeddings # _emb_dim_file = params.emb_dim _emb_dim_file = 0 with io.open(path, 'r', encoding='utf-8', newline='\n', e...
1d7cc0845488bb3bd37eef4ca0cdeff67787f6e8
3,625,042
def corrected_chance(clustering1, clustering2, measure='jaccard_index', random_model='perm', norm_type='sum', n_samples=100): """ This function calculates the adjusted Similarity for one of six random models. .. note:: Clustering 2 is considered the gold-standard clustering for one...
86505ed8eeb38decb551fa77cbec00b8ba9d16f1
3,625,043
def update_account(): """Update account settings.""" form = AccountSettingsForm(request.form) if form.validate(): if 'user_id' not in request.form: return jsonify({'success': False, 'error': 'ID not found in edit!'}) edit_id = paranoid_clean(request.fo...
247d60dbf333f7ed162b091c485e9bffe8418062
3,625,044
def make_weighted_loss(loss_fn, weight=1.0): """ Adapts the given loss function by multiplying by a given constant. Parameters ---------- loss_fn: a function to create the loss weight: the value by which to weigh the loss. Returns ------- fn: The adapted loss """ def fn(*args, ...
bfe235e012cc134b98b5d995935327b11bba8651
3,625,045
def create_differences_matrix(rows, cols): """ Creates the central differences matrix A for an n by m shaped grid """ n = rows*cols M = np.zeros((n,n)) for r in range(rows): for c in range(cols): i = r*cols + c # Two inner diagonals if c > 0: M[i-1,i] ...
ea199ed8fb3f33e4e059d5748d347a46dc78d7d7
3,625,046
def isvalid_corr(corrmat): """ Check if 1. corrmat is symmetric 2. off-diagonal values in [-1, 1] 3. diagonal values = 1 4. the matrix is positive semidefinite. @param corrmat: numpy nxn ndarray @return: CorrDiagnostics object ---> evaluates to True if corrmat is valid and False otherwi...
6f2509daaf9901d3b35841bda08dd062d2b1caa1
3,625,047
def multi_JMI(X, y, is_disc, cost_vec, cost_param_vec, num_features_to_select = None, random_seed = 123, num_cores = 1): """ Cost-based JMI feature ranking with multiple penalization parameters. Function to obtain the rankings associated to different cost parameters, with the filter featu...
8e0f641d89b07548fde555225ff9c2dad094e484
3,625,048
def arcsin(x): """ Compute the inverse sine of x. Return the "principal value" (for a description of this, see `numpy.arcsin`) of the inverse sine of `x`. For real `x` such that `abs(x) <= 1`, this is a real number in the closed interval :math:`[-\\pi/2, \\pi/2]`. Otherwise, the complex princi...
6692bb51b5347ab77d2d12969a8fc98ccc43ac62
3,625,049
def run_queued(fn, params, processes=1, queued_params=None, logging_level=None): """ Same as run_function, but the function should be such that it accepts a parameter queue and reads its inputs from there; params still contains options for the function. If logging_level is not None, a QueueHandler ...
bef4ae414bbe8787ef6c606c5391a49832aa0e90
3,625,050
import signal def ExtractFrequencyTime(data, bands): """Computes the spectrogram of data, and the takes the sum of frequencies inside the band range. """ bands_results = {'all_spec':[], 'alpha':[], 'beta1':[], 'beta2':[], 'beta3':[]} f, t, Sxx = signal.spectrogram(data,window = 'hamming', fs = 500,n...
1ebf9e9a39d34d6a1657c6a2c440996e1ba88302
3,625,051
from typing import Any from typing import List def ensure_list(data: Any) -> List: """Ensure input is a list. Parameters ---------- data: object Returns ------- list """ if data is None: return [] if not isinstance(data, (list, tuple)): return [data] ret...
58016feaf49d63255944fa615e7e2e1dac6dcc76
3,625,052
def decode_logistic_mixture( targets, means, log_scales, logit_probs_softmax, # CDF input_string): """ NOTE: This function uses either the CUDA or CPU backend, depending on the device of the input tensors. NOTE: targets, means, log_scales, logit_probs_softmax must all be on the same device ...
66ad78e22a538c788729bdbd1bb6a74a88d24be3
3,625,053
def _match_up_provided_args_with_field_defs(field_defs, args, kwargs): """ Returns a list of provided values, aligned with the field definitions. Missing values are represented using the NVP (No Value Provided) token (as None can be a valid provided value). """ values = [NVP] * len(field_defs) ...
440b218e3bde552a10890304278ef9604d8f988b
3,625,054
def var_recode(TEDS_A_Imputed, user_target, TEDS_Af): """Recodes categorical variables present in the data. Returns A recoded data frame.""" # Identify the variable types col_list = list(TEDS_A_Imputed.columns) col_list_cat = [s for s in col_list if s != 'CASEID' and s != 'ADMY...
cc656e9a6840af4d95a6a114073459d815c533dc
3,625,055
def get_cannonical(group): """ For each variant, that is unique combination of #CHROM, POS, REF, ALT, it keeps CANONICAL transcript annotations. If more than consequence type is annotated, it keeps the most damaging or severe either if there is more than one entry (row) per variant or either is coma-sep...
31417a30fbfb7800dfdd46352ea9f9e5763be3e3
3,625,056
def get(blob_key): """Gets a `BlobInfo` record from blobstore. Does the same as `BlobInfo.get`. Args: blob_key: The `BlobKey` of the record you want to retrieve. Returns: A `BlobInfo` instance that is associated with the provided key or a list of `BlobInfo` instances if a list of keys was pro...
03c3fe9da40c2986ccce19b62e99c07abe49cbd0
3,625,057
def init_split(df, featname, init_bins=100): """ 对df下的featname特征进行分割, 最后返回中间的分割点刻度 为了保证所有值都有对应的区间, 取两个值之间的中值作为分割刻度 注意这里的分割方式不是等频等常用的方法, 仅仅是简单地找出分割点再进行融合最终进行分割 注意, 分出的箱刻度与是否闭区间无关, 这个点取决于用户,这个函数仅考虑分箱的个数 同时, 分箱多余的部分会进入最后一个箱, 如101个分100箱, 则最后一个箱有两个样本 Parameters: ---------- df: dataframe,...
172f48bb019fd4cf4941b2ff0fefcb24709fe7a4
3,625,059
def dist_of_entity_k(adjacency_dict: dict, levels_dict: dict, c_k: dict, c_notk: dict) -> int: """ Performs the final iterations of the algorithm proposed in the Alternative Geographic Spine document to find the "off spine entity distance" (OSED), which is the number of geounits that must be added or subtra...
787466d3de923fa495d93794823c6b0d51c22f5b
3,625,061
import tkinter def repr_content_and_tags(text_widget: tkinter.Text) -> str: """Represent the content, indices and the tag starts and ends as a text table.""" tbl = prettytable.PrettyTable() tbl.field_names = ["Index", "Char", "Tag starts", "Tag ends"] for index, character, tag_starts, tag_ends in en...
534c1642d77f0229322a1065b237c65e6b0ccf5c
3,625,062
def isotropic_twirl_state(X, d): """ Applies the twirling channel X -> ∫ (U ⊗ conj(U))*X*(U ⊗ conj(U)).H dU to the input operator X acting on two d-dimensional systems. For d=2, this is equivalent to X -> (1/24)*sum_i (c_i ⊗ conj(c_i))*X*(c_i ⊗ conj(c_i)).H where the unitaries c...
5ff32bb3b4c6b2671e9acb8d7963683bcc3c3261
3,625,064
from functools import reduce def flatten_index(builder, index, const_shape): """Converts N-dimensional index into 1-dimensional one. index is of a form ``(i0, i1, ... iN)``, where *i* is ValueRefs holding individual dimension indices. First dimension is considered to be variable. Given array shape ...
2864701c5e3d0263d82fd585ad9d77c7c584ea2b
3,625,065
def init_conds(MdiscI, P): """ Function to convert a disc mass from solar masses to grams and an initial spin period in milliseconds into an angular frequency. :param MdiscI: disc mass - solar masses :param P: initial spin period - milliseconds :return: an array containing the disc mass in grams and th...
612411a3fad7f41309858f20e9aefad16904e16e
3,625,066
from bs4 import BeautifulSoup def fetch_feed() -> list[RenjiData]: """ Get news feed from renji.com """ logger.info("Start fetching info from renji.com ...") res = urlopen("https://www.renji.com/default.php?mod=article&fid=38") logger.info("Info fetched. Parsing ...") soup = BeautifulSoup(...
14cc274b17de03266626166592ae65e88bd54286
3,625,067
from typing import Optional def get_me_ssh_key(key_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetMeSSHKeyResult: """ Use this data source to retrieve information about an SSH key. ## Example Usage ```python import pulumi import pul...
fe957f701869608e818092e22f08dcb0e6d8b27d
3,625,068
import numpy def gower_distance_numpy(point1, point2, max_range): """! @brief Calculate Gower distance between two vectors using numpy. @param[in] point1 (array_like): The first vector. @param[in] point2 (array_like): The second vector. @param[in] max_range (array_like): Max range in each data di...
b97c40cd62654172b0d502e35bbef8ce9e9175c5
3,625,069
def is_fix_only_distro(distro_name: str) -> bool: """ Does the given distro's security feed/db support vulnerability records before a fix is available? :param distro_name: :return: bool """ return distro_name in FIX_ONLY_DISTROS
35eaf42b7111a3ddcec11dd351a7d00378607f86
3,625,070
def step_f(z: np.ndarray, scale: float, loc: float) -> np.ndarray: """ :param z: z-dimension :param scale: width of step function, always 0 :param loc: position of step :return: positioned step function """ new_z = z - loc f = np.ones_like(new_z) * 0.5 f[new_z <= -scale] = 0 ...
f94d0f18aa0805f6e0739927f88517c9e70a802a
3,625,071
def build_SVM(X_train, y_train, kernel_): """ The function builds SVM """ scaler = StandardScaler() X_train_std = scaler.fit_transform(X_train) """ for i in range(1, 5): svc = SVC(kernel=kernel_, random_state=0, gamma=i) model = svc.fit(X_train_std, y_train.values.ravel()) ...
a3ced31185a224b79366d44e3b2ce02f334f7ed6
3,625,072
def status(args: tuple[str]) -> list[res.Response]: """Batch `git status` command.""" return _call_git_use_case("status", args)
855160c530f606535956b5decf766b32abdbeb4d
3,625,073
def get_worker(project, object_id=None, global_id=None, user_id=None): """ Gets the identified worker. Exactly one form of identification should be provided. :param project: :param object_id: The worker's OBJECTID. :param global_id: The worker's GlobalID. :param user_id: The worker'...
bff455591f48c7a45f387364c13b1d6e70c5196d
3,625,074
import xml import re def xml_to_string(elem, pretty=False): """ Returns a string from an xml tree. """ try: if elem is not None: if PY2: xml_str = ElementTree.tostring(elem, encoding='utf-8') else: xml_str = ElementTree.tostring(elem, enc...
55d385a55d8cc998470b19286460267d24ddd26a
3,625,075
from typing import Type from typing import Optional from typing import List def build_config( config_file: str, task_cls: Type[GeneralizedRCNNTask], opts: Optional[List[str]] = None, ) -> CfgNode: """Build config node from config file Args: config_file: Path to a D2go config file o...
5387bf56461c3ad1c71bf25592abd5c77ab4b43c
3,625,076
def get_learner(config_args, train_loader, val_loader, test_loader, start_epoch, device): """ Return a new instance of model """ # Available models learners_factory = { "default": DefaultLearner, "selfconfid": SelfConfidLearner, "oodconfid": OODConfidLearner, } ...
71e566ac47f78598d9ea3e9a79bb0f3c5f9e0276
3,625,079
def localHomologyMultiproc( k, cplx, numProcs, localSimplices=None, iterate=True, rankOnly=False ): """Compute local homology relative to the star over a list of simplices in parallel""" if localSimplices is None: localSimplices = [] for ki in range(k + 1): localSimplices += ksi...
de3998fc755b8c002e960bf0cfd5b28ec9150426
3,625,080
def text_repr(diffs): """ Helper function to dump xml elements into plain string form for the sake of comparison. It also get rid of all attributes in xml elements if any. """ return {change_type:[etree.tostring(elem.attrib.clear() or elem).decode('utf-8') for elem in elems] for change_t...
9e9e2b6b4fff642bb82278642b9c6ea02d0519b3
3,625,081
import json def search_nlucell(): """Search NluCell 搜索问答节点 Get:返回所有问答节点 POST:返回所有包含搜索关键词的问答节点 """ data = { 'skb': database.skb, 'result': [] } state = { 'success' : 0, 'message' : "请先选择知识库再搜索节点" } if not database.skb: return json.dumps(state)...
7a398ce5dddf9e6f2f5fe82b475eef7eba32b2cb
3,625,083
def generate_gate_swap_mat() -> np.ndarray: """Return the Hilbert-Schmidt representation matrix for a SWAP gate with respect to the orthonormal Hermitian matrix basis with the normalized identity matrix as the 0th element. The result is a 16 times 16 real matrix. Parameters ---------- Returns ...
df86f8ef3c2e4321695a87822a063ebee5c4f27c
3,625,084
def can_register(extra, password_meta): """ :param extra: {str: any?}, additional fields that the user will fill out when registering such as gender and birth. :param password_meta: {'count': int, 'count_number': int, 'count_uppercase': int, 'count_lowercase': int, 'count_special'...
a6ba8cc6fc4a4180bbbceb9a8ae14b07d7dad809
3,625,086
def cross_entropy(output, target): """Calculate Cross-entropy loss.""" return F.cross_entropy(input=output, target=target)
e836dd4d0dbae597932aa3265a92776b7a032ccb
3,625,087
def plate_to_genesift_sequencing_order_spreadsheet(plate, output_file, sample_name_function, well_filter=None, direction='row'): """Generate an excel spreadsheet f...
bd317bd535bfa1e465ee0e0df6a020d299e83789
3,625,088
def hours_of_daylight(date, axis=23.44, latitude=39.87): """Compute the hours of daylight for the given date""" #date = datetime.strptime(start_time, "%Y-%m-%d") diff = date - pd.datetime(2000, 12, 21) day = diff.total_seconds() / 24. / 3600 day %= 365.25 m = 1. - np.tan(np.radians(latitude...
390cd02b805686a824b8e1bfa8641d1adeb01e9d
3,625,089
def reject(p, xs): """The complement of filter. Acts as a transducer if a transformer is given in list position. Filterable objects include plain objects or any object that has a filter method such as Array""" return filter(complement(p), xs)
a2556ab9d4514dfb18a513938960211473a508a9
3,625,090
from typing import OrderedDict def filter_excluded_fields(fields, Meta, exclude_dump_only): """Filter fields that should be ignored in the OpenAPI spec :param dict fields: A dictionary of of fields name field object pairs :param Meta: the schema's Meta class :param bool exclude_dump_only: whether to ...
a39a7665052cde0ba9f694696a57f2b1f6ca0603
3,625,092
def parse_xmpp_addresses(text): """.""" xmpp_addresses = ioc_grammars.xmpp_address.searchString(text) return _listify(xmpp_addresses)
36e5567e43bf48674787130a10bc77a69d9dcd54
3,625,093
def login_user(): """ This route handles user login """ user_info = request.get_json() user_instance = UserModel.query.filter_by(email=user_info["email"]).first() if not user_instance: return { "message": "Your email or password is not correct", "status": "failed", ...
de93dc48865c75ae96a43f7cc9534ac64aba443e
3,625,094
from typing import Any def test_email( email_to: EmailStr, current_user: models.User = Depends(deps.get_current_active_superuser), ) -> Any: """ Test emails. """ send_test_email(email_to=email_to) return {"msg": f"Test email sent to {email_to}"}
13e7bcb0e96ae11c910619f4a4f161738c10ac6f
3,625,095
def euclidean_distance(vects): """Compute Euclidean Distance between two vectors. Euclidean distance is defined as the length of a line segment between the two points. d(p,q) = √ [Σ(qi – pi)^2] Args: vects : vectors Returns: euclidean distance between vects. """ x, y ...
f48eac6ff7adaefee700fe48f60cd614655ac704
3,625,096
def process_typedef(line): """处理类型定义""" content = line.split(' ') type_ = type_dict[content[1]] keyword = content[2] if '[' in keyword: i = keyword.index('[') keyword = keyword[:i] else: keyword = keyword.replace('\n', '') # 删除行末分号 keyword = keyword.replace('\r'...
e36f0f6298e2cdf7edc1d843c3fbaae7aa428a97
3,625,097
def findNearestNeighbourPixel(img, seg, i, j, segSize, fourConnected): """ For the (i, j) pixel, choose which of the neighbouring pixels is the most similar, spectrally. Returns tuple (ii, jj) of the row and column of the most spectrally similar neighbour, which is also in a clump of size...
e205652d7b39c922a203162f3cdc58672347b938
3,625,098
import json def _load_json_as_list(path: str) -> list: """Load json file and convert it into list. :param path: path to json file :type path: str :return: dict :rtype: dict """ with open(path, "r") as json_data: data = json.load(json_data) if isinstance(data, list): re...
d7aa301a830a826937522dc9c737bf84bf6f4f9a
3,625,099
def flavor_create(context, values, projects=None): """Create a new instance type. In order to pass in extra specs, the values dict should contain a 'extra_specs' key/value pair: {'extra_specs' : {'k1': 'v1', 'k2': 'v2', ...}} """ specs = values.get('extra_specs') specs_refs = [] if specs: ...
0250bd710c182a99dd270c535b90688062db5734
3,625,100
from typing import Any def dictlike(var: Any) -> Boolean: """ Determine whether or not var is dict-like (Can contain dict-like items). :param var: Any variable to check :return: Boolean """ try: var.items() return True except (TypeError, AttributeError): return False
5e2a16c4f76112892556de840d4ff8821f98aedd
3,625,101
def plot_vehicle_tri(ax, coords, yaw, color=(0, 0, 1, 0.5), zorder=None): """Plot a marker representing a vehicle (either ground truth or estimate)""" vertices = [ [0, 0], [0.77, -0.5], [0, 0.5], [-0.77, -0.5] ] tri = patches.Polygon( vertices, closed=True, fa...
5adc6da320972630aa4277ca49525cc615568464
3,625,102
def PatchDword(ea, value): """ Change value of a double word @param ea: linear address @param value: new value of the double word @return: 1 if successful, 0 if not """ return idaapi.patch_long(ea, value)
4ed7fee3fae16d0026f616bd725db60341652f77
3,625,103
import re def _addquotes(vistr: str) -> str: """Add quotes to '=attribute' attributes""" vistr = re.subn(r'=(?!")(.*?)([\s>])', _quote, vistr)[0] return vistr
63ebe29ef8d78450fc8592646f8042710c78371c
3,625,105
from typing import List def readFile(filename: str) -> List[str]: """ Reads a file and returns a list of the data """ try: with open(filename, "r") as fp: return fp.readlines() except: raise Exception(f"Failed to open {filename}")
a5817ab563b83d5cf4999290d10a14a0b68954b6
3,625,107
def calculate_residuals(df, fit, names): """Calculates residuals values by comparing values in df and in fit. Arguments: df (pandas.DataFrame): Holds the data to be fitted. Either concentrations vs time or charge passed vs time depending on the situation. fit (numpy.nda...
5b597dd8ff83241993bee8cae27e6f85c43b1959
3,625,108
def ted(): """ When A POST request with json data is made to this uri, Read the example from the json, predict probability and send it with a response """ # Get decision score for our example that came with the request data = flask.request.json print(data) X = data#["example"]) #...
11a20ecb7ba60d3debea53cf5b52b76454436c32
3,625,109
import yaml def yaml_load(source, loader=yaml.Loader): """ Wrap PyYaml's loader so we can extend it to suit our needs. Load all strings as unicode: http://stackoverflow.com/a/2967461/3609487. """ def construct_yaml_str(self, node): """Override the default string handling function to alwa...
dbf8f52b159b1f563322a1474a4a14733b741143
3,625,110
def _item_to_instance(iterator, instance_pb): """Convert an instance protobuf to the native object. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that is currently in use. :type instance_pb: :class:`~google.spanner.admin.instance.v1.Instance` :param...
75fceba9caec7fa37d2ef674dca2296a71b4532f
3,625,111
def get_trunc_hour_time(obstime): """Truncate obstime to nearest hour""" return((int(obstime)/3600) * 3600)
8379aafc76c1987f537ea294c7def73ad32f1b23
3,625,113
import re def normalize_package_name(python_package_name): """ Normalize Python package name to be used as Debian package name. :param python_package_name: The name of a Python package as found on PyPI (a string). :returns: The normalized name (a string). >>> from py2deb impor...
47a850c601e64b570470a339769742d8f3732e28
3,625,114
def resolve_all(x): """Recursively resolves the given object and all the internals. Make sure there is no indirect reference within the nested object. This procedure might be slow. """ while isinstance(x, PDFObjRef): x = x.resolve() if isinstance(x, list): x = [ resolve_all(...
28e3903b679f842fd8f104780ddb08379f65cfaf
3,625,115
def logout(): """View of logout""" logout_user() flash('Administrator Logged out') return redirect(url_for('main.index'))
85b8df3f281641b823d7a6765316832f96f5202e
3,625,116
import tqdm def create_data_language( text, vocabulary, window_size=2, fill_strategy="zeros", verbose=False ): """Create a supervised dataset for the characte/-lever language model. Parameters ---------- text : str Some text. vocabulary : list Unique list of supported characte...
2da866ac637d4658c17e69d722c8a9db52987983
3,625,117
import dateutil def format_datetime(value, datetime_format="medium"): """Converts a datetime str to a format that is understood by the db. Args: value: A str representing a datetime datetime_format: A str representing the desired format of the returned datetime, accepted values ar...
f526ddf89f030b66aa7e2567b1cc301c98100096
3,625,118
import csv def getDialect(filename): """Get the dialect of the given csv file.""" with open(filename, 'rb') as csvfile: dialect = csv.Sniffer().sniff(csvfile.read(1024)) return dialect
0169c9058a46ba265768ef405cd525cc2d1a132b
3,625,119
def sort_list(source, target): """ This function is used to sort the source and target list on the basis of key found in the source and target list. :param source: :param target: :return: """ # Check the above keys are exist in the dictionary if len(source) > 0: tmp_key = is_...
3344f83e21e31c1cf3145e1ba5334bc9a0d5216b
3,625,120
def get_audio_source(input=None, **kwargs): """ Create and return an AudioSource from input. Parameters ---------- input : str, bytes, "-" or None (default) source to read audio data from. If `str`, it should be a path to a valid audio file. If `bytes`, it is used as raw audio data....
e046b79bd9bafd2c8a23614834dc1533e0ceb3da
3,625,121
def delete_prtg_device(prtg_single_device_obj): """ deletes the host at PRTG WITHOUT confirmation """ result = prtg_single_device_obj.delete(confirm=False) return result
4cb9b2a35294f0c56a62a7dbd220ab2ada81a15d
3,625,122