content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import json def odict_to_json(odict): """ Dump an OrderedDict into JSON series """ json_series = json.dumps(odict) return json_series
d18a4e0f0d11a2c529edb395671052f15ad8071d
3,644,950
import ast def parenthesize(node: ast.AST, _nl_able: bool = False) -> str: """Wrap the un-parsed node in parentheses.""" return f"({unparse(node, True)})"
d61d6be6e5466559cdaba0602a95f3169d74aa36
3,644,951
def stack_nested_arrays(nested_arrays): """Stack/batch a list of nested numpy arrays. Args: nested_arrays: A list of nested numpy arrays of the same shape/structure. Returns: A nested array containing batched items, where each batched item is obtained by stacking corresponding items from the list ...
bf1e4bd35be871b9098d9789b189c48f36329646
3,644,952
def encode_data(data): """ Helper that converts :class:`str` or :class:`bytes` to :class:`bytes`. :class:`str` are encoded with UTF-8. """ # Expect str or bytes, return bytes. if isinstance(data, str): return data.encode('utf-8') elif isinstance(data, bytes): return data ...
3cd54389719439e8f18cf02b110af07799c946b5
3,644,954
def get_apps_final(the_apps_dummy): """ 计算出: 1.每个用户安装app的数量; 2.每个用户安装小众app的数量; 3.每个用户安装大众app的数量; 4.根据每个用户安装app的向量进行Mean-shift聚类的结果 """ core_data = the_apps_dummy.drop(['id'], axis=1) the_apps_final = get_minor_major(core_data, 'apps', 5, 90) # new_core_data = col_cluster(core_d...
afe92cf7fb79ac73464f7e9189bb56608e0fd424
3,644,955
from indico.modules.events.abstracts.util import (get_events_with_abstract_reviewer_convener, get_events_with_abstract_persons) from indico.modules.events.contributions.util import get_events_with_linked_contributions from indico.modules.events.papers.util import get_events_with_paper_roles from indico.modules.events.r...
145f33cec0b79d74ea1550d22fc8599484d2b16d
3,644,956
def bert_keyword_expansion(keywords: str, num_similar: int, bert_model, tokenizer, bert_embedding_dict): """ Keyword expansion outputs top N most similar words from vocabulary. @param keywords: stri...
5976a52cfcdd8d80f1b3b0fcc0d32b92f40a1f62
3,644,958
def utc_to_tt_offset(jday=None): """Returns the offset in seconds from a julian date in Terrestrial Time (TT) to a Julian day in Coordinated Universal Time (UTC)""" if use_numpy: return utc_to_tt_offset_numpy(jday) else: return utc_to_tt_offset_math(jday)
f40c82840253cc9b9f1f9a2685134b9313cb42d1
3,644,959
from typing import Any import aiohttp async def get_async_request(url: str) -> [int, Any]: """Get the data from the url provided. Parameters ---------- url: str url to get the data from Returns ------- [int, Any] Tuple with the Response status code and the data returned f...
2ad07bf7394d4d7804802d201fab0027171bea3d
3,644,960
def scattering_probability(H, psi0, n_emissions, c_ops, tlist, system_zero_state=None, construct_effective_hamiltonian=True): """ Compute the integrated probability of scattering n photons in an arbitrary system. This function accepts a nonlinearly space...
d4509371303a729a160d1b3d92f5c5f2f8ac3339
3,644,961
def analytical_value_cond_i_shannon(distr, par): """ Analytical value of the conditional Shannon mutual information. Parameters ---------- distr : str-s Names of the distributions; 'normal'. par : dictionary Parameters of the distribution. If distr is 'normal': ...
a9a91d77863829de7f818aa6dcfe0216eb9a70af
3,644,962
def ekin2wl(ekin): """Convert neutron kinetic energy in electronvolt to wavelength in Angstrom""" if _np and hasattr(ekin,'__len__'): #reciprocals without zero division: ekinnonzero = ekin != 0.0 ekininv = 1.0 / _np.where( ekinnonzero, ekin, 1.0)#fallback 1.0 wont be used return ...
873ae25e10dfb3e6d9c6ca8ab1c56efa0066544a
3,644,964
def show_subscription(conn, customer): """ Retrieves authenticated user's plan and prints it. - Return type is a tuple, 1st element is a boolean and 2nd element is the response message from messages.py. - If the operation is successful; print the authenticated customer's plan and return tupl...
93a99075ea98697782845c2751362f9b319cea43
3,644,965
def is_primitive_type (v) : """ Check to see if v is primitive. Primitive in this context means NOT a container type (str is the exception): primitives type are: int, float, long, complex, bool, None, str """ return type(v) in {int:0, float:0, long:0, complex:0, bool:0, None:0, str:0}
2d72e03aa1ec62f214b2a3b468948ff2354508dd
3,644,967
def _get_bit(h, i): """Return specified bit from string for subsequent testing""" h1 = int.from_bytes(h, 'little') return (h1 >> i) & 0x01
b9b672c87b35369dc86abec7005dfeed3e99eb67
3,644,968
def go_down_right_reward(nobs, high_pos, agent_num, act): """ Return a reward for going to the low or right side of the board :param nobs: The current observation :param high_pos: Tuple of lowest and most-right position :param agent_num: The id of the agent to check (0-3) :return: The reward f...
bd8c6f01b55e14cc498cc251b1c0cc92340506c7
3,644,969
def getChannelBoxMenu(): """ Get ChannelBox Menu, convert the main channel box to QT and return the Edit QMenu which is part of the channel box' children. :return: Maya's main channel box menu :rtype: QMenu """ channelBox = getChannelBox() # find widget menus = channelBox....
38957701044f4552cd355c8856abb8c3b486479b
3,644,970
def make_sid_cookie(sid, uri): """Given a sid (from a set-cookie) figure out how to send it back""" # sometime near 0.92, port got dropped... # uritype, uribody = urllib.splittype(uri) # host, path = urllib.splithost(uribody) # host, port = urllib.splitnport(host) # if port == -1: # port...
d194bcb8f47acfbbab9d7405ff9a23069b74f077
3,644,971
def identity_filter(element_tuple): """ element_tuple est consitute des (name, attrs) de chaque element XML recupere par la methode startElement """ return element_tuple
c50208f345f40acce58df86cdae4432aae24cf4b
3,644,972
def EoZ(N2, w0, f, ): """ Wave ray energy when variations can only occur in the vertical (i.e. N2 and flow only vary with depth not horizontally) - Olbers 1981 """ Ez = np.squeeze((w0**2 * (N2 - f**2)) / ((w0**2 - f**2)**(3 / 2) * (N2 - w0**2)**(1 / 2))) return Ez
7dfbcf3c0e29463ccf1663922486ffaad99b1ea5
3,644,973
from typing import Any def safe_string(value: Any) -> str: """ Consistently converts a value to a string. :param value: The value to stringify. """ if isinstance(value, bytes): return value.decode() return str(value)
0ba8dcfe028ac6c45e0c17f9ba02014c2f746c4d
3,644,974
def handle_older_version(upstream_version: Box) -> bool: """ Checks if the current version (local) is older than the upstream one and provides a message to the end-user. :return: :py:class:`True` if local is older. :py:class:`False` otherwise. """ version_utility = VersionUtility(PyFun...
130f825a59ca27a2e3d7d63e7d917f837153a2be
3,644,975
from typing import Union def tp(selector:Union[str, tuple]="@s", selector2:Union[str, tuple]=("~", "~", "~")): """ selector:Union[str, tuple] -> The position to be moved from selector2:Union[str, tuple] -> The position to be moved to """ if not ((isinstance(selector, str) or isinstance(selector, ...
81b3baf308f412bae3718fe165028a970fe56bda
3,644,976
def new_product() -> Product: """Generates an instance of Product with default values.""" return Product( product_id='', desc='', display_name='', capacity=0, image='')
ef50c2e90d5f512b2ae53c1111f501c13bdbca5d
3,644,977
def _rng_bit_generator_batching_rule(batched_args, batch_dims, *, shape, dtype, algorithm): """Calls RBG in a loop and stacks the results.""" key, = batched_args bd, = batch_dims if bd is batching.not_mapped: return lax.rng_bit_generator_p.bind(key, shape=shape, dtype=dtype, ...
6fdcdadb5a303a7f1f38033f7e69be781eee4a49
3,644,978
from typing import List def count_short_tail_keywords(keywords: List[str]) -> int: """ Returns the count of short tail keywords in a list of keywords. Parameters: keywords (List[str]): list with all keywords as strings. Returns: total (int): count of short tail keywords...
1af42d71be75d9279584a8c3edc090a39ec6cf77
3,644,979
def is_odd(number): """Determine if a number is odd.""" if number % 2 == 0: return False else: return True
4efe5114f2e25431808492c768abc0f750e63225
3,644,980
def fmt_quil_str(raw_str): """Format a raw Quil program string Args: raw_str (str): Quil program typed in by user. Returns: str: The Quil program with leading/trailing whitespace trimmed. """ raw_quil_str = str(raw_str) raw_quil_str_arr = raw_quil_str.split('\n') trimmed_qu...
e95c26f3de32702d6e44dc09ebbd707da702d964
3,644,981
from typing import Optional from typing import Collection from typing import cast def get_source_plate_uuid(barcode: str) -> Optional[str]: """Attempt to get a UUID for a source plate barcode. Arguments: barcode {str} -- The source plate barcode. Returns: {str} -- The source plate UUID; ...
b834d7740bfda86037d1d266c53f8618ff8e0bd3
3,644,982
def find_largest_digit(n): """ :param n: integers :return: the largest digit """ n = abs(n) # absolute the value if n < 10: return n else: return find_helper(n, 0)
f18af5c32263254e132ca405ad40c217083bd568
3,644,983
def extractChrononTranslations(item): """ """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol or frag) or 'preview' in item['title'].lower(): return None item['title'] = item['title'].replace('’', '') if 'Weapons cheat'.lower() in item['title'].lower(): return bui...
3c4768745d54257d5654dac74b3278e95611288e
3,644,984
from sklearn.ensemble import RandomForestRegressor from sklearn.feature_selection import SelectFromModel def run_feature_selection(X, y, select_k_features): """Use a gradient boosting tree regressor as a proxy for finding the k most important features in X, returning indices for those features as output."...
0c730e2d2015b3ad0777cd493e2f5235bc9682a3
3,644,985
from typing import Optional from typing import Callable from typing import Literal def _not_json_encodable(message: str, failure_callback: Optional[Callable[[str], None]]) -> Literal[False]: """ Utility message to fail (return `False`) by first calling an optional failure callback. """ if failure_callback: ...
6979261a5f14a32c1ae34d01bad346344f38ed14
3,644,986
import functools def requires(*commands: str) -> RequiresT: """Decorator to require the given commands.""" def inner(func: ReturnT) -> ReturnT: """Decorates the function and checks for the commands.""" for command in commands: if not check_availability(command): ra...
a84199cfff7bf29a3a2c3ccb46cf65b3a09a7136
3,644,987
def _build_model(input_dim, num_classes, num_hidden_layers=0, hidden_dimension=128, normalize_inputs=False, dropout=0): """ Macro to generate a Keras classification model """ inpt = tf.keras.layers.Input((input_dim)) net = inpt # if we're normalizing input...
07386dbf2649463963d754959f7d389c1d2aae90
3,644,988
def get_client( project_id, cloud_region, registry_id, device_id, private_key_file, algorithm, ca_certs, mqtt_bridge_hostname, mqtt_bridge_port): """Create our MQTT client. The client_id is a unique string that identifies this device. For Google Cloud IoT Core, it must be in the format below."""...
6fa945892e7b0174e4fbfebc7e5f2f985982c6f0
3,644,989
def fake_image_sct_custom(data): """ :return: an Image (3D) in RAS+ (aka SCT LPI) space """ i = fake_image_custom(data) img = msct_image.Image(i.get_data(), hdr=i.header, orientation="LPI", dim=i.header.get_data_shape(), ) return img
9593240af25c3c4fc2cb8602dda902713721ebfb
3,644,990
def _get_property_header(resource, resource_type): """ Create a dictionary representing resources properties :param resource: The name of the resource for which to create a property header :param resource_type: The type of the resource (model, seed, etc.) :return: A dictionary representing ...
e9622282a83cfd1b0be5af54def817ed07ad8e21
3,644,991
def create_metapaths_parameters(filename, folder): """ creates a parameters file from the default """ default_filename = folder + PATHDELIM + 'resources'+ PATHDELIM + "template_param.txt" try: filep = open(default_filename, 'r') except: eprintf("ERROR: cannot open the default parameter ...
b859ee0791b3213cc48f253943122290ad5a67fa
3,644,992
def bitwise_dot(x, y): """Compute the dot product of two integers bitwise.""" def bit_parity(i): n = bin(i).count("1") return int(n % 2) return bit_parity(x & y)
074b09a92e3e697eb08b8aaefa6ffd05d58698f4
3,644,994
import itertools def fit (samples, degree, sample_weights=None): """ Fit a univariate polynomial function to the 2d points given in samples, where the rows of samples are the points. The return value is the vector of coefficients of the polynomial (see p below) which minimizes the squared error of th...
4b7a7e77c5e55641a1a666f52abef32088bf680a
3,644,995
def get_ahead_mask(tokens, i_pad=0): """ ahead mask 계산하는 함수 :param tokens: tokens (bs, n_seq) :param i_pad: id of pad :return mask: ahead and pad mask (ahead or pad: 1, other: 0) """ n_seq = tf.shape(tokens)[1] ahead_mask = 1 - tf.linalg.band_part(tf.ones((n_seq, n_seq)), -1, 0) ahea...
31a7bd2710cd86075f753227fa2e4c97b1948e19
3,644,998
def check_containment(row, query_index, reference_index, percent_identity=PERCENT_IDENTITY, covered_length=COVERED_LENGTH): """Checks if a row from a blast out format 6 file is a containment Takes in a row from a blast out format 6 table, a DataFrames with query sequence and reference sequence data. """ ...
a868d9c15abd5c73bc9483cc9a58d7c92875d15a
3,644,999
def get_mgga_data(mol, grid, rdm1): """ Get atomic orbital and density data. See eval_ao and eval_rho docs for details. Briefly, returns 0-3 derivatives of the atomic orbitals in ao_data; and the density, first derivatives of density, Laplacian of density, and kinetic energy density in r...
11de048bbe320721204171d9786a997411b953d6
3,645,000
def _stringify_lmer_warnings(fg_lmer): """create grid w/ _ separated string of lme4::lmer warning list items, else "" """ warning_grids = fitgrid.utils.lmer.get_lmer_warnings( fg_lmer ) # dict of indicator dataframes warning_string_grid = pd.DataFrame( np.full(fg_lmer._grid.shape, ""),...
bbd0fedb2480d4d1ef2a98689861c112552c0b59
3,645,001
def index(): """Loads the index page for the 'Admin' controller :returns: a dictionary to pass to the view with the list of ctr_enabled and the active module ('admin') """ ctr_data = get_ctr_data() users = db().select(db.auth_user.ALL) approvals = db(db.auth_user.registration_key=='pending').select(db.auth_user....
4b5dc978361b970d2dc6b2f5c6df28b06c9f28bf
3,645,002
def get_language_codes(): """Returns a list of available languages and their 2 char input codes """ languages = get_languages() two_dig_codes = [k for k, v in languages.items()] return two_dig_codes
2e368b73783630835ee1ec32875318725f62d72e
3,645,003
def fun_evaluate_ndcg(user_test_recom_zero_one): """ 计算ndcg。所得是单个用户test的,最后所有用户的求和取平均 :param test_lst: 单个用户的test集 :param zero_one: 0/1序列 :param test_mask: 单个用户的test列表对应的mask列表 :return: """ test_lst, zero_one, test_mask, _ = user_test_recom_zero_one test_lst = test_lst[:np.sum(test_ma...
018dcf1095ebdd02e253ae6c1c36e17d1f13431a
3,645,004
def prettyDataSize(size_in_bytes): """ Takes a data size in bytes and formats a pretty string. """ unit = "B" size_in_bytes = float(size_in_bytes) if size_in_bytes > 1024: size_in_bytes /= 1024 unit = "kiB" if size_in_bytes > 1024: size_in_bytes /= 1024 unit = "MiB" ...
30eb068bafe2d9457ea43b59f2f62bdd0ce1c927
3,645,005
def image_resize_and_sharpen(image, size, preserve_aspect_ratio=False, factor=2.0): """ Create a thumbnail by resizing while keeping ratio. A sharpen filter is applied for a better looking result. :param image: PIL.Image.Image() :param size: 2-tuple(width, height) :param pre...
7f581a0a8b1dccf62a3840269e7b2cea1e78a13b
3,645,007
def validate_mash(seq_list, metadata_reports, expected_species): """ Takes a species name as a string (i.e. 'Salmonella enterica') and creates a dictionary with keys for each Seq ID and boolean values if the value pulled from MASH_ReferenceGenome matches the string or not :param seq_list: List of OLC Se...
9eb4fd6e1f156a4fed3cc0be0c5b7153a05b038b
3,645,009
def style_strokes(svg_path: str, stroke_color: str='#ff0000', stroke_width: float=0.07559055) -> etree.ElementTree: """Modifies a svg file so that all black paths become laser cutting paths. Args: svg_path: a file path to the svg file to modify and overwrite. stroke_color: the...
6387625cd71143edb632833cd40006858f239089
3,645,010
import json def preview_pipeline( pipeline: Pipeline, domain_retriever: DomainRetriever, limit: int = 50, offset: int = 0 ) -> str: """ Execute a pipeline but returns only a slice of the results, determined by `limit` and `offset` parameters, as JSON. Return format follows the 'table' JSON table sche...
f1e640ec73bbdeb978762774c81d80e00e98adc9
3,645,011
def redirect_to_url(url): """ Return a bcm dictionary with a command to redirect to 'url' """ return {'mode': 'redirect', 'url': url}
01e4deb80bbd8f8e119c99d64001866c6cd644d9
3,645,012
def get_xml_tagged_data(buffer, include_refstr=True): """ figure out what format file it is and call the respective function to return data for training :param buffer: :param include_refstr: during training do not need refstr :return: """ if len(buffer) > 1 and 'http://www.elsevier.com/...
e51cdde728d3e4c5c1f4936bfeb874be8aabf292
3,645,013
from typing import Dict from typing import Any def de_dup( data: pd.DataFrame, drop_duplicates_kwargs: Dict[str, Any] = {}, ) -> pd.DataFrame: """Drop duplicate rows """ return data.drop_duplicates(**drop_duplicates_kwargs)
2cd78627226170af7e184bc60caa5ee39290ab42
3,645,014
def get_task_defs(workspace: str, num_validators: int, num_fullnodes: int) -> dict: """ Builds a dictionary of: family -> current_task_def task_def can be used to get the following when updating a service: - containerDefinitions - volumes - placementConstraints NOTE: on...
99c131ac60999dd1b2b657575e40f2b813633f61
3,645,015
from azure.mgmt.marketplaceordering.models import OfferType def get_terms(cmd, urn=None, publisher=None, offer=None, plan=None): """ Get the details of Azure Marketplace image terms. :param cmd:cmd :param urn:URN, in the format of 'publisher:offer:sku:version'. If specified, other argument values can ...
7483e6d150b784535dd47ead0b63d079e66c391d
3,645,016
def encode_payload( result ): """JSON encodes a dictionary, named tuple, or object for sending to the server """ try: return tornado.escape.json_encode( result ) except TypeError: if type( result ) is list: return [ tornado.escape.json_encode( r ) for r in result ] ...
551264dcb0b9ad6d380b8ae393b2dfbfafb93dee
3,645,017
def relu(shape) -> np.ndarray: """ Creates a gaussian distribution numpy array with a mean of 0 and variance of sqrt(2/m). Arguments: shape : tuple : A tuple with 2 numbers, specifying size of the numpy array. Returns: output : np.ndarray : A uniform numpy array. """ return np.random.normal(0, np.s...
e41835dc5e6de8f0b6161c8ea73afeffd8f84c31
3,645,018
def reset_all(): """Batch reset of batch records.""" _url = request.args.get("url") or request.referrer task_id = request.form.get("task_id") task = Task.get(task_id) try: count = utils.reset_all_records(task) except Exception as ex: flash(f"Failed to reset the selected records:...
a4241ce81531db7d18d226327f6a96b600a50fd0
3,645,019
def update_to_report(db, data, section_name, img_path,id): """ Update data of report """ query = '''UPDATE report SET data = "{}" , section_name = "{}", image_path = "{}" WHERE id = "{}" '''.format(data, section_name, img_path, id) result = ge...
995d17b364bcb6a0b338b1b0323b0fd1f7692f25
3,645,020
from datetime import datetime def keyboard(table, day=None): """Handler for showing the keyboard statistics page.""" cols, group = "realkey AS key, COUNT(*) AS count", "realkey" where = (("day", day),) if day else () counts_display = counts = db.fetch(table, cols, where, group, "count DESC") if "c...
d3053f06b85d6606353b71a76096558d760e5a8e
3,645,021
def tsCrossValidationScore(params, series,loss_function=mean_squared_error, nsplits=3, slen=1): """ #Parameters: params : vector of parameters for optimization (three parameters: alpha, beta, gamma for example series : dataset with timeseries sle: ...
f3278ad55a423f6df0b108636c88151a72451cfa
3,645,023
from typing import Any def get_psf_fwhm(psf_template: np.ndarray) -> float: """ Fit a symmetric 2D Gaussian to the given ``psf_template`` to estimate the full width half maximum (FWHM) of the central "blob". Args: psf_template: A 2D numpy array containing the unsaturated PSF templ...
1982d89eb5f952d10336003e4d580fda3ab210b7
3,645,024
def sqrt(number): """ Calculate the floored square root of a number Args: number(int): Number to find the floored squared root Returns: (int): Floored Square Root """ assert number >= 0, 'Only square root of positive numbers are valid' start = 0 end = number res = None...
7ed4d547e0dbabebff7ffdf1e368817a415cbb9e
3,645,025
def repetition_sigmoid(M): """ Used to model repetition-driven effects of STDP. More repetitions results in stronger increase/decrease. """ return 1.0/(1+np.exp(-0.2*M+10))
5cfae40b12f2ff871b60f9cad13308b8bb9189b9
3,645,026
def generate_features(ids0, ids1, forcefield, system, param): """ This function performs a minimization of the energy and computes the matrix features. :param ids0: ids of the atoms for the 1st protein :param ids1: ids of the atoms for the 2nd protein :param forcefield: forcefield for OpenMM simula...
86fbc0fa67ea5a14b38af4c1fc37566b066b50a3
3,645,027
def extract_bow_feature_vectors(reviews, dictionary): """ Inputs a list of string reviews Inputs the dictionary of words as given by bag_of_words Returns the bag-of-words feature matrix representation of the data. The returned matrix is of shape (n, m), where n is the number of reviews and m the...
3373179024127ab0202ab50f3e20184d02ed016c
3,645,028
from astropy.io.fits import Header from scipy.optimize import least_squares def model_wcs_header(datamodel, get_sip=False, order=4, step=32): """ Make a header with approximate WCS for use in DS9. Parameters ---------- datamodel : `jwst.datamodels.ImageModel` Image model with full `~g...
1b43d5382b92f7da47d72dcf5acaaca65c6329df
3,645,029
def create_session(): """Return a session to be used for database connections Returns: Session: SQLAlchemy session object """ # Produces integrity errors! # return _Session() # db.session is managed by Flask-SQLAlchemy and bound to a request return db.session
8c7dbc2ee1db64cfbbb3466704a7e4f70ef073be
3,645,030
def meta_to_indexes(meta, table_name=None, model_name=None): """Find all the indexes (primary keys) based on the meta data """ indexes, pk_field = {}, None indexes = [] for meta_model_name, model_meta in meta.iteritems(): if (table_name or model_name) and not (table_name == model_meta['Met...
12c12055f424680a68d81d5466dc6d3515d797a5
3,645,031
def index(): """Render and return the index page. This is a informational landing page for non-logged-in users, and the corp homepage for those who are logged in. """ success, _ = try_func(auth.is_authenticated) if success: module = config.get("modules.home") if module: ...
9ebc7a98ee60a59a5bed6ec5a726c5c1a5a11ca7
3,645,032
def _(origin, category="", default=None): """ This function returns the localized string. """ return LOCALIZED_STRINGS_HANDLER.translate(origin, category, default)
58f1d7033b1689068bf1bcb532eea78e8bf51250
3,645,033
from datetime import datetime def next_month(month: datetime) -> datetime: """Find the first day of the next month given a datetime. :param month: the date :type month: datetime :return: The first day of the next month. :rtype: datetime """ dt = this_month(month) return datetime((dt+_...
1d5cb70fa7b3d98689e3dd967aa95deb29f5de45
3,645,034
from typing import Mapping from typing import OrderedDict def walk_json(d, func): """ Walk over a parsed JSON nested structure `d`, apply `func` to each leaf element and replace it with result """ if isinstance(d, Mapping): return OrderedDict((k, walk_json(v, func)) for k, v in d.items()) elif...
cc977f4cf3eaec03bd591fa4cd1e44ab5717caee
3,645,035
def getUser(): """This method will be called if a GET request is made to the /user/ route It will get the details of a specified user Parameters ---------- username the name of the user to get info about Raises ------ DoesNotExist Raised if the username provided doe...
edc8570b83e4a173ac8028f2d8b51e93a19b27a1
3,645,036
import types def _create_ppo_agent( time_step_spec: types.NestedTensorSpec, action_spec: types.NestedTensorSpec, preprocessing_layers: types.NestedLayer, policy_network: types.Network) -> tfa.agents.TFAgent: """Creates a ppo_agent.""" actor_network = policy_network( time_step_spec.observation, ...
931e7078bdf634187ac0a506decb2d651373fbab
3,645,037
def stiffness_matrix_CST(element=tetra_4()): """Calculate stiffness matrix for linear elasticity""" element.volume() B = strain_matrix_CST(element) D = material() print('B') print(B) print('V',element.V) return element.V * np.dot(np.dot(np.transpose(B),D),B)
5c5c443ab1007997848357d698fcce91f069a13f
3,645,038
async def can_action_member(bot, ctx: SlashContext, member: discord.Member) -> bool: """ Stop mods from doing stupid things. """ # Stop mods from actioning on the bot. if member.id == bot.user.id: return False # Stop mods from actioning one another, people higher ranked than them or themselves....
c3fa4eee66ec80df2c4f91cfee181d900f0b8c45
3,645,039
import types def trim_waveform_signal( tr: obspy.Trace, cfg: types.ModuleType = config ) -> obspy.Trace: """Cut the time series to signal window Args: tr: time series cfg: configuration file Returns: tr: trimmed time series """ starttime, en...
bce3a0f88903b7c62c287f6e40bb7d377215a45d
3,645,040
def animation_plot( x, y, z_data, element_table, ani_fname, existing_fig, ani_funcargs=None, ani_saveargs=None, kwargs=None, ): """ Tricontourf animation plot. Resulting file will be saved to MP4 """ global tf # Subtract 1 from element table to alig...
e9ef60c6240900de6fd082ff5933dbbbc471933a
3,645,041
def preprocess_adj(adj): """Preprocessing of adjacency matrix for simple GCN model and conversion to tuple representation.""" # adj_appr = np.array(sp.csr_matrix.todense(adj)) # # adj_appr = dense_lanczos(adj_appr, 100) # adj_appr = dense_RandomSVD(adj_appr, 100) # if adj_appr.sum(1).min()<0: # ...
82674be0b9573c24135e56f2a5e3988fbb0966e1
3,645,042
def plot_figure_one_input_resource_2(style_label=""): """ Plot two bar graphs side by side, with letters as x-tick labels. latency_dev_num_non_reuse.log """ prng = np.random.RandomState(96917002) #plt.set_cmap('Greys') #plt.rcParams['image.cmap']='Greys' # Tweak the figure size to b...
69c25829adf9ef3d5dc818621bb724bb92c29f31
3,645,043
def comp_rot_dir(self): """Compute the rotation direction of the winding Parameters ---------- self : LamSlotWind A LamSlotWind object Returns ------- rot_dir : int -1 or +1 """ MMF = self.comp_mmf_unit() p = self.get_pole_pair_number() # Compute rotation ...
524fdfd195a70bcd07b89e594a90e624ec4db4ea
3,645,044
def search_pk(uuid): """uuid can be pk.""" IterHarmonicApprox = WorkflowFactory("phonopy.iter_ha") qb = QueryBuilder() qb.append(IterHarmonicApprox, tag="iter_ha", filters={"uuid": {"==": uuid}}) PhonopyWorkChain = WorkflowFactory("phonopy.phonopy") qb.append(PhonopyWorkChain, with_incoming="ite...
d1a8d9d32e6d3272d49163ee8abf74363a520c8d
3,645,045
def _region_bulk(mode='full', scale=.6): """ Estimate of the temperature dependence of bulk viscosity zeta/s. """ plt.figure(figsize=(scale*textwidth, scale*aspect*textwidth)) ax = plt.axes() def zetas(T, zetas_max=0, zetas_width=1): return zetas_max / (1 + ((T - Tc)/zetas_width)**2) ...
9a76f28b47a5e8c1ce45a9ea0dcaef723032bcce
3,645,046
def bias(struct,subover=True,trim=True, subbias=False, bstruct=None, median=False, function='polynomial',order=3,rej_lo=3,rej_hi=3,niter=10, plotover=False, log=None, verbose=True): """Bias subtracts the bias levels from a frame. It will fit and subtract the overscan region, trim the images...
035da6b5eaa73a30ffec3f148d33199b275529a8
3,645,047
def getItemStatus(selected_item, store_id, num_to_average): """ Method pulls the stock status of the selected item in the given store :param selected_item: current item being processed (toilet paper or hand sanitizer) :param store_id: id of the current store :param num_to_average: number of recent stat...
00c0ecdec56ac4446b3db247fd234daeecada589
3,645,048
def filter_and_copy_table(tab, to_remove): """ Filter and copy a FITS table. Parameters ---------- tab : FITS Table object to_remove : [int ...} list of indices to remove from the table returns FITS Table object """ nsrcs = len(tab) mask = np.zeros((nsrcs), '?') mas...
cc13a002715c36cc2c07b836a5045cfb62311529
3,645,049
def _archive_logs(conn, node_type, logger, node_ip): """Creates an archive of all logs found under /var/log/cloudify plus journalctl. """ archive_filename = 'cloudify-{node_type}-logs_{date}_{ip}.tar.gz'.format( node_type=node_type, date=get_host_date(conn), ip=node_ip ) ...
970683258d664a1170fe9ab5253287313fa9f871
3,645,050
def get_scripts(): """Returns the list of available scripts Returns: A dict holding the result message """ return Response.ok("Script files successfully fetched.", { "scripts": list_scripts() })
5aa2ecd9a19c3e4d577c679e5249b71b01b62f20
3,645,051
from typing import Any from typing import Optional import functools import contextvars import asyncio from typing import cast async def invoke( fn: callbacks.BaseFn, *args: Any, settings: Optional[configuration.OperatorSettings] = None, cause: Optional[causation.BaseCause] = None, ...
4f132bab3eaae0ebe64f4cfdcfefa89cd2b59f3f
3,645,052
from datetime import datetime def home(): """Renders the home page.""" return render_template( 'index.html', title='Rococal', year=datetime.now().year, )
4cee1eed6c45d79aad0acebdd55ed61ef7dff9da
3,645,054
def Dx(x): """Nombre de survivants actualisés. Args: x: l'âge. Returns: Nombre de survivants actualisés. """ return lx(x)*v**x
886fdfb8b5337e9520f94fa937cb967328391823
3,645,055
def tracek(k,aee,aii,see,sii,tau=1,alpha=0): """ Trace of recurrently connected network of E,I units, analytically determined input: k: spatial frequency aee: ampltidue E to E connectivity aii: ampltidue I to I connectivity see: standard deviation/width of E to E connectivity sii: standard deviation/width of I ...
005c612f8d54b4ba61b7e701d40b9814136695b4
3,645,056
def get_verbose_name(model_or_queryset, field): """ returns the value of the ``verbose_name`` of a field typically used in the templates where you can have a dynamic queryset :param model_or_queryset: target object :type model_or_queryset: :class:`django.db.models.Model`, :class:`django.db.query....
1f395d62a20b307dce2f802c498630fd237aec33
3,645,058
def if_then_else(cond, t, f, span=None): """Conditional selection expression. Parameters ---------- cond : PrimExpr The condition t : PrimExpr The result expression if cond is true. f : PrimExpr The result expression if cond is false. span : Optional[Span] ...
dba758c13d3108244f389f0cbae97c1eeb1f8e04
3,645,059
def get_resources(filetype): """Find all HTML template or JavaScript files in the package. Caches the results for quick access. Parameters ---------- filetype : {'templates', 'js'} The type of file resource needed. Returns ------- :class:`dict` A dictionary mapping fil...
73244ac590db5a310170142b6b43b7840cfc94ca
3,645,061
def sum_fn(xnum, ynum): """ A function which performs a sum """ return xnum + ynum
61a1ae2e4b54348b9e3839f7f2779edd03f181df
3,645,062