content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import random def chooseAxes(numBits): """Return Alice and Bob's randomly chosen mstment axes for the specified number of qubits in the E91 protocol: A chooses from (0, pi/4, pi/2) with equal probability, B chooses from (pi/4, pi/2, 3pi/4) with equal probability. """ choicesA ...
76ae98d9dd4d590d84e2194a3ae0c6bd91ae9838
3,616,100
import time def newCommentUri(secs=None): """this is essentially a bnode, but a real URI is easier to work with""" if secs is None: secs = time.time() return URIRef("http://bigasterisk.com/comment/%r" % secs)
00f384ec0c7fe2151ce7a112e9eefddefcfc5407
3,616,101
import logging def debug(line): """Log debug""" return logging.debug(line)
bb66a637a7ce6f426b5b59687f2ce3e705448d77
3,616,102
def non_max_suppression(dets, threshold): """执行non-maximum suppression并返回保留的boxes的索引. dets:(x1、y1、x2、y2,scores) threshold: Float型. 用于过滤IoU的阈值. """ x1 = dets[:, 0] y1 = dets[:, 1] x2 = dets[:, 2] y2 = dets[:, 3] scores = dets[:, 4] # 每一个检测框的面积 areas = (x2 - x1 + 1) * (y2 - y1...
fdd4917e85641def1b13d6764a3d880b271721a4
3,616,103
import os def GetLogDir(): """Gets the path to the currently in use log directory. Returns: str, The logging directory path. """ log_file = _log_manager.current_log_file if not log_file: return None return os.path.dirname(log_file)
345ff6cdc59aa85a708121901fc8820254f4b4ed
3,616,104
from windspharm.xarray import VectorWind def wind_rot_div(u, v, truncation=None, const=None): """Split the wind field into divergent and zonal mean and eddy rotational components.""" vec = VectorWind(u, v, rsphere=const.rplanet_m) div_cmpnt_u, div_cmpnt_v, rot_cmpnt_u, rot_cmpnt_v = vec.helmholtz(truncat...
a45ea9f5807d6756dd9b770d9e3e33bd8b03c0f5
3,616,105
def blank_image(width=1024, height=1024, background=BG_COLOR): """ It creates a blank image of the given background color """ img = np.full((height, width, MONOCHROME), background, np.uint8) return img
aa96b09e2233b8371321df3837278488399d9332
3,616,106
def determineAlpha(mag_ratio): """ Bug: No docstring Bug: Each image should have its own alpha, because the different images have different magnifications (these are in the OM10 "MAG" columns, and need to be applied to each image's sourceX magnitude.) Bug: function name should be "dete...
be7640401a8347a1ab712253eb404f092f6e283f
3,616,107
def pretrained_embedding_layer(word_to_vec_map, word_to_index): """ Creates a Keras Embedding() layer and loads in pre-trained GloVe 50-dimensional vectors. Arguments: word_to_vec_map -- dictionary mapping words to their GloVe vector representation. word_to_index -- dictionary mapping from words to...
ecc973587aaa08cbe5d5b10c582c38374b992de9
3,616,108
import csv def generate_gaussian_rewards(num_bandits, num_actions, m, c, v, n, out_file = ""): """ Generate rewards that are correlated across bandits from a Multivariate Gaussian. For example, the reward of arm 1 in bandit 2 may be correlated with the reward of arm 1 in bandit 1. This is modelled...
00e8108621bafb1c9f4711363b146da16ffaeeae
3,616,109
async def update_request(connection: Connection, old_key: str, new_key: str, json: str) -> int: """ returns amount of entries updated """ return await connection.execute( """ update requests.requests set id = :new_key, body = :json, ...
a67b31ed409be5cdd6269409e9d355c2d763bf80
3,616,110
from datetime import datetime def _prepare_transactions(response, telegram_id, mcc_codes): """Parse response from monobank API and return formatted transaction.""" transactions = [] costs_converter = 100.0 for transaction in response: transactions.append(( transaction["id"], ...
0794c0761e7232bf517dd867f4d8bab252b2c708
3,616,111
import torch def get_gaps(o : Tensor, forward : bool = True, backward : bool = True, nearest : bool = True, normalize : bool = True): """Number of sequence steps from previous, to next and/or to nearest real value along the last dimension of 3D arrays or tensors""" _gaps = [] if forward ...
d0b7938687433b2307fd121db07b9cdb09c1f07b
3,616,112
def DoubleCast(value): """Explicitly cast a value to type Double.""" if istype(value, Double): return value return UPlus(value)
bbef5bfc39c0be1a1ec7572f941596e513adbda9
3,616,113
def search_dsrs( dsi_uuid: str = None, query_params: dict = None, user: dict = None ): """ search dsr(s) from ES / MongoDB """ ### TO DO ### check user's auth res, status = search_documents( index_name = dsi_uuid, doc_type = DSR_DOC_TYPE, query_params = query_params, user = user ) ...
34bb27edb9c95cb097375740863d2a9845905360
3,616,114
def _find_datapoints(sheet, row, col): """Return start and stop points for adsorption and desorption.""" rowc = 1 # Check for adsorption branch if sheet.cell(row + rowc, col).value == 'ADS': ads_start_row = row + rowc + 1 ads_final_row = ads_start_row point = sheet.cell(ads_final_r...
38f0f0d9706c7ed7d3171e1b1c02161af618a4e0
3,616,115
from typing import Tuple from typing import List def _read_dvxrel2_flag(data: bytes, n0: int, i0: int, i1: int, size: int, ints: np.ndarray) -> Tuple[List[int], List[str]]: """reads the DVxREL2 flag table""" flag = ints[i0+10] #print(int...
2e8e6f58d01a3bfda7030186b392850fa3cb6c83
3,616,116
from typing import Optional from typing import Tuple from typing import Dict def eval_step( *, flax_model: nn.Module, train_state: train_utils.TrainState, batch: Batch, metrics_fn: MetricFn, debug: Optional[bool] = False ) -> Tuple[Batch, jnp.ndarray, Dict[str, Tuple[float, int]], jnp.ndarray]...
d064b275b9bd7d1dcd06aa88cdda88996627432a
3,616,117
def patient_list(request): """Accepts a request to return a list of all patients from the backing data store. Used for synching the mobile client. Warning: This can return a significant amount of patient data. Request parameters: username a valid username password ...
b76ee242902f91e4f31c0a940196b5bf5ed298ca
3,616,118
def create_dict_playlists_playlistids(p_list, pid_list): """ Create a dictionary of playlists and playlist ids """ playlists_and_playlist_ids = {} for i in range(len(p_list)): playlists_and_playlist_ids[p_list[i]] = pid_list[i] return playlists_and_playlist_ids
173850ed85b3dc774ddea14674e22e701991c807
3,616,119
from datetime import datetime def create_bot(market, strategy, resolution, start, end, verbose, percent, automatic, btc): """Will create a new bot instance.""" bot = Cointrader(market=market, strategy=strategy, resolution=resolution, start=start, end=end, automatic=automatic, percent=perc...
82efbc617094ab07b5d9f151e1c63dec12b1a404
3,616,120
import os import warnings def fetch_coords_seitzman_2018(ordered_regions=True, legacy_format=True): """Load the Seitzman et al. 300 ROIs. These ROIs cover cortical, subcortical and cerebellar regions and are assigned to one of 13 networks (Auditory, CinguloOpercular, DefaultMode, DorsalAttention, Fro...
e20ae14473138444ea789746d058a102ffe6aea7
3,616,121
def money_manager(manager): """ Patches a model manager's get_queryset method so that each QuerySet it returns is able to work on money fields. This allow users of django-money to use other managers while still doing money queries. """ # Need to dynamically subclass to add our behaviour, an...
e73b4d2a513f836c333a673e499f9cf3daacc8ce
3,616,122
def get_address():# check_author=True): """Get a address and user by id. Checks that the id exists and optionally that the current user is the author. :param id: id of address to get :return: the address :raise 404: if a address with the given id doesn't exist """ success = True uid...
44851e91940f4f190be4764bfcf84b713278e06b
3,616,123
def round(sdf: np.float, radius: np.float) -> np.float: """ Rounds a shape :param sdf: pre-calculated SDF :param radius: radius :return: SDF """ return sdf - radius
b440d3a9dbe5f78988605efb024af5c9e311150b
3,616,124
def get_in_system_by_id( system_id, stop_id, return_only_stations=True, earliest_time=None, latest_time=None, minimum_number_of_trips=None, include_all_trips_within=None, exclude_trips_before=None, alerts_detail=None, ): """ Get information about a specific stop. """ ...
8601c0d5788bad73c7db959f962828b8e7e45bf7
3,616,125
def required_input(message, method=input): """ Collect input from user and repeat until they answer. """ result = method(message) while len(result) < 1: result = method(message) return result
c9a21d6e63ab6bdde081db471cf0d2420f9047ea
3,616,126
from typing import Callable from typing import List from typing import Any def worker_map(worker: WorkerPool, fn: Callable[..., List[Any]], input_objects: List[Any]) -> List[Any]: """ Maps a list of objects through a worker. :param worker: Worker pool to use for parallelization. :param fn: Function to...
1e3f4d7a4c367e9323f4dd399164998292323301
3,616,127
def _generate_normals(polygons): """Takes a list of polygons and return an array of their normals. Normals point towards the viewer for a face with its vertices in counterclockwise order, following the right hand rule. Uses three points equally spaced around the polygon. This normal of course might...
4d43d2f8b868c89238be165930c956e7032bcf21
3,616,128
def initSeedSolutions() : """ This function should do any initialization needed to make generating individual solutions fast. It will get called before any solutions are generated. The value returned will be passed into generateSolution, so this is a good place to read in files or initializ...
a18a3099dc957a1195267a5eb742e7db0b026ac4
3,616,129
from operator import ge def gen_courses(): """ Helper function to populate the course dropdown. Creates a list of every course in every degree necessary for a CIS student. Currently static since this app only supports CIS students. Can be changed later to create a dropdown list for a different type of student i...
346cd1e90b684d708c26316d4f247811683b4477
3,616,130
def message( val: ArrayLike, src: int, sgroup: int, dest: int, dgroup: int) -> np.void: """Creates a message used for passing information between objects. Args: val: A numpy structured array. src: A 64-bit int that represents the source of the message. ...
32c343a8d427bc15bea725871e7fc395b5b33938
3,616,131
import requests import joblib import json def classify(): """ Make a POST to this endpint and pass in an URL to an image in the body of the request. Swap out the model.pkl with another trained model to classify new objects. """ try: body = request.get_json() print(body) img_ur...
501a97d1c9a2e56e9fee64f689bc624cab5b96b5
3,616,132
def list_nmmr_tris_bitfield(fp, child, sfrname, offset): """ Format a single bitfield of NMMR TRIS pseudo register Input: - index in .pic - register node Notes: - Expected to be used with 12Fs only """ if (child.nodeType == Node.ELEMENT_NODE): if (child.nodeName == "edc:AdjustPoin...
3f18126ea529b5bf299f69fad1bc92f8345718f7
3,616,133
def _mogrify_team(cursor, xs, fieldsList): """Shortcut for mogrifying a list as if it were a tuple.""" for valueIndex, [thisValue, thisColumn] in enumerate(zip(xs, fieldsList)): if (thisColumn == "team") | (thisColumn == "pos_team"): xs[valueIndex] = nfldb.standard_team(thisValue) ...
f90a87ebedb8af35e691231cab4c157533d4abc5
3,616,134
def table_columns(table, session): """ :param string table: Name of table or table schema :param Session session: SQLAlchemy Session :returns: List of column names in the table or empty list """ res = [] if isinstance(table, basestring): table = table_schema(table, session) for ...
6ac7d4923e55800d3ed2b636b9764b599d9e5c31
3,616,135
def _dpss_wavelet(sfreq, freqs, n_cycles=7, time_bandwidth=4.0, zero_mean=False): """Compute Wavelets for the given frequency range Parameters ---------- sfreq : float Sampling Frequency. freqs : ndarray, shape (n_freqs,) The frequencies in Hz. n_cycles : float...
c10cde512bcbbf222fb15c2ae5f7d432aaad4f63
3,616,136
def create_model(config: ml_collections.ConfigDict, deterministic: bool) -> nn.Module: """Creates a Flax model, as specified by the config.""" if config.model == "GraphNet": return models.GraphNet( latent_size=config.latent_size, num_mlp_layers=config.num_mlp_lay...
bcc2581de315876b115da2f5a06770a7d51d865e
3,616,137
def property_from_list(index): """Returns the item at position 'index' from a list. Args: index: The (0-based) item in the list to return. Returns: A function that returns the specified item from a list, or '' if the list contains too few items. """ @empty_if_none def property_from_list_lambd...
6a5aad5f40f6fbb94333492b520f341e530e14ba
3,616,138
def clothes_info(request, id): """Просмотр информации об одежде""" clothes = Clothes.objects.get(pk_clothes=id) return render(request, "clothes_info.html", {"clothes": clothes})
4ab555d24e6de7fe7a73f97a727052ca9032296d
3,616,139
def multiTag(type, tag=None, **kwargs): """ Displays the "multiple tag widget" """ kwargs["tag"] = tag kwargs["type"] = type kwargs["atf"] = AddTagForm({"type":type, "colour":["white"]}) return kwargs
53483fc339dc28c99eebb3d703868c57f4b67b90
3,616,140
import inspect import re def findsource(object, cache_key): """ findsource that does not cache """ file = inspect.getsourcefile(object) if not file: raise IOError('source code not available') lines = None with open(file) as f: lines = f.readlines() if not lines: ...
1f7deb36420df615d07b578e12c77abc5138a8f2
3,616,141
def parse_from_file( root_processor, # type: RootProcessor xml_file_path, # type: Text encoding='utf-8' # type: Text ): # type: (...) -> Any """ Parse the XML file using the processor starting from the root of the document. :param root_processor: Root processor of the XML doc...
03d002a33e236578c49ae7527b8192a982b575ad
3,616,142
def bb(a, b, c): """ナップザック問題を分枝限定法で解く :param np.array a: 制約条件の係数 :param int b: 制約条件の値 :param np.array c: 目的関数の係数 :return: """ answer_temp = greedy(a, b, c) # スタックに(aの残り, bの残り, cの残り, 答えの先頭部分)という形式で部分問題を登録する stack = [(a, b, c, np.array([]))] while stack: print('---------...
fabf39d16d9cc74f17be0e33260598f8d22b736c
3,616,143
import typing def is_lock_pending( end_state: NettingChannelEndState, secrethash: typing.SecretHash, ) -> bool: """True if the `secrethash` corresponds to a lock that is pending to be claimed and didn't expire. """ return ( secrethash in end_state.secrethashes_to_lockedlocks or...
2e4df0e532230f3d0176eb60ce5eff9440d18aac
3,616,144
def NCBITAXON( directed = False, preprocess = "auto", load_nodes = True, load_node_types = True, load_edge_weights = True, auto_enable_tradeoffs = True, sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None, cache_sys_var = "GRAPH_CACHE_DIR", version = "2021-12-14", **kwargs ) -> Graph: ...
fd99a31972c9ed9acab845b4325084c7be2b8832
3,616,145
def gather_contact_details(): """ **gather_contact_details** obtains contact details from request. args :return: """ names = request.args.get('names') email = request.args.get('email') cell = request.args.get('cell') subject = request.args.get('subject') message = req...
9dc5d81102009173be680903bd50f8ab13c1b6f0
3,616,146
def dave4vm(mag, window_size, threshold=1.0): """ DAVE4VM - Differential Affine Velocity Estimator for Vector Magnetograms Parameters --------- MAG : structure of vector magnetic field measurements', MAG.DX : X spatial scale (used to compute B?X), ...
b48bd97644775462965bc6c2898fa181f4f94ec5
3,616,147
def get_unc_directory_from_string(string): """ Parses a string from `UncDirectory`'s `get_auth_path` method and returns a new `UncDirectory` object based on it. This may raise any errors that can be raised by `UncDirectory`'s constructor. """ creds = None path = string if '@\\\\' in str...
11b0a0e7e09c66b278a3610e2c6d300659e64b9b
3,616,148
def start(start): """When given the start only, calculate TMIN, TAVG, and TMAX for all dates greater than and equal to the start date.""" start_date = dt.datetime.strptime(start, '%Y-%m-%d') session = Session(engine) year_query = session.query(func.min(measurement.tobs), \ ...
84a29ce18bd3c5fbc801657de135164f7487542a
3,616,149
def create_model(fingerprint_input, model_settings, model_architecture, is_training): """Builds a model of the requested architecture compatible with the settings. There are many possible ways of deriving predictions from a spectrogram input, so this function provides an abstract interface for c...
fceddf64e7a4d50d307b34c954c5e8bcadcc0655
3,616,150
def orbit2frame(name, ref_orbit, orientation=None, center=None, bypass=False): """Create a frame based on a Orbit or Ephem object. Args: name (str): Name to give the created frame ref_orbit (Orbit or Ephem): orientation (str): Orientation of the created frame bypass (bool): By-p...
4236fa92e60c56e18ee19e7860e844836b9cc428
3,616,151
def from_hex_lsb(text): """Decode a hex encoded fingerprint string where the bits and bytes are in LSB order >>> from_hex_lsb('102f') (None, '\\x08\\xf4') >>> Raises a ValueError if the hex string is not a multiple of 2 bytes long or if it contains a non-hex character. """ return (Non...
bc66e35176eca5ea9148714a7929c90a9a167c66
3,616,152
def get_first_char(value): """ Returns the first char of the given string :param value: :return: """ return value[:1]
98207e7269371f0177f45a2c85f874e1d9bbb756
3,616,153
import json def load_instructions(ufilename): """ Expand this, maybe in the readme/docs because it's pretty much the heart and soul of the program. Loads a json file that describes the titlecard. In general, it'll be pairings of json keys and values. There are two keys that are handled specially...
e6b0d5ed81f5bc5c3a1837455f3815b282533e80
3,616,154
def dfs_search_recursive(G, src): """Entry to recursive Depth First Search.""" marked = {} node_from = {} def dfs(v): """Recursive DFS.""" marked[v] = True for w in G[v]: if not w in marked: node_from[w] = v dfs(w) dfs(src) re...
b433aba6a0d397c355ce578a867cfdebcccd980d
3,616,155
def is_cat(filename: str) -> bool: """ Returns true if filename is an image of a cat. In the dataset we are using this is indicated by the first letter of the filename; cats are labeled with uppercase letters, dogs with lowercase ones. """ result = filename[0].isupper() # print(f"File: {fil...
ad56c7c3ae28951fc31bcf70fece29bf934e4cec
3,616,156
def rm_user_edges(lcen, rcen, rm_slits): """ Remove one or more slits, as applicable Code compares exisiting slits (which must be sycnhronized) against the input request and removes any that match. Args: lcen (np.ndarray): Left traces of slit/orders rcen (np.ndarray): Right traces ...
38e9eae662813e126721aa1e45d7ff738775c02d
3,616,157
def analyze_text(filename): """ Calculate the number of lines and characters in a file :param filename: the name of the file to analyze :raises: IOError: if ``filename`` does not exist or can't be read :return: a tuple where the first element is the number of lines in the file and the second...
1670d3bff0402482e9e33be401e8914eea117f6c
3,616,158
def auto_adapt_batch(train_size, val_size, batch_count_multiple=1, max_size=256): """ returns a suitable batch size according to train and val dataset size, say max_size = 128, and val_size is smaller than train_size, if val_size < 128, the batch_size1 to be returned is val_size if 128 < val...
d0a6fa9e6bde3d563bd7fad5e2bbcf7068f9ff65
3,616,159
def get_model(model, feat_dim, meta): """Build a model specific for the given task. Arguments: - model: The model architecture. - feat_dim: Feature (last hidden layer) dimension. - meta: Meta data about the task. Return: - The corresponding neural network ""...
04c033555cc91ea622b70cd1edde72e7ecf51fb1
3,616,160
from typing import Tuple def pascals_triangle(rows: int) -> Tuple[Tuple[int, ...], ...]: """Return tuple containing pascals triangle up to specified length.""" result = [] next_numbers = [1] for _ in range(0, rows): # move row current_numbers = next_numbers next_numbers = [] ...
80c46657d413ff67bf3fc94091fd8a81bdb5a148
3,616,161
def gauss2D(valRange, size, mu, sigma): """ calculate 2D Gaussian on array. Parameters ---------- valRange : int value range to which the Gaussian will be scaled. size : list of ints x and y size of array. mu : list of floats x and y center position of Gaussian. ...
345152a70ef25fe607e4de2503a9e7424dd2ab8e
3,616,162
from typing import Mapping import os def _version_tag( key: str, artifacts: Mapping[str, str], require_artifact: bool = False, ) -> str: """ First, try and get the value from artifacts; if no artifact and require_artifact, throw error then fall back to $TAG; then fall back to "dev"...
bff7de55291e77a7b59aab07a5d986d28d3da33d
3,616,163
import os def list_results_files(path, instanceid, omittedfiles): """ lists the files associated with an instanceid leavuing out the omittedfiles and in ascending age. :param path: :param instanceid: :param omittedfiles: :return: """ files = sorted(os.listdir(os.path.join(path, instanc...
c7e1d5e62ef1e4dc87a321cf0c391397fad8bc7c
3,616,164
def two_fer(name="you"): """Returns a string in the two-fer format.""" return "One for " + name + ", one for me."
a7f10a45b214ea1ea79a6956148b3c6677f27e21
3,616,165
import random def insere_randomico(lista, qtd_insercao): """ Insere n elementos de acordo com a quantidade passada por parametro qtd_insercao - quantidade a ser inserida na lista """ for i in range(qtd_insercao): lista.append(random.randint(1,10000)) random.shuffle(lista) return li...
8e208870893e3809db6e589ec41a305a8e089b80
3,616,166
def use_case_config(privilege=None, request_object=NoneType): """Class decorator that allows to attach a privilege and a request_object class to a certain use case class Usage: @use_case_config(Privileges.ListStudies, ListStudiesRO) class ListStudiesUC(UseCase): pass :param privilege...
2b9c96333ca55c53eda4e86ad46734ab5492898a
3,616,167
def project(ifs: IteratedFunctionSystem, point: Vec) -> Vec: """Project a point by repeatedly applying functions from the IFS. :param ifs: The Iterated Function System to use for projection. :param point: The point in the plane to repeatedly project. :returns: A point obtained by applying random functi...
5389b902d8d3e158abc5adab8305597d02db1577
3,616,168
import math def create_pagination(page, results_per_page, total_results): """Create pagination to filter results to manageable amounts.""" pagination = {} # For UI pagination['page'] = page pagination['total_results'] = total_results pagination['total_pages'] = math.ceil(total_results / resul...
d58bf2adee3e090e88aa82a5a91560e8fb1631e0
3,616,169
def get_source(url): """Return the source of the supplied url argument""" http = httplib2.Http() try: status, response = http.request(url, headers={'User-Agent':' Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0'}) if status.status == 200: return response else: return None ex...
f0c9f98d8de070ccf0d0f88582ab4fc5227a771c
3,616,170
def pygrep_iterator(iterator, keyword, ilen=100, ishift=0, begin=0): """ """ ibuffer = -1 out_str = "" maxlen = ishift + ilen # for line in iterator: if keyword in line: out_str = keyword + line.partition(keyword)[2] ibuffer = len(out_str) break #...
c5438357792155007ab479d37bccf1ae1bd2373b
3,616,171
def sdebug(f): """ debugging decorator for _store functions """ def newf(*args, **kwds): print('{0:20} {1:20}'.format(f.func_name, args[2])) return f(*args, **kwds) newf.__doc__ = f.__doc__ return newf
ec5a15281b799cc37a30352ac3dff4dd7ffa32ad
3,616,172
def waveletCoeffs(name): """ Return the wavelet coefficients according to the wavelet name. Parameters ---------- name : str Name of wavelet. Supported values: * '**haar**' : Haar wavelet * '**db1**'-'**db20**' : Daubechie wavelets with different support size ...
b0c692f25326c127a3a91eb060cd964705ef955f
3,616,173
import socket import struct def get_default_gateway_linux(): """Read the default gateway directly from /proc.""" with open("/proc/net/route") as fh: for line in fh: fields = line.strip().split() if fields[1] != '00000000' or not int(fields[3], 16) & 2: # If not ...
9dd0117358d7b333d03cf1cf87a02c0d7f203943
3,616,174
def find_or_update_user(id, role=None): """ Find existing user and update role """ user = User.query.filter(User.id == id).first() if user and role: user.roles.append(role) db.session.commit() return user
ceef9023dc1222595141a66eb3fbd05e54efe205
3,616,175
def conv_len(a, l): """ Function that converts a number into a bit string of given length :param a: number to convert :param l: length of bit string :return: padded bit string """ b = bin(a)[2:] padding = l - len(b) b = '0' * padding + b return b
b3c28e82c759e3a433ca9b52d7e7726f786e76ff
3,616,176
def catalog_to_mask(catalog, shape, wcs, radius=np.radians(4/60)): """ Convert catalog with DEC, RA values to binary point source mask. Parameters ---------- catalog : (2, N) array DEC and RA values (in radians) for each point source. shape : tuple Shape of output map. wcs :...
35360e67473affa3c4bc8fbe1c8da10a728337cb
3,616,177
def xml_check_xsd(xml, flavor='autodetect', level='autodetect'): """ Validate the XML file against the XSD :param xml: the Factur-X or Order-X XML :type xml: string, file or etree object :param flavor: possible values: 'factur-x', 'zugferd', 'order-x' or 'autodetect'. Value 'zugferd' means ZUGFe...
f40556d2a4a54e5de2c1217ae11d411ea467b0f6
3,616,178
import os import base64 def get_image_as_b64(uuid, filetype='png'): """Gets b64 image string by uuid :param uuid: uuid of image :param filetype: file type to output, options are jpeg, png, or gif :returns: b64 string of image """ filetype = filetype.lower() img_format = None ...
986c5b55bb54c9174749c607e5324b49e74ff717
3,616,179
import math def _cost_of(rule): """Calculate the cost of a rule based on the number of constraints. Rules requiring more tokens to match are made less costly and tried first. """ return math.log2(1 + 1 / (1 + _num_tokens_of(rule)))
819ef7c2f1115c553d1be62f0dc9ec727b3e9f1f
3,616,180
from datetime import datetime import logging def generate_test_cohort(project, max_size=10, write=False, user_interval_size=1, rev_interval_size=7, rev_lower_limit=0): """ Build a t...
fd8ffdc83143e835ac10a18eff2af8bfb2f144e3
3,616,181
def ensure_aware_datetime(dt, default_tz=UTC): """ Ensures that the returned datetime object is not naive. """ if dt.tzinfo is None: dt = dt.replace(tzinfo=default_tz) return dt
e211cea62f22f089df922dbb88a6548a754e8daa
3,616,182
import socket def ping_target(target, timeout, count, size): """Ping a target and handle socket errors. Returns: pythonping.ResponseList socket.error RuntimeError """ try: return pythonping.ping( target=target, timeout=timeout, coun...
d9c0e1223c1444bc8a7b890d1b0fa4678febfcc2
3,616,183
def validate_password(password): """Validates a password Notes ----- The valid characters for a password are: * lowercase letters * uppercase letters * numbers * special characters (e.g., !@#$%^&*()-_=+`~[]{}|;:'",<.>/?) with the exception of a backslash ...
09628fed13c161a477d28fa8016bc2cccf0b298e
3,616,184
def Sub(a, b): """ Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). :param a: operand a :param b: operand b :return: a - b if a - b > 0 or revert the transaction. """ Require(a>=b) return a-b
5f6fde80f3b4a6da31b0eb75ddfb680c0667ed33
3,616,185
def wrap_mc_method(func, f_args, f_kwargs, return_val, funcname=None): """Pulls the operation and (for get) whether a key was found, on each public method.""" kvs = {} if funcname in MC_COMMANDS: kvs['KVOp'] = funcname # could examine f_args for key(s) here if funcname == 'get': kvs[...
867265d4c3b7446cc5380c366d5a16f3ceae1932
3,616,186
def binary_accuracy(output: paddle.Tensor, target: paddle.Tensor) -> float: """Computes the accuracy for binary classification""" with paddle.no_grad(): batch_size = target.shape[0] # .size(0) pred = (output >= 0.5).t().flatten() # .view(-1) correct = pred.eq(target.flatten()).sum() ...
28a92cec755168c31e5deeec3a729b7bb6800c6e
3,616,187
def check_iban(iban): """Check the syntax and the checksum of an IBAN. Return the parts of the IBAN: Country Code, Checksum, Bank/Branch Code and Account number. Raise an IBANError exception if the input is not correct. """ err = None code = iban[:2] checksum = iban[2:4] bban ...
2cb6ded222499973dcb0d2516c43401b1648be9b
3,616,188
def best_step(x, y): """ Fits a step function to the data. Returns ------- low, high, threshold : floats The parameters of the step function """ ths = x[2:-2] scores = np.array([((y - degrau(x, y[x<th].mean(), y[x>=th].mean(), th))**2).sum() for th in ths]) th = ths[scores...
773223a2a9c4466025511920c3b396a7f801898a
3,616,189
def peek(buckets, max_builds=None, start_cursor=None): """Returns builds available for leasing in the specified |buckets|. Builds are sorted by creation time, oldest first. Args: buckets (list of string): fetch only builds in any of |buckets|. max_builds (int): maximum number of builds to return. Defaul...
80641dcdf3e97e8a4d020c139187f4bb90b43f0f
3,616,190
import math def a_raininess_oracle(timestep): """Mimics an external data source for raininess Arguments ========= timestep : int Requires a year between 2010 and 2050 Returns ======= raininess : int """ msg = "timestep {} is outside of the range [2010, 2050]".format(time...
e1b4f32f62fe19f95ac876a0acf03fe533858366
3,616,191
def load_model_keras(model_path): """ Loads Keras model. :param model_path: Path to H5 model. :return: Keras model. """ model_loaded = load_model(model_path) return model_loaded
7289af5e628ad50275d6da78956bc8635d88c20e
3,616,192
def user_identity_lookup(user: User) -> str: """Define identity user field.""" return user.email
ff1251eee8c126b94d37c3302e4fa4b1a1060cd8
3,616,193
def plot_data_tiled(data, normalize=False, title="", vmin=None, vmax=None, cmap="Greys_r", save_filename=None): """ Save figure for input data as a tiled image Inpus: data: [np.ndarray] of shape: (height, width, features) - single image (n, height, width, features) - n images normalize: [boo...
15c76eff2ff16ec4f1eb2a254a395a339afd5d66
3,616,194
import asyncio def extract_entity(funct): """Decorate for extract entity object from request.""" @asyncio.coroutine def async_api_entity_wrapper(hass, config, request): """Process a turn on request.""" entity_id = request[API_ENDPOINT]['endpointId'].replace('#', '.') # extract sta...
c623443933d801ad0526fbe293d37b87a13b76bd
3,616,195
def _value_name(value): """Return the name of the value.""" return '{} {}'.format(_node_name(value.node), value.label)
f2efacd23b86787d246fa9257aeb235d72dd9fc8
3,616,196
def shrinking_sphere(xyz, vxyz, m, delta=0.025): """ Compute the center of mass coordinates and velocities of a halo using the Shrinking Sphere Method Power et al 2003. It iterates in radii until reach a convergence given by delta of 1% of the total number of particles while there are more than 1000...
9a97509647fcff67a7ff22d83a60ce4ecfa99f3b
3,616,197
def movefiles(): """ function to move files. """ data=json.loads(request.data) parentid = data["parentid"] filelist = data["filelist"] if len(filelist) > 0: try: return update.movefiles(parentid,filelist,current_user) except Exception as e: print e ...
5e52d08d5ee3de1126da6bb3cc2ca860d53ab130
3,616,198
from math import ceil def get_positives(scores, label, other_labels, threshold, shift = 10): """ :param scores: :param label: :param other_labels: :param threshold: :return: """ avg_window_half_size = int(ceil(100 / shift)) positives = [] x = scores[:, label] peaks = fin...
a5e655cee5db2facd77f33efb5abaadf9b676697
3,616,199