content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import functools import tqdm import time def extract_knn(data_shape, index_builder=AnnoyKnnMatrix.load, verbose=1, **kwargs): """Starts multiple processes to retrieve nearest neighbours from a built index in parallel. :param tuple data_shape: The shape of the data that the index was built on. :param inde...
ff2e15ed03a36b86baf1719c4ae79e3c764d785c
3,608,721
def adjust_scale_prediction(y_pred, cell_grid, ANCHORS): """ Adjust prediction == input == y_pred : takes any real values tensor of shape = (N batch, NGrid h, NGrid w, NAnchor, 4 + 1 + N class) ANCHORS : list containing width and height...
84bf66304bb05fa0ec85538fb37def319c4c0e9f
3,608,722
def getTweeningMethod(method): """Get the tweening method from a string, if the function doesn't exists None will be returned. :return: Tweening function :rtype: func/None """ _dict = getTweeningMethods() return _dict[method] or None
a312f0154c83ba32af1aa84d0bf80acc68dbfbd1
3,608,723
def mesh_offset(mesh, distance=1.0): """Offset a mesh. Parameters ---------- mesh : :class:`compas.datastructures.Mesh` A Mesh to offset. distance : float, optional The offset distance. Returns ------- :class:`compas.datastructures.Mesh` The offset mesh. No...
151c39c36c868f110d1a39b631d73c8d3ab042cf
3,608,725
def extract_java(fpath: str): """ Extract regexes from java file :param fpath: A path to a file :return: A list of FoundExpressions """ # find import statement f = open(fpath, "r") # get lines in file lines = f.readlines() expressions = [] # list of FoundExpressions im...
9f27b55ac541f1f14499d153f74f79acb5f9ef8a
3,608,726
import torch def _evaluate_iou(target, pred): """ Evaluate intersection over union (IOU) for target from dataset and output prediction from model """ if pred["boxes"].shape[0] == 0: # no box detected return torch.tensor(0.0, device=pred["boxes"].device) return box_iou(target["b...
8442abbb0442bb65f1a5fa38ddc1acc488e9d395
3,608,727
def partial_product_generation(bit_list, exp_prime): """Generate partial-products.""" pp_list = [] while bit_list: pp = PartialProduct(exp_prime) tmp_bit_list = [] for bit in bit_list: check = pp.add_bit(bit) if check is False: tmp_bit_list.app...
17f7077486839cb1ee74072c8b977d8d4d46b408
3,608,728
import concurrent def validate_keys_multi( w3, operators: t.List[t.Dict], lido_address: str, lido_abi_path: str, ) -> t.List[t.Dict]: """ Main multi-process validation function. Modifies the input! Adds "valid_signature" field to every key item. It will spawn an appropriate process poo...
e0cf457ad3d70b36c584ff63d55a9e56217b2d92
3,608,730
def paginationpageurl(context, page, url_name, page_id, qs): """ Enhanced version of wagtails own 'routablepageurl' that adds handling for the routing of page 1 and :param context: page context :param page: Page: The root page with the child pages :param url_name: sting: the url named pattern f...
04689eebe1de43b82ef5d971e5a3874c77706ae6
3,608,732
def _connect_mongo(host, port, username, password, db): """ A util for making a connection to mongo """ if username and password: mongo_uri = 'mongodb://{}:{}@{}:{}/{}'.format(username, password, host, port, db) conn = MongoClient(mongo_uri) else: conn = MongoClient(host, port) ...
945509455084ecf33ec488b4d239dc92a5bc1c6c
3,608,733
def client(): """ A test client that has the Authorization header """ app_test.testing = True app = app_test.test_client() return app
c777d1f0eb4e1218be24c6be9f15597d19ffb875
3,608,734
def fix_term_scope(term): """ 对term的scope进行硬处理 :param term: :return: """ scope = 'realtime' left = term.left if left and left.type == 'func' and left.subtype == 'getvariable' and 'profile' in left.variable[1]: scope = 'profile' # hard code if left and left.subtype == ...
bf67f5839a402281c2ef943983e857e10d5da627
3,608,735
def gf_add_const(f, a, p): """Returns f + a where f in GF(p)[x] and a in GF(p). """ if not f: a = a % p else: a = (f[-1] + a) % p if len(f) > 1: return f[:-1] + [a] if not a: return [] else: return [a]
8c728467213a6a83a1e98ddec68f8145697d15dc
3,608,736
from typing import Optional async def delete_item(identifier: Optional[str] = None, item_name: Optional[str] = None, city_name: str = None, current_user: AdminModel = Depends(get_current_user)): """ Delete an item by item and city name: - **current user** should be admin - **ite...
e5b58076cc29e656880ca96aecafbf47915df79b
3,608,737
from typing import Callable from typing import Awaitable async def async_bind_async_future( function: Callable[[_ValueType], Awaitable['Future[_NewValueType]']], inner_value: Awaitable[Result[_ValueType, _ErrorType]], ) -> Result[_NewValueType, _ErrorType]: """Async binds a container returning ``IO`` over...
22b50c829732e273f75e33e57c163e5d99c8a4bb
3,608,738
def pyramid_lucas_kanade( img1, img2, keypoints, window_size=9, num_iters=7, level=2, scale=2 ): """Pyramidal Lucas Kanade method Args: img1 - same as lucas_kanade img2 - same as lucas_kanade keypoints - same as lucas_kanade window_size - same as lucas_kanade num_...
a677512eddf39557ea878e4da9d1db397969fc07
3,608,739
import pkg_resources def version(): """ Returns the current version of the CySCS Python wrapper. """ return pkg_resources.get_distribution("cyscs").version
b530c798702dfb62a041a6a9c1fb8ff1dc1e6365
3,608,740
def get_parameter_name_by_parameter_stream(stream_parameter_name, stream): """ Get parameter display name using stream rest api to get english name and units. (Used in plotting.py where plot_layout == 'stacked') """ display_name = None try: # Check input parameters. if not stream or ...
ddfeb2cf4d9433e1adebcea166290bed2ffb67b7
3,608,741
def check_code(): """Run pylint on code and get output :return: JSON object of pylint errors { { "code":..., "error": ..., "message": ..., "line": ..., "error_info": ..., ...
e94cb01d63354c5c7f497a130151deed86e017c4
3,608,742
def gcd(f, g, *gens, **args): """Returns polynomial GCD of `f` and `g`. """ gens = _analyze_gens(gens) try: F, G = _polify_basic(f, g, *gens, **args) except CoercionFailed, (f, g): try: return f.gcd(g) except (AttributeError, TypeError): # pragma: no cover ...
10f33ffe6211ed81d80378960d7dec3c57682d2e
3,608,743
import types def _generic_ode_solve(r, rho0, tlist, e_ops, opt, progress_bar): """ Internal function for solving ME. Solve an ODE which solver parameters already setup (r). Calculate the required expectation values or invoke callback function at each time step. """ # # prepare output arra...
ba8c111ebd0a8abf29e2ba63af4440a6c8e119ff
3,608,745
def register_done(request): """ Shows registration complete message. """ return render(request, 'blog/register_done.html')
ee984e34035d2c345db740ffa781a87ffeb8cc42
3,608,747
import torch from typing import List def validate_on_data( model: SignModel, data: Dataset, batch_size: int, use_cuda: bool, sgn_dim: int, do_recognition: bool, recognition_loss_function: torch.nn.Module, recognition_loss_weight: int, do_translation: bool, translation_loss_func...
bed81c156c2c5393a8d8ce228a2c67d31985ba8d
3,608,748
import random def miller_rabin_primality_testing(n): """Calculates whether n is composite (which is always correct) or prime (which theoretically is incorrect with error probability 4**-k), by applying Miller-Rabin primality testing. For reference and implementation example, see: https://en.wikip...
6f7263f261bf20b851aa40e0c616a68e9936f16d
3,608,749
def draw_tab(_image, _width, _height, _key_background): """draws enter arrow""" im = ImageDraw.Draw(_image) # white = (255,255,255,255) # black = (0,0,0,255) fill = pick_fill(_key_background) scalex = _width / 52.0 scaley = _height / 40.0 poly = [(int(x * scalex), int(y * scaley)) for x,...
a26b3ebd69b611a39a5454aaf04f62caffa0d000
3,608,750
import json def identity(): """ Generates a response with the name of this node. Returns: Response : Name of node """ return Response( json.dumps({RESPONSE_MSG.SUCCESS: True, "identity": local_worker.id}), status=200, mimetype="application/json", )
3d18e2bd04dc3c43fcced48bfbd704199d533b58
3,608,751
import functools from datetime import datetime def busy_try(delay_secs: int, ExceptionType=Exception): """ A decorator that repeatedly attempts the function until the timeout specified has been reached. This is different from timeout-related functions, where the decorated function is called only *onc...
0d005935ffa8b7f594da692edfa39ec4342ed4e1
3,608,752
def apply_to_tuple(*funcs, **kwargs): """ Applies several functions to one ``item`` and returns tuple of results. :param list func: The list of functions we need to apply. :param dict kwargs: Keyword arguments with only one mandatory argument, ``item``. Functions would be appli...
ecd24cc472cdb61c006e8f377041f7e5167e8df6
3,608,754
def MakeDeclarationString(params): """Given a list of (name, type, vectorSize) parameters, make a C-style parameter declaration string. Ex return: 'GLuint index, GLfloat x, GLfloat y, GLfloat z'. """ n = len(params) if n == 0: return 'void' else: result = '' i = 1 for (name, type, vecSize) in params: ...
1b009bce0d6c25b25e4830b3a021dda877519ea3
3,608,756
from datetime import datetime def get_value_from_view(context, field): """ Responsible for deriving the displayed value for the passed in 'field'. This first checks for a particular method on the ListView, then looks for a method on the object, then finally treats it as an attribute. """ view...
b28215907a82d9548067ad8283e5391383028599
3,608,757
from typing import Tuple from typing import Union def min_avg(arr: list, k: int) -> Tuple[list, Union[float, int]]: """ Time Complexity: O(n) space complexity: O(1) """ avg: Union[int, float] = sum(arr[:k]) / k start: int = 0 end: int = k - 1 cur_avg = avg for index in range(k, le...
1a2cdafd54eda4ed1078fe72f369fb8750634b84
3,608,759
def user_delete(request): """ --Delete a User instance (make inactive)-- ========================================================================================================== 1) Checks wether this delete is confirmed. If False returns 400. 2) Checks to make sure there is a refresh token string ...
c66711be8ef83404449a33075cf6810c61c16525
3,608,760
from BigDFT.Fragments import Fragment def system_from_log(log, fragmentation=None): """ This function returns a :class:`~BigDFT.Fragment.System` class out of a logfile. If the logfile contains information about fragmentation and atomic multipoles, then the system is created accordingly. Otherwise,...
2cf9514c31d3046f699f2ec81c06f124afdf378c
3,608,764
def _ComputeLeafChildCacheKey(node): """Computes a key that uniquely identifies the node, or None if no key.""" if not _NodeHasAllLeafChildren(node): # We do not compute cache keys for nodes that have children, since # there is a low hitrate for such duplicates and since the cache # keys would be substa...
6a5e3a6915749a8767ef20f753a57b9ba29075fc
3,608,765
import click def update_crs_cmd(epsg): """ Reproject the CityJSON to a new EPSG. The current file must have an EPSG defined (do it with function update_epsg()). """ def processor(cm): print_cmd_status('Reproject to EPSG:%d' % epsg) if (cm.get_epsg() == None): click.echo...
39323e2184212d03a40c8b9c548ad3f2e43f587b
3,608,766
def get_gs(urldata): """ 训练二分类器,用于后期特异度判断 :param urldata: :return: """ tmp = host_count(urldata) urldata = pd.merge(urldata, tmp, on='original_host') low = urldata['ip_dst_nunique'].describe()[4] mid = urldata['ip_dst_nunique'].describe()[5] high = urldata['ip_dst_nunique'].descr...
735d5bd6fd9454ed87be3b98cf9779154a3d2f5f
3,608,767
def db_connect(rdb): """ Connect to specified database Keyword arguments: db: database key """ LOGGER.info("Connecting to %s on %s", rdb['name'], rdb['host']) try: conn = MySQLdb.connect(host=rdb['host'], user=rdb['user'], passwd=rdb['password'], db...
39d9dd1c76fd1d04f8c74d17cd9f4d29d2aa866e
3,608,768
import numpy as np def rand_jitter(arr, sensib = 0.01, lowerLimit=None, upperLimit=None): """ Creation of jittering in a one-D data array arr sensibility can be adjust with parameter sensib. In case of an array only made of a same value, you can use the lowerlimit and upperlimit parameters """...
1e7e6f67a660508effedb1b68cb4034acaa5e0c2
3,608,769
def make_text_list(postings_dict, first_n_postings=100): """ Extract the texts from postings_dict into a list of strings Parameters: postings_dict: first_n_postings: Returns: text_list: list of job posting texts """ text_list = [] for i in rang...
0d2a4e0f2d904b246942508e03cfd97cf5d43ea0
3,608,770
def SegNet(input_shape, num_classes): """ 论文中介绍的SegNet网络 :param input_shape: 模型输入shape :param num_classes: 分类数量 :return: model """ inputs = layers.Input(shape=input_shape) # encoder x = layers.Conv2D(64, (3, 3), padding='same', kernel_initializer='he_uniform')(inputs) x = layers...
3aed89a84c91a32fb7a8ab76af7b053328faa527
3,608,771
from pathlib import Path from typing import Dict from typing import Tuple from typing import List def get_tensorboard_hooks( config: dict, experiment_root_directory: Path, train_metrics: Dict[str, Metric], test_metrics: Dict[str, Metric] ) -> Tuple[List, List]: """ Get TensorBoard hooks for visualizin...
03f2fed5aee9aac3c234d0456b579ffdf47f63c3
3,608,772
import yaml def db_read_benchmark(db_name=cfg.FILES.DB_BENCHMARK): """ Read benchmark data from file.""" with open(cfg.FILES.DB_BENCHMARK,'r') as f: db_benchmark = edict(yaml.load(f.read())) if cfg.EVAL_SET == 'paper': db_benchmark['techniques'] = filter( lambda technique: technique.eval_set=='paper',d...
49e27079945dc62a98e5da9b96a9d5718037cc55
3,608,774
def create_widgets(root, model): """Create the window and its widgets. Arguments: root: the root window. model (str): keyboard model Returns: A SimpleNamespace of widgets """ # Set the font. default_font = nametofont("TkDefaultFont") default_font.configure(size=12)...
927a6c186f3cdf75eaa7957fabd55a4b4ac04376
3,608,775
def nonoverlap(a, i, omega, R): """No overlap constraint. This function receives a 1D array which is the row of a matrix. Each element is a vector. i is which row we are passing. """ nonzeroi = np.nonzero(omega[i])[0] x = a n1, n2 = a[nonzeroi] vec = n1 - n2 norm = np.linalg.norm(vec...
aca025b81b001e6af91731fdd2d87b6e8f0168ff
3,608,776
def update_addon_download_totals(): """Update add-on total and average downloads.""" if not waffle.switch_is_active('local-statistics-processing'): return False qs = ( Addon.objects .annotate(sum_download_count=Sum('downloadcount__count')) .values_list('id', 'sum_d...
8e3846ed071ac2b63a4acfbe525072815ea94ba9
3,608,777
import json def get_file(projectCode, branch, filepath): """ :projectCode: идентификатор проекта :branch: необходимая ветка :folderPath: GET параметр путь к папке, получить через request.args.get('filePath') **Response:** ``` { "name": "myfile.md", "full_path": "/folder/my...
1765c422e2f9ced254775f1da354f424071b7763
3,608,778
def parse_input_shape(input_shape): """ Function Description: parse input shape Parameter: input_shape:the input shape,this format like:tensor_name1:dim1,dim2;tensor_name2:dim1,dim2 Return Value: the map type of input_shapes """ input_shapes = {} if input_shape == '':...
793810607751c5866dfd35a0aaf9632ff8593004
3,608,779
def app_add_developers(app_name_or_id, alias=None, input_params={}, always_retry=True, **kwargs): """ Invokes the /app-xxxx/addDevelopers API method. For more info, see: https://documentation.dnanexus.com/developer/api/running-analyses/apps#api-method-app-xxxx-yyyy-adddevelopers """ fully_qualified...
2108709599993fc695e60038a6523f7276922f8a
3,608,781
def wave_exist_2d_trunc_v2(b=.8): """ plot zeros of -nu1 + G(nu1,nu2) and -nu2 + G(nu2,nu1) as a function of g """ plane1_z = 0.55 plane2_z = 0.889 g = np.linspace(0+.0*1j,2+0.*1j,1000) # nu1 branches L1 = Sqrt(-1 + 1.8*g) L2 = Sqrt(-5 + (4 + b)*g + Sqrt(9 + 6*(-4 + b)*g + (4...
d845fca19de9007549dd1cf0e9f96f099e57f635
3,608,782
def _get_test_unconnected_page(site): """Get unconnected page from site for tests.""" gen = pagegenerators.NewpagesPageGenerator(site=site, total=10, namespaces=[1, ]) for page in gen: if not page.properties().get('wikibase_item'): return pa...
172fdb8770d7864eed7f1a94908a94e5ed4e05dd
3,608,783
def not_contains_non_russian_cyrillic_letters(text: str) -> bool: """Checks if a text contains any non-russian but cyrillic letter.""" return all(letter not in NON_RUSSIAN_CYRILLIC_LETTERS for letter in text)
1aa732e83f63438c1b45f85aef412acbc829d926
3,608,784
def evaluation_rect(box,image,range,cur_state,thresh,k_thresh,min_thresh,max_thresh,k_select): """ :param box: 外包矩形四个顶点 :param image: 图片 :param min_thresh max_thresh 对于该斜率范围直线,保持原本斜率会过于大,直接加减又不合适,更新为k_select :param k_thresh :param k_thresh:代表确定斜率无穷大的阈值 :param thresh: 白色像素百分比阈值,大于此阈值,为1 ...
fce9a8e78667feade7ae679dca5f4fa7edae68f7
3,608,785
import uuid import json def test_blank_index_upload_authz( app, client, auth_client, encoded_creds_jwt, user_client ): """ Same test as above, except request a specific "authz" for the new record """ class MockResponse(object): def __init__(self, data, status_code=200): self.d...
b78abbf76cdb0f9a121b4f6df743b2d8e40ff524
3,608,786
def get_blocked_mlp(class_or_reg, num_blocks, num_layers_per_block=None, num_units_in_each_layer=None): """ Creates a blocked MLP. """ # Create rectifiers and sigmoids rectifiers = ['relu', 'elu', 'crelu', 'leaky-relu', 'softplus'] sigmoids = ['logistic', 'tanh'] obtl_label = 'linear' if c...
5a539d4bd54a1af374f528c5f4cc41f110a5ffe2
3,608,787
def auto_review_task(study, task): """ Reviews a Task machine-wise. Based on the regulations on http://fetc-gw.wp.hum.uu.nl/reglement-algemene-kamer/. """ reasons = [] for registration in task.registrations.all(): if registration.requires_review: if registration.age_min:...
121d2fbf861283c8eccd7c447ad5474e25b80d62
3,608,788
def make_Anndata(input_data, mtx_name='bmat', feature_names=None, metadata_name='metaData', jaccard=True, jaccard_key='jmat', save_all_rds=False, save=None, copy=True): """ Cu...
cd06ac717a73d81fec7f4807fce54b5bd4737e08
3,608,789
def _ensure_year(yr, isyr2): """ Ensure 4-digit year Years are supposed to be 4-digit years. If they have only 1 or 2 digits, then every year that is above the current year of the century will be taken as being in 1900, i.e. 90 will be taken as 1990, while all other years are taken in the 21st ...
1fdc894da9165aa494a842f96b35ba62111f2c10
3,608,790
def calculate_iou(confusion_matrix): """ https://github.com/ternaus/robot-surgery-segmentation/blob/master/validation.py """ confusion_matrix = confusion_matrix.astype(float) ious = [] for index in range(confusion_matrix.shape[0]): true_positives = confusion_matrix[index, index] ...
7f8eb6f957b031c808bb4ef0f921de26a2c855eb
3,608,791
def create_manager(notifiers=None, **kwargs): """ Create manager. If notifiers is given and is a tuple (a, b), it generates a authorized notifiers and b non-authorized notifiers in the same state. """ state = kwargs.setdefault("state", random_state()) kwargs = { "email": "manager@manager...
f9d463dc303a8e0e6b5765b4ab977c9bd85aeeab
3,608,793
def tokenise(string): """ Tokenise an ASJP string into a list of tokens. Raise ValueError if it cannot be unambiguously tokenised and raise TypeError if it is not a string. The input may consist of several words, i.e. whitespace-separated sub-strings. Usage: >>> tokenise('nova zEmy~a') ['n', 'o', 'v', 'a', 'z',...
4d3ee3faa9912b463cbe984605352b8823b708b9
3,608,794
def cards_db(db): """Empty the CardsDB object after each function""" db.delete_all() return db
1f62dc919e860b9d4db31f611a8109356c1c6c1b
3,608,795
def dense_to_one_hot(labels_dense, num_classes): """Convert class labels from scalars to one-hot vectors.""" if type(labels_dense) != np.ndarray: labels_dense = np.asarray(labels_dense) num_labels = labels_dense.shape[0] index_offset = np.arange(num_labels) * num_classes labels_one_hot = np...
a7068c22d272cf155e059d46b1d6bb6054da7da0
3,608,796
def viewmesh(): """ mesh / glacier view """ mapform = get_map_form(session) extractform = get_form(ExtractForm(), session) meshform = get_form(MeshForm(), session) return render_template('mesh.html', form=mapform, extractform=extractform, meshform=meshform)
be35ffb7db9c76c98313a5b6ebb7dd5f288a8417
3,608,797
def cellres(lat, xres=1.0, yres=1.0): """Return the cell (x, y) resolution [m] based on cell center latitude and its resolution measured in degrees.""" m1 = 111132.92 # latitude calculation term 1 m2 = -559.82 # latitude calculation term 2 m3 = 1.175 # latitude calculation term 3 m4 = -0.0023...
b05104ae2f8e5b4365091cd30c22d40f727faa77
3,608,798
from typing import Callable from typing import Any def commands_dict( funcs, *, mk_command: Callable[[Callable, tuple, dict], Any] = Command, what_to_do_with_remainding='ignore', **kwargs, ): """ :param funcs: :param mk_command: :param kwargs: :return: >>> def add(a, b: f...
e489eda57c5bc7a81472d5e5b53f72d1fa09d8e4
3,608,799
def invert0(x): """ Invert 0 -> 1 if OK = 0, FALSE > 1 """ return 0 if x > 0 else 1
1c7a71885cdc84f12b3e2214aa74f99ff2aab326
3,608,800
def _calc_proj_cnrs(imgs, ncore, nlist, method, medfilt2_kernel_size, medfilt_kernel_size, ): """ Private function calculate slit corners concurrently Parameters ---------- imgs :...
a3d6addcd4bab497820b771e2a3de39d083199d7
3,608,801
from tokenize_rt import ( src_to_tokens, tokens_to_src, reversed_enumerate, ) from typing import Tuple def remove_trailing_semicolon(src: str) -> Tuple[str, bool]: """Remove trailing semicolon from Jupyter notebook cell. For example, fig, ax = plt.subplots() ax.plot(x...
0c566a446d3097ebf2ae94549d5788002b067fb8
3,608,802
from datetime import datetime def calc_duration_rel(wl_obj, end_time, start_time): """ Determines a duration based on two times. Arguments: - wl_obj -- the work log object. - end_time -- the ending time. - start_time -- the starting time. Returns: a timedelta obj...
be87c4b66b4bfe9056da306b1cad6caf4b04616c
3,608,803
def setup_EC(w_EC, c, V, b, U, rho_e, dx, ds, normal, dirichlet_bcs, neumann_bcs, boundary_to_mark, c_1, u_1, K_, veps_, phi_, solutes, per_tau, z, dbeta, enable_NS, enable_PF, use_iterative_solvers, q_rhs): """ ...
0df40d4942ba5c4387b66cc884b68f7868b2fb71
3,608,804
def list_get_comments_g(amid: int, order: str = "time", verify: utils.Verify = None): """ 获取评论 :param amid: 歌单ID :param order: :param verify: :return: """ replies = common.get_comments(amid, "audio_list", order, verify) return replies
28f31c934ed4bb1bbef644456b69d737b27ee2c6
3,608,805
import torch def bounded_iou_loss(loc1, size1, loc2, size_): """ loc1/2:[(l,t),...] size1/2:[(w,h),...] 2 |= target :return 0 if same, >0 if diff SINGLE_IMAGE """ loc_delta = torch.abs(loc1 - loc2) iou_loc = torch.div(size_ - loc_delta, size_ + loc_delta) iou_size = torch.min(t...
67964833f5a190065b843f1c89c1eccd16824245
3,608,806
def show_user_keys(username): """ Client's personal page GET: Displays the client page html. Displays download button and generates hash if keys haven't been downloaded for this user """ downloaded = hl.checkDistributeFlag(username) #Prevent Replay Attacks by downloading keys hash ...
d5aecb2794dbf4e69cb0a1b4182d9137413394b5
3,608,807
def one_or_more(amount, single_str, multiple_str): """ Return a string which uses either the single or the multiple form. @param amount the amount to be displayed @param single_str the string for a single element @param multiple_str the string for multiple elements @return the string represent...
8c3495614cd8c718e243383bcc72cc7daa8fa286
3,608,808
def auroc(labels=None,predictions=None,tp=None,fp=None): """auroc - calculate area under the curve from a given fp/rp plot""" if labels is not None: [fp, tp] = roc(labels,predictions) n = tp.size auc = 0.5*((fp[1:n]-fp[0:n-1]) * (tp[1:n]+tp[0:n-1])).sum() return auc pass
1ed616ec6455d0159bdd51321f23ef972f21d63b
3,608,810
def det_ZZ(n=200, min=1, max=100, system='sage'): """ Dense integer determinant over ZZ. Given an n x n matrix A over ZZ with random entries between min and max, inclusive, compute det(A). INPUT: - ``n`` - matrix dimension (default: ``200``) - ``min`` - minimal value for entries of matrix ...
7d8c74853a5b49323aee2ce0a66b7a72b1433a3d
3,608,811
def particle_class_instance(flavor, particle_config): """ Return a particle class from a flavor or handle CLI error message """ particle_class = particle_class_from_flavor(str(flavor).strip()) if particle_class is None: fail( "Error: {} is not a supported Particle or Quasiparticle flavor...
3bbb7a7ca358f5b38b3488943382b88be8de4d0a
3,608,812
def create_being(): """ Creating a new entry of type being """ form = EntryBeing() form.category_id.choices = [(i.id, i.name) for i in Category.query.all()] if form.validate_on_submit(): being = Being(name=form.name.data, meaning=form.meaning.data, ...
e55b8d0b0b0442412cd05d576031d05ff714dd52
3,608,813
import torch def accuracy(output, target, topk=(1,), exact=False): """ Computes the top-k accuracy for the specified values of k Args: output (ch.tensor) : model output (N, classes) or (N, attributes) for sigmoid/multitask binary classification target (ch.t...
cc2194bb72460ff39e3648e173d52875f64abeab
3,608,814
def liqwater_h(T, To=0): """Calculates the specific enthalpy [J/kg] of liquid water at atmospheric pressure, for a given temperature ( Celsius). Notes: This is calculated via the specific heat capacity of water at Patm, for a specified reference temp (O C by defualt). Some sources report slightly diffe...
172b54d687fe2ea02696b68477fc092af64bc312
3,608,815
import itertools def enumerate_hyperparameter_combinations(parameter_to_options): """ Returns a list of dictionaries of all hyperparameter options :param parameter_to_options: a dictionary that maps parameter name to a list of possible values :return: a list of dictionaries that map parameter names ...
8665ef66b7cb1467599ff0a56f47ac60042e0e9a
3,608,816
def get_ts_guess_function_and_params(reaction, bond_rearr): """Get the functions (1dscan or 2dscan) and parameters required for the function for a TS scan Arguments: reaction (autode.reaction.Reaction): bond_rearr (autode.bond_rearrangement.BondRearrangement): Returns: (list): ...
39a0e45748d87dd481db5737d8654216c424908e
3,608,817
from typing import List from datetime import datetime from operator import add def water_licences_summary(licences: List[Feature], polygon: Polygon) -> LicenceDetails: """ takes a list of licences and the search polygon, and returns a summary of the licences that fall within the search area. """ ...
5d86ffe3da3bb940e27467ea8ee6cc5b511b703b
3,608,818
def get_new_pvars(opvs, epvs): """Returns a list of new projection variables from a list of old PVar's opvs, based on a list of existing PVar's epvs. Args: opvs: Old projection variables. evps: Existing projection variables. Returns: A list of projection variables. """ ...
b344e4fb60daa0452c944065b3164d90e7698a21
3,608,820
def check_all_types(src_dict, sinks, sourceField): # type: (Dict[Text, Any], List[Dict[Text, Any]], Text) -> Dict[Text, List[SrcSink]] # sourceField is either "soure" or "outputSource" """Given a list of sinks, check if their types match with the types of their sources. """ validation = {"warning":...
99d8b7e1a8ed7818aa3c46bd85799f466cb8837a
3,608,821
import requests def get_metadata(path): """ Get metadata relative to metadata/computeMetadata/v1/instance/ """ URL = 'http://metadata.google.internal/computeMetadata/v1/instance/' HEADERS = {'Metadata-Flavor': 'Google'} full_path = URL + path try: resp = requests.get(full_path, headers=HEA...
f4bb27434327745efa3340e11865513e1fbf9290
3,608,822
def count_gaps(sequence): """In order to calculate the correct percent divergence between two strings where there are gaps present, the gaps need to be counted in order to be deducted from the total number of differences. This function takes a sequence string and returns the number of instanc...
a0124ef8ee77d5b1c39da96131a9a0dff7301bcc
3,608,823
def get_year_graph(cardinal: GraphFst) -> 'pynini.FstLike': """ Returns year verbalizations as fst < 2000 neunzehn (hundert) (vier und zwanzig), >= 2000 regular cardinal **00 ** hundert Args: delete_leading_zero: removed leading zero cardinal: cardinal GraphFst """ year_g...
b50f61b1b51934cad41e5fdb35efe973d41e528c
3,608,824
def sql_update_pd(sql, table_1=None, table_2=None, func1=None, func2=None, func3=None): """主函数""" # 第一步,判断SQL是否正确 table_1_cols = table_1.columns.tolist() table_2_cols = table_2.columns.tolist() if isinstance(table_2, pd.DataFrame) else [] judge_format(sql, table_1_cols, table_2_cols) # 第二步,解析SQL...
cc7392237ef90ce5bfd009907571d8f97d3c8cae
3,608,825
def getReAuthors(articleurl): """获取相关学者""" # 本篇文章的作者 res = [] authors = getAus(articleurl) for author in authors: co = getACo(author.url) # 同机构的学者 res.extend(co) return res[0:20]
68a260672c2bbb474559de46e2c715719798667f
3,608,826
import functools def route(route=None, **kw): """ Decorator marking the decorated method as being a handler for requests. The method must be part of a subclass of ``Controller``. :param route: string or array. The route part that will determine which http requests will match the dec...
ac26a919bfd2639a845e829219367470366ee3a1
3,608,827
def multiprocess_tokenize_tweet(documents): """ Args: documents (list): this is a list of the documents to be tweet tokenized Returns: tokenized_tweets (list): a list of tokenized tweets done with multiprocessing """ n_processes = mp.cpu_count() p = mp.Pool(n_processes) ...
c3c669f0fb5146cce88a72d641a382fa925a2857
3,608,828
def _node_description(op: saldag.OpNode, kind: str, inner): """ Returns description of node properties. """ if inner: return "{{ {{ <I>{}</I> | <B>{}</B> }} | {} | {} }}".format( op.out_rel.name, kind, inner, _column_list(op)) else: ...
2e1bee71865f24e0d48917f8e6c623b1135ae381
3,608,829
import ctypes def _is_little_endian(obj: ctypes.Structure) -> bool: """ Checks whether a Structure instance/class is little endian :param obj: Structure instance/class :return: True if little endian """ is_swapped = hasattr(obj, _CTYPES_SWAPPED_ATTR) if _SYS_ENDIANNESS_IS_LITTLE: ...
4dde9bedc4847f4e1bb38670a5b5b691975b6527
3,608,830
def get_mean_next_generation_matrix_from_simulation(N,counters): """ Compute the mean next generation matrix from a simulation result. Parameters ========== N : int Number of species/states counters : list of tuple of (int, :class:`collections.Counter`) Each entry of this li...
a69fcb203d92875414a379c79703670764e19957
3,608,832
def detect_seq(x, value=0, min_seq=1, show=False, ax=None): """Detect initial and final indices of sequential data identical to value. Detects initial and final indices of sequential data identical to parameter value (default = 0) in a 1D numpy array_like. Use parameter min_seq to set the minimum numbe...
a6fc354d5d7fcff06b6715ea8adf19e07837d74e
3,608,833
from typing import List from typing import Optional def _expand_param_units(param: BaseDescriptor) -> List[Optional[str]]: """ Get expanded param units :param param: The param to get units for :return: A list of the units (or None if no unit) """ unit = getattr(param, 'unit', None) expand...
e9b610063d28427af5ec29e7734da9fb5784ebf8
3,608,834
def get_dissimilarity_matrix(sequences, function): """ Computes a dissimilarity matrix using a given function. This function can be a measure of dissimilarity, distance, or any other measurement between two sequences. The column names and index on the matrix are the indexes of each sequences in the collection. E...
37aa422cbca03f5d94084c3ae6c0e7b92e09f921
3,608,835
def request_project_by_key(cfg, project_key): """Request project data by jira project key""" url = cjm.request.make_cj_url(cfg, "project", project_key) response = cjm.request.make_cj_request(cfg, url) return response.json()
693a73c29aab1ec5deaa2c6859e29fcdf2b19eda
3,608,836
def _minimum( *, value, schema: dict, uri: str, validation: Validation, ref_list: RefList ) -> Callback: """ minimum https://json-schema.org/draft-06/json-schema-validation.html#rfc.section.6.4 https://json-schema.org/draft-07/json-schema-validation.html#rfc.section.6.2.4 """ return lambda ...
b1d7a838a7e045472957e3b50b72f8c2937e803f
3,608,837