content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def tau_for_x(x, beta): """Rescales tau axis to x -1 ... 1""" if x.min() < -1 or x.max() > 1: raise ValueError("domain of x") return .5 * beta * (x + 1)
1d7b868dfadb65e6f98654276763fd4bff2c20ff
3,653,700
from typing import Optional from typing import Dict def _generate_element(name: str, text: Optional[str] = None, attributes: Optional[Dict] = None) -> etree.Element: """ generate an ElementTree.Element object :param name: namespace+tag_name of the element :...
d7d8f7d174f207d64993aca54803af6600c3ddb6
3,653,701
def CoA_Cropland_URL_helper(*, build_url, config, **_): """ This helper function uses the "build_url" input from flowbyactivity.py, which is a base url for data imports that requires parts of the url text string to be replaced with info specific to the data year. This function does not parse the dat...
5cd08b8c4198428e45267f33d35d98b63df4fd17
3,653,702
def _centered_bias(logits_dimension, head_name=None): """Returns `logits`, optionally with centered bias applied. Args: logits_dimension: Last dimension of `logits`. Must be >= 1. head_name: Optional name of the head. Returns: Centered bias `Variable`. Raises: ValueError: if `logits_dimension...
868fc2681ee1177932b77bdfe9ce9eefc3c5fde1
3,653,703
from typing import Union from typing import List def get_columns(dataframe: pd.DataFrame, columns: Union[str, List[str]]) -> Union[pd.Series, pd.DataFrame]: """Get the column names, and can rename according to list""" return dataframe[list(columns)].copy(True)
e624233a3aca3f71f203bf7acca700722819b237
3,653,704
import pandas import math def get_vote_activity(session): """Create a plot showing the inline usage statistics.""" creation_date = func.date_trunc("day", Vote.created_at).label("creation_date") votes = ( session.query(creation_date, func.count(Vote.id).label("count")) .group_by(creation_da...
9b59ad083147d7e21d8d32e730b235a23b187c0f
3,653,705
def viz_graph(obj): """ Generate the visulization of the graph in the JupyterLab Arguments ------- obj: list a list of Python object that defines the nodes Returns ----- nx.DiGraph """ G = nx.DiGraph() # instantiate objects for o in obj: for i in o['input...
a826438b3e207f88a7bddddcd4fc02a4ad9c753d
3,653,706
def zrand_convolve(labelgrid, neighbors='edges'): """ Calculates the avg and std z-Rand index using kernel over `labelgrid` Kernel is determined by `neighbors`, which can include all entries with touching edges (i.e., 4 neighbors) or corners (i.e., 8 neighbors). Parameters ---------- grid ...
4b3950239886cb7e41fb2a7105c2413234dcdb30
3,653,707
def msg_receiver(): """ 消息已收界面 :return: """ return render_template('sysadmin/sysmsg/sys_msg_received.html', **locals())
0902f9eb4ad75802d7f858f4474c5e587082403f
3,653,708
from datetime import datetime def abs_timedelta(delta): """Returns an "absolute" value for a timedelta, always representing a time distance.""" if delta.days < 0: now = datetime.datetime.now() return now - (now + delta) return delta
81018ea9c54585a8c24e52cc48c21fcb2d73e9b3
3,653,709
import subprocess def is_word_file(file): """ Check to see if the given file is a Word file. @param file (str) The path of the file to check. @return (bool) True if the file is a Word file, False if not. """ typ = subprocess.check_output(["file", file]) return ((b"Microsoft Office Word" ...
cb297e9cf8ed709e9802f1d3d48bc7d1271eac26
3,653,710
def make_new_get_user_response(row): """ Returns an object containing only what needs to be sent back to the user. """ return { 'userName': row['userName'], 'categories': row['categories'], 'imageName': row['imageName'], 'refToImage': row['refToImage'], ...
e13d8d297bd1401752ce07d93a68e765ed1113e8
3,653,711
def upload_bus_data(number: int) -> dict: """Загружает данные по матерям из базы""" logger.debug("Стартует upload_bus_data") try: query = ProfilsCows.select().where( ProfilsCows.number == number ) if query.exists(): bus = ProfilsCows.select().where( ...
fa1697cb1e67410d7c8da74f299fe2ed38990257
3,653,712
def is_feature_enabled(): """ Helper to check Site Configuration for ENABLE_COURSE_ACCESS_GROUPS. :return: bool """ is_enabled = bool(configuration_helpers.get_value('ENABLE_COURSE_ACCESS_GROUPS', default=False)) if is_enabled: # Keep the line below in sync with `util.organizations_hel...
57f0b94409d9332f8846d64a6a30518b6dcc8173
3,653,713
def solve_disp_eq(betbn, betbt, bet, Znak, c, It, Ia, nb, var): """ Решение дисперсионного уравнения. Znak = -1 при преломлении Znak = 1 при отражении """ betb = sqrt(betbn ** 2. + betbt ** 2.) gamb = 1. / sqrt(1. - betb ** 2.) d = c * It / Ia Ab = 1. + (nb ** 2. - 1.) * gamb ** 2. *...
b67b41cdccf37a14fda103b6f05263c7cbb4514e
3,653,714
import numpy def phistogram(view, a, bins=10, rng=None, normed=False): """Compute the histogram of a remote array a. Parameters ---------- view IPython DirectView instance a : str String name of the remote array bins : int Number of histogra...
3c4633891b495a5cad867c945a8f8cc1c6b3c14f
3,653,715
from typing import Iterable from typing import Iterator def windowed(it: Iterable[_T], size: int) -> Iterator[tuple[_T, ...]]: """Retrieve overlapped windows from iterable. >>> [*windowed(range(5), 3)] [(0, 1, 2), (1, 2, 3), (2, 3, 4)] """ return zip(*(islice(it_, start, None) fo...
6e3b29b67f9eb323d00065fa58ccd916c7c49640
3,653,716
def minmax(data): """Solution to exercise R-1.3. Takes a sequence of one or more numbers, and returns the smallest and largest numbers, in the form of a tuple of length two. Do not use the built-in functions min or max in implementing the solution. """ min_idx = 0 max_idx = 0 for idx, n...
9715bef69c120f6d1afb933bd9030240f556eb20
3,653,717
def sample_discreate(prob, n_samples): """根据类先验分布对标签值进行采样 M = sample_discreate(prob, n_samples) Input: prob: 类先验分布 shape=(n_classes,) n_samples: 需要采样的数量 shape = (n_samples,) Output: M: 采样得到的样本类别 shape = (n_samples,) 例子: sample_discreate([0.8,0.2],n_sa...
34c19c2dcbad652bdae8f2c829f42934c2176e84
3,653,718
from xml.dom.minidom import parseString # tools for handling XML in python def get_catalyst_pmids(first, middle, last, email, affiliation=None): """ Given an author's identifiers and affiliation information, optional lists of pmids, call the catalyst service to retrieve PMIDS for the author and return a ...
d0cb5560ec8e6f80627b40c4623683732c84dc7c
3,653,719
def validar(request, op): """ Método que verifica consistência a partir de um log """ lista_datas = [] # arquivo de log para consistência with open(settings.BASE_DIR + "/log.txt", "r+") as fileobj: for line in fileobj: #pega cada linha do arquivo if "inicio" in line: ...
7a86d9c15ae632912039c26e74eb677f2ffd7257
3,653,720
from typing import List from typing import Dict def upload_categories_to_fyle(workspace_id): """ Upload categories to Fyle """ try: fyle_credentials: FyleCredential = FyleCredential.objects.get(workspace_id=workspace_id) xero_credentials: XeroCredentials = XeroCredentials.objects.get(w...
0efcdc205a3aaa33acd88a231984ab9407d994ac
3,653,721
def georegister_px_df(df, im_fname=None, affine_obj=None, crs=None, geom_col='geometry', precision=None): """Convert a dataframe of geometries in pixel coordinates to a geo CRS. Arguments --------- df : :class:`pandas.DataFrame` A :class:`pandas.DataFrame` with polygons in...
e310fee04d214186f60965e68fb2b896b8ad0004
3,653,722
def load_ui_type(ui_file): """ Pyside "load_ui_type" command like PyQt4 has one, so we have to convert the ui file to py code in-memory first and then execute it in a special frame to retrieve the form_class. """ parsed = xml.parse(ui_file) widget_class = parsed.find('widget').get('class')...
1f9bfc05d52fd8f25d63104c93f675cc8e978501
3,653,723
def how_did_I_do(MLP, df, samples, expected): """Simple report of expected inputs versus actual outputs.""" predictions = MLP.predict(df[samples].to_list()) _df = pd.DataFrame({"Expected": df[expected], "Predicted": predictions}) _df["Correct"] = _df["Expected"] == _df["Predicted"] print(f'The netwo...
5fbebeac01dad933c20b3faf3f8682ae59d173ba
3,653,724
def all_bootstrap_os(): """Return a list of all the OS that can be used to bootstrap Spack""" return list(data()['images'])
b7a58aabe17ee28ed783a9d43d1d8db5d0b85db3
3,653,725
def coords_to_volume(coords: np.ndarray, v_size: int, noise_treatment: bool = False) -> np.ndarray: """Converts coordinates to binary voxels.""" # Input is centered on [0,0,0]. return weights_to_volume(coords=coords, weights=1, v_size=v_size, noise_treatment=noise_treatment)
62e2ba5549faff51e4da68f6bc9521ff2f9ce9cb
3,653,726
def logo(symbol, external=False, vprint=False): """:return: Google APIs link to the logo for the requested ticker. :param symbol: The ticker or symbol of the stock you would like to request. :type symbol: string, required """ instance = iexCommon('stock', symbol, 'logo', external=external) retu...
320755632f81686ceb35a75b44c5176893ea37e2
3,653,727
def get_dependency_node(element): """ Returns a Maya MFnDependencyNode from the given element :param element: Maya node to return a dependency node class object :type element: string """ # adds the elements into an maya selection list m_selectin_list = OpenMaya.MSelectionList() m_selectin_...
d573b14cf7ba54fd07f135d37c90cfe75e74992a
3,653,728
def create_lineal_data(slope=1, bias=0, spread=0.25, data_size=50): """ Helper function to create lineal data. :param slope: slope of the lineal function. :param bias: bias of the lineal function. :param spread: spread of the normal distribution. :param data_size: number of samples to generate....
fa735416a1f23a5aa29f66e353d187a5a896df7a
3,653,729
def parse_station_resp(fid): """ Gather information from a single station IRIS response file *fid*. Return the information as a :class:`RespMap`. """ resp_map = RespMap() # sanity check initialization network = None stn = None location = None # skip initial header comment block ...
9d61b2c033008fc594b230aad83378a442cb748b
3,653,730
def plot_pol(image, figsize=(8,8), print_stats=True, scaled=True, evpa_ticks=True): """Mimics the plot_pol.py script in ipole/scripts""" fig, ax = plt.subplots(2, 2, figsize=figsize) # Total intensity plot_I(ax[0,0], image, xlabel=False) # Quiver on intensity if evpa_ticks: plot_evpa_ti...
dc3741703435bb95b7ea511460d9feda39ea11f3
3,653,731
def dbrg(ds, T, r): """ Segmentation by density-based region growing (DBRG). Parameters ---------- ds : np.ndarray The mask image. T : float Initial mask threshold. r : int Density connectivity search radius. """ M = _generate_init_mask(ds, T) D = _densit...
8b83c1335080ebda6087489d76db7bbbcc5d3b29
3,653,732
def _ensure_dtype_type(value, dtype: DtypeObj): """ Ensure that the given value is an instance of the given dtype. e.g. if out dtype is np.complex64_, we should have an instance of that as opposed to a python complex object. Parameters ---------- value : object dtype : np.dtype or Exte...
36de4b993e2da0bacf3228d46e13332f89346210
3,653,733
from typing import List def format_batch_request_last_fm(listens: List[Listen]) -> Request: """ Format a POST request to scrobble the given listens to Last.fm. """ assert len(listens) <= 50, 'Last.fm allows at most 50 scrobbles per batch.' params = { 'method': 'track.scrobble', 's...
8f7b36b6880ecd91e19282b80975cccc999014b6
3,653,734
import os import logging import time def train_eval( root_dir, gpu=0, env_load_fn=None, model_ids=None, reload_interval=None, eval_env_mode='headless', num_iterations=1000000, conv_1d_layer_params=None, conv_2d_layer_params=None, encoder_...
5fe4a1798b8d521af8cfc70b04af177203aa1aa0
3,653,735
import os def file_mtime_ns(file): """Get the ``os.stat(file).st_mtime_ns`` value.""" return os.stat(file).st_mtime_ns
20b384549dae19e35d02b85b20dd62271352f08d
3,653,736
def get_entry_for_file_attachment(item_id, attachment): """ Creates a file entry for an attachment :param item_id: item_id of the attachment :param attachment: attachment dict :return: file entry dict for attachment """ entry = fileResult(get_attachment_name(attachment.name), attachment.cont...
c3d10402da0ada14289a7807ef1a57f97c6a22ba
3,653,737
def check_all_particles_present(partlist, gambit_pdg_codes): """ Checks all particles exist in the particle_database.yaml. """ absent = [] for i in range(len(partlist)): if not partlist[i].pdg() in list(gambit_pdg_codes.values()): absent.append(partlist[i]) absent_...
eab49388d472934a61900d8e972c0f2ef01ae1fb
3,653,738
def binarize_tree(t): """Convert all n-nary nodes into left-branching subtrees Returns a new tree. The original tree is intact. """ def recurs_binarize_tree(t): if t.height() <= 2: return t[0] if len(t) == 1: return recurs_binarize_tree(t[0]) elif len(t)...
5f9bc8ab7a0c1ab862b7366b188072006a80ff51
3,653,739
def calculate_prfs_using_rdd(y_actual, y_predicted, average='macro'): """ Determines the precision, recall, fscore, and support of the predictions. With average of macro, the algorithm Calculate metrics for each label, and find their unweighted mean. See http://scikit-learn.org/stable/modules/generated/...
01fadc6a03f6ce24e736da9d1cfd088b490aa482
3,653,740
def translation_from_matrix(M): """Returns the 3 values of translation from the matrix M. Parameters ---------- M : list[list[float]] A 4-by-4 transformation matrix. Returns ------- [float, float, float] The translation vector. """ return [M[0][3], M[1][3], M[2][3]...
2b3bddd08772b2480a923a778d962f8e94f4b78a
3,653,741
def saving_filename_boundary(save_location, close_up, beafort, wave_roughness): """ Setting the filename of the figure """ if close_up is None: return save_location + 'Boundary_comparison_Bft={}_roughness={}.png'.format(beafort, wave_roughness) else: ymax, ymin = close_up return save...
c0357a211adc95c35873a0f3b0c900f6b5fe42d0
3,653,742
def get_library() -> CDLL: """Return the CDLL instance, loading it if necessary.""" global LIB if LIB is None: LIB = _load_library("aries_askar") _init_logger() return LIB
64183953e7ab3f4e617b050fbf985d79aebc9b95
3,653,743
def childs_page_return_right_login(response_page, smarsy_login): """ Receive HTML page from login function and check we've got expected source """ if smarsy_login in response_page: return True else: raise ValueError('Invalid Smarsy Login')
e7cb9b8d9df8bd5345f308e78cec28a20919370e
3,653,744
def merge_files(intakes, outcomes): """ Merges intakes and outcomes datasets to create unique line for each animal in the shelter to capture full stories for each animal takes intakes file then outcomes file as arguments returns merged dataset """ # Merge intakes and outcomes on animal id and yea...
c7110cf1b5fe7fad52c3e331c8d6840de83891b3
3,653,745
def _ssepdpsolve_single_trajectory(data, Heff, dt, times, N_store, N_substeps, psi_t, dims, c_ops, e_ops): """ Internal function. See ssepdpsolve. """ states_list = [] phi_t = np.copy(psi_t) prng = RandomState() # todo: seed it r_jump, r_op = prng.rand(2) jump_times = [] jump_op_...
0d83b67049d2e48ec3c887339b7d1c935cd897c7
3,653,746
def construct_features_MH_1(data): """ Processes the provided pandas dataframe object by: Deleting the original METER_ID, LOCATION_NO, BILLING_CYCLE, COMMENTS, and DAYS_FROM_BILLDT columns Constructing a time series index out of the year, month, day, hour, minute, second columns Sorting by the tim...
32f238ee730e84c0c699759913ffd2f6a2fc6fbf
3,653,747
from functools import cmp_to_key def sort_observations(observations): """ Method to sort observations to make sure that the "winner" is at index 0 """ return sorted(observations, key=cmp_to_key(cmp_observation), reverse=True)
183b044a48b4a7ea5093efaa92bd0977b085d949
3,653,748
def coor_trans(point, theta): """ coordinate transformation (坐标转换) theta方向:以顺时针旋转为正 """ point = np.transpose(point) k = np.array([[np.cos(theta), np.sin(theta)], [-np.sin(theta), np.cos(theta)]]) print(point) # return np.dot(k, point) return np.round(np.dot(k, point),6)
aa3b1532c629011e6f0ce72dc80eb1eebfc43765
3,653,749
import torch import time def ppo( env_fn, actor_critic=core.MLPActorCritic2Heads, ac_kwargs=dict(), seed=0, steps_per_epoch=4000, epochs=100, epochs_rnd_warmup=1, gamma=0.99, clip_ratio=0.2, pi_lr=3e-4, vf_lr=1e-3, rnd_lr=1e-3, train_pi_iters=80, train_v_iters=8...
481da1fc7cc0677e02009d983345a15fbca23159
3,653,750
import heapq def ltopk(k, seq, key=None): """ >>> ltopk(2, [1, 100, 10, 1000]) [1000, 100] >>> ltopk(2, ['Alice', 'Bob', 'Charlie', 'Dan'], key=len) ['Charlie', 'Alice'] """ if key is not None and not callable(key): key = getter(key) return list(heapq.nlargest(k, seq, key=key))
3d41f8576ca6b2741d12ca8b80c8fb220166b85b
3,653,751
def index(): """ Root URL response """ return ( jsonify( name="Promotion REST API Service", version="1.0", ), status.HTTP_200_OK, )
7c45e54c3500f638291c85d38d27976952d0a6e3
3,653,752
def add_cameras_default(scene): """ Make two camera (main/top) default setup for demo images.""" cam_main = create_camera_perspective( location=(-33.3056, 24.1123, 26.0909), rotation_quat=(0.42119, 0.21272, -0.39741, -0.78703), ) scene.collection.objects.link(cam_main) cam_top = cre...
50428d5f3c79c4581e397af1411a5a92055fe695
3,653,753
def distr_mean_stde(distribution: np.ndarray) -> tuple: """ Purpose: Compute the mean and standard deviation for a distribution. Args: distribution (np.ndarray): distribution Returns: tuple (ie. distribution mean and standard deviation) """ # Compute and print the mean,...
9232587e2c1e71a8f7c672cb962961cab7ad8d85
3,653,754
from operator import and_ def release_waiting_requests_grouped_fifo(rse_id, count=None, direction='destination', deadline=1, volume=0, session=None): """ Release waiting requests. Transfer requests that were requested first, get released first (FIFO). Also all requests to DIDs that are attached to the sam...
9a52a28fe06634de73a0436721aa97e590612e17
3,653,755
def _get_gap_memory_pool_size_MB(): """ Return the gap memory pool size suitable for usage on the GAP command line. The GAP 4.5.6 command line parser had issues with large numbers, so we return it in megabytes. OUTPUT: String. EXAMPLES: sage: from sage.interfaces.gap import ...
035072ff6fff18859717b131cdd660f252ac6262
3,653,756
async def order_book_l2(symbol: str) -> dict: """オーダーブックを取得""" async with pybotters.Client(base_url=base_url, apis=apis) as client: r = await client.get("/orderBook/L2", params={"symbol": symbol,},) data = await r.json() return data
4c9b8e067874871cda8b9a9f113f8ff6e4529c02
3,653,757
import json import sys def _load_json(json_path): """Load JSON from a file with a given path.""" # Note: Binary so load can detect encoding (as in Section 3 of RFC 4627) with open(json_path, 'rb') as json_file: try: return json.load(json_file) except Exception as ex: ...
86a6ab7c509c24a50c248134e01a7d61d1499adb
3,653,758
async def create_comment_in_post(*, post: models.Post = Depends(resolve_post), created_comment: CreateComment, current_user: models.User = Depends(resolve_current_user), db: Session = Depends(get_db)): """Create a comment in a post.""" return cru...
90e4a8628d631bcb33eb5462e0e8001f90fb5c86
3,653,759
def sigma_bot(sigma_lc_bot, sigma_hc_bot, x_aver_bot_mass): """ Calculates the surface tension at the bottom of column. Parameters ---------- sigma_lc_bot : float The surface tension of low-boilling component at the bottom of column, [N / m] sigma_hc_bot : float The surface tensi...
5105e5592556cab14cb62ab61b4f242499b33e1d
3,653,760
def _normalize_zonal_lat_lon(ds: xr.Dataset) -> xr.Dataset: """ In case that the dataset only contains lat_centers and is a zonal mean dataset, the longitude dimension created and filled with the variable value of certain latitude. :param ds: some xarray dataset :return: a normalized xarray dataset ...
0a6021cc22271d6489a1a946e5ff38a6019ae3e8
3,653,761
def setup_audio(song_filename): """Setup audio file and setup setup the output device.output is a lambda that will send data to fm process or to the specified ALSA sound card :param song_filename: path / filename to music file :type song_filename: str :return: output, fm_process, fft_calc, mus...
63ca73faf6511047d273e3b36d3ef450dc073a2f
3,653,762
def _collect_package_prefixes(package_dir, packages): """ Collect the list of prefixes for all packages The list is used to match paths in the install manifest to packages specified in the setup.py script. The list is sorted in decreasing order of prefix length so that paths are matched with t...
6c497725e8a441f93f55084ef42489f97e35acf8
3,653,763
def _grae_ymin_ ( graph ) : """Get minimal y for the points >>> graph = ... >>> ymin = graph.ymin () """ ymn = None np = len(graph) for ip in range( np ) : x , exl , exh , y , eyl , eyh = graph[ip] y = y - abs( eyl ) if None == ymn or y <= ymn : ymn = y ...
99efb6f6466e56b350da02963e442ac2b991ecf5
3,653,764
def get_working_id(id_: str, entry_id: str) -> str: """Sometimes new scanned files ID will be only a number. Should connect them with base64(MD5:_id). Fixes bug in VirusTotal API. Args: entry_id: the entry id connected to the file id_: id given from the API Returns: A working I...
d55fd0855fc954db0ff9a678de3c71529e0946ae
3,653,765
from keras import models from keras.layers import Dense from keras.layers import Dropout from keras.regularizers import l2 def merck_net(input_shape=(128)): """ # The recommended network presented in the paper: Junshui Ma et. al., Deep Neural Nets as a Method for Quantitative # Structure Activity Relatio...
d1c8b92c702752c42bf3c2780969ce0c3d64ff4c
3,653,766
def vec_sum(a, b): """Compute the sum of two vector given in lists.""" return [va + vb for va, vb in zip(a, b)]
d85f55e22a60af66a85eb6c8cd180007351bf5d9
3,653,767
import time def one_v_one_classifiers(x,y,lambd,max_iters,eps=.0001): """ Function for running a 1v1 classifier on many classes using the linearsvm function. Inputs: x: numpy matrix a matrix of size nxd y: numpy matrix a matrix of size nx1 lambd: float ...
3cf564039c78363021cb65650dd50db9536922bb
3,653,768
def rlsp(mdp, s_current, p_0, horizon, temp=1, epochs=1, learning_rate=0.2, r_prior=None, r_vec=None, threshold=1e-3, check_grad_flag=False): """The RLSP algorithm""" def compute_grad(r_vec): # Compute the Boltzmann rational policy \pi_{s,a} = \exp(Q_{s,a} - V_s) policy = value_iter(mdp...
d389363929f4e7261d72b0d9d83a806fae10b8ab
3,653,769
import numbers def rotate(img, angle=0, order=1): """Rotate image by a certain angle around its center. Parameters ---------- img : ndarray(uint16 or uint8) Input image. angle : integer Rotation angle in degrees in counter-clockwise direction. Retu...
8b55fe060ff6b8eb0c7137dc38a72531c24c7534
3,653,770
def activate(request, uidb64, token): """Function that activates the user account.""" try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_...
8538fc17e37b2743a7145286720ba5e8d653c790
3,653,771
def dfn(*args, **kwargs): """ The HTML Definition Element (<dfn>) represents the defining instance of a term. """ return el('dfn', *args, **kwargs)
798fb57360aca6f035ad993998c622eb6fff4e82
3,653,772
def _compile_rds_files_TRHP(array_codes, years_processed, filetypes_to_check, extensions_to_check, subfolder_filestypes): """ Get indexed information from server for Hydrothermal Vent Fluid Temperature and Resistivity (RS03INT1-MJ03C-10-TRHPHA301) Example where dat exi...
0d9d490f23afce4d9c5ed47725658127475d9231
3,653,773
def handle_post_runs(project_id, deployment_id): """Handles POST requests to /.""" is_experiment_deployment = False experiment_deployment = request.args.get('experimentDeploy') if experiment_deployment and experiment_deployment == 'true': is_experiment_deployment = True run_id = create_deplo...
5684a2b1f82981d4a3d5d7b870485b01201fdd2e
3,653,774
def get_in_reply_to_user_id(tweet): """ Get the user id of the uesr whose Tweet is being replied to, and None if this Tweet is not a reply. \n Note that this is unavailable in activity-streams format Args: tweet (Tweet): A Tweet object (or a dictionary) Returns: str: the user i...
74bbfa224f15781f769bf52bb470e23e9c93a95a
3,653,775
import os def cl35(): """Cl35 ENDF data (contains RML resonance range)""" endf_data = os.environ['OPENMC_ENDF_DATA'] filename = os.path.join(endf_data, 'neutrons', 'n-017_Cl_035.endf') return openmc.data.IncidentNeutron.from_endf(filename)
b202bfcd4f842a71429d374bcc4f65bcbf62b56b
3,653,776
def release_definition_show(definition_id=None, name=None, open_browser=False, team_instance=None, project=None, detect=None): """Get the details of a release definition. :param definition_id: ID of the definition. :type definition_id: int :param name: Name of the definition. I...
3a4f13a1dfb7f1bd95bf8eae52d41f14566eb5fb
3,653,777
def GKtoUTM(ea, no=None, zone=32, gk=None, gkzone=None): """Transform any Gauss-Krueger to UTM autodetect GK zone from offset.""" if gk is None and gkzone is None: if no is None: rr = ea[0][0] else: if isinstance(ea, list) or isinstance(ea, tuple): rr = ea...
330804d9bfe4785d867755b58355b0633d1fe7c8
3,653,778
def robots(req): """ .. seealso:: http://www.sitemaps.org/protocol.html#submit_robots """ return Response( "Sitemap: %s\n" % req.route_url('sitemapindex'), content_type="text/plain")
42e21c5968d7e6d02049a0539d5b115aa596292e
3,653,779
import numpy as np def bolling(asset:list, samples:int=20, alpha:float=0, width:float=2): """ According to MATLAB: BOLLING(ASSET,SAMPLES,ALPHA,WIDTH) plots Bollinger bands for given ASSET data vector. SAMPLES specifies the number of samples to use in computing the moving average. ALPHA is an op...
90c06bb45f30713a05cde865e23c0f9e317b0887
3,653,780
def metrics(): """ Expose metrics for the Prometheus collector """ collector = SensorsDataCollector(sensors_data=list(sensors.values()), prefix='airrohr_') return Response(generate_latest(registry=collector), mimetype='text/plain')
93a3de3fbddaeeeaafd182824559003701b718bc
3,653,781
def solar_energy_striking_earth_today() -> dict: """Get number of solar energy striking earth today.""" return get_metric_of(label='solar_energy_striking_earth_today')
a53c6e45f568d5b4245bbc993547b28f5414ca47
3,653,782
def write_data_str(geoms, grads, hessians): """ Writes a string containing the geometry, gradient, and Hessian for either a single species or points along a reaction path that is formatted appropriately for the ProjRot input file. :param geoms: geometries :type geoms: list :...
34c1148f820396bf4619ace2d13fb517e4f6f16d
3,653,783
import types from typing import Dict from typing import Any from typing import List def gen_chart_name(data: types.ChartAxis, formatter: Dict[str, Any], device: device_info.DrawerBackendInfo ) -> List[drawings.TextData]: """Generate the name of chart. ...
032abcb5e6fca1920965fdd20203614dd750c9c0
3,653,784
import re def _parse_whois_response(response): """ Dealing with the many many different interpretations of the whois response format. If an empty line is encountered, start a new record If a line with a semicolon is encountered, treat everything before first : as key and start a value If a line wi...
32978d5965c794b6f388d1e490bfaddd5c58d41f
3,653,785
from typing import Sequence def vector_cosine_similarity(docs: Sequence[spacy.tokens.Doc]) -> np.ndarray: """ Get the pairwise cosine similarity between each document in docs. """ vectors = np.vstack([doc.vector for doc in docs]) return pairwise.cosine_similarity(vectors)
14456abcbb038dd2a4c617690d7f68dfc7a7bcb8
3,653,786
def create_test_validation(): """ Returns a constructor function for creating a Validation object. """ def _create_test_validation(db_session, resource, success=None, started_at=None, secret=None): create_kwargs = {"resource": resource} for kwarg in ['success', 'started_at', 'secret']: ...
7d78ae1c999cb79151e7527fd5bad448946aaccc
3,653,787
def nrmse(img, ref, axes = (0,1)): """ Compute the normalized root mean squared error (nrmse) :param img: input image (np.array) :param ref: reference image (np.array) :param axes: tuple of axes over which the nrmse is computed :return: (mean) nrmse """ nominator = np.real(np.sum( (img - ref...
ab040a2dd88acb2ce1e7df3b37215c5a40092f8a
3,653,788
def pairwise_comparison(column1,var1,column2,var2): """ Arg: column1 --> column name 1 in df column2 --> column name 2 in df var1---> 3 cases: abbreviation in column 1 (seeking better model) abbreviation in column 1 (seeking lesser value in column1 in co...
a67ef991dcad4816e9b15c1f352079ce14d7d823
3,653,789
def prep_data_CNN(documents): """ Prepare the padded docs and vocab_size for CNN training """ t = Tokenizer() docs = list(filter(None, documents)) print("Size of the documents in prep_data {}".format(len(documents))) t.fit_on_texts(docs) vocab_size = len(t.word_counts) print("Vocab ...
a568942bdedbea99d6abf2bd5b8fc8c7912e4271
3,653,790
def gc2gd_lat(gc_lat): """Convert geocentric latitude to geodetic latitude using WGS84. Parameters ----------- gc_lat : (array_like or float) Geocentric latitude in degrees N Returns --------- gd_lat : (same as input) Geodetic latitude in degrees N """ wgs84_e2 = ...
e019a5a122266eb98dba830283091bcbf42f873f
3,653,791
import os import linecache import traceback def _coroutine_format_stack(coro, complete=False): """Formats a traceback from a stack of coroutines/generators. """ dirname = os.path.dirname(__file__) extracted_list = [] checked = set() for f in _get_coroutine_stack(coro): lineno = f.f_lin...
d9828a311150368a958691e286435a6c76b18078
3,653,792
def polynomial_kernel(X, Y, c, p): """ Compute the polynomial kernel between two matrices X and Y:: K(x, y) = (<x, y> + c)^p for each pair of rows x in X and y in Y. Args: X - (n, d) NumPy array (n datapoints each with d features) Y - (m, d) NumPy array (...
5532692b0a8411560f56033bcf6ad27b3c8e41a1
3,653,793
def slug_from_iter(it, max_len=128, delim='-'): """Produce a slug (short URI-friendly string) from an iterable (list, tuple, dict) >>> slug_from_iter(['.a.', '=b=', '--alpha--']) 'a-b-alpha' """ nonnull_values = [str(v) for v in it if v or ((isinstance(v, (int, float, Decimal)) and str(v)))] r...
0da42aa5c56d3012e5caf4a5ead37632d5d21ab0
3,653,794
def modulusOfRigidity(find="G", printEqs=True, **kwargs): """ Defines the slope of the stress-strain curve up to the elastic limit of the material. For most ductile materials it is the same in compression as in tensions. Not true for cast irons, other brittle materials, or magnesium. Where: E =...
cb849755799d85b9d4d0671f6656de748ab38f7c
3,653,795
async def async_unload_entry(hass: HomeAssistantType, entry: ConfigType) -> bool: """Unload FRITZ!Box Tools config entry.""" hass.services.async_remove(DOMAIN, SERVICE_RECONNECT) for domain in SUPPORTED_DOMAINS: await hass.config_entries.async_forward_entry_unload(entry, domain) del hass.data[...
e934ec21be451cc1084bd293dbce5495f6b4915c
3,653,796
def queryMaxTransferOutAmount(asset, isolatedSymbol="", recvWindow=""): """# Query Max Transfer-Out Amount (USER_DATA) #### `GET /sapi/v1/margin/maxTransferable (HMAC SHA256)` ### Weight: 5 ### Parameters: Name |Type |Mandatory |Description --------|--------|--------|-------- asset |STRING |YES | isolatedSymbol |...
f9e178d18eea969e5aabc0efa3aee938ad730752
3,653,797
def IteratePriorityQueueEntry(root, element_type, field_name): """ iterate over a priority queue as defined with struct priority_queue from osfmk/kern/priority_queue.h root - value : Value object for the priority queue element_type - str : Type of the link element field...
db0da178b5fef292267f0c2a2d2120833970e4bb
3,653,798
def remove_layer(nn, del_idx, additional_edges, new_strides=None): """ Deletes the layer indicated in del_idx and adds additional_edges specified in additional_edges. """ layer_labels, num_units_in_each_layer, conn_mat, mandatory_child_attributes = \ get_copies_from_old_nn(nn) # First add new edges to c...
33d4a2e6ba05000f160b0d0cc603c568f68790d7
3,653,799