content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def compute_mean_sem(df, key='fold_change'): """ Computes the mean and standard error of the fold-change given a grouped pandas Series. """ # Compute the properties mean_val = df[key].mean() sem_val = df[key].std() / np.sqrt(len(df)) # Assemble the new pandas series and return. samp...
ec628f966b2fe5d43261c37e44408d7a22fc6583
3,616,004
def main() -> int: """ Handle program invocation. :returns: Exit code. """ logger.info('Initialising Database Connection') db = ed_bgs.Database(config['database']['url'], logger) ebgs = ed_bgs.EliteBGS(logger, db) # return None # Looping over monitored factions for f in config['monitor_factions']:...
bb95137f110cd7fcb8acec2824e07310350d1d46
3,616,006
import xmlrpc def stop_vm(client, session, vm, params): """Stop an existing virtual machine. It will fail if the virtual machine does not exist.""" if vm['state'] is None: return { 'failed': True, 'msg': NOT_EXISTS_ERR } if vm['state'] in ('hold', 'stopped'): return { 'changed': False,...
39a04448f645c337f876a4d48edb8cb4c3cbbfbb
3,616,007
import torch def accuracy(predictions, labels): """ Evaluate accuracy from model predictions against ground truth labels. """ ind = torch.argmax(predictions, 1) # provide labels only for samples, where prediction is available (during the training, not every samples prediction is returned for effic...
484ba64b2239363daddd206e747f6c1456e236c9
3,616,008
def _quick_reap(): """Reaps a task.""" data = _gen_request_data( properties=dict(dimensions={u'OS': u'Windows-3.1.1'})) request = task_request.make_request(data) _result_summary = task_scheduler.schedule_request(request) reaped_request, run_result = task_scheduler.bot_reap_task( {'OS': 'Windows-3....
54e3c1793a2394ec97158e277fb803b7466fc150
3,616,009
from klab.bio.basics import residue_type_3to1_map def read_and_calculate(workspace, pdb_paths): """ Calculate a variety of score and distance metrics for the given structures. """ # Parse the given restraints file. The restraints definitions are used to # calculate the "restraint_dist" metric, w...
568d9647200ee40868421c7e8a957213e045ebad
3,616,010
from typing import Callable def closure(func: Callable) -> Callable: """Wrap a method to eliminate the self keyword from its signature.""" # tried using @functools.wraps, but could not get it to work right def wrapped(*args, **kwargs): self = args[0] if len(args) > 1: args = a...
79eaac9fc3f4df2cee66c444fef5f8feff18e5bb
3,616,011
def dynamic_stub(end, group, cardinalities, pool): """Creates an face.DynamicStub. Args: end: A base.End. group: The group identifier for all RPCs to be made with the created face.DynamicStub. cardinalities: A dict from method identifier to cardinality.Cardinality value identifying the card...
4f5e0660323071d8bff85fbaa0ebb9bcb837097b
3,616,012
def get_issns_for_journal(nlm_id): """Get a list of the ISSN numbers for a journal given its NLM ID. Structure of the XML output returned by the NLM Catalog query:: NLMCatalogRecordSet NLMCatalogRecord NlmUniqueID DateCreated DateRevised DateAu...
3c490d29066d6218ed21b72fd3f010c9ac7ca4d5
3,616,013
def encode(lng, lat, precision=10, bits_per_char=6): """Encode a lng/lat position as a geohash using a hilbert curve This function encodes a lng/lat coordinate to a geohash of length `precision` on a corresponding a hilbert curve. Each character encodes `bits_per_char` bits per character (allowed are 2...
090bffcd46ff26c2428e1fcfc1537da584f63196
3,616,014
def filter_form(context, *args, **kwargs): """Тег представления filter form как таблицы. """ filter_form = (args[0] if len(args) > 0 else kwargs.get('filter')) if not filter_form: filter_form = context.get('filter') if filter_form is None: raise TemplateSyntaxErr...
50526302a9ea7d08e8818c92a68715313be4591b
3,616,015
def test_lr_monitor_multi_lrs(tmpdir, logging_interval: str): """ Test that learning rates are extracted and logged for multi lr schedulers. """ tutils.reset_seed() class CustomBoringModel(BoringModel): def training_step(self, batch, batch_idx, optimizer_idx): return super().training_s...
51e60dfaf745a0dedb6e492828daa7f0f6942839
3,616,016
def non_max_suppression_bbox(bboxes, confidences, img_size, verbose=False): """ high confidence detections suppress all overlapping detections (including detections at other scales). Detections can partially overlap, but the center of one detection can not be within another detection. :param bboxes: Nx4 nump...
fc80d4e039a5658ba23cbc95c7e32297e71ff081
3,616,017
def inet_ntoa(i): """Convert an int to dotted quad.""" return '.'.join(map(str, [(i >> (3-j)*8) & 0xff for j in range(4)]))
b83a6b08118bcd7858cb588f53b71daaf31d358e
3,616,018
def cleanup_string(string): """ >>> cleanup_string(u', Road - ') u'road' >>> cleanup_string(u',Lighting - ') u'lighting' >>> cleanup_string(u', Length - ') u'length' >>> cleanup_string(None) '' >>> cleanup_string(' LIT ..') 'lit' >>> cleanup_string('poor.') 'poor' ...
5f9a369a52b798ff8c26bea56fbfe585b3612db0
3,616,019
def termConvection(t, y, schemeData): """ termConvection: approximate a convective term in an HJ PDE with upwinding. [ ydot, stepBound, schemeData ] = termConvection(t, y, schemeData) Computes an approximation of motion by a constant velocity field V(x,t) for a Hamilton-Jacobi PDE (often calle...
6954cef17beb6d1278dddfaf2ac3537efe42cf78
3,616,021
def is_field_allowed(name, field_filter=None): """ Check is field name is eligible for being split. For example, '__str__' is not, but 'related__field' is. """ if field_filter in ["year", "month", "week", "day", "hour", "minute", "second"]: return False return isinstance(name, s...
8be38b79bab3aeb49219155db0159cc143c38111
3,616,022
def build(help: dict) -> str: """Returns the formatted help string. See the GitHub page for info.""" global _cust_config final_str = "" terms = help["terms"] if "config" in help: _cust_config = help["config"] else: _cust_config = {} # Terms for term in terms: if...
2c7c89afed8b2e8dbbed49a2edcfadaf69ae4fa8
3,616,023
import logging def setup_logger(level): """ Setup a logger for the REST handler """ logger = logging.getLogger('splunk.appserver.lookup_editor.rest_handler') logger.propagate = False # Prevent the log messages from being duplicated in the python.log file logger.setLevel(level) log_file_p...
4d0dff0da93d0a32520ebae1c0eaacde284ec179
3,616,024
from django.contrib.contenttypes import models from django.contrib.auth import models as auth_models def _makePermission(perm, model, app_label='editorialmanager'): """ Retrieves a Permission according to the given model and app_label. """ ct = models.ContentType.objects.get(model=model, app_label=ap...
a2219855a89aab4426a1597632dece89b8aa5afc
3,616,025
def greater_equal(lhs, rhs): """Broadcasted elementwise test for (lhs >= rhs). Parameters ---------- lhs : relay.Expr The left hand side input data rhs : relay.Expr The right hand side input data Returns ------- result : relay.Expr The computed result. """ ...
5b9eeab5fb9323a96895c3009cf15f947cb57910
3,616,026
from typing import List from typing import Optional from typing import Dict def mergeVotingResult(vote: List[int], policevote: Optional[int] = None) -> Dict[int, float]: """ Count the vote result and the return the candidates with most votes ### Parameter - vote: `List[int]`, the vote result ##...
38649fc4e1c80d31375cce920b39387fd533b0b0
3,616,027
def get_avatar(burl, height): """ xxx """ return_data = '' uid = user_get_uid() avatar_id = 0 connection = pymysql.connect(host=DB_SRV, user=DB_USR, password=DB_PWD, db=DB_NAME, ...
1cbbcd31adffb4c5c0d60a803ef65b793cf5cd40
3,616,029
def signup(): """ Presents an anonymous user with the registration form and adds their info to the database. Uses user.set_password() to hash their password (instead of storing it plaintext). """ if current_user.is_authenticated: return redirect(url_for('index')) form = RegistrationForm...
76a9f449162f7bd1131ffab9e551f31529431f69
3,616,030
def read_bdf(iterable): """ Read a BDF-format font from the given source. iterable should be an iterable that yields a string for each line of the BDF file - for example, a list of strings, or a file-like object. """ name = "" pointSize = 0.0 resX = 0 resY = 0 comments = [] font = None for line in iterabl...
cb0ae7f28060e702317184ae93d538bd10c1a77c
3,616,031
def parallel_apply(df, group_list, f, num_cores, print_every_n=1000, **kwargs): """ A lightweight version of apply using the multiprocess library :param df: the pandas dataframe that needs to be grouped :param group_list: a list of variable names to group by :param f: the function that operates on ...
d14e3d8a354121abf0dfe193eb1cfa2af89d65bd
3,616,032
import requests import socket def _do_generate_runner(endpoint): """ Get the hostname or IP of the runner. Will try to get the public host name from AWS metadata first, then from reverse lookup, and then fall back to using the local hostname :return: An ip address or a hostname :rtype: str ...
0d2f62f393270f12763e0635df38e6bf2e6c596b
3,616,033
def vectorized_is_element(array, choices): """ Check if each element of ``array`` is in choices. Parameters ---------- array : np.ndarray choices : object Object implementing __contains__. Returns ------- was_element : np.ndarray[bool] Array indicating whether each ...
03818826ea0d7a9bf48a6bfce204f591c96dea58
3,616,034
def what_am_I_from_prob(probabilities, no_of_guesses=5, true_class='', verbose=True): """Function to classify based on 'prob'ability layer inputs probabilities: a vector of input probabilities no_of_guesses: how many of the top probabilities do you want? true_class: the real class name if known outp...
f30692ea00d00dfb12c217751e18f40fde80a7a6
3,616,035
import typing def _parse_term_from_lists( term_list: typing.List, networks: NetworkStore = None ) -> Term: """Term is a list where the first element is either a valid functor or the keyword 'list'. If the first element is list, then this term is a list, we parse recursively all its elements and return the...
7d2bd73d4f63105e627613c47cea4a21c80ad5ff
3,616,036
def create_urine_features(charts): """ features of urine color and appearance""" res = charts.loc[charts.label.str.lower().str.contains('urine', na=False), ['hadm_id', 'eventtime', 'admittime', 'label', 'value', 'valuenum', 'unitname']] # clean the label column res['labe...
379a4707f5a773375e5f289287dd2cc0f4df2c60
3,616,037
def merge_user_settings(settings): """Return the default linter settings merged with the user's settings.""" user = settings.get('user', {}) default = settings.get('default', {}) if user: tooltip_styles = default.get('tooltip_styles', {}) user_tooltip_styles = user.get('tooltip_styles',...
969457f907d8431c9af6ef8a1b587575cb3ba681
3,616,038
def RSRS1(dataFame, Sbuy=1.0, Ssell=0.8): """斜率指标交易策略 """ data = dataFame.copy() data['flag'] = 0 # 买卖标记 data['position'] = 0 # 持仓标记 position = 0 # 是否持仓,持仓:1,不持仓:0 for i in range(1, data.shape[0] - 1): # 开仓 if data.loc[i, 'beta'] > Sbuy and position == 0: data...
a57d6199828b765ceb70d25fc61c4cc559a05580
3,616,039
def rgb2gray(rgb): """ Change RGB color image into grayscale in RGB representation using colorimetric (perceptual luminance-preserving) conversion :param rgb: NumPy array of the RGB image :return: NumPy array of grayscale image, same shape as input """ r, g, b = rgb[:, :, 0]/255, rgb[:, :, 1]/2...
3c0b3a4ad1b2057b2b793569e629d36d7be27f7f
3,616,041
import wave def get_speech_features_from_file(filename, num_features, pad_to=8, features_type='spectrogram', window_size=20e-3, window_stride=10e-3,...
bdb92866fa4014c9a1831e1138d1358a8b4d36c5
3,616,042
def health() -> dict: """ Root Get """ health = schemas.Health( name=settings.PROJECT_NAME, api_version=__version__, model_version=model_version ) return health.dict()
65b059e44f929886576e9c181ffd8b3b785f17ba
3,616,043
import copy def site_response(sp, asig, linear=0, freqs=(0.5, 10), xi=0.03): """ Run seismic analysis of a soil profile - example based on: http://opensees.berkeley.edu/wiki/index.php/Site_Response_Analysis_of_a_Layered_Soil_Column_(Total_Stress_Analysis) Parameters ---------- sp: sfsimodels....
5cbbf8b980156ca579135620c81592950f6b7b41
3,616,044
from typing import Tuple def _get_field_names( schema_field_details: Tuple[Tuple[str, DataType], ...], ) -> Tuple[str, ...]: """Returns field names from schema fields.""" return tuple(field[0] for field in schema_field_details)
9e985b0a2619c24004e35f1ead6912a6fad91769
3,616,047
def strip_outer_matching_chars(s, outer_char): """ If a string has the same characters wrapped around it, remove them. Make sure the pair match. """ s = s.strip() if (s[0] == s[-1]) and s.startswith(outer_char): return s[1:-1] return s
b55d1f966a8b216dce2d4817117f350f639b9b83
3,616,048
def lr_schedule(step): """Linear scaling rule optimized for 90 epochs.""" steps_per_epoch = 30000 // FLAGS.batch_size current_epoch = step / steps_per_epoch # type: float lr = (1.0 * FLAGS.batch_size) / 32 boundaries = jnp.array((20, 40, 60)) * steps_per_epoch values = jnp.array([1., 0.1, 0.01, 0.001]) * ...
f0579c77084e1092fc09b7a236b4bf4f848fc1cf
3,616,050
def make_chunks(infos, **kwargs): """Generate chunks from note infos""" return s.chunked(make_sound(infos, **kwargs))
1dc4ab1bccc3ed83e008efc45731df4cc532ad99
3,616,051
from pathlib import Path def plot_traces_by_qu_unexp_sess(analyspar, sesspar, stimpar, extrapar, quantpar, sess_info, trace_stats, figpar=None, savedir=None, modif=False): """ plot_traces_by_qu_unexp_sess(analyspar, sesspar, stimpar, extrapar, ...
7a1bfcf03b4468b58eff8d842ec82c5a508479db
3,616,053
def to_cartesian(p, direction=1, axis='z'): """ Converts a point given in (r, theta, z) coordinates to cartesian coordinate system. optionally, axis can be aligned with either cartesian axis x* or z and rotation sense can be inverted with direction=-1 *when axis is 'x': theta goes from 0 at y-axis...
9f171da66e66b1f7a580f0f22d9b5bc7c970cd95
3,616,054
def getLimits(locations, current, sortResults=True, verbose=False): """ Find the projections for each delta in the list of locations, relative to the current location. Return only the dimensions that are relevant for current. """ limit = {} for l in locations: a, b = current.comm...
b8c62aecc2ce37fcaefd63544bd64ccba94f257b
3,616,055
def mclag_ka_session_dep_check(ka, session_tmout): """Check if the MCLAG Keepalive timer and session timeout values are multiples of each other and keepalive is < session timeout value """ if not session_tmout >= ( 3 * ka): return False, "MCLAG Keepalive:{} Session_timeout:{} values not satisfying ...
3f3fd6a12711c0c290cdb0fbd68cfd1c743ef515
3,616,056
import struct def pack(fmt, *args): """pack() is wrapper of struct.pack """ value = struct.pack(fmt, *args) result = [] if isinstance(value, str): # For Python2 for v in value: result.append(ord(v)) return result elif isinstance(value, bytes): # F...
a9e4349debf9d9d9e088e8c02a9fc044b9a1897b
3,616,057
def get_teacher_information(gid): """ Retrieve the team information for all teams in a group. Args: gid: the group id Returns: A list of team information """ group = get_group(gid=gid) member_information = [] for tid in group["teachers"]: team_information = api....
c140fc2718f7bef1dd1367fd187b048e31304dfc
3,616,058
def needs_owner(func): """Decorator to require the owner for the given function.""" @wraps(func) def decorated_function(*args, **kwargs): if args[0].chat.id != SETTINGS['owner']: bot.reply_to(args[0], 'Sorry, you are not the owner of this bot') return return func(*ar...
7cbecfb5901b0cab362f30017c615baac1dd9c57
3,616,059
def decompose_to_device(operation: cirq.Operation, atol: float = 1e-8) -> cirq.OP_TREE: """Decompose operation to ionq native operations. Merges single qubit operations and decomposes two qubit operations into CZ gates. Args: operation: `cirq.Operation` to decompose. atol: absolute er...
f0b78287d44922482f81f59c1d8a202cf36167d3
3,616,060
def lucas(n): """ compute the nth Lucas number """ a, b = 2, 1 # notice that all I had to change from fib were these values? if n == 0: return a for _ in range(n - 1): a, b = b, a + b return b
9d9404edf59690cafc49ba70d7dc776376d1f020
3,616,061
def do_map_eval(B, S, param, O, W = None, BGp = None): """ This function evaluate the target function given a output window set. Args: B: . S: . param: . O: . W: . BGp: . Returns: statTmp: . """ statTmp = {} statTmp['W'] = np.array([]) statTmp['Xp'] =...
1cf7ced27aac09a996b359936b28ad00b0fb7527
3,616,062
def transform_disturbances(draws, shocks_mean, shocks_cholesky): """Transform the standard normal deviates to the relevant distribution.""" draws_transformed = draws.dot(shocks_cholesky.T) draws_transformed += shocks_mean draws_transformed[:, :2] = np.clip( np.exp(draws_transformed[:, :2]), 0....
532096f3710ebcf7259dfa8641152efc98db1660
3,616,063
import torch def predict_one_scan_binary_class(rescaled_array, direction, checkpoint_path, array_info, batch_size=16, evaluate=False): """ :param array_info: stores information of the rescaled_array :param rescaled_array: float32 array in shape [512, 512, 512, data_channel + enhanced_channel + semantic_ch...
4b7fb388a1b557c4f2c13eeeea24989cfe9c29a2
3,616,064
def shuffle_batch(labeled_tensors, batch_size, num_threads=1, capacity=32, enqueue_many=False, min_after_dequeue=0, seed=None, allow_smaller_final_batch=False, name=None): ""...
923f16f93e9107e8b2969c084751fb78e8f177fe
3,616,065
from typing import Tuple from typing import Union def natural_keys(text: str) -> Tuple[Union[int, str], ...]: """ alist.sort(key=natural_keys) sorts in human order :see: http://nedbatchelder.com/blog/200712/human_sorting.html :see: http://stackoverflow.com/a/5967539/1391325 """ return tuple(__atoi(c) for c in ...
d8c902ee7ee06fa33001e75f2c0fb87d83126175
3,616,066
def return_dict_of_attrs(obj): """ Returns dictionary of attributes of object that are not private or None, and which top namespace is not sqlalchemy or wpipe. Parameters ---------- obj Input object. Returns ------- attrs : dict Dictionary of attributes of obj. ...
465abfd8ebb19d8dbfd5d8e6dd7cbb9099ad0b36
3,616,067
def BenefitSurg(t): """Surgery benefits""" return SizeBenefitSurg(t) * PolsSurg(t)
3376ae734d92b00b0bbb4ec6246e533f00bc88ce
3,616,068
def _get_edge_attrs(edge_attrs, concat_qualifiers): """ get edge attrs, returns for qualifiers always a list """ attrs = dict() if "qualifiers" not in edge_attrs: attrs["qualifiers"] = [] elif edge_attrs["qualifiers"] is None: attrs["qualifiers"] = edge_attrs["qualifiers"] if at...
8500ae7c606041071264d980155fbada98ba870e
3,616,069
def destroy_raid_bdev(client, name): """Destroy pooled device Args: name: raid bdev name Returns: None """ params = {'name': name} return client.call('destroy_raid_bdev', params)
ef377fc024cd326ef3e496ffc94b10ef2076e1e2
3,616,070
def get_closest_point_index(pt, pts): """ Closest point index of the pts from pt. """ distances = [rs.Distance(p, pt) for p in pts] min_index = distances.index(min(distances)) return min_index
5df14d648ead10e694323785625aa842a1ddd1ff
3,616,071
def IFS(FS, T0=2 * np.pi, m_start=-4, m_stop=4, x_min=0, x_max=2 * np.pi, x_num=10): """Function to reconstruct (or check) the periodic function from the obtained Fourier coefficients""" m = np.arange(m_start, m_stop + 1) m = np.reshape(m, (-1, m.size)) M = np.tile(m, (x_num, 1)) x = np.linspa...
466a4e2c967ebda2a8a0ae6804b4427d695c3928
3,616,072
def get_calendar(username, base_url='https://github.com/'): """retrieves the github commit calendar data for a username""" base_url = base_url + 'users/' + username try: url = base_url + '/contributions' page = urllib2.urlopen(url) except (urllib2.HTTPError,urllib2.URLError) as e...
d4c40371ed208046e97e79d92fb97c5a8e60c463
3,616,073
def stop_comm_msg_create(pid: int, ts: float) -> message.Message: """ create a message to stop the comm_handler :param pid: agent pid :type pid: int :param ts: timestamp :type ts: float :return: stop communication handler message :rtype: Message """ return message.Message(pid,...
c9d7c6361f276c1b8d54402aad713b05f17044ac
3,616,074
def _normalize_data(data): """Turn entities in properties into entity ids""" entities = data['layout']['entities'] for obj in entities: schema = model.get(obj.get('schema')) if schema is None: raise InvalidData("Invalid schema %s" % obj.get('schema')) properties = obj.get...
ff5f7de484f1483cc6ce2399d464d73724d3d8ee
3,616,075
def conv2D_generative(inputs, filters, kernel_size=(1, 1), padding="same", activation=None, reuse=False, name="conv2D", strides=(1, 1), dilation_rate=(1, 1), use_bias=True, mask=None, bias_init=0. ): """ 2D...
515915d47c3715ccb60de909e07e10ed65fa60dd
3,616,076
def FlattenList(list): """Flattens a list of lists.""" return [item for sublist in list for item in sublist]
5ab33bd326d221449f9efc0da7ffa39eeedd3add
3,616,077
def _build_state_value(django_request, user): """Composes the value for the 'state' parameter. Packs the current request URI and an XSRF token into an opaque string that can be passed to the authentication server via the 'state' parameter. Meant to be similar to oauth2client.appengine._build_state_value. A...
4434c025065124f942f436ecf88f383d7cfe6c43
3,616,078
import sh def commit(experiment_name, time): """ Try to commit repo exactly as it is when starting the experiment for reproducibility. """ try: sh.git.commit('-a', m=f'"auto commit tracked ' f'files for new experiment: ' ...
b62a32ddae3c53ce16f2931356493b683fa8794c
3,616,079
import numpy def angd2vec2d(ang: float) -> numpy.array: """Convert angle in degrees to a 2-d unit vector in the x-y plane.""" return ang2vecd(ang)[:2]
03b9ff6f569a1745d6b7a3fb125e92b3eabc95b2
3,616,080
def pair_align(a, b): """ Accurate Registration. :param a: Point cloud for previous frame. :param b: Point cloud for current frame. :return: The matrix. """ x = 0 return x
033515d87b900a7790c4a461409138d420aa164d
3,616,081
async def battery(request): """GET /api/battery cf. https://docs.mistyrobotics.com/misty-ii/rest-api/api-reference/#getbatterylevel """ return web.json_response({ 'status': 'Success', 'result': generate_batterylevel(), })
e1e404ca3cbae05bcf9db0e982fb906197edd05f
3,616,082
def refresh_auth(action): """ Uses the 'Authorization' block in the request header to return a fresh token for a user. """ # first, drop GETs trying to do a refresh: we don't play that shit if action == 'refresh' and flask.request.method == 'GET': return utils.http_405 setattr(flask.reques...
375ac68493ec725245647b252819cb7a295c4f48
3,616,083
from typing import Iterable from typing import Type from typing import Union def apply_noise_to_gates( circuit: Circuit, noise: Iterable[Type[Noise]], target_gates: Union[Iterable[Type[Gate]], np.ndarray], target_qubits: QubitSet, ) -> Circuit: """Apply noise after target gates in target qubits. ...
1299ce4eaa2ad8f5993767d41883d44af1855ee4
3,616,084
def load_info(path = defaults._default_info_path, verbose = False): """ :param path: :param verbose: :return: """ if verbose: print(path) i = classes.InfoClass() i.load(path) return i
582c17e473267b0124ac09a79c0cb9bc9fa9f97a
3,616,085
import numbers def mlevel(level): """Convert level name/int to log level. Borrowed from celery, with <3""" if level and not isinstance(level, numbers.Integral): return LOG_LEVELS[level.upper()] return level
143f5f4610034d372a55a8a6c1a8c7f4e3ee6a0e
3,616,087
from datetime import datetime from typing import Dict from typing import Any def get_legislation_introduced_since(since_date: datetime) -> Dict[str, Any]: """See: http://wslwebservices.leg.wa.gov/legislationservice.asmx?op=GetLegislationIntroducedSince""" argdict: Dict[str, Any] = dict(sinceDate=since_date) ...
1d6cb1d0eb1fa01c4305dca422b7fdb22ac18520
3,616,090
import io def extern(decorated): """ A decorator gadget that generates a Rust extern {} block Usage: properties.name = "my::rust::extern" @extern function(generator, outfile, ...): outfile.write("contents inside generated extern block") Generates: extern ...
d42470dd962c2b92e03b199872726b10b0a8f7d7
3,616,092
def make_exp_vocab(exp_dic): """ Returns a dictionary that maps words to indices. """ exp_vdict = {'<EOS>': 0} exp_vdict[''] = 1 exp_id = 2 for qid in exp_dic.keys(): exp_strings = exp_dic[qid] for exp_str in exp_strings: exp_list = ActivityDataProvider.seq_to_lis...
a496f4bf0e5ef2692f7f904e9dd4c905dc2e7826
3,616,093
def load_frames(folder_name, offset=0, desired_fps=3, max_frames=40): """ :param folder_name: Filename with a gif :param offset: How many frames into the gif we want to start at :param desired_fps: How many fps we'll sample from the image :return: [T, h, w, 3] GIF """ coll = ImageCollection(...
46c41f393cfc73581ef89ba0d4204f0a96a8b303
3,616,094
from typing import Tuple from typing import Union def _verify_data_shape(data, shape, path=None) -> Tuple[bool, Union[str, None]]: """ _verify_data_shape( {'data': []}, {'data': list} ) == (True, None) _verify_data_shape( {'data': ''}, {'data': list} ) == (False, '.data') ...
3e76362938146972d96e34a22373b43dca23381b
3,616,095
def MultipleComparisons(trends, kys, aplha = 0.10, MCmethod="fdr_by"): """ Takes the results of an existing trend detection aproach and modifies them to account for multiple comparisons. args trends: list list of numpy arrays containing results of trend analysis kys: list list of what is in results y...
9c4a74c9ffe319b3a4058a9252ff5f64de71d048
3,616,096
def view_questions_default_page(): """View all tests, for default test page""" questions = Question.select() return questions
8fdf5849bd9536d076f6ffc7f6aa9cc65eb61685
3,616,098
import random def chooseAxes(numBits): """Return Alice and Bob's randomly chosen mstment axes for the specified number of qubits in the E91 protocol: A chooses from (0, pi/4, pi/2) with equal probability, B chooses from (pi/4, pi/2, 3pi/4) with equal probability. """ choicesA ...
76ae98d9dd4d590d84e2194a3ae0c6bd91ae9838
3,616,100
import time def newCommentUri(secs=None): """this is essentially a bnode, but a real URI is easier to work with""" if secs is None: secs = time.time() return URIRef("http://bigasterisk.com/comment/%r" % secs)
00f384ec0c7fe2151ce7a112e9eefddefcfc5407
3,616,101
def non_max_suppression(dets, threshold): """执行non-maximum suppression并返回保留的boxes的索引. dets:(x1、y1、x2、y2,scores) threshold: Float型. 用于过滤IoU的阈值. """ x1 = dets[:, 0] y1 = dets[:, 1] x2 = dets[:, 2] y2 = dets[:, 3] scores = dets[:, 4] # 每一个检测框的面积 areas = (x2 - x1 + 1) * (y2 - y1...
fdd4917e85641def1b13d6764a3d880b271721a4
3,616,103
from windspharm.xarray import VectorWind def wind_rot_div(u, v, truncation=None, const=None): """Split the wind field into divergent and zonal mean and eddy rotational components.""" vec = VectorWind(u, v, rsphere=const.rplanet_m) div_cmpnt_u, div_cmpnt_v, rot_cmpnt_u, rot_cmpnt_v = vec.helmholtz(truncat...
a45ea9f5807d6756dd9b770d9e3e33bd8b03c0f5
3,616,105
def blank_image(width=1024, height=1024, background=BG_COLOR): """ It creates a blank image of the given background color """ img = np.full((height, width, MONOCHROME), background, np.uint8) return img
aa96b09e2233b8371321df3837278488399d9332
3,616,106
def pretrained_embedding_layer(word_to_vec_map, word_to_index): """ Creates a Keras Embedding() layer and loads in pre-trained GloVe 50-dimensional vectors. Arguments: word_to_vec_map -- dictionary mapping words to their GloVe vector representation. word_to_index -- dictionary mapping from words to...
ecc973587aaa08cbe5d5b10c582c38374b992de9
3,616,108
async def update_request(connection: Connection, old_key: str, new_key: str, json: str) -> int: """ returns amount of entries updated """ return await connection.execute( """ update requests.requests set id = :new_key, body = :json, ...
a67b31ed409be5cdd6269409e9d355c2d763bf80
3,616,110
from datetime import datetime def _prepare_transactions(response, telegram_id, mcc_codes): """Parse response from monobank API and return formatted transaction.""" transactions = [] costs_converter = 100.0 for transaction in response: transactions.append(( transaction["id"], ...
0794c0761e7232bf517dd867f4d8bab252b2c708
3,616,111
import torch def get_gaps(o : Tensor, forward : bool = True, backward : bool = True, nearest : bool = True, normalize : bool = True): """Number of sequence steps from previous, to next and/or to nearest real value along the last dimension of 3D arrays or tensors""" _gaps = [] if forward ...
d0b7938687433b2307fd121db07b9cdb09c1f07b
3,616,112
def DoubleCast(value): """Explicitly cast a value to type Double.""" if istype(value, Double): return value return UPlus(value)
bbef5bfc39c0be1a1ec7572f941596e513adbda9
3,616,113
def _find_datapoints(sheet, row, col): """Return start and stop points for adsorption and desorption.""" rowc = 1 # Check for adsorption branch if sheet.cell(row + rowc, col).value == 'ADS': ads_start_row = row + rowc + 1 ads_final_row = ads_start_row point = sheet.cell(ads_final_r...
38f0f0d9706c7ed7d3171e1b1c02161af618a4e0
3,616,115
from typing import Tuple from typing import List def _read_dvxrel2_flag(data: bytes, n0: int, i0: int, i1: int, size: int, ints: np.ndarray) -> Tuple[List[int], List[str]]: """reads the DVxREL2 flag table""" flag = ints[i0+10] #print(int...
2e8e6f58d01a3bfda7030186b392850fa3cb6c83
3,616,116
def patient_list(request): """Accepts a request to return a list of all patients from the backing data store. Used for synching the mobile client. Warning: This can return a significant amount of patient data. Request parameters: username a valid username password ...
b76ee242902f91e4f31c0a940196b5bf5ed298ca
3,616,118
def create_dict_playlists_playlistids(p_list, pid_list): """ Create a dictionary of playlists and playlist ids """ playlists_and_playlist_ids = {} for i in range(len(p_list)): playlists_and_playlist_ids[p_list[i]] = pid_list[i] return playlists_and_playlist_ids
173850ed85b3dc774ddea14674e22e701991c807
3,616,119
from datetime import datetime def create_bot(market, strategy, resolution, start, end, verbose, percent, automatic, btc): """Will create a new bot instance.""" bot = Cointrader(market=market, strategy=strategy, resolution=resolution, start=start, end=end, automatic=automatic, percent=perc...
82efbc617094ab07b5d9f151e1c63dec12b1a404
3,616,120
def money_manager(manager): """ Patches a model manager's get_queryset method so that each QuerySet it returns is able to work on money fields. This allow users of django-money to use other managers while still doing money queries. """ # Need to dynamically subclass to add our behaviour, an...
e73b4d2a513f836c333a673e499f9cf3daacc8ce
3,616,122
def get_address():# check_author=True): """Get a address and user by id. Checks that the id exists and optionally that the current user is the author. :param id: id of address to get :return: the address :raise 404: if a address with the given id doesn't exist """ success = True uid...
44851e91940f4f190be4764bfcf84b713278e06b
3,616,123
def round(sdf: np.float, radius: np.float) -> np.float: """ Rounds a shape :param sdf: pre-calculated SDF :param radius: radius :return: SDF """ return sdf - radius
b440d3a9dbe5f78988605efb024af5c9e311150b
3,616,124