content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def d2tf(ndp, days): """ Wrapper for ERFA function ``eraD2tf``. Parameters ---------- ndp : int array days : double array Returns ------- sign : char array ihmsf : int array Notes ----- The ERFA documentation is below. - - - - - - - - e r a D 2 t f - ...
5577e48bf50304cbda71947e673e06ab09d18ea7
3,629,000
def libxl_init_members(ty, nesting = 0): """Returns a list of members of ty which require a separate init""" if isinstance(ty, idl.Aggregate): return [f for f in ty.fields if not f.const and isinstance(f.type,idl.KeyedUnion)] else: return []
fae1eb0e3962ee59df83209ba605473f893cb2ea
3,629,001
import os from sys import path import imp def find_commands(cache=True): """ Scans the script directory and extracts all commands. """ global _command_cache if _command_cache is not None and cache: return _command_cache files = os.walk(command_dir) commands = {} for (dirpath, ...
046daf38a6b61efb67c82decf851bb5769ffa8be
3,629,002
from datetime import datetime import os import fnmatch def snr_and_sounding(radar, soundings_dir=None, refl_field_name='DBZ'): """ Compute the signal-to-noise ratio as well as interpolating the radiosounding temperature on to the radar grid. The function looks for the radiosoundings that happened at t...
506f7d0c7a5be778915b1c5d22b5ad3064619400
3,629,003
from operator import concat def make_weekly_data(con, ticker_id, begin_date, today): """ INPUTS: con (mysql) - pymysql database connection ticker_id (int) - Ticker id number from symbols table begin_date (str) - Last price date in series. Iso8601 standard format today (str) - T...
8cb9f4baca363df8f081ccf8a6eae5dc90ecd5d3
3,629,004
import zmq def kill_service(ctrl_addr): """kill the LLH service running at `ctrl_addr`""" with zmq.Context.instance().socket(zmq.REQ) as sock: sock.setsockopt(zmq.LINGER, 0) sock.setsockopt(zmq.RCVTIMEO, 1000) sock.connect(ctrl_addr) sock.send_string("die") return soc...
8ffdb8fda4e8ed6c9b82a70fa70adbe6fcdc7f29
3,629,005
def dmp_grounds(c, n, u): """ Return a list of multivariate constants. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.densebasic import dmp_grounds >>> dmp_grounds(ZZ(4), 3, 2) [[[[4]]], [[[4]]], [[[4]]]] >>> dmp_grounds(ZZ(4), 3, -1) [4, 4, 4] ...
32f2e60bce921f525336fd8288c4736ee7677129
3,629,006
def has_attrs(inst, *args): """ checks if the instance has all attributes as specified in *args and if they not falsy :param inst: obj instance :param args: attribute names of the object """ for a in args: try: if not getattr(inst, a, None) return False ...
297911bd61824cf171946afa26014ffcd0ee6be1
3,629,007
def get_related_offers(order): """ Search related offers to order from parameter :param order: client order :return: string with related offers to order from parameter or empty string """ related_offers = "" if OrdersOffers.objects.filter(order=order).count() > 0: order_offers = Orde...
d55c3d58b4e88161fbeaa3226d4d9ee636b53de4
3,629,008
import torch def undo_imagenet_preprocess(image): """ Undo imagenet preprocessing Input: - image (pytorch tensor): image after imagenet preprocessing in CPU, shape = (3, 224, 224) Output: - undo_image (pytorch tensor): pixel values in [0, 1] """ mean = torch.Tensor([0.485, 0.456, 0.406]).v...
57d4cfc365c4e6c2dcfd37c8a2c500465daa421a
3,629,009
def ob_mol_from_file(fname, ftype="xyz", add_hydrogen=True): """ Import a molecule from a file using OpenBabel fname: the path string to the file to be opened ftype: the file format add_hydrogen: whether or not to insert hydrogens automatically openbabel does not always add ...
6dbbff4dc176637274af53799143e3bc862d403a
3,629,010
def collapse(html): """Remove any indentation and newlines from the html.""" return ''.join([line.strip() for line in html.split('\n')]).strip()
a5a55691f2f51401dbd8b933562266cbed90c63d
3,629,011
import torch def multiclass_cross_entropy(phat, y, N_classes, weights, EPS = 1e-30) : """ Per instance weighted cross entropy loss (negative log-likelihood) """ y = F.one_hot(y, N_classes) # Protection loss = - y*torch.log(phat + EPS) * weights loss = loss.sum() / y.shape[0] ret...
782e230c49314e8426a8a78cc78709929dadcf67
3,629,012
def get_arc_polygon(resolution,size=[1,1],arc=[0,1]): """resolution is the quantity of polygon points horizontal and vertical size are requested arc give the starting and ending angles""" polygon=[] for increment in range(resolution+1): inc= arc[1]*(increment/resolution) angl=(arc[0]+inc)*pi*2 polygon.append...
7688bd90c093fb3db4a822af8e4ddd317d55cd62
3,629,013
def load(filename): """ Loads data line by line from a .wbp file, initiates a WellPlan object and populates it with data. Parameters ---------- filename: string The location and filename of the .wbp file to load. Returns ------- A welleng.exchange.wbp.WellPlan o...
d0606514ffe89e9e3f09b76c8becd65db94e0bd9
3,629,014
def get_input_fn(data_dir, is_training, num_epochs, batch_size, shuffle, normalize=True): """ This will return input_fn from which batches of data can be obtained. Parameters ---------- data_dir: str Path to where the mnist data resides is_training: bool Whether to read the trai...
4f41ff8939df638749efaf4a29106cc363a6737e
3,629,015
from pyngrok import ngrok from jupyter_dash import JupyterDash from dash import Dash def getDashApp(title:str, notebook:bool, usetunneling:bool, host:str, port:int, mode: str, theme, folder): """ Creates a dash or jupyter dash app, returns the app and a function to run it :param title: Passed to dash app...
dfc5c8196f9a86a6efaa79fdb938189b10f1b1aa
3,629,016
def get_pagination_request_params(): """ Pagination request params for a @doc decorator in API view. """ return { "page": "Page", "per_page": "Items per page", }
8ceb2f8ead3d9285017b595671f02817d098bc40
3,629,017
def access_bit(data, num): """ from bytes array to bits by num position """ base = int(num // 8) shift = 7 - int(num % 8) return (data[base] & (1 << shift)) >> shift
fed874d0d7703c9e697da86c5a5832d20b46ebe5
3,629,018
def _any_isclose(left, right): """Short circuit any isclose for ndarray.""" return _any(np.isclose, left, right)
8732c8db0b3e574a220c534ae7336acd89dbe753
3,629,019
def push(src, dest): """ Push object from host to target :param src: string path to source object on host :param dest: string destination path on target :return: result of _exec_command() execution """ adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_PUSH, src, dest] return _exec_comm...
926964ac7aa8b6c9e83c2049128bee138c5157ba
3,629,020
def merge_set_if_true(set_1, set_2): """ Merges two sets if True :return: New Set """ if set_1 and set_2: return set_1.from_merge(set_1, set_2) elif set_1 and not set_2: return set_1 elif set_2 and not set_1: return set_2 else: return None
833e6925ef2b3f70160238cdc32516be2482082d
3,629,021
import pytz def localtime(utc_dt, tz_str): """ Convert utc datetime to local timezone datetime :param utc_dt: datetime, utc :param tz_str: str, pytz e.g. 'US/Eastern' :return: datetime, in timezone of tz """ tz = pytz.timezone(tz_str) local_dt = tz.normalize(utc_dt.astimezone(tz)) ...
f48844c72895813fdcd3913cfe7de0e6f6d0ac3c
3,629,022
from typing import List import torch def _flatten_tensor_optim_state( state_name: str, pos_dim_tensors: List[torch.Tensor], unflat_param_names: List[str], unflat_param_shapes: List[torch.Size], flat_param: FlatParameter, ) -> torch.Tensor: """ Flattens the positive-dimension tensor optimiz...
1b8ebbbe99cc5d0ce6f48ef9f321c8ea4fd0b7ee
3,629,023
def variance ( func , xmin = None , xmax = None , err = False ) : """Get the variance for the distribution using >>> fun = ... >>> v = variance( fun , xmin = 10 , xmax = 50 ) """ ## ## get the functions from ostap.stats.moments actor = lambda x1,x2 : Variance ( x1 , x2 , err ) ## use...
da2978abca2ecaa2754564d3bc7f5a82915211ac
3,629,024
def get_mysql_entitySets(username, databaseName): """ View all the enity sets in the databaseName """ password = get_password(username) try: cnx = connectSQLServerDB(username, password, username + "_" + databaseName) mycursor = cnx.cursor() sql = "USE " + username + "_" + databaseNam...
3eac962c936422258a2740e5ef429a72a440da92
3,629,025
def check_dbconnect_success(sess, system): """ 測試資料庫是否成功連上(若連上且查詢成功代表資料庫存在) Args: sess: database connect session system: 使用之系統名稱 Returns: [0]: status(狀態,True/False) [1]: err_msg(返回訊息) """ try: if not sess.execute("select 1 as is_alive"): raise Exception ...
28a4bfc0ac1a71ba9d7d13f62cea1f4bb9cec385
3,629,026
def split(filename, size=10.): """split the figure into color bands""" arr, aspect = _load_array(filename) fig = Figure(figsize=(size, size*aspect)) cmaps = ['Reds_r', 'Greens_r', 'Blues_r', 'gray_r'] for i, band in enumerate(arr): ax = fig.add_axes([(i % 2) * .5, (1 - i // 2) * .5, .5, .5...
4e64ed73c2054aef1f729674f13c059010466c0a
3,629,027
from sys import argv def main(): """ Main body """ # validate the input if len(argv) != 2: print("usage: python gen_rand_sys.py <size of grid>") return 1 else: # get size from input size = int(argv[1]) grid = gen_rand_sys(size) print(grid)
c93361f08c6f7ea1bd0f57bb8c129fcf0f717cd9
3,629,028
def _compute_common_args(mapping): """Compute the list of arguments for dialog common options. Compute a list of the command-line arguments to pass to dialog from a keyword arguments dictionary for options listed as "common options" in the manual page for dialog. These are the options that are not ...
3e3dff995864d64452e8ef091ec949b281899455
3,629,029
def is_url(url): """URL書式チェック""" return url.startswith("https://") or url.startswith("http://")
bc8f59d2e96e0a625317e86216b9b93077bbf8e2
3,629,030
import re def _preclean(Q): """ Clean before annotation. """ Q = re.sub('#([0-9])', r'# \1', Q) Q = Q.replace('€', ' €').replace('\'', ' ').replace(',', '').replace('?', '').replace('\"', '').replace('(s)', '').replace(' ', ' ').replace(u'\xa0', u' ') return Q.lower()
115828037b884108b9e3324337874c6b23dc066c
3,629,031
import aiohttp async def job_info(request): """Get job info.""" conn_manager = request.app[common.KEY_CONN_MANAGER] conn_uid = request.match_info[ROUTE_VARIABLE_CONNECTION_UID] job_uid = request.match_info[ROUTE_VARIABLE_JOB_UID] connection = conn_manager.connection(conn_uid) info = await conn...
29ad0a6fb10d1ce0b982743443889d0771940d7d
3,629,032
from typing import Dict from typing import Callable def load_dataset_map() -> Dict[str, Callable]: """ Get a map of datasets. Returns: Dict[str, Callable]: Key: Dataset name, Value: loader function which returns (X, y). """ dss = { "iris-2d": load_iris_2d, "wine-2d": load_...
9ecb35ba59ef1c15f0d0d609d269c2c8a54aed3b
3,629,033
def m2fs_pixel_flat(flatfname, fiberconfig, Npixcut): """ Use the flat to find pixel variations. DON'T USE THIS. It doesn't work. """ R, eR, header = read_fits_two(flatfname) #shape = R.shape #X, Y = np.meshgrid(np.arange(shape[0]), np.arange(shape[1]), indexing="ij") tracefn = m2fs...
07a82fe106f38e9da70c02d1195e596606c9d835
3,629,034
def HTTP405(environ, start_response): """ HTTP 405 Response """ start_response('405 METHOD NOT ALLOWED', [('Content-Type', 'text/plain')]) return ['']
f07522ac904ec5ab1367ef42eb5afe8a2f0d1fce
3,629,035
from operator import concat import torch import io import time def train_one_batch(batch, generator, optimizer, reward_obj, opt, global_step, tb_writer, lagrangian_params=None, cost_objs=[]): #src, src_lens, src_mask, src_oov, oov_lists, src_str_list, trg_sent_2d_list, trg, trg_oov, trg_lens, trg_mask, _ = batch ...
d8f1df07641584860022def119f8f49db3e6e5dc
3,629,036
import sys import os def getProgramName(): """Get the name of the currently running program.""" progName = sys.argv[0].strip() if progName.startswith('./'): progName = progName[2:] if progName.endswith('.py'): progName = progName[:-3] # Only return the name of the program not the ...
486c454756dea87b7b422fb00e80e1346183d9d2
3,629,037
from datetime import datetime from typing import Iterable def get_all_trips(*, date_from: datetime, date_to: datetime, departure_station: BusStation, arrival_station: BusStation) \ -> Iterable[Trip]: """ [Step1] filter trips with departure time between `date_form` and `date_to` [Step2] filter trip...
be58f578740bde35b45435d1f82a4d5e82b4dc6d
3,629,038
from typing import Callable from typing import Optional from datetime import datetime import httpx import time def get_coinbase_api_response( get_api_url: Callable, base_url: str, timestamp_from: Optional[datetime] = None, pagination_id: Optional[str] = None, retry=30, ): """Get Coinbase API r...
bc34ab3980f782403321d65214f0dad27e92e800
3,629,039
def intersect(A, B, C, D): """ Finds the intersection of two lines represented by four points. @parameter A: point #1, belongs to line #1 @parameter B: point #2, belongs to line #1 @parameter C: point #3, belongs to line #2 @parameter D: point #4, belongs to line #2 @returns: None if lines are...
54bb9fc4c826de00d144120edea55463699214ac
3,629,040
def detect(inputs, anchors, n_classes, img_size, scope='detection'): """Detect layer """ with tf.name_scope(scope, 'detection',[inputs]): n_anchors = len(anchors) bbox_attrs = 5+n_classes predictions = inputs grid_size = predictions.get_shape().as_list()[1:3] n_dims = grid_size[0] * grid_size...
4751db9980137cf3f5acaee9a900653d5f31e90e
3,629,041
def get_scenario_data(): """Return sample scenario_data """ return [ { 'population_count': 100, 'county': 'oxford', 'season': 'cold_month', 'timestep': 2017 }, { 'population_count': 150, 'county': 'oxford', ...
b66ba716e6bd33e1a0ff80735acb64041663ed99
3,629,042
def user_not_found(error): """Custom error handler. More info: http://flask.pocoo.org/docs/1.0/patterns/apierrors/#registering-an-error-handler """ response = jsonify(error.to_dict()) response.status_code = error.status_code return response
3b63876308d616d4d206b3eaa4742a77490f4c50
3,629,043
from typing import Dict from typing import Any def get_do_pass_with_amendments_by_committee( biennium: str, agency: str, committee_name: str ) -> Dict[str, Any]: """See: http://wslwebservices.leg.wa.gov/committeeactionservice.asmx?op=GetDoPassWithAmendmentsByCommittee""" argdict: Dict[str, Any] = dict(bie...
f27622c2840b3375181f42e373ad96c569d2edc6
3,629,044
def petrosian_fd(x): """Petrosian fractal dimension. Parameters ---------- x : list or np.array One dimensional time series Returns ------- pfd : float Petrosian fractal dimension Notes ----- The Petrosian algorithm can be used to provide a fast computation of ...
775d0e27d305d0111d20a001282d369f78f7d48e
3,629,045
def lemma(word): """ Transforms a given word to its lemmatized form, checking a lemma dictionary. If the word is not included in the dictionary, the same word is returned. :param word: string containing a single word :type: string :return: the word's lemma :type: string """ return le...
04f434d7a86ceeadc16a2d2a4eb329f7b814e61a
3,629,046
def is_style_file(filename): """Return True if the filename looks like a style file.""" return STYLE_FILE_PATTERN.match(filename) is not None
18a85b21d898b27e65d8debcda408507ba5ca5d9
3,629,047
def add_subnet(): """add subnet. Must fields: ['subnet'] Optional fields: ['name'] """ data = _get_request_data() return utils.make_json_response( 200, network_api.add_subnet(user=current_user, **data) )
82db191d2b678cbf873ac80878138708a10371c7
3,629,048
def V_beta(gamma, pi): """ Defining function for the expected utility for insured agent, where we know the coverage ratio gamma and x is drawn from beta distribution. Args: pi(float): insurance premium gamma(float): coverage ratio Returns: Expected utility for agent. ...
bf21816d5c80f34e8bc8c8883de14b739520a0da
3,629,049
def counted(fn): """ count number of times a subroutine is called :param fn: :return: """ def wrapper(*args, **kwargs): wrapper.called+= 1 return fn(*args, **kwargs) wrapper.called= 0 wrapper.__name__= fn.__name__ return wrapper
5c1ad20af39ed745718726045fa9f23938d7e479
3,629,050
def removeneg(im, key=0): """ remove NAN and INF in an image """ im2 = np.copy(im) arr = im2 < 0 im2[arr] = key return im2
572aa73d2f50f48b7940e476ba4cd885f93151d4
3,629,051
def mape(df, w): """Mean absolute percent error Parameters ---------- df: Cross-validation results dataframe. w: Aggregation window size. Returns ------- Dataframe with columns horizon and mape. """ ape = np.abs((df['y'] - df['yhat']) / df['y']) if w < 0: return pd....
c42c1fd32d71f0f2a2c2224fc88e1f9ecc467c39
3,629,052
def p3p(pts_2d, pts_3d, K, q_ref=None, allow_imag_roots=False): """An implementation of the ... problem from "A Stable Algebraic Camera Pose Estimation for Minimal Configurations of 2D/3D Point and Line Correspondences", from Zhou et al. at ACCV 2018. 3 points pts_2d - pixels in 2d. Each pixel is ...
a042a9adb9f4c8d705fe8fdc54c4e100c083db50
3,629,053
def status() -> tuple: """Health check endpoint.""" return xmlify('<status>ok</status>'), HTTP_200_OK
0479c7f3a18b30680f8878c3f439ff9c8a18538b
3,629,054
from typing import Dict from typing import Any from typing import Sequence def nested_keys(nested_dict: Dict[Text, Any], delimiter: Text = '/', prefix: Text = '') -> Sequence[Text]: """Returns a flattend list of nested key strings of a nested dict. Args: nested_dict: Nested di...
7403321634986897e3ab9b974ba91dc81a2b0941
3,629,055
import os def add_it(workbench, file_list, labels): """Add the given file_list to workbench as samples, also add them as nodes. Args: workbench: Instance of Workbench Client. file_list: list of files. labels: labels for the nodes. Returns: A list of md5s. """ md5...
88e85b8bcc2fdbf6fdac64b9b4e84d82e7ea3185
3,629,056
def has_id(sxpr, id): """Test if an s-expression has a given id. """ return attribute(sxpr, 'id') == id
a7e7ce73c8c99af003dfff9954b351bb0e02cd41
3,629,057
def gf_gcdex(f, g, p, K): """Extended Euclidean Algorithm in `GF(p)[x]`. Given polynomials `f` and `g` in `GF(p)[x]`, computes polynomials `s`, `t` and `h`, such that `h = gcd(f, g)` and `s*f + t*g = h`. The typical application of EEA is solving polynomial diophantine equations. Consid...
e40ceccf34173d4b6349ea2c77147e2a81ff09e4
3,629,058
from datetime import datetime def _filetime_from_timestamp(timestamp): """ See filetimes.py for details """ # Timezones are hard, sorry moment = datetime.fromtimestamp(timestamp) delta_from_utc = moment - datetime.utcfromtimestamp(timestamp) return dt_to_filetime(moment, delta_from_utc)
81122e093c78004392e3eee7819c52bc62d8d60b
3,629,059
from typing import Callable from typing import Optional from typing import Union from typing import Type from typing import Sequence from typing import Any from typing import get_type_hints def optimize( func: Callable[[np.ndarray], float], x: ArrayLike, trials: int = 3, iterations: Optional[int] = 15...
ccef3d67669e0420e88b119d9c180fb35a0a98f8
3,629,060
import types def _create_reconstruction( n_cameras: int=0, n_shots_cam=None, n_pano_shots_cam=None, n_points: int=0, dist_to_shots: bool=False, dist_to_pano_shots: bool=False, ): """Creates a reconstruction with n_cameras random cameras and shots, where n_shots_cam is a dictionary, con...
c381724cbaf7da1e368744ce874d4a9702b0033e
3,629,061
from typing import Set from typing import Tuple from typing import cast from typing import List from typing import Dict from typing import Any def _validate_dialogue_section( protocol_specification: ProtocolSpecification, performatives_set: Set[str] ) -> Tuple[bool, str]: """ Evaluate whether the dialogue...
a9155544cae98723bb629d40ae24275c483c807a
3,629,062
def _hsic_naive(x, y, scale=False, sigma_x=None, sigma_y=None, kernel='gaussian', dof=0): """ Naive (slow) implementation of HSIC (Hilbert-Schmidt Independence Criterion). This function is only used to assert correct results of the faster method ``hsic``. Parameters ---------- ...
03ff899048ce740873cd32fc64ba4ce517e8cd5a
3,629,063
from datetime import datetime def translate(raw_path): """Reads official Rio de Janeiro BRT realized trips file and converts to standarized realized trips. TODO: - get trip_id, maybe from GTFS? - get departure_id and arrival_id, also from GTFS? Parameters ---------- raw_path : str ...
333daf9883a959b1fac53cc676405b7c629551e1
3,629,064
def get_percentage(numerator, denominator, precision = 2): """ Return a percentage value with the specified precision. """ return round(float(numerator) / float(denominator) * 100, precision)
7104f6bf2d88f9081913ec3fbae596254cdcc878
3,629,065
def _calculate_verification_code(hash: bytes) -> int: """ Verification code is a 4-digit number used in mobile authentication and mobile signing linked with the hash value to be signed. See https://github.com/SK-EID/MID#241-verification-code-calculation-algorithm """ return ((0xFC & hash[0]) << 5) |...
173f9653f9914672160fb263a04fff7130ddf687
3,629,066
def add_message(user, text, can_dismiss=True): """Add a message to the user's message queue for a variety of purposes. :param user: the instance of `KlaxerUser` to add a message to :param text: the text of the message :param can_dismiss: (optional) whether or not the message can be dismissed :retur...
f0deff8ed230716b88ed9876a06509f04c1cbfbf
3,629,067
def dataQC(json_data): """ perform quality analysis on data """ bad_data = {} for device in json_data.keys(): for item in json_data[device]: if item[1] <= check_lower * abs_std[0+omit_lower]: if device not in bad_data: bad_data[device] = [] ...
388465f3388f871f7a1bd397c964bff63681fac4
3,629,068
from typing import Union from typing import Tuple from typing import List from typing import Optional def get_interatomic_r(atoms: Union[Tuple[str], List[str]], expand: Optional[float] = None) -> float: """ Calculates bond length between two elements Args: atoms (list or tup...
befa7950d0cd52ba26576c9c5c12589f71604577
3,629,069
def annualized_return_nb(returns, ann_factor): """2-dim version of `annualized_return_1d_nb`.""" result = np.empty(returns.shape[1], dtype=np.float_) for col in range(returns.shape[1]): result[col] = annualized_return_1d_nb(returns[:, col], ann_factor) return result
8e7c3ae47a81b7a700b5714544aabd0d9105f88c
3,629,070
import resource def canon_ref(did: str, ref: str, delimiter: str = None, did_type: str = None): """ Given a reference in a DID document, return it in its canonical form of a URI. Args: did: DID acting as the identifier of the DID document ref: reference to canonicalize, either a DID or a ...
5a0fa42a1a28597ec4863ace221c272ad5114076
3,629,071
def cars_produced_this_year() -> dict: """Get number of cars produced this year.""" return get_metric_of(label='cars_produced_this_year')
96f25b773eaaaaf74bdb9d660830d1ddcff821f5
3,629,072
import argparse def parse_script_args(): """ """ parser = argparse.ArgumentParser(description="Delete images from filesystem.") parser.add_argument('--reg_ip', type=str, required=True, help='Registry host address e.g. 1.2.3.4') parser.add_argument('images', type=str, nargs=...
fc77674d45f22febcb93b6bb0317cb5a0ef18e0f
3,629,073
def merge_authentication_authorities(managed_auth_authority, user_record): """Merge two authentication_authority values, giving precedence to the managed_auth_authority""" existing_auth_authority = get_attribute_for_user( "authentication_authority", user_record) if existing_auth_authority: ...
db5e47be422dbc27d1117040bc3632717112a461
3,629,074
def preprocess_pil_image(pil_img, color_mode='rgb', target_size=None): """Preprocesses the PIL image Arguments img: PIL Image color_mode: One of "grayscale", "rgb", "rgba". Default: "rgb". The desired image format. target_size: Either `None` (default to original size) ...
83cb54157d7bd85299b6bc3149f7f14d9ed52d95
3,629,075
import torch def _handle_coord(c, dtype: torch.dtype, device: torch.device) -> torch.Tensor: """ Helper function for _handle_input. Args: c: Python scalar, torch scalar, or 1D torch tensor Returns: c_vec: 1D torch tensor """ if not torch.is_tensor(c): c = torch.tensor...
129a03900e8047a9c37400568d16316601e25671
3,629,076
import time def current_time_hhmmss(): """ Fetches current time in GMT UTC+0 Returns: (str): Current time in GMT UTC+0 """ return str(time.gmtime().tm_hour) + ":" + str(time.gmtime().tm_min) + ":" + str(time.gmtime().tm_sec)
11a2874237c3fc7d25b93d6f10da167c7d700b33
3,629,077
def equalize_adaptive_clahe(image, ntiles=8, clip_limit=0.01): """Return contrast limited adaptive histogram equalized image. The return value is normalised to the range 0 to 1. :param image: numpy array or :class:`jicimagelib.image.Image` of dtype float :param ntiles: number of tile regions :...
8ecd36bc50e9fd147bee676a92a8ebb1a892c59b
3,629,078
def suggest_parameters_DRE_NMNIST(trial, list_lr, list_bs, list_opt, list_wd, list_multLam, list_order): """ Suggest hyperparameters. Args: trial: A trial object for optuna optimization. list_lr: A list of floats. Candidates of learning rates. list_bs: A list of ints. Candidate...
627855f5fe8fd15d43cc7c8ca3da22b704b5907e
3,629,079
def format_seconds(seconds, hide_seconds=False): """ Returns a human-readable string representation of the given amount of seconds. """ if seconds <= 60: return str(seconds) output = "" for period, period_seconds in ( ('y', 31557600), ('d', 86400), ('h', 3600)...
341ab077b9f83a91e89a4b96cb16410efab90c1c
3,629,080
def _contains_atom(example, atoms, get_atoms_fn): """Returns True if example contains any atom in atoms.""" example_atoms = get_atoms_fn(example) for example_atom in example_atoms: if example_atom in atoms: return True return False
c9e60d956585c185f9fb62cc0d11f169e6b79f88
3,629,081
import yaml import sys def load_config_file(filename): """Load the YAML configuration file.""" try: config = None with open(filename, 'r') as f: config = yaml.load(f) print('Using configuration at {0}'.format(filename)) if not config.keys() == default_config.key...
183ae3ad10caa0ddc4324772c32181660c162e6c
3,629,082
import torch import math def kllossGn2(o, l: 'xtrue'): """KL loss for Gaussian-mixture output, 2D, precision-matrix parameters.""" dx = o[:,0::6] - l[:,0,np.newaxis] dy = o[:,2::6] - l[:,1,np.newaxis] # precision matrix is positive definite, so has positive diagonal terms Fxx = o[:,1::6]**2 Fyy = o[...
198b6b5189d72171b87e05998d326d006e6d156d
3,629,083
def IngestApprovalDelta(cnxn, user_service, approval_delta, setter_id, config): """Ingest a protoc ApprovalDelta and create a protorpc ApprovalDelta.""" fids_by_name = {fd.field_name.lower(): fd.field_id for fd in config.field_defs} approver_ids_add = IngestUserRefs( cnxn, approval_d...
5f1851ac2cfb7f2515da9468701a2c92e9d457cd
3,629,084
def get_diff_level(files): """Return the lowest hierarchical file parts level at which there are differences among file paths.""" for i, parts in enumerate(zip(*[f.parts for f in files])): if len(set(parts)) > 1: return i
c9c3f774712684c6817c8bb5b3bf9c101e1df8fa
3,629,085
def get_max(list_tuples): """ Returns from a list a tuple which has the highest value as first element. If empty, it returns -2's """ if len(list_tuples) == 0: return (-2, -2, -2, -2) # evaluate the max result found = max(tup[0] for tup in list_tuples) for result in list_tuples:...
91c662d5865de346a1ac73025ced78a996077111
3,629,086
def prepare_observation_lst(observation_lst): """Prepare the observations to satisfy the input fomat of torch [B, S, W, H, C] -> [B, S x C, W, H] batch, stack num, width, height, channel """ # B, S, W, H, C observation_lst = np.array(observation_lst, dtype=np.uint8) observation_lst = np.move...
28a4d190c515b4f6aed882b4a3448e49b93f6b39
3,629,087
def test_problem_builder(name: str, n_of_variables: int = None, n_of_objectives: int = None) -> MOProblem: """Build test problems. Currently supported: ZDT1-4, ZDT6, and DTLZ1-7. Args: name (str): Name of the problem in all caps. For example: "ZDT1", "DTLZ4", etc. n_of_variables (int, optional)...
e6917dd1edcd711ae1dd6370223b9bfbca252592
3,629,088
def get_coord_y(x, y): """ Function returns the y value of the coordinate :param x: x value of coordinate :param y: y value of coordinate :return: y value of coordinate """ coord = Coordinates(x, y) return coord.get_y()
ba844806a430130e20cfd320865b78f0af09cf25
3,629,089
import numpy def calc_som2_flow(som2c_1, cmix, defac): """Calculate the C that flows from surface SOM2 to soil SOM2. Some C flows from surface SOM2 to soil SOM2 via mixing. This flow is controlled by the parameter cmix. Parameters: som2c_1 (numpy.ndarray): state variable, C in surface SOM2 ...
a90089f65fa2ff8ea681d9f2c3375920e8cda52c
3,629,090
def cdlseparatinglines(opn, high, low, close): """Separating Lines: Bullish Separating Lines Pattern: With just two candles – one black (or red) and one white (or green) – the Bullish Separating Lines pattern is easy to learn and spot. To confirm its presence, seek out the following criteria: F...
37d4a8e1721cc52157b944c2bf0a8db9a8439f52
3,629,091
def get_context(file_in): """Get genomic context from bed file""" output_dict = {} handle = open(file_in,'r') header = handle.readline().rstrip('\n').split('\t') for line in handle: split_line = line.rstrip('\n').split('\t') contig,pos,context = split_line[:3] if context == '...
90975b6eb929c546372fdce0eb449f455e9ffc18
3,629,092
def get_rating_users_total(contest_id: ContestID) -> int: """Return the number of unique users that have rated bungalows in this contest. """ return User.query \ .join(Rating) \ .join(Contestant) \ .filter(Contestant.contest_id == contest_id) \ .distinct() \ .coun...
25b649f32273c208ae3ad163ffd3ec1929eb1d1c
3,629,093
def read_from_file(filename): """ Reads the set of known plaintexts from the given file. """ candidates = [] with open(filename) as f: lines = f.readlines() if len(lines) > 5: # from first candidate, # to the end of the file, # counting in incre...
d7adda3d84ac02bf2d8095a42dae20b66ca4d4f0
3,629,094
def galactic_offsets_to_celestial(RA, Dec, glongoff=3, glatoff=0): """ Converts offsets in Galactic coordinates to celestial The defaults were chosen by Pineda for Galactic plane survey @param RA : FK5 right ascension in degrees @type RA : float @param Dec : FK5 declination in degrees @type Dec...
737072bc3d26b91dab93a7cbefafe732eba0b43a
3,629,095
import torch from typing import Tuple from typing import List def compute_regularizer_term(model: LinearNet, criterion: torch.nn.modules.loss.CrossEntropyLoss, train_data: Tuple[torch.Tensor, torch.Tensor], valid_data: Tuple[torch.Tensor, torch.Tensor], ...
9216e938f611d085f3c877bb3d9aeb98aaa6565d
3,629,096
def get_to_and(num_bits: int) -> np.ndarray: """ Overview: Get an np.ndarray with ``num_bits`` elements, each equals to :math:`2^n` (n decreases from num_bits-1 to 0). Used by ``batch_binary_encode`` to make bit-wise `and`. Arguments: - num_bits (:obj:`int`): length of the generating...
0da0d253f8951bf54e9d4c2d9d720813fd99c538
3,629,097
def in_role_list(role_list): """Requires user is associated with any role in the list""" roles = [] for role in role_list: try: role = Role.query.filter_by( name=role).one() roles.append(role) except NoResultFound: raise ValueError("role '{...
82f171601b4e823fdc2ab265bd955272d033936d
3,629,098
def handle_not_start(fsm_ctx): """ :param ctx: FSM Context :return: False """ global plugin_ctx plugin_ctx.error("Could not start this install operation because an install operation is still in progress") return False
dc69de1e2c49ed5cda20fecbf9338081c027ff7b
3,629,099