content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def pcmd(progressive, lr, fb, vv, va): """ Makes the drone move (translate/rotate). Parameters: progressive -- True: enable progressive commands, False: disable (i.e. enable hovering mode) lr -- left-right tilt: float [-1..1] negative: left, positive: right rb -- front-back tilt: float ...
4534ac48f00a39c944b1be01ea0818235aea2559
57,561
def model_with_multiple_training_tensors(): """ Return model with multiple batchnorms using different training tensors """ inputs = tf.keras.Input(shape=(32, 32, 3,)) # Should create a keras learning phase tensor x = tf.keras.layers.BatchNormalization(momentum=.3, epsilon=.65)(inputs) is_training =...
18d3bcf6d47d3f911a7d8568e705a2ca8ac8c610
57,562
def consume(generator): # pragma: no cover """ Helper function to consume a synchronous or asynchronous generator. Arguments: generator (generator|asyncgenerator): generator to consume. Returns: list """ # If synchronous generator, just consume and return as list if hasatt...
cba35032ee327a4feacb547d59de6c70d8b1bb74
57,563
def b2h(n): """Convert bytes int into human friendly string format. >>> b2h(10000) '9.8 KB' >>> b2h(100001221) '95.4 MB' """ t = "{0:.2f} {1}".format symbols = ("KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB") prefix = {s: 1 << (i + 1) * 10 for i, s in enumerate(symbols)} for s i...
6337fa1d1c7a2e324bcbe99eac28225551f84ef5
57,564
def modules_to_opt_conf(*modules,**opt_kwargs)->"a list of PyTorch optimizer config": """ put in a sequence of pytorch modules, return optimizer param groups of configs """ param_list = [] param_list_nd = [] no_decay = ["bias", "LayerNorm.weight"] for m in modules: for n,p in m...
721c92fd9749b678f03fe5910da8167faab930b7
57,565
from typing import List from typing import Tuple def get_residual_blocks_for_ferminet_backflow( spin_split: ParticleSplit, ndense_list: List[Tuple[int, ...]], kernel_initializer_unmixed: WeightInitializer, kernel_initializer_mixed: WeightInitializer, kernel_initializer_2e_1e_stream: WeightInitiali...
63ce43eacba2b8179efa046b6a963697acd2515b
57,567
def adjoin(space, *lists): """ Glues together two sets of strings using the amount of space requested. The idea is to prettify. """ outLines = [] newLists = [] lengths = [max(map(len, x)) + space for x in lists[:-1]] # not the last one lengths.append(max(map(len, lists[-1]))) m...
7eb2df83aed2c0b4f32926940bbb9f4d2b497832
57,568
def lambda_tokenize(string): """ Tokenizes a lambda-calculus statement into tokens. Inputs: string: a lambda-calculus string Outputs: a list of tokens. """ space_separated = string.split(" ") new_tokens = [] # Separate the string by spaces, then separate based on existence...
b704ad3361b1e188c1577b22b90545069199eda7
57,569
import requests def series_id(TVDB_id, JWT=None): """TV series data search of TheTVDB by TheTVDB series id. Arguments: TVDB_id: TheTVDB episode id to search. JWT: Java Web Token for authentication as a string, if None, will run authentication function. Returns: JSON ...
b0212564d06d9e2a7f4fb3057f7b2a81e24ef5d7
57,570
def delete_listas_cmd(listas_id): """ Construct a command to delete a listas :param listas_id: listas's id :return: Command """ return DeleteNode(listas_id)
2d5589fe9418703872f51edaea7cefaeb7f5dad1
57,571
import requests def GetUserStatus(accesskey): """ Queries keepa for available tokens """ url = 'https://api.keepa.com/token/?key={:s}'.format(accesskey) r = requests.get(url) status_code = r.status_code # Return parsed response if successful if status_code == 200: response = r.json(...
3f8c21cdb667b62755cede1ae2bfc66e84cea862
57,572
def aten_gather(mapper, graph, node): """ 构造gather激活的PaddleLayer。 TorchScript示例: %result.3 : Tensor = aten::gather(%input.5, %18, %19, %20, %21) 参数含义: %result.3 (Tensor): 输出,gather后的结果。 %result.5 (Tensor): 需要gather的Tensor。 %18 (int): 需要gather的维度。 %19 (Tensor): 需要...
de7d2205baa0714ab972da71c9db0ae48edfd1c3
57,574
import importlib def get_module(name: str): """Import a module dynamically.""" if name.lower() == "std": return std module = importlib.import_module(name) print(f"Loaded {module}") return module
2e3e5eb2245bd89a7c259a1069493ae6627e1a33
57,575
def html_to_text_h2t(html: str): """ 从html提取核心内容text :param html: :return: """ doc = Document(html) h = html2text.HTML2Text() h.ignore_links = True h.bypass_tables = False h.unicode_snob = False text = h.handle(doc.summary()) return text.strip()
b6c673f8670330987eba83359a0664b763c0dc1a
57,577
import numpy as np def f_calculate_thresholds(combined_uncertainties, phi=0.95): """ Calculates EDMF thresholds for provided target reliability of identification Developed by : Sai G.S. Pai (ETH Singapore) Contact : saiganesh89@gmail.com Date: June 30, 2020 INPUTS: ...
b82feca1823c2bd772f1f6ba06a6053f6d30ad15
57,578
import json def check_blacklist(method): """ API请求参数校验黑名单 """ def request_decorator(func): def func_wrapper(self, *args, **kwargs): self.set_header("content-type", "application/json") query = unquote(self.get_argument("query", "") ) if method...
168061508a4f56cf3e3e239f9aa012d2b12811b0
57,579
def MSB(num: int, size: int) -> int: """ Get the most significant bit of a `size`-byte number `num`. :param num: A number. :param size: The number of bytes in this number. :return: """ return (num >> (size * 8 - 1)) & 1
eff28af2e71234e6188cc27f2fea48a2496a43b4
57,580
def ismarkdown(file_path): """ Check if file at given path is a .md file by extension :param file_path: The path of the given file :return: True if ends with .md. Otherwise, return False """ return hasextension(file_path, ".md")
e3af6385e1758d9c0d098d48e5d19c2eb5563899
57,582
def addToSession(session, flaskform): """ Function used in the hiringmanger tab. It must keep backward compatibility with the fields named commentOne..., commentTwo..., commentThree..., commentFour... since the DB was built in this way at first. """ if 'evaluatorName' in flaskform: sessi...
8ecaf782373730efa6c251a4354de4355cf31884
57,583
def test_module(client: Client, *_) -> str: """Performs basic get request to get ip geo data. Args: client: Client object with request. Returns: string. """ client.ip_geo_get_request(ip_='1.1.1.1') return 'ok'
20ea497b8f57c59bc44637e9b3c243febe741497
57,585
import time def go_up(seconds): """Endpoint for the table to go up.""" seconds = int(seconds) GPIO.output(17, GPIO.HIGH) time.sleep(seconds) GPIO.output(17, GPIO.LOW) return '<a href="up/{0}">Go up {1} seconds again</a>'.format( seconds, seconds)
73242fdf9a710e728d5f904452a331d2c41891e1
57,586
from pathlib import Path def read_dlc(dlc_file, drop_first_column=False): """ Read DeepLabCut output, regardless of format :param dlc_file: DeepLabCut output file :param drop_first_column: Remove the first column with timepoint index :return: Dataframe of the DLC results """ file_type = P...
ed777b439c3811c17f551e9e0433ce934aa5494f
57,587
def dashboard(lti=lti, lti_exception=None): """ :type lti: controllers.pylti.flask.lTI """ force_default_assignment = maybe_bool(request.values.get('force_default_assignment', "false")) if 'user' not in g and not g.user: return "You are not logged in." course_id = get_course_id() use...
10c7059c4e1dffc78e7d4516939eae0af6fd601b
57,588
def check_legal_moves(board): """Return the legal moves on the board. """ return board[:, :, 0] == board[:, :, 1]
a8643c6cd06722b0110a09d8c12f34a20f03a31d
57,590
def wordnet_pos(tag: str) -> str: """Transform a `nltk` part-of-speech tag string to a `wordnet` part-of-speech tag string. Arguments: tag: An `nltk` part-of-speech tag string. Returns: The corresponding `wordnet` part-of-speech tag string. """ return getattr( ...
ca2f3f8032265e5c3c6fa0aebf63f06624812a0b
57,591
def enhance_fprint_1(matrix, block_size=10, alpha=0.7): """ Enhance image using locally calculating average and then thresholding against it. Block size determines the window for computing average Thresholding is done using computed mean times alpha assuming ridges are represented by high values...
09e428d538e4462d9d53c39109c95f297a84288b
57,593
import functools def loss_function_for_data(loss_function, X): """Get a loss function for a fixed dataset Parameters ---------- loss_function : function The loss function to use. The data parameter for the function must be `X` X : coo_matrix coo_matrix of data to apply lo...
2b45bdfd229fb79fd866dd67e9a6d8d44325a112
57,595
def remove_brew(): """Render the index page.""" args = request.get_json() if 'id' not in args: return jsonify({'success': False, 'error': 'ID not found in request!'}) c = mongo.db[app.config['BREWS_COLLECTION']] remove_id = paranoid_clean(args.get('id')) c.remove(...
8922483373056da58fe1c4ba46a4c982af5a88b7
57,597
from typing import List from typing import Tuple def plotlines( optical_start: List[float], ratio_wanted: List[float] ) -> Tuple[List[float], List[float], List[float]]: """Draws the 'Distance Lines' for the main plot. Takes inputs of desired optical and radio limits of where the distance lines should...
5c2b83b881c8b8101a5177709096c79dfce8c16c
57,598
def nl_cont_matrix(vf_f, vf_g, xx, n_extra_cols=0): """ 'Controllability' (or 'Reachability') matrix for the nonlinear system based on iterated lie bracketts. :param vf_f: drift vector filed ((n x 1) sympy-matrix) :param vf_g: input vector field ((n x 1) sympy-matrix) :pa...
da12ecba05d2b0149cecddcf9ef5542ff9a16904
57,599
def gen_verification_token(user): """Create JWT token that the user can use to verify its account.""" expiration_date = timezone.now() + timedelta(days=3) payload = { 'user': user.username, # UTC format 'exp': int(expiration_date.timestamp()), 'typ...
2d2c286b66b7ee1ad8a579c4c21c030501afbe1c
57,601
def FontMapper_GetSupportedEncodingsCount(*args): """FontMapper_GetSupportedEncodingsCount() -> size_t""" return _gdi_.FontMapper_GetSupportedEncodingsCount(*args)
68d3111e5d2787393720719ee70c3587d43f874b
57,602
def get_ramp_multiplier(ramp_option, T, wp_final_multiplier=1.0): """ Return a time-varying multiplier. Returns: A (T,) float vector containing weights for each time step. """ if ramp_option == RAMP_CONSTANT: wpm = np.ones(T) elif ramp_option == RAMP_LINEAR: wpm = (np.ara...
e200ed6a31c0758195b89c729fccb0cb0871ff56
57,603
from typing import Dict def true_best_objective( optimization_config: OptimizationConfig, true_values: Dict[str, np.ndarray] ) -> np.ndarray: """Compute the true best objective value found by each iteration. Args: optimization_config: Optimization config true_values: Dictionary from metri...
ba4f92c5acc02fc8530f84a097244aaae2faf5eb
57,604
def max_liquid_water_content(model): """ Calculate the maximum liquid water content of snow. The following options for calculating the maximum liquid water content are supported: - 'pore_volume_fraction': maximum LWC is set to a fraction of the snow pore volume following [1]. ...
14441e0fb6476f91160cf413510af925f28f3180
57,605
def get_equipment_config(oc_user,params): """获得装备配置 """ return 0, {'equipment_config':game_config.equipment_config}
79a37f365dd4c5bc7bd2c97424e79b4a628d33b9
57,608
import signal def butter_bandpass_filter(h, lowcut, highcut, fs, order): """ -> Esta função aplica um filtro digital linear duas vezes, uma para frente e outra para trás. O filtro combinado tem fase zero e um filtro solicita o dobro do original. A função fornece opções para lidar com as bordas do sin...
2a0b08a4f889f9576302dfc1afd9a46a6a4c251c
57,610
def deleteWatch(): """ Delete a movie to from watchlist """ filmId = request.form["delete"] record = Watchlist.query.filter_by(id=1) print(record.film_id) print(record.user_id) db.session.delete(record) db.session.commit() return redirect(url_for('home.watchlist'))
16f51ce2dd1652bd15f6c41b8adb2406e279f730
57,611
import random def ramb18(tile_name, luts, lines, sites): """ RAMB18E1 in either top or bottom site. """ params = {} params['tile'] = tile_name params['Y0_IN_USE'] = random.randint(0, 1) == 1 params['Y1_IN_USE'] = not params['Y0_IN_USE'] params['FIFO_Y0_IN_USE'] = False params['FIFO_Y1_IN_...
bddb777fe93fb27fd13fd781db38a8b007fc7528
57,612
from typing import Sequence from typing import Tuple def get_attestation_component_deltas(state: BeaconState, attestations: Sequence[PendingAttestation] ) -> Tuple[Sequence[Gwei], Sequence[Gwei]]: """ Helper with shared logic for use by...
0236e72808422c1de5df3a83c0a3ca7d064043f3
57,613
from functools import wraps import traceback def throws_synthesis_exception(fn): """ A decorator to automatically catch and format synthesis exceptions raised by synthesis functions. The decorator will call the given function and log simulator specific exceptions before throwing them to the caller. ...
b6be65d2369e37ddd06c0b63f77cd948bea17f57
57,614
def _put_key(pubkeyb64, eph_secret, file_key): """This method encrypts file key using X25519 and returns X25519 line argument list. Args: pubkeyb64: target base64url-encode X25519 public key. eph_secret: 32-bytes ephemeral secret. file_key: file key to encrypt using X25519. R...
4e3dbbd37f9d6f7de0a71301d400641603892386
57,616
def gen_fit_pars(**kwargs): """ Generate fit parameters. Every keyword will create a parameter, keywords ending with '_min' or '_max' will define the upper and lower bound for the parameter. Example ------- gen_fit_pars(D=1e-6, D_min=0, f_c=1000, f_c_max=1e6) will create OrderedDict([(...
0ad2c7ad8fa838f2a3164c47630524def52626c1
57,617
def get_unique_fields(fld_lists): """Get unique namedtuple fields, despite potential duplicates in lists of fields.""" flds = [] fld_set = set([f for flst in fld_lists for f in flst]) fld_seen = set() # Add unique fields to list of fields in order that they appear for fld_list in fld_lists: ...
0e131c5b3fe695670fafb51810c674e859c29b63
57,618
def tag_vm_to_resource_id(tag_id, vm_id): """Generate resource_id from tag_id/vm_id""" if not vm_id or not tag_id: raise cfy_exc.NonRecoverableError( "Please recheck tag_id/vm_id" ) return "%s|%s" % (tag_id, vm_id)
8bc1a638f423930a38baa0cccb1999557ba70e6c
57,619
def derive_url_dicts(url_obj_list): """Derive a list of url dicts from the obj list :param url_obj_list: List of URL objects :type url_obj_list: `list` :return: List of URL dicts :rtype: `list` """ dict_list = [] for url_obj in url_obj_list: dict_list.append(derive_url_dict(url_...
176c98559da69fd7465e687819346992ea93eaf7
57,620
def get_homology_mapping(homologene_file, tax_id="10090", from_tax_id="9606", symbol_type="geneid"): """ symbol_type: geneid | symbol """ geneid_to_geneid, group_to_taxid_to_geneid = parse_ncbi.get_homology_mapping(homologene_file, tax_id, from_tax_id=from_tax_id, symbol_type=symbol_type) return gen...
c1cd7a79656230b6da42a324fd81171c3aca6427
57,621
def cmp_func_different_hash(request): """Return a comparison function that checks whether two hashes are different.""" return request.param
5e917de2db60c03d17fc5536e5af48e0328423fc
57,622
def get_root_to_frame_info(frame_to_root_info, verbose): """returns a dictionary with per root the frame, path to root and length of the path""" root_to_frame_dict = defaultdict(list) for frame, info_list in frame_to_root_info.items(): for info_dict in info_list: root = info_dict['root'...
89c4459c269b3915a73182c00afe83ba1f03bfc3
57,624
import itertools def partition_probability(partition, A, beta=.1): """Gives partitions probabilities as exp(-beta*Ei) where Ei is the sum of binding energies of the components of the partition. Given a partition (list of mass fragments {A_j}), the sets of all possible species per mass {S^A_k} are...
df5c903d692b4241d6bde68df6a61b85d2433054
57,625
import logging def setup_console_logger(name, level=logging.INFO): """Setup a project wide logger singleton""" formatter = logging.Formatter(fmt='%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler = ColorizingStreamHandler() handler.setFormatter(formatter) handler.setLevel(level) ...
cbe0f16997f194fb02469028c4b194869ad07266
57,626
def rolling_std_nb(a: tp.Array2d, window: int, minp: tp.Optional[int] = None, ddof: int = 0) -> tp.Array2d: """2-dim version of `rolling_std_1d_nb`.""" out = np.empty_like(a, dtype=np.float_) for col in range(a.shape[1]): out[:, col] = rolling_std_1d_nb(a[:, col], window, minp=minp, ddof=ddof) r...
8525beb15647a85fe505e28efe61a05c226ad0d4
57,627
def winner(board): """This function accepts the Connect Four board as a parameter. If there is no winner, the function will return the empty string "". If the user has won, it will return 'X', and if the computer has won it will return 'O'.""" for row in range(7): count = 0 last = ''...
7c7983ec33cf6aca89283a2c09b9fabf2045f1b9
57,628
def main(input_dir, output_dir): """ Make interim PDB structures (from pdb/raw/) for final processing (saved in pdb/processed/). """ config = utils.read_config() pdb_code = config['pdb']['id'] # Data import pdb_struct = load_structure(pdb_code, input_dir, file_extension="pdb1") ...
61be0b1d9d143296ae9e4b752bf0866b82398e39
57,629
import torch def picp(target, predictions:list, total = True): """ Calculate PICP (prediction interval coverage probability) or simply the % of true values in the predicted intervals Parameters ---------- target : torch.Tensor true values of the target variable predictions : list ...
ef075b4cf3904a5f854ab4db3ecfbc6ba66ad674
57,630
import math def diameter(freq): """Calculates a node diameter based on the frequency of its word.""" return STYLES['node']['diameter'] * math.sqrt(freq)
9fc992ef3718fa9c741a2346b13f32ca7e083971
57,631
def get_next_click_pos(): """ Gets the x, y coordinates of the next left-click. Returns: (int, int) - the x and y coordinates. """ while win32api.GetKeyState(0x01) > -127: sleep(0.001) print("GOT") pos = win32api.GetCursorPos() while win32api.GetKeyState(0x01) <= -127: ...
82975a1e696f944cf02a3f87c4b0bee903400935
57,632
def licence(request): """ 授权信息 :param request: :return: """ licence_file = '/usr/local/u-mail/data/www/webmail/licence.dat' if request.method == "POST": f = request.FILES.get('licence_file', '') if not f: messages.add_message(request, messages.ERROR, u'请选择授权文件导入'...
039ba06be30e5e76d2ecfc51a9d34fd6cf603676
57,633
import random import hashlib def generate_token(): """Generates a token with randomly salted SHA1. Returns a string. """ _MAX_CSRF_KEY = long(2 << 63) salt = str(random.randrange(0, _MAX_CSRF_KEY)).encode('utf-8') return hashlib.sha1(salt).hexdigest()
6424bd6f8b2f7d8f7233cb878d01f6e96ac98c9c
57,634
def get_solver(solver='default', loss='lin_reg', penalty=None, constraint=None, lla=False): """ Returns a GlmSolver object. Parameters ---------- solver: str, GlmSolver The solver we want. If 'default', we will try to guess the best solver to use. loss: LossConfig ...
90f59aa1808155ba2e328d9bd0e1456c5db313d9
57,635
def entropy(y_true, y_pred): """SOM class distribution entropy measure. Parameters ---------- y_true : array, shape = [n] true labels. y_pred : array, shape = [n] predicted cluster ids. Returns ------- entropy : float (lower is better) References ---------- ...
988181d6e875c7139491377ab174f29f385c9be2
57,636
def _smooth_image_pair(con_img, vcon_img, sigma, method='default'): """ Smooth an input image and associated variance image using either the spatial uncertainty accounting method consistent with Keller et al's model, or the SPM approach. """ if method == 'default': smooth_fn = _smooth ...
f6c106db4ae6a2416c9e3d862d01c2e69b2a008a
57,637
def section(): """ RESTful CRUD controller - unused """ # Load Model #table = s3db.survey_section def prep(r): s3db.configure(r.tablename, deletable = False, orderby = "%s.posn" % r.tablename, ) re...
ce2313af3934c95942146fc3eceb0f6d0de24617
57,638
def getval(filename, key, *ext, **extkeys): """Get a keyword's value from a header in a FITS file. @type filename: string, file object, or file like object @param filename: name of the FITS file, or file object (if opened, mode must be one of the following rb, rb+,...
a112d24795aba4dbf2fbbbb1b672badfdd97751e
57,639
import io import yaml import hashlib def compute_parse_tree_hash(tree): """Given a parse tree, compute a consistent hash value for it.""" if tree: r = tree.as_record(code_only=True, show_raw=True) if r: r_io = io.StringIO() yaml.dump(r, r_io, sort_keys=False) ...
38f5af485d6f008d46b8b4165096f30e5b004d0b
57,640
def read_sql_table_from_connection(query, connection, selected_columns=None): """This function executes a SQL query in the given connection. Although you can specify the columns selected in the query, you can specify the columns needed in selected_columns. This will help to deal with different versions ...
290dd3c7a5a7d64704c908a11d0ffec7fb1c7e3b
57,641
import re def filterSetupJson(fd): """Filters out possible comments in setup JSON file""" return ''.join(list(filter(lambda line: re.search('^[ \t]*#',line) == None,fd.readlines())))
b05c0cb2e88c1192ed6dae19d47c112df91441d4
57,642
from typing import Tuple import datasets def load_regression_dataset( dataset_name: str) -> Tuple[testbed_base.Data, testbed_base.Data]: """Returns dataset data from dataset_name.""" if dataset_name not in datasets.REGRESSION_DATASETS: raise ValueError(f'dataset {dataset_name} is not supported yet.') x,...
c8b343f05f5b85e17165293a995875a5d2a83825
57,643
def calc_cost(y, x, theta_1, theta_0): """ y = theta_0 + theta_1 * x """ h = theta_1 * x + theta_0 d = h - y cost = np.dot(d.T, d) / (2*x.shape[0]) return cost.flat[0]
f0fe7472044fc1dd711e3e43e2d8d1755919f5bb
57,644
def split_matrix_1(input1): """ Split matrix. Args: inputs:tvm.Tensor of type float32 with shape [4608,4608]. Returns: result_2:tvm.Tensor of type float32 with shape [4,128,128]. """ result_2 = allocate((4, split_dim, split_dim), input1.dtype, 'local') for i in range(4): ...
39134ecf4cc12242a4ef868d8ce1b4b6896d92d9
57,646
from typing import Sequence def int_seq_to_layertypes(int_seq: Sequence[int]) -> Sequence[LayerTypes]: """ Convert an integer sequence to a sequence of layer types. Parameters ---------- int_seq An iterable of integers in the range [1, 4) Returns ------- type_seq A...
6ba257ee8f77cbc0581c401e1312eccad09e215b
57,647
def knot_vector_from_params(degree, params, periodic=False): """Computes a knot vector from parameters using the averaging method. Please refer to the Equation 9.8 on The NURBS Book (2nd Edition), pp.365 for details. Parameters ---------- degree : int The degree of the curve params...
059463258011eaa4f76dfd8c640b62aa663d8226
57,648
from typing import OrderedDict import json def _parse_register_dump(version: int, data: memoryview) -> str: """ Parser for the register dump. """ stream = DataStream(data, byte_order='big', is_signed=False) parser = ParserData() out = OrderedDict() # The register dump will just be a l...
74f60f9a65631a49f7823ca6c3a53d8336b103cf
57,650
from typing import List from typing import Callable def multiple_selection_with_duplicates(population: List[Individual], selection_size: int, selection_function: Callable[[List[Individual]], Individual] ...
6b66f106699e6c00aa08519d9ffc3b5a805dc35d
57,651
import re def time_to_frame(line: str, fps=24000 / 1001) -> int: """ Converts a timestamp in the format <hours>:<minutes>:<seconds>.<milliseconds> into the corresponding frame number. <hours> and <milliseconds> are optional, and milliseconds can have arbitrary precision (which means they are no longer...
0942ce5526592eeb8c6a858631382530ad2dccbd
57,652
import torch def get_test_dict(idx): """ Get FRCNN style dict """ num_objs = 0 boxes = torch.zeros((num_objs, 4), dtype=torch.float32) return {'boxes': boxes, 'labels': torch.ones((num_objs,), dtype=torch.int64), 'image_id': torch.tensor([idx]), 'area': (b...
bd7e37499c30b9bd23d9b99ed187795fb9e5e6e1
57,653
def effective_robustness_helper(robustness_result, task): """ Helper function that computes the effective robustness metric as the performance difference compared to late fusion method. :param robustness_result: Performance of the method on datasets applied with different level of noises. :param task: ...
d8ee94f6039b3f674048bcaaf7191ef5794e6252
57,654
def scan_vul_details(request): """ Get the Network scan vulnerability details. :param request: :return: """ if request.method == 'GET': scan_id = request.GET['scan_id'] if request.method == 'POST': vuln_id = request.POST.get('vuln_id') scan_id = request.POST.get('sca...
7ffb692798225a4a323d6f0697ed30c4ad569447
57,655
import numpy def mp3_singles2N(no, f, eri, D11, D12, D21, D22): """Return the doubly anomalous singles piece of the 3rd order correction to the free energy. """ nv = (1.0 - no) dA = (-1.0)*numpy.einsum( 'i,j,a,ai,ij,ja,ij,ja->', no, no, nv, f, f, f, D11, D12) dB = numpy.einsum(...
3333115b4dfc7d11e11ad50e05f106bde327484c
57,656
import logging import collections import operator def export_gmf(ekey, dstore): """ :param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object """ sitecol = dstore['sitecol'] oq = dstore['oqparam'] investigation_time = (None if oq.calculation_mode == 'scenari...
77db2bcc7f1b33612971d87b24353176caa3b9d5
57,658
import functools import inspect import copy import traceback from datetime import datetime def revert_to_error_rollback(function): """Decorator to revert task_state to error on failure.""" @functools.wraps(function) def decorated_function(self, context, *args, **kwargs): try: return ...
059ba9c19dbd05d3898d51638319861bedb0bfad
57,659
def remove_none_vals(dt): """remove None values in a dictionary""" return {k: v for k, v in dt.items() if not pd.isnull(v)}
3e6c9762ebdcf44f5cc468f440f571c427e63f25
57,660
from typing import List def checksum(rows: List[List[int]]) -> int: """ Solves the AOC second puzzle. """ check = 0 for row in rows: minimum = min(row) maximum = max(row) check += maximum - minimum return check
e95ff4418899d1f09671aac83feb4f5d35072808
57,661
import logging def novice_move(board): """Novice AI - lightly weighted towards a low scoring move. Args: board: (Board) The game board. Returns: Array: Our chosen move. """ valid_moves = _get_moves(board, Square.black) # Adjust Scores to prefer low point moves large = valid_moves[0][2] for ...
488954650485f8f76a389ec4cdc964c0b6854320
57,662
def avg_steps_by_zero_eaters(model): """Returns average number of steps of zero eaters.""" steps = [ a.done_steps for a in model.schedule.agents if isinstance(a, Creature) and a.eaten_candies == 0 ] if steps: return np.average(steps) else: return np.NaN
fe628177277a486f15d02bfd5c770c0f5fff819a
57,663
def ham_1d_bilinear_biquadratic(L=None, theta=0, *, S=1 / 2, cyclic=False, **local_ham_1d_opts): """ Hamiltonian of one-dimensional bilinear biquadratic chain in LocalHam1D form, see PhysRevB.93.184428. Parameters ---------- L : int The number of sites. t...
aa7f88fb05fa2188fc8c1597f7f19637d1175d13
57,664
def source_action(model_artifact_location, assets_bucket): """ source_action configures a codepipeline action with S3 as source :model_artifact_location: path to the model artifact in the S3 bucket: assets_bucket :assets_bucket: the bucket cdk object where pipeline assets are stored :return: codepi...
ca3dc8a88ee97784d0d118b3f5f0b18e9b6f254d
57,665
def file_order(entry): """ For a PlaylistEntry, return its original order in the Playlist. """ return entry['lineno']
8bbd6546e120cec018c0f7628fd1473ae5926dad
57,666
import json def create_diff_json(image_diff, file_output_name): """diff image file and save as file args: image_diff (object) file_output_name (str) returns: saved_file (str) """ diff_content = {} for attr in image_diff.attributes: diff_content[attr] = {} ...
0e5b506b7acbc15ca26f21640ee2748598858008
57,667
def build_hw_space(generator, constraints, method): """ Create hardware parameter search space. Parameters ---------- generator : generator Generator info. constraints : dict constraint dictionary. method : str Measure method. Ret...
6079229a06ecfc725bcc758005c4d8e8a7d8aa3c
57,668
import textwrap import asyncio async def drawtext(message): """ Generates an image with given text. Example:: /drawtext Hello there! """ def execute(): im = Image.new('RGB', (1, 1), (0, 0, 0, 0)) draw = ImageDraw.Draw(im) lines = textwrap.wrap(message.content, w...
4d83d4f2833e2d26389e5cc57cadca1a2b13ab7a
57,669
def kinetic(ax,ay,az,bx,by,bz,aa,bb,Ra,Rb): """ Compute kinetic integral between two Cartesian gaussian functions. INPUT: AX: Angular momentum lx for Gaussian 1 AY: Angular momentum ly for Gaussian 1 AZ: Angular momentum lz for Gaussian 1 AA: Exponential coefficient for Gaus...
54a0d4a923dab421c0c538ba1fed174e0d65d1a6
57,670
import requests import json def get_weather(coord_dict, token=None, test=True): """ Getting weather from Open Weather Map by coordinates (needs token). :param dict coord_dict: latitude & logitude. :param str token: token to Open Weather Map API. :param bool test: if test=True, returns sample weat...
2c6d51992dfea63d198575ef690324e1497e4eb8
57,671
def format_class_name(spider_name): """Format the spider name to A class name.""" return spider_name.capitalize() + 'Spider'
a477c02873347e8df975dade64b8c316ab8dfe67
57,672
def model_histories(request, *args, **kwargs): """ Looks at all the audit model histories and shows for a given model """ db = AccessAudit.get_db() vals = db.view('auditcare/model_actions_by_id', group=True, group_level=1).all() # do a dict comprehension here because we know all the keys in this...
5dab0e9e2e92dfca1a5c00d14e637bdb0775e526
57,674
def ordinal(value): """ Cardinal to ordinal conversion for the edition field """ try: digit = int(value) except: return value.split(' ')[0] if digit < 1: return digit if digit % 100 == 11 or digit % 100 == 12 or digit % 100 == 13: return value + 'th' elif digit ...
b97accfe96f214ffe9878c24bd78ab63083c9329
57,675
def mono_fp(unit_comb): """create bit mask image from wall/entrance/LDK/bedroom/balcony/bathroom stacked array""" # AREA_WALL = 64 # AREA_ENTRANCE = 32 # AREA_LDK = 16 # AREA_BEDROOM = 8 # AREA_BALCONY = 4 # AREA_BATHROOM = 2 mask_bits = np.array([64, 32, 16, 8, 4, 2], dtype=np.ui...
79c27a7b8f020e9ec21cae575b8edf7b158c6358
57,676
import torch def complex_abs(tensor): """Compute absolute value of complex image tensor Parameters ---------- tensor : torch.Tensor Tensor of shape (batch, 2, height, width) Returns ------- Tensor with magnitude image of shape (batch, 1, height, width) """ tensor = (tensor[:, 0] ** 2 + tensor[...
dd206d9fb58b819d5ed1c58af8e9fc559430ac3a
57,677
from typing import OrderedDict def create_column_index(annotations): """ Create a pd.MultiIndex using the column names and any categorical rows. Note that also non-main columns will be assigned a default category ''. """ _column_index = OrderedDict({'Column Name' : annotations['Column Name']}) ...
0174be1f2c747f362c6149d429683f9df2a390d1
57,678
def base_x(alphabet_id: int) -> BaseX: """ lazy initialization for BaseX instance >>> base_x(58).encode(b'the quick brown fox jumps over the lazy dog') '9aMVMYHHtr2a2wF61xEqKskeCwxniaf4m7FeCivEGBzLhSEwB6NEdfeySxW' >>> base_x(58).decode('9aMVMYHHtr2a2wF61xEqKskeCwxniaf4m7FeCivEGBzLhSEwB6NEdfeySxW') ...
d9a2a070c09964182312d7139b6368a7db8506b6
57,679