content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import tqdm def adjust_contrast_with_mask(img, img_mask=None, contrast=-1, mu=-1, img_min=0, img_max=255, force=True, verbose=False, mu_steps=500, gain_steps=500): """ A version of the contrast adjustment that is mindful of the mask Performs contrast adjustment of the image,...
3980737a222d8618d42fe1e2add4f4af78289091
73,334
def get_minimum_n_cores_for_only_LSNN_placement_no_ws(LSNN_size, input_dim, n_relay_copies, use_cores_for_input=False): """ Unlike the function get_minimum_n_cores_for_LSNN_placement_no_ws, this function only calculates the parameters for the placement of the input and LSNN layers given the number of re...
c51eec344ecaa579c882c6b24a10fede2842bc65
73,335
def attack(url): """Implement timing attack on given url.""" guess = '' found = True while found: c, found = next_guess(url, guess) guess += c if found else '' valid = check_valid(url, gen_params(guess)) return valid, guess
c21de994600de346024950b0a8bb9d551c65836f
73,336
from typing import List def get_macro_recall(executions: List[RevisionResults]) -> float: """ Calculate macro-averaged recall for a list of tool executions. :param executions: list of RevisionResults objects :return: macro-recall value """ red_tests_recall = [ res.score[1] / res.score...
7ad1a564f3e1ebe674dbf52e193c48943848741a
73,337
import types import keyword def invalidPythonNames(): """ Creates a list of valid Java identifiers that are invalid in Python. """ ts = [getattr(types, n) for n in dir(types) if not n.startswith('_')] ns = [t.__name__ for t in ts if isinstance(t, type)] return ['None', 'True', 'False', ] + ns + keywor...
0eaf0f7188d3e821bb37faa5e5f698cbcdc9e0e0
73,338
def return_obs_RA_DEC(): """ Return OM10's lensed system's position """ return SkyCoord('03h 32m 30s', '10d 00m 24s')
8b19ee8f1f83816246918284033bc98670223894
73,339
def delete_object_property(object_type, property_name): """ Delete a property from Hubspot Args: object_type (str): The object type of the property (ie "deals") property_name (str): The property name Returns: dict: the result of the delete request in JSON format """ re...
29f5b8d83e45ae052d1946abbf21d21a8b96f3f6
73,340
def populate_table(parsed_header, parsed_line, file, data_dict): """Appends parsed sample metadata to a nested dictionary where dictionary['Sample_Name']['QC_Attribute'] = QC_Metadata. Returns an updated dictionary containing new information for N-th line.""" sample_index = parsed_header.index('Sample'...
fe12a867bf2a6893580eb05f1e8d6bdb284786ae
73,341
def get_report(query, page_len): """ Extract user's reports from the website based on query and page number. Here, we want to extract reports from user, institute destination, and category of the reports. In the HTML code, the reports element is in the <p> (paragraph) tag with class attribute `readmore`...
bdf8141c9bed1e85c49a00bcddbbc926bc589a4a
73,342
def get_object_id(path): """Read, if present an object_id if not available -- would simply raise a corresponding exception """ with h5py.File(path, "r") as f: return f.attrs["object_id"]
b1457dcd5d3e7bc393a78e0bd1cdf47a40fbacd1
73,343
def split_sql(sql): """Splits given SQL into list of statements, stripping comments.""" sql = sqlparse.format(sql, strip_comments=True) return sqlparse.split(sql)
d6627568afb28fb27b5f43d8635ea1d764a2990a
73,344
def generalised_dice_loss(prediction, ground_truth, weight_map=None, type_weight='Square'): """ Function to calculate the Generalised Dice Loss defined in Sudre, C. et. al. (2017) Generalised Dice overlap as a deep learning ...
05adfcaf5e86b8fa6861d4a29e1d2cb89680d92b
73,345
def calc_best_fit_n_param_fast(ndim,flatchain_path,output_file_path=None): """Description: -Input : -Output : a numpy array with [best params, chi2] Plots and txt files: txt files: pdf files: Tested : ? By : Maayane T. Soumagnac Nov 2016 URL :...
f922ac74527e03087d3522623528ad9a661cce4b
73,346
def maximum_leja(next_point, z, lower_bound, upper_bound, weight=lambda x : 1): """ the maximums function for the leja points the next leja point is the input so that this function returns its maximum """ if (next_point[0] < lower_bound or next_point[0] > upper_bound): return -100 pr...
079c312787a0d0e8704985f0f8ffd146754b2c59
73,347
def submit_metadata(metadata_modal, name, description=None, version=None, load_workspace=False): """ Submits metadata for a project Returns ``(projects_page, data)`` """ metadata_modal.submit_metadata(name, description, version) workspace_page = WorkspacePage.verify(metadata_modal.browser, TEST...
7e49169c8ede637b060f7c59e8feba03bed9d281
73,348
def calculate_individual_geo_mean(lines, index, geo_mean, num): """ Calculate an individual line of parse results goe_mean """ previous_value = None for line in lines: line = line.split("\t")[4:] current_value = line[index] try: if float(current_value) > 0: ...
765b03379d11d2622d07086e1858ee51807bc293
73,349
def sendDataToMDB(): """ Parses array of items from frontend, sends to mongoDB :input: array of json objs - name, price, need vs want """ feData = request.get_json() for i in feData: post = { "_id" : dataIndex.count_documents({}) + 1 , "ItemName" : i['name'], ...
b937303ff45a33911b78e289e794555e572c4003
73,350
def regenerated_pyconfig_h_in(file_paths): """Check if pyconfig.h.in has been regenerated.""" if 'configure.ac' in file_paths: return "yes" if 'pyconfig.h.in' in file_paths else "no" else: return "not needed"
d5d180a5a9d149cbbcdccb3d72ef69647908678f
73,351
def not_equal(a,b): """ return 1 if True, else 0 """ if(a != b): return 1 else: return 0
a37ae9177a450b11412c82898e1dade68b97416f
73,353
def check_square(): """ Checks the square of the board the mouse is currently over, selecting a piece if there is one Returns: selection: The object that was under the mouse at the time of checking """ x, y = pygame.mouse.get_pos() selection = the_board.board_[y // 100][x // 100] ...
900ced25a99a2a65b3b2914b602b3a386f94778e
73,355
from operator import and_ def view_codec_list(): """ admin: codec list not admin: query by productID """ if g.tenant_uid is None: query = Codec.query \ .join(Tenant, Tenant.tenantID == Codec.tenantID) \ .join(Product, Product.productID == Codec.productID) \ ...
f3913555025434a74579e7f434fc0b7bd171911b
73,356
from datetime import datetime def get_latest_one_piece_chapter_jb(): """Retrieves the latest chapter number on Jaimini's box.""" today = datetime.date.today() jb_page = "https://jaiminisbox.com/reader/series/one-piece-2" jb_request = urllib2.Request(jb_page, headers=get_headers()) jb_response = ur...
9937346367b65b55b3908c432c6e8fa56458aa88
73,357
def active_view(): """Return currently active view""" return sublime.active_window().active_view()
e19348dc249b63aab1350b8a2362ee24db9f930d
73,358
import pathlib import shutil def cache_audio_local(path, max_audio_length, cache_dir=pathlib.Path('./audio')): """ Copies the file specified by `path` to cache_dir in the same folder structure that is present at the source. The file should be in an audio format readable by `nt.io.audioread.load_audio`...
07b2eb61e842b8c603416313f3c1c2a472d8ab66
73,359
def centerdc_2_twosided(data): """Convert a center-dc PSD to a twosided PSD""" N = len(data) newpsd = np.concatenate((data[N//2:], (cshift(data[0:N//2], -1)))) return newpsd
28d712a16f5118e73081ef857194f39488fcd027
73,360
def getCount(board): """gets counts for all pieces and empty moves present on the board""" #For fast counting Implemented this Idea #https://stackoverflow.com/questions/10741346/numpy-most-efficient-frequency-counts-for-unique-values-in-an-array unique, counts = np.unique(np.array(board), return_counts...
274d5cfe6a593a78752d775a08a0bb27ea638eaf
73,361
def src_gauss(l, m, sigma_lm, A=1., i=0., pa=0., l0=0., m0=0.): """ A 2D Gaussian model on the source emission. Parameters ---------- l : array like The l axis coordinate. m : array like The m axis coordinate. sigma_lm : float The sigma of a Gaussian profile of the s...
8ca8f5f7521ec605f3bb6db1ef3cdeed4a2241ce
73,362
def sort_hsvs(hsv_list): """ Sort the list of HSV values :param hsv_list: List of HSV tuples :return: List of indexes, sorted by hue, then saturation, then value """ bars_with_indexes = [] for index, hsv_val in enumerate(hsv_list): bars_with_indexes.append((index, hsv_val[0], hsv_val...
49a0936a04156ef1d785dea7efc95d5fffb368e0
73,363
def GetCcIds(issue): """Get the Cc's of an issue, whether they are explicit or derived.""" return issue.cc_ids + issue.derived_cc_ids
c5d558c4bfac4da5e501bc834e6218a44c49fbd9
73,366
import cmd def kill_remote_process(pids, instance): """Kill processes in remote device (`instance`) Parameters ---------- pids : list A list of process id's to kill instance : instance.Instance Instance object corresponding to remote device Returns ------- str Result of `kill` command ...
81b272a099ffa9f0815526abbad66647ababf13e
73,367
def sortedArrayToBST(nums): """ :type nums: List[int] :rtype: TreeNode """ if len(nums) == 0: return None mid_idx = int(len(nums) / 2) root = TreeNode(nums[mid_idx]) root.left = sortedArrayToBST(nums[:mid_idx]) root.right = sortedArrayToBST(nums[mid_idx + 1 :]) return root
9f842a9818da7bc5de6c136d4ea46c099ce79711
73,368
def render_md(full_path, format): """ Render a given markdown file """ with open(full_path, encoding="utf-8") as file_handle: text = file_handle.read() html = markdown.markdown(text) return Response(html, mimetype="text/html")
f65ea879c1c501b28c27d2c369645a60c323fffa
73,369
import urllib def extract_params(qs, known_params, object_type, object_name): """ Extract parameters from a query string to a dict while ensuring there is no unknown parameter qs: the query string known_params: a list of known parameters, any unknown parameter found will fail an "ensure" check object_type: stri...
2b836ebb1a826c9d0ab17dbb472acb7ca5690fcc
73,370
import torch from typing import Sequence from typing import Any def clamp_n(tensor: torch.Tensor, min_values: Sequence[Any], max_values: Sequence[Any]) -> torch.Tensor: """ Clamp a tensor with axis dependent values. Args: tensor: a N-d torch.Tensor min_values: a 1D torch.Tensor. Min value...
bc3f486d04c55d92b001239d1f9e2496a7d201d0
73,371
import time def login(): """ A form (GET) and the assocaited handler (POST) for validation of user credentials. It is possible to put the application in testing mode, so that password checks are not enforced and the user only need supply a username. This should never be enabled in production....
447610c550da1fed231577d7819574548d408605
73,373
import shlex import click def parse_parameters(_filter): """Return parsed filter parameters.""" try: parsed_filters = [] filters = ' '.join(_filter).replace(',', ' ') for item in shlex.split(filters): if '=' in item: filter_item = { 'colu...
174841c52303dc73a3ef0b598c025d8b97760461
73,374
def admin_auth(f): """Creates the admin guard decorator""" @wraps(f) def decorated(*args, **kwargs): data, status = Auth.get_logged_in_user(get_jwt_identity()) user = data.get('data') if not user: return data, status if not user['admin'] == store.is_admin(): ...
80ccaea73fc168b1bdc5e6d84ea160e29508c4f3
73,375
def load(test=False, cols=None): """Loads data from FTEST if *test* is True, otherwise from FTRAIN. Pass a list of *cols* if you're only interested in a subset of the target columns. """ f_name = FTEST if test else FTRAIN df = pd.read_csv(f_name) df['Image'] = df['Image'].apply(lambda im: np...
eb92ac8ee57b961118c37788915ca90b02a40cc9
73,376
import types def do(f): """ A decorator which allows you to use ``do`` notation in your functions, for imperative-looking code:: @do def foo(): thing = yield Effect(Constant(1)) return 'the result was %r' % (thing,) eff = foo() return eff.on(...) ...
c2408d4d546047098eb92979729b33395b41adca
73,377
def check_data_id(data_id): """检查DataId是否合法 :param dataId: :return: """ return check_param_isvalid(data_id)
1101c7f4a2bffd7bb1342640dd5fc22cbfadd080
73,378
from typing import List def BruteCollinearPoints(points: List[Point2D]): """ Examines 4 points at at a time Checks whether all 4 points lie on the same line, returning all such line segments """ segments = [] for p in range(0, len(points)): pp = points[p] for q in range(p +...
e6cd0099af7fe314eb1be1ba0693bfa357945d6b
73,379
def cleanupFilename( fname ): """: Make the filename usable. = INPUT VARIABLES - fname Given a filename, clean-it up to make sure we can use it with the file system. = RETURN VALUE - Returns a cleaned up form of the input file name. """ fname = fname.replace( ' ', '_' ) fname = ...
25f727172ed9438c49510fd6703d2d56c61f85f2
73,381
from paraview.modules.vtkPVVTKExtensionsFiltersGeneral import vtkCellIntegrator def IntegrateCell(dataset, cellId): """ This functions uses vtkCellIntegrator's Integrate method that calculates the length/area/volume of a 1D/2D/3D cell. The calculation is exact for lines, polylines, triangles, triangle...
a2eeb687d48fbab73aeb4de39726e93fdb0be6bd
73,382
def get_PS_embeddings(_files, params): """ Computes the Patchy-San embeddings for all functions in _files """ CNN_input = {} for function, acfgs in _files.items(): CNN_input[function] = list(map(lambda acfg: get_CNN_input(np.array(acfg['A']), np.array(acfg['X']), params),acfgs)) return C...
0b1d447d9176bb77261d40f6dd456b49dc60dcd1
73,383
import json import ast def parseJsonDatum(js): """Parse a JSON string, return parsed object or None :rtype: :param js A valid JSON string :return parsed JSON as a dict """ if isinstance(js, dict): return js if not isinstance(js, str): return None try: # prin...
29d334038b9275fc822576f9670966768d02060e
73,384
def randomly_resort(x, sigma, seed=None): """ Function randomizes the entries of ``x`` with an input level of stochasticity ``sigma``. Parameters ----------- x : ndarray Input array of shape (npts, ) that will be randomly reordered sigma : float Input level of stochasticity in ...
ea73a296cdcaa7ec28c7f8b6106ba2e95092b12f
73,385
def FullCopy(obj): """ * Return full copy of passed object. Inputs: * obj: Any object. """ if hasattr(obj, '__enum__'): if isinstance(obj, dict): copyObj = {} for key in obj: copyObj[deepcopy(key)] = FullCopy(obj) else: copyObj ...
717e70e28b1cdd803225c774304010a87a3ece3c
73,386
def model_from_sklearn(sk_model, name, accuracy): """Loads a model from the given sklearn data structure. Args: sk_model: A model previously fitted via scikit-learn. name (str): The name of the model. This name will later be used during code-generation for naming functions. accuracy (fl...
8f2904b471234bf65ffc947208166526649e9966
73,387
def tokenizer_encode(texts, tokenizer, maxlen=512): """ Let Transformers Tokenizer API prepare the input data and encode, precisely tokenizing Parameters: ------------ texts : list of str A list of string to be encoded by the tokenizer. tokenizer : Transformers AutoTokenizer ...
c28ee490a8d2e8efd473d25ed9b58b3b209dafa3
73,388
def is_tlog(filename): """Boolean specifying if filename is a Trajectory log file.""" return _is_log(filename, ('VOSTL',))
707a4b62bb9cb85fc279662b3910bafe382e48df
73,389
def continue_or_stop(question): """ n or y is parsed from inputs first character so it's the only part that matters """ while "answer not y or n": reply = str(input(question + " (y/n): " )).lower().strip() if reply[:1] == 'y': return True elif reply[:1] == 'n': return False else: print("ERROR: Not ...
3447a3b205e71270ccede9fa5608c823afa10062
73,390
def get_default_if(): """ Returns the default interface """ f = open('/proc/net/route', 'r') for line in f: words = line.split() dest = words[1] try: if int(dest) == 0: interf = words[0] break except ValueError: pass ...
b9c046aa02cd5e7df4f1ca7506c1d01ebf93f19e
73,392
def _get_mro(obj): """Get the method resolution order for an object. In other words, get the list of classes what are used to look up methods on the given object, in the order in which they'll be consulted. """ try: return obj.__class__.__mro__ except AttributeError: return _get...
3e7dbd7d4210726e5834c8a95a9b9086e16aad7d
73,393
import json def jsonify(val): """Perform a naive JSON dump.""" return json.dumps(val)
0b52203062c031ad10fd660c96daa0459f81d367
73,394
def linregress(x, y, weights=None): """ fit a line to y(x) using least squares. """ if weights is None: weights = np.ones(x.shape) weights /= np.sum(weights) μx = np.sum(weights*x) μy = np.sum(weights*y) m = np.sum(weights*(x - μx)*(y - μy))/np.sum(weights*(x - μx)**2) b = μy - m*μx return m, b
934a9734c92a2052ff038578781902a51378bdf2
73,395
import math def opacMg1(numDeps, temp, lambda2, logGroundPops): """//c****************************************************************************** //c This routine computes the bound-free absorption due to Mg I. //c******************************************************************************""" #//...
c97da4bf667163bc73c95da43b6300a4be9a38be
73,396
def find_road_building_relations(voronoi, pts_line, pts_left, pts_right, road_crds): """ Find all road IDs facing the current road segment. Makes use of the indices of the points between which a voronoi ridge lies. This can be used to check if a road and building are facing each other. """ r_fi...
4c023d6a93bb8a6fbdcd7565e4b191fe2b63a66a
73,398
def create_sqlalchemy_url(drivername, username=None, password=None, host=None, port=None, database=None, **kwargs): """ 输出一个 sqlalchemy的 url,有一些额外的优化。 :param drivername: :param username: :param password: :param host: :param port: :param database: :param kwa...
1516d6c97ba8272dd3d2fe3829e64b8beb668e15
73,399
async def subnet_present( hub, ctx, name, address_prefix, virtual_network, resource_group, security_group=None, route_table=None, connection_auth=None, **kwargs, ): """ .. versionadded:: 1.0.0 Ensure a subnet exists. :param name: Name of the subnet. ...
66ab96df63a1a4e0d6ba0e5380360d06afe079d4
73,400
from typing import Dict def get_files_modified_since_fork(repo_dir, base_sha, head_sha, log, project_dir) -> Dict: """Get changed files and their status in head tree compared to base tree. Skip submodule changes. They require further processing to find out which files have actually been changed under the...
99e625833c58aff79af7ec8f5913bbfdc8d49269
73,401
from typing import Type def loadenv_into_dataclass(dataklass: Type[DataClass]) -> DataClass: """Return dataklass, instantiated with values from the environment""" dataklass_envfields = {} for var_in_env, var_in_dataklass in dataklass.__dataclass_fields__.items(): if not isinstance(var_in_dataklass...
8036af916da73250d4eb7a897438845b5029ab35
73,402
def random_sign(shape, dtype=tf.float32, seed=None): """Draw values from {-1, 1} uniformly, i.e., Rademacher distribution.""" random_bernoulli = tf.random_uniform(shape, minval=0, maxval=2, dtype=tf.int32, seed=seed) return tf.cast(2 * ...
db4b3b4fabede101186ba7f3500bf5b87fb39aba
73,403
def _lucas_test_sequence(n, a, b): """ Return x_0, x_1, x_m, x_{m+1} of Lucas sequence of parameter a, b, where m = (n - (a**2 - 4*b / n)) >> 1. """ d = a**2 - 4*b if (d >= 0 and arith1.floorsqrt(d) ** 2 == d) \ or not(gcd.coprime(n, 2*a*b*d)): raise ValueError("Choose another parame...
e412efcc088ea2a3ed8d548c873f234d62d5d24e
73,404
def _timestamp_date(arg: ir.TimestampValue) -> ir.DateValue: """Return the date component of `arg`. Parameters ---------- arg A timestamp expression Returns ------- DateValue The date component of `arg` """ return ops.Date(arg).to_expr()
6ba110d0d076253d22d34ec2dc11bd5c3ac7e582
73,405
import torch import tqdm def train_one_epoch(model,train_loader:DataLoader,optimizer:AdamW,scheduler:torch.optim.lr_scheduler.LambdaLR,epoch:int,max_epoch:int): """Loops through the dataloader and trains the model and optimizer Args: model ([BertForSequenceClassification]): [description] data...
f05fe3a2fb5d392a8cf5f3e0abecb9956e42a23b
73,407
def generate_2D_reflection(angle): """ Given an angle generate a 2D rotation matrix""" angle_rad = angle/180.*np.pi return np.array([[np.cos(2.*angle_rad),np.sin(2.*angle_rad)],[np.sin(2.*angle_rad),-np.cos(2.*angle_rad)]])
80aa26eb16e9146e8f6b4f192c6be9afcf389106
73,408
from operator import index def compute_expected_obs_counts_jax(gamma, obs, n_states, n_obs): """ Computes the expected observation count for each observation o by summing the probability of being at any of the states for each time t. Parameters ---------- gamma : array A matrix of shap...
3cbe9625ad16c14a743382ba5a54b111082dedfe
73,409
def STOCH(data: xr.DataArray, fastk_period: int = 5, slowk_period: int = 3, slowk_matype: int = 0, slowd_period: int = 3, slowd_matype: int = 0) -> xr.DataArray: """ Stochastic (Momentum Indicators) Input: data: [high, low, close] Parameters: fastk_period: 5...
bb497649d36008b3cbd3df34caed13e0a1aa964a
73,410
from ecommerce.models import Product from hubspot.serializers import ProductSerializer def make_product_sync_message(product_id): """ Create the body of a sync message for a product. Args: product_id (int): Product id Returns: list: dict containing serializable sync-message data for ...
ed9f5512fd3f15169b829f57fee3334bb3e7a5fe
73,411
def generate_xy(number_pixels, center=0.0 * u.arcsec, pixel_size=1.0 * u.arcsec): """ Generate the x or y coordinates given the number of pixels, center and pixel size. Parameters ---------- number_pixels : `int` Number of pixels center : `float`, optional Center coordinates ...
e43d9fe3d0601453472c335db29ab240ee8c7652
73,412
def matched_modifiers(g, n, modifiers): """ returns the set of predecessors of node 'n' that are of a category contained in 'modifiers' """ pred = g.predecessors(n) if not pred: return False pcats = [] for p in pred: pcats.extend(p.getCategory()) return set(pcats).in...
d58453fa40271cad95ba9845026c17c2cc1025af
73,413
def new_matrix_input(): """Логика генерации новой матрицы""" n = int(input("Введите кол-во строк в матрице -> ")) m = int(input("Введите кол-во столбцов в матрице -> ")) # Генерируем matrix1 = matrix_gen(n, m) matrix2 = matrix_gen(m, n) # Пишем в файлы matrix_writer(matrix1, MATRIX1_FI...
0a3bc38edd90eb104e5a53252e1caeb2c1f53499
73,414
def _layout_to_matrix(layout): """Create the adjacency matrix for the tree specified by the given layout (level sequence).""" result = [[0] * len(layout) for i in range(len(layout))] stack = [] for i in range(len(layout)): i_level = layout[i] if stack: j = stack[-1] ...
cd27cad3a7ab6f34ea2be13e5617a34dbbba834f
73,415
from typing import Type def get_alg_dataset(alg_cls: Type[Algorithm]) -> Dataset: """Return an instance of the dataset for an algorithm.""" settings = _get_alg_settings(alg_cls)['dataset'] if isinstance(settings, tuple): (cls, kwargs) = settings else: (cls, kwargs) = (settings, {}) ...
1e4814f59abb85bb3918ae63a5562a20fad78a10
73,416
import click def email_arg(required, email="email", metavar="[EMAIL]", nargs=1): """ Email positional argument standard definition. Use as decorator for commands. """ return click.argument(email, metavar=metavar, nargs=nargs, type=str, required=required)
26e51c44f1109c0f690f243ee9d40de959570b08
73,417
def simplify_dataset_name(dataset_name): """In a couple of cases (BraTS and MURA) the dataset name is not quite correct because of a mistake made earlier in the pipeline. This function transforms the dataset names into a more readable format. Args: dataset_name (string): name of dataset to sim...
af0e504df0af2f250c716fb4f797970f31cbb1e1
73,418
def read_graph(filepath, format='edgelist') -> Graph: """Reads a graph from an edge list file and returns an igraph Graph object. Parameters ---------- filepath : str Path to the edge list file. format : str Format of the input file, e.g. 'edgelist', 'pajek',... Returns ---...
2db0a5d6af99eb76aeec84a2085f88e54084879e
73,420
def read_img(components): """ Loads image from meta.img_path. Assigns the image to the field img of the same meta instance. :param components: components :return: updated components """ img_buf = open(components[0], 'rb').read() if not img_buf: raise Exception('image not read,...
016628a0f167cac7a4efa6da20e8e6d8c0504523
73,421
import requests from bs4 import BeautifulSoup def get_problems() -> list: """Get the list of problems Returns: list: Problems """ problems = [] website = requests.get(view_url) soup = BeautifulSoup(website.text, 'lxml') for i in soup.find_all('span'): try: ...
3a2ceb643edb22d09dee76a62e7c23269986af01
73,422
import logging def NN_aggregate_model_updates(clients_model_updates, global_model_parameters, update_rate, verbose, aggregation_type): """ For each layer average the gradient and add it to the global model layer with some update_rate """ agg_weights = [] clients_model_updates_copy = list(clients_m...
9fdcdc0ccd539345708a41f0c6f170c7bb2ee86c
73,423
from datetime import datetime def report_top_month(request): """ TOP 30 users-downloaders """ today = datetime.datetime.combine(datetime.date.today(), datetime.time()) last_mon = today - datetime.timedelta(days=today.weekday(), weeks=1) last_mon = int(datetime.datetime.timestamp(last_mon)) ...
35201f0a0509bc1d78d58cf5d90407b16dbb0720
73,424
import json def api_products_delete(barcode): """ API method : Deletes an item from the products table. Outputs JSON. Returns the latest version of the grocery list. JSON format : - {"status": ...} Possible return status : - OK (200) - DELETE ERROR (400) """ # AJAX Auth che...
5a32d5e203e7d4a76c6a12d6bb2375d030bf6022
73,425
def cpu_mandel(x, y, max_iters): """ Given the real and imaginary parts of a complex number, determine if it is a candidate for membership in the Mandelbrot set given a fixed number of iterations. """ c = complex(x, y) z = 0.0j for i in range(max_iters): z = z * z + c if ...
30d0b637a924670e4038ba9f68c20c943de0e009
73,427
def get_model(model_class): """This functio nis for building the model for mlp and lstm""" model = Sequential() if model_class == 'mlp' or model_class == 'mlp_angle' : # Add a hidden layer with ReLU activation model.add(Dense(1024, input_dim=input_dim, activation='rel...
5a2b568ea1f02d9b007bc92d59e8535bf478b275
73,428
def get_test_data_path(): """ Returns the path to test datasets, terminated with separator. Test-related data are kept in tests folder in "data". Based on function by Yaroslav Halchenko used in Neurosynth Python package. """ return abspath(join(dirname(__file__), "data") + sep)
22325d16fd6eafb6acfa7564918cf3941dec803d
73,429
from typing import Tuple def load_dataset(dataset_path: str, mode: str) -> Tuple[list, list, list, list]: """ Divide all audio paths and transcripts into train and validate Args: dataset_path (str): path with audio and transcript mode (str): flag indication train or eval Returns: tra...
af18885c5cf9bc7b6831fae7574b520e5a55046f
73,430
def single_recurrence_goal(target, z_next, within, players, ij, aut): """Development harness for parameterized assumption construction.""" assert 'scheduler' not in players print('single recurrence goal: {ij}'.format(ij=ij)) i, j = ij assert i >= 0, i assert j >= 0, j phase = '{i}_{j}'.forma...
5082ee4c4e07be296e7bd15d03e3930ebc0c6b20
73,431
def upload_file(project_id): """Upload file (POST) - Upload a data file to the project's filestore. """ # The upload request may contain a file object or an Url from where to # download the data. if request.files and 'file' in request.files: file = request.files['file'] # A browser m...
a9ab038b9e65e8abc0a71904a9c75a282bc13df6
73,432
def colormap_to_rgb(raster): """" The function is designed to work with single band image service that has internal colormap. It will convert the image into a three-band 8-bit RGB raster. This function takes no arguments except an input raster. For qualified image service, there are two situations ...
6174c519a854ff15cf5bc8cc17cafee6ebacb4df
73,433
import numpy def filled_circle(shape, radius, center=None): """ creates a circle mask of defined radius and center in an array of the provided shape with value of 0 inside the circle and 1 outside the circle """ r2 = radius*radius if center is None: ### set to center of array center = (shape[0]-1)/2.0,(sh...
ad7f252d5b225ccd4496843ee8ebbd71ab2196da
73,434
def binary_labelisation_from_markers(tree, object_marker, background_marker, leaf_graph=None): """ Given two binary markers :math:`o` (object) and :math:`b` (background) (given by their indicator functions) on the leaves of a tree :math:`T`, the corresponding binary labelization of the leaves of :math:`T` i...
6861b2411f99f5accc02726eb132afde3c3ce442
73,435
def get_pointcloud_bbox(pointcloud: np.ndarray) -> AABB: """ Create a mitsuba bounding box by using min and max on the input ndarray :param pointcloud: The pointcloud (Nx3) to calculate the bounding box from :return: The bounding box around the given pointcloud """ min_values = np.min(pointcloud...
f0070a2ff339a7bd72052f7933ac29cca05bd949
73,436
def arange(start, stop=None, step=1, dtype=None, ctx=None): """Return evenly spaced values within a given interval. Values are generated within the half-open interval ``[start, stop)`` (in other words, the interval including `start` but excluding `stop`). For integer arguments the function is equivalen...
93c2698032b9f0864bcf3b3537cbba2914a02c61
73,437
def U_np(angle1, angle2, angle3, invert): """Return numpy array with U gate (IBM).""" gate = np.zeros(4, dtype=complex).reshape(2, 2) cosan = np.cos(angle1/2) sinan = np.sin(angle1/2) mult = 1 if invert: mult = -1 gate[0, 0] = cosan if not invert: gate[0, 1] = -sinan * np...
eaf81ac490d9cdb8d97410737bae2caa4ff370cc
73,438
def log_log(xarr, yarr, *args): """Given x and y, returns log(x) and log(y) arrays. """ x = np.array(list(map(lambda xi: np.log(abs(xi)), xarr))) y = np.array(list(map(lambda yi: np.log(abs(yi)), yarr))) return (x, y) + args
5a3dcc7340468cfed5bbfb06c300769ac5eb2460
73,439
import google def get_local_user(network, site_id): """Get the local user_instance from the social details.""" network_check = models.User.oauth_site == network id_check = models.User.social_id == site_id existing_user = (models.User.query .filter(network_check) ...
56b8b0851f27d12b73948fb7bc9f72405a71ce65
73,440
def insertTensor(tree, graph, dims=[2, 2, 2], dtype='VX_TYPE_UINT8', fpp="0"): """ Insert a tensor """ tensor = etree.Element(etree.QName(tree, stensor)) ref = getNewRef() updateAttributes(tensor, dict(reference=ref, number_of_dims=len(dims), data_type=dtype, fi...
deb628d797d26714bd5e11602e3b1695268b8a10
73,441
import random def seq_aleatoire(l_ascii): """Mélange une liste. Cette fonction permet de générer une séquence alétoire de même composition que celle passée en argument. Parameters ---------- l_ascii : list `l_ascii` est une liste d'entiers. Returns ------- l_ascii : list...
eb9c3e1d5182c4a359566e8efd1174934f415c4b
73,442
def pos_wise_FFN_module(x, n_inner=2048, keep_prob=0.9, is_training=False, scope='PW_FNN_module'): """ postion wise Feed forward networks sublayer module """ with tf.variable_scope(scope): n_hidds = x.get_sh...
b4cd7173337c3bb3a4ebf8ae49a3a58f87cd8e95
73,443
def maketrans(fromstr, tostr): """maketrans(frm, to) -> string Return a translation table (a string of 256 bytes long) suitable for use in string.translate. The strings frm and to must be of the same length. """ if len(fromstr) != len(tostr): raise ValueError, "maketrans arguments mus...
38be4d42c1e671fb04b693055b355b501490422d
73,444