content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from datetime import datetime def testjob(request): """ handler for test job request Actual result from beanstalk instance: * testjob triggerd at 2019-11-14 01:02:00.105119 [headers] - Content-Type : application/json - User-Agent : aws-sqsd/2.4 - X-Aws-Sqsd-Msgid : 6998edf8-3f19-4c69-...
c2a751d64e76434248029ec1805265e80ef30661
31,500
import argparse def args_parser_test(): """ returns argument parser object used while testing a model """ parser = argparse.ArgumentParser() parser.add_argument('--architecture', type=str, metavar='arch', required=True, help='neural network architecture [vgg19, resnet50]') parser.add_argument('--dataset',type=...
77ce5f9cacd8cd535727fa35e8c9fb361324a29a
31,501
from datetime import datetime def todatetime(mydate): """ Convert the given thing to a datetime.datetime. This is intended mainly to be used with the mx.DateTime that psycopg sometimes returns, but could be extended in the future to take other types. """ if isinstance(mydate, datet...
10ce9e46f539c9d12b406d65fb8fd71d75d98191
31,502
from datetime import datetime def generate_datetime(time: str) -> datetime: """生成时间戳""" today: str = datetime.now().strftime("%Y%m%d") timestamp: str = f"{today} {time}" dt: datetime = parse_datetime(timestamp) return dt
f6fa6643c5f988a7e24cf807f987655803758479
31,503
def get_rgb_scores(arr_2d=None, truth=None): """ Returns a rgb image of pixelwise separation between ground truth and arr_2d (predicted image) with different color codes Easy when needed to inspect segmentation result against ground truth. :param arr_2d: :param truth: :return: """ ar...
7d5fff0ac76bf8326f9db8781221cfc7a098615d
31,504
def calClassMemProb(param, expVars, classAv): """ Function that calculates the class membership probabilities for each observation in the dataset. Parameters ---------- param : 1D numpy array of size nExpVars. Contains parameter values of class membership model. expVars : 2D num...
a77b1c6f7ec3e8379df1b91c804d0253a20898c5
31,505
from typing import List def detect_statistical_outliers( cloud_xyz: np.ndarray, k: int, std_factor: float = 3.0 ) -> List[int]: """ Determine the indexes of the points of cloud_xyz to filter. The removed points have mean distances with their k nearest neighbors that are greater than a distance thr...
2e48e207c831ceb8ee0f223565d2e3570eda6c4f
31,506
def collinear(cell1, cell2, column_test): """Determines whether the given cells are collinear along a dimension. Returns True if the given cells are in the same row (column_test=False) or in the same column (column_test=True). Args: cell1: The first geocell string. cell2: The second geocell string. ...
f79b34c5d1c8e4eed446334b1967f5e75a679e8a
31,507
def plasma_fractal(mapsize=512, wibbledecay=3): """Generate a heightmap using diamond-square algorithm. Modification of the algorithm in https://github.com/FLHerne/mapgen/blob/master/diamondsquare.py Args: mapsize: side length of the heightmap, must be a power of two. wibbledecay: integer, decay facto...
96457a0b00b74d269d266512188dfb4fab8d752c
31,508
import pwd import grp import time def stat_to_longname(st, filename): """ Some clients (FileZilla, I'm looking at you!) require 'longname' field of SSH2_FXP_NAME to be 'alike' to the output of ls -l. So, let's build it! Encoding side: unicode sandwich. """ try: n_link = str(s...
c0a4a58ec66f2af62cef9c3fa64c8332420bfe1c
31,509
def driver(): """ Make sure this driver returns the result. :return: result - Result of computation. """ _n = int(input()) arr = [] for i in range(_n): arr.append(input()) result = solve(_n, arr) print(result) return result
fcd11f88715a45805fa3c1629883fc5239a02a91
31,510
def load_element_different(properties, data): """ Load elements which include lists of different lengths based on the element's property-definitions. Parameters ------------ properties : dict Property definitions encoded in a dict where the property name is the key and the property ...
a6fe0a28bb5c05ee0a82db845b778ddc80e1bb8c
31,511
def start_survey(): """clears the session and starts the survey""" # QUESTION: flask session is used to store temporary information. for permanent data, use a database. # So what's the difference between using an empty list vs session. Is it just for non sens. data like user logged in or not? # QUESTI...
9a9cc9aba02f31af31143f4cc33e23c78ae61ec2
31,512
def page(token): """``page`` property validation.""" if token.type == 'ident': return 'auto' if token.lower_value == 'auto' else token.value
5b120a8548d2dbcbdb080d1f804e2b693da1e5c4
31,513
import os def create_fsns_label(image_dir, anno_file_dirs): """Get image path and annotation.""" if not os.path.isdir(image_dir): raise ValueError(f'Cannot find {image_dir} dataset path.') image_files_dict = {} image_anno_dict = {} images = [] img_id = 0 for anno_file_dir in ann...
346e5a331a03d205113327abbd4d29b9817cc96c
31,514
def index(): """ Gets the the weight data and displays it to the user. """ # Create a base query weight_data_query = Weight.query.filter_by(member=current_user).order_by(Weight.id.desc()) # Get all the weight data. all_weight_data = weight_data_query.all() # Get the last 5 data points f...
a812dd55c5d775bcff669feb4aa55b798b2042e8
31,515
def upload_binified_data(binified_data, error_handler, survey_id_dict): """ Takes in binified csv data and handles uploading/downloading+updating older data to/from S3 for each chunk. Returns a set of concatenations that have succeeded and can be removed. Returns the number of failed FTPS so...
8b4499f3e5a8539a0b0fb31b44a5fe06ce5fd16b
31,516
from enum import Enum def system_get_enum_values(enum): """Gets all values from a System.Enum instance. Parameters ---------- enum: System.Enum A Enum instance. Returns ------- list A list containing the values of the Enum instance """ return list(Enum.GetValues(e...
b440d5b5e3012a1708c88aea2a1bf1dc7fc02d18
31,517
def skip_leading_ws_with_indent(s,i,tab_width): """Skips leading whitespace and returns (i, indent), - i points after the whitespace - indent is the width of the whitespace, assuming tab_width wide tabs.""" count = 0 ; n = len(s) while i < n: ch = s[i] if ch == ' ': c...
e787a0a1c407902a2a946a21daf308ca94a794c6
31,518
import sys import inspect def linkcode_resolve(domain, info): """ Determine the URL corresponding to Python object """ if domain != 'py': return None modname = info['module'] fullname = info['fullname'] submod = sys.modules.get(modname) if submod is None: return None ...
60066eccd462bdc8cca16af66feb348079ed4102
31,519
import sh def get_minibam_bed(bamfile, bedfile, minibam=None): """ samtools view -L could do the work, but it is NOT random access. Here we are processing multiple regions sequentially. See also: https://www.biostars.org/p/49306/ """ pf = op.basename(bedfile).split(".")[0] minibamfile = minib...
48142e8df2468332699459a6ff0a9c455d5ad32f
31,520
def create_app(config_object="tigerhacks_api.settings"): """Create application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/. :param config_object: The configuration object to use. """ app = Flask(__name__.split(".")[0]) logger.info("Flask app initialized") app...
7bd2af062b770b80454b1f1fc219411fdb174a41
31,521
def dest_in_spiral(data): """ The map of the circuit consists of square cells. The first element in the center is marked as 1, and continuing in a clockwise spiral, the other elements are marked in ascending order ad infinitum. On the map, you can move (connect cells) vertically and horizontally....
a84a00d111b80a3d9933d9c60565b7a31262f878
31,522
from datetime import datetime def get_current_time(): """ returns current time w.r.t to the timezone defined in Returns ------- : str time string of now() """ srv = get_server() if srv.time_zone is None: time_zone = 'UTC' else: time_zone = srv.time_zone ret...
3b8d547d68bbc0f7f7f21a8a5b375cb898e53d30
31,523
import async_timeout import aiohttp import asyncio async def _update_google_domains(hass, session, domain, user, password, timeout): """Update Google Domains.""" url = f"https://{user}:{password}@domains.google.com/nic/update" params = {"hostname": domain} try: async with async_timeout.timeo...
372137db20bdb1c410f84dfa55a48269c4f588bc
31,524
def smoothen_over_time(lane_lines): """ Smooth the lane line inference over a window of frames and returns the average lines. """ avg_line_lt = np.zeros((len(lane_lines), 4)) avg_line_rt = np.zeros((len(lane_lines), 4)) for t in range(0, len(lane_lines)): avg_line_lt[t] += lane_lines[t...
64c31747ed816acbaeebdd9dc4a9e2163c3d5274
31,525
from typing import List from typing import Optional import random def select_random(nodes: List[DiscoveredNode]) -> Optional[DiscoveredNode]: """ Return a random node. """ return random.choice(nodes)
7bb41abd7f135ea951dbad85e4dc7290d6191e44
31,526
def convert(from_path, ingestor, to_path, egestor, select_only_known_labels, filter_images_without_labels): """ Converts between data formats, validating that the converted data matches `IMAGE_DETECTION_SCHEMA` along the way. :param from_path: '/path/to/read/from' :param ingestor: `Ingestor` to rea...
0407768620b3c703fec0143d2ef1297ba566ed7f
31,527
import timeit def timer(method): """ Method decorator to capture and print total run time in seconds :param method: The method or function to time :return: A function """ @wraps(method) def wrapped(*args, **kw): timer_start = timeit.default_timer() result = method(*args, **...
526a7b78510efb0329fba7da2f4c24a6d35c2266
31,528
def macro_states(macro_df, style, roll_window): """ Function to convert macro factors into binary states Args: macro_df (pd.DataFrame): contains macro factors data style (str): specify method used to classify. Accepted values: 'naive' roll_window (int): specify rolling...
1d4862cfb43aeebd33e71bc67293cbd7b62eb7b5
31,529
import torch def get_sparsity(lat): """Return percentage of nonzero slopes in lat. Args: lat (Lattice): instance of Lattice class """ # Initialize operators placeholder_input = torch.tensor([[0., 0]]) op = Operators(lat, placeholder_input) # convert z, L, H to np.float64 (simplex ...
703bd061b662a20b7ebce6111442bb6597fddaec
31,530
def XYZ_to_Kim2009( XYZ: ArrayLike, XYZ_w: ArrayLike, L_A: FloatingOrArrayLike, media: MediaParameters_Kim2009 = MEDIA_PARAMETERS_KIM2009["CRT Displays"], surround: InductionFactors_Kim2009 = VIEWING_CONDITIONS_KIM2009["Average"], discount_illuminant: Boolean = False, n_c: Floating = 0.57, )...
bf694c7a66052b3748f561018d253d2dfcdfc8df
31,531
from typing import Union from pathlib import Path from typing import Optional def load_capsule(path: Union[str, Path], source_path: Optional[Path] = None, key: Optional[str] = None, inference_mode: bool = True) -> BaseCapsule: """Load a capsule from the filesyste...
f6810bdb82ab734e2bd424feee76f11da18cccf4
31,532
def geodetic2ecef(lat, lon, alt): """Convert geodetic coordinates to ECEF.""" lat, lon = radians(lat), radians(lon) xi = sqrt(1 - esq * sin(lat)) x = (a / xi + alt) * cos(lat) * cos(lon) y = (a / xi + alt) * cos(lat) * sin(lon) z = (a / xi * (1 - esq) + alt) * sin(lat) return x, y, z
43654b16d89eeeee0aa411f40dc12d5c12637e80
31,533
def processor_group_size(nprocs, number_of_tasks): """ Find the number of groups to divide `nprocs` processors into to tackle `number_of_tasks` tasks. When `number_of_tasks` > `nprocs` the smallest integer multiple of `nprocs` is returned that equals or exceeds `number_of_tasks` is returned. When ...
f6d9a760d79ff59c22b3a95cc56808ba142c4045
31,534
def skin_base_url(skin, variables): """ Returns the skin_base_url associated to the skin. """ return variables \ .get('skins', {}) \ .get(skin, {}) \ .get('base_url', '')
80de82862a4a038328a6f997cc29e6bf1ed44eb8
31,535
from typing import Union import torch import os import warnings def load( name: str, device: Union[str, torch.device] = 'cuda' if torch.cuda.is_available() else 'cpu', jit: bool = False, download_root: str = None, ): """Load a CLIP model Parameters ---------- name : str A mode...
f99c7bdddfe0c92d83d6931b475ec55dc85fb07b
31,536
import os def default_pre_training_callbacks( logger=default_logger, with_lr_finder=False, with_export_augmentations=True, with_reporting_server=True, with_profiler=False, additional_callbacks=None): """ Default callbacks to be performed before the fitting of th...
bef795f2db89b4cd443a4716baabcbd7a26a0f37
31,537
import json def validate_dumpling(dumpling_json): """ Validates a dumpling received from (or about to be sent to) the dumpling hub. Validation involves ensuring that it's valid JSON and that it includes a ``metadata.chef`` key. :param dumpling_json: The dumpling JSON. :raise: :class:`netdumpl...
7d6885a69fe40fa8531ae58c373a1b1161b1df49
31,538
def check_gradient(func,atol=1e-8,rtol=1e-5,quiet=False): """ Test gradient function with a set of MC photons. This works with either LCPrimitive or LCTemplate objects. TODO -- there is trouble with the numerical gradient when a for the location-related parameters when the finite st...
1acb91e7ed4508fb0c987b6e2d21c0ce86081d28
31,539
def _recurse_to_best_estimate( lower_bound, upper_bound, num_entities, sample_sizes ): """Recursively finds the best estimate of population size by identifying which half of [lower_bound, upper_bound] contains the best estimate. Parameters ---------- lower_bound: int The lower bound...
969b550da712682ae620bb7158ed623785ec14f5
31,540
def betwix(iterable, start=None, stop=None, inc=False): """ Extract selected elements from an iterable. But unlike `islice`, extract based on the element's value instead of its position. Args: iterable (iter): The initial sequence start (str): The fragment to begin with (inclusive) ...
e1079158429e7d25fee48222d5ac734c0456ecfe
31,541
import logging def map_configuration(config: dict) -> tp.List[MeterReaderNode]: # noqa MC0001 """ Parsed configuration :param config: dict from :return: """ # pylint: disable=too-many-locals, too-many-nested-blocks meter_reader_nodes = [] if 'devices' in config and 'middleware' in con...
0d9212850547f06583d71d8d9b7e2995bbf701d5
31,542
def places(client, query, location=None, radius=None, language=None, min_price=None, max_price=None, open_now=False, type=None, region=None, page_token=None): """ Places search. :param query: The text string on which to search, for example: "restaurant". :type query: string :...
50aea370006d5d016b7ecd943abc2deba382212d
31,543
def load_data(_file, pct_split): """Load test and train data into a DataFrame :return pd.DataFrame with ['test'/'train', features]""" # load train and test data data = pd.read_csv(_file) # split into train and test using pct_split # data_train = ... # data_test = ... # concat and labe...
1a02f83aba497bc58e54c262c3f42386938ee9bd
31,544
def sorted_items(d, key=None, reverse=False): """Given a dictionary `d` return items: (k1, v1), (k2, v2)... sorted in ascending order according to key. :param dict d: dictionary :param key: optional function remapping key :param bool reverse: If True return in descending order instead of default as...
4e4302eebe2955cdd5d5266a65eac3acf874474a
31,545
import sys def factorize(eri_full, rank): """ Do single factorization of the ERI tensor Args: eri_full (np.ndarray) - 4D (N x N x N x N) full ERI tensor rank (int) - number of vectors to retain in ERI rank-reduction procedure Returns: eri_rr (np.ndarray) - 4D approximate ERI tensor ...
1019c8bde59e0567d16b18da923e7902e8ba572e
31,546
def randint_population(shape, max_value, min_value=0): """Generate a random population made of Integers Args: (set of ints): shape of the population. Its of the form (num_chromosomes, chromosome_dim_1, .... chromesome_dim_n) max_value (int): Maximum value taken by a given gene. ...
79cbc5ceba4ecb3927976c10c8990b167f208c0e
31,547
def simplex_creation( mean_value: np.array, sigma_variation: np.array, rng: RandomNumberGenerator = None ) -> np.array: """ Creation of the simplex @return: """ ctrl_par_number = mean_value.shape[0] ################## # Scale matrix: # Explain what the scale matrix means here ##...
a25ac6b6f92acb5aaa1d50f6c9a5d8d5caa02639
31,548
def _scale_db(out, data, mask, vmins, vmaxs, scale=1.0, offset=0.0): # pylint: disable=too-many-arguments """ decibel data scaling. """ vmins = [0.1*v for v in vmins] vmaxs = [0.1*v for v in vmaxs] return _scale_log10(out, data, mask, vmins, vmaxs, scale, offset)
dab3125f7d8b03ff5141e9f97f470211416f430c
31,549
def make_tree(anime): """ Creates anime tree :param anime: Anime :return: AnimeTree """ tree = AnimeTree(anime) # queue for BFS queue = deque() root = tree.root queue.appendleft(root) # set for keeping track of visited anime visited = {anime} # BFS downwards while len(queue) > 0: current = queue.pop()...
d93257e32b024b48668e7c02e534a31e54b4665d
31,550
def draw_bboxes(images, # type: thelper.typedefs.InputType preds=None, # type: Optional[thelper.typedefs.AnyPredictionType] bboxes=None, # type: Optional[thelper.typedefs.AnyTargetType] color_map=None, # type: Optional[thelpe...
6e82ee3ad211166ad47c0aae048246052de2d21c
31,551
def html_table_from_dict(data, ordering): """ >>> ordering = ['administrators', 'key', 'leader', 'project'] >>> data = [ \ {'key': 'DEMO', 'project': 'Demonstration', 'leader': 'leader@example.com', 'administrators': ['admin1@example.com', 'admin2@example.com']}, \ {'key': 'FOO', 'project': ...
f3a77977c3341adf08af17cd3d907e2f12d5a093
31,552
import random def getRandomChests(numChests): """Return a list of (x, y) integer tuples that represent treasure chest locations.""" chests = [] while len(chests) < numChests: newChest = [random.randint(0, BOARD_WIDTH - 1), random.randint(0, BOARD_HEIGHT - 1)] # Make...
285b35379f8dc8c13b873ac77c1dcac59e26ccef
31,553
import random def random_tolerance(value, tolerance): """Generate a value within a small tolerance. Credit: /u/LightShadow on Reddit. Example:: >>> time.sleep(random_tolerance(1.0, 0.01)) >>> a = random_tolerance(4.0, 0.25) >>> assert 3.0 <= a <= 5.0 True """ valu...
abe631db8a520de788540f8e0973537306872bde
31,554
def routes_stations(): """The counts of stations of routes.""" return jsonify( [ (n.removeprefix("_"), int(c)) for n, c in r.zrange( "Stats:Route.stations", 0, 14, desc=True, withscores=True ) ] )
2e0e865681c2e47da6da5f5cbd9dc5b130721233
31,555
import math def montage(packed_ims, axis): """display as an Image the contents of packed_ims in a square gird along an aribitray axis""" if packed_ims.ndim == 2: return packed_ims # bring axis to the front packed_ims = np.rollaxis(packed_ims, axis) N = len(packed_ims) n_tile = math.c...
27d2de01face567a1caa618fc2a025ec3adf2c8c
31,556
def blocks2image(Blocks, blocks_image): """ Function to stitch the blocks back to the original image input: Blocks --> the list of blocks (2d numpies) blocks_image --> numpy 2d array with numbers corresponding to block number output: image --> stitched image """ image = np.zeros(np.shape(blocks_im...
ef6f5af40946828af664fc698e0b2f64dbbe8a96
31,557
def box_mesh(x_extent: float, y_extent: float, z_extent: float) -> Mesh: """create a box mesh""" # wrapper around trimesh interface # TODO: my own implementation of this would be nice box = trimesh.primitives.Box(extents=(x_extent, y_extent, z_extent)).to_mesh() return box.vertices, box.faces
984b9ec62fe5e5c2d64c301d436d5f6de70a480f
31,558
def create_bucket(storage_client, bucket_name, parsed_args): """Creates the test bucket. Also sets up lots of different bucket settings to make sure they can be moved. Args: storage_client: The storage client object used to access GCS bucket_name: The name of the bucket to create p...
df7ccc9979007ee7278770f94c27363936961286
31,559
from typing import Dict from typing import List from typing import Tuple def learn_parameters(df_path: str, pas: Dict[str, List[str]]) -> \ Tuple[Dict[str, List[str]], nx.DiGraph, Dict[str, List[float]]]: """ Gets the parameters. :param df_path: CSV file. :param pas: Parent-child relationship...
ea34c67e5bf6b09aadc34ee271415c74103711e3
31,560
import io def extract_urls_n_email(src, all_files, strings): """IPA URL and Email Extraction.""" try: logger.info('Starting IPA URL and Email Extraction') email_n_file = [] url_n_file = [] url_list = [] domains = {} all_files.append({'data': strings, 'name': 'IP...
edb0dd4f0fe24de914f99b87999efd9a24795381
31,561
def find_scan_info(filename, position = '__P', scan = '__S', date = '____'): """ Find laser position and scan number by looking at the file name """ try: file = filename.split(position, 2) file = file[1].split(scan, 2) laser_position = file[0] file = file[1].split(date...
f98afb440407ef7eac8ceda8e15327b5f5d32b35
31,562
def arglast(arr, convert=True, check=True): """Return the index of the last true element of the given array. """ if convert: arr = np.asarray(arr).astype(bool) if np.ndim(arr) != 1: raise ValueError("`arglast` not yet supported for ND != 1 arrays!") sel = arr.size - 1 sel = sel -...
b4c6424523a5a33a926b7530e6a6510fd813a42a
31,563
def number_formatter(number, pos=None): """Convert a number into a human readable format.""" magnitude = 0 while abs(number) >= 100: magnitude += 1 number /= 100.0 return '%.1f%s' % (number, ['', '', '', '', '', ''][magnitude])
a9cfd3482b3a2187b8d18d6e21268e71b69ae2f2
31,564
from pathlib import Path import shutil def simcore_tree(cookies, tmpdir): """ bakes cookie, moves it into a osparc-simcore tree structure with all the stub in place """ result = cookies.bake( extra_context={"project_slug": PROJECT_SLUG, "github_username": "pcrespov"} ) work...
f9889c1b530145eb94cc7ca3547d90759218b1dc
31,565
def calc_density(temp, pressure, gas_constant): """ Calculate density via gas equation. Parameters ---------- temp : array_like temperatur in K pressure : array_like (partial) pressure in Pa gas_constant: array_like specicif gas constant in m^2/(s^2*K) Returns ...
1e492f9fb512b69585035ce2f784d8cf8fd1edb0
31,566
def __parse_ws_data(content, latitude=52.091579, longitude=5.119734): """Parse the buienradar xml and rain data.""" log.info("Parse ws data: latitude: %s, longitude: %s", latitude, longitude) result = {SUCCESS: False, MESSAGE: None, DATA: None} # convert the xml data into a dictionary: try: ...
16fc5377951fc902218fb8571d18c3e5ef2d44bd
31,567
def load_post_data(model, metadata): # NOQA: C901 """Fully load metadata and contents into objects (including m2m relations) :param model: Model class, any polymorphic sub-class of django_docutils.rst_post.models.RSTPost :type model: :class:`django:django.db.models.Model` :param metadata: ...
13182e62f2006aaf30d8af95c7e19b34ccf8ce90
31,568
def address(addr, label=None): """Discover the proper class and return instance for a given Oscillate address. :param addr: the address as a string-like object :param label: a label for the address (defaults to `None`) :rtype: :class:`Address`, :class:`SubAddress` or :class:`IntegratedAddress` """...
13b1e24abc7303395ff9bbe82787bc67a4d377d6
31,569
def retrieve_molecule_number(pdb, resname): """ IDENTIFICATION OF MOLECULE NUMBER BASED ON THE TER'S """ count = 0 with open(pdb, 'r') as x: lines = x.readlines() for i in lines: if i.split()[0] == 'TER': count += 1 if i.split()[3] == resname: ...
8342d1f5164707185eb1995cedd065a4f3824401
31,570
import ctypes import ctypes.wintypes import io def _windows_write_string(s, out, skip_errors=True): """ Returns True if the string was written using special methods, False if it has yet to be written out.""" # Adapted from http://stackoverflow.com/a/3259271/35070 WIN_OUTPUT_IDS = { 1: -11, ...
471fd456769e5306525bdd44d41158d2a3b024de
31,571
def in_relative_frame( pos_abs: np.ndarray, rotation_matrix: np.ndarray, translation: Point3D, ) -> np.ndarray: """ Inverse transform of `in_absolute_frame`. """ pos_relative = pos_abs + translation pos_relative = pos_relative @ rotation_matrix return pos_relative
5f7789d7b5ff27047d6bb2df61ba7c841dc05b95
31,572
def check_url_namespace(app_configs=None, **kwargs): """Check NENS_AUTH_URL_NAMESPACE ends with a semicolon""" namespace = settings.NENS_AUTH_URL_NAMESPACE if not isinstance(namespace, str): return [Error("The setting NENS_AUTH_URL_NAMESPACE should be a string")] if namespace != "" and not names...
e97574a60083cb7a61dbf7a9f9d4c335d68577b5
31,573
def get_exif_data(fn): """Returns a dictionary from the exif data of an PIL Image item. Also converts the GPS Tags""" exif_data = {} i = Image.open(fn) info = i._getexif() if info: for tag, value in info.items(): decoded = TAGS.get(tag, tag) if decoded == "GPSInfo": gps_data = {} for t in value: ...
b6a97ed68753bb3e7ccb19a242c66465258ae602
31,574
import os def get_circuitpython_version(device_path): """ Returns the version number of CircuitPython running on the board connected via ``device_path``. This is obtained from the ``boot_out.txt`` file on the device, whose content will start with something like this:: Adafruit CircuitPython 4...
ce4d407062566cd42473d2cef8d18024b0098b69
31,575
def _setup_modules(module_cls, variable_reparameterizing_predicate, module_reparameterizing_predicate, module_init_kwargs): """Return `module_cls` instances for reparameterization and for reference.""" # Module to be tested. module_to_reparameterize = _init_module(module_cls, module_init_kwarg...
367ecae71835044055765ace56f6c0540e9a44ba
31,576
def external_compatible(request, id): """ Increment view counter for a compatible view """ increment_hit_counter_task.delay(id, 'compatible_count') return json_success_response()
c82536cdebb2cf620394008d3ff1df13a87a9715
31,577
def lowpass_xr(da,cutoff,**kw): """ Like lowpass(), but ds is a data array with a time coordinate, and cutoff is a timedelta64. """ data=da.values time_secs=(da.time.values-da.time.values[0])/np.timedelta64(1,'s') cutoff_secs=cutoff/np.timedelta64(1,'s') axis=da.get_axis_num('time') ...
0628d63a94c3614a396791c0b5abd52cb3590e04
31,578
def _calc_zonal_correlation(dat_tau, dat_pr, dat_tas, dat_lats, fig_config): """ Calculate zonal partial correlations for sliding windows. Argument: -------- dat_tau - data of global tau dat_pr - precipitation dat_tas - air temperature dat_lats - latitude of the given mo...
f596536bde5ded45da2ef44e388df19d60da2c75
31,579
def is_unary(string): """ Return true if the string is a defined unary mathematical operator function. """ return string in mathwords.UNARY_FUNCTIONS
914785cb757f155bc13f6e1ddcb4f9b41f2dd1a2
31,580
def GetBucketAndRemotePath(revision, builder_type=PERF_BUILDER, target_arch='ia32', target_platform='chromium', deps_patch_sha=None): """Returns the location where a build archive is expected to be. Args: revision: Revision string, e.g. a git commit hash or...
30ced6c37d42d2b531ae6ecafc4066c59fb8f6e4
31,581
def cutmix_padding(h, w): """Returns image mask for CutMix. Taken from (https://github.com/google/edward2/blob/master/experimental /marginalization_mixup/data_utils.py#L367) Args: h: image height. w: image width. """ r_x = tf.random.uniform([], 0, w, tf.int32) r_y = tf.random.uniform([], 0, h, tf...
adf627452ebe25b929cd78242cca382f6a62116d
31,582
import math def compute_star_verts(n_points, out_radius, in_radius): """Vertices for a star. `n_points` controls the number of points; `out_radius` controls distance from points to centre; `in_radius` controls radius from "depressions" (the things between points) to centre.""" assert n_points >= 3 ...
97919efbb501dd41d5e6ee10e27c942167142b24
31,583
def create_ordering_dict(iterable): """Example: converts ['None', 'ResFiles'] to {'None': 0, 'ResFiles': 1}""" return dict([(a, b) for (b, a) in dict(enumerate(iterable)).iteritems()])
389a0875f1542327e4aa5d038988d45a74b61937
31,584
def sparse2tuple(mx): """Convert sparse matrix to tuple representation. ref: https://github.com/tkipf/gcn/blob/master/gcn/utils.py """ if not sp.isspmatrix_coo(mx): mx = mx.tocoo() coords = np.vstack((mx.row, mx.col)).transpose() values = mx.data shape = mx.shape return coords, values, shape
a20b12c3e0c55c2d4739156f731e8db9e2d66feb
31,585
def correct_predicted(y_true, y_pred): """ Compare the ground truth and predict labels, Parameters ---------- y_true: an array like for the true labels y_pred: an array like for the predicted labels Returns ------- correct_predicted_idx: a list of index of correct predicted correct...
3fae4287cb555b7258adde989ef4ef01cfb949ce
31,586
def coord_image_to_trimesh(coord_img, validity_mask=None, batch_shape=None, image_dims=None, dev_str=None): """Create trimesh, with vertices and triangle indices, from co-ordinate image. Parameters ---------- coord_img Image of co-ordinates *[batch_shape,h,w,3]* validity_mask Boolea...
8719498ddf24e67ed2ea245d73ac796662b5d08e
31,587
def expand_db_html(html, for_editor=False): """ Expand database-representation HTML into proper HTML usable in either templates or the rich text editor """ def replace_a_tag(m): attrs = extract_attrs(m.group(1)) if 'linktype' not in attrs: # return unchanged r...
2e01f4aff7bc939fac11c031cde760351322d564
31,588
def hungarian(matrx): """Runs the Hungarian Algorithm on a given matrix and returns the optimal matching with potentials. Produces intermediate images while executing.""" frames = [] # Step 1: Prep matrix, get size matrx = np.array(matrx) size = matrx.shape[0] # Step 2: Generate trivi...
dc4dffa819ed836a8e4aaffbe23b49b95101bffe
31,589
def open_spreadsheet_from_args(google_client: gspread.Client, args): """ Attempt to open the Google Sheets spreadsheet specified by the given command line arguments. """ if args.spreadsheet_id: logger.info("Opening spreadsheet by ID '{}'".format(args.spreadsheet_id)) return google_cl...
355545a00de77039250269c3c8ddf05b2f72ec48
31,590
def perturb_BB(image_shape, bb, max_pertub_pixel, rng=None, max_aspect_ratio_diff=0.3, max_try=100): """ Perturb a bounding box. :param image_shape: [h, w] :param bb: a `Rect` instance :param max_pertub_pixel: pertubation on each coordinate :param max_aspect_ratio_diff: result ca...
4044291bdcdf1639e9af86857cac158a67db5229
31,591
def simpleCheck(modelConfig, days=100, visuals=True, debug=False, modelName="default", outputDir="outputs", returnTimeseries=False): """ runs one simulatons with the given config and showcase the number of infection and the graph """ loadDill, saveDill = False, False pickleName = flr.fullPath("c...
4a1662688c83147f2ba1eb7fc232c6bbe5c4f050
31,592
def neural_network(inputs, weights): """ Takes an input vector and runs it through a 1-layer neural network with a given weight matrix and returns the output. Arg: inputs - 2 x 1 NumPy array weights - 2 x 1 NumPy array Returns (in this order): out - a 1 x 1 NumPy array, rep...
dc2d5cccf0cf0591c030b5dba2cd905f4583821c
31,593
def complex_randn(shape): """ Returns a complex-valued numpy array of random values with shape `shape` Args: shape: (tuple) tuple of ints that will be the shape of the resultant complex numpy array Returns: (:obj:`np.ndarray`): a complex-valued numpy array of random values with shape `shape` ...
6379fb2fb481392dce7fb4eab0e85ea85651b290
31,594
import glob from sys import path import pickle def load_pairs(inputdir, regex, npairs=100): """Load a previously generated set of pairs.""" pairfiles = glob.glob(path.join(inputdir, regex)) pairs = [] slcnr = 0 tilenr = 0 for pairfile in pairfiles: p, src, dst, model, w = pickle.load...
06a63e80e1c34f385e7492f19df65a9f68ec9626
31,595
def sin(x: REAL) -> float: """Sine.""" x %= 2 * pi res = 0 k = 0 while True: mem_res = res res += (-1) ** k * x ** (2 * k + 1) / fac(2 * k + 1) if abs(mem_res - res) < _TAYLOR_DIFFERENCE: return res k += 1
0ae009139bc640944ad1a90386e6c66a6b874108
31,596
import tokenize from operator import getitem def _getitem_row_chan(avg, idx, dtype): """ Extract (row,chan,corr) arrays from dask array of tuples """ name = ("row-chan-average-getitem-%d-" % idx) + tokenize(avg, idx) dim = ("row", "chan", "corr") layers = db.blockwise(getitem, name, dim, ...
ff3da6b935cd4c3e909008fefea7a9c91d51d399
31,597
import gzip def make_gzip(tar_file, destination): """ Takes a tar_file and destination. Compressess the tar file and creates a .tar.gzip """ tar_contents = open(tar_file, 'rb') gzipfile = gzip.open(destination + '.tar.gz', 'wb') gzipfile.writelines(tar_contents) gzipfile.close() ta...
38d9e3de38cb204cc3912091099439b7e0825608
31,598
def symmetrize_confusion_matrix(CM, take='all'): """ Sums over population, symmetrizes, then return upper triangular portion :param CM: numpy.ndarray confusion matrix in standard format """ if CM.ndim > 2: CM = CM.sum(2) assert len(CM.shape) == 2, 'This function is meant for single subje...
91964cc4fd08f869330413e7485f765696b92614
31,599