content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def convert_to_uint8(data: np.ndarray) -> np.ndarray: """ Convert array content to uint8. If all negative values are changed on 0. If values are integer and bellow 256 it is simple casting otherwise maximum value for this data type is picked and values are scaled by 255/maximum type value. Bi...
b93fe84de10620bc5f2e0f16da67b1b2a71b9669
3,608,600
def spending_as_pos_value(credit_card_pd, bankName): """Make sure that the spending are listed as positive values Args: credit_card_pd (pandas.core.frame.DataFrame): The dataframe to modify Returns: pandas.core.frame.DataFrame: A dataframe with all the spending entries listed as positive v...
7887891b65cdc9f886419dd96f449c826c0835c7
3,608,601
def pr_notebook_filenames(pr_num): """Return all the notebook filenames in a given GitHub pull request. Args: pr_num: The pull request number. Returns: [str]: A list of strings containing paths to notebooks in the PR. """ return filter(is_notebook, [file.filename for file in get_p...
5a370fa84207ccd3e5157ace47112c13309c257b
3,608,602
def binh_korn(x, y): # pylint:disable=invalid-name """https://en.wikipedia.org/wiki/Test_functions_for_optimization""" obj1 = 4 * x ** 2 + 4 * y ** 2 obj2 = (x - 5) ** 2 + (y - 5) ** 2 return -obj1, -obj2
b15db03f14a21bbbf974c5465d20717efb27837b
3,608,603
def detect_lip(source: SOURCE_TYPES, offset: int = 0) -> FileFormat: """ Returns what format the LIP data is believed to be in. This function performs a basic check and does not guarantee accuracy of the result or integrity of the data. Args: source: Source of the LIP data. offset: Offs...
a6fdc9224629c18f415b94d592f67bdbd6ea7eda
3,608,604
def user_get_by_uid(context, uid): """Get user by uid.""" return IMPL.user_get_by_uid(context, uid)
0164625183e22a187dbfe96628e9bcb83b598114
3,608,605
def not_equal(evaluator, ast, state): """Evaluates "left != right".""" res = UppaalBool(evaluator.eval_ast(ast["left"], state) != evaluator.eval_ast(ast["right"], state)) return res
64c56bb9189a0256588519ce21ebddbcd4a4e0b5
3,608,606
import logging def build_user_json(me, resp=None): """user_json contains an h-card, rel-me links, and "me" Args: me: string, URL of the user, returned by resp: :class:`requests.Response` (optional), re-use response if it's already been fetched Return: dict, with 'me', the URL for this person...
84cdc97bb53a6e8a59928e1ce4263b760406725a
3,608,607
def create_or_modify(topic_name, question, answer, user): """ Creates or modifies a topic based if we have topics with the name entered and the user is the creator. """ query_ids = topics_by_id(topic_name) topic_com = None for topic_id in query_ids: topic = Topic.objects.get(id=topic_id) ...
1e0d47cb1f8cce0927f62ce38071bc0e184a3c3d
3,608,608
def match_comment_type(file_name): """ Check the type of a single file and return the correct charachter that needs to be checked for comments # -> python // -> Java # -> Textfile (my preference I recognize this loophole) """ if(file_name.endswith(".txt")): return "#" elif(file_n...
20c4c04e8e656862443ea5ce7584e383d6c72842
3,608,609
def micore_tf_copts(): """C options for Tensorflow builds. Returns: a list of copts which must be used by each cc_library which refers to Tensorflow. Enables the library to compile both for Android and for Linux. """ return tf_copts(android_optimization_level_override = None) + tf_opt...
d94c0a6c3c57b4ac4401863af9bd09848153fb23
3,608,610
def getDirName(): """ () -> None Get the directory name for the repo """ try: file = open('dirname', 'r') return file.read() except IOError: return None
ca05bbd8da05dd5f06f95bc457e31df9c9b9e45a
3,608,611
import operator def getdata(filename, *args, **kwargs): """ Get the data from an extension of a FITS file (and optionally the header). Parameters ---------- filename : file path, file object, or file like object File to get data from. If opened, mode must be one of the follow...
ada665bb516c1f940b8aa485ceb9f4876e7e7e79
3,608,612
def get_conversion_factor_WTE(volume): """Return conversion factor of thermal conductivity.""" return ( (THz * Angstrom) ** 2 # ----> group velocity * EV # ----> specific heat is in eV/ * Hbar # ----> transform lorentzian_div_hbar from eV^-1 to s / (volume * Angstrom**3) )
535ca4b4ca702cac72b10a6f8ec580a53b1ba844
3,608,613
import configparser def defaults_to_cfg(): """ Creates a blank template cfg with all accepted fields and reasonable default values Returns: config (ConfigParser): configuration object containing defaults """ config = configparser.ConfigParser(allow_no_value=True) config.add_section("General...
eba080ecae59ff7764a8558911a8357a14fe9778
3,608,614
def diagh2mat(dlow): """ Return hermitian matrix W from lower diagonal format. Parameters ---------- dlow: ndarray, shape=(N//2+1, N) Returns ------- ndarray, shape=(N, N) """ N = dlow.shape[-1] assert dlow.shape[-2] == N//2+1, "Seems dlow is out of shape!" W = np.zeros...
e40fc7f44077b0680d4c519120fa75b790e02e4a
3,608,615
def filter_submission(submission): """Determines whether to filter out this submission (over-18, deleted user, etc.).""" if submission["num_comments"] < args.mincomments: return True if "num_crossposts" in submission and submission["num_crossposts"] > 0: return True if "locked" in submis...
0e6a6c1b907d7e99aa9a96086103bd679ac64b6b
3,608,616
def Append(**kwargs): """ Recibe los nombres de los dataframes que se quieren añadir uno bajo el otro""" appenddf = pd.DataFrame() dfs = list(kwargs.values()) appenddf = appenddf.append(dfs, sort=False) appenddf.reset_index(drop=True, inplace=True) appenddf = appenddf.astype(object).where(pd.notnull(appenddf),No...
0f0a2d551e879a1e4d3c8a90f1d1a8e6b8c726a2
3,608,617
def get_plannings(client, page, per_page): """ Gets the list of all plannings in the database :param client: the client to make the request :param page: the page to be shown :param per_page: the amount of plannings per page :return: """ pagedetails = dict( page=page, page...
2ebfd016e4e32ec819f4bc5319cb980a1d4b2d6a
3,608,618
def to_rq_symbol(symbol: str, exchange: Exchange) -> str: """将交易所代码转换为米筐代码""" # 股票 if exchange in [Exchange.SSE, Exchange.SZSE]: if exchange == Exchange.SSE: rq_symbol = f"{symbol}.XSHG" else: rq_symbol = f"{symbol}.XSHE" # 金交所现货 elif exchange in [Exchange.SGE...
1f2189c2ad5aeacfe1035778e12758730a7fd1a2
3,608,619
def cat6(update: Update, _: CallbackContext) -> int: """Show new choice of buttons""" query = update.callback_query query.answer() keyboard = [ [InlineKeyboardButton("Katherine Johnson, la matemática que llevó astronautas", callback_data=str(ONE))], [InlineKeyboardButton("Ada Lovelace, l...
a96e9c12be60230cf0dc7e69a28513524203e2fa
3,608,620
import html def function_metrics(): """Determine the function metrics.""" settings = { "report_directory": "D:\\\\Projects\\github\\sqatt\\reports", "analysis_directory": "D:\\\\Projects\\github\\sqatt", "tokens": "20", "language": "python", } metrics_file = measure_f...
fb93dbc693999ec798c82517d77e12e73256554d
3,608,621
import torch def categorical_accuracy(preds, target): """ Returns accuracy per batch, i.e. if you get 8/10 right, this returns 0.8, NOT 8 """ max_preds = preds.argmax(dim=1, keepdim=True) # get the index of the max probability correct = max_preds.squeeze(1).eq(target) return correct.sum().to...
a37237b1a73efcef313a81d131e001e16ad506f7
3,608,622
from pathlib import Path def create_planar_paths(mesh, planes): """ Creates planar contours. Does not rely on external libraries. It is currently the only method that can return identify OPEN versus CLOSED paths. Parameters ---------- mesh: :class: 'compas.datastructures.Mesh' The mes...
eef2a06911ab262cddf4d6686d05062ced6d9beb
3,608,623
def process_switch_positions(switch_positions: list) -> list: """iterate through the list of binary switch positions, return the ascii equivalent""" ascii_characters = [] for byte in switch_positions: byte_as_string = "" for switch in byte: byte_as_string += str(switch) c...
9194dd103d02e1f79cdf8d81a84e540626898dc9
3,608,624
def triangle_area(x_data: np.ndarray, y_data: np.ndarray, i0: int, i1: int, i2: int) -> float: """ Compute area of triangle given by 3 points given by their coordinates *x_data* and *y_data*, and their indices *i0*, *i1*, *i2*. """ x0 = x_data[i0] y0 = y_data[i0] dx1 = x_data[i1] - x0 dy...
8d0e68527b548d61a5c4dd1592630182f3c5ea9c
3,608,625
import socket def get_hostname(): """Get hostname. """ return socket.getfqdn(socket.gethostname())
42a3ee2304e73c6858553c7fe00edd49c0747826
3,608,626
def horizontal_interp( lon_in_1d, lat_in_1d, mlat_misomip, mlon_misomip, lon_out_1d, lat_out_1d, var_in_1d ): """ Interpolates one-dimension data horizontally to a 2d numpy array reshaped to the misomip standard (lon,lat) format. Method: triangular linear barycentryc interpolation, using nans (i.e. gives nan...
25e03985f7f13079c61e7b5a658b2672d43e1b97
3,608,627
def cross_entropy_seq(logits, target_seqs, batch_size=None):#, batch_size=1, num_steps=None): """Returns the expression of cross-entropy of two sequences, implement softmax internally. Normally be used for Fixed Length RNN outputs. Parameters ---------- logits : Tensorflow variable 2D tenso...
cf64aaaa5e65ff24f148c18c89679abfa04ce221
3,608,628
def class_net(images, level, num_classes, num_anchors=6, is_training_bn=False): """Class prediction network for RetinaNet.""" for i in range(4): images = tf.layers.conv2d( images, 256, kernel_size=(3, 3), bias_initializer=tf.zeros_initializer(), kernel_initializer=tf.rand...
f75d12f65276e8195df990b5a4ac59f242e685ef
3,608,629
def random_walk(nsteps=100, seed=1, start=(0, 0)): """Creates 2d random walk trajectory. Parameters ---------- nsteps : int Number of steps for trajectory to move. seed : int Seed for pseudo-random number generator for reproducability. start : tuple of int or float Start...
fea59a08bcad5ed0b15f8d98b052313209696c1b
3,608,630
import seaborn as sns def _get_fig_ax(fig, ax, size=9): """Check figure and axis, and create if none.""" if fig and not ax: ax = fig.axes elif ax and not fig: fig = ax.figure if fig and ax: return fig, ax else: sns.set_style('darkgrid') if isinstance(size, i...
309f5da5bf4971ba8b2878b631c25766b89830fd
3,608,631
def update_perceptron_batch(lexicon, data, learning_rate=0.1, parser=None): """ Execute a batch perceptron weight update with the given training data. Args: lexicon: CCGLexicon with weights data: List of `(x, y)` tuples, where `x` is a list of string tokens and `y` is an LF string. learning_rat...
fe62fa8595890431c4fcef5a3cac71969c084b4a
3,608,632
def length_str(msec: float) -> str: """ Convert a number of milliseconds into a human-readable representation of the length of a track. """ seconds = (msec or 0)/1000 remainder_seconds = seconds % 60 minutes = (seconds - remainder_seconds) / 60 if minutes >= 60: remainder_minut...
7cf6674d68d118c78a2953b3fef873633673bbf0
3,608,633
from typing import Optional from typing import Iterable from typing import Dict from typing import List def update( dataset: Dataset, *, attributes: Optional[Iterable[str]] = None, attribute_types: Optional[Dict[str, attribute_type.AttributeType]] = None, attribute_descriptions: Optional[Dict[str,...
4761ad5441fec6c617cd436c920342bd784e8c03
3,608,634
from typing import Callable from typing import Type from typing import Union import pandas import functools def func( __original_func=None, *, function: Callable[ [Type[Relation], Union["pyspark.sql.DataFrame", "pandas.DataFrame"]], Union["pyspark.sql.DataFrame", "pandas.DataFrame"], ]...
24bd0ab68bf9e0c62fe010393d1d01e6dda0abbd
3,608,635
def remove_rests_from_track(track): """ Remove rests from a given percussion track. This function also works for other types of tracks as well. """ for measure in track.measures: for voice in measure.voices: last = None newbeats = [] for beat in voice.bea...
90064b181a6f2198e98c9ac80b691eb91572c1f1
3,608,636
def handle_invalid_usage(error): """ Handle ApiException as HTTP errors and react to its specification inside """ log.warn("Caught ApiException. Reason: {}".format(str(error))) response = error.to_dict() return response, error.status_code
9debb5014748b2ece6e569c899c99c7510d425ee
3,608,637
def process_spikes(group_index, n_co_spikes=2, hdu_only=False): """ Get the paths to all files belonging to the group numbered by group_index. There are typically 7 files per group :param group_index: group number as given by grouping the database by unique group indices. :param hdu_only: set to ...
2c3666befee1ebdbdb87a9aa567d1c4d399db7f5
3,608,638
def sales(from_, to, hashids=None, tz=None, format_=None, **opts): """ Returns the total price for sales checkouts in a period, where session_id identifies every sale. """ query_params = parse_query_params({ 'from': from_, 'to': to, 'hashid': hashids, 'tz': tz, ...
879f98498bb93e31acb413cc69b301308c7f5b7a
3,608,639
from typing import Dict from typing import Any from typing import Callable def get_reader(data: Dict[str, Any]) -> Callable[[str], nbf.NotebookNode]: """Returns a function to read a file URI and return a notebook.""" if data.get("type") == "plugin": key = data.get("name", "") reader = get_entr...
6e9d273f83d0fceba21f734bfe853491c3b26b64
3,608,640
def retrieve_context_topology_node_owned_node_edge_point_connection_end_point_name_name(uuid, node_uuid, owned_node_edge_point_uuid, connection_end_point_uuid): # noqa: E501 """Retrieve name Retrieve operation of resource: name # noqa: E501 :param uuid: ID of uuid :type uuid: str :param node_uuid...
29660c6a1f6421f477e416b20e53befa8233ddec
3,608,641
import json def generate_core(config_data, tuned_profile=None, template=None, output_path=None, output_filter=None, render_options=None, write_profile_data=False): """Core of the generator, gets complete dataset with selected template in config data or explicitly selected v...
ad1dc0f880412cc09cbf96fe267a74d4e2e37380
3,608,642
def raw_to_sec_df(raw_df): """ Convert a 100 millisecond apart raw match dataframe to a second apart match dataframe by only considering the 1st snapshot of all 10 snapshots for a second. Parameters ---------- raw_df : pandas.DataFrame 100 ms apart raw match dataframe. Returns ...
7c9c3ddae1f1b0496071f12a64645fd6796e8a4d
3,608,643
def var(a=0, b=1): """ Variance of the uniform distribution. """ with _mpmath.extradps(5): a, b = _validate(a, b) return (b - a)**2 / 12
ad9369616ff4dc6be903ce7fd19e8a5bc310487c
3,608,644
import unicodedata import string def safe_file_name(filename, replace=' '): """Make safe filename""" valid_filename_chars = "-_.() %s%s" % (string.ascii_letters, string.digits) char_limit = 150 # 255 replaced by 150 to be onsafe side # replace spaces for r in replace: filename = filenam...
594de592a72b924e64b3b9bb90d58c5f65c255d7
3,608,645
def get_E_E_CG_gen_d_t(E_E_gen_PU_d_t, E_E_TU_aux_d_t): """1時間当たりのコージェネレーション設備による発電量 (kWh/h) (2) Args: E_E_gen_PU_d_t(ndarray): 1時間当たりの発電ユニットの発電量 (kWh/h) E_E_TU_aux_d_t(ndarray): 1時間当たりのタンクユニットの補機消費電力量 (kWh/h) Returns: ndarray: 1時間当たりのコージェネレーション設備による発電量 (kWh/h) """ return E_E_ge...
46870e6ca7739d34027fa8ac3c2f57b2f27e9a6c
3,608,646
def make_all_plaq_observables(source: cirq.GridQubit, ancilla: cirq.GridQubit, circuit: cirq.Circuit): """Generate a list of observables like <X_i (X + iY)_ancilla > for every location `i` in the grid. Args: source, ancilla: "special" qubits for this correlator circuit circuit: Co...
47be350f90ec6c86f1dfa00aee051719b3c547eb
3,608,647
def main(myhostname, cnfpath, logpath): """Worker process's entry point. :param myhostname: hostname of the node in which workers are being launched :param cnfpath: path to config file :param logpath: path to log file :returns: exit status of worker process """ _run_worker_servers(myhostnam...
35bdb8db65829477f407c9695c9b1feae2ed9a39
3,608,648
from typing import Dict from datetime import datetime import json def frame_handler(frame: Dict): """Handle a single frame""" LOGGER.debug("Frame handler received frame to handle: %s", frame) sample_time = datetime.fromtimestamp(frame.get("timestamp")) # Insert into a memo.raw.Brefv message msg_i...
548a69a29969f1f914d01c6710145e71d47a37bc
3,608,649
import math def stamp(analysis_type, analysis_instance, MNA, RHS): """ Generating MNA and RHS to Represent the Circuit This function retrieve information from the internal structure to constitute MNA and RHS. It also collects neessary information for doing iterate and converge operations. :param analysis_type: ...
ae378200102885ab6b21aad0823daeb99fcbc488
3,608,650
import random def _is_review_needed(task): """ Determine if `task` will be reviewed according to its step policy. Args: task (orchestra.models.Task): The specified task object. Returns: review_needed (bool): True if review is determined to be needed according ...
429c49e8a32826c9f60aeed0ef886f755de1d79c
3,608,651
def num_lines(file): """Return # of lines in file Args: file: Target file. Returns: # of lines in file """ return sum(1 for _ in open(file))
6c65455c7b16dd4956b68c8cb60f647946ba1fb7
3,608,652
def TW_WA_WP_BA_Calculation(Depth, RiverLength, Volume, SAlist, dh): """Calculate channel top width, wet area, wetted perimeter, and bed area """ Volume = Volume - Volume[0] DDepth = np.diff(Depth) TotalArea = Volume/RiverLength/1000 TWlist = SAlist/RiverLength/1000 WAlist = list(TotalAr...
6332154ad17e5573b8cbfa6b12e5f408dbb3685f
3,608,653
def build_model(opt, data): """Builds model and optimiser nodes opt: dict of options data: dict of numpy data Returns a dict containing: 'learning_rate', 'train_phase', 'loss' 'accuracy', 'train_op', and IO placeholders 'x', 'y' """ n_GPUs = len(opt['deviceIdxs']) print('Using Multi-GPU Model with %d devices...
7f4381e7ddbcb4b2d553b63f48c35beef89acf8d
3,608,654
def get_dirpath(name=None): """ Get a pipe directory as Pathlib.Path Args: name (str): name of pipe """ return get_pipe(name).dirpath
b28a042275e936492ed5e5bea14c826a8c5d66e3
3,608,655
def tuple_from_ase(asecell: ase.Atoms): """ Convert an ase cell to a structure tuple. """ cell = asecell.cell.tolist() # Wrap=False to preserve the absolute positions of atoms rel_pos = asecell.get_scaled_positions(wrap=False).tolist() numbers = [ ase.atom.atomic_numbers[symbol] for ...
05936e417a5e9aa6c17083cbf8e7a04dc70757cb
3,608,656
def plot_cov_ellipse(cov, pos, nstd=2, ax=None, **kwargs): """ Plots an `nstd` sigma error ellipse based on the specified covariance matrix (`cov`). Additional keyword arguments are passed on to the ellipse patch artist. Parameters ---------- cov : The 2x2 covariance matrix to base the...
241259bc7d4679a9f72183ce1b3898623d9be1da
3,608,657
import socket from datetime import datetime def build_response_data(): """ Build a dictionary with timestamp, server ip, server name, secret and requester ip. """ hostname = socket.gethostname() return { 'now': datetime.now().isoformat(sep=' '), 'local_ip': socket.gethostbyname...
2ef8476cc6dc195733bc922703ed370c42aba8d1
3,608,658
def failure_message(message: str, code: str) -> dict: """ Return a dict that is a standard failure message. Args: code (str): Mnemonic that never changes for this message message (str): Human-readable message text explaining the failure Returns: (dict): A message template. "...
791fc4dd22862c592af139aa956e0a0664931115
3,608,659
def row_sum(lst): """ Sum of non-missing items in `lst` """ return sum(int(x) for x in lst if x > -1)
5fabe4d3487e502dcb82dd452854de3777e1a5a8
3,608,660
import itertools def cartesian_power(lhs, rhs, ctx): """Element ÞẊ (any, num) -> cartesian_power(a, b) (num, any) -> cartesian_power(b, a) """ ts = vy_type(lhs, rhs) if NUMBER_TYPE not in ts: return rhs else: lhs, rhs = (lhs, rhs) if ts[-1] == NUMBER_TYPE else (rhs, lhs) ...
d21522a32404f715f82d0cc6c8d120f89697be32
3,608,661
def plot_per_experiment(**kwargs): """ This function creates one figure per experiment defined, with plots of all dependent variables and their fit in it. :param kwargs: - | `model`: to specify the data model to be used (if not specified | the one from :func:`.get_current_model` will be take...
bb6608bb6ac55458691dc23cc59502d0f3f87e07
3,608,662
from datetime import datetime def get_weather_data(requested_date, location): """ get weather data for date & location - main function. Args: requested_date (date) - date requested for forecast. location (str) - location name. Returns: dictionary with the following entries: Status ...
0f323e776d1ddd50c6e9a018f6f92d04b595c30d
3,608,663
def twoGMMcalib_lin(s, niters=20): """ Train two-Gaussian GMM with shared variance for calibration of scores 's' Returns threshold for original scores 's' that "separates" the two gaussians and array of linearly callibrated log odds ratio scores. """ weights = np.array([0.5, 0.5]) means = np...
9fe7f796f14ead0643167b1fc14d4e0929a3720a
3,608,664
def route_chess(): """load game specific resources here""" return render_template("games/garbo/chess.html"), 200
a4e5e69bb57dd05972e3088f30247f60590196d8
3,608,665
import sys import logging def build_persistence(location, fallback_to_plaintext=False): """Build a suitable persistence instance based your current OS""" if sys.platform.startswith('win'): return FilePersistenceWithDataProtection(location) if sys.platform.startswith('darwin'): return Keych...
8d36f685a1a17fb8d2348a565da922a11bf78d87
3,608,666
def edit_distance_train(encoder_method, vector_distance, texts, distance_labels, plot=False): """ The goal of the training procedure is to find the scaling parameter alpha that minimizes (for i along the dataset) \sum_i (r_i - alpha * p_i)^2 where r_i is the real distance and p_i the predicted one. ...
9496c937c9ddecf6a46c2699b9dc077409ce2a39
3,608,667
def compress_dataframe_time_interval(processed_df, interval): """ Resamples dataframe according to time interval. If data is originally in 1 minute intervals the number of rows can be reduced by making the interval 15 minutes. To maintain data quality, an average is taken when compressing the dataframe....
ffbb35719e33f445ba4b5c91acf8a069cd4902a6
3,608,668
import os import re def read_from_restart_file(structure, energy, gulp_res_file): """ Read unit cell, atomic positions and energy from a GULP ".res" file, where they are quoted to greater precision than the output file (and hence the ASE atoms object if available). For the GULP calculator in ASE ...
2a08e7f1fd27c96b8792416edc5cc4e5b3415eba
3,608,669
from typing import Sequence def create_colormap(color_list: Sequence[str], n_colors: int) -> NDArrayFloat: """Create hex colorscale to interpolate between requested colors. Args: color_list: list of requested colors, in hex format. n_colors: number of colors in the colormap. Returns: ...
24f4a0b6dfe4c396cdbde5c79ec9bf88378cd441
3,608,670
def update_file(filename: str, url: str) -> bool: """Check and update file compares with remote_url Args: filename: str. Local filename, normally it's `__file__` url: str or urllib.request.Request object. Remote url of raw file content. Use urllib.request.Request object for headers. Returns...
10cde22c7a34ca9fb453557e1a6bfb8270d662e3
3,608,671
def iseast(bb1, bb2, north_vector=[0,1,0]): """ Returns True if bb1 is east of bb2 For obj1 to be east of obj2 if we assume a north_vector of [0,1,0] - The min X of bb1 is greater than the max X of bb2 """ #Currently a North Vector of 0,1,0 (North is in the positive Y direction) #i...
9764d373d14530fca2d26d8c7855cc0620e14496
3,608,672
def GetHashAddr(variable): """ Get address of a hash as $H_(var_name) """ if type(variable) == INSTRUCTION.Entity: return "$H_" + str(variable.value) else: return "$H_" + str(variable)
cc1004ff7f8b544222342cbd03cb33a1ee4dcd0c
3,608,673
def getObjId(s3key): """ Return object id given valid s3key """ if len(s3key) >= 44 and s3key[0:5].isalnum() and s3key[5] == '-' and s3key[6] in ('g', 'd', 'c', 't'): # v1 obj keys objid = s3key[6:] elif s3key.endswith("/.domain.json"): objid = '/' + s3key[:-(len("/.domain.json"))] ...
d1220bae1ab4934f41b683143ace94d388db7beb
3,608,674
def vq5(a_z, a_t): """ a_z: nx1, visible area of polygon z a_t: float, projected area of the model """ prob = a_z[a_z!=0]/float(a_t) v = -np.sum(np.multiply(prob, np.log2(prob))) #prob = tf.truediv(a_z,a_t) #v = tf.sum(tf.multiply(prob, np.log2(prob))) return v
9719429d6d51f936af3dcb3e927944b2e43253e5
3,608,675
def StandardDialogLayoutAdapter_DoFitWithScrolling(*args, **kwargs): """StandardDialogLayoutAdapter_DoFitWithScrolling(Dialog dialog, ScrolledWindow scrolledWindow) -> bool""" return _windows_.StandardDialogLayoutAdapter_DoFitWithScrolling(*args, **kwargs)
b8bcbf9fd57ba94648bcdec54296fb5df421cfc2
3,608,676
def timesheet_index_view(request): """Redirects the logged-in user (not superuser) to their timesheet for the current month, while for an superuser display all timesheets available for each of the users """ # Redirect none super users to their timesheet. if not request.user.is_superuser: re...
a3f891d513dbcaa84b1deeed4a801c420a627913
3,608,677
import functools import os import sys def remapping_test(*, cli_args): """Return a decorator that returns a test function.""" def real_decorator(coroutine_test): """Return a test function that runs a coroutine test in a loop with a launched process.""" @functools.wraps(coroutine_test) ...
72e456f62318248a572fc5c4feede056e686e3d9
3,608,678
from typing import Set def get_fastq_read_ids(ref_path: str) -> Set[str]: """Extracts the read ids from a fastq file.""" read_ids = set() with pysam.FastxFile(ref_path) as fastq: for entry in fastq: read_ids.add(entry.name.strip()) return read_ids
a77b25238851cadf9fff9e4a26272478c4b26d2e
3,608,679
def after(target_event_source: t.Callable): """Call decorated function before target function. :param target_event_source: Target method decorated with @event_source """ def _outer(advisor_method): wrapped = getattr(target_event_source, "__wrapped__", None) assert wrapped, "The target...
952c92fbda81bbcefffb9f788d2daad92e677bf3
3,608,680
import os def download(request): """Download translated resource.""" try: slug = request.POST['slug'] code = request.POST['code'] part = request.POST['part'] except MultiValueDictKeyError: raise Http404 content, path = utils.get_download_content(slug, code, part) ...
501524be5d1890f8a1f40e062ec2aecf3cdb9d45
3,608,681
import itertools def concat_list(in_list: list) -> list: """Concatenate a list of list into a single list.""" return list(itertools.chain(*in_list))
5a58e8e1899fce99f8dabe681206507ae8ad4b8c
3,608,682
def testenv_deposit_pending_almost_filled_auction( testenv_almost_filled_auction, accounts, chain ) -> TestEnv: """A testenv with auction awaiting deposit transfer with a number of bidders below the maximal number of bidders""" time_travel_to_end_of_auction(chain) testenv_almost_filled_auction.close_auc...
a28b91cbbf7b63deb59c36b40fe3d89abb8958a7
3,608,683
def notificationMarkAllRead(request): """ Mark all the notifications for this user as read. """ Notification.objects.markAllReadForUser(request.user.id) return HttpResponseRedirect("/notifications")
efc3c4b9ac5adcb227293681e27c470024611c56
3,608,684
def is_sale(line): """Determine whether a given line describes a sale of cattle.""" return len(line) == 5
e4ff4ae2ea7ea14a2975eaf87852eed2fad0abff
3,608,685
from typing import List from typing import Generator from typing import Tuple from typing import Optional from typing import Iterable import tqdm def match_contexts( contexts: List[str], candidates: Generator[Tuple[str, str], None, None], threshold: float = 65.0, show_progress: bool = False, num_p...
f939e715839ff7347e780212dd7b16c095ce43de
3,608,686
from datetime import datetime def floor_datetime( dt: datetime.datetime, precision: spec.DatetimeUnit, ) -> datetime.datetime: """take floor of datetime down to a given level of precision ## Inputs - dt: datetime object - precision: str name of precision unit to take floor to """ if ...
9c50f40e170672d03d4d750b0b5b342865f617ad
3,608,687
def apology(message, code=400): """Render message as an apology to user.""" def escape(s): """ Escape special characters. https://github.com/jacebrowning/memegen#special-characters """ for old, new in [("-", "--"), (" ", "-"), ("_", "__"), ("?", "~q"), ...
dbb577b79d76200fc3c8624b3c4679286c3ce33d
3,608,688
def calc_swsh_eq(phi, aa, omega, ell, em, ess=-2): """ Finds Slm(pi/2) based on a spectral decomposition Normalization is that from Glampedakis and Kennefick (2002) Inputs: aa (float): spin parameter (0, 1) omega (float): gravitational wave frequency ell (int): swsh mode ...
00bb7c38463ce210a6fbf14fcda39d7d88837b2f
3,608,689
import numpy import math def log(inputArray, scale_min=None, scale_max=None): """Performs log10 scaling of the input numpy array. @type inputArray: numpy array @param inputArray: image data array @type scale_min: float @param scale_min: minimum data value @type scale_max: float @param sca...
a6f6ef5a5f964cadc05ae6b9f93747eb8de691e0
3,608,690
import sys import os import pandas def run(*argv): """ Parameters: argv = [signture, dir ,"3D/2D","Baseline","Your model*", subfolder] signture: 3D/2D: Baseline: Name of basline must match the folder where the results are stored. ...
c410601e1ec06dbe4a215c85287b9408c2e031d9
3,608,691
import os import collections def resolve(path, pinyin_firstletter: bool, prefix: bool): """ Returns the target directory. """ if not path: return [os.path.expanduser('~')] path = os.path.normpath(path) pinyin_style = (pypinyin.Style.FIRST_LETTER if pinyin_firstletter ...
cae7a271138c60dd829aabf952061cbce2fc3a66
3,608,692
def all_daemons_healthy(instance, curr_time_seconds=None): """ True if all required daemons have had a recent heartbeat Note: this method (and its dependencies) are static because it is called by the dagit process, which shouldn't need to instantiate each of the daemons. """ statuses = [ ...
32834006bb08b37a6c64623bea6aefbdcac6a377
3,608,693
def build_nngp_with_dataset(dataset, kernel_type, num_coeffs, dist_type): """ Builds a GP using the training set in dataset. """ mean_func = lambda x: np.array([np.median(dataset[1])] * len(x)) noise_var = (dataset[1].std() ** 2)/20 kernel_hyperparams = get_kernel_hyperparams(num_coeffs, kernel_type, dist_type)...
5a8f05fa1acf27bd24ce85df542d8246d1564900
3,608,694
def parse_type_reference(lexer: Lexer) -> TypeNode: """Type: NamedType or ListType or NonNullType""" start = lexer.token if skip(lexer, TokenKind.BRACKET_L): type_ = parse_type_reference(lexer) expect(lexer, TokenKind.BRACKET_R) type_ = ListTypeNode(type=type_, loc=loc(lexer, start))...
a0169a80afc8378041f64ed0c9fb67d5968d854f
3,608,695
from functools import reduce def phash(img): """ :param img: 圖片 :return: 返回圖片的局部hash值 """ img = img.resize((8, 8), Image.ANTIALIAS).convert('L') avg = reduce(lambda x, y: x + y, img.getdata()) / 64. hash_value = reduce(lambda x, y: x | (y[1] << y[0]), enumerate(map(...
bf298ecf82965283ce2a61828a32852017988f00
3,608,696
import os def _AttemptPseudoLockRelease(pseudo_lock_fd): """Try to release the pseudo lock and return a boolean indicating whether the release was succesful. This whole operation is guarded with the global cloud storage lock, which prevents race conditions that might otherwise cause multiple processes to b...
6132e1cbea72a820e8664ce0e81d7967f7ac2d21
3,608,697
def _is_recipe_fitted(recipe): """Check if a recipe is ready to be used. Fitting a recipe consists in wrapping every values of `fov`, `r`, `c` and `z` in a list (an empty one if necessary). Values for `ext` and `opt` are also initialized. Parameters ---------- recipe : dict Map the...
77e438dd00ac5606c52c88518c6932a09dff75df
3,608,698
def identify_company_name(target_name): """ Identify company name by JCL dictionary Arg: target_name (str): target name Return: dict: Identified unique name or candidate names from JCL dictionary into BigQuery """ fmt_name_str = fmt_string(target_name) bq_resp = fetch_company_na...
b55a9fe54214019616720ce90162d8c135ef0b4a
3,608,699