content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def findOnePath(startPoint, endPoint, accessMap): """ @ Parameter: startPoint (int, int) the coordinate of starting point endPoint (int, int) the coordinate of ending point accessMap [str] the string list map that indicates whether a place is ...
75fd5df6f586595421dc42e6c40c6e3f700bed82
3,599,200
def index(): """Show portfolio of stocks""" # Define variables that describe the users portfolio using SQL queries cash = db.execute("SELECT cash FROM users WHERE id = ?", session["user_id"])[0]["cash"] stocks = db.execute( "SELECT stock AS symbol, SUM(CASE WHEN transaction_type='buy' THEN shar...
669d308d45177868b671596d77f29896462cd867
3,599,201
def president(request): """ Renders the President page and all relevant information """ return render(request, 'president.html', {'semester_picker': SelectSemester()})
d3ac37ca46f77c1c4202184d0f03e9a9696d15dd
3,599,202
from datetime import datetime def start_of_month(dt, d_years=0, d_months=0): """ Given a date, return a date first day of the month. @param dt: The date to base the return value upon. @param d_years: Specify a delta in years to apply to date. @param d_months: Specify a delta in months to appl...
90976e7df97b8581622df77528540487181cbb8f
3,599,203
def period_circ(p0,p1,pb,asini,t0,t,pepoch): """ Calculate apparent pulse period, given los velocity. Inputs: p0 - pulsar spin period (s) p1 - pulsar period derivative (s/s) pb - orbital period (s) asini - projected semi-major axis (m) t0 - epoch of periapsis (s) t - measurement epo...
d72120f293b6009b1bb165ab847ccef2d7e56e56
3,599,204
def negate(func): """ Creates a function that negates the result of the predicate `func`. The `func` function is executed with the arguments of the created function. Args: func (callable): Function to negate execute. Returns: Negate: Function wrapped in a :class:`Negate` context. ...
9dc4ad29cf8fc447a6e5dc2143b75c9f6f87f73e
3,599,205
def send_message(): """Send message""" first_name = request.form.get("first_name") last_name = request.form.get("last_name") email = request.form.get("email") # message_type = request.form.get("message_type") message = request.form.get("message") print(first_name, last_name, email, message,...
ea10861c787964dfba5d77d3f1031671eb7f1f84
3,599,206
def create_hypergraph(labels): """Create the incidence matrix of labels' hypergraph. Parameter ---------- labels: Labels generated by multiple clustering algorithms such as K-Means. Return ------- H: Incidence matrix of labels' hypergraph. """ H = [] for label in labels: ...
b325cba36941b5ba262dfe9671d8fb3d33822eb2
3,599,207
from sys import path def tensorboard_dir(storage_name: str) -> str: """Absolute path of tensorboard storage folder""" return assure_created(path.join(storage_dir(storage_name), 'tensorboard'))
1049f462d781c472c9b9f7f9a41ec95fca6ec806
3,599,208
import os import uuid def make_job_data(url, script_fn): """Choose defaults. Run in same directory as script_fn. Base job_name on script_fn. """ wd = os.path.dirname(script_fn) job_name = '{0}-{1}-{1}'.format( os.path.basename(script_fn), url.split("/")[-1], ...
8dcc4e0064421964b4e2c717d2e8927cfebd15ff
3,599,209
def create_debug_dir(directory=None): """Creates the directory if doesn't exist already. If directory is None, returns without doing anything. """ if directory is not None: return create_dir(directory)
3817ec4fe327229e75acc8e28e20b2fe2d067989
3,599,210
def _graph_from_voronoi(vor, geometry): """Return networkx.Graph from Voronoi diagram within geometry.""" graph = nx.Graph() for x, y, dist in _yield_ridge_vertices(vor, geometry, dist=True): graph.add_nodes_from([x, y]) graph.add_edge(x, y, weight=dist) return graph
9bd2f949eb355dbb9061ec58e38c394c0d1fd974
3,599,211
def data_transforms(): """get transform of dataset""" if FLAGS.data_transforms in [ 'imagenet1k_basic', 'imagenet1k_inception', 'imagenet1k_mobile']: if FLAGS.data_transforms == 'imagenet1k_inception': mean = [0.5, 0.5, 0.5] std = [0.5, 0.5, 0.5] crop_scal...
a485a7deccd94e65b6fd16a1c6a4f7bd0f6eddc3
3,599,212
def frames(string): """Takes a comma separate list of frames/frame ranges, and returns a set containing those frames Example: "2,3,4-7,10" => set([2,3,4,5,6,7,10]) """ def decode_frames(string): print('s', string) if '-' in string: a = string.split('-') start, en...
a00a80bba4ab369a9682db6b62dad88911ecc711
3,599,213
def isdisc(node): """Test whether a particular node has a discontinuous yield. i.e., test whether its yield contains two or more non-adjacent strings. Nodes can be continuous even if some of their children are discontinuous.""" if not isinstance(node, Tree): return False elif isinstance(node, ImmutableTree): ...
5afc9645e5744706db210a5f805c23091e2ac3af
3,599,214
def key_exists(dictionary, *keys): """Check if key exist in a nested dictionary. :param dictionary: Nested dicionary :type dictionary: dict :param keys: Keys to test agains the dictionary :type keys: args :return: ``True`` if at least one key is in the dicionary :rtype: bool :raise KeyE...
5bf414987e3bf25083cecdcff0af5c201561b15a
3,599,215
def intrusion_sets(filters=None): """Retrieve all Intrusion Set objects. Args: filters (list, optional): A list of additional filters to apply to the query. """ filter_list = FilterSet(filters) filter_list.add(Filter('type', '=', 'intrusion-set')) return query(filter_list)
2c985aad3e8a8ffdef52acbc1e9a83e73e717f9d
3,599,216
def five_zero_zero(exception): """ Usage:: The 500 page for this flask application. """ mail(exception) return render_template("error-handler/500.html")
86733f4672af164e5078e26f4538a13a6e936fd9
3,599,217
async def create_follow_record_for_user( request_body: schemas.FollowsCreateRequestBody, bg_tasks: BackgroundTasks, db: Session = Depends(get_db), current_user: schemas.User = Depends(get_current_user) ): """ The POST method for this endpoint will create a follow relationship between two users. ...
0886352471d1bef36c4585552b3a37104d3328b1
3,599,218
def extendClusterSet(coi, adata=None, G="MetaNeighborUS_metacluster_graph", max_neighbor_distance=2): """Extend cluster set to nearest neighbor on cluster graph Note that the graph is directed, i.e. the neighbors are retrieved by following the ...
7cdad3853d8da98719e1393d0f0b36494f3c92c9
3,599,219
from typing import Tuple def log_normal_distribution( radius_g: float, sigma_g: float, n_bins: int ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """ Function for returning a log-normal size distribution. See Eq. 9 in Ackerman & Marley (2001). Parameters ---------- radius_g : float ...
ef0a623fa3496e7ac042d4355a55c5d9e2730d39
3,599,220
def Default(a): """ Return a default value for array expression. >>> b = K(IntSort(), 1) >>> prove(Default(b) == 1) proved """ if z3_debug(): _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression") return a.default()
e7a00ae818f7112f509bb9cf4f9c23433cfc2289
3,599,221
def dumps(structure): """ Returns structure encoded as a single string, encoded as XML """ buffer = [] env = { 'envelope': structure } __descend(buffer, 0, env) return "".join(buffer)
8cc8d49f033e4807ae56ef32c8c8e953eee015a8
3,599,222
import mpmp.test_config as tcfg import os import sys def load_pancancer_data(verbose=False, test=False, subset_columns=None): """Load pan-cancer relevant data from previous Greene Lab repos. Data being loaded includes: * sample_freeze_df: list of samples from TCGA "data freeze" in 2017 * mutation_df:...
cb5dd51d66071fab7b14f9f27ba6d93c05c33402
3,599,223
def get_creation_hook_name(job_name): """Return the name of the creation hook for the given job (as a string) or None""" return settings.JOBS[job_name].get(CREATION_HOOK_KEY)
76d545eb3ead317efd401828d52c972725b5eade
3,599,224
def brute_force_cow_transport(cows,limit=10): """ Finds the allocation of cows that minimizes the number of spaceship trips via brute force. The brute force algorithm should follow the following method: 1. Enumerate all possible ways that the cows can be divided into separate trips Use the gi...
31a443ba74d778568a1e6c0cd22fef5974a1369c
3,599,225
def process_windshear(procstatus, dscfg, radar_list=None): """ Estimates the wind shear from the wind velocity Parameters ---------- procstatus : int Processing status: 0 initializing, 1 processing volume, 2 post-processing dscfg : dictionary of dictionaries data set con...
11f5c60b5d66f95cbf75aac4c34465e80d588ef0
3,599,226
from uncertainties import unumpy def power_law_I_with_err( f_val=1, f_err=0, g_val=g_DEFAULT, g_err=0, e=1, e1=1, e2=E_INF ): """Wrapper for f so the user doesn't have to know about the uncertainties module""" f = unumpy.uarray(f_val, f_err) g = unumpy.uarray(g_val, g_err) _I = power_law_inte...
5d95f6dcee9ee0734b73c81646357d66ea486e81
3,599,227
def repo_is_neon(repo_url: str) -> bool: """ Determines if the specified repository url is part of the NeonGeckoCom org on github Args: repo_url: string url to check Returns: True if the repository URL is known to be accessible using a neon auth key """ url = urlparse(repo_url) ...
63555347e22a4fe40dd1ec84147c1740da71a5d0
3,599,228
import importlib def class_from_module_path(module_path): """Given the module name and path of a class, tries to retrieve the class. The loaded class can be used to instantiate new objects. """ # load the module, will raise ImportError if module cannot be loaded if "." in module_path: module...
e1b4935efd165c38c6394274c030c52eca5e241d
3,599,229
import logging async def load_gene(ensembl, gene_id): """ sort out all the necessary sequences and positions for a gene Args: ensembl: EnsemblRequest object to request data from ensembl gene_id: HGNC symbol for gene Returns: Gene object, containing info for each trans...
a9f1a8c2afaa5f71f599f25f1ac0afb5f1af0644
3,599,230
import copy def mask_secret_parameters(parameters, secret_parameters): """ Introspect the parameters dict and return a new dict with masked secret parameters. :param parameters: Parameters to process. :type parameters: ``dict`` :param secret_parameters: List of parameter names which are secr...
380045cfe738e3831dd7fe29633d9a8f5fa91306
3,599,231
def matched_allocation(allocation_str_list, **kwargs): """Get allocation declaration""" out = shared_orchestrator.check_add_allocation(allocation_str_list, **kwargs) return out
f0c794b5bbf344a71f9f16400a11a5cc5fbcea59
3,599,232
import tqdm import torch def eval_epoch(model, data_loader, loss, model_device, loss_device): """ Calculates the total dice score and classwise dice score for full volume based evaluations. The loss function is designed to be an torch.nn.Module object Args: model (torch.nn.Module): The mo...
1b80f9e3c539cbfed51d842185ff65d489d4051a
3,599,233
import torch def get_mat_slices(seq_input: Tensor, core_tensor: Tensor) -> Tensor: """ Use sequential input and core tensor to get sequence of matrix slices Args: seq_input: Tensor with shape `(batch, seq_len)` for discrete input sequences, or `(batch, seq_len, input_dim)` for vector ...
299bbac4758cb9d716e1e30c4682a4588ad5b422
3,599,234
def get_kernel_devel_rpms(): """ Get all installed kernel-devel packages ordered by release number (ascending). """ rpms = next(api.consume(InstalledRedHatSignedRPM), InstalledRedHatSignedRPM()) return sorted([pkg for pkg in rpms.items if pkg.name == 'kernel-devel'], key=get_kernel_rpm_release)
19e92fbf10fc0986dbc0453eaa7a88304109b2f1
3,599,235
def make_twitch_blueprint( client_id=None, client_secret=None, *, scope=None, redirect_url=None, redirect_to=None, login_url=None, authorized_url=None, session_class=ClientIdHeaderOAuth2Session, storage=None, rule_kwargs=None, ): """Make a blueprint for authenticating wit...
b57f99449afefbd9ef9be69ae96b0066d88611fe
3,599,236
def share_get_all_by_share_server(context, share_server_id, filters=None, sort_key=None, sort_dir=None): """Returns all shares with given share server ID.""" return IMPL.share_get_all_by_share_server( context, share_server_id, filters=filters, sort_key=sort_key, ...
3c0bbc4b0ca12f98527fb2dfc5e4cf61d6ba6cef
3,599,237
def dictfetchall(cursor): """Returns all rows from a cursor as a dict""" desc = cursor.description return [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()]
72dfab4ad6de6359777d248252fc5e711edc86ad
3,599,238
def dateAsRFC3339Text(date: Date) -> str: """ Convert a :class:`Date` into an RFC 3339 formatted date string. :param date: A date to convert. :return: An RFC 3339 formatted date string corresponding to :obj:`date`. """ return date.isoformat()
0b1641e5a100d6fd28de6ca0a7e73602f2dedb8c
3,599,239
import os import shutil import logging def configure_logger(): """ Configures the logger from the base_config.ini file. When logging to file, the file rotates every new run and also when it reaches a size of 10mb. Mainly to either log to stdout and a file or only a file and how many files it should ke...
3e1c45dd65cd909945ba4b30c27a9cd057e6287f
3,599,240
def place(vertices_resources, nets, machine, constraints, random=default_random): """A random placer. This algorithm performs uniform-random placement of vertices (completely ignoring connectivty) and thus in the general case is likely to produce very poor quality placements. It exists primar...
877a75df9732f31b363a0284e29b60851f54dbb8
3,599,241
def fillin_for_test(template_name, rendered_filename='ta3.yml', **kwargs): """Run for DM template winter eval as in https://datadrivendiscovery.org/wiki/pages/viewpage.action?pageId=11276800 """ global CURRENT_DIR info_dict = dict() # Add or overwrite any arguments # additional_info = ...
f83ae9feb84ecaf422256852d7183554e31f33fd
3,599,242
def get_archive_formats(): """Returns a list of supported formats for archiving and unarchiving. Each element of the returned sequence is a tuple (name, description) """ formats = [(name, registry[2]) for name, registry in _ARCHIVE_FORMATS.items()] formats.sort() return formats
e795c931c9a9061301516134468f5cc970908c79
3,599,243
def add( name, address, root_password, cluster, wait=True, deploy_hosted_engine=False, **kwargs ): """ Add new host Args: name (str): Host name address (str): Host FQDN or IP root_password (str): Host root password cluster (str): Host cluster name wait (bool)...
0b67dc60ab5fa90d92005e3f26e8bb4bebe0f4e4
3,599,244
import json def monitor(plugin): """Monitors channels of this node.""" reply = {} reply['num_connected'] = 0 reply['num_channels'] = 0 reply['format-hint'] = 'simple' peers = plugin.rpc.listpeers() info = plugin.rpc.getinfo() nid = info["id"] chans = {} states = {} for p in...
22a3dd3f161f2c5adc91d7d869981bab0ae73450
3,599,245
def plotvol2(dim, ax=None, equal=False): """ Create 2D plot area :param ax: axes of initializer, defaults to new subplot :type ax: AxesSubplot, optional :param equal: set aspect ratio to 1:1, default False :type equal: bool :return: initialized axes :rtype: AxesSubplot Initialize a...
ce7f4b911a7569e4579a161987dbd10359d914d0
3,599,246
def create_annual_projections_pipeline(**kwargs): """ Combine together all the annual projection sources into a single annual projection This only works for the current year, which is assumed Returns: Pipeline: this pipeline gets all the annual projections from various sources and combines them...
1e235f131c576a96279036210088745a536245c0
3,599,247
def get_thick_line(point1, point2, length_spacing=1, line_thickness=0, width_spacing=1): """Construct a list of points representing a discrete line. If `line_thickness` > 0 then the line is composed of multiple parallel line to each other with a width equal to `line_thickness`. Args: point1: 1D a...
4dd909d044041b2152e88aad630b32e24222bc53
3,599,248
def run_interpolator(interpolator, filename, visualize, dump): """Testing an interpolation method.""" grid = load_data() lon = np.arange(-180, 180, 1 / 3.0) + 1 / 3.0 lat = np.arange(-90, 90, 1 / 3.0) + 1 / 3.0 time = 898500 + 3 x, y, t = np.meshgrid(lon, lat, time, indexing="ij") z0 = core....
05ddf7bb71ab181453ed8ec59b74000b55b9b2ab
3,599,249
def bar_plot(df, colormap, horizontal=False): """ """ # Get the color palette # colors = [colormap(np.arange(len(df)))] colors = get_colors(df, colormap, axis=0) width=0.8 if horizontal: ax = df.plot.barh(label='index', width=width, color=colors) else: ax = df.plot.bar(la...
ec81c0501a648a6ddd69585440183b9021a5c677
3,599,250
def threshold_tukey(signal, threshold): """ Calculate threshold by Tukey method. Parameters ---------- signal : numpy array 1D signal for threshold determination. threshold : float Number of interquartile interval above the 75th percentile. Returns ------- ths_value...
8b2987e7f99ad5538e44d32a7977242348b645b8
3,599,251
from django.db import models import types def check_model_signals(app_configs=None, **kwargs): """ Ensure lazily referenced model signals senders are installed. """ # Avoid circular import errors = [] for name in dir(models.signals): obj = getattr(models.signals, name) if isin...
1e4da612f4a9b481f1bd44b938cf80ece895b55f
3,599,252
import tqdm def img_resize(imgs, img_shape, img_mode='L', resize_filter=None, verbose=True): """Resize images""" resized_imgs = [] if verbose: iterator = tqdm(imgs, ncols=100, unit=' images') else: iterator = imgs for img in iterator: ...
711e458edd8758ac9a7e9bc8cc1c37c529e3ab51
3,599,253
from sgtk_plugin_basic_3dsmax import manifest from tank_vendor import yaml import os def _get_plugin_info(): """ Returns a dictionary of information about the plugin of the form: { plugin_id: <plugin id>, base_configuration: <config descriptor> } """ try: ...
cd35537ab8b790fbd7ef75883a0c77a7022c33d7
3,599,254
def create_sqlalchemy_model( table_name: str, Schema: mm.Schema, segmentation_source: str = None, table_metadata: dict = None, with_crud_columns: bool = False, ) -> DeclarativeMeta: """Create a SQLAlchemy model from supplied marshmallow schema. Parameters ---------- table_name :...
dd3ce35302b95e91cbea55616df2ca0886566a7b
3,599,255
def write_answers(references, hypotheses, rev_vocab, dir_name, id_end): """Writes text answers in files. One file for the reference, one file for each hypotheses Args: references: list of list (one reference) hypotheses: list of list of list (multiple hypotheses) hypoth...
e9e6b10322926bd81f3b18a7fdcee12e360525ac
3,599,256
import re def bcftoolsversion(bcftoolsbin): """ :param bcftoolsbin: bwa bin path :return: string, version of bcftools """ bcftoolscmd = [bcftoolsbin] bcftoolsrun = Popen(bcftoolscmd, stdout=PIPE, stderr=PIPE) pat = re.compile('Version') version = 'None' for i in bcftoolsrun.s...
6a59d04b2fe78ad42c45f294ffb9c101e515d68a
3,599,257
import yaml def load_urls(): """Loads the URLs yaml file and returns a yaml object / dictionary.. Args: None Returns: A yaml (dictionary) object. """ with open(URLS_PATH) as ymlfile: urls = yaml.load(ymlfile, Loader=yaml.FullLoader) return urls
758f4455887ea09686a00d5519a5287605cfbf0a
3,599,258
def has_dynamic_registration_perm(user_level, obj, ctnr, action): """Permissions for static registrations.""" return { 'cyder_admin': True, 'ctnr_admin': True, 'ctnr_user': True, 'ctnr_guest': action == ACTION_VIEW, 'cyder_guest': action == ACTION_VIEW, }.get(user_lev...
30169b515d7d5b782e3971e6a5060c349cf445dd
3,599,259
import re import ast def package_meta(): """Read __init__.py for global package metadata. Do this without importing the package. """ _version_re = re.compile(r'__version__\s+=\s+(.*)') _url_re = re.compile(r'__url__\s+=\s+(.*)') _license_re = re.compile(r'__license__\s+=\s+(.*)') with ope...
70a4f8c2ad820f5817d059f8ddbf6fc844d4a88a
3,599,260
def _fraser_correction( pd, fraserflux, yesterday, afterHope, NonFraser, fraserratio, otherratio, runoff, area, ): """For the Fraser Basin only, replace basic values with the new climatology after Hope and the observed values for Hope. Note, we are changing runoff and ens...
5609c011d7cf95d07953d7ca2b19736a2c687c09
3,599,261
import select import logging def list_sprint(): """ List ALl Sprint :return: """ sprints = list() for item in select(s for s in Sprint if s.status in ['active', 'disable']).order_by(Sprint.name): logging.info('Get sprint %s[%s] info' % (item.uuid, item.name)) sprints.append({ ...
76406d18ec1e6b91d1aa0cf44514e79bca9fe253
3,599,262
import glob import os import re def convert_to_dependencies( changed_files_fullpath: set, build_path, verbose=False): """For each changed hpp file, find a cpp file that depends on it (clang-tidy requires cpp files only) and replace it in the set. To do this, find cmake generated depend.make files ...
4106e34fcaaa1416ef5da89388a65769e1b8f814
3,599,263
def saveper(): """ Real Name: SAVEPER Original Eqn: TIME STEP Units: Month Limits: (0.0, None) Type: component The frequency with which output is stored. """ return time_step()
21fca12744791334fd0f2604c51e64c9099315d9
3,599,264
import re import string import time def main(question: str): """ takes in question from user, then trasnslates an answer """ print("Started Program") thisData = Data(API_KEY, PROJECT_TOKEN) ASK_PATTERNS = { # ASK FOR HELP re.compile("[\w\s]+ help [\w\s]+ "): lambda: thisData.getHelp(...
4622659f728b482ce3a713fcca7efe9938a870d0
3,599,265
def get_ocr_json_url_for_an_image(first_three_digits, second_three_digits, third_three_digits, fourth_three_digits, image_name): """ Get the URL of a JSON file given a barcode ...
44c4d70971f24beee622ff2e11bef0474001aaa3
3,599,266
def download_yt(url): """ Download youtube video by url and save to video folder """ youtube = pytube.YouTube(url) video = youtube.streams.get_highest_resolution() path = video.download(app.config['VIDEO_FOLDER']) return path
196fbe0e099887bfa88c53a888fc0b90cb7bf742
3,599,267
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up the sensors from a ConfigEntry.""" try: api = await real_time_api( entry.data[CONF_IP_ADDRESS], entry.data[CONF_PORT], entry.data[CONF_PASSWORD], ) await api.get_d...
b72c73d7acc421cda830b009e5c9281018f3cbe0
3,599,268
def toWKB(g): """Use :func:`writeWKB`""" return writeWKB(g)
81f0f5642f03a07bbe7f8bca67ced786f7295fed
3,599,269
def cumulate_productivity(df, window=5): """Compute productivity over current and past 4 years.""" return (df.pivot(index="scopus_id", columns="t", values="SJR") .fillna(0).rolling(window, min_periods=1, axis=1).sum() .reset_index().melt(id_vars="scopus_id", value_name="SJR"))
2330b39408136b4a0609f02c1174498c857085cb
3,599,270
def tupleRemoveByIndex(initTuple, indexList): """ Remove the elements of given indices from a tuple. Parameters ---------- initTuple : tuple of any The given tuple from which we will remove elements. indexList : list of ints The indices of elements that we want to remove. R...
17009fc3616afa586467f43b1e7910a17c89ed0d
3,599,271
import os def show_detection(im_ms, cloud_mask, im_labels, shoreline,image_epsg, georef, settings, date, satname): """ Shows the detected shoreline to the user for visual quality control. The user can accept/reject the detected shorelines by using keep/skip buttons. KV WRL 20...
b90b666822e1a3567c73ddb41e31ef1e1127140b
3,599,272
def is_verb(word): """ Проверяет является ли переданное слово глаголом @param word: слово @return: True если слово является глаголом, иначе False """ if not word: return False pos_info = pos_tag([word]) return pos_info[0][1] == 'VB'
a37b9f2f9fea11dc12a7beb9add307b4ec0212c0
3,599,273
import os def run_go_tests(): """Run Go tests.""" return execute_cmd('python butler.py go_unittest', os.environ.copy())
fae5ab9f22f342c628cbf956bb2d06c22d12f277
3,599,274
def parse_mot_record(serialized_example): """Parse serialized example of TfRecord and extract dictionary of all the information """ features = tf.io.parse_single_example( serialized_example, features={ 'video_name': tf.io.FixedLenFeature([], tf.string), 'height': tf.i...
2b52b6ae22546be75cfe7299207a7a5261831902
3,599,275
import argparse def prepare_arguments(): """ Define and return arguments. """ parser = argparse.ArgumentParser(description="PyTorch Energy Experiment v0_1") # model training parser.add_argument("--batch-size", type=int, default=64, metavar="N", help="input batch size for traini...
8019c31bf529b14178b63498d54f9ec6fde6ea4f
3,599,276
def set_hybridization_and_saturate(mol): """ Assign bond orders, saturate with hydrogens, and assign formal charges Specifically, this is a convenience function that runs: ``mdt.guess_bond_orders``, ``mdt.add_hydrogen``, and ``mdt.assign_formal_charges`` Note: This does NOT add missing residue...
abb3dbbade675bf62ba640a56c20183ee30397b8
3,599,277
def executors_benchmark(fn): """Generates different local executors for basic benchmarks.""" def wrapped_fn(self): """Runs `fn` against different local executor stacks.""" tff.framework.set_default_executor( tff.test.ReferenceExecutor(compiler=None)) fn(self, 'reference executor') tff.frame...
074834d5f141716df283565664a30e49952493f7
3,599,278
def hadamard_matrix_paleyII(n): """ Implements the Paley type II construction. EXAMPLES:: sage: sage.combinat.matrices.hadamard_matrix.hadamard_matrix_paleyI(12).det() 2985984 sage: 12^6 2985984 """ N = ZZ(n/2) if is_prime(N-1) and (N-1)%4==1: p = N-1 ...
e057c02c46fbb46a3da05468a2d660c84f689408
3,599,279
import logging def p_distance_calc(current_sample_seq, reference_sample_seq, missing_data_threshold): """This function takes in the current sample sequence and the reference sample sequence and calculates the p-distance per window""" snp_count = 0 same_base = 0 nan_count = 0 logging.debug(f"...
14c27bb34c0efe006c43a78d6fb3313583d707e4
3,599,280
def format_one_query(q, read_seq, read_coords, barcode_dict=None): """Formats output. Parameters ---------- q : dict A dictionary of fuzzy searching result. Key is levenshtein distance. Value is list of matched barcodes. read_seq : str A DNA string (full length read). re...
2523ca6e15547a89e466fc4b4c9dad322fe91dbf
3,599,281
import subprocess def execute_cmd(cmd: str, wd: str = None) -> int: """Execute a shell command.""" # we call it like this because the normal exception # subprocess.CalledProcessError doesnt return the stderr # of the pip call itself (it just says it fails) # so we solve it with popen and pipe/capt...
49d37a26a41d2ae26e5ece07ba2128fb81a20875
3,599,282
def CDLEVENINGDOJISTAR(barDs, count, penetration=-4e37): """Evening Doji Star""" return call_talib_with_ohlc(barDs, count, talib.CDLEVENINGDOJISTAR, penetration)
ceafd0817b72b760658242d1eae0ea0be621fed9
3,599,283
import os import click def scan_config(config, config_dir=None): """ Return the real config path or raise an exception. If config is directory, scan for .tmuxp.{yaml,yml,json} in directory. If one or more found, it will warn and pick the first. If config is ".", "./" or None, it will scan curren...
3adb33d1ded92db0c01512c30c62eb6e48f4b690
3,599,284
def norm_sym_dsn_dist(X, g): """ Returns the normalized pdf of the derivative of a symmetric shot noise process, (td/2)*dS(t)/dt, lambda = 1/2. Input: X: The normalized variable X = (x-<x>)/x_rms, 1d numpy array g: shape parameter Output: F: The pdf of X. """ F = np.zeros...
3dc8353ce347b222feb2da91b52dc5f239843160
3,599,285
from typing import Any from typing import Optional from typing import List from typing import Dict def specs_are_the_same(obj1: Any, obj2: Any, field_paths: Optional[List[str]]=None) -> bool: """Determine if the specifications for two Kubernetes objects are equivalent Only the relevant parts of the two objec...
d24b7b90d040ef7f0ad4715300fb2c39483a634e
3,599,286
def split_graph_feature(node_feat, edge_feat, node_index_list, edge_index_list): """ Split batched node and edge features (graph features) to individual lists :param node_feat: torch.Tensor of shape [N1 + N2 + ..., D1] :param edge_feat: torch.Tensor of shape [E1 + E2 + ..., D2] :param node_index_lis...
628790616dbc0712691b2d61c7ded63519c9568f
3,599,287
import codecs def read_relative_file(filename): """ Returns contents of the given file, whose path is supposed relative to this module. """ with codecs.open(join(dirname(abspath(__file__)), filename), encoding='utf-8') as f: return f.read()
8c3e167247ed0a70350095b9d9eb0eced6023193
3,599,288
import os def mask_cosmicrays(rootname, chip): """ Masks out all cosmic ray-flagged pixels (equal to 0). The *crmask files were generated with AstroDrizzle. The FLT and FLC versions of the image share the same mask. Parameters: rootname : string Rootname of the image. ...
850b0969fa8fa8c1a6f6e2c3aec97c5b47e0772b
3,599,289
def skipThirdPay(): """ 无需支付基本逻辑 1.获取参数 2.校验参数 3.查询订单支付信息 4.判断支付金额与支付状态 5.返回响应 """ # 1.获取参数: token, orders_id token = request.json.get("token") orders_id = request.json.get("orders_id") # 2.校验参数 # 判断用户是否登陆 if not token: return jsonify(code=RET.TOKENERR, ...
ef121fa87ee4af37ce658e8ff04b949fc24f8e23
3,599,290
import random def flirt(text, conn, nick, message): """<user> - flirts with <user>""" target = text.strip() if not is_valid(target): return "I can't flirt with that." if is_self(conn, target): # user is trying to make the bot attack itself! target = nick message('{}, {}'...
cb840e414567b3be3b2ad8318fa03167a449db35
3,599,291
def deepclustering_loss(targets, logits, usedbins, seq_length, batch_size): """ Compute the deep clustering loss cost function based on Hershey et al. 2016 Args: targets: a [batch_size x time x (feat_dim*nrS)] tensor containing the binary targets logits: a [batch_size x time x (feat_dim*emb_dim)] tensor contai...
ff18834a32d712e691964b51201b80b77c4c406d
3,599,292
import os def get_data(name=None): """ Get ANTsPy test data filename ANTsR function: `getANTsRData` Arguments --------- name : string name of test image tag to retrieve Options: - 'r16' - 'r27' - 'r64' - 'r85' - ...
3d88aa1c049217530355dae60536ac8129ffadbf
3,599,293
def refine_with_details_criteria(flats_list, constraint): """ Filter a list of flats according to the criteria which require the full details to be fetched. These include minimum number of photos and terms that should appear in description. .. note :: This has to be done in a separate func...
e5f86e272ca3a73a5146efa71dc53222d5175bc8
3,599,294
def merge_spike_trains(spike_trains): """ Merges a number of spike trains into a single spike train. :param spike_trains: list of :class:`.SpikeTrain` :returns: spike train with the merged spike times """ # concatenating and sorting with numpy is fast, it also means we can handle # empty spike ...
d4972b008fb60ceb6fc0a51a3eba83104049bea2
3,599,295
def create_mysql_mysqldb(username, password, host, port, database, **kwargs): # pragma: no cover """ create an engine connected to a mysql database using mysqldb. """ return create_engine( _create_mysql_mysqldb(username, password, host, port, database), **kwargs )
d1b599b33012c85f893665817136ae6d3c08647b
3,599,296
import json async def create(_req, gameid, jwt): """Create a new group for the given game""" groupid = await KVS.create_group(jwt["uid"], gameid) return json({"groupid": str(groupid)})
a1c6ab446b86e911bc759854c56f84838863f552
3,599,297
def get_diagfile(results_dir): """Return the name of a diagnostics file in results_dir that is completed. Useful for the functions that insert git commits into files and need a representative diagnostic file to get the git commits from. We arbitrarily pick the last complete directory.""" ...
09b429dea1df12aae1e2c26c15c31ebc63fbee52
3,599,298
import torch def regression(src_bbox, loc): """ Apply regression, by applying the offset coefficient Input: srx_bbox [N, R, 4]: coordinates of bounding boxes in XYXY.REL format loc [N, R, 4]: offset coefficient t_x, t_y, t_w, t_h in CxCyWH.REL format Return: dst_bbox[N, R, 4]: ...
1d6137ecf1895fc92f63c37a510f2d0f3d68f54f
3,599,299