content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import Tuple import math def near_duplicate_similarity_cached( gold: Tuple[str], pred: Tuple[str], threshold: float = 0.1, ) -> float: """ Computes the approximate token-level accuracy between gold and pred. Returns: token-level accuracy - if not exact match an...
68734870a9797f8d9eed43704577f5f7df306acb
633,132
def deltatime_str(deltatime_seconds: float) -> str: """ Convert time in a format appropriate of time. Parameters ---------- deltatime_seconds : float Represents the elapsed time in seconds Returns ------- time_str : str Represents time in a format hh:mm:ss Examples...
bd0b79c13377538271e6ff758115b1fc8d30374f
633,133
import functools def on_flow(initializer, alias): """ Use this decorator to create an updater that responds to flows of nodes between parts of the partition. Decorate a function that takes: - The partition - The previous value of the updater on a fixed part P_i - The new nodes that are ju...
97b0532a4f1b32d3b2b3c1d6e3911377c4dfe393
633,138
import unicodedata import re def clean_filename(name, replace_empty=""): """ Make a user-supplied string safe for filename use. Returns an ASCII-encodable string based on the input string that's safe for use as a component of a filename or URL. The returned value is a string containing only lower...
0538b729a08b3622fc303b8193ed5b301a514af1
633,139
import math def logistic_loss(f_x,y_true): """ Compute the logistic_loss loss given the returned value f_x from a linear discrimination function on the feature x and its label y. Please use logarithm with base = 2 """ return math.log(1+math.exp(-f_x*y_true),2)
ad507b1d5b871cdf65b505966188e0db7baa3fb3
633,149
from typing import Dict from typing import Any def remove_none_values_recursively(dictionary: Dict[Any, Any]) -> Dict[Any, Any]: """ Recursively removes the key value pairs where the value is None. This is a recursive function which tries to find key value pairs where the value is None and then remove ...
2394eaa2a6f503cd4250a69ebfa52affe4621ee1
633,151
from typing import Optional from typing import Union from typing import Mapping from typing import Tuple from typing import Dict def get_compression_method( compression: Optional[Union[str, Mapping[str, str]]] ) -> Tuple[Optional[str], Dict[str, str]]: """ Simplifies a compression argument to a compressio...
f24de541b10e5f77956b5a6e466fa23640fe535b
633,152
import torch def reshape_data(data_list, batch_first=True, collapse_dims=False): """Concat input/output data and clear buffers Args: data_list (list): list of tensors of equal, arbitrary shape where the batch_dim is either 0 or 1 depending on self.batch_first. batch_first (bool, optiona...
5c626dd7a34c2bca73fe6649b707fbdcea01fe39
633,154
def tostr(data): """convert bytes to str""" if type(data) is bytes and bytes is not str: data = data.decode('utf8') return data
cb774974f0ebe643862af5058ccd57eafe2b9d13
633,158
from typing import Any def get_object_name(obj: Any) -> str: """Get a human-readable name of a Python object, e.g. a pipeline component. obj (Any): The Python object, typically a function or class. RETURNS (str): A human-readable name. """ if hasattr(obj, "name") and obj.name is not None: ...
ccd8022fc560297d8e6c94c0561127a622758525
633,159
def required_error(name): """ The error message presented when a required field is not present """ return "You must specify a value for {0}".format(" ".join(name.split("_")))
a60b000632b6304618820d00c65f0716dc21020c
633,160
def deep_merge(first: dict, second: dict) -> dict: """ Dict deep merge function Merge recursive second dict in first and return it >>> deep_merge({},{}) {} >>> deep_merge({'key': 'value'}, {'key': 'value'}) {'key': 'value'} >>> deep_merge({'key': 'value'}, {'key': 'new_value', 'second_k...
8306b925f8c7b69044135e0e8387d082553bda4e
633,161
def play_one(env, model, eps, gamma, copy_period): """ Plays a single episode. During play, the model is updated, and the total reward is accumulated and returned. Parameters ---------- env : gym.Env Environment. model : NumpyDQNObsSingle Model instance. eps : numeric ...
eac4fb1bfeb425b3f87b2bba459122d1c1b31371
633,168
def curvature(cs, x): """ Return the curvature (inverse radius of curvature) of the lane. Parameters: cs: CubicSpline Instance of the CubicSpline calss x: float or array of floats Points at which to evaluate the curvature >>> from eksternlab import curvature >>> x = [0.23...
e7cfb95be1073a27d176f52e582fd3a462239296
633,170
from typing import Tuple def pad(left: int, right: int, top: int, bottom: int) -> Tuple[Tuple[int, int], Tuple[int, int]]: """Set padding of element. Args: left: Left padding. right: Right padding. top: Top padding. bottom: Bottom padding. Returns ---------- padding: The padding ...
4e49571b59e6dc5becadf9c2786b363ca515f2b8
633,173
def all_validate_to(func): """ Validate that all elements in the given list pass the validation of the given validator function. >>> f = all_validate_to(positive()) >>> f([10, 20, 30]) True >>> f([10, 0, 30]) False >>> f([10, 10, -100]) False >>> f = all_validate_to(in_range...
c6be2c5430285691cc31f5e036fbad26122fce46
633,179
def get_neighbor_distances(ntw, v0, l): """Get distances to the nearest vertex neighbors along connecting arcs. Parameters ---------- ntw : spaghetti.Network A spaghetti network object. v0 : int The vertex ID. l : dict The key is a tuple (start vertex, end vertex...
ed54dcdff7abadcf99c2f6892cb0abc3daa94b7d
633,180
def stations_by_river(stations): """ Groups stations by the river they are on. Args: stations: list of MonitoringStation objects Returns: A dictionary mapping river names (string) to a list of MonitoringStation objects """ ret = {} for s in stations: river = s.river ...
80f55713bffe82883309f26bd24c2d7a9460bf11
633,181
def truncate_name(text): """Ensure the comic name does not exceed 100 characters.""" return text[:100]
4fbaf6f0122b852306c78c7a06da53e73f392302
633,182
def with_prefix(prefix, name): """Adds prefix to name.""" return "/".join((prefix, name))
03e82480cee3bb9cdf0b73c4e26a792c271e202d
633,183
def split_stream_name(ui_stream_name): """ Splits the hyphenated reference designator and stream type into a tuple of (mooring, platform, instrument, stream_type, stream) """ mooring, platform, instrument = ui_stream_name.split('-', 2) instrument, stream_type, stream = instrument.split('_', 2) s...
4c01dd99d8c6e1963af03a241a3a1a8a517af06d
633,184
import pickle def _load_command_store_from_pickle(file_name): """Load the command store from a pickle file.""" return pickle.load(open(file_name, "rb"))
2b35e37af9736f983f232261140f2db516198678
633,188
def plateInput_files(pldef_params): """ Get ordered list of plateInput files given plate_definitio pararmeters. Parameters ---------- pldef_params : dictionary Should likely be the output of io.fp_platedef_params() """ return [pldef_params[f'plateInput{N+1}'] for N in r...
98cfeb7585206d70f804bca76556de9ccf4c614e
633,190
def decode(x): """Decode in case input is bytes-like """ try: x = x.decode() return x except: return x
b96bf301b8c8ed99251e39aaa80f869a5cf49bcc
633,191
def getNameBuiltwithpip(lines): """ Used if buildWithPip == True. If the file contains "%define pipname packagename", returns packagename. None otherwise """ name = None for line in lines: if line.startswith("%define"): if "pip_name" in line: name = line.s...
f6fee367af20f9c687ef0cedf651e8a799bde660
633,193
def tickDiff(t1, t2): """ Returns the microsecond difference between two ticks. t1:= the earlier tick t2:= the later tick ... print(pigpio.tickDiff(4294967272, 12)) 36 ... """ tDiff = t2 - t1 if tDiff < 0: tDiff += (1 << 32) return tDiff
a08b74432ccaae8f4a4223aad6758aa4742d5ea5
633,198
def limit(num, minimum=1, maximum=255): """Limits input 'num' between minimum and maximum values. Default minimum value is 1 and maximum value is 255.""" return max(min(num, maximum), minimum)
fac54ad0bba741f14f97341a6331c025b5bd49fd
633,199
def occursInEq(var, deq): """ Detects if a variable appears within a delta equation. """ return (var == deq.clo1.expr) or (var == deq.clo2.expr)
f2d6a6b9888cc3eb685e90a72f726811408a6945
633,200
import hashlib def Digest(manifest): """Compute the digest of the manifest.""" return 'sha256:' + hashlib.sha256(manifest).hexdigest()
b26378a68390eb57d6f7e8210d87c346ab7f8c14
633,201
def fromHomogeneous(M): """ Return the linear and affine parts of a homogenous matrix :math:`M = [A, b]`. Parameters ---------- M : numpy array of float, shape (*, num_dims, num_dims + 1) or (*, num_dims + 1, num_dims + 1) Matrix representing an affine transformation in homogeneous coordinates....
80eedff60073a95030c9a7a574efc0231703a589
633,202
import torch def apply_filterbank(specgram, filterbank): """ Apply a filterbank on specgram Args: specgram: [..., F, T] filterbank: [F, N]. N is the number of filters Returns: [..., N, T] """ # Pack batch shape = specgram.size() specgram = specgram.reshape(-1,...
c03424276de8ee17b4b991f6f116bbcf9d478ec2
633,210
def readProcessed( serverName, itemIds, startDate, endDate, resampleIntervalMS, aggregates ): """Reads processed values from the OPC-HDA server. Processed values are calculated values, based on the aggregate function requested for each item. The list of aggregates can be obtained by calling system....
f34ace2196426a392e79a652888e00e0a92b60c2
633,211
def filter_rules_action(user_actions, rules): """ Divide the list of rules by user_actions to editable and viewonly subsets :param user_actions: list of actions allowed for normal user :param rules: list of rules to be filtered :return: editable, viewonly lists """ editable = [] viewonly...
84b668e2d470e81e92b8f1d85365d18cd0d39207
633,213
def has_compatible_scheme(url): """Check whether the given URL uses a scheme compatible with and intended to be used by apt.""" return url.startswith(('http://', 'https://'))
69e1d2854ce7b69f73c9863a84de54db3aacf9af
633,214
import torch def vec_like(n, tensor): """ Returns a 2-D tensor with a vector containing zeros with same size as the input. """ assert n > 0, (type(n), n) assert len(tensor.shape) >= 1, tensor.shape vec = torch.zeros(n, 1, device=tensor.device, dtype=tensor.dtype) return vec[None].rep...
cb039684f129a6d078dd545d826906202b3a94b7
633,216
def alter_data(df, context): """ Perform any alterations here on the Pandas DataFrame "df". For example, here is how you might drop the "education" column from indicator ENV1-3-2: if context['indicator_id'] == 'ENV1-3-2': df = df.drop(columns=['education']) """ # Don't forget to re...
d8fac6c47028a68e7240d5a84659e314da73aef8
633,217
def arg_neither_empty_nor_all_whitespace(_, arg: str) -> bool: """ Tests if the single argument is not None :param _: Ignored (typically mapped to `self` for bound methods) :param arg: The argument to be tested :return: True if arg is neither an empty string nor a string consisting only of whitespa...
9c0c79c1d9f8e092bdc914e662b677ab379a7952
633,218
def sumlist(x, y): """ Sums two lists of the same shape elementwise. Returns the sum. """ z = x for i in range(0, len(z)): if isinstance(x[i], list) and isinstance(y[i], list): z[i] = sumlist(x[i], y[i]) else: z[i] = x[i] + y[i] return z
c59a576694ffde673943abf0cf0973382ed7b2b4
633,219
import itertools def dict_list_cartesian_product(**kwargs) -> list: """ Given a dictionary whose values are lists, creates a list with every possible dictionary combination and regular unpacked values. Adapted from the Propheticus function in propheticus.shared.Utils.cartesianProductDictionaryLists. """ keys, valu...
de09b3450ac11496e7e34187b0853c89d09396b2
633,224
def split_mtx(X, n_folds=200): """ Split a matrix/Tensor into n parts. Useful for processing large matrices in batches """ X_folds = [] fold_len = X.shape[0]//n_folds for i in range(n_folds): start = i * fold_len if i == n_folds -1: end = X.shape[0] else: end = (i + 1) * fold_len ...
6a40af2e58ee8dc2156362ccf65cff8faa168ac4
633,225
def merge_dicts_lists(parent_dict, merge_dict): """ Function to add two dictionaries by adding lists of matching keys :param parent_dict: The Dict to which the second dict should be merged with :param merge_dict: Dict to be merge with the parent :return: Dict having the two inputs merged """ ...
d1d130d1fc58e1b2e293459bae37d0440686a17a
633,226
def FindSubstr(subseq, seq, expAt, wobble): """ Here we search for model parts pre and post barcode within a sequence from reads. subseq (str) Subsequence within string we're looking for seq (str) Full sequence to search subseq within expAt (int) expected at location of subseq wobble (int) ...
aaa92ea326b3a34e629c205066121f6a4bc61b08
633,236
def extract_relevant (msg): """ Extracts relevant (to the app) headers & info from a GMail message """ headers_to_extract = set (["subject", "from", "message-id"]) headers = msg["payload"]["headers"] data = dict () data ["id"] = msg ["id"] data ["thread_id"] = msg ["threadId"] for heade...
afcf4010c7e989899fecddcc444cbc76b802a917
633,237
import re def stringify_segments(sent_dict_list, segment_type): """ Converts a list of sentences (Doc objects) into strings based on their segment number, to pass to a model. :param sent_dict_list: The dictionary list containing the list of sentences. :param segment_type: The type of segment to conver...
047d52af3994285c3a16c3efe5d1bdad8fa307e9
633,242
import ntpath def extract_filename(path_filename): """ In case the customer uses a path instead of a filename, we extract the filename If it is just a filename, then we return it back directly. Using ntpath to make sure it works on all platforms. Note the filename could be empty :param path_f...
6223984119bc758953fa518a0f7e2e216ed56fd5
633,245
def extract_coord(var_name): """Assuming prefix_R_C format, return (prefix,row,column) tuple. prefix is of type string, row and column are integers. The "nowhere" coordinate has form prefix_n_n. To indicate this, (-1, -1) is returned as the row, column position. If error, return None or throw exc...
a0f51761d3865e78cecd1d74a87a03b7ddf10c71
633,249
import json def _read_city_name(path: str) -> str: """read city name from json file in the log folder Args: path: path to the json city_name in the log folder Returns: city_name: city name of the current log, either 'PIT' or 'MIA' """ with open(path, "r") as f: city_name = ...
d758be33e25cf36260f97dbb23be4441c9f4ae75
633,252
def complex_product(a_re, a_im, b_re, b_im): """ Computes the complex product of a and b, given the real and imaginary components of both. :param a_re: real component of a :param a_im: imaginary component of a :param b_re: real component of a :param b_im: imaginary component of a :return: tu...
4e17df4023ff9d6042105dc7d57cdb124cbafec6
633,256
def get_species_counts(individuals): """ Returns a dictionary with species name as the key and the number of individuals in that species as the value. :param individuals: :return: """ species_counts = {} for individual in individuals: species = individual.split("_")...
694660d7519b20560bc3ea173aa2d49261d8c0cf
633,257
from typing import Callable from functools import reduce def pipe(*fns: Callable) -> Callable: """ Returns a function invoking 'fns' in sequence left to right, the first with the initial arguments, each thereafter with the last return value. >>> pipe(lambda x, y, z: x + y + z, lambda x: x + 1)(1, 2, ...
7bf42d461524c2af85760562c3cf74f952e2933a
633,258
import torch def cross_broadcast(x: torch.Tensor, y: torch.Tensor): """ Cross broadcasting for 2 tensors :param x: torch.Tensor :param y: torch.Tensor, should have the same ndim as x :return: tuple of cross-broadcasted tensors x, y. Any dimension where the size of x or y is 1 is expa...
e19ed1a821905f2ee9deeddb9712621fcd2399e2
633,260
def remove_country_code(language): """ Returns only the ISO-639-1 language part of the provided language string, that may also contain a ISO-3166 country part as suffix. :param language: :return: """ if '-' in language: return language.split('-')[0] if '_' in language: re...
5ee9fbb6e05aa00ae10945177f2f02c34a750ddf
633,261
def first_line(text, keep_empty=False, default=None): """First line in 'data', if any Args: text (str | list | None): Text to examine keep_empty (bool): When False skip empty lines (+ strip spaces/newlines), when True don't filter (strip newlines only) default (str | None): Default to r...
7090aca1d7e5e187d41ff0c39ec78a3866f4d3a1
633,262
def index_nest(nest, index): """Index a nested object, using a tuple of indices or keys in the case of dicts. Parameters ---------- nest The nested object to index. index A tuple of indices for indexing. """ ret = nest for i in index: ret = ret[i] return ret
e4dff364f86e83cf59fc1e5c3737c16b9b9e3319
633,263
def get_common_characters(character_counter, coverage=1.0): """ Get the most common characters of a language. Parameters ---------- character_counter : collections.Counter coverage : float, optional (default: 1.0) Take the most common characters that make up `coverage` of the dataset ...
c53fa456ff3b656173cc58b94dc76f983e65519a
633,275
def replace(text, from_string, to_string): """Replace a string.""" return text.replace(from_string, to_string)
ffba99b78b05b4262d013244abae282d2e31e932
633,277
def stationary(t): """Probe is stationary at location h = 2, v = 0""" return 0.*t, 2/16 + 0*t, 0*t
984734db7045bbc49850b0b641882b8812bcbe18
633,280
from typing import List from typing import Dict from typing import Tuple def simplify_experiments(experiments: List[Dict]) -> List[List[Tuple[str, ...]]]: """Converts a list of experiments into a list of lists of tuples, where each tuple represents a crossing in a given experiment. :param experiments: ...
daccc28faf2be25115ea18091ccbca5153b11a1f
633,286
def signature_parse(content: str, signature: str) -> bool: """Parses given text looking for the presence of a given signature. Returns ``True`` if the signature was found, ``False`` otherwise. :param content: str :param signature: str :return: bool """ if content.find(signature) != -1: ...
9b60fe034f5717813483a82a063086b95c5ffd89
633,287
import string def parse_a3m(filename): """Load a3m file to list of sequences Parameters: ----------- filename : str path to a3m file Returns: -------- seqs : list list of seqs in MSA """ seqs = [] table = str.maketrans(dict.fromkeys(string.ascii_lowercase)) ...
83521867a7ec244616c9e7aebb7900c3b1cf2025
633,290
def frequency_text(hz): """ return hz as readable text in Hz, kHz, MHz or GHz """ if hz < 1e3: return "%.3f Hz" % hz elif hz < 1e6: return "%.3f kHz" % (hz / 1e3) elif hz < 1e9: return "%.3f MHz" % (hz / 1e6) return "%.3f GHz" % (hz / 1e9)
8c1e1ba3e07e7bd720b7a55bff85d528043697b8
633,298
from typing import Tuple def rebase_donate_argnums(donate_argnums, static_argnums) -> Tuple[int, ...]: """Shifts donate to account for static. >>> rebase_donate_argnums((3, 4), (0, 1)) (1, 2) Args: donate_argnums: An iterable of ints. static_argnums: An iterable of ints. Returns: A tuple of u...
414f6d883c57438bd055039a7883abee320977f7
633,301
def old_vertex_from_dummy(dummy: int, key: int, biggest) -> int: """Old vertex ID from the dummy vertex ID""" if dummy < 0: return -(dummy + (biggest + 1) * (key - 1) + 1) return dummy
13bbca37effd44e21ce2d8ba8c49b5569b2c3ad5
633,302
def interval_start(DateTime): """Return the default start of the recurrence interval.""" return DateTime(2014, 4, 1, 0)
db1bcafccebe0518a45a500b45db9fe43219472f
633,303
import socket def is_connected() -> bool: """Check if connected to Internet.""" try: # connect to the host -- tells us if the host is actually reachable sock = socket.create_connection(('connectivitycheck.gstatic.com', 80)) if sock is not None: sock.close() return T...
83528dd54d0aed7683dd7430f16ab21e86562cdb
633,304
import threading def new_thread(name=None): """Creates new thread decorator. Args: name (str): Thread name. Returns: function: New thread decorator. """ def decorator(f): """Decorator which calls function on a new thread. Args: f (fun...
16d8017326c32215729a59b05c1d29c994566e2e
633,305
def r_to_p(r, d, rtype='EI'): """ Inverse of the p_to_r function. Parameters ---------- r : float The RB error rate d : int Number of dimensions of the Hilbert space rtype : {'EI','AGI'}, optional The RB error rate rescaling convention. Returns ------- ...
fbb7411d367684fbfabda8f937d3dd4a53ae6b0f
633,307
import random def successfulStarts(eventProb, numTrials): """Assumes eventProb is a float representing a probability of a single attempt being successful. numTrials a positive int Returns a list of the number of attempts needed before a success for each trial.""" triesBeforeSuccess = [] for t ...
486dc50d4f9ebf69902cee25d157b3e9a5fc5f0c
633,309
def default_step_condition_factory(target_version, step_name): """Create a default condition used by upgrade steps. The created condition checks if the step was already successfully ran and skip it if it is the case. """ def default_step_condition(alembic, failed_migration, *args): if faile...
b4b7dece059d05df3650d5649f72760271b52c65
633,313
def _idempotent(method): """Return whether *method* is idempotent.""" return method in ('GET', 'HEAD', 'PUT')
f9940276f1ebf112a4d53e17c632eb4fffb09c4d
633,314
import re def get_contents (fname): """ Return the contents of the given file. Strip comments (lines starting with ;) """ if type(fname) == list: contents = '\n'.join(fname) else: fp = open (fname, "r") contents = fp.read() fp.close() return re.sub(r...
1ec8cce0c8e4a719691b8c7f802eb3a9152e34cc
633,318
def isiter(x): """ Returns `True` if the given value implements an valid iterable interface. Arguments: x (mixed): value to check if it is an iterable. Returns: bool """ return hasattr(x, '__iter__') and not isinstance(x, (str, bytes))
6b2e5a6e4d676cf6c749fbac6f1e3ba64057f8e9
633,321
def Latentc(tempc): """Latent heat of condensation (vapourisation) INPUTS: tempc (C) OUTPUTS: L_w (J/kg) SOURCE: http://en.wikipedia.org/wiki/Latent_heat#Latent_heat_for_condensation_of_water """ return 1000 * (2500.8 - 2.36 * tempc + 0.0016 * tempc ** 2 - 0.00006 * tempc ** 3...
7e74ad7de405272cb385ddb085179890da9d0171
633,322
def image_proc_normalize( image ): """ Normalize image pixel component values to 0-1 range. """ output_image = [] for row in image: output_row = [] for pixel in row: if isinstance( pixel, float ) or isinstance( pixel, int ): output_row.append( pixel / 255 ...
a8270775b2f2e259a0aec5855e28df9030aec51e
633,324
def rollout(tree, s, depth): """Rollout from the current state s. Parameters ---------- tree : :py:class:`ast_toolbox.mcts.MCTSdpw.DPWTree` The seach tree. s : :py:class:`ast_toolbox.mcts.AdaptiveStressTesting.ASTState` The current state. depth : int The maximum search d...
546493c1b24b3e196d25e8087253578c8c1021bc
633,327
import urllib.request import shutil def download(url, file=None): """ Pass file as a filename, open file object, or None to return the request bytes Args: url (str): URL of file to download file (Union[str, io, None]): One of the following: - Filename of output file ...
92edc9b3a4e529bd7f2975c1491f7629da18f92f
633,329
import torch def compute_classification_logits(pooled_output, output_weights_cls, output_bias_cls): """Computes logits for each classification of the sequence. Args: pooled_output: <float>[batch_size, hidden_dim] Output of the pooler (BertPooler) on top of the encoder layer. Returns: logit...
e4822875aa58bc6c0a57ea4a0275e88b9fe9dc77
633,331
def _get_base_step(name: str): """Base image step for running bash commands. Return a busybox base step for running bash commands. Args: name {str}: step name Returns: Dict[Text, Any] """ return { 'image': 'busybox', 'name': name, 'script': '#!/bin/sh\n...
6ca005e3c46007ee2b4a3c852fa0c657990cb87c
633,332
def find_ss_regions(dssp_residues, loop_assignments=(' ', 'B', 'S', 'T')): """Separates parsed DSSP data into groups of secondary structure. Notes ----- Example: all residues in a single helix/loop/strand will be gathered into a list, then the next secondary structure element will be gathered i...
a6f59aacdd58c6cc30532a260e03e3d24ac9bae8
633,336
def tabulate(lines): """ Add a tab before each line in the list """ out = [] for line in lines: out.append(" {}".format(line)) return out
a730d79f69fffda6ef530bb7586357180935bf81
633,338
def start_session(self, request, force = False, set_cookie = True): """ Starts a new session for the provided request, by default the session is created even if a previous one already exists in the request. An optional set cookie flag may control if the cookie value should be returned to the cl...
58f941eaa5cd29d4b927bd7453dbebf69c52c412
633,339
def is_2nd_after_1st(event_stat_1, event_stat_2): """Returns true if 2nd event has a later minute / second as the first""" min_1 = event_stat_1.minute sec_1 = event_stat_1.second min_2 = event_stat_2.minute sec_2 = event_stat_2.second return min_1 * 60 + sec_1 < min_2 * 60 + sec_2
dd2004c70a7b7bbb6fd79e8c50dc2aeb8e467277
633,340
import requests def live_url_check(url): """ This function takes an URL and check whether it is live or not. If it is live return True and False otherwise. :param url: a Uniform Resource Locator(URL) of a website :return: True or False """ r = requests.head(url) # print(r.status_code) ...
aaf88cc8eb5b5f9b906e1886ff7e8377b0161b11
633,342
def getkey(d,key,default): """gets key from dict (d), if key does not exist, return default""" if key in d: return d[key] else: return default
950636120f1cfc0e2437802a5a50d1cea56af496
633,343
def get_images(data): """ Get all images from facebook JSON response, or return None if no data present. """ try: return data['data'] except KeyError: return []
eda4a99f801fd176f4ff514ae8a276c620d6b054
633,345
def _get_acf_params(p): """Get ACF parameters from the given parameter vector.""" return p[0], p[1], p[2], p[3] * p[2]
805bcbaac15a69321342f0748168dba2010ba505
633,348
def pad(str_float_value): """ Pad value with zeroes to 8 digits after dot """ return "%.8f"%float(str_float_value)
af10b81592a7957a6aa23c87f433ffde8da34705
633,350
def url_path(url): """ Construct a path string for a Hyperlink URL. :type url: hyperlink.URL :param url: URL. :rtype: unicode """ return (u'/' if url.rooted else u'') + u'/'.join(url.path)
977431e969e7903a728bf97a36c9a653ef11f6f1
633,353
def get_node_color_map(selected_events): """Generate color map for all organism groups in selected_events. This is done dynamically for each node-link diagram, because it minimizes collisions. :param selected_events: Specified organism_group-organism_group relationships inside nested dictionary. ...
2cec415755bc89c726141b82d7c2d125bd2b4c11
633,356
def send_message(service, message): """Sends an email message.""" return service.users().messages().send(userId="me", body=message).execute()
d36388ee2aa418953ad1b41c503d0660c3c400a4
633,359
import pathlib def last_modified(path: pathlib.Path) -> float: """Returns the timestamp of the last modification of a file. Parameters ---------- path File path. """ path = pathlib.Path(path) return path.stat().st_mtime
0102fb79bff5808d38049501f04761d5ccfc80e0
633,361
def scrape_quotes_container(soup): """Get the quote container from a quote page. Args: soup (bs4.element.Tag): connection to the quote page. Returns: bs4.element.Tag """ return soup.findAll('div', attrs={'class': 'quotes'})
16a57fcce32969b7c8c29689cbe5ffe1a02b1a16
633,366
def get_remote_url(remote_url): """ Takes a GitHub remote URL (e.g., `mozilla/fireplace`) and returns full remote URL (e.g., `git@github.com:mozilla/fireplace.git`). """ if ':' not in remote_url: remote_url = 'git@github.com:' + remote_url if not remote_url.endswith('.git'): rem...
d813a9b209280b35f260dab818542d220e79c277
633,371
def _curl_https_get_code(host): """ Create a curl command for a given host that outputs HTTP status code. """ return ( '/opt/mesosphere/bin/curl ' '-s -o /dev/null -w "%{{http_code}}" ' 'https://{host}' ).format(host=host)
b9ac384e0cf0ab18fedbe619fc27c4ce4b8a3725
633,375
def is_open_access(record): """Returns True if permissions subject(s) is anyone (all).""" return record.get('permissions', '').startswith('all_')
6e7dec27e930ac10f4e4972342755c9ea2da9b72
633,376
def mean(values): """Calculate the mean. Parameters ---------- values : list Values to find the mean of Returns ------- out : float The mean """ return sum(values)/float(len(values)) if len(values) > 0 else 0.0
de133de8916979ceedd7588c0fa2dea67a97d17d
633,378
def remove_from_string(string, letters): """Given a string and a list of individual letters, returns a new string which is the same as the old one except all occurrences of those letters have been removed from it.""" for i in string: for j in letters: if i == j: strin...
cf594b682dbdeefbe159dfd666f6757caf1ee8ed
633,380
def n_air(lambda0, temperature=15): """ Calculate refractive index of air at atmospheric pressure. This follows the equation on page 4 of Smith, Modern Optical Engineering. Args: lambda0: wavelength in vacuum [m] temperature: degrees celsius Returns: index of refraction [--...
1b0c2ae9a25b1ed3a3c9f81b6eb80999c4d5e68d
633,385
import torch def index_points(points, idx): """ Input: points: input points data, [B, N, C] idx: sample index data, [B, D1, D2, ..., Dn] Return: new_points:, indexed points data, [B, D1, D2, ..., Dn, C] """ device = points.device B = points.shape[0] view_shape = lis...
88483a77a566b42db7073a41d6a1cb49a51a5164
633,387
async def ping() -> str: """health check""" return "pong"
95c730e4d05fbc5e86d66ffad6bbbab182ece9a4
633,388