content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def blur(img): """ :param img: the original image :return: img, the blurred image This function make image blurred """ old_image = img blurred = SimpleImage.blank(old_image.width, old_image.height) for y in range(old_image.height): for x in range(old_image.width): cou...
6ddd8dd896b419d0d776aa36f249af93e5049a73
34,100
from sys import version def delete_all_cache(package): """ Remove cached data, this will delete entire cache folder. """ _delete_macos(package) home, _ = _get_home(package) try: _delete_folder(home) with open(version_path, 'w') as fopen: fopen.write(version) ...
ceeeaa296484cfdf24386ccfaff70f333a0c3583
34,101
def _validator(record_type, ref): """ Create a DataValidator instance. """ if record_type == mds.STATUS_CHANGES: return mds.DataValidator.status_changes(ref=ref) elif record_type == mds.TRIPS: return mds.DataValidator.trips(ref=ref) else: raise ValueError(f"Invalid record...
5e5eb3288304ba9a3fa7635d698370e041a731bd
34,102
def create_gif(pictures: list, watermark: str, user_id: int, private=0) -> BytesIO: """ Creates gif with watermark from list of PIL images and adds it to database. Returns BytesIO object :param pictures: list of PIL.Image objects :param watermark: watermark text, takes from user name ...
ff5fd0aeaf9e0b02ee99e7f75624d2a1340c0272
34,103
import torch import itertools import time import sys def td3Student(env_fn, actor_critic=td3_core.MLPActorCritic, ac_kwargs=dict(), seed=0, steps_per_epoch=4000, epochs=100, replay_size=int(1e6), gamma=0.99, polyak=0.995, pi_lr=1e-3, q_lr=1e-3, batch_size=100, start_steps=10000, update_after=1...
ea1eb5b0dd73c83cd38218cc4c497a28851291e2
34,104
import logging def getLogger(logFile='', logLevel='DEBUG', logOutName='api.log', rotateTime='midnight', backupCount=10): """ Get new Logger for logging """ levels = {'FATAL': logging.FATAL, 'ERROR': logging.ERROR, 'WARNING': logging.WARNING, 'INFO': logging.INFO, ...
7557c654a71154d74f0252065473e71d42bff0b9
34,105
def ret_comb_index(bi_tot, get_indices=False, isotope=None): """ :param bi_tot: :return: """ bi_1 = int(str(bi_tot)[-2:]) bi_2 = int(str(bi_tot)[0:-2]) if get_indices: return (bi_1, bi_2 - 1, isotope) else: return (bi_1, bi_2 - 1)
5647b273d4807aa876f6cd3bd28d287f60cf6296
34,106
def run_list(arg): """ Convert a :class:`~list` to a `RUN` instruction. :param arg: List that represents instruction arguments. :return: Fully-qualified `RUN` instruction. """ indent = len(run_list.instruction_name) + 1 return formatting.list_with_conditional_command_line_breaks(arg, indent...
a2652abed5df8ec5bcdc0df678a57b6d2425fe49
34,107
def count_loops(G): """ Count the loop edges in a graph. Parameters ---------- G : NetworkX graph """ loops = get_loops(G) return len(loops)
58fdcf8aac09fa7a52d59f9fbbcba170313408ab
34,108
async def post_projectversion_toggle_ci(request): """ Toggles the ci enabled flag on a projectversion. --- description: Toggles the ci enabled flag on a projectversion. tags: - ProjectVersions consumes: - application/x-www-form-urlencoded parameters: - name: projectv...
f9c50607e90f0f910503b6557bd324ad3adba43e
34,109
def edit_item(category, item): """App route function to edit an item.""" # Verify user login. If not, redirect to login page. login_status = None if 'email' in login_session: login_status = True else: flash('Please log in.') return redirect(url_for('home')) # Query databa...
e8300e083da286544d58c5e4aaa59cdc126414ac
34,110
def sanity_check_gcon(): """Sanity check gcon.""" cmd = gcon_py + " --help" errmsg = gcon_py + " is not installed." execute(cmd=cmd, errmsg=errmsg) return gcon_py
11585da8701edc482ab2d0588f1d983d32b5e1c4
34,111
import os import sys def make_ddf(view_map, submissionNode, daf_name, make_condor=False, outdir=None): """ Make ddf files, and bonus condor file """ query_template = """PREFIX libraryOntology: <http://jumpgate.caltech.edu/wiki/LibraryOntology#> PREFIX submissionOntology: <http://jumpgate.caltech.edu/w...
b5fdaee52b288cdde8db9fa1b86cae49af4ee216
34,112
import requests import json def get_Cust_Bookings_Hours(request, *args, **kwargs): """Request Chart Points per Themes""" bookings_H_tmp = requests.get('http://127.0.0.1:5000/customer/bookings/hours').text bookings_Hours_list = json.loads(bookings_H_tmp) bookings_Hours = [ ['Heures', 'Nombre de...
9463cb31da46f751014a14d6daeb28df3d0c8cfe
34,113
import re def deprecated_version(filename, expression): """ Summary. Extract program version N-1. Args: :filename (str): Name of file contents searched for N-1 version num. :expression (str): Regex or string which matches deprecated version Returns: exact match, TYPE...
0b2dbae98f713a636f450225b7a1e04c47755562
34,114
import scenic.syntax.veneer as veneer # TODO improve import typing import numbers def canCoerceType(typeA, typeB): """Can values of typeA be coerced into typeB?""" if get_type_origin(typeA) is typing.Union: # only raise an error now if none of the possible types will work; # we'll do more careful checking at ru...
baa4f439a9699fc46c70980efe214ced132b7036
34,115
def judo_turnier(): """Show participants for judo turnier.""" participants = Participant.query.filter_by(user_id=current_user.id, event=EVENT_JUDO_TURNIER).all() form = ParticipantDeleteForm(request.form) return render_template('events/judo-turnier.html', ...
78614761f183d1280eeb80e08e17500fed62d25a
34,116
import os def _yamlfiles(zipfile, has_subdirs=False): """Helper to get a yaml file (according to POLICYD_VALID_EXTS extensions) and the infolist item from a zipfile. If the `has_subdirs` param is True, the the only yaml files that have a directory component are read, and then first part of the direct...
a964fff34705cfea7413a94ce9bf4ff7612e1651
34,117
def preprocess_mapper(features, params, lookup_table): """Model-specific preprocessing of features from the dataset.""" features["question_inputs"] = text_utils.build_text_inputs( text=features["question"], length=params["question_length"], lookup_table=lookup_table) features["context_inputs"] ...
5454cf1149982ddc3314fb9793123b16e70e1381
34,118
import logging def get_user_playlists(): """Return all of the user's playlists""" logging.info("fetching user playlists") url = "https://api.spotify.com/v1/me/playlists" return get_all_pages(url)
17d96f81ccf78cc0d9210968deb6a9550f82f34c
34,119
def set_circuit_ic_mrucc(n_qubits, v_n, a_n, c_n, DS, theta_list, ndim1, a2a): """ """ circuit = QuantumCircuit(n_qubits) if DS: circuit = icmr_ucc_singles(circuit,v_n, a_n, c_n, theta_list, 0) circuit = icmr_ucc_doubles(circuit,v_n, a_n, c_n, theta_list, ndim1, a2a) else: c...
7a3fc8474f07b926b49980b467cbb8c19a24d8b8
34,120
def dct2spatial(image): """ Rearrange DCT image from [H//8, W//8, 64] to [H,W] """ assert image.shape[2] == 64 block_view = (image.shape[0], image.shape[1], 8, 8) image_shape = (image.shape[0] * 8, image.shape[1] * 8) block_permute = 0, 2, 1, 3 result = image.reshape(block_view).transp...
a1052b2f851a59eabb28c672f01547b5c4797bbc
34,121
def theta2rotx(theta: np.ndarray) -> np.ndarray: """ Rx = [[1, 0, 0], [0, c(t), -s(t)], [0, s(t), c(t)]] :param theta: angle(s) in degrees, positive is counterclockwise :return: rotation_matrices """ theta = np.deg2rad(np.asarray(theta).reshape(-1)) rotation_matrices = np...
48aaa4a84b49495f2106fba7dc70749865001811
34,122
import os import PIL import io def resize_image(ratio, path, image_format=None): """ thumbnail est une imagette :param ratio:entier : Taux de réduction :param path: string : chemin du fichier image à réduire . :param image_format: string : extension indiquant le type de l'image (PPM, PNG, JPE...
6aba540abeabd3ca9498611a8fefde653da3a6cb
34,123
from datetime import datetime def json_serializer(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, datetime): # Serialize datetime as the ISO formatted string serial = obj.isoformat() return serial raise TypeError("Type not serializa...
dfc2ebf9f254cd9f3723144b4d97839159a428f7
34,124
import torch import os import nibabel as nib def save_as_pt(input_img): """ This function is to transfer nii.gz file into .pt format, in order to train the classifiers model more efficient when loading the data. :param input_img: :return: """ image_array = nib.load(input_img).get_fdata() ...
ca3a5864ee9adaa9a1280b7b050366fba26a5b73
34,125
def leaves_f(prog, typ): """Doc.""" return list(filter(lambda it: type(it), leaves(prog)))
4119e92c2bd5c910b5a9b5badca69fd09dedc429
34,126
def imshow_xy(axes, coord, data, xy_limits=None, xy_pad=0.02, add_lines=False, step_kw=None, line_kw=None, **kwargs): """ Show data as an image in ax, with slices at x and y in the subplots axy and axx. img = ax.imshow(data) step_x = axx.step(data[coord[1], :...
e8727c5a7c3dd114e6beda1c171156f636e08b28
34,127
import re def create_endpoint(project_id: str, region: str, endpoint_name: str) -> str: """ Create an endpoint on Vertex AI :param project_id: :param region: :param endpoint_name: :return: """ try: endpoint = aiplatform.Endpoint.create(display_name=endpoint_name, project=proje...
383fb8961050e31270f5f4c9b68008864ce34ae9
34,128
import logging def get_warning_logger() -> logging.Logger: """ Set up a logger to capture warnings and log them """ logging.captureWarnings(True) warning_logger = logging.getLogger('py.warnings') if warning_logger.handlers: warning_logger.handlers = [] return warning_logger
5cdf76ff66963851715b3302c02681340d2f6a72
34,129
def check_type_match(actual_val, expected_val) -> bool: """Check actual_val matches type of expected_val The exception here is that expected_val can be float, and in that case actual_val can be either int or float Args: actual_val (Any): Actual type expected_val (Any): Expe...
90f74b1978deb0c55b65a4faa2569f54fe6bceee
34,130
from typing import Callable from typing import Tuple def _single_step_smart_generalized_leapfrog( grad_log_posterior: Callable, metric: Callable, grad_metric: Callable, grad_log_posterior_and_metric_and_grad_metric: Callable, zo: Tuple[np.ndarray], step_size: float, ...
f091280bcda175ec0b1b399825a484e5d725c82a
34,131
def real_sph_harm(l, zero_m_only=True, spherical_coordinates=True): """ Computes formula strings of the the real part of the spherical harmonics up to order l (excluded). Variables are either cartesian coordinates x,y,z on the unit sphere or spherical coordinates phi and theta. """ if not zero_m_onl...
cff7053e02600934f8b00a4d74fffeb6223fc1d3
34,132
def drsky(x, ecc, omega, inc): """Function whose roots we wish to find to obtain time of secondary (and primary) eclipse(s) When one takes the derivative of equation (5) in Winn (2010; https://arxiv.org/abs/1001.2010v5), and equates that to zero (to find the minimum/maximum of said function), one g...
03238e267760e081f4f69367e7e37f46877072cf
34,133
from typing import List import types from typing import Iterator from typing import Tuple from typing import Dict from typing import Any def ComputeQueryBasedMetrics( # pylint: disable=invalid-name extracts: beam.pvalue.PCollection, prediction_key: str, query_id: str, combine_fns: List[beam.CombineFn...
ee3907109a8ff0c67f02e5d9b2296c3955bd501f
34,134
def get_brier_scores(at_time_intervals, censored_indicator=1.0): """Construct Brier score metrics for survival probability predictions.""" metrics = [] for t in at_time_intervals: metric = partial( brier_score, t=t, censored_indicator=censored_indicator) metric.__name__ = 'bs_at_...
58a23d2c7706761a68bfd375b20400dc075a4c96
34,135
def create_id_maps(session): """ Create a large universal map of maps that carries common items like "Allegiance" or "Government" onto the id expected to be inserted into the db. Returns: A adict of dicts that ultimately points to integer ids in the db. """ maps = { 'Allegiance': {x.edd...
ae5f30fc4338c61b26087b3d6d5f30d87e7b97cd
34,136
def _box_without_row_and_column_of(row, col, width, height): """Return some coordinates in the square of (col, row) as a list. The coordinates in the same row and column are removed. This is an internal function and should not be used outside of the coordinates module. """ grid_x = col - (col ...
e7dc91611788fb5e22a70d30edcda5708f751085
34,137
def fieldtype(field): """Get the type of a django form field (thus helps you know what class to apply to it)""" return field.field.widget.__class__.__name__
e2d68cbdd72219de1a23095100c054a46c6c191b
34,138
def options(parser, help_menu=False): """ Summary. parse cli parameter options Returns: TYPE: argparse object, parser argument set """ parser.add_argument("-b", "--build", dest='build', default=False, action='store_true', required=False) parser.add_argument("-D", "--debug", de...
f4311106d848c150cefce6141ac9b04d30de5ea9
34,139
def fitToIntervals(areas: list, num_of_bins: int): """ fitting the area of each contour to the suitable interval. :param areas: a list of contour areas. :param num_of_bins: the number of intervals. :return: a list containing each suitable interval for a given area. """ intervals = findInter...
aa731e7ed298c55649242923a774e07da308b757
34,140
import argparse def parse_cmd_line(): """ Return True if a commnd-line option was run, else False """ HelpInformation = "kjv.py: Search, bookmark & browse the Bible." parse = argparse.ArgumentParser(usage="", description=HelpInformation) parse.add_argument( "-s", "--Sierra",type = int,met...
bb48a0763e747cda9f94d87752b9cde976ba6409
34,141
def compute_reduced_reciprocal(init_approx, vy, num_iteration): """ Compute the correctly rounded approximation of 1.0 / vy using @p init_approx as starting point and execution @p num_iteration Newton-Raphson iteration(s) """ current_approx = init_approx inv_iteration_list = [] # comput...
6c694c168c77d6181c4a4e364734421ace1167f8
34,142
def topology_deployment_locations_name_get(name): """ get details of a deployment location Returns information for the specified deployment location :param name: Unique name for the location requested :type name: str :rtype: InlineResponse20010 """ osmVim = OsmClient().getVim() vim...
7d07f2b425ae72f5a75529bac459194644bd6540
34,143
def get_team_repo(remote_url): """ Takes remote URL (e.g., `git@github.com:mozilla/fireplace.git`) and returns team/repo pair (e.g., `mozilla/fireplace`). """ if ':' not in remote_url: return remote_url return remote_url.split(':')[1].replace('.git', '')
5e0120881557e9d95b697ab194fd7a8e8a84c68d
34,144
def ajax_request(func): """ If view returned serializable dict, returns JSONResponse with this dict as content. example: @ajax_request def my_view(request): news = News.objects.all() news_titles = [entry.title for entry in news] return {'news_tit...
a672e3164af2c282fa301d351434ce863e7b2204
34,145
def load_collection_from_file(resource, filename, content_type=None): """ Creates a new collection for the registered resource and calls `load_into_collection_from_file` with it. """ coll = create_staging_collection(resource) load_into_collection_from_file(coll, filename, ...
c85eb82ee3633c69bef5ceb8b2954ea0fd700798
34,146
import os def test_data_folder(request): """ This fixture returns path to folder with shared test resources among asr tests """ data_dir = os.path.join(script_dir, "testdata") if not os.path.exists(data_dir): os.mkdir(data_dir) return data_dir
d35121cf34f6d52b3e73fdce8d0e36adf4864bb9
34,147
import requests import time def get_fxa_token(*, code=None, refresh_token=None, config=None): """Given an FxA access code or refresh token, return dict from FxA /token endpoint (https://git.io/JJZww). Should at least contain `access_token` and `id_token` keys. """ assert config, 'config dict must ...
d0e0b70fd4b6adc7f944b68eb0788b82eed6344d
34,148
def merge_connected_components(conn_components, ingoing, outgoing): """ Merge the unconnected connected components Parameters ------------- conn_components Connected components ingoing Ingoing dictionary outgoing Outgoing dictionary Returns ------------- ...
15dda42103aab964a9a67ca763e17ba63d552457
34,149
def split_indices_with_unseen_target_geo_in_test(loads, geo_ids, labels, bias_train=False, seed=None, debug=True): """ Args: loads: (list) train-test-val split percentages strictly positive and must sum to...
904d200954162a6abb8d1d00e44cf66574c71eb2
34,150
def create_doc_index(ui_mat_rdd, export=False): """ Indexes the docs and saves the index in a dictionary. The indexes are then saved to disk. The indexing allows us to use internal integer IDs for the users and documents instead of real IDs. The internal IDs are used to index the different model matrices efficie...
97874b0effaa93b35760330abaa1fc23628389d6
34,151
def read_markers_from_file(filepath, ext=None): """ Read a cell marker file from accepted file formats. Currently supported: csv, tsv. See doc for formatting. """ # Get extension if ext is None: ext = filepath.split('.')[-1] dict_format = {"csv":read_markers_csv, "tsv":read_marke...
5c2a34bf3d568d1b0f9e81c23d23eba315059ee3
34,152
def get_user_id_from_email(email): """ Pulls the user from the MDB (or dies trying). Returns its email. """ u = utils.mdb.users.find_one({'login': email.lower().strip()}) if u is None: raise AttributeError("Could not find user data for %s" % email) return u['_id']
c81d9d62bc3ecd9d37afef3f38b5735b5bb0215b
34,153
def _object_exists(key): """Verify if a given key (path) exists, using the S3 API.""" try: app.s3.head_object(Bucket=app.config.get("AWS_S3_BUCKET_NAME"), Key=key) except ClientError as e: if e.response["Error"]["Code"] == "404": return False ra...
65ca7932412f988518f40a6830d512049e40fe31
34,154
def dpgmm_predict(data:pd.DataFrame, code=None, indices:pd.DataFrame=None,) -> np.ndarray: """ (假设)我们对这条行情的走势一无所知,使用机器学习可以快速的识别出走势,划分出波浪。 DPGMM聚类 将整条行情大致分块,这个随着时间变化会有轻微抖动。 所以不适合做精确买卖点控制。但是作为趋势判断已经足够了。 """ sub_offest = 0 nextsub_first = sub_first = 0 ...
b12365f50a498d2ece6be65a0a284aad9c235274
34,155
from typing import List def list_ep(server: Server, path: str, r_type: OT = OT.DOMAIN, scope: EPScope = None) -> List[str]: """ List elements under an object fitting a type. :param Server server: server object :param str path: path to object :param OT r_type: type of ep to return (default is doma...
ccf90a435b72e4e822ef2c580304c889bc4f4136
34,156
import re def check_if_partial(comments): """ Checks if comments contain info about Dat being a part of a series of dats (i.e. two part entropy scans where first part is wide and second part is narrow with more repeats) Args: comments (string): Sweeplogs comments (where info on part#of# shoul...
6f565bae6fe1cf5da4a11e0d511a25daa07aadd1
34,157
import json import os import tempfile def create_v1_session(): # noqa: E501 """POST /v1/session Creates a new boot session. # noqa: E501 :param session: A JSON object for creating sessions :type session: dict | bytes :rtype: Session """ if connexion.request.is_json: LOGGER.debug(...
8db8e9dc9d5bd02c344eec097a970e8fa43b0123
34,158
def cardChunk(key, chunk): """ Parse Card Chunk Method """ for line in chunk: values = [] sline = line.strip().split() for idx in range(1, len(sline)): values.append(sline[idx]) return {'card': sline[0], 'values': values}
84b8a12f701078f2ebcf19a5c1902b1e370b16e6
34,159
def update_outline(outline, filename=None, message=None): """ Updates the the outline from active instances in the workspace """ if not message: message = "Automated update via presalytics.lib.tools.workflows.update_outline()" update_components(filename=filename) for p in range(0, ...
3582d47b641c4e554f2b2f0e38110fd98343476c
34,160
def slave_hub_factory(config, comm_class, comm_config): """Factory of management bus slave hub instances Args: config (dict): management bus master config comm_class (string): communication backend. Unused, ZMQRedis is always used comm_config (dict): config of the communicat...
b421c065158aa3e7fd07fc28ccdd72ffc24045ec
34,161
def rgb565_to_rgb(arr, out=None): """ Convert a numpy :class:`~numpy.ndarray` in RGB565 format (unsigned 16-bit values with 5 bits for red and blue, and 6 bits for green laid out RRRRRGGGGGGBBBBB) to RGB format (structured floating-point type with 3 values each between 0 and 1). """ check_r...
5c660169cdfd47a0d513a833356c82557ff636bb
34,162
def run_highstate_tests(saltenv="base"): """ Lookup top files for minion, pass results to wrapped run_state_tests for copy and run """ top_states = __salt__["state.show_top"]().get(saltenv) state_string = ",".join(top_states) ret = run_state_tests(state_string, saltenv) return ret
3e12d102a44e8233eb539c1636f19eebb23da266
34,163
def varianceOfLaplacian(img): """ Compute the Laplacian of the image and then return the focus measure, which is simply the variance of the Laplacian. Source: A.Rosebrock, https://www.pyimagesearch.com/2015/09/07/blur-detection-with-opencv/ """ return cv2.Laplacian(img, cv2.CV_64F).var()
8a80c40f24c1a282ae7a46c521e4cb3a975451ee
34,164
import argparse import sys def main(): """ Parses the command-line args, and calls run. """ parser = argparse.ArgumentParser( description='A pipeline that generates analysis pipelines.') parser.add_argument('input', nargs='?', help='A valid metapipe configuration file.') par...
4524a74da097ed66f0b4652737f677fedee41630
34,165
def show(tournament, participant_id, **params): """Retrieve a single participant record for a tournament.""" return api.fetch_and_parse( "GET", "tournaments/%s/participants/%s" % (tournament, participant_id), **params )
bf1e43ab2b071343405a09659580d5d8311d0dff
34,166
def logsubexp(A, B): """ Numerically stable log(exp(A) - exp(B)) """ # Just adding an epsilon here does not work: the optimizer moves it out result = A + tt.log(1 - tt.clip(tt.exp(B - A), epsilon, 1-epsilon)) return result
0bd07fec6cfe3247e7dffd0af1794306f34601f1
34,167
import collections def sort_dict(d: dict, by: str = 'key', allow_duplicates: bool = True) -> collections.OrderedDict: """ Sort a dictionary by key or value. The function relies on https://docs.python.org/3/library/collections.html#collections.OrderedDict . The dulicated are determin...
59ea66e44b9a41161e38e243f49e5a20df20093f
34,168
def read_file_info(filename): """ Read an info file. Parameters ---------- filename : string The name of file with cross-sectional area and length information. Returns ------- info : dict The values of cross-sectional area and length of the specimens, """ fd = o...
c3f8c106126b45845c1202b34b19cad2ce2ae036
34,169
def search_to_new_ids(index, query, k): """ this function maps the result ids to the ones ordered by the ivf clusters to be used along with a re-ordered metadata """ distances, indices = index.search(query, k) opq2 = faiss.downcast_VectorTransform(index.chain.at(0)) xq = opq2.apply(query) ...
62fc04b67bfa3aaf6ceed5a5f8bd65e1e7783cc9
34,170
import itertools def build_simplex_lattice(factor_count, model_order = ModelOrder.quadratic): """Builds a Simplex Lattice mixture design. This design can be used for 2 to 30 components. A simplex-lattice mixture design of degree m consists of m+1 points of equally spaced values between 0 and 1 for ea...
9a6861a211b6829b971cf76ab8f1bbcb2bb668ae
34,171
def position_specializations(position_block): """ :param bs4.Tag position_block: position block :return: list """ position_block = position_block.find("div", {"class": "bloko-gap bloko-gap_bottom"}) profarea_name = position_block.find("span", {"data-qa": "resume-block-specialization-category"})...
c37a43b2c139780d0bcb0db2cb758165d155a526
34,172
def GetElement(layers, locations): """ Return the node(s) at the location(s) in the given layer(s). This function works for fixed grid layers only. * If layers contains a single GID and locations is a single 2-element array giving a grid location, return a list of GIDs of layer elements at...
6fecffa20aa9d4722153c50572c9ded26035c1f3
34,173
def create_sampling_strategy(param_variation_model, sampling_strategy_configuration): """ A factory method that creates a memosampler.strategies.SamplingStrategy object from a memosampler.sampler.ParameterVariationModel and a memomodel.SamplingStrategy configuration obje...
f93451eb1b3739ac2985bd4a2b8bb84ed0b6f9f5
34,174
def json_to_hps(dct): """Translate the params dict to HyperparameterSpace object. :param dict dct: params dict. :return: HyperparameterSpace. :rtype: HyperparameterSpace or None """ if "hyperparameters" in dct: hps = HyperparameterSpace() for hp_dict in dct["hyperparameters"]: ...
0f80da7d4fb5d3d548cc23edf7761976db727654
34,175
def phone_number(update: Update, context: CallbackContext): """Добавляет номер телефона в контекст пользователя и предлагает ввести ИНН""" logger.info(f"User with chat_id {update.effective_user.id} sent phone number [{update.message.text}]") context.user_data[State.PHONE_NUMBER] = update.message.text ...
b41cebc8b47e9e3ef729ddd7ebea560f143be071
34,176
from bob.io.base.test_utils import datafile from nose.plugins.skip import SkipTest import functools import os def db_available(test): """Decorator for detecting if OpenCV/Python bindings are available""" @functools.wraps(test) def wrapper(*args, **kwargs): dbfile = datafile("db.sql3", __name__, None) i...
4a2b8614db1b7744e505613b494beaa9803f6f96
34,177
from typing import Optional from typing import Union def downsample_adata(adata: AnnData, mode: str = 'total', n_cells: Optional[int] = None, by: Optional[str] = None, balance_cell_type: bool = False, random_state...
d1de9ac6c347750ed4ebfb1b8f870b8bc613f20d
34,178
def parse_blob(value, offset=0, **kwargs): """Return a blob from offset in value.""" size = calcsize('>i') length = unpack_from('>i', value, offset)[0] data = unpack_from('>%iQ' % length, value, offset + size) return data, padded(length, 8)
855b55394d8fbe5a3e05e98997185d87051b56a2
34,179
from datetime import datetime def _get_now(utc: bool = False) -> datetime.datetime: # pragma: nocover """Workaround over datetime C module to be able to mock & patch in tests. """ if utc: return datetime.datetime.utcnow() return datetime.datetime.now()
7b71266bf46d464bb8515d5552752f2b7739262e
34,180
def dilation(image, selem, out=None, shift_x=False, shift_y=False): """Return greyscale morphological dilation of an image. Morphological dilation sets a pixel at (i,j) to the maximum over all pixels in the neighborhood centered at (i,j). Dilation enlarges bright regions and shrinks dark regions. ...
2485ddf865f4476dc0c46f89bc789948d9c47153
34,181
def randn(*args): """Returns samples from a normal distribution. Uses `tf.random_normal`. Args: *args: The shape of the output array. Returns: An ndarray with shape `args` and dtype `float64`. """ # TODO(wangpeng): Use new stateful RNG if utils.isscalar(args): args = (args,) return utils....
4478cb766e3458ebe7fea5a6159f9be8d4109f24
34,182
def nice_layer_name(weight_key): """Takes a tuple like ('weights', 2) and returns a nice string like "2nd layer weights" for use in plots and legends.""" return "Layer {num} {name}".format(num=weight_key[1] + 1, name=weight_key[0])
c88dd554c2a3cf35e6d6e96131833738c19766ac
34,183
def categories(request, structure_slug, structure): """ Retrieves structure categories list :type structure_slug: String :type structure: OrganizationalStructure (from @is_manager) :param structure_slug: structure slug :param structure: structure object (from @is_manager) :return: render ...
c322b754de2ed36e98088a1d494f807589d1fbc2
34,184
def checaDiagonal3D4( tabuleiro ): """ Checa se todos os elementos da diagonal 3D 4 (decrescente|crescente) são iguais a 'X' ou 'O', retornando o caractere em caso afirmativo e retornando '' caso contrário """ if tabuleiro[0][3][0] == 'X' and tabuleiro[1][2][1] == 'X' and ...
09453db75d6ea2b8018bdfaf488811c6a802daa4
34,185
def do_quantize_training_on_graphdef(input_graph, num_bits): """A general quantization scheme is being developed in `tf.contrib.quantize`. Consider using that instead, though since it is in the tf.contrib namespace, it is not subject to backward compatibility guarantees. Args: input_graph: A `GraphDef`. ...
868a2c67d7c69270039af69e82110951a987480c
34,186
from typing import List from typing import Tuple def get_session_triplets( sessions: List[int], match_types: List[int] ) -> Tuple[List[int], List[int], List[int]]: """Generate all possible triplets for each session. :param sessions: A list of integers denoting session label :param match_types: A list...
39992557bc788f4b8bb5248cd66f56bf4276d99c
34,187
def _rotation_matrix_hme_to_hee(hmeframe): """ Return the rotation matrix from HME to HEE at the same observation time """ # Get the Sun-Earth vector sun_earth = HCRS(_sun_earth_icrf(hmeframe.obstime), obstime=hmeframe.obstime) sun_earth_hme = sun_earth.transform_to(hmeframe).cartesian # Ro...
157378316058b4898b9ecccb8acf673c4170c03b
34,188
def get_image(microscopy_collection, series): """Return microscopy image.""" image = microscopy_collection.image(s=series) image = image[:, :, 0] return image
d95b213c8db49e89d2bcaa3f7b69c0f4d546ac1c
34,189
import pickle import subprocess def goToDirectory(alias): """go to a saved directory""" if not settings.platformCompatible(): return False data = pickle.load(open(settings.getDataFile(), "rb")) try: data[alias] except KeyError: speech.fail("Sorry, it doesn't look like you have saved " + alias + " yet.") ...
1886681ee7cd6f0c01e6c058560dcbc5b7437f58
34,190
def process_aa_snvs(aa_snv_dict, name, defs): """ Parameters ---------- aa_snv_dict: dict name: str defs: pandas.DataFrame - genes or proteins dataframe from genes_and_proteins.py """ aa_snv = ( pd.DataFrame.from_dict(aa_snv_dict, orient="index", columns=["id"]) ....
f9dbf499bc7baf311e2c1063167e40570f40d218
34,191
def use_file(filename): """ Return a decorator which will parse a kicad file before running the test. """ def decorator(test_method): """ Add params to decorator function. """ @wraps(test_method) def wrapper(self): """ Parse file then run test. """ self.desi...
c381fa417ae3226f7a4a5bac3fa907821dd76876
34,192
def create_autoscaler(gce, mig, params): """ Create a new Autoscaler for a MIG. :param gce: An initialized GCE driver object. :type gce: :class: `GCENodeDriver` :param mig: An initialized GCEInstanceGroupManager. :type mig: :class: `GCEInstanceGroupManager` :param params: Dictionary of ...
1be818388aa48b70f4252937a4db44671d03581e
34,193
from typing import List def chromium_all(*, min_major_version: int = 90, min_minor_version: int = 40) -> List[str]: """get chrome versions""" resp = Request.get(CHROME_REP_URL) versions = RE_CHROMIUM.findall(resp) versions = [v for v in versions if len(v.split(".")) > 2 and (int(v.split(".")[-1]) >= m...
900e4b24417e3c778218614c65787931631d2fbd
34,194
def setup(hass, config): """Setup platfrom""" async def async_auto_scale(call): """Call auto scale service handler.""" await async_handle_auto_scale_service(hass, call) hass.services.register( DOMAIN, SERVICE_AUTO_SCALE, async_auto_scale, schema=AUTO_SCALE_S...
61cc3d2b0461bb78a745a53dee1dc5bfb1a4a75f
34,195
import argparse def parse_command_line_args(args): """Parse command line arguments. Args: args ([str]): List of command line arguments and flags. Returns (argparse.Namespace): Parsed arguments from argparse """ parser = argparse.ArgumentParser() parser.add_argument( ...
9cbc6c91e5c2f15baadb342a0e09e87e6be3da3b
34,196
from re import X from datetime import datetime def train_linear_clf(n_fits): """Called by the `/train` HTTP GET method in `logic.py` module. Parameters ---------- n_fits : int Number of partial fits applied to the linear estimator. Returns ------- dict measured_accuracy : float Accuracy ...
8430edf945d03e6c68ca1fe5944ed6957d4e3857
34,197
def list_joysticks(): """return list of all joystick names""" joysticks = get_all_joysticks() return [joy.get_name() for joy in joysticks]
a04e584fe5d35b21cde1b44274bb725ea95260bc
34,198
def kurtosis(inlist): """ Returns the kurtosis of a distribution, as defined in Numerical Recipies (alternate defn in CRC Standard Probability and Statistics, p.6.) Usage: lkurtosis(inlist) """ return moment(inlist, 4) / pow(moment(inlist, 2), 2.0)
e5df631d9d5d81ca9e2df8d7b7723eb723c696db
34,199