content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import glob import os import fnmatch def parse_directory(path, rgb_prefix='img_', flow_x_prefix='flow_x_', flow_y_prefix='flow_y_'): """ Parse directories holding extracted frames from standard benchmarks """ print('parse frames under folder {}'.format(path)) frame_folders = glob.glob(os.path.join...
5459cbb64686718d6275c1349e2062d5ed277023
20,200
def create_effect( effect_id: CardEffect.EffectId = CardEffect.EffectId.DMG, target: CardLevelEffects.Target = CardLevelEffects.Target.OPPONENT, power: int = 10, range_: float = 5 ) -> Effect: """ Creates effect with given data, or creates default effect dealing dmg to opponent i...
9055250c4ab7db3700b2393c16f54cfef3566747
20,201
def part_two(stream: Stream, violation: int) -> int: """Find the sum of min & max in the sequence that sums to `violation`.""" for start in range(len(stream) - 1): for end in range(start + 2, len(stream) + 1): seq = stream[start:end] seq_sum = sum(seq) if seq_sum == v...
a1481af0183f1e42642a9137242d57fe75738770
20,202
def getDoubleArray(plug): """ Gets the float array from the supplied plug. :type plug: om.MPlug :rtype: om.MDoubleArray """ return om.MFnDoubleArrayData(plug.asMObject()).array()
6e93113d1968a56cb3b12c500be04c554f79c165
20,203
import numpy def get_fb(file_name): """#{{{ load feature file and transform to dict return: dict key_list_feat """ ff = open(file_name, 'r') fb = [] delta = [] fb_matrix = numpy.zeros([1, 24]) delta_matrix = numpy.zeros([1, 24]) fbanks = {} deltas = {} ...
85589f74f47a58f0ba36a438b3340ff0858737e4
20,204
def make_train_input_fn( feature_spec, labels, file_pattern, batch_size, shuffle=True): """Makes an input_fn for training.""" return _make_train_or_eval_input_fn( feature_spec, labels, file_pattern, batch_size, tf.estimator.ModeKeys.TRAIN, shuffle)
1f8d481d5fff1913f392a4286c445af757f849bd
20,205
def _find(xs, predicate): """Locate an item in a list based on a predicate function. Args: xs (list) : List of data predicate (function) : Function taking a data item and returning bool Returns: (object|None) : The first list item that predicate returns True for or None """ ...
94d8dd47e54e1887f67c5f5354d05dc0c294ae52
20,206
from typing import OrderedDict def remove_dataparallel_prefix(state_dict): """Removes dataparallel prefix of layer names in a checkpoint state dictionary.""" new_state_dict = OrderedDict() for k, v in state_dict.items(): name = k[7:] if k[:7] == "module." else k new_state_dict[name] = v ...
28fe85b262f8d4bdefa40d34839787ba1a8ef094
20,207
def user_upload_widget(node, on_complete=''): """Returns a Valum Uploader widget that uploads files based on the user's home directory. :param node: storage type (public or private) and path indicator, e.g. "public:foo/bar" to have the uploaded file go in MEDIA_ROOT/$USERNAME/foo/bar. ...
77a797aaabaf7d3d0f9923e3931e938e568952e0
20,208
def run_lsa(model, lsa_options): """Implements local sensitivity analysis using LSI, RSI, and parameter subset reduction. Parameters ---------- model : Model Object of class Model holding run information. options : Options Object of class Options holding run settings. ...
2a8376f3e287dbeefa8f13321804ef6052357bf5
20,209
def condense_simple_conv3x3(in_channels, out_channels, groups): """ 3x3 version of the CondenseNet specific simple convolution block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Num...
061d0df67fdcf5f3c56f227ca7e53d0fef3e2db2
20,210
def read_data_from(file_: str) -> list: """Read bitmasks and values from file.""" return open(file_, "r").read().splitlines()
ec1bd526d46ee94452df23f92448e60af4d6865c
20,211
def version_for(plugin): # (Plugin) -> Optional[str] """Determine the version of a plugin by its module. :param plugin: The loaded plugin :type plugin: Plugin :returns: version string for the module :rtype: str """ module_name = plugin.plugin.__module__ ...
6d7c4ccc868d11d28c92d1264d52488e22d7f5e5
20,212
import json def choose_organization(): """Allow user to input organization id. Returns: str: Access target id """ target_id = None while not target_id: orgs = None return_code, out, err = utils.run_command([ 'gcloud', 'organizations', 'list', '--format=json']) ...
fa46edc07e45eaa53bb6a52a6f0e7992a836fad7
20,213
def start_server(function): """ Decorator. Tries to call function, if it fails, try to (re)start inotify server. Raise QueryFailed if something went wrong """ def decorated_function(self, *args): result = None try: return function(self, *args) except (OSError,...
e6de74cacb703172ff25c30c8a1bd54937f47d7b
20,214
def get_subscriber_groups(publication_id, subscription_id='', full_uri=False): """This function identifies the subscriber groups for one or more subscriptions within a publication. .. versionchanged:: 3.1.0 Refactored the function to be more efficient. :param publication_id: The ID of the publicati...
e7dd2a052992109a2673dcdbbac388ee0babf7ec
20,215
def get_salutation_from_title(title): """ Described here: https://github.com/VNG-Realisatie/Haal-Centraal-BRP-bevragen/blob/v1.0.0/features/aanhef.feature#L4-L38 """ if title in [BARON, HERTOG, JONKHEER, MARKIES, RIDDER]: return HOOGWELGEBOREN_HEER if title in [BARONES, HERTOGIN, JONKVROUW,...
afbafcf7c2ec2a77b44d2e9aad5930f83d5cc10c
20,216
def hourOfDayNy(dateTime): """ Returns an int value of the hour of the day for a DBDateTime in the New York time zone. The hour is on a 24 hour clock (0 - 23). :param dateTime: (io.deephaven.db.tables.utils.DBDateTime) - The DBDateTime for which to find the hour of the day. :return: (int) A Qu...
eac5db0723bf44162d50a787c56244d5bcb094d9
20,217
def _extract_action_num_and_node_id(m): """Helper method: Extract *action_num* and *node_id* from the given regex match. Convert *action_num* to a 0-indexed integer.""" return dict( action_num=(int(m.group('action_num')) - 1), node_id=m.group('node_id'), )
f1e5f0b81d6d82856b7c00d67270048e0e4caf38
20,218
import re def get_uid_cidx(img_name): """ :param img_name: format output_path / f'{uid} cam{cidx} rgb.png' """ img_name = img_name.split("/")[-1] assert img_name[-8:] == " rgb.png" img_name = img_name[:-8] m = re.search(r'\d+$', img_name) assert not m is None cidx = int(m.group())...
29363f4fc686fa972c2249e5e1db1a333625be36
20,219
def parse_color(hex_color): """Parse color values""" cval = int(hex_color, 16) x = lambda b: ((cval >> b) & 0xff) / 255.0 return {k: x(v) for k, v in dict(r=16, g=8, b=0).iteritems()}
70ca92f7696dd5193730326de141ad30c039f7c6
20,220
def apply_4x4(RT, XYZ): """ RT: B x 4 x 4 XYZ: B x N x 3 """ #RT = RT.to(XYZ.device) B, N, _ = list(XYZ.shape) ones = np.ones([B, N, 1]) XYZ1 = np.concatenate([XYZ, ones], 2) XYZ1_t = np.transpose(XYZ1, 1, 2) # this is B x 4 x N XYZ2_t = np.matmul(RT, XYZ1_t) XYZ2 = np.tr...
b2b2e76a79dbbdf2bc0039fb073a0a6209c9f82d
20,221
def smoothmax(value1, value2, hardness): """ A smooth maximum between two functions. Also referred to as the logsumexp() function. Useful because it's differentiable and preserves convexity! Great writeup by John D Cook here: https://www.johndcook.com/soft_maximum.pdf :param value1: Value of...
60ef9d14b6867aaa205c186309d0c9f53e4edb21
20,222
import os def base_app(instance_path): """Flask application fixture.""" app_ = Flask('testapp', instance_path=instance_path) app_.config.update( SECRET_KEY='SECRET_KEY', SQLALCHEMY_DATABASE_URI=os.environ.get( 'SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'), SQLALCHEMY_...
e4391a35fc92b228b3a1ae425478a9a777f85594
20,223
def udf_con(udf_backend): """ Instance of Client, already connected to the db (if applies). """ return udf_backend.connection
7e95460b4e6808cc148406dfbdb8e952ebb4739a
20,224
from typing import Union from pathlib import Path from typing import Optional def resolve_config(*, config: Union[Path, str]) -> Optional[Path]: """Resolves a config to an absolute Path.""" path = config if isinstance(config, Path) else Path(config) # Is it absolute, or relative to the CWD? if path.e...
4290e46cda385fd60c164af712d28e5e7ad22c83
20,225
def get_default_config() -> DefaultConfig: """ Get the default config. Returns: A dict with the default config. """ images = assets.get_images() return { "static_url": "/static", "favicon_ico": images.favicon_ico.name, "favicon_png": images.favicon_png.name, ...
72685f6bb2a45e03f42d96c82cd0436a826fed68
20,226
import string import re def normalize_elt(elt, alphanum=True): """ Normalize string by removing newlines, punctuation, spaces, and optionally filtering for alphanumeric chars Args: elt (string): string to normalize alphanum (bool, optional, default True): if Tr...
79aad0a7425270b8708598fe5429ecd7c46bffde
20,227
from typing import Tuple from typing import Optional def check_importability(code: str, func_name: str) -> Tuple[bool, Optional[Exception]]: """Very simple check just to see whether the code is at least importable""" try: import_func_from_code( code, func_name, rais...
b7823344bf2ab7055882fb366b0903fcab1a5366
20,228
import torch def compute_q(u, v, omega, k_hat, m_hat, N=100, map_est=False): """ Inputs: u, v - (B,L*2) omega - (L,n) k_hat, m_hat - (B,J) """ B, L = u.size()[0], int(u.size()[1]/2) unique_omega, inverse_idx = torch.unique(omega, dim=0, return_inverse=True) # (J,n), (L) c, s = util...
d8ab2b71a9c149ed3c8e25daa86954c8d24ce79e
20,229
def stationarity(sequence): """ Compute the stationarity of a sequence. A stationary transition is one whose source and destination symbols are the same. The stationarity measures the percentage of transitions to the same location. Parameters ---------- sequence : list A list of ...
39f96d4a07a83ef2c46033dcac9cfaa343747b2f
20,230
def build_nmt_model(Vs, Vt, demb=128, h=128, drop_p=0.5, tied=True, mask=True, attn=True, l2_ratio=1e-4, training=None, rnn_fn='lstm'): """ Builds the target machine translation model. :param demb: Embedding dimension. :param h: Number of hidden units. :param drop_p: Dropout per...
ff3991dab1b4d6e8e5556f064356e1cce1320e78
20,231
from typing import List import json import requests def get_available_tf_versions(include_prerelease: bool = False) -> List[str]: """Return available Terraform versions.""" tf_releases = json.loads( requests.get("https://releases.hashicorp.com/index.json").text )["terraform"] tf_versions = sor...
4be8820bb7cc2b5e5a649b8690fdef3d376a80ed
20,232
def relay_tagged(c, x, tag): """Implementation of tagged for Relay.""" assert tag.is_constant(int) rtag = get_union_ctr(tag.value, None) return rtag(c.ref(x))
b9d97051b3bfe13194a4123ec044e79d53c7587f
20,233
def get_vf(Xf, Nf): """ compute the 1-spectrogram of the projection of a frequency band of the mix at 1 frequency on some directions :param Xf: T x I complex STFT of mix at a given f :param Nf: Mp x Md x I projection matrix :return: Vf: Mp x Ml x Nt magnitude spectrogram of projection...
921bebfb4129f9ae7b0b2d5878c20eb957328c6c
20,234
def gen_data_code(stream, bits=ic.core_opts.data_bits): # type: (ic.Stream, int) -> dict """ Create a similarity preserving ISCC Data-Code with the latest standard algorithm. :param Stream stream: Input data stream. :param int bits: Bit-length of ISCC Data-Code (default 64). :return: ISCC Data-...
ede11d67f305b57a2734cc5898e22102c0db07bb
20,235
import os def file_get_size_in_bytes(path: str) -> int: """Return the size of the file in bytes.""" return int(os.stat(path).st_size)
e9692259d2f5cb8f536cb8c6a0ae53e0b7c6efd1
20,236
def model_fn_builder( bert_config, init_checkpoint, layer_indexes, use_tpu, use_one_hot_embeddings): """Returns `model_fn` closure for TPUEstimator.""" def model_fn(features, labels, mode, params): # pylint: disable=unused-argument """The `model_fn` for TPUEstim...
7a57c1557f4643c738a22b0baf4dbdce0fa06a3a
20,237
def git2pep440(ver_str): """ Converts a git description to a PEP440 conforming string :param ver_str: git version description :return: PEP440 version description """ dash_count = ver_str.count('-') if dash_count == 0: return ver_str elif dash_count == 1: return ver_str.s...
7c4a5185305627c22118722b73b2facfa830875a
20,238
def rejoin(hyphenated, line): """Add hyphenated word part to line start, dehyphenating when required.""" first_part, hyphen = split_hyphen(hyphenated) second_part, rest = split_first_token(line) if is_same_vowel(first_part[-1], second_part[0]): # same vowel before and after hyphen keep_...
ced2bd2b791660e45741997e17ba3bdc0adfad6f
20,239
from typing import Union import zmq def msg_bytes(msg: Union[bytes, bytearray, zmq.Frame]) -> Union[bytes, bytearray]: """Return message frame as bytes. """ return msg.bytes if isinstance(msg, zmq.Frame) else msg
166865f5d51526cf70c767fc90e3d7b474501fb0
20,240
import math def iucr_string(values): """Convert a central value (average) and its s.u. into an IUCr compliant number representation. :param values: pair of central value (average) and s.u. :type values: tuple((float, float)) :return: IUCr compliant representation :rtype: str """ if values...
c6c6602aa0ba481ed5467ed62df59a16f26a8091
20,241
def augment_signals(ds, augment_configs): """ Apply all augmentation methods specified in 'augment_config' and return a dataset where all elements are drawn randomly from the augmented and unaugmented datasets. """ augmented_datasets = [] for conf in augment_configs: aug_kwargs = {k: v for k...
5c07fcaefc277a4190336995440d1380f4263409
20,242
def sse_pack(d): """For sending sse to client. Formats a dictionary into correct form for SSE""" buf = '' for k in ['retry','id','event','data']: if k in d.keys(): buf += '{}: {}\n'.format(k, d[k]) return buf + '\n'
a497c7ab919115d59d49f25abfdb9d88b0963af3
20,243
def proj_beta_model(r2d_kpc, n0, r_c, beta): """ Compute a projected beta model: P(R) = \int n_e dl at given R Parameters ---------- - r2d_kpc: array of projected radius at which to compute integration - n0 : normalization - r_c : core radius parameter - beta : slope of the profile...
1d581d73da98833ca0df33df9de19b7cd71d7164
20,244
def read_raw_datafile(filename): """ Read and format the weather data from one csv file downloaded from the climate.weather.gc.ca website. """ dataset = pd.read_csv(filename, dtype='str') valid_columns = [ 'Date/Time', 'Year', 'Month', 'Day', 'Max Temp (°C)', 'Min Temp (°C)', 'Me...
08d56daa375e3a05d0bca9041c8e973ec80ebe11
20,245
def zeros(shape, backend=TensorFunctions): """ Produce a zero tensor of size `shape`. Args: shape (tuple): shape of tensor backend (:class:`Backend`): tensor backend Returns: :class:`Tensor` : new tensor """ return Tensor.make([0] * int(operators.prod(shape)), shape, back...
1c3115613850819ece6f5a86142e7feb532930e7
20,246
def formatLabels(labels, total_time, time): """Format labels into vector where each value represents a window of time seconds""" time_threshold = 1 num_windows = total_time // time Y = np.zeros(num_windows) for label in labels: start = label['start'] duration = label['duration'] ...
714bfda3c8a997abb9389f74261bcc9aa2fb768b
20,247
import re def line(line_def, **kwargs): """Highlights a character in the line""" def replace(s): return "(%s)" % ansi.aformat(s.group()[1:], attrs=["bold", ]) return ansi.aformat( re.sub('@.?', replace, line_def), **kwargs)
755dee2147f606e57825314642dd35cc713cb9ff
20,248
from datetime import datetime def ceil_datetime_at_minute_interval(timestamp, minute): """ From http://stackoverflow.com/questions/13071384/python-ceil-a-datetime-to-next-quarter-of-an-hour :param timestamp: :type timestamp: datetime.datetime :param minute: :type minute: int :return: ...
7e9522ac8eebdab531d13d842a5018f3813ab86c
20,249
import requests import json def make_response( activated=True, expires_in=0, auto_activation_supported=True, oauth_server=None, DATA=None, ): """ Helper for making ActivationRequirementsResponses with known fields """ DATA = DATA or [] data = { "activated": activated, ...
eaf971695752dfd3d0e4b414d3085c3d60349534
20,250
def post_create_manager_config( api_client, id, log_files=None, configuration_files=None, ports=None, process_manager=None, executables=None, **kwargs ): # noqa: E501 """post_create_manager_config # noqa: E501 Create a new plugin manager configuration. If no params are provide...
c3f27767a6b94604390b683b4169d7ecc54e945f
20,251
import re import os def get_long_desc() -> str: """ read long description and adjust master with version for badges or links only for release versions (x.y.z) """ get_version() release = re.compile(r'(\d+\.){0,2}\d+$') with open(os.path.join(wd, 'README.md')) as fd: if _version == '0.0...
6a2366a7555d654897271a43cf680e7555cc03a1
20,252
def get_current_user(): """Load current user or use anon user.""" return auth.User( uuid=None, login='anon', password='', name='anon', visiblity=None, language=None, last_seen=None, )
2074b73d970e0549726b887e67b9c7b36db6e463
20,253
def validate(number, alphabet='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*'): """Check whether the check digit is valid.""" try: valid = checksum(number, alphabet) == 1 except Exception: # noqa: B902 raise InvalidFormat() if not valid: raise InvalidChecksum() return number
1d521eaa369c6436d8c8cfc93889d769ca15c193
20,254
from typing import Union def pct_chg(x: Union[np.ndarray, pd.Series]) -> np.ndarray: """Percentage change between the current and a prior element. Args: x: A numpy.ndarray or pandas.Series object Returns: A numpy.ndarray with the results """ x = x.astype("float64") if isins...
253a8223c58fa9d89d50c554f54051724961c3bb
20,255
def calc_gram_matrix(input_mat): """ Paper directly mentions about calculating Gram matrix: G_{ij}^l = \sum_k F_{ij}^l F_{jk}^l i and j stand for filter position and k stands for position in each filters. If matrix A is composed of vectors, a1, a2, a3, etc, e.g. A = [a1, a2, a3, ...] note...
386db7deec87127f8c2872e091283fb555611f04
20,256
def parse_annotations_with_food_part_template(annotations, premise): """ """ annotations_aggregated = [] annotations_reported = [] rows_grouped_by_premises = annotations[annotations["premise"] == premise] for hypothesis in rows_grouped_by_premises["hypothesis"].unique(): rows_grouped_by_hy...
1bf17aa605b9ec581ec1379ed0ae7f7340461a19
20,257
def filter_dictionary(dictionary, filter_func): """ returns the first element of `dictionary` where the element's key pass the filter_func. filter_func can be either a callable or a value. - if callable filtering is checked with `test(element_value)` - if value filtering is checked ...
f5fa77a51241323845eb9a59adc9df7f662f287b
20,258
def restart_workflow(workflow_id, clear_data=False, delete_files=False): """Restart a workflow with the latest spec. Clear data allows user to restart the workflow without previous data.""" workflow_model: WorkflowModel = session.query(WorkflowModel).filter_by(id=workflow_id).first() WorkflowProcesso...
70c5df4b31559830c94d01cfb86e9a68070f63b1
20,259
def spike_lmax(S, Q): """Maximum spike given a perturbation""" S2 = S * S return ((1.0 / Q) + S2) * (1 + (1.0 / S2))
ba845e3255e4d3eb5116d279a209f4424062603b
20,260
def get_engine(): """Returns the db engine.""" if not hasattr(g, 'sqlite_engine'): g.sqlite_engine = create_engine('sqlite:///' + app.config['DATABASE'], echo=True) return g.sqlite_engine
579d7110cd27787095c6ede2f25841cbac5e8ca0
20,261
def is_on_curve(point): """Returns True if the given point lies on the elliptic curve.""" if point is None: # None represents the point at infinity. return True x, y = point return (y * y - x * x * x - curve.a * x - curve.b) % curve.p == 0
563d567c7dadc9d23bf6467c4fe30c697b0fd9fa
20,262
from typing import Dict from typing import List from typing import Tuple def find_closest_point( odlc: Dict[str, float], boundary_points: List[Dict[str, float]], obstacles: List[Dict[str, float]], ) -> Tuple[Dict[str, float], List[float]]: """Finds the closest safe point to the ODLC while staying with...
c07f2a1922f5083d9155da12a7273208ae440cf5
20,263
from typing import Tuple from typing import Dict from typing import List def _get_band_edge_indices( band_structure: BandStructure, tol: float = 0.005, ) -> Tuple[Dict[Spin, List[int]], Dict[Spin, List[int]]]: """ Get indices of degenerate band edge states, within a tolerance. Parameters ----...
bd0ed67b879c627c77e35c519dbfcf86890523e1
20,264
import logging import os def make_val_dataloader(data_config, data_path, task=None, data_strct=None): """ Return a data loader for a validation set """ if not "val_data" in data_config or data_config["val_data"] is None: print_rank("Validation data list is not set", loglevel=logging.DEBUG) re...
cbcb53fc3a9f8a27b2c371df693b5abe059d3f37
20,265
def _get_urls(): """Stores the URLs for histology file downloads. Returns ------- dict Dictionary with template names as keys and urls to the files as values. """ return { "fsaverage": "https://box.bic.mni.mcgill.ca/s/znBp7Emls0mMW1a/download", "fsaverage5": "https://box...
697cf29b3caaeda079014fd342fbe7ad4c650d30
20,266
import struct def guid_bytes_to_string(stream): """ Read a byte stream to parse as GUID :ivar bytes stream: GUID in raw mode :returns: GUID as a string :rtype: str """ Data1 = struct.unpack("<I", stream[0:4])[0] Data2 = struct.unpack("<H", stream[4:6])[0] Data3 = struct.unpack("<H"...
23f013b48806d1d2d4b4bec4ab4a5fcf6fc2e6b0
20,267
def thaiword_to_time(text: str, padding: bool = True) -> str: """ Convert Thai time in words into time (H:M). :param str text: Thai time in words :param bool padding: Zero padding the hour if True :return: time string :rtype: str :Example: thaiword_to_time"บ่ายโมงครึ่ง") ...
235874bf252908eeba96f17b2ccc4d7ab32b90ce
20,268
import torch import os import time def _build_index_mappings(name, data_prefix, documents, sizes, num_samples, seq_length, seed): """Build doc-idx, sample-idx, and shuffle-idx. doc-idx: is an array (ordered) of documents to be used in training. sample-idx: is the start document i...
396299fffff56b6edcb1be075561dd4a20f1f326
20,269
import random def get_grains(ng,gdmin,angrange0,angrange1,two_dim): """ Get specified number of grains with conditions of minimum distance and angle range. """ dang = (angrange1-angrange0) /180.0 *np.pi /ng grains= [] ig = 0 dmin = 1e+30 while True: if ig >= ng: break p...
591858e16353d5363767c7816d59f64b890929f8
20,270
from typing import List def two_loops(N: List[int]) -> List[int]: """Semi-dynamic programming approach using O(2n): - Calculate the product of all items before item i - Calculate the product of all items after item i - For each item i, multiply the products for before and after i L[i] = N[i-1] *...
3620aa19833b2e967b2c295fa53ba39bf3b6b70d
20,271
import os import subprocess def make_slurm_queue(dirmain, print_level=0): """get queue list from slurm """ # Check slurm list_ids = [] list_scripts = [] usr = os.environ.get('USER') proc = subprocess.run(['squeue', "-u", usr, "-O", "jobid:.50,name:.150,stdout:.200"], capture_output=True) a...
5ce9da0a90720175d0730a6c8ca099e3f54e3667
20,272
from typing import Union from pathlib import Path from typing import Optional import re def read_renku_version_from_dockerfile(path: Union[Path, str]) -> Optional[str]: """Read RENKU_VERSION from the content of path if a valid version is available.""" path = Path(path) if not path.exists(): return...
9b9c343db6ca0604e04c90cb6a51be9bba3e0b1c
20,273
def zero_mean(framed): """Calculate zero-mean of frames""" mean = np.mean(framed, axis=1) framed = framed - mean[np.newaxis, :].T return framed
f970522327b019cfddc42a5764f9854eaf681378
20,274
def now(): """ 返回当前时间 """ return timezone.now()
86dee41549eeef546f5447ed657eb849c36239cc
20,275
import os def calc_thickness_of_wing(XFOILdirectory, chordArray2): """ calculation wing thickness list """ # open airfoil data data = io_fpa.open2read(os.path.join("data", XFOILdirectory, "foil.dat")) # make airfoil list xlist = [float(i.split()[0]) for i in data[1:]] ylist = [float(i...
67d9b5fa03b9dec00739a3e4e4fffa82a539848c
20,276
def rgb_to_hex(r, g, b): """Turn an RGB float tuple into a hex code. Args: r (float): R value g (float): G value b (float): B value Returns: str: A hex code (no #) """ r_int = round((r + 1.0) / 2 * 255) g_int = round((g + 1.0) / 2 * 255) b_int = round((b + 1...
a5181c475c798bbd03020d81da10d8fbf86cc396
20,277
def calc_R(x,y, xc, yc): """ calculate the distance of each 2D points from the center (xc, yc) """ return np.sqrt((x-xc)**2 + (y-yc)**2)
7a10251f3048a3d7c07f6fd886225b841e19a1a2
20,278
def get_followers_list(user_url, driver, followers=True): """ Returns a list of users who follow or are followed by a user. Parameters ---------- user_url: string driver: selenium.webdriver followers: bool If True, gets users who are followers of this user. If False, gets us...
fbb592c29b66b41b51d67a938659177ead9a13c6
20,279
from typing import Optional def policy_to_dict(player_policy, game, all_states=None, state_to_information_state=None, player_id: Optional = None): """Converts a Policy instance into a tabular policy represented as a dict. This is com...
c5e048d7886dac6b36197c0ee1593f8602972fa5
20,280
import time def compressed_gw(Dist1,Dist2,p1,p2,node_subset1,node_subset2, verbose = False, return_dense = True): """ In: Dist1, Dist2 --- distance matrices of size nxn and mxm p1,p2 --- probability vectors of length n and m node_subset1, node_subset2 --- subsets of point indices. This version o...
7008e62138e2f98238fdba6bf698559690c83972
20,281
import sys def get_stats(service: googleapiclient.discovery, videos_list: list): """Get duration, views and live status of YouTube video with their ID :param service: a YouTube service build with 'googleapiclient.discovery' :param videos_list: list of YouTube video IDs :return items: playlist items (v...
52ec8ccfe10609f175c3ffdd480c9292ad306e90
20,282
import sys def NotecardExceptionInfo(exception): """Construct a formatted Exception string. Args: exception (Exception): An exception object. Returns: string: a summary of the exception with line number and details. """ name = exception.__class__.__name__ return sys.platform ...
bf45535776298a8d0afd326539f9492bfb710a9c
20,283
from typing import Dict from typing import Tuple from typing import List def load_test_dataset(cfg: Dict) -> Tuple[Tuple[List]]: """Read config and load test dataset Args: cfg (Dict): config from config.json Returns: Tuple[Tuple[List]]: Test dataset """ X_test, y_test, test_promp...
b4306f48a927ab0036b5815c5b119480ea4452ba
20,284
import shutil def clear_caches() -> None: """ Clear all Caches created by instagramy in current dir """ return shutil.rmtree(cache_dir, ignore_errors=True)
262cb8117d5987b2b2c7bef6c1f9444061f527a2
20,285
import numpy import warnings def SingleCameraCalibration_from_xml(elem, helper=None): """ loads a camera calibration from an Elementree XML node """ assert ET.iselement(elem) assert elem.tag == "single_camera_calibration" cam_id = elem.find("cam_id").text pmat = numpy.array(numpy.mat(elem.find("ca...
ad9f8d36b82dc3dbf4b3189166e48c0b5304a389
20,286
def contrast_augm_cv2(images,fmin,fmax): """ this function is equivalent to the numpy version, but 2.8x faster """ images = np.copy(images) contr_rnd = rand_state.uniform(low=fmin,high=fmax,size=images.shape[0]) for i in range(images.shape[0]): fac = contr_rnd[i] images[i] = np.a...
7bd56e2b053e0ede33bdd62c269e66858745c642
20,287
def load_preprocess(): """ Load the Preprocessed Training data and return them in batches of <batch_size> or less """ return pickle_load('preprocess.p')
80bf8a509c972291767ade03a64e74aed11b8298
20,288
def detection_layer(config, rois, mrcnn_class, mrcnn_bbox, image_meta): """Takes classified proposal boxes and their bounding box deltas and returns the final detection boxes. Returns: [batch, num_detections, (y1, x1, y2, x2, class_score)] in pixels """ # Currently only supports batchsize 1 ...
7770241c44dc050c0fb20f18b729eba388a47721
20,289
def connectedSocketDiscover(): """ Try to discover the internal address by using a connected UDP socket. @return: a L{Deferred} called with the internal address. """ def cb(address): protocol = DatagramProtocol() listeningPort = reactor.listenUDP(0, protocol) protocol.tr...
a443ef9774774fe4a31cb3f76462d35255380caa
20,290
from typing import Dict from typing import Tuple from typing import List from typing import Optional def construct_source_plate_not_recognised_message( params: Dict[str, str] ) -> Tuple[List[str], Optional[Message]]: """Constructs a message representing a source plate not recognised event; otherwise retur...
73c34f090dcdd802e0161d0f808deb03aef2c660
20,291
def odd(x): """True if x is odd.""" return (x & 1)
9cd383ea01e0fed56f6df42648306cf2415f89e9
20,292
def sparse_transformer_local(): """Set of hyperparameters for a sparse model using only local.""" hparams = common_hparams.basic_params1() hparams.max_length = 4096 hparams.batch_size = 4096 hparams.add_hparam("max_target_length", 4096) hparams.add_hparam("add_timing_signal", False) hparams.add_hparam("lo...
29c4ce03eabc311cc6526d381ff1b09e33cd9667
20,293
import scipy def make_aperture_mask(self, snr_threshold=5, margin=4): """Returns an aperture photometry mask. Parameters ---------- snr_threshold : float Background detection threshold. """ # Find the pixels that are above the threshold in the median flux image median = np.nanmed...
26e176f68155f2d7c8756eb794083e71cd1a920c
20,294
def verify_password(username, password): """Verify the password.""" if username in users: return check_password_hash(users.get(username), password) return False
a41664c6121f9f88522d69d5f2720da94fddc299
20,295
def data_mnist(one_hot=True): """ Preprocess MNIST dataset """ # the data, shuffled and split between train and test sets (X_train, y_train), (X_test, y_test) = mnist.load_data() X_train = X_train.reshape(X_train.shape[0], FLAGS.IMAGE_ROWS, ...
d160d9033acc0e84255cf43faf094d7ecd83e99c
20,296
import glob import os def get_file_paths_by_pattern(pattern='*', folder=None): """Get a file path list matched given pattern. Args: pattern(str): a pattern to match files. folder(str): searching folder. Returns (list of str): a list of matching paths. Examples >>> ge...
467485dd4b162654bd73cf412c93558fa43a5b8e
20,297
def pval_two(n, m, N, Z_all, tau_obs): """ Calculate the p-value of a two sided test. Given a tau_obs value use absolute value to find values more extreme than the observed tau. Parameters ---------- n : int the sum of all subjects in the sample group m : int number of ...
efc1f602d72d71a0270ef2f4c2c2ed8610832d62
20,298
def make_where_tests(options): """Make a set of tests to do where.""" test_parameters = [ { "input_dtype": [tf.float32, tf.int32], "input_shape_set": [([1, 2, 3, 4], [1, 2, 3, 4]),], "use_where_v2": [False, True], }, { "input_dtype": [tf.float32, tf.int32],...
fa10458af3e9043ea5779ff05cb679ef4b798d1b
20,299