content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Optional from typing import Any import time import json def success(message: Optional[str] = None, data: Any = None, status: int = 200, code: int = 20000) -> Response: """ 函数体处理成功,请求流程正常结束 """ if data is None: data = dict() res = { 'code': code, 'message'...
21ed8a5748fdba20da28e92f9a0a2290166bdb75
3,599,186
import time def dehydrate_time(value): """ Dehydrator for `time` values. :param value: :type value: Time :return: """ if isinstance(value, Time): nanoseconds = int(value.ticks * 1000000000) elif isinstance(value, time): nanoseconds = (3600000000000 * value.hour + 600000000...
ba3528b7364a775ddcad7acebdb771f8aee666f4
3,599,187
def make_df_range(df, start, end): """ Given a dataframe, a starting date and an ending date (both datetime objects), return a data frame of the value counts for song ids """ songs = pd.DataFrame(columns=["ID","Timestamp"]) for i in range(len(df)): timestamp = df.iloc[i,1] parsed = p...
ea3dadc4f18e8cfdff6d7eac53760d3d420e99c0
3,599,188
def get_duration(self): """ Returns time taken for particles to exit the system following release (duration of trajectory). The duration (ns) is given as the time elapsed from the release of a particle to it's exiting from the sytem and is returned for all trajectories as an ndarray. Param...
3b9cbeac456c592d7ab66d522fce545539505344
3,599,189
def softmax(x): """Compute softmax values for each sets of scores in x.""" e_x = np.exp(x - np.max(x)) return e_x / e_x.sum()
2d47067fc6fb94a823e562eb192b926314bbf963
3,599,191
import struct def make_primitive_serializer(format): """Create a serializer for a primitive type from a struct format string. The given `format` is a format string as defined in the `struct` module and is expected to include a single primitive type. See: http://docs.python.org/library/struct.html ...
d7db31a67d3faf8d773f0317b9f8684b6f981426
3,599,192
import datasets def evaluate(dataset: object, predictions: object, output_folder: object, ovthresh: object) -> object: """evaluate dataset using different methods based on dataset type. Args: dataset: Dataset object predictions(list[BoxList]): each item in the list represents the p...
d20048ffb80bd541e227d292478a19e1fd6c6dee
3,599,193
from ralph.attachments.models import Attachment, AttachmentItem import mimetypes from typing import Iterable def add_attachment_from_disk(objs, local_path_to_file, owner, description=''): """Create attachment from absolute file path. Function create and returns attachment object with file from local path. ...
d7ff0be7716d90ca62528d5f9a734ae8b0eb38a1
3,599,194
def estimate_poses_given_rot(factors: gtsam.BetweenFactorPose3s, rotations: gtsam.Values, d: int = 3): """ Estimate Poses from measurements, given rotations. From SfmProblem in shonan. Arguments: factors -- data structure with many BetweenFactor...
1542b9e1f1d82384fa3e44e5f477cee489b259ab
3,599,195
def _weights(x, dx=1, orig=0, ravel=True, labels=None): """ Compute linear interpolation weights for projection array `x` and regularly spaced detector pixels separated by `dx` and starting at `orig`. """ if ravel: x = np.ravel(x) floor_x = np.floor((x - orig) / dx).astype(np.int32) ...
10c4250a7b185ce5730e1f24258810c2b099ede4
3,599,196
def hazel_library(package_name): """Returns the label of the haskell_library rule for the given package.""" return "@{}//:lib".format(hazel_workspace(package_name))
1c67b4b3ad5468c76394e9e0b68bc91ab6bfa61d
3,599,197
import re def regex_from_segments(segments, requires=None, escape_segment=True): """Converts a list of segment tuple pairs into a regular expression string. Args: segments (list): The segment tuple pairs to convert. requires (dict): Key/value pairs to be used in each segment. Returns: ...
2753db6616bd7ac7d66c0fe84585f400a696d794
3,599,198
async def update_user( id: str, user: UserUpdate = Body(...), current_user: User = Depends(services.get_current_user), ): """Endpoint for updating user.""" user = services.update_user(id=id, user=user) if user: return JSONResponse(status_code=200, ...
8ab6500292b950ed760b1ba58a5f7ac0bceb1b5e
3,599,199
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
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 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
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
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
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 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
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
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
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
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
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
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
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
def CDLEVENINGDOJISTAR(barDs, count, penetration=-4e37): """Evening Doji Star""" return call_talib_with_ohlc(barDs, count, talib.CDLEVENINGDOJISTAR, penetration)
ceafd0817b72b760658242d1eae0ea0be621fed9
3,599,283
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
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
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
from typing import List from datetime import datetime def filter_archives( archives: List[Archive], intervals: List[datetime.timedelta], current_date: datetime.datetime = None, ) -> List[Archive]: """ Return a list of archive names which should be kept. ``archives`` is a list of ``jdsnap.Arch...
82dd416734ba9b7811a71c0ef2661b369db4ff62
3,599,300
def get_action(state, player): """ Returns an action from the _ACTION_CATALOGUE, given the state. Args: state (connect_x.game.connect_x.ConnectXState): The state. player (int): The player. Returns: int: The action. """ matrix = bitmaps_to_matrix(state.bitmaps) mark ...
03e10eeca9cf9d912d226766cc0bb3f7cf0af5a6
3,599,301
def get_path(name, scheme=_get_default_scheme(), vars=None, expand=True): """Returns a path corresponding to the scheme. ``scheme`` is the install scheme name. """ return get_paths(scheme, vars, expand)[name]
755223fea25a7153a3441ca048ffeb0aad68123f
3,599,302
def get_bot(): """ Gets the already instantiated Telegram client :return: Telegram client instance :rtype: telegram.Bot """ if not _bot: initialize_bot() return _bot
4be9e7a3bdc4ee21a2bc126f7fcefb92daee6714
3,599,303
def get_binwise_reduced_column(a_gpu, stride, a_range): """ description: calls the cuda jit function calc_binwise_reduced_column and returns the result input: - a_gpu -> single col nd-array - stride -> stride value - a_range -> min-max values (ndarray => shape(2,)) ...
2dddf4012480d5645d86e9b0c2a61c8175977ad5
3,599,304
from typing import Dict def select_dict_from_resname(u: Universe) -> Dict[str, str]: """ Infer select_dict (possibly interested atom species selection) from resnames in a MDAnalysis.universe object. The resname must be pre-assigned already. Args: u: The universe object to work with. retu...
a9e844ade104303ffc9c8b1f6b5c742570353156
3,599,305