content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import random def sample_dims( min_num_layers: int = 1, max_num_layers: int = 5, upper: int = 256, q: int = 16, ) -> Function: """ Create a sampler for hidden dimensions. :param min_num_layers: The minimum number of hidden layers. :param max_num_layers: The maximum num...
42c6c16402618ee3d593f764624e923e47ca6d6a
56,272
def get_containerbox_list(context, slug, num=0, template_name=None): """ returns a list of sub-lists of the containerbox specific containers, the size of the sub lists is treated with a parameter num """ request = context['request'] cachekey = "ContainerBoxList-{}-{}-{}".format( slug, ...
4be68fcc35e6d72629dcfaadabd6d6cbe05b140e
56,273
from typing import Counter def recompute_interest_by_batch(queryset=None, verbose=False): """ Using `verbose` reports potential discrepancies between old and recomputed interest values. It requires 2 extra queries for each import batch, so it should be used with caution. """ with cache_based_lock(...
a9f573791d953126ab868b8db44a5fef0b466b93
56,275
from typing import Optional from datetime import datetime def tomorrow(tz: Optional[tzinfo]=None) -> datetime: """get datetime of tomorrow""" return today(tz) + timedelta(days=1)
396a07456142463d0c707a74728a766ca470b926
56,276
def get_accessable_systems(ships, systems): """ Determine which systems are currently accessable """ accessable = [] for ship in ships: if ship[const.LOCATION] not in accessable: accessable.append(ship[const.LOCATION]) for system in systems: if system[const.NAME] not ...
26ffc740879d6f324489883b153aaf4b184329ba
56,277
import math def set_engine_state(engine: Engine, aggregation_epochs: int, aggregation_iters: int): """ This function is used to set the engine's state parameters according to the aggregation ways (iteration based or epoch based). Args: engine: the engine that to be processed. aggregat...
41b65b6fc6cff5d1b7269f25309977bf1f672906
56,278
def _get_const_info(const_index, const_list): """Helper to get optional details about const references Returns the dereferenced constant and its repr if the constant list is defined. Otherwise returns the constant index and its repr(). """ argval = const_index if const_list is not ...
e495685a5d742f014cbe14cda23e2cc97ba2761d
56,279
def config_list(): """ List all config items. :return: """ # Pull all the config items items = Config.query.all() # Return the broken down objects return success_response({"config": [item.data for item in items]})
7cdc3a986a54b103fc6a591ffef532c6d500bcab
56,280
def inv_linear_augTikho_chol_dense( Tn=None, TTn=None, Tyn=None, R=None, yn=None, sol0=None, nchan=None, nbs=None, mu0=None, conv_crit=None, a0bis=None, b0=None, a1bis=None, b1=None, d=None, conv_reg=True, verb=None, verb2head=None, **kwdargs, ...
2bd511443e5695c824bdec5abdc3bf58ce428a3e
56,281
def return_gaia_Ag(): """set the Hipparcos computation if truly obsessed see https://www.cosmos.esa.int/documents/532822/552851/vol1_all.pdf though this has higher precision!! """ return np.array([[-0.0548755604162154,+0.4941094278755837,-0.8676661490190047], [-0.8734370902348...
5d8071120fcc8a429a31f049dab1cd8a009bc7fb
56,282
def find_repeated_adjectives(lyrics): """Creates a list of all repeating adjectives from the lyrics. Args: lyrics: A string containing the lyrics of a song. Returns: A list of all adjectives found more than once in the lyrics. """ adjectives = adjectives_sorted(lyrics) repeated...
4dbef0fb9afa7571c054b60a7774345f42e8153d
56,283
def set_attr(conninfo, credentials, mode, owner, group, modification_time, change_time, size=None, creation_time=None, extended_attrs=None, path=None, id_=None, if_match=None): """ Sets all file attributes on the specified file system object. !!! This function is deprecated in favor of set_f...
b69f958abbf1f6ba6430f2b62a3527737f050a24
56,284
def DBK(graph, LIMIT, solver_function): """ INPUT: - "graph" must be a Networkx Undirected Graph - "LIMIT" is an integer describing the largest size of graph which solver_func can solve; all subgraph sizes solved will be less than or equal to LIMIT - "solver_function" takes a Networkx Graph, and outputs a list ...
4b9f5c104bf55fff1728ce5ff2686c191be0898e
56,286
def _character_name(code): """Returns the printable name of a character.""" return unicode_data.name(unichr(code), '<Unassigned>')
f2b598198013ac65dbe80deb8e42e3e65bb9dde5
56,287
def readmask(name) : """ Read a single FERRE mask file """ f=open(name) data=[] for line in f : data.append(float(line)) return np.array(data)
a55641126abf57812d6db3d3236fddd4af194b92
56,288
def _featuresmanager_parsing_creation(feats_info): """FeaturesManager instantiation from features information. This function transforms features information into a FeaturesManager object. Parameters ---------- feats_info: np.ndarray, list, tuple, pst.BaseFeatures, pst.FeaturesManager The fe...
6dc00d2df0edd3536385e5aef5f5114492775623
56,290
def __from_probmap_to_labels(probmap, threshold): """Thresholds an intensity map and find connected components. Args: probmap (np.array): The original array with probabilities. threshold (int/float): threshold Returns: regions: res: numpy array in which each disconnected re...
f8bd59815d86a0d246d02a5728a8c02364fecc9c
56,291
def checkout(): """ This function represents a /checkout API endpoint. """ return Response(status_code=200, body={"result": "Success"}, headers=RESPONSE_HEADERS)
1f9921bff1ecb10e50541e50b25ee947fc331b84
56,292
def send_trial(parameters: dict) -> int: """ Send a new trial. Executed on tuner end. Return a ID that is the unique identifier for this trial. """ return get_advisor().send_trial(parameters)
919eee4a644a0ec15172e724c4367b1864596545
56,293
def _create_binary_operator(operator_func, description, list_kword=None): """Creates and returns a BinaryOperator class based on the given operator_func function, which is assumed to be a function taking two arguments (lvalue, rvalue) and returning a boolean value. """ class _BinaryOperatorImpl(_Bi...
1a5691b018df8e7b9f296b33d0187e327819befe
56,295
async def get_commit_oneline_message(*, github_access_token, repo_url, commit_hash): """ Get the git commit message plus a piece of the hash for display purposes Args: github_access_token (str): The access token repo_url (str): The URL for the git repo of the project commit_hash (st...
56de60b5477c2707e5fafeb29eccb56727e44c0b
56,296
def return_subset_number(pedigree): """ Find out how many founders there are in the given file. """ founder = 0 with open(pedigree, 'r') as filein: for lines in filein: line = lines.rstrip().split() if line[2] == "0" and line[3] == "0": founder += 1 return foun...
090661dfbc367fe3974fe2dfa2069f97dd70ee75
56,297
def waveoauth(func): """Decorator used to specify that a handler requires wave authentication.""" @wraps(func) def inner(request, *args, **kwargs): result = _oauth_helper(request) if result is not None: return result return func(request, *args, **kwargs) return inner
b8936965c60410856ee436b159a098044fcd5fc8
56,298
def tool_no_apply(cols): """Gets the tool number from the PMC signal Explanation =========== Same explanation as in the cut_signal_apply function """ pmc = cols[0] if (pmc - 64) > 0: return int(pmc - 64) else: return int(pmc)
8d094cabdab58bd009d9019de8896c772e5fc72a
56,299
def normalize_http_url(url): """ Strip http schema, port number and path from a url :param url: the url to normalize :return: normalized url """ parsed = urlparse(url) netloc = parsed.netloc return netloc.split(':')[0] if netloc else url
d514f72c787399e0253ecabab2d236a9ab75f816
56,300
def loop_until_choice_is_correct(msg_prompt: str, valid_choices: dict) -> str: """ Loop until a valid value is provided, which must match a key from `valid_choices`. Args: msg_prompt (str): Prompt to display to the user to enter a choice. valid_choices (dict, optional): Keys are valid c...
bb05f1d11b14611ffcada93629382bfb8a447fad
56,301
from email.header import decode_header def emailHeader(header): """ Takes an email header and decodes it if it has been MIME-encoded. :param header: The email header to be decoded :return: The decoded header returned as a string """ dh = decode_header(header) # Returns a list of 2-...
50df52dbd52d2ee02c3870e96ff77d9ccd38a844
56,303
def get_hash(string_value, algorithm): """ Create hash for the given string and algorithm """ if not isinstance(string_value, str) and not algorithm: return string_value hash_object = HASH_ALGO.get(algorithm)(string_value.encode()) if not hash_object: return string_value hex_...
26031c2335b515b7e413fac47c9a9452b40fe188
56,306
def middle(t): """Returns all but the first and last elements of t. t: list returns: new list """ return t[0:-1]
c94f0d6575257d7528c0164823944058d794d0ca
56,308
def rollout_multiple( *args, num_repeats=1, initial_context=None, accum_context=True, **kwargs ): """ Do multiple rollouts and concatenate the paths """ assert num_repeats >= 1 last_path = rollout( *args, accum_context=accum_context, in...
285399b40928c552b7755e19180e2f835dd5d272
56,310
def get_cdf(prc, bg_prc): # , study_id, cdf_df=None): """ Specifically for the dictionary data prc = syn[study_id]['lost']['prc'] bg_prc : which prc to use as bg: 0 = min, 1 = 5% , 2 = 10%, 3 = 15%, 4 = 20% """ int_cdf = np.zeros((51, 1)) # if cdf_df is None: # cdf_df = pd.DataFram...
38481d3d0d0bd662e837e2dade3fdd0aa7e61c70
56,311
def joli_string(f): """renvoie une jolie chaine de caractèrepour la formule f """ operator = { 'OU': 'u', 'ET': 'n', 'NON': '-', 'IMPL': '=>', 'EQ': '<=>', 'VRAI': 'V', 'FAUX': 'F' } n = f.nb_operandes() if n == 0: v = f.get_val() ...
bf2160481f444fa690c61750ba286fe1739d9291
56,312
import time def generate_proposals(predictor, test_data, imdb, vis=False, thresh=0.): """ Generate detections results using RPN. :param predictor: Predictor :param test_data: data iterator, must be non-shuffled :param imdb: image database :param vis: controls visualization :param thresh: t...
240cd3fdcb148cc0a205c71eed7d8a453f8ff16a
56,313
from typing import Callable def _create_tasks(reader: Callable, assets, threads, *args, **kwargs) -> TaskType: """Create Future Tasks.""" tasks: TaskType if threads and threads > 1: with futures.ThreadPoolExecutor(max_workers=threads) as executor: return [ (executor.su...
7684e46b8e2061a0812b0579d106671949357e0d
56,315
import torch def sample_init_points(n_vertices, n_points, random_seed=None): """ :param n_vertices: 1D np.array :param n_points: :param random_seed: :return: """ if random_seed is not None: rng_state = torch.get_rng_state() torch.manual_seed(random_seed) init_points = ...
4ccfa02292992bc54989eb4cea6d9f7befb7a67b
56,317
def iget_list_column_slice(list_, start=None, stop=None, stride=None): """ iterator version of get_list_column """ if isinstance(start, slice): slice_ = start else: slice_ = slice(start, stop, stride) return (row[slice_] for row in list_)
1c604be6c59d43fb1c2b1b1a3078f5e98105347f
56,318
def create_saver(): """ Restore the moving average version of the learned variables for eval. """ variable_averages = tf.train.ExponentialMovingAverage(FLAGS.moving_average_decay) variables_to_restore = variable_averages.variables_to_restore() return tf.train.Saver(variables_to_restore)
3002c2f91fe482ef243a35563118fbf607ac8afc
56,319
async def hashtag_info(sessionid: str = Form(...), name: str = Form(...), clients: ClientStorage = Depends(get_clients)) -> Hashtag: """Return Hashtag info (id, name, picture) """ cl = clients.get(sessionid) return cl.hashtag_info(name)
d59e375e9eeb1c8a6b636632bdf6be60c2f58a58
56,320
def config_dict(gps_dict): """A test configuration based on a dictionary""" cfg = config.Configuration("dictionary") cfg.update_from_dict(gps_dict, section="gps") return cfg
bc1f5119713980914c05e51adfc586415bae08b3
56,321
def compute_contract_address(address: Address, nonce: Uint) -> Address: """ Computes address of the new account that needs to be created. Parameters ---------- address : The address of the account that wants to create the new account. nonce : The transaction count of the account...
6cee979e8fc325b2ea2d96adce9a8c13c8090619
56,322
def single_plot(fig_num: int, ax_prop: dict, arr_A: list, arr_B: list, filenames_db: list, marker: str, mark_size: float, bsf: bool, rev: bool, shrink: bool, xlab: str, ylab: str, title: str, filename: str, extra_line: list = None, mdpi: int = 400) -> int: """ Args: :par...
440ea0e406ed4deb6f8e7798305f93070bd14429
56,323
def _wrapper(args=None): # type: (Optional[List[str]]) -> int """Central wrapper for all old entrypoints. Historically pip has had several entrypoints defined. Because of issues arising from PATH, sys.path, multiple Pythons, their interactions, and most of them having a pip installed, users suffer ...
cca1faed560e8622fd6627bc7bd0897d2d0bce6e
56,324
import random def assign_read_kmers_to_contigs(reads_filename, kmer_ii, kmer_size): """ Given a set of reads and k-mer length, assign k-mer counts to the contigs. """ contig_counts = defaultdict(int) pf = SeqIO.ParseFastQ(reads_filename) #tuple = pf.getNextReadSeq() kmer = None conti...
e573f7d87f6ce4e523a6e29f10725d6cd003c6c1
56,325
def Base64EncodeConditional(input_text): """ Values which can be :param input_text: :return: """ if not isinstance(input_text, str): raise Exception("input_text should not be %s", type(input_text)) if r_cgi_vars_char_set.search(input_text) and not input_text.startswith(base64_prefi...
0f225f8ef33c67c51a2ca508488a5e56921b36ab
56,326
def _generate_widget_parameters(bot_name, user_photo, size, corner_radius, access_write): """ Generate common widget embed code parameters. """ user_photo_bool = str(user_photo).lower() data_telegram_login = 'data-telegram-login="{}" '.format(bot_name) data_size = 'data-size="{}" '.format(size)...
97132676a5e7218b1224e9be0fff4e178157c4ca
56,327
def application_instance(db_session, pyramid_request): """Return the ApplicationInstance that the test OAuth2Token's belong to.""" application_instance = ApplicationInstance( consumer_key=pyramid_request.lti_user.oauth_consumer_key, shared_secret="test_shared_secret", lms_url="test_lms_u...
59036cde4b8a40f534c0a1faf21a704c73379148
56,328
def eval_loss(model, mode, orig_img, adv, lab, autoencoder, c_start, kappa, gamma, beta, to_optimize=True): """ Compute the loss function component for the network to find either pertinent positives (PP) or pertinent negatives (PN). Input: - model : nn model - mode ...
ddecfdb08ddcb104826732561b935780cbb0f733
56,329
def docstring_parameter(*sub): """ Decorator to add strings to a doc string.""" def dec(obj): obj.__doc__ = obj.__doc__.format(*sub) return obj return dec
56181279d4999008df792873fd3bf411dff9d2c7
56,330
def GetDisplayPosition(config_name, type_order=CONFIG_TYPE_DUMP_ORDER): """Given a config_name, return display position specified by suffix_order. Args: config_name: Name of config to look up. type_order: A tuple/list of config types in the order they are to be displayed. Returns: If...
5016f8f85136043e5190ddb30e1279be6417178e
56,331
def repunctuate_character(letters, punctuation): """Apply the recorded punctuation to a character. The letters must be an iterator of base characters.""" if punctuation == 'UPPER': return next(letters).upper() elif punctuation == 'LOWER': return next(letters).lower() else: re...
92cd8b30466e19a8ce1278f0b81440399c7f809c
56,335
def get_tree_coords(tree): """Takes Phylo tree object and populates it with coordinates that can be used to plot the tree from scratch""" for _i, i in enumerate(tree.get_terminals()): i.y = _i i.x = tree.distance(i) for i in reversed(tree.get_nonterminals()): _ = i.clades ...
debd0a995dddab8a0287a3d553a0edeacef5e777
56,336
def cluster_scale_out(base, cluster_id, count=None, expected_status='SUCCEEDED', wait_timeout=None): """Utility function that scale out cluster.""" params = { 'scale_out': { 'count': count } } res = base.client.trigger_action('clusters', cluster_id, par...
62030d1ed0cded0fbdff675203b91c8093ef46f3
56,337
def category_view(slug, page): """List latest topics in the category.""" board_id = h.get_board_id() user = g.user h.require_board_access(board_id, user.id) category = board_category_query_service.find_category_by_slug( board_id, slug ) if category is None: abort(404) ...
003391b0822f2f5ad64320be93cb055df6904d87
56,338
def square_loss(labels, predictions): """ Square loss function Args: labels (array[float]): 1-d array of labels predictions (array[float]): 1-d array of predictions Returns: float: square loss """ loss = 0 for l, p in zip(labels, predictions): loss = loss + (l - ...
888e0945fd7cbbbb4f56a98334b932d3117c5db9
56,339
def association_consistency(document, dictHeaderPosition, desiredColumns, newRuleList): """ This function performs a per tuple check to see if the desired columns satisty the consistency rules provided by the user Args: document(RDD): the document to analyze dictHeaderPosition(dict): prelim...
c14993f57136176cc535d54650f24bf49dde0df9
56,340
def count_per_group_nb(group_arr): """Return count per group.""" result = np.empty(group_arr.shape[0], dtype=np.int_) j = 0 prev_group = -1 run_count = 0 for i in range(group_arr.shape[0]): cur_group = group_arr[i] if cur_group < prev_group: raise ValueError("group_ar...
618bb79a766410846a4cc1e43982be36bcd24bdf
56,341
from re import S def roots_quadratic(f): """Returns a list of roots of a quadratic polynomial. If the domain is ZZ then the roots will be sorted with negatives coming before positives. The ordering will be the same for any numerical coefficients as long as the assumptions tested are correct, otherwise...
5f86db9a0b5c72335e4f71a916233a33d2a3e6d2
56,342
import torch def _index(tensor_3d, tensor_2d): """This function is used to index a 3d tensors using a 2d tensor""" x, y, z = tensor_3d.size() t = tensor_3d.reshape(x * y, z) tt = tensor_2d.reshape(x * y) v = t[torch.arange(x * y), tt] v = v.reshape(x, y) return v
f2316f49a77fc094277a221318f9c0ede18da688
56,343
def apply_shifts_dft(src_freq, shifts, diffphase, is_freq=True, border_nan=True): """ adapted from SIMA (https://github.com/losonczylab) and the scikit-image (http://scikit-image.org/) package. Unless otherwise specified by LICENSE.txt files in individual directories, all code is Copyright (C...
68891234071f789b0f46b78a04fe3e67b35130ce
56,344
def search(pattern, string): """Scan through string looking for a match to the pattern, returning true or None if no match was found.""" return Regex(pattern).search(string)
6a5721bff7388f71875f4b168a73e3415212b92d
56,346
import re import json def init_app(app): """Initialize Flask_Login LoginManager with our app""" login_module = get_login_module() if not login_module: return login_manager = flask_login.LoginManager() login_manager.init_app(app) # login_manager.session_protection = 'strong' # pylint: disable=unuse...
964d561606ca1b5acb2e02392016e50f52fb3f1e
56,347
def other(path=''): """a test one with the other login type""" logged,session = check_logged_in() print('logged',logged) print('session',session) if not logged: redirect(utils.join('/_login/other',path)) # NOTE: You need to set the redirect to /_login/<route>/ to work around ...
6cde4f25fd8e3f9a2f93e7f7d1d6be02e211d32b
56,348
def get_hole_degree_radius_w(candidate, circles): """Calculate the hole degree of a candidate circle. Args: candidate: candidate circle. circles: sequence of circles. Returns: Squared euclidian distance of the candidate to the circles in argument. Each component of the dist...
5c705873ac1ab5160444adeb1022c0efd11f43c3
56,349
from typing import List from typing import Tuple def get_pools_with_description() -> List[Tuple[str, str]]: """ :return: List of Tuples containing pool name and description """ return [(pool, get_description(pool)) for pool in available_word_pools()]
bb4d222340dacbf07b0cee57acda97c62c14f06c
56,350
def _tri_coordinates_y(words): """ gives us a list of ocr points [[top, center, bottom], ...]""" return [(cord[1], center[1], cord[3]) for center, cord in zip( image_utils.get_centroids_from_coords([word['coords'] for word in words]), [word['coords'] for word in words] ...
aa14a2f185f564e6537859a14c33f46bb7687aaf
56,352
def get_horse(id): """ Gets information for a specific horse :param id: Identifier of the horse :type id: str :rtype: Horse """ horse = Data.get('horse', id) if horse is None: return 'Horse Not Found', 404 else: return Horse.from_dict(horse)
b9d6c14090f1b12909946c3511f58651864ed17c
56,353
def fix_rpath(file_path, old_rpath_list, new_libdir): """ Fix RPath """ to_recheck = 0 cmd = ["install_name_tool"] for old_rpath in old_rpath_list: lib_file = os.path.basename(old_rpath) lib_path = os.path.join(new_libdir, lib_file) if not os.path.exists(lib_path): pr...
faf96c6802a4a58dd110a67bc3f70b5bf89f2112
56,355
import time def zr_total_dem(): """ Real Name: b'zr total dem' Original Eqn: b'(zr agri dem *agri zr dam coef)+(zr agri dev dem (Time)*agri zr dev coef)+zr dom dem\\\\ (Time)+zr Env dem (Time)+zr Ind (Time)+Zr wr dem (Time)' Units: b'MCM/Month' Limits: (None, None) Type: component b'(Zr A...
4042f494d98902178357b5b07325db70a58aa9b6
56,356
def split_set_by_point(coord_array, point): """ point_array : array of Coord point : Coord Return the array of the points on the left and the right of the point """ left = [] right = [] for coord in set(coord_array): if coord.x < point.x or coord.y < point.y: left.app...
6a7ee4387f2bc74fcf06262bc4262351c66b3a1c
56,358
def ldns_resolver_new(): """LDNS buffer.""" return _ldns.ldns_resolver_new()
5d6cf276dc77c60c299016c6d215e012973b2a27
56,359
def replace_group_with_whitespace(match_obj): """ :type match_obj: MatchObject """ match_start, match_stop = match_obj.span(1) overall_start, overall_stop = match_obj.span(0) start_offset = match_start - overall_start stop_offset = (match_stop-match_start) + start_offset new_str = '{}...
93a0328f1e3afae13422d2bbca12d9052f9bfb65
56,360
import numpy def circle_vs_circle(m): """ Process two circles that collide. """ n = numpy.subtract(m.b.position.data, m.a.position.data) r = m.a.radius + m.b.radius r *= r if r < (m.a.x - m.b.x) ** 2 + (m.a.y - m.b.y) ** 2: return False d = distanceA(m.a.position.data, m.b.po...
7fd8cd49943c57e2c432ba816896a4d744fa79e3
56,362
def get_or_create_family(family): """ Return a models.Family object corresponding to the given Family object. If the given Family has no database id, it will added to the database; otherwise, the existing item is fetched. """ if family is None: return None elif family._id is not Non...
f2cd0b1bebe1789590abfebe3d8e94b37e5987f1
56,364
def generate_repr_code(repr, node, fields): """ The CPython implementation is just: ['return self.__class__.__qualname__ + f"(' + ', '.join([f"{f.name}={{self.{f.name}!r}}" for f in fields]) + ')"'], The only notable difference h...
79b374d013d4bbffe8f2c78d94542f9ff5633b43
56,365
def get_model_time_series(station, fnames, grid_B, mesh_mask, nemo_36=True): """Retrieve the density, salinity and temperature time series at a station. Time series is created from files listed in fnames""" if nemo_36: depth_var = 'gdept_0' depth_var_w = 'gdepw_0' else: depth_var...
5ef35e08c6b713f354b0a8e0640b6073719f239a
56,366
from typing import List def parse_header(header_string: str, sep: str = ' ') -> List: """Parses header data. Args: header_string: A string containing header items. sep: A string containing a delimiter. Returns: A list of header items. """ header = header_string.strip().s...
b6b31de74d5d3e47695c1e014d5803de2bc6a952
56,367
def Import_MultiLith_output(mr_raw,dX=0.0001,MajorElements=pd.Series([7.48,8.51],index=['MgO','FeO']),WalterComps=False): """Import a 1D melting region object generated by the MultiLith code. Must have been integrated already. Returns a pandas dataframe. Parameters ---------- filename: string...
33454b0ad3c8a55595cee960ca2628b5b4e0649b
56,368
def listPipelines(): # type: () -> List[String] """Will return a list of the available Alarm Notification Pipelines. Returns: A list of pipeline names. The list may be empty if no pipelines exist. Unsaved name changes will not be reflected in the list. """ return []
929b95bb190f41dc0293443839fcbf9fa82d10b8
56,369
def calc_rf_ch4(m_0, m_curr, m_bar, n_bar): """ Calculate the radiative forcing for CH4 (methane) Parameters ---------- m_0 : float Initial ch4 concentration, in ppb m_curr : float Current ch4 concentration, in ppb m_bar : float Averaged ch4 concentration, in W m...
6efa23428244d7663568eb453bad1bb325bb9de2
56,370
def offset(freqs, re0, im0): """Complex offset re + j*im. Freqs vector is ignored, but required for lmfit Model.""" return re0 + 1j * im0
ae2b373806dee6e50fb61c4945b99f7ef7c9a6f7
56,371
def build_relative_position(query_size, key_size, bucket_size=-1, max_position=-1): """ Build relative position according to the query and key We assume the absolute position of query \\(P_q\\) is range from (0, query_size) and the absolute position of key \\(P_k\\) is range from (0, key_size), The rel...
ef4cfc800da617f39c7f2271c2a43f03ef1077d6
56,372
def implied_volatility_from_a_transformed_rational_guess(price, F, K, T, q): """ :param price: :type price: float :param F: :type F: float :param K: :type K: float :param T: :type T: float :param q: :type q: float :return: :rtype: float """ return implied_vo...
aaf78c637ec7624033ac2594cf52eb4987ad0380
56,373
def is_kanji(input: str = "") -> bool: """Tests if `input` is Kanji (Japanese CJK Ideographs)""" return (not is_empty(input)) and all(is_char_kanji(char) for char in input)
b43acac43e761afc8d5d02752d23fc0fc3aadb8e
56,374
def after_request(response): """Modifies the response object prior to sending it to the client. Used to add CORS headers to the request Args: response (response): Flask response object Returns: `None` """ response.headers.add('Access-Control-Allow-Origin', '*') response.headers...
96bf051001b0f9eb4a31f2ce101a23bae39c49c9
56,375
import re def split_camel_cased(text): """ Split camelCased elements with a space. :param text: the text to be converted processed. :type: str :return: text with all camelCased elements split into different elements :type: str """ return re.sub('(?!^)([A-Z][a-z]+)', r' \1', text)
6de55ed7d8fc4bc06e0d16d4b327999ad656ceac
56,376
from typing import OrderedDict def _generate_bufferizers_and_unbufferizers(): """Generate bufferizers, forced full bufferizers and unbufferizers, by registering native and torch types, syft objects with custom bufferize and unbufferize methods, or syft objects with custom force_bufferize and force_unb...
895fc30e203c7bbd2f5ec5c28089a3b4e4afc408
56,377
def div(X,varX, Y,varY): """Division with error propagation""" # Direct algorithm: # Z = X/Y # varZ = (varX/X**2 + varY/Y**2) * Z**2 # = (varX + varY * Z**2) / Y**2 # Indirect algorithm to minimize intermediates Z = X/Y # truediv => Z is a float varZ = Z**2 # Z is a floa...
3cdb59a752ef0759f0411cd7d478a3dac204f65f
56,378
def create_information_dict(key): """Create a dictionary with the familiar information from the key.""" info = {} stream = BitStream(bytearray(key)) BRANDS = ('sun', 'moon', 'star', 'planet', 'twin_sun', 'twin_moon', 'twin_star', 'twin_planet') info["name"] = stream.read('str', 4) ...
9b2070e8d75cb746850b670c33510ace08e9f027
56,379
from bs4 import BeautifulSoup def get_word_meaning(response, xth): """ Parse a HTML document and get a text of xth meaning from particular tags By default, xth = 1 """ dom = BeautifulSoup(response.content, "lxml") div_element = dom.select_one(".word_num") or None word_meaning = "" ...
ed19d0d13980541cc89d945b83c5866ca0d7ecb1
56,381
def finish_job(client, cleanup_job, job_completed_normally, client_outputs, lwr_outputs): """ Responsible for downloading results from remote server and cleaning up LWR staging directory (if needed.) """ collection_failure_exceptions = [] if job_completed_normally: output_collector = ClientO...
b6de3e1bd5934b222f91bf11c8bf250c5bfc7620
56,382
def get_dict_from_namespace_object(args): """Unwrap the namespace object to pull out a dict of values""" return vars(args)
e1c34c1faff71ae330a44d91a399260fbdc454c6
56,384
from typing import Optional from typing import Union from typing import Tuple def add2d( x: Tensor, weight: Tensor, bias: Optional[Tensor] = None, stride: Union[int, Tuple[int, int]] = 1, padding: Union[int, Tuple[int, int]] = 0, dilation: Union[int, Tuple[int, int]] = 1, groups: int = 1, ...
ceb7a47170e246326abf089b450a49cfeb718df4
56,389
def norm3(vec): """ Third norm """ return builtinnorm(vec)
2a4513bd2ee3fa138405b56331a3a2a4e5d883aa
56,390
def get_tuple(string, n, as_int = False): """ Splits a string into n tuples, ignoring the rest if there are more, and replicating if there is only one @param string The string @param n The number of elements @param as_int If true, it will cast to int """ t = string.split(",") if len(t) == ...
59b339c561bccc428f4e2882c369a7dcda86aaff
56,391
def report_func(trnr, epoch, batch, num_batches, start_time, lr, report_stats, enc_output_dict, dec_output_dict, mem_dict): """ This is the user-defined batch-level traing progress report function. Args: epoch(int): current epoch count. batch(int): current batch count. num_batch...
4a7a5d9b72e8de759be2ab63be682bdcc5fc4f24
56,392
def print_filenames_option(dflt=True, **kwargs): """Option to tell if filenames should be in the title""" return bool_option( "show-fn", "P", "If set, show filenames in title", dflt, **kwargs )
e9619767a1b43b3dfdf2529ed6eb1ce001ed6ff3
56,393
def get_qdevice( run_type: str, wires: int, backend_name: str, config: dict ) -> pnl.device: """ Configure a pennylane quantum device object used to construct qnodes. Args: run_type: Specifies the mode to run the (hybrid) VQC training: Ideal, noisy simulation or on real quantu...
76fa86234e50d9e959ec5e6f5c863cdcacb18ca5
56,394
def xy_rot(x, y, ang): """Rotate (x,y) positions to new coords Rotate (x,y) values by some angle. Positive ang values rotate counter-clockwise. Parameters ----------- x : float or array X location values y : float or array Y location values ang : float or arra...
f6d60766d72e259dec0d4803e2a57d3fd650d66c
56,395
from comtypes.automation import VARIANT def _is_object(obj): """This function determines if the argument is a COM object. It is used in several places to determine whether propputref or propput setters have to be used.""" # A COM pointer is an 'Object' if isinstance(obj, POINTER(IUnknown)): ...
a537a4286635c11f63f69e27fd3ad986704586ca
56,396
def ParseDupHit(text):#{{{ """ Parse a duplication hit e.g. 1-575(nTM=2) 2-571(nTM=2) """ li = [] strs = text.split() for ss in strs: strs1 = ss.rstrip(')').split('(nTM=') # ['35-345', '7'] li1 = [int(x) for x in strs1[0].split('-')] li1.append(int(strs1[1])) #...
d488076fcaf581376730bb404090d16c99137baa
56,397