content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_prev_and_next_lexemes(request, current_lexeme): """Get the previous and next lexeme from the same language, ordered by meaning and then alphabetically by form""" lexemes = list(Lexeme.objects.filter( language=current_lexeme.language).order_by( "meaning", "phon_form", "romanised",...
ca33f582049d055d35196595fd0c23a06fb0d791
3,656,275
def _sanitize_and_check(indexes): """ Verify the type of indexes and convert lists to Index. Cases: - [list, list, ...]: Return ([list, list, ...], 'list') - [list, Index, ...]: Return _sanitize_and_check([Index, Index, ...]) Lists are sorted and converted to Index. - [Index, Index, .....
1c158934d49270fb17d99477082c49b7839c1fbb
3,656,276
def get_tetranuc_freqs(given_seq): """ Returns dictionary mapping each of the 4^4 = 256 possible tetranucleotides to its observed frequency in the given sequence. Args: given_seq: Returns: """ return {tetranuc : get_observed_oligonuc_freq(given_seq, tetranuc) for tetranuc in TETRANU...
b2279248961b747526bedb14a7fcddf7015fde45
3,656,277
from typing import Optional def _prv_keyinfo_from_wif( wif: String, network: Optional[str] = None, compressed: Optional[bool] = None ) -> PrvkeyInfo: """Return private key tuple(int, compressed, network) from a WIF. WIF is always compressed and includes network information: here the 'network, compres...
d9eef56ea212fafcd7aa5af718aa0b1280e9555d
3,656,279
def build_cmake_defines(args, dirs, env_vars, stage): """ Generate cmake defines :param args: The args variable generated by parse_parameters :param dirs: An instance of the Directories class with the paths to use :param env_vars: An instance of the EnvVars class with the compilers/linker to use ...
227fb680e42786356adbace344cea98433a29aab
3,656,280
def server() -> None: """Старт сервера""" class PredictionServicer(predictions_pb2_grpc.PredictionServicer): def PredictIris(self, request, context): response = predictions_pb2.PredictResponse() response.iris_type = predictions.predict_iris(request.sepal_length, ...
eaa71a36763ffee0d6b201e0900b4f1fcf397fe9
3,656,281
def wasLastResponseHTTPError(): """ Returns True if the last web request resulted in an erroneous HTTP code (like 500) """ threadData = getCurrentThreadData() return threadData.lastHTTPError and threadData.lastHTTPError[0] == threadData.lastRequestUID
cbe2a21752387cfb5b0cba41ecc3bdbacbcdcbb3
3,656,282
import select async def update_rates( user_id: str = None, client_id: str = None, new_amount: str = None, session: Session = Depends(get_session), ): """Update a rate.""" statement = ( select(Rate) .where(Rate.user_id == user_id) .where(Rate.client_id == client_id) ...
c5ef142dda27f27217d71ed811ce8b6f049a0d98
3,656,283
def taillight_detect(image): """ Takes in a road image, re-sizes for the model, predicts the lane to be drawn from the model in G color, recreates an RGB image of a lane and merges with the original road image. """ model = load_model('full_CNN_model.h5') #image1=image #image1=np.array(im...
ee8849b59e94f8c395211af3537310ad7d2d8999
3,656,285
def generate_random_number(rng, length): """Return random number with predefined length.""" return crypto.random_generate(rng, length)
2f3f5f290948c3eb063b46353a01a5edc17599e4
3,656,286
import ftplib import tarfile def update_old_names(): """Fetches the list of old tz names and returns a mapping""" url = urlparse(ZONEINFO_URL) log.info('Connecting to %s' % url.netloc) ftp = ftplib.FTP(url.netloc) ftp.login() gzfile = BytesIO() log.info('Fetching zoneinfo database') ...
a10f5985ea6fe6709816e757ee764138735eb077
3,656,287
from typing import Optional def get_namespace(location: Optional[str] = None, namespace_id: Optional[str] = None, project: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetNamespaceResult: """ Gets a namespace. """ ...
70f59b6eb48e4952d19c5b96b9579f13c0e569fd
3,656,288
def build_headers(access_token, client_id): """ :param access_token: Access token granted when the user links their account :param client_id: This is the api key for your own app :return: Dict of headers """ return {'Content-Type': 'application/json', 'Authorization': f'Bearer {acce...
5cd8ae3e06f67b7a4fdb1644ae82c62cb54479cb
3,656,289
def odd_subgraph_centrality(i, lam, u): """ Calculates the number of odd length closed walks that a node participates in :cite:`estrada2005spectral`. Used in the calculation of spectral scaling and generalized robustness index. :param i: node index :param lam: largest eigenvalue :param u: large...
eeb141ac56d9b70294bbf62a24739c73f3e4755e
3,656,291
def PolyAreasToModel(polyareas, bevel_amount, bevel_pitch, quadrangulate): """Convert a PolyAreas into a Model object. Assumes polyareas are in xy plane. Args: polyareas: geom.PolyAreas bevel_amount: float - if > 0, amount of bevel bevel_pitch: float - if > 0, angle in radians of bevel ...
c2243bca3d3cfa1168bde94dfe078d6cf3e86ad4
3,656,292
def preprocessing(train_data, test_data): """ * The method at first eliminates constant features from both train and test data. * Then, it splits training data into features and labels. * Finally, the method performs pca on training and testing data sets to reduce the dimension and overcome curse...
9f6c01d64d393c9c9fe51925f11842b63098471f
3,656,293
def generate_videos_from_events(response, video_model): """Creates the video containers/representations for this given response. We should only really invoke this as part of a migration as of right now (2/8/2019), but it's quite possible we'll have the need for dynamic upsertion later. """ seen_id...
f5669fbc6466bf3cf1671d04a48bad4c5975f216
3,656,294
def datetime_at_midnight(dt: DateTime, tz: TimeZone) -> DateTime: """ Returns a DateTime for the requested DateTime at midnight in the specified time zone. Args: dt (DateTime): the DateTime for which the new value at midnight should be calculated tz (TimeZone): the TimeZone to use when interpre...
141988c9943911d165f5f3f8ade5536ae65881f2
3,656,295
def convert2sametype(dict_, formula): """Utility function for internal use. Convert string/dict/DataFrame to dict Parameters ---------- dict_ : dict formula : string/dict/DataFrame Returns ------- type(formula) """ return convert2type(dict_, type(formula))
d7393668e5bd22e8482bf4b99c6a789d322b80fb
3,656,297
from typing import List import gzip def from_sdf(sdf_content: str = None, file_path: str = None, ignore_hydrogens = False) -> List[Graph]: """ parse graph from_sdf Read chemical files and parses them into instances of `Graph`. As this function is not meant to be called in a loop, inner functions only relative...
5676b98a699cfed00767f4d51dec27a7dc1a94ad
3,656,298
from typing import Callable def dispatcher_connect( opp: OpenPeerPower, signal: str, target: Callable[..., None] ) -> Callable[[], None]: """Connect a callable function to a signal.""" async_unsub = run_callback_threadsafe( opp.loop, async_dispatcher_connect, opp, signal, target ).result() ...
3dca8d6cf1f581a409c2b64e6c9a88e543fe0615
3,656,299
def get_last_error(): """ Get the last error value, then turn it into a nice string. Return the string. """ error_id = kernel32.GetLastError() # No actual error if error_id == 0: return None # Gonna need a string pointer buf = ffi.new("LPWSTR") chars = kernel32.FormatMessageA(...
424da4211cc5cb19c8143ffe5b4326b2ff440319
3,656,300
import pickle def load_params_from_pkl(params_dump_file_path): """ Loads parameters from a pickle _dump file. :param params_dump_file_path: self-explanatory :return dict of param_name => param """ coll = {} f = open(params_dump_file_path, 'rb') while True: try: par...
e0205d3f4b3d1ac5859eb91424a041273fc23cb8
3,656,301
def plot_by_term(term, df, kind='go', q=0.1, swarm=True, x='genotype', y='b', gene='ens_gene'): """ Plot ontology terms by a given column. Params: term - term to look for in melted_df df - a tidy dataframe with columns x and y kind - the ontology to use q - q-value for stat...
768b59ff479468902af429bdf8603455bad1eab3
3,656,303
def lab_equality(lab1, lab2): """ Check if two labs are identical """ if lab1["ncolumns"] != lab1["ncolumns"] or lab1["nlines"] != lab2["nlines"]: return False return all(set(lab1[cell]) == set(lab2[cell]) for cell in lab1.keys() if type(cell) != type("a"))
d5ffca9acfa6bc2cc324f1b6c5ed416541812c13
3,656,304
import attrs def read_wwm(filename_or_fileglob, chunks={}, convert_wind_vectors=True): """Read Spectra from SWAN native netCDF format. Args: - filename_or_fileglob (str): filename or fileglob specifying multiple files to read. - chunks (dict): chunk sizes for dimensions in dataset. ...
4623a31a0d3d780960d58743278a847377213555
3,656,305
def is_sorted(t): """Checks whether a list is sorted. t: list returns: boolean """ return t == sorted(t)
442c5a4670c595f3dea45c8aac315eda5dae26d0
3,656,306
def create_container_port_mappings(container): """ Create the port mappings for the given container. :param container: The container to create the mappings for. """ ports = [] image = None if container.is_image_based(): image = container.image elif container.is_clone() and conta...
15a93e38ccb2c3d6ecab025a8d3c9226ebbf81d0
3,656,307
from typing import Callable from typing import Any from typing import get_origin from typing import Union from typing import Dict from typing import Sequence from typing import Set import time from typing import Pattern from typing import IO from typing import Literal from enum import Enum def get_caster(typehint: Ty...
7171e70c2870169a5394d3bafc4d114f4a950db0
3,656,309
def values(series): """Count the values and sort. series: pd.Series returns: series mapping from values to frequencies """ return series.value_counts(dropna=False).sort_index()
d4ef6b93b7f2790d8130ac045e9c315b8d57a245
3,656,310
def use_id(type): """Declare that this configuration option should point to an ID with the given type.""" def validator(value): check_not_templatable(value) if value is None: return core.ID(None, is_declaration=False, type=type) if ( isinstance(value, core.ID) ...
0087ad7119999932c9d4b882907019f60346491f
3,656,311
def social_auth_user(backend, uid, user=None, *args, **kwargs): """Return UserSocialAuth account for backend/uid pair or None if it doesn't exists. Raise AuthAlreadyAssociated if UserSocialAuth entry belongs to another user. """ social_user = UserSocialAuth.get_social_auth(backend.name, uid) ...
5a421e3f1f24cecbb4e6313bee8172585f9f3708
3,656,312
def bbox_mask(t_arr, x_arr, limits): """ Just a wrapper for np.where """ #NOTE: t_arr is included but no longer used mask = np.where( (x_arr >= limits[0]) & \ (x_arr <= limits[1]))[0] return mask
90e1a92d76d1b3d406ab50300c6528973f610f0a
3,656,313
import array def kdeplot_2d_clevels(xs, ys, levels=11, **kwargs): """ Plot contours at specified credible levels. Arguments --------- xs: array samples of the first variable. ys: array samples of the second variable, drawn jointly with `xs`. levels: float, array if flo...
806b4278a6bbac91fcdfd6354cb3fa5422fab1ee
3,656,314
def normalization_reg_loss(input): """ input: [..., 3] It computes the length of each vector and uses the L2 loss between the lengths and 1. """ lengths = (input ** 2).sum(dim=-1).sqrt() loss_norm_reg = ((lengths - 1) ** 2).mean() return loss_norm_reg
3b9d999c90d8e9b3ce797d286bb2f0b215fa7ee5
3,656,315
def _get_window_size(offset, step_size, image_size): """ Calculate window width or height. Usually same as block size, except when at the end of image and only a fracture of block size remains :param offset: start columns/ row :param step_size: block width/ height :param image_size: image wi...
90d65229c54a5878fa9b2af8e30293e743679e42
3,656,316
def _ListCtrl_IsSelected(self, idx): """ Returns ``True`` if the item is selected. """ return (self.GetItemState(idx, wx.LIST_STATE_SELECTED) & wx.LIST_STATE_SELECTED) != 0
796916c4cf13e77ec7f21cae2210acbb6d250e14
3,656,317
def sturm_liouville_function(x, y, p, p_x, q, f, alpha=0, nonlinear_exp=2): """Second order Sturm-Liouville Function defining y'' for Lu=f. This form is used because it is expected for Scipy's solve_ivp method. Keyword arguments: x -- independent variable y -- dependent variable p -- p(x) para...
5c34cc622075c640fe2dec03b1ae302192d0f779
3,656,318
def hamming_set(index: str, d: int = 1, include_N: bool = True): """Given an index of bases in {ACGTN}, generate all indexes within hamming distance d of the input :param index: string representing the index sequence :param d: maximum distance to allow :param include_N: include N when generating po...
d8546bd2f7b04518d2d711488045670a60e449fe
3,656,320
from mne import read_epochs def _get_epochs_info(raw_fname): """Get epoch info.""" epochs = read_epochs(raw_fname) return epochs.info
5a7d20041e7b1de7b4dcf3540f7a9d01575fb8f9
3,656,321
def is_private(key): """ Returns whether or not an attribute is private. A private attribute looks like: __private_attribute__. :param key: The attribute key :return: bool """ return key.startswith("__") and key.endswith("__")
498e7522e95317dbb171961f0f5fe8350c29a69d
3,656,322
async def img(filename) -> Response: """Image static endpoint.""" return await send_from_directory("img", filename)
d255f0f11f3b380f332a3165f8917d2d2cb65a6b
3,656,323
def ref_genome_info(info, config, dirs): """Retrieve reference genome information from configuration variables. """ genome_build = info.get("genome_build", None) (_, sam_ref) = get_genome_ref(genome_build, config["algorithm"]["aligner"], dirs["galaxy"]) return genom...
382d32bddef76bb1ba1ecd6a4b39c042909ac3ed
3,656,324
def load_text(file_arg): """ General function used to load data from a text file """ file_handle = validate_file_for_reading(file_arg) try: df = pd.io.parsers.read_csv(file_handle,delim_whitespace=True,\ comment='#', skip_blank_lines=True, engine='c') except: raise So...
f8681d1db1819f2036f0b6304a04fd1762ad31f8
3,656,325
def entropy_from_mnemonic(mnemonic: Mnemonic, lang: str = "en") -> BinStr: """Convert mnemonic sentence to Electrum versioned entropy.""" # verify that it is a valid Electrum mnemonic sentence _ = version_from_mnemonic(mnemonic) indexes = _indexes_from_mnemonic(mnemonic, lang) entropy = _entropy_fr...
adcdfe3f66150f77276af7b4689289fe7609a253
3,656,326
def delete_data_analysis(analysis_id: UUID, token: HTTPAuthorizationCredentials = Depends(auth)): """ Delete a data analysis record. You may only delete records in your private space, or that are associated with a collab of which you are an administrator. """ return delete_computation(omcmp.Dat...
bc8cc6ee1174017be1b0ca17f221784163975132
3,656,327
def get_current_blk_file(current_file_number) -> str: """ Returns the current blk file name with file format. """ return get_current_file_name(blk_file_format(current_file_number))
44c81a5977f42fe38426231421bc3c2b76c36717
3,656,328
def exec_cmd_status(ceph_installer, commands): """ Execute command Args: ceph_installer: installer object to exec cmd commands: list of commands to be executed Returns: Boolean """ for cmd in commands: out, err = ceph_installer.exec_command(sudo=True, cmd=cmd) ...
b5deddf504e1ae0cbc67a5b937d75bb02984b224
3,656,329
import logging def BuildIsAvailable(bucket_name, remote_path): """Checks whether a build is currently archived at some place.""" logging.info('Checking existance: gs://%s/%s' % (bucket_name, remote_path)) try: exists = cloud_storage.Exists(bucket_name, remote_path) logging.info('Exists? %s' % exists) ...
c1947339a00a538c910e669179d19c986cab5b7e
3,656,330
def _channel_name(row, prefix="", suffix=""): """Formats a usable name for the repeater.""" length = 16 - len(prefix) name = prefix + " ".join((row["CALL"], row["CITY"]))[:length] if suffix: length = 16 - len(suffix) name = ("{:%d.%d}" % (length, length)).format(name) + suffix return...
4452670e28b614249fb184dd78234e52ee241086
3,656,331
def wordsinunit(unit): """Counts the words in the unit's source and target, taking plurals into account. The target words are only counted if the unit is translated.""" (sourcewords, targetwords) = (0, 0) if isinstance(unit.source, multistring): sourcestrings = unit.source.strings else: ...
57f6be28eab17ee2bd2cd31783809bd8a413c09e
3,656,332
def check_instance(arg, types, allow_none=False, message='Argument "%(string)s" is not of type %(expected)s, but of type %(actual)s', level=1): """ >>> check_instance(1, int) 1 >>> check_instance(3.5, float) 3.5 >>> check_instance('hello', str) 'hello' >>> check_instance([1, 2, 3], list)...
362d6101e9f6b88077f8615043713989576c7713
3,656,333
def spec_lnlike(params, labels, grid_param_list, lbda_obs, spec_obs, err_obs, dist, model_grid=None, model_reader=None, em_lines={}, em_grid={}, dlbda_obs=None, instru_corr=None, instru_fwhm=None, instru_idx=None, filter_reader=None, AV_bef_bb=False, u...
8411ec37268cd2c169b680b955678d13f0d10cbc
3,656,334
def generic_list(request): """Returns a list of all of the document IDs in the matched DocStore.""" return umbrella_from_request(request).get_doc_ids()
8c5f47c8816fca503c2c4fa93db1204b3b511157
3,656,335
def japan_results(request): """ view function returns template that displays New York-specific photos """ images = Image.filter_images_by_location(location_id=12) return render(request, "all_pictures/japan.html", {"images":images})
d0fd80eac7529f5b9b5699439cabb0c92f82f007
3,656,336
def add_yaml_literal_block(yaml_object): """ Get a yaml literal block representer function to convert normal strings into yaml literals during yaml dumping Convert string to yaml literal block yaml docs: see "Block mappings" in https://pyyaml.org/wiki/PyYAMLDocumentation """ def literal_str_re...
47b4295394a67e92bcbc5d7cb4c25a0a1ca220dc
3,656,337
from typing import List from typing import Dict from typing import Set from typing import Optional def _spans_to_array( doc: Doc, sources: List[str], label2idx: Dict[str, int], labels_without_prefix: Set[str], prefixes: Optional[Set[str]] = None, warn_missing_labels: bool = False ) -> np.ndarr...
ce9f22726877b713eb373dbee9ebb719ef655f4a
3,656,338
def d_out_dist_cooler(P_mass, rho_dist_cool, w_drift): """ Calculates the tube's diameter of out distilliat from distilliat cooler to distilliat volume. Parameters ---------- P_mass : float The mass flow rate of distilliat, [kg/s] rho_dist_cool : float The density of liquid at co...
8d6dfb85aa954ef88c821d2ee1d0bb787d409e96
3,656,339
import socket def is_port_in_use(port): """ test if a port is being used or is free to use. :param port: :return: """ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: return s.connect_ex(('localhost', port)) == 0
5bbdd7b39c2380d2e07e85f483f3ea5072bb616b
3,656,340
def create_variables_eagerly(getter, initial_value, **kwargs): """Attempts to force variable creation to be eager.""" eager_initial_value = None if isinstance(initial_value, tf.Tensor): if _is_eager_tensor(initial_value): eager_initial_value = initial_value else: # Try to compute the static v...
832687547bd06aef61b8a1dca219564ef184dbb3
3,656,341
import time def _Run(vm): """See base method. Args: vm: The vm to run the benchmark on. Returns: A list of sample.Sample objects. """ # Make changes e.g. compiler flags to spec config file. if 'gcc' in FLAGS.runspec_config: _OverwriteGccO3(vm) # swap only if necessary; free local node me...
ba7c8575c45cdd7edccdf212d8ff29adb0d0fe1b
3,656,342
def mixin_method(ufunc, rhs=None, transpose=True): """Decorator to register a mixin class method Using this decorator ensures that derived classes that are declared with the `mixin_class` decorator will also have the behaviors that this class has. ufunc : numpy.ufunc A universal function (...
d1130740628eb947bd786bc3393343b8c283164d
3,656,343
def set_def_quick_print(setting): """ Set the global default (henceforth) behavior whether to quick print when stamping or stopping. Args: setting: Passed through bool(). Returns: bool: Implemented setting value. """ setting = bool(setting) SET['QP'] = setting retur...
835028c97fb03435de65df6f13c5c05fe61710f0
3,656,344
from datetime import datetime def time_handler(start_time, start_fmt, elaps_fmt, today): """return StartTime, ElapsedTime tuple using start/sub time string""" start_time = datetime.strptime(start_time, '%Y-%m-%dT%H:%M:%S') start_time = StartTime(start_time.year, start_time.month, ...
7f063a119947f90a24d76fd2f5ce7eba790a3df5
3,656,345
def lgb_multi_weighted_logloss_exgal(y_preds, train_data): """ @author olivier https://www.kaggle.com/ogrellier https://www.kaggle.com/ogrellier/plasticc-in-a-kernel-meta-and-data/code multi logloss for PLAsTiCC challenge """ # class_weights taken from Giba's topic : https://www.kaggle.com/titer...
576e0263f9088341bd4d8b0e7e016de513da26ca
3,656,346
def api_owner_required(f): """ Authorization decorator for api requests that require the record's owner Ensure a user is admin or the actual user who created the record, if not send a 400 error. :return: Function """ @wraps(f) def decorated_function(*args, **kwargs): if current...
4114abf4abc8afd1fd6d68388c17ed04e4029c13
3,656,347
def flatten_probas_ori(probas, labels, ignore=None): """ Flattens predictions in the batch """ if probas.dim() == 3: # assumes output of a sigmoid layer B, H, W = probas.size() probas = probas.view(B, 1, H, W) B, C, H, W = probas.size() probas = probas.permute(0, 2, 3, 1)...
95d0df96a7ea612546616cc96b8ea78f5bd52641
3,656,349
def VisionTransformer_small(pretrained=False,input_shape=(3,224,224),patch_size=16,num_classes=1000, depth=8,drop_rate=0.2,**kwargs): """ My custom 'small' ViT model. Depth=8, heads=8= mlp_ratio=3.""" vit= VisionTransformer( patch_size=patch_size,num_classes=num_classes, depth=depth, num_heads...
0022e3371c5c9cc138a78f1927f807a91d077f3c
3,656,351
def query_filter_choices(arg=None, fq=[]): """ Makes solr query and returns facets for tickets. :param arg: solr query, string """ params = { 'short_timeout': True, 'fq': [ 'project_id_s:%s' % c.project._id, 'mount_point_s:%s' % c.app.config.options.mount_poi...
226dd808a42981b6183c4425231107d0e7197b2b
3,656,354
def has_no_duplicates(input_): """Check that a list contains no duplicates. For example: ['aa', 'bb', 'cc'] is valid. ['aa', 'bb', 'aa'] is not valid. The word aa appears more than once. """ return len(input_) == len(set(input_))
6bc1b29b3509e4b17523408ea362591cace8d05d
3,656,355
def uplab_to_renotation_specification(spec, lab): """Convert a color in the normalized UP LAB space to its equivalent Munsell color. Parameters ---------- lab : np.ndarray of shape (3,) and dtype float The `l', `a-star` and `b-star` values for the color, with `l` in the domain [0, 1], and `...
7354ee53f9067f4720c438d1a8f743ca0b441c51
3,656,356
def _getBestSize(value): """ Give a size in bytes, convert it into a nice, human-readable value with units. """ if value >= 1024.0**4: value = value / 1024.0**4 unit = 'TB' elif value >= 1024.0**3: value = value / 1024.0**3 unit = 'GB' elif value >= 1024...
6c1859c50edcbd5715443fbf30775eeee83d6a0c
3,656,358
def create_line_segments(df, x="lon", y="lat", epsg=4269): """Creates a GeodataFrame of line segments from the shapes dataframe (CRS is NAD83) Params: df (DataFrame): pandas DataFrame x, y (str, optional) Default values x="lon", y="lat", column names fo...
a0b23c165dc808cc2793f3a62ce002dbf5990562
3,656,361
def population_correlation(data_matrix, x_index, y_index): """ data_matrix is a numpy multi-dimensional array (matrix) x_index and y_index are the index for the first and second variables respectively it returns the correlation between two variables in a data_matrix """ transposed_data = data_ma...
5216a617b5afba9c784fa18cad8506fd57f64e61
3,656,362
from typing import Any def upload(workspace: str, table: str) -> Any: """ Store a nested_json tree into the database in coordinated node and edge tables. `workspace` - the target workspace. `table` - the target table. `data` - the nested_json data, passed in the request body. """ # Set up...
7fb4d0c4c31f499944b263f1f1fedcff34667ea1
3,656,363
def validate_google_login(email): """ Validate a login completed via Google, returning the user id on success. An ``ODPIdentityError`` is raised if the login cannot be permitted for any reason. :param email: the Google email address :raises ODPUserNotFound: if there is no user account for the give...
36e095f58600b6b8a799c459ad6181afafcbcf93
3,656,364
def add_months(start_date, months, date_format=DATE_FORMAT): """ Return a date with an added desired number of business months Example 31/1/2020 + 1 month = 29/2/2020 (one business month) """ new_date = start_date + relativedelta(months=+months) return new_date.strftime(date_format)
7f579dd33807f30fa83a95b554882d6f8bf18626
3,656,365
def inVolts(mv): """ Converts millivolts to volts... you know, to keep the API consistent. """ return mv/1000.0
6c92195996be1aa2bd52aa0a95d247f7fdef5955
3,656,366
from typing import Mapping from typing import Any from typing import Tuple import uuid def extract_hit( hit: Mapping[str, Any], includes: Tuple[str] = (ID_FIELD,), source: str = '_source' ) -> Mapping[str, Any]: """ Extract a document from a single search result hit. :param hit: t...
d67f68618bbfe0e86c1525845cf4af69be31a8df
3,656,367
import time import random def generateUserIDToken(id): """Generates a unique user id token.""" t = int(time.time() * 1000) r = int(random.random() * 100000000000000000) data = "%s %s %s %s" % (ip, t, r, id) return md5(data.encode('utf-8')).hexdigest()
bc523855df0b911868d802352c83bb99d4768cf3
3,656,368
from pytools import generate_nonnegative_integer_tuples_summing_to_at_most \ def grad_simplex_monomial_basis(dims, n): """Return the gradients of the functions returned by :func:`simplex_monomial_basis`. :returns: a :class:`tuple` of functions, each of which accepts arrays of shape *(dims, npts)...
6be49780a984b9a8fb1b54073d845da683d06e36
3,656,369
from typing import Collection def get_collection() -> Collection: """Коллекция для хранения моделей.""" return _COLLECTION
e82f93a14e1a6640fe9b7b02b062540073060acf
3,656,370
def ask_for_flasherhwver(): """ Ask for the flasher version, either 1 or 2 right now... """ #if FLASHER_SKIP_ON_VALID_DETECTION and FLASHER_VERSION != 1: # return FLASHER_VERSION FLASHER_VERSION = 1 flash_version = FLASHER_VERSION if FLASHER_VERSION is None: while True...
6d9cf88ce3fd6850e345431b85ee0ed1bcaffb84
3,656,371
import torch def real_to_complex_channels(x, separate_real_imag=False): """ Inverse of complex_as_real_channels: C*2 real channels (or 2*C if separate_real_imag) to C complex channels. """ if separate_real_imag: channel_shape = (2, -1) permute = (0, 2, 3, 4, 1) else: channel_shape ...
76692fb1597ae30d99672361e9a6db74f9d1dd86
3,656,372
def create_coffee_machine() -> CoffeeMachine: """Create CoffeeMachine object for testing""" _coffee_machine = CoffeeMachine() _coffee_machine.refill_water() _coffee_machine.refill_milk() _coffee_machine.refill_coffee_beans() return _coffee_machine
10c203249c681d8f13058227521532aefaeda478
3,656,373
def validate_mqtt_vacuum(value): """Validate MQTT vacuum schema.""" schemas = {LEGACY: PLATFORM_SCHEMA_LEGACY, STATE: PLATFORM_SCHEMA_STATE} return schemas[value[CONF_SCHEMA]](value)
6c850f7f72d61ef0b0b04363a31d2563bf316d33
3,656,374
def detect(iring, mode, axis=None, *args, **kwargs): """Apply square-law detection to create polarization products. Args: iring (Ring or Block): Input data source. mode (string): ``'scalar': x -> real x.x*`` ``'jones': x,y -> complex x.x* + 1j*y.y*, x.y*`` ...
42690bf325e0d21f5839ac5f87e3d0be7ca42029
3,656,375
import watchdog def is_watchdog_supported(): """ Return ``True`` if watchdog is available.""" try: except ImportError: return False return True
8c777b9a6b29876d902087f2b719519771b5fc2a
3,656,377
def set_bit(arg1, x, bit, y): """ set_bit(Int_ctx arg1, Int_net x, unsigned int bit, Int_net y) -> Int_net Parameters ---------- arg1: Int_ctx x: Int_net bit: unsigned int y: Int_net """ return _api.set_bit(arg1, x, bit, y)
c5e7062a9e7f8f46bb4935905b9a485487c0bfad
3,656,378
def get_time_format(format='medium', locale=LC_TIME): """Return the time formatting patterns used by the locale for the specified format. >>> get_time_format(locale='en_US') <DateTimePattern u'h:mm:ss a'> >>> get_time_format('full', locale='de_DE') <DateTimePattern u'HH:mm:ss zzzz'> :param...
d774c14a27b263f4a9cadfd4d144cd9bd0ce1fd3
3,656,379
def resource_type_service(resource_type): """Gets the service name from a resource type. :exc:`ValueError` is raised if the resource type is invalid, see :func:`parse_resource_type`. >>> resource_type_service('AWS::ECS::Instance') 'ECS' """ return parse_resource_type(resource_type)[1]
04ff4ffa22e742dbd63a41cb8f9eec79628938f2
3,656,380
def loads(ss): """ loads(ss) Load a struct from the given string. Parameters ---------- ss : (Unicode) string A serialized struct (obtained using ssdf.saves()). """ # Check if not isinstance(ss, basestring): raise ValueError('ssdf.loads() expects a string.'...
ee07c433f9453b5a9f444cbcda2b80217243f0f0
3,656,381
from typing import IO import mimetypes def guess_mime_type(file_object: IO) -> str: """Guess mime type from file extension.""" mime_type, _encoding = mimetypes.guess_type(file_object.name) if not mime_type: mime_type = "application/octet-stream" return mime_type
12e6e6667b08eaaa24b822c37d56055c1487a801
3,656,382
def postcount_test(metadict_friends): """Среднее число постов по выборке, чтобы выделить активных/неактивных неймфагов.""" all_postcount = 0 for namefag in metadict_friends.keys(): name_number = namefag[0] name_postcount = cursor.execute("SELECT postcount FROM namefags WHERE number=?"\ ...
dd9f717f8c1c81e6805a257e28e74124f156661f
3,656,383
def extract_stack_name(fields): """_extract_stack_name(self, fields: list[str]) -> str Extract a stack name from the fields Examples: ffffffff818244f2 [unknown] ([kernel.kallsyms]) -> [kernel.kallsyms] 1094d __GI___libc_recvmsg (/lib/x86_64-linux-gnu/libpthread-2.23.so) -> __GI__libc_recvms...
093a2397da50bac3ce299256a6d9640af33bf59f
3,656,384
def valid_shape(shape): """ @returns: True if given shape is a valid tetris shape """ return shape in SHAPES and len(shape) == 1
e40fda46078a615b6d93438ea9d9e9d72800b25a
3,656,387
def get_device(device_id): """ @api {get} /devices/:device_id Get Unique Device @apiVersion 1.0.0 @apiName GetDevice @apiGroup Device @apiSuccess {Boolean} success Request status @apiSuccess {Object} message Respond payload @apiSuccess {Object} message.device Device object """ ...
0bad727a1a554d63db774179f45deacb1164ba18
3,656,388
import gzip def read_imgs(filename, num_images): """读入图片数据 :param filename: :param num_images: :return: """ with gzip.open(filename) as bytestream: bytestream.read(16) buf = bytestream.read( 28 * 28 * num_images * 1) data = np.frombuffer(buf, dtype=np.uint8...
a97602470c729211214b4d4a7acd0744beecdfae
3,656,389
def all_faces(coord, connect): """ Gets vertices of all faces of the mesh. Args: coord (:obj:`numpy.array`): Coordinates of the element. connect (:obj:`numpy.array`): Element connectivity. Returns: Corresponding nodes. """ nodes_per_face = np.array([connect[:, [1,2,3...
9955260eae11bd6a32e76fb96468989922e856dc
3,656,390
def edit_assignment(request_ctx, course_id, id, assignment_name=None, assignment_position=None, assignment_submission_types=None, assignment_allowed_extensions=None, assignment_turnitin_enabled=None, assignment_turnitin_settings=None, assignment_peer_reviews=None, assignment_automatic_peer_reviews=None, assignment_noti...
d83094e9d3e9ab66f5c6d4f5245dde80cf4579cc
3,656,392