content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
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
from pathlib import Path import traceback import sys def _extract_filename_from_filepath(strFilePath=""): """ Function which extracts file name from the given filepath """ if strFilePath: try: strFileName = Path(strFilePath).name strFileName = str(strFileName).split("."...
340b51cc6ac484cdf7a978890147fe453f335521
3,656,302
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
def _get_dep_for_package(package, platform): """ Convert arguments in the `package` parameter to actual deps. """ if is_list(package) or is_tuple(package): package, _ = package # TODO: ghc-8.4.4 if (package == "compact" and _get_ghc_version(platform) == "8.4.4"): packag...
e5e77c0bf0a48864e042ba8fcbdcf8c34f7918f2
3,656,308
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
import logging import sys def logged(func): """Pipes exceptions through root logger""" @wraps(func) def deco(*args, **kwargs): try: result = func(*args, **kwargs) except Exception as e: logging.exception(f"{func.__name__}:\n{e}") print("Exception logged ...
cbece89917a8329c03b9c4c24b503ff0c78edbd1
3,656,319
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
import os def save_prediction_image(stacked_img, im_name, epoch, save_folder_name="result_images", save_im=True): """save images to save_path Args: stacked_img (numpy): stacked cropped images save_folder_name (str): saving folder name """ div_arr = division_array(388, 2, 2, 512, 512) ...
69bd429c74a3af66346d41f116495b772baea828
3,656,348
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
import os def get_new_file_number(pat, destdir, startnum=1, endnum=10000): """Substitute the integers from startnum to endnum into pat and return the first one that doesn't exist. The file name that is searched for is os.path.join(destdir, pat % i).""" for i in range(startnum, endnum): temp =...
33ffed09804692bd1cb3dbe94cbdfc36eed42270
3,656,350
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
import os def downgrade_database( alembic_config_filename: str, destination_revision: str, alembic_base_dir: str = None, starting_revision: str = None, version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE, as_sql: bool = False) -> None: """ Use Alembic to downgrad...
bea91f195eb27fcaf37706ba18d415b0ff743dd6
3,656,352
import sys import six def cast_env(env): """Encode all the environment values as the appropriate type for each Python version This assumes that all the data is or can be represented as UTF8""" env_type = six.ensure_binary if sys.version_info[0] < 3 else six.ensure_str return {env_type(key): env_type(...
885811983c6ca8732338a68f683e5c0f833820c2
3,656,353
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
import argparse def string_type_check(valid_strings, case_sensitive = True, metavar = None): """ Creates an argparse type for a list of strings. The passed argument is declared valid if it is a valid string which exists in the passed list valid_strings. If case_sensitive is False, all input strings ...
dc2814638d479e2ec5182b0c03ffe95e7379e47c
3,656,357
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 enable_oeenclave_debug(oe_enclave_addr): """For a given OE enclave, load its symbol and enable debug flag for all its TCS""" enclave = oe_debug_enclave_t(oe_enclave_addr) # Check if magic matches if not enclave.is_valid(): return False # No version specific checks. # The contract w...
84de42a5e16adc7f4c40593b299a28b44293ac7d
3,656,359
import os def loadxrmcresult_xmimsim(xmimsimpath, outradix="out", convoluted=False): """XRMC result based on input files converted from XMIMSIM""" xrmcoutpath = os.path.join(xmimsimpath, "xrmc", "output") if convoluted: suffix = "_convoluted" else: suffix = "_lines" return loadxrmc...
dba17556f35415ee43105fcd25378eead32ad8f0
3,656,360
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
def DiffedUpdateItem( Table: TableResource, Key: ItemKey, before: InputItem, after: InputItem, **kwargs ) -> InputItem: """Safe top-level diff update that requires only 'before' and 'after' dicts. By calling this you are trusting that we will make a choice about whether or not you actually have an upda...
e3f8fc9d6ec20a294c7fd04e20dc7b230290ab4a
3,656,376
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 parse_args(argv): """Parse any command line arguments.""" # Set the default logging level to DEBUG # log_level = logging.INFO log_level = logging.DEBUG # This is the dictionary of arguments. arg_dict = {'start_date': DEFAULT_START_DATE, 'end_date': DEFAULT_END_DATE, ...
bf11d7992c6962fe1e52dd82e68d921b9463d9e9
3,656,385
import logging def get_pafy_stream_obj(url,format=None,only_video=False): """This function return stream object from pafy Arguments: url {string} -- The url of the video from youtube Returns: Stream_Obj -- This is a object of Stream class from pafy """ try: obj = ...
bf1b2d360538b4abc9043a87b34eddae65ec8591
3,656,386
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
import os def _resource_path_dev(relative_path): """ :return: Package relative path to resource """ base_path = os.path.dirname(os.path.abspath(__file__)) return os.path.join(base_path, relative_path)
8cdf30f3fa62fb824dcdc70bf9d2627b74f66110
3,656,391
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
import sys def alpha_097(code, end_date=None, fq="pre"): """ 公式: STD(VOLUME,10) Inputs: code: 股票池 end_date: 查询日期 Outputs: 因子的值 """ end_date = to_date_str(end_date) func_name = sys._getframe().f_code.co_name return JQDataClient.instance().get_alpha_191(**l...
5f0a50233502c6162884be015edea2d2fd4bb417
3,656,393
def filter(p): """ 把索引list转换为单词list """ result = [] for idx in p: if idx == stop_tag: break if idx == padding_tag: continue result.append(index_word[idx]) return result
ab79343d3d924bf1b69813d6a32b967bf45f39bd
3,656,394
import sys def get_sequin_annots(sequin_path, ref_contigs, quiet=False): """ Load all genes in the Sequin table as SeqRecords, fetching their sequence data from the reference. ref_contigs is a dictionary of ref contig sequences created with BioPython's SeqIO.to_dict(). For documentation on the Se...
c984b1588ce5a33c3f2711ac14512050a543dd3f
3,656,395
def transformer_decoder_layer(dec_input, enc_output, slf_attn_bias, dec_enc_attn_bias, n_head, d_key, d_value, ...
57367b4aa27da48a1cff5ca24bfcecb36a10c39b
3,656,396
def replace_word_choice(sentence: str, old_word: str, new_word: str) -> str: """Replace a word in the string with another word. :param sentence: str - a sentence to replace words in. :param old_word: str - word to replace :param new_word: str - replacement word :return: str - input sentence with ne...
27d0eae1aa12538c570fec3aa433d59c40556592
3,656,397
def append_slash(url): """Make sure we append a slash at the end of the URL otherwise we have issues with urljoin Example: >>> urlparse.urljoin('http://www.example.com/api/v3', 'user/1/') 'http://www.example.com/api/user/1/' """ if url and not url.endswith('/'): url = '{0}/'.format(url) ...
3d8f009f0f7a2b93e2c9ed3fee593bbcf0f25c4f
3,656,398
def find_cards(thresh_image): """Finds all card-sized contours in a thresholded camera image. Returns the number of cards, and a list of card contours sorted from largest to smallest.""" # Find contours and sort their indices by contour size dummy, cnts, hier = cv2.findContours(thresh_image, cv...
2bf8a0a0ea64de51b34c5826538d591865533353
3,656,399