content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Union from typing import List from typing import Dict from typing import Set import tqdm def scaffold_to_smiles(mols: Union[List[str], List[Chem.Mol]], use_indices: bool = False) -> Dict[str, Union[Set[str], Set[int]]]: """ Computes the scaffold for each SMILES and return...
2a45731a5574bb37e81042fa19ac7c2f015c21ef
14,421
import crypt def encontrar_passwords(): """ Probar todas las combinaciones de 6 letras, hasheando cada una para ver si coinciden con los hashes guardados en los /etc/shadow Para el tema de equipos, basicamente fui probando con copiar y pegar contenido en texto de distintas paginas de wikipedia en ...
5762fed1f5e493c2399d40dbbc1e19ad24c6718e
14,422
def queue_merlin_study(study, adapter): """ Launch a chain of tasks based off of a MerlinStudy. """ samples = study.samples sample_labels = study.sample_labels egraph = study.dag LOG.info("Calculating task groupings from DAG.") groups_of_chains = egraph.group_tasks("_source") # magi...
448365e799001d09281707cab69c71c3be05408e
14,423
import math def sphere_mass(density,radius): """Usage: Find the mass of a sphere using density and radius""" return density*((4/3)*(math.pi)*radius**3)
8c1a2dc949980ca96a4f56f3918bacd19568965e
14,424
def generate_stats_table(buildings_clust_df): """ Generate statistical analysis table of building types in the area Args: buildings_clust_df: building footprints dataframe after performed building blocks assignment (HDBSCAN) Return: stat_table: statistical analysis results ...
732f035e591dc9f0b03673584f3a6e21dad03cad
14,425
def make_multisat(nucsat_tuples): """Creates a rst.sty Latex string representation of a multi-satellite RST subtree (i.e. merge a set of nucleus-satellite relations that share the same nucleus into one subtree). """ nucsat_tuples = [tup for tup in nucsat_tuples] # unpack the iterable, so we can che...
16c1808267087beea6cea21811cd3c1f7d70932e
14,426
import io def plot_to_image(figure): """Converts the matplotlib figure to a PNG image.""" # The function is adapted from # github.com/tensorflow/tensorboard/blob/master/docs/image_summaries.ipynb # Save the plot to a PNG in memory. buf = io.BytesIO() plt.savefig(buf, format="png") # Closing the figure ...
24a63f7b27d47421baf2c7913bf989903e4d9545
14,427
async def getDiscordTwitchAlerts(cls:"PhaazebotDiscord", guild_id:str, alert_id:int=None, limit:int=0, offset:int=0) -> list: """ Get server discord alerts, if alert_id = None, get all else only get one associated with the alert_id Returns a list of DiscordTwitchAlert(). """ sql:str = """ SELECT `discord...
00c1bad85f4f7891d36e5fab5c651f10c79abf02
14,428
def is_visible_dir(file_info): """Checks to see if the file is a visible directory. @param file_info: The file to check @type file_info: a gnomevfs.FileInfo """ return is_dir(file_info) and not is_hidden(file_info)
776361d4cbe16a5b3c45dc3073a37192e31e87a9
14,429
def read_file(item): """Read file in key path into key image """ item['image'] = tf.read_file(item['path']) return item
06b87851717bd486b13f964ad5b45cbdc7a97142
14,431
def make_joint(withdraw, old_password, new_password): """Return a password-protected withdraw function that has joint access to the balance of withdraw. >>> w = make_withdraw(100, 'hax0r') >>> w(25, 'hax0r') 75 >>> make_joint(w, 'my', 'secret') 'Incorrect password' >>> j = make_joint(w,...
f40073429aea946486263a7d6e0fc8b24cd60a84
14,432
def should_parse(config, file): """Check if file extension is in list of supported file types (can be configured from cli)""" return file.suffix and file.suffix.lower() in config.filetypes
1c2258d405ef715574b557d99cdf87e461627ffd
14,433
def _get_pipeline_per_subband(subband_name: str): """ Constructs a pipeline to extract the specified subband related features. Output: sklearn.pipeline.Pipeline object containing all steps to calculate time-domain feature on the specified subband. """ freq_range = FREQ_BANDS_RANGE[subband_n...
2b1d8bd2543ae07b861df6f979297a82e3f5e827
14,434
def get_credentials_interactively() -> Credentials: """ Gets credentials for the bl interactively """ return ("placeholder-user", "placeholder-pass")
b5e4d55015155589632b958252a3c078b5920e59
14,435
def reynolds(find="Re", printEqs=True, **kwargs): """ Reynolds Number = Inertia / Viscosity """ eq = list() eq.append("Eq(Re, rho * U * L / mu)") return solveEqs(eq, find=find, printEq=printEqs, **kwargs)
df5ad0c0279894e8f671942ceddb64e08e35fa0d
14,436
def data_app(): """ Data Processer and Visualizer """ st.title("Data Cake") st.subheader("A to Z Data Analysis") file = ['./dataset/Ac1',[0,1]] def file_selector(): filename = st.file_uploader("Upload Excel File", type=['xls','xlsx']) if filename is not None: sheetname...
b6286064757d276a5319ef0b3cffe1515c4a7fb1
14,437
def derivative(x, y, order=1): """Returns the derivative of y-coordinates as a function of x-coodinates. Args: x (list or array): 1D array x-coordinates. y (list or array): 1D array y-coordinates. order (number, optional): derivative order. Returns: ...
23a1213721e553e5b72a0bd92877675b499f9848
14,438
from typing import Dict def get_ff_parameters(wc_params, molecule=None, components=None): """Get the parameters for ff_builder.""" ff_params = { 'ff_framework': wc_params['ff_framework'], 'ff_molecules': {}, 'shifted': wc_params['ff_shifted'], 'tail_corrections': wc_params['ff_...
d87008dba0b9d835f71366eb64486b1d18fe2381
14,439
def healpix_header_odict(nside,nest=False,ordering='RING',coord=None, partial=True): """Mimic the healpy header keywords.""" hdr = odict([]) hdr['PIXTYPE']=odict([('name','PIXTYPE'), ('value','HEALPIX'), ('comment','HEALPIX pixelisation')]) ordering =...
1202d7564b94a3c2288a513f42e4b781a583e41c
14,440
def hello(): """Test endpoint""" return {'hello': 'world'}
91ad620815a6371a4723e21bc79aad8c1d49e73e
14,441
def permute_channels(n_channels, keep_nbr_order=True): """Permute the order of neighbor channels Args: n_channels: the total number of channels keep_nbr_order: whether to keep the relative order of neighbors if true, only do random rotation and flip if false, random perm...
5491f181d32a5ff77ef1d9f6ac3327e6b0a746e0
14,443
def from_file(file,typcls): """Parse an instance of the given typeclass from the given file.""" s = Stream(file) return s.read_value(typcls._ep_typedesc)
90507278f33fe30a73c31f94ab046c07962250cc
14,444
def read_test_ids(): """ Read sample submission file, list and return all test image ids. """ df_test = pd.read_csv(SAMPLE_SUBMISSION_PATH) ids_test = df_test['img'].map(lambda s: s.split('.')[0]) return ids_test
cc4d53d28631fe0e22cabe30704a1844ff3e3a5b
14,445
def chuseok(year=None): """ :parm year: int :return: Thanksgiving Day of Korea """ year = year if year else _year return LunarDate(year, 8, 15).toSolarDate()
28a3170153862bda2ae52176d4931ee10050c3e1
14,446
def DELETE(request): """Delete a user's authorization level over a simulation.""" # Make sure required parameters are there try: request.check_required_parameters( path={ 'simulationId': 'int', 'userId': 'int' } ) except exceptio...
7ac7c6277126a827790e786cbfdf9f84ccaace7b
14,447
def process_query(data): """ Concat query, question, and narrative then 'preprocess' :data: a dataframe with queries in rows; query, question, and narrative in columns :return: 2d list of tokens (rows: queries, columns: tokens) """ lst_index = [] lst_words = [] for index, row in da...
8a8067f1766abdc08aa7b8995508d6cdc9057bd2
14,448
def nb_view_patches(Yr, A, C, S, b, f, d1, d2, YrA=None, image_neurons=None, thr=0.99, denoised_color=None, cmap='jet'): """ Interactive plotting utility for ipython notebook Args: Yr: np.ndarray movie A,C,b,f: np.ndarrays outputs of matrix factorization algorithm ...
84db2e40734b21ebb6be5eef8eeb89bbe2838542
14,450
def menu(): """Manda el Menú \n Opciones: 1: Añadir a un donante 2: Añadir a un donatario 3: Revisar la lista de donantes 4: Revisar la lista de donatarios 5: Realizar una transfusion 6: Estadisticas 7: Salir Returns: opc(num):Opcion del menu "...
805d1ef48fbe03f8185e3c7be71ce3d9aa6104df
14,451
import shutil def get_engine(hass, config): """Set up Pico speech component.""" if shutil.which("pico2wave") is None: _LOGGER.error("'pico2wave' was not found") return False return PicoProvider(config[CONF_LANG])
d03a19dcff4bc8556a84b434d14468a45ffc7e6c
14,452
from typing import Tuple from typing import List def load_cp() -> Tuple[List[str], List[List[float]]]: """ Loads cloud point data; target values given in Celsius Returns: Tuple[List[str], List[List[float]]]: (smiles strings, target values); target values have shape (n_samples, 1) ...
84b11da1b3cd1a9ecaf5e1419d69b877c160e2aa
14,453
def look_up(f, *args, **kwargs): """ :param f: :type f: :param args: :type args: :param kwargs: :type kwargs: :return: :rtype:""" ag_hash = hash(args) + make_hash(kwargs) if f in global_table: if ag_hash in global_table[f]: return global_table[f][ag_hash]...
ebc9015066959f66cd98db226178cdf087fc897b
14,454
def getenv(key, default=None): """Get an environment variable, return None if it doesn't exist. The optional second argument can specify an alternate default. """ return environ.get(key, default)
0e355c73dbbdc971e4442123dc5945dc04fac8fc
14,455
def read_tag(request, tid, *args, **kwargs): """read_tag(tid) returns ...""" s = api.read_tag(request, tid, *args, **kwargs) return render_to_response('read/tag.html', s)
7582e752563f35eb8d025625eaac87d8a9f45f32
14,456
def ber_img(original_img_bin, decoded_img_bin): """Compute Bit-Error-Rate (BER) by comparing 2 binary images.""" if not original_img_bin.shape == decoded_img_bin.shape: raise ValueError('Original and decoded images\' shapes don\'t match !') height, width, k = original_img_bin.shape errors_bits...
f5768aa5435a76bcd82b331d76dadf554749e82d
14,457
def get_fractal_patterns_WtoE_NtoS(fractal_portrait, width, height): """ get all fractal patterns from fractal portrait, from West to East, from North to South """ fractal_patterns = [] for x in range(width): # single fractal pattern f_p = get_fractal_patterns_zero_amounts() for y in...
ad5e2025515231ae8efb256b5dc466d66fedb467
14,458
import time from datetime import datetime import requests import io def rating(date=None): """P2peye comprehensive rating and display results. from https://www.p2peye.com Args: date: if None, download latest data, if like '201812', that download month data. Returns: DataFrame...
d76205c933c07764938b38fbfcdcbbe84b584471
14,459
def crop_image(src, box, expand=0): """Read sensor data and crop a bounding box Args: src: a rasterio opened path box: geopandas geometry polygon object expand: add padding in percent to the edge of the crop Returns: masked_image: a crop of sensor data at specified bounds ...
84948cf3c81fe650d15acd834f89c532e9658466
14,460
def add_msgpack_support(cls, ext, add_cls_methods=True): """Adds serialization support, Enables packing and unpacking with msgpack with 'pack.packb' and 'pack.unpackb' methods. If add_method then enables equality, reading and writing for the classs. Specificly, adds methods: bytes <- obj...
fa8a6fcce7103466f923b84eeb6f5bdae8383b79
14,461
def UnN(X, Z, N, sampling_type): """Computes block-wise complete U-statistic.""" return UN(X, Z, N, Un, sampling_type=sampling_type)
0e2fb8c62cbcca99017bc7d0ff2c13dbecad1ab3
14,463
def view_log_view(request, model_name, object_id): """view log view Arguments: request {object} -- wsgi request object content_type {str} -- content type object_id {int} -- admin_log id Returns: retun -- html view """ if model_name not in register_form: re...
55ebd2d5226e06b1f5833595b0efad3de81140d7
14,464
from typing import Tuple from typing import Dict def parse_markdown(source: str) -> Tuple[str, Dict]: """Parse a Markdown document using our custom parser. Args: source (str): the Markdown source text Returns: tuple(str, dict): 1. the converted output as a string ...
2bf5a8d43f3763d6b1356dc0496ab4ed1896fe99
14,465
def flatten_list(nested_list): # Essentially we want to loop through each element in the list # and check to see if it is of type integer or list """ Flatten a arbitrarily nested list Args: nested_list: a nested list with item to be either integer or list example: [2,[[...
d79b350167cd1fdf35582e9b149bfb364741d566
14,466
import inspect def detect_runner(): """ Guess which test runner we're using by traversing the stack and looking for the first matching module. This *should* be reasonably safe, as it's done during test discovery where the test runner should be the stack frame immediately outside. """ i...
881758d42e5047fe58106a99377dcc7191c0010c
14,467
def retinanet( mode, offsets_mean=None, offsets_std=None, architecture='resnet50', train_bn=False, channels_fmap=256, num_anchors_per_pixel=9, num_object_classes=1, pi=0.01, alpha=0.25, gamma=2.0, confidence_threshold=0....
a3cdb088345740583c7ea08049e5f03f8d496cad
14,468
from typing import Union from typing import Tuple from typing import List from typing import Literal def default_chap_exec(gallery_or_id: Union[Gallery, int], chap: Chapter, only_values=False) \ -> Union[Tuple[str, dict], Tuple[int, Union[str, List[str]], int, bytes, int, Literal[0, 1]]]: """Pass a Galler...
8bd8cbfc47ce3463f2ea6da313cc871d8b6dcdf5
14,469
from typing import List from typing import Dict from typing import Literal from typing import Any def get_matching_based_variables(match_definitions:List[Dict[Literal['name', 'matching'],Any]], global_dict=None, local_dict=None, ...
6722bb4f258ef69c4aab74970f8f924ca938bbf5
14,471
def _AStar_graph(problem: BridgeProblem) -> (list, list): """Used for graphing, returns solution as well as all nodes in a list""" all_nodes = [problem.initial_node] pq = [(problem.initial_node.path_cost + problem.h(problem.initial_node.state), problem.initial_node)] closed = set() while True: ...
a1616f7d499f12a229843007d7bc4939cbd02a7a
14,472
def plot_setup(name, figsize=None, fontsize=9, font='paper', dpi=None): """ Setup a PDF page for plot. name: PDF file name. If not ending with .pdf, will automatically append. figsize: dimension of the plot in inches, should be an array of length two. fontsize: fontsize for legends and labels. font...
4f9595757df57ee451dddc82815a91b727feb1f1
14,473
def author_endyear(pub2author_df = None, colgroupby = 'AuthorId', datecol = 'Year', show_progress=False): """ Calculate the year of last publication for each author. Parameters ---------- pub2author_df : DataFrame, default None, Optional A DataFrame with the author2publication information. ...
8a3ebf5e1870a8aa79ed2cba18fbb18fa634e604
14,474
def to_gif(images, fps): """Converts image sequence (4D numpy array) to gif.""" imageio.mimsave('./animation.gif', images, fps=fps) return embed.embed_file('./animation.gif')
b329da4710a5ad2da57ed2cf6b774ac4b6b8c7dd
14,475
import logging def get_half_max_down(signal, peak): """See `get_half_max_up` for explanation. This is a minor modification of the above function. """ if peak['peak'] == 0: return np.nan fflag = False half_max = signal[peak['peak']] / 2 falling_signal = signal[peak['peak']:(peak['r...
0b9b20b66a82d8a60aa650bc1bacd24f67f217f1
14,476
import copy def ternary(c): """ Encodes the circuit with ternary values Parameters ---------- c : Circuit Circuit to encode. Returns ------- Circuit Encoded circuit. """ if c.blackboxes: raise ValueError(f"{c.name} contains a blackbox") t ...
6fd813b957da408c23cc8a37038b8f3b660fdc73
14,478
from typing import List from typing import Dict def eval_lane_per_frame( gt_file: str, pred_file: str, bound_ths: List[float] ) -> Dict[str, np.ndarray]: """Compute mean,recall and decay from per-frame evaluation.""" task2arr: Dict[str, np.ndarray] = dict() # str -> 2d array gt_byte = np.asarray(Imag...
571cd737151576869170e33d181f89d22bc0657b
14,479
import torch def membrane(field, voxel_size=1, bound='dct2', dim=None, weights=None): """Precision matrix for the Membrane energy Note ---- .. This is exactly equivalent to SPM's membrane energy Parameters ---------- field : (..., *spatial) tensor voxel_size : float or sequence[float...
5e238ca2253fc7105b1bbfba58947ac442c05699
14,480
from typing import Tuple import struct def get_uint64(dgram: bytes, start_index: int) -> Tuple[int, int]: """Get a 64-bit big-endian unsigned integer from the datagram. Args: dgram: A datagram packet. start_index: An index where the integer starts in the datagram. Returns: A tuple cont...
e5ed2470656e3c0d1a8efe02bd638ac05245f187
14,481
import torch from typing import Optional from typing import List def fftshift(x: torch.Tensor, dim: Optional[List[int]] = None) -> torch.Tensor: """ Similar to np.fft.fftshift but applies to PyTorch Tensors Args: x: A PyTorch tensor. dim: Which dimension to fftshift. Returns: ...
a1ff7a81df83df63dcbcf56cf89d9b0e54c16ba0
14,482
def flatten(x): """Flattens nested list""" if isinstance(x, list): return [a for i in x for a in flatten(i)] else: return [x]
7d348f8287dfccfbb77a52a84a5642c265381eb1
14,483
import copy def get_capture_points_gazebo(bag, odom_topic='/gazebo/model_states', sync_topic='/mavros/imu/data_raw', camera_freq=20, sync_topic_freq=100, method='every'): """ method(string): method for sampling capturing points. 'every': Sample IMU for every n msgs, and then capture odometry msg whic...
75d351c0ecd6ad8dad6e7cfcd2ecd04d0826405b
14,484
import fileinput def parse_input(): """Parse input and return array of calendar A user can either pass the calendar via the stdin or via one or several icalendar files. This method will parse the input and return an array of valid icalendar """ input_data = '' calendars = [] for line...
a60a760968f139da0b7753ae5717d78b640cb232
14,485
def identity(obj): """Returns the ``obj`` parameter itself :param obj: The parameter to be returned :return: ``obj`` itself >>> identity(5) 5 >>> foo = 2 >>> identity(foo) is foo True """ return obj
a3271a831d2e91fe6eebed7e80c18e7c81996da6
14,486
def percent_clipper(x, percentiles): """ Takes data as np.ndarray and percentiles as array-like Returns clipped ndarray """ LOWERBOUND, UPPERBOUND = np.percentile(x, [percentiles[0], percentiles[1]) return np.clip(x, LOWERBOUND, UPPERBOUND)
3d114a956bfd0b6b8349c39f5c42f4487a812ee7
14,487
def check_prob_vector(p): """ Check if a vector is a probability vector. Args: p, array/list. """ assert np.all(p >= 0), p assert np.isclose(np.sum(p), 1), p return True
f9a6ea74fe9e5ff8a7244e7cc8aee2cbf5ae512e
14,488
def relabel_subgraph(): """ This function adapts an existing sampler by relabelling the vertices in the edge list to have dense index. Returns ------- sample: a function, that when invoked, produces a sample for the input function. """ def relabel(edge_list, positive_vertices): sha...
e9b8269640663b830c894c4aa4f8a8cce2b49af7
14,489
def init_binary(mocker): """Initialize a dummy BinaryDigitalAssetFile for testing.""" mocker.patch.multiple( houdini_package_runner.items.digital_asset.BinaryDigitalAssetFile, __init__=lambda x, y, z: None, ) def _create(): return houdini_package_runner.items.digital_asset.Binar...
34a3ee5fb09f413bf07b36f1b73189472c188f3d
14,491
def with_setup_(setup=None, teardown=None): """Decorator like `with_setup` of nosetest but which can be applied to any function""" def decorated(function): def app(*args, **kwargs): if setup: setup() try: function(*args, **kwargs) f...
f9e8eddfd01ee99e458857de403c49b91dafa92c
14,492
import click def post_options(): """Standard arguments and options for posting timeseries readings. """ options = [ click.argument('port'), click.argument('value', type=JSONParamType()), click.option('--timestamp', metavar='DATE', help='the time of the reading'...
7b7c386bfcbf36f1365392a6ba2562fa0ed520ce
14,493
def authenticated(f): """Decorator for authenticating with the Hub""" @wraps(f) def decorated(*args, **kwargs): token = request.cookies.get(auth.cookie_name) if token: user = auth.user_for_token(token) else: user = None if user: return f(u...
1149f14ad540521b71efa3a3240c13719ccf8a17
14,494
def json_complex_hook(dct): """ Return an encoded complex number to it's python representation. :param dct: (dict) json encoded complex number (__complex__) :return: python complex number """ if isinstance(dct, dict): if '__complex__' in dct: parts = dct['__complex__'] assert len(parts) == 2 return pa...
a3c8cb13485279ab3b222eb63efdfdf6421c17a6
14,495
def reg_logLiklihood(x, weights, y, C): """Regularizd log-liklihood function (cost function to minimized in logistic regression classification with L2 regularization) Parameters ----------- x : {array-like}, shape = [n_samples, n_features + 1] feature vectors. Note, first column of x mu...
4a13bac09a6989463014784c72c72729ec40e718
14,496
import itertools def estimate_gridsearch_size(model, params): """ Compute the total number of parameter combinations in a grid search Parameters ---------- model: str name of the model to train. The function currently supports feedforward neural networks (model = 'FNN'), long-short ...
8105a457b3ec30c3cdc6c42bb71afd229770b376
14,499
import pytz from datetime import datetime def str2posix(timelist): """ This will take a list of strings with the date along with a start and end time and make a list with the posix times. Inputs timelist - A list of strings with the data followed by two times. The date for ...
476fc634b967419818ef41d9ff4b21f9e4f76ff1
14,502
def keys_verif(verif: bool = True): """ Used to verify existence of private or/and public keys of ElGamal. """ print("\nChecking the presence of keys in the system....") if isFileHere("public_key.kpk", config.DIRECTORY_PROCESSING): # from cipher.asymmetric import elGamal as elG p...
824b8c31ad9cc0fb1b2ef7eef585e47c2e338a8b
14,503
def r2(ground_truth, simulation, join='inner', fill_value=0): """ R-squared value between ground truth and simulation Inputs: ground_truth - ground truth measurement (data frame) with measurement in the "value" column simulation - simulation measurement (data frame) with measurement in the "value" ...
75d78e575bef0a59620cbdbf1992396a8edd0929
14,504
def depth_analysis_transform_1(rgb_tensor, depth_tensor, num_filters): """Builds the analysis transform.""" with tf.variable_scope("analysis"): # --------------------------------------- rgb branch with tf.variable_scope("layer_0"): layer = tfc.SignalConv2D( num_filters, (9, 9), corr=True, s...
27637e35619f61e5da2b965392a39b38cdfb6a29
14,506
def hub_quantile_prediction_dict_validator(target_group_dict, prediction_dict): """ Does hub prediction_dict validation as documented in `json_io_dict_from_quantile_csv_file()` """ error_messages = [] # return value. filled next valid_quantiles = target_group_dict['quantiles'] prediction_quanti...
ec13824557ef9533d7c4a777daadd07414752767
14,508
def allclose_periodical(x, y, a, b, atol=1e-10): """ Checks np.allclose(x,y), but assumes both x and y are periodical with respect to interval (a,b) """ assert(len(x) == len(y)) period = b-a x_p = np.remainder(x-a,period) # now in 0, b-a y_p = np.remainder(y-a,period) return all(np.isclo...
bd1c58a362a9c3926bffbcb0a27e355bfc982955
14,509
import operator def get_categories_to_rows_ratio(df): """ Gets ratio of unique categories to number of rows in the categorical variable; do this for each categorical variable :param df: pd.DataFrame :return: array of tuples """ cat_columns = get_categorical_variable_names(df) rati...
2734b898b6c6538b65d54709be617a6dd393c3da
14,510
def _width_left_set(size: int, lsize: int, value: list, fmt: str, meta: dict) -> dict: """Width setting of paragraph with left repositioning.""" return Plain([RawInline(fmt, '<p style="text-align:left !important;' 'text-indent:0 !important;' 'position:rela...
6042b0d255fe804d7423b5e49dd700bd7f0b9bdf
14,511
def GetMappingKeyName(run, user): """Returns a str used to uniquely identify a mapping.""" return 'RunTesterMap_%s_%s' % (run.key().name(), str(user.user_id()))
b4eb80ca5f084ea956f6a458f92de1b85e722cda
14,512
def get_invitee_from_table(invite_code: str, table): """ Get a dictionary of the stored information for this invite code. Args: invite_code: The invitation code to search for table: A DynamoDB table for querying Returns: A dictionary of information stored under the invite code ...
1377e20a58174f69d8984e36aab3426c0eb392bd
14,513
import math def d_beta_dr(radius, beta, mass_r, epsilon, pressure, h_r): """ d_beta_dr """ return 2. * (1 - 2 * (mass_r/radius)) ** (-1.) * h_r * \ ( -2. * math.pi * (5*epsilon + 9*pressure + f(epsilon, pressure)) + (3/radius**2.) + 2*(1 - 2 * mass_r / radius)**(-1) * \ ((mass_r/radius) + 4 * ...
0880439516b70e07c01be3164a3c030bb9deeaca
14,514
import json def score(capstone, student_api): """ Calculates the score of the students' API model :param student_api: StudentApi object :return: score as a float """ # Check which simulators have datapoints with outcomes outcomes simulator_ids = [] for simulator in capstone.simulators...
bb4f545835f480c9fac97acc698daef08a7684f2
14,515
def clean_lhdf(df: pd.DataFrame): """ Removes unneccessary columms from the location history data frame and computes new required columns Parameters ---------- df : pandas.DataFrame DataFrame to process Returns ------- Copy of `df`, altered the following way: * Colums remov...
86280a333082e964553030d4e586a267e93edfae
14,516
def year_from_operating_datetime(df): """Add a 'year' column based on the year in the operating_datetime. Args: df (pandas.DataFrame): A DataFrame containing EPA CEMS data. Returns: pandas.DataFrame: A DataFrame containing EPA CEMS data with a 'year' column. """ df['year']...
1c7bbc6465d174465151e5e777671f319ee656b7
14,517
def is_thrift(target): """Returns True if the target has thrift IDL sources.""" return isinstance(target, JavaThriftLibrary)
4a56cf5cec923933fec628173cb2ab1a122b0127
14,518
def get_instance(value, model): """Returns a model instance from value. If value is a string, gets by key name, if value is an integer, gets by id and if value is an instance, returns the instance. """ if not issubclass(model, db.Model): raise TypeError('Invalid type (model); expected subcla...
85544b057e3e6c82730ba743a625610c55b48ff0
14,519
def clean_infix(token, INFIX): """ Checks token for infixes. (ex. bumalik = balik) token: word to be stemmed for infixes returns STRING """ if check_validation(token): return token for infix in INFIX_SET: if len(token) - len(infix) >= 3 and count_vowel(token[len(infix):]) >= 2: if token[0] == token[...
fdd8e90bdea14ca2344dd465622bd2e79905e4fe
14,520
def seq_to_encoder(input_seq): """从输入空格分隔的数字id串,转成预测用的encoder、decoder、target_weight等 """ input_seq_array = [int(v) for v in input_seq.split()] encoder_input = [PAD_ID] * \ (input_seq_len - len(input_seq_array)) + input_seq_array decoder_input = [GO_ID] + [PAD_ID] * (output_seq_len - 1) e...
9a9203aa9e3005acd7d55516fbe8c5710ea25ae3
14,521
def getMergers(tree, map_strain2species, options): """merge strains to species. returns the new tree with species merged and a dictionary of genes including the genes that have been merged. Currently, only binary merges are supported. """ n = TreeTools.GetSize(tree) + 1 all_strains = map_...
48fb083027e00d93754ee4064edbc268ea4047a5
14,522
def convolve_with_gaussian( data: np.ndarray, kernel_width: int = 21 ) -> np.ndarray: """ Convolves a 1D array with a gaussian kernel of given width """ # create kernel and normalize area under curve norm = stats.norm(0, kernel_width) X = np.linspace(norm.ppf(0.0001), norm.ppf(0.9999), k...
63949d9c235a1a467858077de8dda8455c139551
14,523
def post_netspeed(event, context): """ Speed test data ingestion handler """ return process_reading(event['query'], NETSPEED_SQL)
8414fe3608b7433a177f0c8c54cce61d01339b67
14,524
import json def notify_host_disabled(token, host_name): """ Notify OpenStack Nova that a host is disabled """ url = token.get_service_url(OPENSTACK_SERVICE.NOVA, strip_version=True) if url is None: raise ValueError("OpenStack Nova URL is invalid") # Get the service ID for the nova-com...
904c951a37b8b84df4aa48951c424686a123ff30
14,525
def compute_moments_weights_slow(mu, x2, neighbors, weights): """ This version exaustively iterates over all |E|^2 terms to compute the expected moments exactly. Used to test the more optimized formulations that follow """ N = neighbors.shape[0] K = neighbors.shape[1] # Calculate E[G]...
5a2984174f366a34f16490bb7b9252ec4eaf08db
14,526
import functools def sum_fn(fun, ndims=0): """Higher order helper for summing the result of fun.""" @functools.wraps(fun) def wrapped(*args): batch_loglik = fun(*args) return jnp.sum( batch_loglik.reshape((-1,) + batch_loglik.shape[-ndims + ...
521a4084fee84f16de5714010be9528296f8b231
14,527
from typing import Optional def get_control_policy_attachments(language: Optional[str] = None, output_file: Optional[str] = None, policy_type: Optional[str] = None, target_id: Optional[str] = None, ...
cfa39ca8926c281151b5ae06ef89ce865dfd0af4
14,528
def get_gdb(chip_name=None, gdb_path=None, log_level=None, log_stream_handler=None, log_file_handler=None, log_gdb_proc_file=None, remote_target=None, remote_address=None, remote_port=None, **kwargs): """ set to != N...
15dc451b9cbf21c5f96279a17449e4169e0bae83
14,529
from typing import Callable from typing import Awaitable def check(func: Callable[..., Awaitable[Callable[[CommandContext], Awaitable[bool]]]]) -> Check: """ A decorator which creates a check from a function. """ return Check(func)
2354eef311e1867333ade47996fb37cee07ce4cd
14,531
def service_c(request): """ Renders the service chair page with service submissions """ events = ServiceEvent.objects.filter(semester=get_semester()) submissions_pending = ServiceSubmission.objects.filter(semester=get_semester(), status='0').order_by("date") submissions_submitted = ServiceSubmission.ob...
96d9b281c562a0ddb31d09723012cc9411c4ff09
14,532
def get_tank_history(request, tankid): """ Returns a response listing the device history for each tank. """ # Sanitize tankid tankid = int(tankid) # This query is too complex to be worth constructing in ORM, so just use raw SQL. cursor = connection.cursor() cursor.execute("""\ SE...
39c21c9761ff0e40e1c1f8904cf9b9881faf13ed
14,533
import inspect def get_absolute_module(obj): """ Get the abolulte path to the module for the given object. e.g. assert get_absolute_module(get_absolute_module) == 'artemis.general.should_be_builtins' :param obj: A python module, class, method, function, traceback, frame, or code object :retu...
ea2c85d9ba90414cddce00dcc5ed092b8c6777a2
14,534