content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_dcgan_args(parser, args=[]): """ parameters determing the DCGAN parameters """ # DCGAN: # ------------------------------------------------------------------------ parser.add_argument( "--lam", type=float, default=10, help="Factor for scaling gradient penalty" ) parser.add...
28d00721fad62ecbc381190b05d81fe578860f8e
9,443
from pathlib import Path def store_tabular_data(filepath: Path, use_stem: bool = True) -> None: """Reads the tabular data from filepath and stores it in-memory to be plotted asychronously. Args: filepath (Path): The tabular data file to be read and stored. use_stem (bool, optional): Only stor...
98c1c74aefe855690ad67ba0c6f09bd574c877ce
9,445
import pkgutil import io def load_uci_credit_card(return_X_y=False, as_frame=False): """Loads the UCI Credit Card Dataset. This dataset contains a sample of [Default of Credit Card Clients Dataset](https://www.kaggle.com/uciml/default-of-credit-card-clients-dataset). Example: ```python from sko...
ae388efcf82e0e6ff5be40ff5293d0b23d474735
9,446
def quad_lsq(x, y, verbose=False, itmax=200, iparams=[]): """ Fits a parabola to the data, more handy as it fits for parabola parameters in the form y = B_0 * (x - B_1)**2 + B_2. This is computationally slower than poly_lsq, so beware of its usage for time consuming operations. Uses scipy odrpack, b...
02dda2ba78ac6754b913941f2204ef4aa26d3f36
9,447
from typing import Tuple import re def _parse_cli_variable(mapping_str: str) -> Tuple[str, str]: """Checks that the input is of shape `name:value` and then splits it into a tuple""" match = re.match(r"(?P<name>.+?):(?P<value>.+)", mapping_str) if match is None: raise ValueError(f'CLI variable inpu...
f701b7e85c45c2df35e1252721cd3215357909ba
9,449
import json def list_privileges_by_role(request, role): """ List sentry privilegs by role :param request: :param role: role name :return: A Json array of SentryPrivileges: [p1, p2, p3...] """ sentry_privileges = _get_sentry_api(request.user).list_sentry_privileges_by_role("cdap", role) sentry_privileg...
fbb488f6d55b3a51646bc0c74f4861677cc16912
9,450
from typing import Any import torch from typing import Union def to_torch_as(x: Any, y: torch.Tensor) -> Union[Batch, torch.Tensor]: """Return an object without np.ndarray. Same as ``to_torch(x, dtype=y.dtype, device=y.device)``. """ assert isinstance(y, torch.Tensor) return to_torch(x, dtype=y.d...
c6d71e0b903b611653b07e0f55666672dc123602
9,451
def atexit_shutdown_grace_period(grace_period=-1.0): """Return and optionally set the default worker cache shutdown grace period. This only affects the `atexit` behavior of the default context corresponding to :func:`trio_parallel.run_sync`. Existing and future `WorkerContext` instances are unaffected....
f7440172f40b00069b149254a689521373dbded0
9,454
def get_point(points, cmp, axis): """ Get a point based on values of either x or y axys. :cmp: Integer less than or greater than 0, representing respectively < and > singhs. :returns: the index of the point matching the constraints """ index = 0 for i in range(len(points)): if cmp <...
b59035d390e83b45a0131e28c4acf7e302cf3e45
9,456
import pathlib def create_jobs_list(chunks, outdir, *filters): # TO DO # Figure out the packing/unpacking """ Create a list of dictionaries that hold information for the given chunks Arguments: chunks: list: A list of lists. Each nested list contains the filepaths to be processed ...
433992eb34bc1f80d12f8cdcee3dbd99d04d22c1
9,458
import torch def per_symbol_to_per_seq_probs(per_symbol_probs, tgt_out_idx): """ Gather per-symbol probabilities into per-seq probabilities """ # per_symbol_probs shape: batch_size, seq_len, candidate_size # tgt_out_idx shape: batch_size, seq_len # output shape: batch_size, 1 return torch.prod( ...
fc39ac129b8bbffcb602c73bc67fcc44b1d354ed
9,459
def solve_game(payoffs): """ given payoff matrix for a zero-sum normal-form game, return first mixed equilibrium (may be multiple) returns a tuple of numpy arrays """ # .vertex_enumeration() # .lemke_howson(initial_dropped_label=0) - does not return *all* equilibrium game = nash.Game(payoffs) ...
9eb0dd84592f9a2d135c79322f6c812b775b0e74
9,460
from functools import reduce def zone_features(df, zfeatures, aufeatures): """Create zone features from the data Args: df (DataFrame): Input dataframe zfeatures (list): List of zone median features aufeatures (list): List of zone autocorr features Return: 2 dataframes """ ...
fb055e1c2fea040c95422818fbd6d16a97bf873f
9,461
from typing import List def get_active_validator_indices(validators: [ValidatorRecord]) -> List[int]: """ Gets indices of active validators from ``validators``. """ return [i for i, v in enumerate(validators) if is_active_validator(v)]
14719147b49f903240e19fbaa46da8a40315a5cf
9,462
def parse_decodes(sentences, predictions, lengths, label_vocab): """Parse the padding result Args: sentences (list): the tagging sentences. predictions (list): the prediction tags. lengths (list): the valid length of each sentence. label_vocab (dict): the label vocab. Retur...
bf40d8570e0a552853108e860fd193c0d9940e98
9,463
from datetime import datetime def get_weekday(start_date, end_date, weekday_nums, repeat=None): """ 获取一段时间范围内每个周天对应的日期 :param start_date: :param end_date: :param weekday_nums: list, 星期对应数字 0 ~ 6 :param repeat: :return: """ sdate = datetime.datetime.strptime(start_date, date_patter...
65e0495951647cbb6648a3a68d7fd2c7e1e2e88b
9,464
def context_processor(target): """ Decorator that allows context processors with parameters to be assigned (and executed properly) in a RequestContext Example:: return render_to_response( template_name, context_instance=RequestContext( request, processors=[ ...
842395b29aedbfe23bb3332bf343b12d26519d97
9,465
def data_context_path_computation_context_path_comp_serviceuuid_end_pointlocal_id_capacity_bandwidth_profile_committed_burst_size_delete(uuid, local_id): # noqa: E501 """data_context_path_computation_context_path_comp_serviceuuid_end_pointlocal_id_capacity_bandwidth_profile_committed_burst_size_delete removes...
a3bc85df9fa77b210573058b640e47f41930ae0d
9,466
import typing import json def decode_messages(fit_bytes: bytes) -> typing.List[typing.Dict]: """Decode serialized messages. Arguments: fit_bytes: Encoded messages Returns: Decoded messages """ messages = [] for line in fit_bytes.splitlines(): payload = json.loads(lin...
c56a805b5c2ffee3b48be7ae88ad6a91cddd4cc5
9,467
def iresnet101(pretrained=False, progress=True, **kwargs): """ Constructs the IResNet-101 model trained on Glint360K(https://github.com/deepinsight/insightface/tree/master/recognition/partial_fc#4-download). .. note:: The required input size of the model is 112x112. Args: pretrained (b...
d986282b805de959cfa2d6707532d23f1c23c31b
9,469
from typing import Dict def get_full_jwt(user: User) -> Dict: """ Get a full jwt response from the username and uid token. """ return { 'access_token': create_access_token(identity=user, fresh=True), 'refresh_token': create_refresh_token(identity=user) }
bbc4bc12352671878edc392717d58636475001c3
9,470
import re from datetime import datetime def GridSearch_Prophet(prophet_grid, metric='mape'): """ GridSearch tool to determine the optimal parameters for prophet Args: - prophet_grid: List of parameters. Enter it as list(ParameterGrid(prophet_grid) - metric: String. Not used yet. May be us...
324f6468109bfa52258d1ad6645692395be7859a
9,471
def _check_max_features(importances, max_features): """Interpret the max_features value""" n_features = len(importances) if max_features is None: max_features = n_features elif isinstance(max_features, int): max_features = min(n_features, max_features) elif isinstance(max_feature...
816daf9d99ac4ecd2d5024a3be63f793d7669e1f
9,472
def map_blocks(func, data): """Curried version of Dask's map_blocks Args: func: the function to map data: a Dask array Returns: a new Dask array >>> f = map_blocks(lambda x: x + 1) >>> f(da.arange(4, chunks=(2,))) dask.array<lambda, shape=(4,), dtype=int64, chunksize=(2,)> ...
ab97911bb147ceb6d5350fcd16300926d2a89f8e
9,473
def premises_to_syllogism(premises): """ >>> premises_to_syllogism(["Aab", "Ebc"]) 'AE1' """ figure = {"abbc": "1", "bacb": "2", "abcb": "3", "babc": "4"}[premises[0][1:] + premises[1][1:]] return premises[0][0] + premises[1][0] + figure
a048d44acea1eb4c9346880a74547a9cd100ebf0
9,475
import re def fix_fits_keywords(header): """ Update header keyword to change '-' by '_' as columns with '-' are not allowed on SQL """ new_header = {} for key in header.keys(): new_key = key.replace('-', '_') new_header[new_key] = header[key] # Temporary fix - needs to be ...
0d8a2f502252051857a131944a4c31ba8ec9ff0e
9,476
def is_sum_lucky(x, y): """This returns a string describing whether or not the sum of input is lucky This function first makes sure the inputs are valid and then calculates the sum. Then, it will determine a message to return based on whether or not that sum should be considered "lucky" """ if x...
081b5e8cc2657a00ea160e398fb00f84187e2ab6
9,478
import asyncio def unsync_function(func, *args, **kwargs): """Runs an async function in a standard blocking way and returns output""" return asyncio.run(func(*args, **kwargs))
cd7c19bf226b78c9e3c4b19325e7acb4fcc90e21
9,479
from typing import Iterable from typing import Union from typing import List from typing import Tuple from typing import Any from typing import Dict def zip_results(name: str, recipes: Iterable[Recipe], cache=CacheType.Auto) \ -> Recipe[Union[List[Tuple[Any, ...]], Dict[Any, Tuple[Any, ...]]]]: """ Cr...
a1e0b7aa2d5071e485f49b0b7aa43343f8760ab2
9,480
def get_muscle_reference_dictionary(): """ The @article{bashkatov2011optical, title={Optical properties of skin, subcutaneous, and muscle tissues: a review}, author={Bashkatov, Alexey N and Genina, Elina A and Tuchin, Valery V}, journal={Journal of Innovative Op...
b2bcedabce6309a11d0b1f8424ccefc06d7c8dee
9,481
import shlex def smartquotes(text): """ Runs text through pandoc for smartquote correction. This script accepts a paragraph of input and outputs typographically correct text using pandoc. Note line breaks are not retained. """ command = shlex.split('pandoc --smart -t plain') com = Popen(...
bab6ec252495d8e279cdcde7f51f60331117bae2
9,483
def get_nearest_stations_xy(x, y, variable, n=1, stations=None, ignore=None): """find the KNMI stations that measure 'variable' closest to the x, y coordinates Parameters ---------- x : int or float x coordinate in RD y : int or float x coordinate in RD variable : str ...
2d19e64054eb0813919e2a286c686b91e6d0a6f4
9,484
def parseStdInput(): """Obtain a graph by parsing the standard input as per the format specified in the PACE Challange. """ edges = [(1,2),(2,3),(3,4),(4,1)] G = nx.Graph() G.add_edges_from(edges) return G
4e26d50c590321241101586d9e83b2d53c7324ea
9,485
def strfdelta(tdelta, fmt): """ Get a string from a timedelta. """ f, d = Formatter(), {} l = {"D": 86400, "H": 3600, "M": 60, "S": 1} k = list(map(lambda x: x[1], list(f.parse(fmt)))) rem = int(tdelta.total_seconds()) for i in ("D", "H", "M", "S"): if i in k and i in l.keys(): ...
01e7d3678cc88a08ec91e64dd59037294f17d9fe
9,486
def imputation_Y(X, model): """Perform imputation. Don't normalize for depth. Args: X: feature matrix from h5. model: a trained scBasset model. Returns: array: a peak*cell imputed accessibility matrix. Sequencing depth isn't corr...
75e2de758c3544655d4332098d4398255770d7c3
9,488
def format_percent(x, _pos=None): """ plt.gca().yaxis.set_major_formatter(format_percent) """ x = 100 * x if abs(x - round(x)) > 0.05: return r"${:.1f}\%$".format(x) else: return r"${:.0f}\%$".format(x)
27362ffa3b5726c135afdf034208eeca8d7c4f60
9,489
def is_row_and_col_balanced(T1, T2): """ Partial latin squares T1 and T2 are balanced if the symbols appearing in row r of T1 are the same as the symbols appearing in row r of T2, for each r, and if the same condition holds on columns. EXAMPLES:: sage: from sage.combinat.matrices.latin...
f0a9d1522da2fc079d4021603198e79c438de727
9,490
def submit(ds, entry_name, molecule, index): """ Submit an optimization job to a QCArchive server. Parameters ---------- ds : qcportal.collections.OptimizationDataset The QCArchive OptimizationDataset object that this calculation belongs to entry_name : str The base entr...
50a30a25af59906ce5636ce8a176e29befd27d60
9,491
def list_isos(apiclient, **kwargs): """Lists all available ISO files.""" cmd = listIsos.listIsosCmd() [setattr(cmd, k, v) for k, v in kwargs.items()] return(apiclient.listIsos(cmd))
ad3117c6fc2c7bc4543372d306d0d476918d5898
9,492
from .....main import _get_bot from typing import Optional from typing import Union async def edit_message_live_location( token: str = TOKEN_VALIDATION, latitude: float = Query(..., description='Latitude of new location'), longitude: float = Query(..., description='Longitude of new location'), chat_id...
39eef452e570e4b00b08aa66aba6d4253bce154f
9,493
def process_rollout(rollout, gamma, lambda_=1.0): """ given a rollout, compute its returns and the advantage """ batch_si = np.asarray(rollout.states) batch_a = np.asarray(rollout.actions) rewards = np.asarray(rollout.rewards) action_reward = np.concatenate((batch_a,rewards[:,np.newaxis]), a...
da37f8b55294df5204f18772552e72d2131dd072
9,494
async def async_setup_entry(hass, config_entry, async_add_entities): """Add sensors for passed config_entry in HA.""" coordinator: IotawattUpdater = hass.data[DOMAIN][config_entry.entry_id] created = set() @callback def _create_entity(key: str) -> IotaWattSensor: """Create a sensor entity."...
171d65acf5227ed9027481bcc2eb773bee52bbca
9,495
from datetime import datetime import calendar def calculate_cost(cost, working_days_flag, month, nr_of_passes): """Calculate the monthly tolls cost""" if working_days_flag: passes = working_days(month) * nr_of_passes else: now = datetime.datetime.now() passes = calendar.monthrange(...
5221e0dedd56d7d3302aa88cdf9ad7feb67173a3
9,496
def e_dl() -> str: """Fetch size of archives to be downloaded for next system update.""" size = 'Calculating...' with open(file=TMERGE_LOGFILE, mode='r', encoding='utf-8') as log_file: for line in list(log_file)[::-1]: reqex = search(r'(Size of downloads:.)([0-9,]*\s[KMG]iB)', line) ...
1639d6cd0e78ca4f4adfceb75875f6b0de398a63
9,497
def get_model_fn(): """Returns the model definition.""" def model_fn(features, labels, mode, params): """Returns the model function.""" feature = features['feature'] print(feature) labels = labels['label'] one_hot_labels = model_utils.get_label( labels, params, FLAGS.src...
ef006ff79c6979a61a745ebfecd599858ded0418
9,498
def build_node(idx, node_type): """ Build node list :idx: a value to id mapping dict :node_type: a string describe the node type :returns: a list of records of the nodes extracted from the mapping """ return rekey(idx, 'value', 'id:ID', {':LABEL': node_type})
cf9cb20b152aa55ef7f37ee1e2f513d166e2b7c5
9,499
def residual_block(filters, repetitions,kernel_size=(3,3),strides=(2,2), is_first_layer=False): """Builds a residual block with repeating bottleneck blocks. """ def f(input): for i in range(repetitions): init_strides = (1, 1) if i == 0 and not is_first_layer: ...
d3771289e034c4cd06f38caa715c925d7b947ab1
9,500
def vpg_omega(X,Y,Gamma=1, sigma=1, polarIn=False): """ Vorticity distribution for 2D Gaussian vortex patch """ if polarIn: r = X else: r = np.sqrt(X ** 2 + Y ** 2) omega_z = Gamma/(np.pi*sigma) * (np.exp(- r**2/sigma**2)) return omega_z
d7964152c9d21defc395e2a31d8709fe9c5d94c8
9,501
from typing import Tuple def get_outgroup(tree: CassiopeiaTree, triplet: Tuple[str, str, str]) -> str: """Infers the outgroup of a triplet from a CassioepiaTree. Finds the outgroup based on the depth of the latest-common-ancestors of each pair of items. The pair with the deepest LCA is the ingroup a...
c48e7121a8622876b6fb1269f881da4afe9cd8da
9,502
from unittest.mock import call def delete_host(resource_root, host_id): """ Delete a host by id @param resource_root: The root Resource object. @param host_id: Host id @return: The deleted ApiHost object """ return call(resource_root.delete, "%s/%s" % (HOSTS_PATH, host_id), ApiHost)
8d4349c0722517e0f4f8d74ea74b2d74bbc08227
9,503
from typing import Union from typing import Tuple from typing import List def get_preds(model: nn.Module, image: Union[np.array, str], **kwargs) -> Tuple[List]: """ Generated predictions for the given `image` using `model`. """ logger = _get_logger(name=__name__) # load in the image if string is ...
8778f43fd65bccca8fc9372454aba2a7cd2544d5
9,504
def init_w(w, n): """ :purpose: Initialize a weight array consistent of 1s if none is given This is called at the start of each function containing a w param :params: w : a weight vector, if one was given to the initial function, else None NOTE: w MUST be an array of np.float6...
2157f12410c2a909a32f37b9fcae4a489361fb6e
9,507
def _ensure_min_resources(progs, cores, memory, min_memory): """Ensure setting match minimum resources required for used programs. """ for p in progs: if p in min_memory: if not memory or cores * memory < min_memory[p]: memory = float(min_memory[p]) / cores return cor...
f311259242a73a7bc527e3601765c95153a08748
9,508
import ctypes def ctypes_pointer(name): """Create a ctypes type representing a C pointer to a custom data type ``name``.""" return type("c_%s_p" % name, (ctypes.c_void_p,), {})
d87f10ac06391379a24f166272fd42fa938e3676
9,509
def generate_linear_data(n, betas, sigma): """Generate pandas df with x and y variables related by a linear equation. Export data as csv. :param n: Number of observations. :param betas: beta parameters. :param sigma: standard deviation :return: None """ x = np.linspace(start=0.0, stop=1....
2f8b99a3c11ecf75afee51bd5df31f22efaddf58
9,510
def vrotate_3D(vec: np.ndarray, ref: np.ndarray) -> np.ndarray: """Rotates a vector in a 3D space. Returns the rotation matrix for `vec` to match the orientation of a reference vector `ref`. https://math.stackexchange.com/questions/180418/calculate-rotation-matrix-to-align-vector-a-to-...
4cea9d84d8fba2dd5bd9399b83ca9f1aca79b830
9,512
def asymptotic_decay(learning_rate, t, max_iter): """Decay function of the learning process. Parameters ---------- learning_rate : float current learning rate. t : int current iteration. max_iter : int maximum number of iterations for the training. """ return le...
7cc699caed4ddcbde67f5d6e4199fc8479364585
9,513
def get_cell_content(browser, author): """ get novel cells return [cell, cell, cell] """ content = list() cells = browser.find_all(class_='t t2') for cell in cells: if cell.find(class_='r_two').b.string != author: continue for cell_content in cell.find(class_=['tp...
eb498d937b8ffd51ef7805a30940833e09571ed5
9,514
def triangle_area(a, h): """Given length of a side and high return area for a triangle. >>> triangle_area(5, 3) 7.5 """ #[SOLUTION] return a * h / 2.0
9890d5e8332e667fab6dd672f62ca852f6f8f8c0
9,515
from nicos.core import ConfigurationError import urllib import logging def create_mongo_handler(config): """ :param config: configuration dictionary :return: [MongoLogHandler, ] if 'mongo_logger' is in options, else [] """ if hasattr(config, 'mongo_logger'): url = urllib.parse.urlparse(c...
c7ac39574a21c44519ae57c6fb40b8f6ca679311
9,516
def split_and_load(data, ctx_list, batch_axis=0, even_split=True): """Splits an NDArray into `len(ctx_list)` slices along `batch_axis` and loads each slice to one context in `ctx_list`. Parameters ---------- data : NDArray A batch of data. ctx_list : list of Context A list of Co...
4b8f0d1b6b256895da3e37fbb4b1be0cd0da5c46
9,517
def _get_scoped_outputs(comp, g, explicit_outs): """Return a list of output varnames scoped to the given name.""" cnamedot = comp.name + '.' outputs = set() if explicit_outs is None: explicit_outs = () for u,v in g.list_connections(): if u.startswith(cnamedot): outputs.a...
8ff2cfe49dc3d892c4ed4adaeb9300e9395c790b
9,518
def judge_1d100_with_6_ver(target: int, dice: int): """ Judge 1d100 dice result, and return text and color for message. Result is critical, success, failure or fumble. Arguments: target {int} -- target value (ex. skill value) dice {int} -- dice value Returns: message {string}...
f870f6ffee3bb90046eb2f1660e827b899c59f04
9,519
def get_normals(self, indices=None, loc="center"): """Return the array of the normals coordinates. Parameters ---------- self : MeshVTK a MeshVTK object indices : list list of the points to extract (optional) loc : str localization of the normals ("center" or "point") ...
5d08247f70e1012eef7d525ae63f7aebe294e700
9,520
def string_to_weld_literal(s): """ Converts a string to a UTF-8 encoded Weld literal byte-vector. Examples -------- >>> string_to_weld_literal('hello') '[104c,101c,108c,108c,111c]' """ return "[" + ",".join([str(b) + 'c' for b in list(s.encode('utf-8'))]) + "]"
d85b016091988c9307cbed56aafdd5766c3c9be5
9,521
def verify_model_licensed(class_name : str, model_path:str): """ Load a licensed model from HDD """ try : m = eval(class_name).load(model_path) return m except: print(f"Could not load Annotator class={class_name} located in {model_path}. Try updaing spark-nlp-jsl")
057987d838982a85925f70c93ff2f4166b038cec
9,522
def examine_api(api): """Find all style issues in the given parsed API.""" global failures failures = {} for key in sorted(api.keys()): examine_clazz(api[key]) return failures
c94efa9a2be66e30597c63b376adf74bd2ef6462
9,523
def launch(): """ Initialize the module. """ return BinCounterWorker(BinCounter, PT_STATS_RESPONSE, STATS_RESPONSE)
07bfc99731088a8572616aa1cbfbd0be74db5492
9,525
def make_map(source): """Creates a Bokeh figure displaying the source data on a map Args: source: A GeoJSONDataSource object containing bike data Returns: A Bokeh figure with a map displaying the data """ tile_provider = get_provider(Vendors.STAMEN_TERRAIN_RETINA) TOOLTIPS = [ ...
51578186a1fabd071e31e46b20568c23c79bc693
9,526
def rotate_images(images, rot90_scalars=(0, 1, 2, 3)): """Return the input image and its 90, 180, and 270 degree rotations.""" images_rotated = [ images, # 0 degree tf.image.flip_up_down(tf.image.transpose_image(images)), # 90 degrees tf.image.flip_left_right(tf.image.flip_up_down(images)), # 1...
dd151b83918eba9b62a91b499273772e66af6ba9
9,528
def csv(args:[str])->str: """create a string of comma-separated values""" return ','.join(args)
1e48583c236940f2af10f8e050af8ad70ace51f6
9,529
import types def _update_class(oldclass, newclass): """Update a class object.""" # XXX What about __slots__? olddict = oldclass.__dict__ newdict = newclass.__dict__ # PDF changed to remove use of set as not in Jython 2.2 for name in olddict.keys(): if name not in newdict: d...
123eb4eadf7bf6ee65ae5df6ae9ed6df444c25d3
9,530
def mean_by_weekday(day, val): """ Returns a list that contain weekday, mean of beginning and end of presence. """ return [day_abbr[day], mean(val['start']), mean(val['end'])]
8aa7ac3dde83db88b44d2178ba19c5b731af683c
9,533
def parse_metrics(match, key): """Gets the metrics out of the parsed logger stream""" elements = match.split(' ')[1:] elements = filter(lambda x: len(x) > 2, elements) elements = [float(e) for e in elements] metrics = dict(zip(['key', 'precision', 'recall', 'f1'], [key] + elements)) return m...
70de1ad16edfe827e0a851c719d902695696700f
9,534
def minecraftify(clip: vs.VideoNode, div: float = 64.0, mod: int | None = None) -> vs.VideoNode: """ Function that transforms your clip into a Minecraft. Idea from Meme-Maji's Kobayashi memery (love you varde). :param clip: Input clip :param div: How much to divide the clip's resolution with...
4f8338cfe2df8bff8d4f2c7571fa38688e39496c
9,535
def processGOTerm(goTerm): """ In an object representing a GO term, replace single-element lists with their only member. Returns the modified object as a dictionary. """ ret = dict(goTerm) #Input is a defaultdict, might express unexpected behaviour for key, value in ret.items(): if l...
541916a0060726bbc972b784f9a011541e7c8128
9,536
import urllib def searchxapian_show(request): """ zeigt den Inhalt eines Dokumentes """ SORT_BY = { -1: _(u'Relevanz'), 0: _(u'URL'), 1: _(u'Überschrift/Titel'), 2: _(u'Datum der letzten Änderung') } if request.path.find('index.html') < 0: my_path = request.pa...
bd1f252107bfcf2aa02cf58ef6d1a302d71edbd8
9,537
import re def html2plaintext(html, body_id=None, encoding='utf-8'): """ From an HTML text, convert the HTML to plain text. If @param body_id is provided then this is the tag where the body (not necessarily <body>) starts. """ ## (c) Fry-IT, www.fry-it.com, 2007 ## <peter@fry-it.com> ## dow...
70a7af7e557b6cffac05e33a7a394fdccbf7bc84
9,538
def MooreSpace(q): """ Triangulation of the mod `q` Moore space. INPUT: - ``q`` -0 integer, at least 2 This is a simplicial complex with simplices of dimension 0, 1, and 2, such that its reduced homology is isomorphic to `\\ZZ/q\\ZZ` in dimension 1, zero otherwise. If `q=2`, this is...
448e948782d530f6b1ee0909fae02b66606da94d
9,540
def show(tournament_name, params=[], filter_response=True): """Retrieve a single tournament record by `tournament name`""" utils._validate_query_params(params=params, valid_params=VALID_PARAMS, route_type='tournament') uri = TOURNAMENT_PREFIX + tournament_name response = api.get(uri, params) if fi...
d854c97e312a0bd6860a5c7fa7cbd36cd79d4ffd
9,541
from typing import Optional from datetime import datetime def create(arxiv_id: ArXivID, arxiv_ver: int, resource_type: str, resource_id: str, description: str, creator: Optional[str]) -> Relation: """ Create a new relation for an e-print. Parameters ...
e1cbe374bba359b66d8564134ee27ac777c4a16e
9,543
def p_contain_resist(D, t, f_y, f_u=None): """Pressure containment resistance in accordance with DNVGL-ST-F101. (press_contain_resis) Reference: DNVGL-ST-F101 (2017-12) sec:5.4.2.2 eq:5.8 p:94 $p_{b}(t)$ """ if f_u is None: f_cb = f_y else: f_cb = np.minimum(f_y, ...
1c771eebf2ed43115b8ae32405172cd8576d66a2
9,544
def revalue(request): """其它设备参数修改""" value = request.GET.get('value') name = request.GET.get('name') others = Machines().filter_machines(OtherMachineInfo, pk=request.GET.get('dID'))[0] if name == 'remark': others.remark = value elif name == 'machine_name': others.machine_name = v...
0a7ab179932466e171a119c87871e04e2a3ae252
9,545
import authl.handlers.indieauth import json def indieauth_endpoint(): """ IndieAuth token endpoint """ if 'me' in flask.request.args: # A ticket request is being made me_url = flask.request.args['me'] try: endpoint, _ = authl.handlers.indieauth.find_endpoint(me_url, ...
29809af2c243a08b675738b0169bdc794965c934
9,546
def policy_simulation_c(model,var,ages): """ policy simulation for couples""" if var == 'd': return {'hs': lifecycle_c(model,var=var,MA=[0],ST_w=[1,3],ages=ages,calc='sum')['y'][0] + lifecycle_c(model,var=var,MA=[1],ST_h=[1,3],ages=ages,calc='sum')['y'][0], ...
d81ddd950eafb23b8cb219638b358a65084ae08d
9,547
def emit_obj_db_entry(target, source, env): """Emitter for object files. We add each object file built into a global variable for later use""" for t in target: if str(t) is None: continue OBJ_DB.append(t) return target, source
e02c2b4e3f3b1aad15097c6b4701407ef1902b77
9,548
def listtimes(list, c): """multiplies the elements in the list by the given scalar value c""" ret = [] for i in range(0, len(list)): ret.extend([list[i]]*c); return ret;
8aef63677a1a926f355644187d58b47e437e152c
9,549
def split_audio_ixs(n_samples, rate=STEP_SIZE_EM, min_coverage=0.75): """ Create audio,mel slice indices for the audio clip Args: Returns: """ assert 0 < min_coverage <= 1 # Compute how many frames separate two partial utterances samples_per_frame = int((SAMPLING_RATE * WINDOW_STEP_...
d3a71082c9f551dffb5a0457ba79fc3318f6df6a
9,551
def new(w: int, h: int, fmt: str, bg: int) -> 'Image': """ Creates new image by given size and format and fills it with bg color """ if fmt not in ('RGB', 'RGBA', 'L', 'LA'): raise ValueError('invalid format') c = len(fmt) image = Image() image.im = _new_image(w, h, c) lib.im...
c570eab9d62def584a2a12b8a228b30c57cfed76
9,552
def eval_f(f, xs): """Takes a function f = f(x) and a list xs of values that should be used as arguments for f. The function eval_f should apply the function f subsequently to every value x in xs, and return a list fs of function values. I.e. for an input argument xs=[x0, x1, x2,..., xn] the function e...
00c6ed7fc59b213a3ec9fec9feeb3d91b1522061
9,553
def cie94_loss(x1: Tensor, x2: Tensor, squared: bool = False, **kwargs) -> Tensor: """ Computes the L2-norm over all pixels of the CIEDE2000 Color-Difference for two RGB inputs. Parameters ---------- x1 : Tensor: First input. x2 : Tensor: Second input (of size matching x1). ...
1044585ce4cf8158caa3b969a8b94001681815db
9,554
def get_current_user_id() -> str: """ This functions gets the id of the current user that is signed in to the Azure CLI. In order to get this information, it looks like there are two different services, "Microsoft Graph" (developer.microsoft.com/graph) and "Azure AD Graph" (graph.windows.net), the ...
79a557762c9c4c2a6546370f492f879f3f046f67
9,555
def scale_labels(subject_labels): """Saves two lines of code by wrapping up the fitting and transform methods of the LabelEncoder Parameters :param subject_labels: ndarray Label array to be scaled :return: ndarray Scaled label array """ encoder = preprocessing.LabelEncoder() ...
e7c4e4c01f7bc7b43519f1eaf97ff9ce0fda9bbd
9,556
def _get_basemap(grid_metadata_dict): """Creates basemap. M = number of rows in grid M = number of columns in grid :param grid_metadata_dict: Dictionary created by `grids.create_equidistant_grid`. :return: basemap_object: Basemap handle (instance of `mpl_toolkits.basemap.Basemap`)....
caeac576f5a6345378c71e8e0e690f9bafda0995
9,557
import types def unary_math_intr(fn, intrcode): """ Implement the math function *fn* using the LLVM intrinsic *intrcode*. """ @lower(fn, types.Float) def float_impl(context, builder, sig, args): res = call_fp_intrinsic(builder, intrcode, args) return impl_ret_untracked(context, bui...
cd3a4c22dab5ea1776987a717c32fbbc71d75da7
9,558
def is_is_int(a): """Return `True` if `a` is an expression of the form IsInt(b). >>> x = Real('x') >>> is_is_int(IsInt(x)) True >>> is_is_int(x) False """ return is_app_of(a, Kind.IS_INTEGER)
d7565102a228119ba3157e9569495c5531ea5d74
9,559
def getTestSuite(select="unit"): """ Get test suite select is one of the following: "unit" return suite of unit tests only "component" return suite of unit and component tests "all" return suite of unit, component and integration tests "pending" ...
8ea94ad556dd77d28d5abdb2034b51858c996042
9,560
import torch def normalize_channel_wise(tensor: torch.Tensor, mean: torch.Tensor, std: torch.Tensor) -> torch.Tensor: """Normalizes given tensor channel-wise Parameters ---------- tensor: torch.Tensor Tensor to be normalized mean: torch.tensor Mean to be subtracted std: torch....
862a5497d9c4379a974e8e2543acc0c1282faea5
9,561
import tqdm def load_images(shot_paths): """ images = { shot1: { frame_id1: PIL image1, ... }, ... } """ images = list(tqdm(map(load_image, shot_paths), total=len(shot_paths), desc='loading images')) images = {k: v for k, v in images} retur...
4916c68e1b4255d066bc624284cde77036764dd6
9,562
import numpy def rmSingles(fluxcomponent, targetstring='target'): """ Filter out targets in fluxcomponent that have only one ALMA source. """ nindiv = len(fluxcomponent) flagger = numpy.zeros(nindiv) for icomp in range(nindiv): target = fluxcomponent[targetstring][icomp] ...
013d5f3169fd1dcb277733627ecd5b0135bc33fb
9,563