content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def index(current_user=None): """ Display home page """ return render_template('homepage.html', username=current_user['name'], \ logged_in=current_user['is_authenticated'], \ display_error=request.cookies.get('last_attempt_error') == 'True', \ login_banner=APP.config['LOGIN_BANNER'])
287d8101ef318cb7ca308340e0d11ab157538450
17,555
def disable_admin_access(session, return_type=None, **kwargs): """ Disable Admin acccess :type session: zadarapy.session.Session :param session: A valid zadarapy.session.Session object. Required. :type return_type: str :param return_type: If this is set to the string 'json', this function ...
5ac6c09ed3098f5b99baa2d5749d7b42a465e9f4
17,557
def _get_bbox_indices(x, y, bbox): """ Convert bbox values to array indices :param x, y: arrays with the X, Y coordinates :param bbox: minx, miny, maxx, maxy values :return: bbox converted to array indices """ minx, miny, maxx, maxy = bbox xindices, = np.where((x >= minx) & (x <= maxx))...
dd71f1852971dbd2d3026c1720f9f477b3093fc8
17,558
def skill_competencies(): """ Called by S3OptionsFilter to provide the competency options for a particular Skill Type """ table = s3db.hrm_skill ttable = s3db.hrm_skill_type rtable = s3db.hrm_competency_rating query = (table.id == request.args[0]) & \ (table.skil...
7edc87d20d36d25b05337365ed903126ef02742f
17,559
def calc_field_changes(element, np_id): """ Walk up the tree of geo-locations, finding the new parents These will be set onto all the museumobjects. """ fieldname = element._meta.concrete_model.museumobject_set.\ related.field.name field_changes = {} field_changes[fieldname] = e...
cba816488dcf10a774bc18b1b3f6498e1d8dc3d8
17,560
def index(request, _): """ 路由请求 `` request `` 请求对象 """ if request.method == 'GET' or request.method == 'get': return index_page(request) elif request.method == 'POST' or request.method == 'post': return send_wxmsg(request) else: rsp = JsonResponse({'code': -1, 'erro...
5006cf1e5cb23e49b17e9083fca66c7731f5559b
17,561
def get_daisy_client(): """Get Daisy client instance.""" endpoint = conf.get('discoverd', 'daisy_url') return daisy_client.Client(version=1, endpoint=endpoint)
6ed0df1259672becfca3197f2d115a1c789306a1
17,562
from pathlib import Path import multiprocessing def intermediate_statistics( scores, ground_truth, audio_durations, *, segment_length=1., time_decimals=6, num_jobs=1, ): """ Args: scores (dict, str, pathlib.Path): dict of SED score DataFrames (cf. sed_scores_eval.utils.sco...
5039bec8ceafed7952833aa2f39c5d44d0909790
17,563
def vnorm(v1): """vnorm(ConstSpiceDouble [3] v1) -> SpiceDouble""" return _cspyce0.vnorm(v1)
00016eaa6a765f564ce247c4126c4a360aa2b60d
17,564
def mean_iou(y_true, y_pred): """F2 loss""" prec = [] for t in np.arange(0.5, 1.0, 0.05): y_pred_ = tf.to_int32(y_pred > t) score, up_opt = tf.metrics.mean_iou(y_true, y_pred_, 2) K.get_session().run(tf.local_variables_initializer()) with tf.control_dependencies([up_opt]): ...
a2503703bae7c8c83b42ac93406178bc4c52a675
17,565
def _encode_string_parts(value, encodings): """Convert a unicode string into a byte string using the given list of encodings. This is invoked if `encode_string` failed to encode `value` with a single encoding. We try instead to use different encodings for different parts of the string, using the enc...
58f514ed7cbd9a6e2c10e6d8b22f32a32d71d6a7
17,566
def SocketHandler(qt): """ `SocketHandler` wraps a websocket connection. HTTP GET /ws """ class _handler(websocket.WebSocketHandler): def check_origin(self, origin): return True def open(self): qt.log("new socket open ...") qt.register_socket(self...
001f9dbee77560d4d5970fce731084b5a9cca7af
17,568
def extract_flow_global_roi(flow_x, flow_y, box): """ create global roi cropped flow image (for numpy image) image: numpy array image box: list of [xmin, ymin, xmax, ymax] """ flow_x_roi = extract_global_roi(flow_x, box) flow_y_roi = extract_global_roi(flow_y, box) if flo...
1b6d22d413693e978dc31cfbf1708c93d9256cf1
17,570
from unittest.mock import patch def patch_shell(response=None, error=False): """Mock the `AdbDeviceTcpFake.shell` and `DeviceFake.shell` methods.""" def shell_success(self, cmd): """Mock the `AdbDeviceTcpFake.shell` and `DeviceFake.shell` methods when they are successful.""" self.shell_cmd = ...
cdf4df2bb383c4c8b49b59442550e2c73ca828aa
17,571
def __setAdjacent_square__(self, pos): """ Sets all adjacencies in the map for a map with square tiles. """ self.__checkIndices__(pos) i, j = pos; adjacent = [] # Function to filter out nonexistent cells. def filterfn(p): do_not_filter = 0 <= p[0] < self.__numrows__ and 0 <= p[1] < s...
ebdd3ee3d0104b5bd26cc48e07760de027615263
17,572
def model_definition_nested_events(): """Test model for state- and parameter-dependent heavisides. ODEs ---- d/dt x_1: inflow_1 - decay_1 * x1 d/dt x_2: - decay_2 * x_2 Events: ------- event_1: trigger: x_1 > inflow_1 / decay_2 bolus: [[ 0], ...
f42a5c7c01fd6f966ecec11b28c9620022dd7aaf
17,573
async def address_balance_history( request: Request, address: Address, token_id: TokenID = Query(None, description="Optional token id"), timestamps: bool = Query( False, description="Include timestamps in addition to block heights" ), flat: bool | None = Query(True, description="Return d...
2fcae2ab775611e51fd056e98928afbcb6bf1278
17,574
def load(as_pandas=None): """ Loads the Grunfeld data and returns a Dataset class. Parameters ---------- as_pandas : bool Flag indicating whether to return pandas DataFrames and Series or numpy recarrays and arrays. If True, returns pandas. Returns ------- Dataset ...
183c37228619b835a36dc4a1cc1e1a7649fca6ec
17,575
def rule_if_system(system_rule, non_system_rule, context): """Helper function to pick a rule based on system-ness of context. This can be used (with functools.partial) to choose between two rule names, based on whether or not the context has system scope. Specifically if we will fail the parent of a ne...
2149c2ffdd6afdd64f7d33a2de4c6a23b3143dee
17,576
def find_inactive_ranges(note_sequence): """Returns ranges where no notes are active in the note_sequence.""" start_sequence = sorted( note_sequence.notes, key=lambda note: note.start_time, reverse=True) end_sequence = sorted( note_sequence.notes, key=lambda note: note.end_time, reverse=True) notes...
8db86584908283385958c5f710fb36d95795f7b1
17,577
def is_connected(G): """Returns True if the graph is connected, False otherwise. Parameters ---------- G : NetworkX Graph An undirected graph. Returns ------- connected : bool True if the graph is connected, false otherwise. Raises ------ NetworkXNotImplemented: ...
03a2602629db60565702bee044a1d70ba026a8aa
17,578
import math def show_result(img, result, skeleton=None, kpt_score_thr=0.3, bbox_color=None, pose_kpt_color=None, pose_limb_color=None, radius=4, thickness=1, font_scale=0.5, ...
af90da2b30ff9891613654d70724162ce7b4d702
17,579
def D2(X, Y, Y2=None, YT=None): """ Calculate the pointwise (squared) distance. Arguments: X: of shape (n_sample, n_feature). Y: of shape (n_center, n_feature). Y2: of shape (1, n_center). YT: of shape (n_feature, n_center). Returns: pointwise distances (n_sample, n...
daa8940e939eb2806e043f9b4521bf8cd1aefd2e
17,580
from typing import Dict from typing import Any from typing import cast def spec_from_json_dict( json_dict: Dict[str, Any] ) -> FieldSpec: """ Turns a dictionary into the appropriate FieldSpec object. :param dict json_dict: A dictionary with properties. :raises InvalidSchemaError: ...
9bf557364a7a17cea0c84c65ece5b1d0e3983b2f
17,582
import scipy def hyp_pfq(A, B, x, out=None, n=0): """ This function is decorated weirdly because its extra params are lists. """ out = np_hyp_pfq([a+n for a in A], [b+n for b in B], x, out) with np.errstate(invalid='ignore'): out *= np.prod([scipy.special.poch(a, n) for a in A]) ou...
f1d9e0454fa63d24b1a8a403bbae12e00b818bb2
17,583
from typing import Optional from datetime import datetime def create_new_token( data: dict, expires_delta: Optional[timedelta] = None, page_only: bool = False): """Creates a token with the given permission and expiry""" to_encode = data.copy() if page_only: expires = dateti...
3a0a2aebc6b814850333a5d4f5db72b1396cf208
17,584
from pathlib import Path from typing import Union import re def parse_json_year_date(year: Number, fullpath: Path) -> Union[Path, None]: """ Filtra os arquivos json por ano. """ if not isinstance(fullpath, Path): raise TypeError("O parâmetro path deve do tipo Path.") pattern_finder = re.se...
1d482bf916c3574225fdc31e700fb570c47555b1
17,585
from malaya_speech.utils import describe_availability def available_fastspeech2(): """ List available FastSpeech2, Text to Mel models. """ return describe_availability( _fastspeech2_availability, text = '`husein` and `haqkiem` combined loss from training set', )
b7fa7f6132eb478cf27068a4377688f8b3ec5c7b
17,586
def solve(A, b, method='gauss', verbose=0, eps=1e-6, max_itration_times=100000, omega=1.9375): """ Solve equations in specified method. :param A: coefficient matrix of the equations :param b: vector :param method: the way to solve equations :param verbose: whether show the running information ...
50c7cdc5a2c8b146a062c028c4cb684c0b7efc2f
17,587
def returns_unknown(): """Tuples are a not-supported type.""" return 1, 2, 3
9fc003c890b4e053362c684b1a5f0dfca59bbe42
17,588
def get_user( cmd, app_id: str, token: str, assignee: str, api_version: str, central_dns_suffix=CENTRAL_ENDPOINT, ) -> User: """ Get information for the specified user. Args: cmd: command passed into az app_id: name of app (used for forming request URL) token...
cc387259c97ebfecadd5d82dc6acf8f970d19478
17,589
def get(fg, bg=None, attribute = 0): """ Return string with ANSI escape code for set text colors fg: html code or color index for text color attribute: use Attribute class variables """ if type(fg) is str: bg = bg if bg else "#000000" return by_hex(fg, bg, attribute=attribute) ...
16ee7ea3bd5c66c415a6466632cee1c5b337696b
17,591
def get_Qi(Q,i,const_ij,m): """ Aim: ---- Equalising two polynomials where one is obtained by a SOS decomposition in the canonical basis and the other one is expressed in the Laguerre basis. Parameters ---------- Q : matrix for the SOS decomposition i : integer ...
a54313c8763777840c4a018dedb2fe6363e09d55
17,592
def strToBool(s): """ Converts string s to a boolean """ assert type(s) == str or type(s) == unicode b_dict = {'true': True, 'false': False, 'yes': True, 'no': False} return b_dict[s.lower()]
84e59429523e6e59a90739b0f1b160fa9e84bdc8
17,594
import json def publish_to_sns(topic_name, message, region=None): """ Post a message to an SNS topic """ AWS = AWSCachedClient(region) # cached client object partition = None if region: partition = partition_from_region(region) else: partition = 'aws' region = 'us...
5a3c35c0367873e2c0b3c79a176b7c384d2b74ed
17,595
from typing import List from typing import Tuple def get_subset( classes: List, train_data, train_labels, val_data, val_labels, test_data, test_labels, ) -> Tuple: """ creates a binary subset of training, validation, and testing set using the specified list of classes to select ...
8857b7f5c4563692b3236b68889201bd3a28507e
17,597
def to_xyzw(matrix): """Convenience/readibility function to bring spatial (trailing) axis to start. Args: matrix (...x4 array): Input matrix. Returns: 4x... array """ return np.rollaxis(matrix, -1)
7c74b9bd6dc271db4a5dd925bbcfec4eef7ca791
17,598
import numpy def do_3d_pooling(feature_matrix, stride_length_px=2, pooling_type_string=MAX_POOLING_TYPE_STRING): """Pools 3-D feature maps. :param feature_matrix: Input feature maps (numpy array). Dimensions must be M x N x H x C or 1 x M x N x H x C. :param stride_length_px: S...
180ceae7364dcd1dd55d23a00389d0c3bb43cc38
17,599
def sin_wave(freq, duration=1, offset=0): """Makes a sine wave with the given parameters. freq: float cycles per second duration: float seconds offset: float radians returns: Wave """ signal = SinSignal(freq, offset=offset) wave = signal.make_wave(duration) return wave
f0f0e58d0a864a114aafa24f68b683ac4ec2f419
17,601
def assign_lpvs(lat): """ Given lattice type return 3 lattice primitive vectors""" lpv = zeros((3,3)) if lat=='FCC': lpv[0,1]=1./sqrt(2) lpv[0,2]=1./sqrt(2) lpv[1,0]=1./sqrt(2) lpv[1,2]=1./sqrt(2) lpv[2,0]=1./sqrt(2) lpv[2,1]=1./sqrt(2) elif lat=='SC': ...
ecf599a661446e19e4155f170c41b5ac8271c8cb
17,602
import torch def flatten_and_batch_shift_indices(indices: torch.LongTensor, sequence_length: int) -> torch.Tensor: """``indices`` of size ``(batch_size, d_1, ..., d_n)`` indexes into dimension 2 of a target tensor, which has size ``(batch_size, sequence_length, embedding_si...
6b283f3baaa4fde17af194f996b7f2dec409fc0b
17,603
def raveled_affinity_watershed( image_raveled, marker_coords, offsets, mask, output ): """Compute affinity watershed on raveled arrays. Parameters ---------- image_raveled : 2D array of float(32), shape (npixels, ndim) The z, y, and x affinities around each pixel. marker_coo...
bc109b59bec4389a851cfc46a8e02648e1809c60
17,604
def get_spike_times(units: pynwb.misc.Units, index, in_interval): """Use bisect methods to efficiently retrieve spikes from a given unit in a given interval Parameters ---------- units: pynwb.misc.Units index: int in_interval: start and stop times Returns ------- """ st = unit...
c121747deec1fcc9b5e317f6ec5e57349604ebc3
17,605
def _make_hours(store_hours): """Store hours is a dictionary that maps a DOW to different open/close times Since it's easy to represent disjoing hours, we'll do this by default Such as, if a store is open from 11am-2pm and then 5pm-10pm We'll slice the times in to a list of floats representing 30 minut...
4845594e59e5dba2790ac1a3c376ddb8e8290995
17,606
def mul_time(t1, factor): """Get the product of the original Time and the number time: Time factor: number returns: Time """ assert valid_time(t1) secods = time_to_int(t1) * factor return int_to_time(secods)
43d9c3a52670b8755590693fe6886748665d81ee
17,607
def create_pmf_from_samples( t_samples_list, t_trunc=None, bin_width=None, num_bins=None): """ Compute the probability distribution of the waiting time from the sampled data. Parameters ---------- t_samples_list : array-like 1-D Samples of the waiting time. t_trunc: int ...
ce14c169ee719979284b01584b7e0523b19f256a
17,608
def box_corner_to_center(boxes): """从(左上,右下)转换到(中间,宽度,高度)""" x1, y1, x2, y2 = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3] cx = (x1 + x2) / 2 cy = (y1 + y2) / 2 w = x2 - x1 h = y2 - y1 boxes = paddle.stack((cx, cy, w, h), axis=-1) return boxes
c07ef637576e5b9ebd8ba43795535e630ccf8b09
17,609
def irrelevant(condition=None, library=None, weblog_variant=None, reason=None): """ decorator, allow to mark a test function/class as not relevant """ skip = _should_skip(library=library, weblog_variant=weblog_variant, condition=condition) def decorator(function_or_class): if not skip: ...
7d2633247569c4ca5bc20d5249e0b49991ae1047
17,610
def get_all_approved(self) -> list: """Get all appliances currently approved .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - appliance - GET - /appliance/approved :return: Returns approved appliances :rtype: l...
4c8c00cce144cf73b2a7b63d1e82a13f28de383c
17,611
def bokeh_hover_tooltip( label=False, text=False, image=False, audio=False, coords=True, index=True, custom=None, ): """ ???+ note "Create a Bokeh hover tooltip from a template." - param label: whether to expect and show a "label" field. - param text: whether to expe...
198e76e29d62c12c891c0fe51e947d16f39d65bb
17,613
import math def constant_xavier_initializer(shape, dtype=tf.float32, uniform=True): """Initializer function.""" if not dtype.is_floating: raise TypeError('Cannot create initializer for non-floating point type.') # Estimating fan_in and fan_out is not possible to do perfectly, but we try. # This ...
f11403932f04327b77f38930a8a7a235633449da
17,614
from typing import Dict from typing import Tuple from typing import Any def upload_script(name: str, permission_type: str, content: str, entry_id: str) -> Dict: """ Uploads a script by either given content or file :param name: Script name to upload :param permission_type: Permissions type ...
d33aa3a4f19cfac08d8ee5cb559c0088c6f577bb
17,615
def create_orthogonal(left, right, bottom, top, znear, zfar): """Create a Mat4 orthographic projection matrix.""" width = right - left height = top - bottom depth = zfar - znear sx = 2.0 / width sy = 2.0 / height sz = 2.0 / -depth tx = -(right + left) / width ty = -(top + bottom) /...
3f10bcabe0d95a9832956a7edcef1719c7db0d15
17,616
def update_image_version(name: str, new_version: str): """returns the passed image name modified with the specified version""" parts = name.rsplit(':', 1) return f'{parts[0]}:{new_version}'
cde798361a6c74d22f979fe013e963c46028a7e6
17,617
def compute_entanglement(theta): """Computes the second Renyi entropy of circuits with and without a tardigrade present. Args: - theta (float): the angle that defines the state psi_ABT Returns: - (float): The entanglement entropy of qubit B with no tardigrade initially present ...
bc6d70f1ef76666fa3b4d753f13dc04a8a368374
17,618
import logging def parse_CDS_info(CDS_info): """ Args: CDS_info (python d): 'aliases' (list<alias_list (multiple)>): alias_list list<'locus_tag', str> AND/OR list<'old_locus_tag', str> AND/OR list<'protein_id', st...
d55e5b2c56b42c89c9abeba63cb7c68213688945
17,619
import re def recover_original_schema_name(sql: str, schema_name: str) -> str: """Postgres truncates identifiers to 63 characters at parse time and, as pglast uses bits of PG to parse queries, image names like noaa/climate:64_chars_of_hash get truncated which can cause ambiguities and issues in provenance...
041c747e8722dc1e81a94b29b76ee0eded88992c
17,620
def on_method_not_allowed(error): """Override the HTML 405 default.""" content = {"msg": "Method not allowed"} return jsonify(content), 405
a174592834952beca21c683890ab94c9583544f9
17,621
def dir_name(dir_path): """ 转换零时文件夹、输入文件夹路径 :param dir_path: 主目录路径 :return:[tmp_dir, input_dir, res_dir] """ tmp_dir = dir_path + "tmp\\" input_dir = dir_path + "input\\" res_dir = dir_path + "result\\" return tmp_dir, input_dir, res_dir
9f775b4ace14b178fd7bc0dfa94e5df13e583557
17,622
def profile_binning( r, z, bins, z_name="pm", z_clip=None, z_quantile=None, return_bin=True, plot=True, ): """Bin the given quantity z in r. Parameters ---------- r: 1d array, binned x values z: 1d array, binned y values bins: 1d array, bins Returns ...
f040fe7c7505e628978faf733a91578cb1a04709
17,623
def sequence_to_synergy_sims(inputs, params): """same as sequence to synergy, but prep some other tensors first """ # set up orig seq tensor inputs[DataKeys.ORIG_SEQ] = inputs[DataKeys.FEATURES] # set up thresholds tensor num_interpretation_tasks = len(params["importance_task_indices"]) ...
6abb659be6d1977e7d8a3c7b47f2f60997faf951
17,624
def _gen_roi_func_constant(constant_roi): """ Return a RoI function which returns a constant radius. See :py:func:`map_to_grid` for a description of the parameters. """ def roi(zg, yg, xg): """ constant radius of influence function. """ return constant_roi return roi
c7c69cf32fb289d5e9c9497474989aa873a231ba
17,626
def less_important_function(num: int) -> str: """ Example which is documented in the module documentation but not highlighted on the main page. :param num: A thing to pass :return: A return value """ return f'{num}'
d6ba0644fc8f4582fb63ceb722b05e824d63312a
17,627
def weth_asset_data(): # pylint: disable=redefined-outer-name """Get 0x asset data for Wrapped Ether (WETH) token.""" return asset_data_utils.encode_erc20( NETWORK_TO_ADDRESSES[NetworkId.GANACHE].ether_token )
0341c1f5c46e05a316c99154be82399145ae9d1a
17,628
def match_known_module_name(pattern): """ Matching with know module name. Args: pattern (Pattern): To be replaced pattern. Returns: str, matched module name, return None if not matched. """ matched_result = [] for ptn, module_name in BUILT_IN_MODULE_NAME.items(): if...
0d76e22517d4fc435101702591e095a96cc5faf7
17,629
def _get_jones_types(name, numba_ndarray_type, corr_1_dims, corr_2_dims): """ Determine which of the following three cases are valid: 1. The array is not present (None) and therefore no Jones Matrices 2. single (1,) or (2,) dual correlation 3. (2, 2) full correlation Parameters ---------- ...
8a9d6f3441c488e2bf1059dd6fcb506a2285d291
17,630
def editing_passport_serial_handler(update: Update, context: CallbackContext) -> int: """Get and save passport serial.""" new_state = editing_pd(update, context, validator=validators.passport_serial_validator, attribute='p...
81c86bffa07376f17dd2c013f5eab42856fa4cea
17,631
import requests def get_overview(ticker: str) -> pd.DataFrame: """Get alpha vantage company overview Parameters ---------- ticker : str Stock ticker Returns ------- pd.DataFrame Dataframe of fundamentals """ # Request OVERVIEW data from Alpha Vantage API s_req...
ddc87f05c8e67f84f2327cf0f06aded0e31e5e8c
17,632
def effective_sample_size(samples): """ Calculates ESS for a matrix of samples. """ try: n_samples, n_params = samples.shape except (ValueError, IndexError): raise ValueError('Samples must be given as a 2d array.') if n_samples < 2: raise ValueError('At least two samples ...
7a31d4a2c2bee133ab264dc793f16d0d6bd866f2
17,633
def get_credentials(credentials_path): """ Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid it returns None. Returns: Credentials, the obtained credential or None """ store = Storage(credentials_path) credentials = s...
b6a6fcd20f8def88c554d276e8f07aae3dc1f536
17,634
def setup(hass, config): """Set up this component.""" conf_track = config[DOMAIN][CONF_TRACK] _LOGGER.info('version %s is starting, if you have ANY issues with this, please report' ' them here: https://github.com/custom-components/custom_updater', __version__) ha_conf_dir = str(hass.co...
d0a18b4c2c3e2c94f19afb66e2e9d2a3d18fea07
17,635
def get_model(**kwargs): """ Returns the model. """ model = ShuffleNetV2(**kwargs) return model
6b226b56fe603a0b703267bc35e2b92f2c6dda7c
17,637
import torch def absolute_filter_change(baseline_state_dict, target_state_dict): """ Calculate sum(abs(K2 - K1) / sum(K1)) Args: baseline_state_dict (dict): state_dict of ori_net target_state_dict (dict): state_dict of finetune_net Returns: sorted_diff (list): sorted values ...
ad4616a03ef80f5a5430a87fd07d70d6bb10f7b7
17,638
import torch def load_checkpoints(checkpoint_name): """ Load a pretrained checkpoint. :param checkpoint_name: checkpoint filename :return: model.state_dict, source_vocabulary, target_vocabulary, """ # Get checkpoint from file checkpoint = torch.load(checkpoint_name, map_location=torch.dev...
e81f094c811d497504fd1f93a8ee537e6b122bd6
17,640
def _extract_data(prices, n_markets): """ Extract the open, close, high and low prices from the price matrix. """ os = prices[:, :, :n_markets] cs = prices[:, :, n_markets:2*n_markets] hs = prices[:, :, 2*n_markets:3*n_markets] ls = prices[:, :, 3*n_markets:4*n_markets] return os, cs, hs, ls
154af0c8270fbe664b3dd5d07a724b753ff02040
17,641
def make_screen(): """creates the code for a new screen""" return pygame.display.set_mode((800,600))
ca0e23f5583e652207f0297e7363dacaa5a7f085
17,642
def flip_vert(r, c, row, col, reversed): """1번 연산""" if reversed: row, col = col, row return row - 1 - r, c, reversed
053f6a354e5f6387a528af4ce07290cba370830c
17,644
def get_orders(self, **kwargs): """ | | **Current All Open Orders (USER_DATA)** | *Get all open orders on a symbol. Careful when accessing this with no symbol.* | *If the symbol is not sent, orders for all symbols will be returned in an array.* :API endpoint: ``GET /dapi/v1/openOrders`` :AP...
0561fdeb4863ea08b1644a7695ca7f4ed0622fd9
17,645
def en_13757(data: bytes) -> int: """ Compute a CRC-16 checksum of data with the en_13757 algorithm. :param bytes data: The data to be computed :return: The checksum :rtype: int :raises TypeError: if the data is not a bytes-like object """ _ensure_bytes(data) return _crc_16_en_13757...
85a7793f475f04cca2d7dcf92eeba523fde9b1c2
17,647
def get_agent_supported_features_list_for_extensions(): """ List of features that the GuestAgent currently supports (like Extension Telemetry Pipeline, etc) needed by Extensions. We need to send this list as environment variables when calling extension commands to inform Extensions of all the features t...
8a453286c433b3ecaed2fc402c5d557b335f3935
17,648
def GCMV(image, mask=None): """ :param image: input image, color (3 channels) or gray (1 channel); :param mask: calc gamma value in the mask area, default is the whole image; :return: gamma, and output """ # Step 1. Check the inputs: image if np.ndim(image) == 3 and image.shape[-1] == 3: ...
47070fdda8dcb2507fefd6a5aa922d21481c0896
17,649
from typing import Union def downloadStaffFile(request: HttpRequest, filename: str) -> Union[HttpResponse, FileResponse]: """Serves the specified 'filename' validating the user is logged in and a staff user""" return _downloadFileFromStorage(storages.StaffStorage(), filename)
0e0137f5b5e4140c2d9ff300ed97b7a3e3c37602
17,650
def get_view_renderer_type(*args): """ get_view_renderer_type(v) -> tcc_renderer_type_t Get the type of renderer currently in use in the given view ( 'ui_get_renderer_type' ) @param v (C++: TWidget *) """ return _ida_kernwin.get_view_renderer_type(*args)
e35269d7b77196ebd8ea325db3d6301ffdb63908
17,651
async def create(req): """ Add a new label to the labels database. """ data = req["data"] async with AsyncSession(req.app["pg"]) as session: label = Label( name=data["name"], color=data["color"], description=data["description"] ) session.add(label) try:...
1d7de257f0a3bc1259168821e1fcd6358d4c31c6
17,652
def process_radial_velocity(procstatus, dscfg, radar_list=None): """ Estimates the radial velocity respect to the radar from the wind velocity Parameters ---------- procstatus : int Processing status: 0 initializing, 1 processing volume, 2 post-processing dscfg : dictionary of d...
2114cf4f5524662f80cac69dab45a00729053192
17,653
def brute_force_diagonalize(answers, wordlist=WORDS, quiet=False): """ Find the most cromulent diagonalization for a set of answers, trying all possible orders. See README.md for a cool example of this with 10 answers. As a somewhat artificial example, let's suppose we have these seven answers from...
25725e34dc328cc605cc5dc147547c84de803873
17,654
def train(): """ MNIST training set creator. It returns a reader creator, each sample in the reader is image pixels in [-1, 1] and label in [0, 9]. :return: Training reader creator :rtype: callable """ return reader_creator( paddle.dataset.common.download(TRAIN_IMAGE_URL, 'mnis...
b7008aa61ce49822838c4b30709537396a93f453
17,655
import base64 import hmac import hashlib def sign_v2(key, msg): """ AWS version 2 signing by sha1 hashing and base64 encode. """ return base64.b64encode(hmac.new(key, msg.encode("utf-8"), hashlib.sha1).digest())
1aa54cc2cd3ce20ad5222a889754efda2f4632c3
17,656
def graph_apply(fun, *args): """Currying wrapper around APP(-,-).""" result = fun for arg in args: arg = as_graph(arg) result = APP(result, arg) return result
709306884b37b41c9a7289ad6a372d2b43ede6a9
17,657
def find_hcf(a, b) : """ Finds the Highest Common Factor among two numbers """ #print('HCF : ', a, b) if b == 0 : return a return find_hcf(b, a%b)
818bbc05ab9262e8fd1e8975daf68ca3e0fa6a8b
17,658
def GAU_pdf(x: np.ndarray, mu: float, var: float) -> np.ndarray: """ Probability function of Guassian distribution :param x: ndarray input parameters :param mu: float mean of the distribution :param var: float variance of the distribution :return: ndarray probability of each sample """ k...
9810da4a05d86ac7895a2947a1890fe111faeae4
17,659
def version_compare(a, b): # real signature unknown; restored from __doc__ """ version_compare(a: str, b: str) -> int Compare the given versions; return a strictly negative value if 'a' is smaller than 'b', 0 if they are equal, and a strictly positive value if 'a' is larger than 'b'. """ ...
97b3fd3bbd542d776b75327c88f9e80d776ba248
17,660
def line_status(): """ 设备线路详情 :return: """ device_id = request.args.get("device_id") lines = Line.objects(device_id=device_id).all() result = Monitor.device_status(device_id, lines) result.pop(0) return Success(result)
47ca3cfef469c346ad85b701339941707e2084ea
17,661
def _hist_fig(df, pred, c): """ """ bins = np.linspace(0, 1, 15) unlabeled = pred[c][pd.isnull(df[c])].values fig, (ax1, ax2) = plt.subplots(2,1) # top plot: training data pos_labeled = pred[c][(df[c] == 1)&(df["validation"] == False)].values neg_labeled = pred[c][(df[c] =...
6836c0228f2db705642e5f5fa4da6d318674fd55
17,663
import requests def is_responsive(url, code=200): """Check if something responds to ``url`` syncronously""" try: response = requests.get(url) if response.status_code == code: return True except requests.exceptions.RequestException as _e: pass return False
1ed307d7be468157c880bf7e481f255bac449c34
17,664
def fit_and_report(model, X, y, X_valid, y_valid): """ It fits a model and returns train and validation scores. Parameters: model (sklearn classifier model): The sklearn model X (numpy.ndarray): The X part of the train set y (numpy.ndarray): The y part of the train set ...
f993a5410248e5303995f37b5464cb4a57928bcf
17,665
def move_all_generation_to_high_voltage(data): """Move all generation sources to the high voltage market. Uses the relative shares in the low voltage market, **ignoring transmission losses**. In theory, using the production volumes would be more correct, but these numbers are no longer updated since ecoinvent ...
ed9b1fcf60bb1b5645dbd6946fe2e98e6e73ccf3
17,666
from typing import Union def parser_first_text_or_content_if_could(html: etree._Element, query_path: str) -> Union[str, None]: """ 如果解析出的内容是一个数组,默认取的第一个 """ nodes = html.xpath(query_path) if not nodes: return None if len(nodes) > 0: de...
8410280ca71083986af0aa89a312d5082ff36d8d
17,667
def get_all_quantity(results, q_func=None): """ """ quantities = [] for res_name in results: if q_func is not None: # We change the quantity function results[res_name].q_func = q_func min_quantity = results[res_name].min_quantity quantities.append(min_quan...
56d50cacab2dcd7cb1554798a11bb1937436c73e
17,669
import random def generate_example_type_2a(problem, one_step_inferences): """Generates a type 2a training example. Args: problem: a lib.InferenceProblem instance. one_step_inferences: the list of one step inferences that can be reahced form the premises. Returns: An instance of "Example", or...
fafc05b70c7b2a84a2c1476e51fa783f240f2bd5
17,670