content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import binascii def mangleNec(code, freq=40): """Convert NEC code to shorthand notation""" # base time is 550 microseconds # unit of burst time # lead in pattern: 214d 10b3 # "1" burst pattern: 0226 0960 # "0" burst pattern: 0226 0258 # lead out pattern: 0226 2000 # there's large di...
99619206b2470526c1037a28cc8ae05393d88aa2
3,599,306
def _init_bot(bot_type, game, player_id): """Initializes a bot by type.""" rng = np.random.RandomState(FLAGS.seed) if bot_type == "mcts": evaluator = mcts.RandomRolloutEvaluator(FLAGS.rollout_count, rng) return mcts.MCTSBot( game, player_id, FLAGS.uct_c, FLAGS.max_simulatio...
744d2f4adf47f3a2eb59c371c10336d00f8afcb2
3,599,307
def _stacked_separable_conv(net, stride, operation, filter_size): """Takes in an operations and parses it to the correct sep operation.""" num_layers, kernel_size = _operation_to_info(operation) for layer_num in range(num_layers - 1): net = tf.nn.relu(net) net = slim.separable_conv2d( net, ...
182c8fe6910927fe318f53f91bb2b8c25ad857d4
3,599,308
def get_account_by_name(account_name): """ Retrieves an account plus any additional custom fields """ account = Account.query.filter(Account.name == account_name).first() manager_class = account_registry.get(account.account_type.name) account = manager_class()._load(account) db.session.expun...
c4e1a08c7f47a4ba55691904b5d27adc4d156e57
3,599,309
def first_not_none(*args): """ Returns the first argument that is not None. """ for i in args: if i is not None: return i return i
77ad9ecf4136f9a346f35fd0d027250056126f59
3,599,310
def generate_launch_description(): """Fixture for tests.""" return LaunchDescription([ launch.actions.DeclareLaunchArgument( 'example', default_value='example', description='example argument'), ])
02bc929ec9f4185007a3cf8ab08cb1bfec42be55
3,599,311
def fetch_news_info( ticker_list, meta_list=[] ): """Process ticker_list and save news endpoints NOTE: Step1, needs to run as first step Args: ticker_list (:obj:`list` str): list of tickers to fetch news feeds on meta_list (:obj:`list`, optional): special list of index ticke...
4bff2ec9f7c59e7ab52ec97132271f9ceb95b419
3,599,314
def omega(freq): """Angular frequency, omega""" return 2.*np.pi*freq
4f7ed2e29127bef0a3a19fd9886509379fd18955
3,599,315
def _filter3(meta, filter_peak=0.5): """ Filter peak based on the number of cells. """ meta = meta[(meta>0).sum(axis=1)>meta.shape[1]*filter_peak] return meta.T
06842b557422cd63589c63d96ce3b19853357844
3,599,316
from typing import Tuple def create_categorical_encoder_and_decoder(categorical_variables: list[str]) -> Tuple[dict, dict]: """ Given a list of categorical variables, returns an encoder and decoder. Encoder Key = category. Value = integer encoding. Decoder Key = integer encoding. Value = category. ...
70de5c8a3e1667da2776a3750c1fae1edf9fd8ae
3,599,317
def bin_pop_rate(times, senders, binwidth=1.): """ times: spike times senders: associated sender binwidth: how many ms to bin in """ t_min = np.min(times) t_max = np.max(times) N_senders = len(np.unique(senders)) rate, bin_edges = np.histogram(times, np.arange(t_min, t_m...
1880c94bfb665ab087ea01824f5273520d395218
3,599,318
def _sentinel_visitor(path, key, value): """If `value` is a `Sentinel` return the value it represents. Else `default_visit`""" if isinstance(value, Sentinel): return (key, value.retrieve_by_sentinel()) return (key, value)
170ec197e8a882931dfd301e20f7877fb05b9624
3,599,319
def render(filename, context): """ template.render(filename, context) -> rendered html filename is location of the template relative to template.TEMPLATES_DIR context is a dictionary of values to give to the template Raises an error if template is invalid """ template = parser.Template(open(TEMPLATES_DIR + '...
368ddd01d3d24f62355318a502c71e705a7e027a
3,599,320
def find_bb_centre( x: "np.ndarray", y: "np.ndarray", image: "np.ndarray", bb_diameter: float, edge_lengths: TwoNumbers, penumbra: float, field_centre: TwoNumbers, field_rotation: float, bb_repeats: int = DEFAULT_BB_REPEATS, bb_consistency_tol: float = DEFAULT_BB_CONSISTENCY_TOL,...
60198b68355a3ce81d873c28702ce0f45fcc0683
3,599,321
def cf_NIG(u, t=1, mu=0, theta=-0.1, sigma=0.2, kappa=0.1): """ Characteristic function of a Normal Inverse Gaussian random variable at time t mu: additional drift theta: Brownian motion drift sigma: Brownian motion diffusion kappa: Inverse Gaussian process variance """ return np.ex...
9237bc40462f7b365ca6f8f95b463ecc2a4f576a
3,599,322
def update_dependencies(new_dependencies, existing_dependencies): """Update the source package's existing dependencies. When a user passes additional dependencies from the command line, these dependencies will be added to the source package's existing dependencies. If the dependencies passed from the c...
7f520c0c980cd0b929be32d9d4cceb8c99f75934
3,599,323
def zeta_real(s): """ zeta function for a real positive value s. zeta(s) = \sum n^{-s} = \prod (1 - p^{-s})^{-1} """ zeta_s = 1 for p in prime.generator(): euler_factor = 1 - 1/p**s if euler_factor == 1: break zeta_s /= euler_factor return zeta_s
f548b0c922893d590973bb906b9add7d8abb8135
3,599,324
def do_compress(data, pid): """ this *must* succeed adding the pdf""" try: # compress data = pdf_compress(data) except: pass db = get_mongo('paper') db.update({'_id': pid}, {'$set': {'pdf': Binary(data)}} ) log_info("Updated pdf {0}: size={1}".format( pid, parse_...
9b5d58cd6b3fb74922fa25a3207c11055ae80d24
3,599,325
def dask_client(request): """ This fixture is meant to be called one per pytest session. The goal of this function is to create a global client at the start of the testing phase. We can create clients at the start of the session (this case, as above scope is session), module, class or function l...
3aa97336a26fc13cd8712234248d4e29f393a244
3,599,326
def BuildService(credentials=None): """Build the directory api service. Args: credentials: Optional credentials to use instead of any in the datastore. Returns: service object for interacting with the directory api Raises: Exception: An exception that that the PEM file content is not valid. """...
48c5c84417d99c8b3ea9d867a1d7bf9fa61263ca
3,599,327
def norm_xcorr(a, v): """ Compute the normalized cross-correlation (lag plot) args a : time series #1 v : time series #2 returns normlized cross correlation (where 1.0 is 100% correlated) """ a = (a - np.mean(a)) / (np.std(a) * len(a)) v = (v - np.mean(v)) / np.std...
1d7aa0d9857a91e234b681b963ebb163afb356fd
3,599,328
def get_modules(model_params, action_spec): """Get agent modules.""" model_params, n_q_fns = model_params if len(model_params) == 1: model_params = tuple([model_params[0]] * 2) elif len(model_params) < 2: raise ValueError('Bad model parameters %s.' % model_params) def q_net_factory(): return netwo...
1a266420496dc8da6b0a763379a4f5f95c6be57f
3,599,329
def hidden50(**kwargs): """Constructs a ResNet-50 model. """ model = Hidden(2304,2304,2) return model
bdc0cc3a86412b0e34cba8bc99841a82ea1b56f2
3,599,331
import functools def trace_info(tmpdir_factory): """Return a TracedCommand that uses temporary directories. """ remote_dir = str(tmpdir_factory.mktemp("remote")) local_dir = str(tmpdir_factory.mktemp("local")) cls = functools.partial(TracedCommand, remote_dir=remote_dir...
f8351290e729f3df83e11dc3eb9b977910fd8c2e
3,599,333
def long_decrypt(s, kx, spice, blocksize, lmask=None): """ Decryption of Long Subciphers (128 < blocksize < 513) """ if not lmask: lmask = (1 << 64) - 1 for cycle_num in reversed(range(1 + BACKUP + BACKUPSUBCIPHER[4])): for i in range(len(s)-1): s[i] = m_sub(s[i], kx[(blocksize&255)+8+...
017a8d2ee64fee2be597b6ff10f7d189875f3e24
3,599,334
from datetime import datetime def hfeed(value, arg=None, autoescape=None): """ Formats a value to conform with the hFeed Microformat fragment Inspired by the markup found here: http://microformats.org/wiki/hatom-examples """ if isinstance(value, datetime.datetime) or isinstance(value, st...
1db040228d3bdbab4f3939889585832ba700b199
3,599,335
def read_brecon(infile, tree, stree): """ Reads branch reconciliation from file """ brecon = {} for line in infile: tokens = line.rstrip().split("\t") # parse node node_name = tokens[0] if node_name.isdigit(): node_name = int(node_name) node = t...
366295c2196df5c45bae9d8a59d068814285b168
3,599,336
import logging def get_VGG16_model(input_shape: list, model_path: str) -> tf.keras.models.Model: """saving and returning the base model extracted from VGG16 model Args: input_shape (list): shape of the input image model_path (str): path to save the base model Returns: tf.keras...
2a5367b52fa43560e37c7c9fb40ec0e269f0088c
3,599,337
def _convert_to_int_list(check_codes): """Takes a comma-separated string or list of strings and converts to list of ints. Args: check_codes: comma-separated string or list of strings Returns: list: the check codes as a list of integers Raises: ValueError: if conversion fails ...
965a68466d0aab358043cedb4838ac9d99ce3249
3,599,339
import collections def _build_personalize_fn(optimizer_fn): """Builds a personalization function given an optimizer constructor.""" optimizer = optimizer_fn() @tf.function def personalize_fn(model, train_data, test_data, context=None): def train_fn(num_examples_sum, batch): """Runs gradient descen...
14e8d4df295f77e7f4b5beeb657cebf0b4aae2b7
3,599,340
from typing import Optional def analize_variadic_generic( ctx: AnalyzeTypeContext, validate_callback: Optional[_ValidateCallback] = None, ) -> MypyType: """ Variadic generic support. What is "variadic generic"? It is a generic type with any amount of type variables. Starting with 0 up to ...
e072788ba599bd0b58627f83f2eadcae7394ddf7
3,599,341
def _get_functions(expr, ldelim="(", rdelim=")"): """Parse function calls.""" tpars = _pair_delims(expr, ldelim=ldelim, rdelim=rdelim) alphas = "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" fchars = "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789" "_" tfuncs = [] ...
1b6d5ee905275b5da01fb26032c1afdbd2fd1265
3,599,342
import xml def CreateUIActionList(actions_per_command, num_commands, given_seed=None): """Generate user-like pseudo-random action sequences. Args: actions_per_command: length of each ui action sequence. num_commands: number of sequences to generate. seed: optional rand seed for this list. Returns:...
09bd3e983e5e53ea05ae7db436e3b9e9a4bc95c2
3,599,343
def get_note_freq(p): """ Return the frequency corresponding to a particular note number Parameters ---------- p: int Note number, in halfsteps. 0 is a concert a """ return 440*2**(p/12)
cec12355f481494fa53fb0ed535ecd82fd038016
3,599,345
import pickle def main(refs,sys_outs,out_file): """ inputs:: refs: a txt file with a list of labels for each wav-fileid in the format: <id> <label> sys_outs: a txt file with a list of scores (probability of being covid positive) for each wav-fileid in the format: <id> <score> threshold (optional):...
7aaa0adbca42771bd0c7b9befbe7569e78453098
3,599,346
def eval_dfcell(cell_value): """ Returns None if cell is NaN else, the value """ if dfcell_is_empty(cell_value): return None return cell_value
9d7789f25b776c0b9c807d49c974a165eaf95594
3,599,347
def stringify_parameters(items): """ Convert all items in list to string. """ return [str(item) for item in items]
41a47f611d1514043eeac27de6c8be6c01607649
3,599,349
def count_missing(genotypes, axis=None): """Count non-missing genotype calls. Parameters ---------- genotypes : array_like, int An array of shape (n_variants, n_samples, ploidy) or (n_variants, ploidy) or (n_samples, ploidy), where each element of the array is an integer corres...
d15bac11ed2a7fd2d64d80a9f54095040020685a
3,599,350
def get_current_spec_list(ctx): """ Get the current spec list, either from -p/--project-specs or --specs-to-include-in-project-generation or specs_to_include_in_project_generation in user_settings.options :param ctx: Current context :return: The current spec list """ try: return ctx....
e0e2788b86bf005b6986ab84f507d784ef837cca
3,599,351
import torch def inner_prod(x, y): """A function that returns the inner product of two complex vectors, x and y (<x|y>). :param x: A complex vector. :type x: torch.Tensor :param y: A complex vector. :type y: torch.Tensor :raises ValueError: If x and y are not complex vectors with their f...
e89d97845941f09120272669eb09a882fba90fed
3,599,352
def kpt_mapping_back(kpts, img_shape, scale_factor, flip): """Map bboxes from testing scale to original image scale""" new_kpts = kpt_flip(kpts, img_shape) if flip else kpts new_kpts = new_kpts / scale_factor return new_kpts
336f1d0c679c45ee363438aa4883ff45f734e9bc
3,599,353
def get_Emission_Likelihoods(tHMMobj, E: list = None) -> list: """ Emission Likelihood (EL) matrix. Each element in this N by K matrix represents the probability :math:`P(x_n = x | z_n = k)`, for all :math:`x_n` and :math:`z_n` in our observed and hidden state tree and for all possible discre...
5b0569acbc45bb11c46226784a43770598d701f8
3,599,354
import requests import json def retrieve_user_name_from_user_id(user_id): """Return a user name given a user ID. """ url = '{0}/api/3/users/{1}'.format(BASE_URL, user_id) response = requests.get(url, auth=AUTH, headers=generate_headers()) if response.status_code != 200: print("[-] User ID...
f720753072fa1d7e22233ec41f350231b8d64874
3,599,355
def title_from_name(name): """ Create a title from an attribute name. """ def _(): """ Generator to convert parts of title """ try: int(name) yield 'Item #%s'% name return except ValueError: pass it = iter(n...
44182a7aefc552701517292563717884835230aa
3,599,357
def check_address_exists_pc(request, list_id): """ 检测地址池是否在母子账户中。 """ try: MailList.objects.get(id=list_id, customer=request.user) return True except: try: MailList.objects.get(id=list_id, user=request.user.parent) return True except: r...
e34bd02b5384eb1e36c35dd1102d2d53042bbf0a
3,599,358
def parse_subexp( pattern: str, timings: list[str], args: list[str] ) -> tuple[str, list[RuleDef]]: """Parse a susecion of o or more consecutive rules.""" subexp: list[RuleDef] = [] while pattern: pattern, rule = parse_rule(pattern, timings, args) if rule is not None: sube...
c9f64e5ac3100cd2bd9fca24a60e884ec2a73d75
3,599,359
def sort_reagents(gras): """ Sort reagents by size, from largest to smallest :param gras: the reagent (i.e. reactant or product) graphs :returns: the reagent graphs, in sorted order """ gras = tuple(gras) idxs = argsort_reagents(gras) gras = tuple(map(gras.__getitem__, idxs)) return gra...
a59d8f815ec0d9caf1f99243c6fd214b3c1c579f
3,599,360
def fill_empties(abstract): """Fill empty cells in the abstraction The way the row patterns are constructed assumes that empty cells are marked by the letter `C` as well. This function fill those in. The function also removes duplicate occurrances of ``CC`` and replaces these with ``C``. P...
cc27354fd50ac8588c8374e06025a2ceeff691c6
3,599,362
def normal_shock_density_ratio(M, gamma): """GIves the normal shock density ratio as a function of upstream Mach number.""" return ((gamma+1.0)*M**2.0)/(2.0+(gamma-1.0)*M**2.0)
780e435602278f02d3a1839f460edf1ce40a5a5a
3,599,363
def garage_door(): """Opens the garage door and takes a picture to show state""" date_string = time.strftime("%Y-%m-%d-%H:%M:%S") GPIO.setmode(GPIO.BCM) GPIO.setup(24, GPIO.OUT) GPIO.setup(25, GPIO.OUT) GPIO.setup(23, GPIO.IN) # activate input with PullUp GPIO.setup(23, GPIO.IN, pull_...
690d0633f93e43de2b8d66801822b54db11d398a
3,599,364
import pandas def fast_api_query(client=None, url=None, name=None, team=None, project=None, version=None, password=None, as_df=False): """ Retrieves the list of dataframe based on partial information. :param client: for unittest purpose :param url: API url (can b...
f6c289a5fec0dde98e363d83b7eda9aa42a179c8
3,599,365
def _corrupt_contrast(image, mask): """Randomly applies a random contrast change.""" cond_contrast = tf.cast(tf.random_uniform( [], maxval=2, dtype=tf.int32), tf.bool) image = tf.cond(cond_contrast, lambda: tf.image.random_contrast( image, 0.2, 1.8), lambda: tf.identity(image)) return im...
1bfd28a0b8008ae41c0aba794af8a0b4f19b0305
3,599,366
import time import http import urllib import json def get_verifycode(): """ 获取验证码 """ # 获取当前时间戳 timestamp = time.time() url = 'http://newxk.urp.seu.edu.cn/xsxkapp/sys/xsxkapp/student/4/vcode.do?timestamp=' + \ str(int(timestamp)) # global vtoken # 创建cooliejar对象 cookie = htt...
668a41f3779d5d6e2e606ebf1b6860ec731329e1
3,599,367
def _find_ebcdic_codec(code_name): """ The `codec.CodecInfo` matching `codec_name` provided it is part of the package, otherwise `None`. """ return _codec_name_to_info_map.get(code_name)
c4370c76cdeaf2025af153602fcdd276ad00f74c
3,599,368
def get_default_out() -> tuple[str, str, str]: """To return private default values. Returns: Returns three strings. The first describes the default string for describing the purchase price. The second the default string for the sum of all sales taxes of the purchase and the third the de...
ca04785570be033d3ca176425ab0103d8e2e5e38
3,599,369
def my_train_k(): """交易训练页面""" return render_template("train_k.html")
267360cd4cf4e624be126f22b51a08df49657509
3,599,370
def np_json_value(x): """Ensures values are json compabible.""" if np.isnan(x): return None else: return str(x)
151c8c45ab79afc46d652f9a60180d729d0705a0
3,599,371
def run_with_PI_exploration(PI=None, exploration=0.2, N_Iter = 100, render_flag=False): """ Return buff_df if done, otherwise return None """ if PI is None: # No PI, action will be determined fully randomly exploration = 1.0 s = flake.reset() if render_flag: flake.render() ...
cb1d4898a71b76c8f39934c565019ef5d7e3fde7
3,599,372
import configparser def aws(): """Read and parse config file and create AWS API connection.""" config = configparser.ConfigParser() config.read('config.ini') config.sections() my_config = Config(region_name=config['aws']['region'], signature_version='v4', ...
5753e14e8df32956eb8e3a983f714b9345033ab0
3,599,373
def rfc822date(text): """:rfc822date: Date. Returns a date using the same format used in email headers: "Tue, 18 Aug 2009 13:00:13 +0200". """ return util.datestr(text, "%a, %d %b %Y %H:%M:%S %1%2")
7af6e856c2b906ec39d76e0f997faab414f9cbab
3,599,374
def pretty_print(state): """ Returns a 3x3 string matrix representing the given state. """ assert len(state) == 9 str_state = [str(i) for i in state] lines = [' '.join(map(str, l)) for l in [state[:3], state[3:6], state[6:]]] return '\n'.join(lines)
67fb7b091e7256d1fa71f2936d3c8989d5a90f0e
3,599,375
def get_rules_packages(opts=None): """ The AWS Inspector Rules Packages data source allows access to the list of AWS Inspector Rules Packages which can be used by AWS Inspector within the region configured in the provider. """ __args__ = dict() if opts is None: opts = pulumi.Invoke...
20b611e8082c853108ff098b0428ee7fa002874a
3,599,376
import time import torch def validate(Dataset, model, criterion, epoch, writer, device, args): """ Evaluates/validates the model Parameters: Dataset (torch.utils.data.Dataset): The dataset model (torch.nn.module): Model to be evaluated/validated criterion (torch.nn.criterion): Los...
a2165748647062a7882464968e3fceedde310a4d
3,599,377
def make_df(nrow: int, ncol: int) -> pd.DataFrame: """make toy DataFrame""" df = pd.DataFrame(np.random.randint(100_000, 1_000_000, size=(nrow, ncol)), columns=[f'col{i}' for i in range(ncol)]).astype(float) return df
8aab14f9e0673f989befc203c78bdb512cbb5b28
3,599,378
import requests def user_info(handles): """ Returns information about one or several users. Return value: Returns a list of User objects for requested handles. Parameter: - handles (Required): Semicolon-separated list of handles. No more than 10000 handles is a...
690dbe93d3693389ef62fa19d0a678b44d69bf72
3,599,379
def field_output_format(override=None, field_name=None): """ Decorator in charge of giving the output its correct format, either json or pandas Parameters ---------- func: function The function to be decorated override: str Override the internal format of the call, default n...
5b3134c000aed03aaae21001ae2cc74e325607f3
3,599,380
def time_difference(dataset, since, until): """ For the given dataset returns dataframe with time differences between measurements of buses' locations. :param dataset: List of pandas.DataFrames, each corresponding to one moment of time. Each of these dataframes should have columns: "Lines", "Lon", "VehicleN...
82e2540cbeb278b2f0a37ccb54ae840d62dbfc54
3,599,381
def dask_detrend_data(data, output_arr): """ Detrend data using a linear fit. Parameters ---------- data: dask.array Input dataset to detrend. Assumes leading axis is sampling dimension. output_arr: ndarray-like Output array with same shape as data to store detrended data. ...
db8cb60e3a4c2cf87a44eb53a559715734fb442a
3,599,382
def I_props(D, B, TF, TW, ETABS=True): """Properties of an I-section >>> I_props(12, 15, 3, 2) {'P': 74, 'A': 90, 'Avy': 72, 'Avz': 30, 'Iyy': 2767.5, 'Izz': 858.0} """ A = B*D - (B-TW)*(D-2*TF) Iyy = B*D**3/12 - (B-TW)*(D-2*TF)**3/12 Zyy = 2 * Iyy / D Syy = B * TF * (D - TF) + 0.25 * TW...
c10d8c0e0bf65bfa17d4b29250d42db30466eccc
3,599,383
import ssl def get_server_context(verify=True): """Our TLS configuration for the server""" server_ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) server_ctx.set_ecdh_curve('prime256v1') server_ctx.verify_mode = ssl.CERT_OPTIONAL if not verify else ssl.CERT_REQUIRED server_ctx.set_ciphers(CIPHERS) ...
f12b26246d76e1244c7cd068a75f4b5d16ae07ee
3,599,384
def listofilesuploaded(currentuser): """ Function to return list of files uploaded by a user. """ session=DBSession() files=session.query(Filedetails).filter_by(userid=currentuser.userid) listoffiles=[] for i in files: filedata={} filedata['fileid']=i.fileid filedata[...
5cb6a0da1838436c9bf5b5e50abcc99e222157bc
3,599,385
def statistic(current): """ Categorize and count the samples Return an numpy.record whose dtype=[('x',int),('f',int)]""" samprob = {} for x in current: xind = state2ind(x) if xind in samprob: samprob[xind] += 1 else: samprob[xind] =1 memory = [(x, samprob[x]) for x in samprob] memory = np.asarray(memo...
35282e1d91284dd0b5735aab7ed36d8802619888
3,599,386
def traceroute(params): """ Execute some `traceroute` commands via subprocess. Args: params ([TracerouteParams]): params for the `traceroute` commands Returns: [TracerouteResult]: stats from the executed `traceroute` commands """ return subprocess_workflow.exec_and_parse_subpro...
fe8407a0a2b56ee38eea2031ce3236ae6fb1511e
3,599,388
def load_fourier_spectrum(fname): """Load Fourier amplitude spectrum file created by fas_drvr.exe. Inputs ------ fname : string File name of the data file Returns ------- event : dict Dictionary containing the event """ assert fname.endswith('_fs.col') rows = np...
7c9b1bc9c62d7d4f84344533e579ea3972503749
3,599,389
from typing import List from typing import Dict from typing import Any def expand_decks_list( decks: List[Dict[str, Any]], deck_info: Dict[str, Any], ) -> List[Dict[str, Any]]: """ Given a list of decks and their cards, fills in the missing information using the detailed decks specification """ ...
1a50f5c2ba461be54605cf7637d64a8257200494
3,599,390
import json def decode_req_encode_rsp(f): """Decorator to decode incoming requests and encode responses.""" def decode_inner(req): return json.dumps(f(json.loads(req))) return decode_inner
ee41df3de3c41fbe2f32ddf4a07e769abfe31fda
3,599,391
def jamieson_pth(v, v0, c0, s, gamma0, q, theta0, n, z, mass, c_v, three_r=3. * constants.R, t_ref=300.): """ calculate thermal pressure from Hugoniot data using the constq formulation :param v: unit-cell volume in A^3 :param v0: unit-cell volume in A^3 at 1 bar :param c0: velo...
55c662c60a5cdcbc6bae1deaafb17afb1f2b8eeb
3,599,392
def init_circuit(state: QuantumCircuit | Statevector) -> QuantumCircuit: """Initialize state.""" if isinstance(state, QuantumCircuit): return state if not isinstance(state, Statevector): state = Statevector(state) qc = QuantumCircuit(state.num_qubits) qc.append(Initialize(state), qar...
318967530295d80861186055554f9a7f4c000b0a
3,599,393
def vinth2p(datai, hbcofa, hbcofb, plevo, psfc, intyp, p0, ii, kxtrp): """ Interpolates CCSM hybrid coordinates to pressure coordinates. A multi-dimensional NumPy array of the same shape as datai is returned, except that the input level coordinate is replaced by plevo. array = Ngl.vinth2p(datai, hbcofa, hbcofb, ple...
50164358db897412d3fe7df9434223c9f1ced65a
3,599,394
import re def find_images(document): """Returns the list of image filepaths used by the `document`.""" images = [] for line in document: match = re.match(r"\.\. image::\s+(img\/.+)", line) if match: images.append(match[1]) return list(set(images))
2c58b04974f5ec0d1752cb405cfd314de81a841c
3,599,395
import html def card_cutouts(data): """ Add a card containing cutouts Parameters ---------- data: java.util.TreeMap Results from a HBase client query Returns ---------- card: dbc.Card Card with the cutouts drawn inside """ card = dbc.Card( dbc.CardBody( ...
2a568fa6416d70ce5d423c40d0ecc6f38af946f0
3,599,396
from datetime import datetime def _read_time_from_string(str1): """ Reads the time from a string in the format HH:MM:SS.S and returns :class: datetime.time """ full_time = [float(x) for x in str1.split(':')] hour = int(full_time[0]) minute = int(full_time[1]) if full_time[2] > 59.99: ...
d876c47b60827acfd7fba05794124136734be017
3,599,397
def extract_kwargs_from_ctx(ctx): """ Extracts kwargs from Click context manager. """ args = [] i = 0 for arg in ctx.args: if arg[:2] == '--': args.append([arg[2:]]) i += 1 else: args[(i-1)].append(arg) for i, arg in enumerate(args): if le...
678a819daf33a26c599cea08817397741bfbef8a
3,599,398
def load_config(cfgfile): """ Parses a configuration file """ cfgf = open(cfgfile,'r') cfg = {} for l in cfgf: ps = [p.strip() for p in l.split(':')] if len(ps)==2: try: cfg[ps[0]] = float(ps[1]) except ValueError: cfg[ps[0]] = ps[...
283a36f1d92c58b0018fe62714cc9dc23f96c898
3,599,399
def xsec_NSI(E_R, E_nu, A, Z, Eps_u_e, Eps_d_e, Eps_u_mu=0, Eps_d_mu=0, Eps_u_tau=0, Eps_d_tau=0): """ Calculates the differential cross section for Coherent Elastic Neutrino-Nucleus Scattering including Non-standard Neutrino interactions (NSI) Parameters ---------- E_R : float ...
e39c48e5ff1c0e8cf9b165a6b54d0f902bd0c440
3,599,400
def gen_callbacks(***kwargs): """ A callback is a set of functions to be applied at given stages of the training procedure. Use callbacks to get a view on internal states and statistics of the model during training. """ #args filepath = kwargs['filepath'] monitor = kwargs[...
6d8b5dd7c7f99865698820cc296caf37ea18591e
3,599,401
def read_wav(fname, verbose=None): """Read in a WAV file Parameters ---------- fname : str Filename to load. verbose : bool, str, int, or None If not None, override default verbose level. Returns ------- data : array The WAV file data. Will be of datatype np.flo...
2f21c125dd735b5b2a5ed1fde30fbfd48159ae07
3,599,402
def gradient_norm_func(A, theta): """ Returns the 2 norm of the gradient vector (more precisely, 2 norm of 1/2 of the gradient vector). """ return np.linalg.norm(trig.trig_grad(A, theta))
77c7b660a8f4941bc189c1e9e4d9821701a954ec
3,599,403
import pandas import scipy import numpy def scan_preprocessing_outlier(inp): """ LOESS outlier handling. Outlier detection and removing for LOESS procedure. Parameters ---------- inp : dict Method dictionary. Returns ------- inp : dict Method dictionary. """ ...
1a090286d4ff38fa3e692323a6ae6aa2a145f3b1
3,599,404
def get_all_rois_from_folder_v2( gc, folderid, get_all_rois_kwargs, monitor=''): """Get all rois in a girder folder using get_all_rois_from_slide_v2(). Parameters ---------- gc : girder_client.Girder_Client authenticated girder client folderid : str girder id of folder g...
5490b6fce217818dcb2d22cf0d51237d5db63f00
3,599,405
def rotate(A, turns=1): """A matrix which is formed by rotating the given matrix, n times, in clockwise sense. Args ---- A (compulsory) A matrix. turns (int, optional) The number of turns to rotate the matrix. Defaults to 1. Returns ------- Matrix The matrix obt...
c6fb428c15317b314443101093ec96019be52bfa
3,599,407
from pathlib import Path import yaml def read_config(config_file: Path="./config.yaml"): """ Reads the configuration file :param config_file: :return: """ with open(config_file) as file: context = yaml.load(file, Loader=yaml.FullLoader) return Box(context, default_box=True)
fb2fb0d1253d85a806d2f4020c4b4d347f94ec88
3,599,408
def distance(a, b): """ Clockwise distance Based on the globally defined key size in bits -- k. Max node id is 2 to the power of k. """ if a==b: return 0 elif a<b: return b-a; else: return (2**NUM_KEY_BITS)+(b-a);
3680f98df5dacb8a0fee08469feb0050ea5f9ecd
3,599,409
import time import logging import traceback def run_selected_algorithm(timeseries, metric_name): """ Filter timeseries and run selected algorithm. """ # Get rid of short series if len(timeseries) < MIN_TOLERABLE_LENGTH: raise TooShort() # Get rid of stale series if time() - timese...
709bdae02ad8e55682c25dff16671816caa9587d
3,599,410
def determine_time_system(header: dict) -> str: """Determine which time system is used in an observation file.""" # Current implementation is quite inconsistent in terms what is put into # header. try: file_type = header['RINEX VERSION / TYPE'][40] except KeyError: file_type = header...
00a7908aa5eaf21eaaa39d97b23304644ebe27b4
3,599,411
def _all(oper, left, right): """Short circuit all for ndarray.""" return all(oper(ai, bi) for ai, bi in zip(left, right))
fe982f59086d2aa688004f83f9c63c6ecf6919f4
3,599,413
from typing import Iterable def get_available_seats(*, trip: Trip, departure_station: BusStation, arrival_station: BusStation) -> Iterable[BusSeat]: """ return all non-reserved seats from `departure_station` to `arrival_station` """ # [StepPre] get corresponding trip stops from bus stations de...
0161ec6ec9adadb977d49a7556d8407eb62255ad
3,599,414
def stats_demographic_data_controller(): """ Function to be called from controller functions to display all requests as a tab for a site. """ vars = current.request.vars output = dict() if "viewing" not in vars: return output else: viewing = vars.viewing if...
327e7a11510e29d66f9e60007ffcb16833eba437
3,599,415
import requests import json def exchange(fr, number, to=user_currency): """ 查询<number> <fr> 对应 多少 <to> Query <number> <fr> corresponding <number?> <to> :param to: 待查询的币种 :param number: 待查询的货币数量 :param fr: 目标币种 :return: """ try: res = requests.get(v2_url + 'exchange', ...
3ccc0f73cf11bcecb9c77fe91e08f5f1392d66ef
3,599,416
def list_services(t, s='http://portainer:9000/api', e='1') : """List swarm services. List the services on the swarm. Args: t: Authorization token s: Portainer server api endpoint e: Docker endpoint id Returns: List of sevice details """ return rt.get(s + '/endp...
80c08f9ba283269cdae8302906252edca2c7613c
3,599,417