content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import time def test(ipu_estimator, args, x_test, y_test): """ Test the model on IPU by loading weights from the final checkpoint in the given `args.model_dir`. """ def input_fn(): dataset = tf.data.Dataset.from_tensor_slices((x_test, y_test)) dataset = dataset.prefetch(len(x_test...
083c2c830315ccf2602109a4a3e718cecd1b6760
3,658,028
def _get_service(): """Gets service instance to start API searches. Returns: A Google API Service used to send requests. """ # Create the AI Platform service object. # To authenticate set the environment variable # GOOGLE_APPLICATION_CREDENTIALS=<path_to_service_account_file> return g...
5d79698216626eff9618dc55b6b651a5da3f5187
3,658,029
def giq(scores, targets, I, ordered, cumsum, penalties, randomized, allow_zero_sets): """ Generalized inverse quantile conformity score function. E from equation (7) in Romano, Sesia, Candes. Find the minimum tau in [0, 1] such that the correct label enters. """ E = -np.ones((scores.shape[0],)) ...
99a877053cf095622184cbbd9043b742c6ae076f
3,658,030
def findUser(userId): """ :param userId: :return: The user obj Finds a particular user from a dataset. """ return user_collection.find_one({"user_id": userId})
ffca934689c554993ca5d33005a32e4f9afe48cd
3,658,031
def sub_sample_map(data, aug_map, n_input, n_output, n_teach, buffer): """ Expands an augmentation map to produce indexes that will allow targets values of previous outputs to be used as inputs """ n_io = n_input + n_output n_req = n_io teach_range = range(n_teach) tf_map = [] for ...
05f88939ad2e293e3370f5585ad30f1d9d6256d1
3,658,032
def rcGetBBModelEnum(): """ Get the BeagleBone model as member of the BBModel Enum. """ return BBModel(rcGetBBModel())
90cf6857f2754a1947d017a1a57b11790d534c05
3,658,035
def ordToString(ordList): """Use this function to convert ord values to strings.""" newStrList = [] cstr = "" for cint in ordList: cstr += chr(cint) if cint == 44: newStrList.append(cstr[:-1]) cstr = "" return newStrList
5a836f7fe34803744de90aa2608e3d99a081c7ff
3,658,036
def get_test_data_for_successful_build(): """Returns a test data set of test suites and cases that passed. """ return _get_test_data(["PASSED", "PASSED", "PASSED"])
8969d33f887dcc7c7f7fb8148cbcfc7a4eb4d7c1
3,658,037
import re import logging def fromOldAdjacencyList(adjlist, group=False, saturateH=False): """ Convert a pre-June-2014 string adjacency list `adjlist` into a set of :class:`Atom` and :class:`Bond` objects. It can read both "old style" that existed for years, an the "intermediate style" that existe...
0c54ee172948437f9cb075c5880eb7eb25d2893f
3,658,038
def read_arg_optional( src, args, n_optional=-1, tolerance=0, mode=MODE_NON_MATH, skip_math=False): """Read next optional argument from buffer. If the command has remaining optional arguments, look for: a. A spacer. Skip the spacer if it exists. b. A bracket delimiter. If the optional ar...
641fe9ab9a96b6e59e15b115abe843fa09a07659
3,658,039
def searcheduxapian_ajax_get_schlagwort(request, item_container): """ moegliche Schlagworte """ schlagworte = get_schlagworte(request.GET['query']) res = '<items>\n' for schlagwort in schlagworte: res += '<schlagwort>\n<name><![CDATA[%s]]></name>\n</schlagwort>\n' % schlagwort.name res += '</items>\n' r...
5a248ced5006d49f2dc303c68957d07ba187c3d5
3,658,040
def expanded_X_y_sample_weights(X, y_proba, expand_factor=10, sample_weight=None, shuffle=True, random_state=None): """ scikit-learn can't optimize cross-entropy directly if target probability values are not indicator vectors. As a workarou...
7398062d3eb75fa68c39e20415b944e58a20387e
3,658,041
def refine_uniformly(dom, seg): """ Refine all edges of the given domain and segmentation. :param dom: Domain to refine :type dom: :class:`viennagrid.Domain` :param seg: Segmentation of the domain to refine :type seg: :class:`viennagrid.Segmentation` :returns: A two-element tuple containing the output domain...
623b9fc2fa6c83133ca1e01714fecba7e70ab95e
3,658,042
def rename_tuning(name, new_name): """rename tuning""" session = tables.get_session() if session is None: return False, 'connect' try: tuning_table = TuningTable() if not tuning_table.check_exist_by_name(TuningTable, name, session): return False, 'tuning not exist' ...
1ea1498483fc9abe0bb5be7a7c892c6a171b5df9
3,658,043
import re def _xfsdump_output(data): """ Parse CLI output of the xfsdump utility. """ out = {} summary = [] summary_block = False for line in [l.strip() for l in data.split("\n") if l.strip()]: line = re.sub("^xfsdump: ", "", line) if line.startswith("session id:"): ...
dbc7fbf9dced99b83a7dc5917c473a1dee16d749
3,658,045
def get_current(): """Return the currently running interpreter.""" id = _interpreters.get_current() return Interpreter(id)
0949280d364cc6f2935b9109c19c508ed06352b8
3,658,046
def csstext(text: str, cls: str, span: bool=False, header: bool=False) -> str: """ Custom build HTML text element. """ if span: tag = 'span' elif header: tag = 'h1' else: tag = 'p' return f'<{tag} class="{cls}">{str(text)}</{tag}>'
0833fd9d83143e09b5c234e193a8e53ef653112b
3,658,047
def trans_exam_list_to_colum(example_list, headers=None): """ 将example列表转换成以列表示的形式,用于适配输出附加信息 :param example_list: example 列表 :param headers: 需要的属性,默认为("question", "answer", "yes_or_no") :return: {header1:[...],header2:[...],...} """ if headers is None: headers = ("question", "answer...
ff5a2e5f6e27ce0a32717e55ba35dbd864a11dbb
3,658,048
def member(): """ RESTful CRUD Controller """ return s3_rest_controller()
2f14df1f9b97ee4777c2ce0740207c691aedb1c2
3,658,049
from datetime import datetime def _now(): """Get EST localized now datetime.""" return EST_TIMEZONE.localize(datetime.datetime.now())
a7a62b5f5febdbacab0c0ac1e6ef0de843f09a11
3,658,050
def pydantic_model_to_pandas(pydantic_model_input) -> pd.DataFrame: """ Function that transforms <pydantic.BaseModel> child objects to <pandas.DataFrame> objects :param pydantic_model_input: Input validator for API """ return dict_to_pandas(pydantic_model_input.dict())
8397c39d7c760ad44565a7b89013d95c241413ed
3,658,051
def calculate_pair_energy(coordinates, i_particle, box_length, cutoff): """ Calculate the interaction energy of a particle with its environment (all other particles in the system) - rewrite Parameters ---------- coordinates : list The coordinates for all particles in the system ...
42150ff5282731b13e4ac512c08fd71566f0bdb4
3,658,052
def simulation_activation(model, parcel_df, aerosols_panel): """ Given the DataFrame output from a parcel model simulation, compute activation kinetic limitation diagnostics. Parameters ---------- model : ParcelModel The ParcelModel parcel_df : DataFrame used to generate the results to ...
41461da13062177124ca4ebedc801ff5d574fbb8
3,658,053
def create_config( case=None, Exp='Dummy', Type='Tor', Lim=None, Bump_posextent=[np.pi/4., np.pi/4], R=None, r=None, elong=None, Dshape=None, divlow=None, divup=None, nP=None, returnas=None, strict=None, SavePath='./', path=_path_testcases, ): """ Create easily a tofu.geom.Config object ...
e9f855ff614cd511f730afd34c34e1d610b06a43
3,658,055
def is_project_description(description): """Validates the specified project description. A valid description is simply a non-empty string. Args: description (str): A project description to validate. Returns: <bool, str|None>: A pair containing the value True if the specified descripti...
ef831f2ddeede75bb1dbd0730dccacba3e379c2b
3,658,056
import json def remove_friend(): """ Accepts an existing friend request. """ data = json.loads(request.data) friend_id = data['id'] user = interface.get_user_by_id(get_jwt_identity()) friend = interface.get_user_by_id(friend_id) interface.remove_friendship(user, friend) return '...
0d5e2c390d5da7ff1869d907bbe85bcda80a9513
3,658,057
import functools import logging def ensure_configured(func): """Modify a function to call ``basicConfig`` first if no handlers exist.""" @functools.wraps(func) def wrapper(*args, **kwargs): if len(logging.root.handlers) == 0: basicConfig() return func(*args, **kwargs) ret...
2c04afd53ab9c7341fc4913485a8a1f7f7e7e1b3
3,658,058
from typing import Dict from typing import Any from typing import Optional from typing import Type def get_loss(dataset_properties: Dict[str, Any], name: Optional[str] = None) -> Type[Loss]: """ Utility function to get losses for the given dataset properties. If name is mentioned, checks if the loss is co...
a9f75d6e2c35a0b9472e3fdc046f72eb1188e48d
3,658,059
def ten_to_base(value : int, base): """Converts a given decimal value into the specified base. :param value: The number to convert :param base: The base to convert the specified number to :return: The converted value in the specified base """ # Check if the base is 10, return the value if...
2f5ba92af48fe2ce19dbcb6001afadfde2514373
3,658,060
def get_style(selector, name): """ Returns the resolved CSS style for the given property name. :param selector: :param name: """ if not get_instance(): raise Exception("You need to start a browser first with open_browser()") return get_style_g(get_instance(), selector, name)
903e4abc09dc196d0d1dbbbb3c58869e3c0beb78
3,658,061
import inspect def argmod(*args): """ Decorator that intercepts and modifies function arguments. Args: from_param (str|list): A parameter or list of possible parameters that should be modified using `modifier_func`. Passing a list of possible parameters is useful when a fu...
5824d20568a3913be59941df0e4f657f05f08cc0
3,658,062
def group_update(group_id, group_min, group_max, desired): """ Test with invalid input >>> group_update('foo', 2, 1, 4) {} """ if group_min > group_max or desired < group_min or desired > group_max: return {} try: client = boto3.client('autoscaling') response = clien...
77eef10b7db604a3aa2e32bdd0d226fb44cf07ab
3,658,063
def remove_bookmark(request, id): """ This view deletes a bookmark. If requested via ajax it also returns the add bookmark form to replace the drop bookmark form. """ bookmark = get_object_or_404(Bookmark, id=id, user=request.user) if request.method == "POST": bookmark.delete() ...
9c8442d5a313e7babf71b9f9a4c41452c65c5aab
3,658,064
def parse_propa(blob): """Creates new blob entries for the given blob keys""" if "track_in" in blob.keys(): muon = blob["track_in"] blob["Muon"] = Table( { "id": np.array(muon)[:, 0].astype(int), "pos_x": np.array(muon)[:, 1], "pos_y...
ae7993d6e51287b6a88d125f63ef7d6edd001cf1
3,658,065
def parseParams(opt): """Parse a set of name=value parameters in the input value. Return list of (name,value) pairs. Raise ValueError if a parameter is badly formatted. """ params = [] for nameval in opt: try: name, val = nameval.split("=") except ValueError: ...
b932f74c8e5502ebdd7a8749c2de4b30921d518b
3,658,066
from ._sparse_array import SparseArray def asnumpy(a, dtype=None, order=None): """Returns a dense numpy array from an arbitrary source array. Args: a: Arbitrary object that can be converted to :class:`numpy.ndarray`. order ({'C', 'F', 'A'}): The desired memory layout of the output ...
54bea22ab6fe8327b3a4df93ac9e4447b4d65fec
3,658,067
def get_next_cpi_date(): """ Get next CPI release date """ df = pd.read_html(r"https://www.bls.gov/schedule/news_release/cpi.htm")[0][:-1] df["Release Date"] = pd.to_datetime(df["Release Date"], errors='coerce') df = df[df["Release Date"] >= current_date].iloc[0] df['Release Date'] = df['Rel...
e23b9bea0996ac442115163729ffeed1407e52b5
3,658,068
from typing import Tuple from datetime import datetime def date_arithmetic() -> Tuple[datetime, datetime, int]: """ This function is used to calculate what is the date after 3 days is given and the differences between two given dates """ date1: str = "Feb 27, 2020" date_2020: datetime = datetim...
1e2d4681578ccab11612771589a46f22246071eb
3,658,069
def get_words_from_line_list(text): """ Applies Translations and returns the list of words from the text document """ text = text.translate(translation_table) word_list = [x for x in text.split() if x not in set(stopwords.words('english'))] return word_list
aaa2a1476e887aa6a7d477d67528f838d6f229b9
3,658,070
def _get_name(dist): """Attempts to get a distribution's short name, excluding the name scope.""" return getattr(dist, 'parameters', {}).get('name', dist.name)
fd57e523c1a84a36f9ed56236e4b8db1e887575c
3,658,071
def compute_mean_std(all_X): """Return an approximate mean and std for every feature""" concatenated = np.concatenate(all_X, axis=0).astype(np.float64) mean = np.mean(concatenated, axis=0) std = np.std(concatenated, axis=0) std[std == 0] = 1 return mean, std
b102a045705efdab8d9783e04da192ec30e167f7
3,658,072
def GenerateConfig(context): """Generates configuration.""" key_ring = { 'name': 'keyRing', 'type': 'gcp-types/cloudkms-v1:projects.locations.keyRings', 'properties': { 'parent': 'projects/' + context.env['project'] + '/locations/' + context.properties['region'], 'keyRingId': context.env['d...
257b7217c1a08bba46866aff0b7faa1a03fe7fdc
3,658,073
def get_valid_collapsed_products(products, limit): """wraps around collapse_products and respecting a limit to ensure that uncomplete products are not collapsed """ next_min_scanid = get_next_min_scanid(products, limit) collapsed_products = [] for scanid, scan in groupby(products, itemgetter(...
df3ffa503855a020c7c011aa58cba20243e19be4
3,658,074
def get_imd(): """Fetches data about LA IMD status. The "local concentration" measure is used - this gives higher weight to particularly deprived areas Source: http://www.gov.uk/government/statistics/english-indices-of-deprivation-2019 """ imd = pd.read_csv( PROJECT_DIR / "inputs/data/so...
4e2495dda505bde8dd8ccf62234730a7227ffa97
3,658,075
def read_bgr(file): """指定ファイルからBGRイメージとして読み込む. # Args: file: イメージファイル名. # Returns: 成功したらイメージ、失敗したら None. """ return cv2.imread(file, cv2.IMREAD_COLOR)
ee96842899ffefa0508218d0a4b721f2ae5a7efb
3,658,076
def _remove_none_from_post_data_additional_rules_list(json): """ removes hidden field value from json field "additional_rules" list, which is there to ensure field exists for editing purposes :param json: this is data that is going to be posted """ data = json additional_rules = json.get...
c82aa568f82ba4abcb8f4e6f9c770969277d078f
3,658,077
import traceback def add_email(request, pk): """ This Endpoint will add the email id into the person contact details. It expects personId in URL param. """ try: request_data = request.data email = request_data.get("email") person = Person.objects.filter(id=pk).last...
5669b442e7ef4fb3e5a22053c368e6a4b68cfeef
3,658,078
from typing import Any def coords_extracter(): """Exctract coords to send command to robot. To be executed inside of xarm_hand_control module.""" SKIPPED_COMMANDS = 5 COEFF = 22 current = [0] def coords_to_command(data: Any): current[0] += 1 if current[0] < SKIPPED_COMMANDS:...
930cef91e517751da3c3fb441543ab736be6aa23
3,658,079
def NO_MERGE(writer, segments): """This policy does not merge any existing segments. """ return segments
0742365f30d59cb219ac60483b867180bd910ba8
3,658,080
def build_ntwk(p, s_params): """ Construct a network object from the model and simulation params. """ np.random.seed(s_params['RNG_SEED']) # set membrane properties n = p['N_PC'] + p['N_INH'] t_m = cc( [np.repeat(p['T_M_PC'], p['N_PC']), np.repeat(p['T_M_INH'], p['N_INH...
88a5b5c73edf015d9b2b4137db874252f63a3571
3,658,082
def createAaronWorld(): """ Create an empty world as an example to build future projects from. """ # Set up a barebones project project = makeBasicProject() # Create sprite sheet for the player sprite player_sprite_sheet = addSpriteSheet(project, "actor_animated.png", "actor_animated", "act...
7326aee61ee4977ccc422955fbd33c6a51b13e37
3,658,083
def builtin_ljustify(s, w, p): """Left-justify a string to a given width with a given padding character.""" sv = s.convert(BStr()).value pv = p.convert(BStr()).value return BStr(sv.ljust(w.value, pv))
dda28d65d1916a7e01aa36e7b90ee5ba98329c58
3,658,084
def get_effective_router(appname): """Returns a private copy of the effective router for the specified application""" if not routers or appname not in routers: return None return Storage(routers[appname])
dd0e3ccc8d05864b5a324541129845e5f82c2669
3,658,086
def is_activated(user_id): """Checks if a user has activated their account. Returns True or false""" cur = getDb().cursor() cur.execute('SELECT inactive FROM users where user_id=%s', (user_id,)) inactive = cur.fetchone()[0] cur.close() return False if inactive is 1 else True
704a5c3462be3612e5cd44057ee082d612ae8aa9
3,658,087
import base64 import json def _encode(dictionary): """Encodes any arbitrary dictionary into a pagination token. Args: dictionary: (dict) Dictionary to basee64-encode Returns: (string) encoded page token representing a page of items """ # Strip ugly base64 padding. return base...
e9a490e659a3a0e6d546fd2ab4dd89a5f6a748af
3,658,088
def selectPlate(plates, jdRange, normalise=False, scope='all'): """From a list of simulated plates, returns the optimal one.""" # Gets the JD range for the following night nextNightJDrange = _getNextNightRange(jdRange) # First we exclude plates without new exposures plates = [plate for plate in pl...
f48207a9be002e6b2295d4100e02ffaddde779e8
3,658,090
from typing import Union def get_events( raw: mne.io.BaseRaw, event_picks: Union[str, list[str], list[tuple[str, str]]], ) -> tuple[np.ndarray, dict]: """Get events from given Raw instance and event id.""" if isinstance(event_picks, str): event_picks = [event_picks] events = None for e...
d1b5c961160848607a40cfcb5b2ba8a47625ab21
3,658,091
def transplant(root, u, v): """ 注意, 这里要返回root, 不然修改不了 """ if u.parent == None: root = v elif u.parent.left == u: u.parent.left = v else: u.parent.right = v if v: v.parent = u.parent return root
cadf0433399e428596d1d0d4ab200e4d79285d21
3,658,092
def is_head_moderator(): """ Returns true if invoking author is a Head Moderator (role). """ async def predicate(ctx: Context): if not any(config.HEAD_MOD_ROLE in role.id for role in ctx.author.roles): raise NotStaff("The command `{}` can only be used by a Head Moderator.".format(ctx...
22f80251190d914d38052e67ca8fe47279eab833
3,658,093
def compute_adj_matrices(type, normalize=True): """ Computes adjacency matrices 'n', 'd' or 's' used in GCRAM. """ # Get channel names raw = mne.io.read_raw_edf('dataset/physionet.org/files/eegmmidb/1.0.0/S001/S001R01.edf', preload=True, verbose=False).to_data_frame() ch_names = raw.columns[2:]...
cecf0c94c5d1efe6c6210949736377d5d7d454c4
3,658,094
def hasNonAsciiCharacters(sText): """ Returns True is specified string has non-ASCII characters, False if ASCII only. """ sTmp = unicode(sText, errors='ignore') if isinstance(sText, str) else sText; return not all(ord(ch) < 128 for ch in sTmp);
c1627d1a0a26e7c4d4e04c84085197ba44b5e640
3,658,096
def draw_matches(image_1, image_1_keypoints, image_2, image_2_keypoints, matches): """ Draws the matches between the image_1 and image_2. (Credit: GT CP2017 course provided source) Params: image_1: The first image (can be color or grayscale). image_1_keypoints: The image_1 keypoints. ...
d2984de4c542fca7dda3863ad934e9eddc14a375
3,658,097
def copy_ttl_in(): """ COPY_TTL_IN Action """ return _action("COPY_TTL_IN")
a01acb2645e033ad658435e9ca0323aec10b720c
3,658,098
import torch from typing import Optional def neuron_weight( layer: str, weight: torch.Tensor, x: Optional[int] = None, y: Optional[int] = None, batch: Optional[int] = None, ) -> Objective: """Linearly weighted channel activation at one location as objective :param layer: Name of the l...
646966613249a02468e00b91157fd43459d246bb
3,658,099
def genargs() -> ArgumentParser: """ Generate an input string parser :return: parser """ parser = ArgumentParser() parser.add_argument("indir", help="Location of input shexj files") parser.add_argument("outdir", help="Location of output shexc files") parser.add_argument("-s", "--save", h...
1958d772e316212f90d6e3b84c5452e4fc02f2da
3,658,100
def get_model_name(factory_class): """Get model fixture name by factory.""" return ( inflection.underscore(factory_class._meta.model.__name__) if not isinstance(factory_class._meta.model, str) else factory_class._meta.model)
1021f287803b5e6dd9231503d8ddab15c355a800
3,658,101
def GetSpatialFeatures(img, size=(32, 32), isFeatureVector=True): """ Extracts spatial features of the image. param: img: Source image param: size: Target image size param: isFeatureVector: Indication if the result needs to be unrolled into a feature vector returns: Spatial features """ res...
36d864bddb125f7cb13c4bd800076733ab939d58
3,658,102
import html import logging import re def html_to_text(content): """Filter out HTML from the text.""" text = content['text'] try: text = html.document_fromstring(text).text_content() except etree.Error as e: logging.error( 'Syntax error while processing {}: {}\n\n' ...
43fc18400ef121bf12f683da03763dff229d45ae
3,658,103
async def get_robot_positions() -> control.RobotPositionsResponse: """ Positions determined experimentally by issuing move commands. Change pipette position offsets the mount to the left or right such that a user can easily access the pipette mount screws with a screwdriver. Attach tip position plac...
816f1794231aa2690665caa8eae26c301d55b198
3,658,104
def compute_basis(normal): """ Compute an orthonormal basis for a vector. """ u = [0.0, 0.0, 0.0] v = [0.0, 0.0, 0.0] u[0] = -normal[1] u[1] = normal[0] u[2] = 0.0 if ((u[0] == 0.0) and (u[1] == 0.0)): u[0] = 1.0 mag = vector_mag(u) if (mag == 0.0): return for ...
3623a80fcb86d506e5f9e2f94d98a69a2831b2a5
3,658,105
def do_LEE_correction(max_local_sig, u1, u2, exp_phi_1, exp_phi_2): """ Return the global p-value for an observed local significance after correcting for the look-elsewhere effect given expected Euler characteristic exp_phi_1 above level u1 and exp_phi_2 above level u2 """ n1, n2 = get_coefficient...
53ee295261d58c59aa1a0a667ec7ded2e986c256
3,658,106
def _check_password(request, mail_pass, uid): """ [メソッド概要] パスワードチェック """ error_msg = {} if len(mail_pass) <= 0: error_msg['mailPw'] = get_message('MOSJA10004', request.user.get_lang_mode()) logger.user_log('LOSI10012', request=request) logger.logic_log('LOSM17015', re...
8753d0ed32db0c501f2f18af9ea88253b7a1add7
3,658,107
def _read_wb_indicator(indicator: str, start: int, end: int) -> pd.DataFrame: """Read an indicator from WB""" return pd.read_feather(config.paths.data + rf"/{indicator}_{start}_{end}.feather")
87a52d5f683fc9795a7baf9ff81f2961567c3a13
3,658,108
def scatter_raster_plot(spike_amps, spike_depths, spike_times, n_amp_bins=10, cmap='BuPu', subsample_factor=100, display=False): """ Prepare data for 2D raster plot of spikes with colour and size indicative of spike amplitude :param spike_amps: :param spike_depths: :param sp...
a72da0b1faacb5e13da51a2dc192778d956eb7e5
3,658,110
def is_pack_real(*args): """ is_pack_real(F) -> bool 'FF_PACKREAL' @param F (C++: flags_t) """ return _ida_bytes.is_pack_real(*args)
64e3ecf58607cf7c363e84a7e5a69ce0c76e8acc
3,658,111
import ast from typing import List from typing import Tuple def _get_sim205(node: ast.UnaryOp) -> List[Tuple[int, int, str]]: """Get a list of all calls of the type "not (a <= b)".""" errors: List[Tuple[int, int, str]] = [] if ( not isinstance(node.op, ast.Not) or not isinstance(node.opera...
f0efdf0b10a0d4ec8a4a75772277169aa708e005
3,658,112
from typing import Union def parse_boolean(val: str) -> Union[str, bool]: """Try to parse a string into boolean. The string is returned as-is if it does not look like a boolean value. """ val = val.lower() if val in ('y', 'yes', 't', 'true', 'on', '1'): return True if val in ('n', 'no...
e2cbda5a849e1166e0f2a3953220c93d1f3ba119
3,658,113
import csv from datetime import datetime def load_users(usertable): """ `usertable` is the path to a CSV with the following fields: user.* account.organisation SELECT user.*, account.organisation FROM user LEFT JOIN account ON user.account_id = account.id; """ users = [] wit...
44c1dad255e2d8152fadbb53523a53002af95001
3,658,114
def get_progress_status_view(request): """Get progress status of a given task Each submitted task is identified by an ID defined when the task is created """ if 'progress_id' not in request.params: raise HTTPBadRequest("Missing argument") return get_progress_status(request.params['progress_...
4e68fc45443443187032ce06552e97895316be41
3,658,115
def pretty_param_string(param_ids: "collection") -> str: """Creates a nice string showing the parameters in the given collection""" return ' '.join(sorted(param_ids, key=utilize_params_util.order_param_id))
10f955480fcf760317f78d478c837c93df598e08
3,658,116
def _center_crop(image, size): """Crops to center of image with specified `size`.""" # Reference: https://github.com/mlperf/inference/blob/master/v0.5/classification_and_detection/python/dataset.py#L144 # pylint: disable=line-too-long height = tf.shape(image)[0] width = tf.shape(image)[1] out_height = size...
2409d06945e77633f70de3e76f7152f61a9eaacf
3,658,117
def resample(ts, values, num_samples): """Convert a list of times and a list of values to evenly spaced samples with linear interpolation""" assert np.all(np.diff(ts) > 0) ts = normalize(ts) return np.interp(np.linspace(0.0, 1.0, num_samples), ts, values)
9453bba67add0307276ff71e85605812af337379
3,658,118
def supports_color(stream) -> bool: # type: ignore """Determine whether an output stream (e.g. stdout/stderr) supports displaying colored text. A stream that is redirected to a file does not support color. """ return stream.isatty() and hasattr(stream, "isatty")
4a427d6725206ef33b3f4da0ace6f2d6c3db78a9
3,658,120
from typing import Union from typing import Optional from typing import Tuple from typing import Dict from typing import List from bs4 import BeautifulSoup def parse_repo_links( html: Union[str, bytes], base_url: Optional[str] = None, from_encoding: Optional[str] = None, ) -> Tuple[Dict[str, str], List[Li...
556ba2bb728c26668548d4f714dc12b1cf2b48bd
3,658,121
def calc_kappa4Franci(T_K, a_H, a_H2CO3s): """ Calculates kappa4 in the PWP equation using approach from Franci's code. Parameters ---------- T_K : float temperature Kelvin a_H : float activity of hydrogen (mol/L) a_H2CO3s : float activity of carbonic acid (mol/L) ...
a5dcab9d871c7e78031ec74fef5f172e2a37f51b
3,658,122
def get_candidates_from_single_line(single_line_address, out_spatial_reference, max_locations): """ parses the single line address and passes it to the AGRC geocoding service and then returns the results as an array of candidates """ try: parsed_address = Address(single_line_address) except...
a2e4c68dc5a27dea98951bfe61c5e10ff887091a
3,658,123
def create_store(): """Gathers all the necessary info to create a new store""" print("What is the name of the store?") store_name = raw_input('> ') return receipt.Store(store_name)
a9b78c73712b9ec3ed39f5851b970aa97e5d3575
3,658,124
def vgg11_bn_vib(cutting_layer, logger, num_client = 1, num_class = 10, initialize_different = False, adds_bottleneck = False, bottleneck_option = "C8S1"): """VGG 11-layer model (configuration "A") with batch normalization""" return VGG_vib(make_layers(cutting_layer,cfg['A'], batch_norm=True, adds_bottleneck = ...
bf893f1e720aae92275abc961675a83c507425ee
3,658,125
from pathlib import Path def get_conf_paths(project_metadata): """ Get conf paths using the default kedro patterns, and the CONF_ROOT directory set in the projects settings.py """ configure_project(project_metadata.package_name) session = KedroSession.create(project_metadata.package_name) ...
f001dc7d6991c57f32afb3d8d6e607d24bfd61cd
3,658,126
import numpy import ctypes def _mat_ptrs(a): """Creates an array of pointers to matrices Args: a: A batch of matrices on GPU Returns: GPU array of pointers to matrices """ return cuda.to_gpu(numpy.arange( a.ptr, a.ptr + a.shape[0] * a.strides[0], a.strides[0], dtyp...
1b56c7b9cbc368612fb0f0f7ecd647b5045773a2
3,658,127
def file_upload_quota_broken(request): """ You can't change handlers after reading FILES; this view shouldn't work. """ response = file_upload_echo(request) request.upload_handlers.insert(0, QuotaUploadHandler()) return response
ed9dab36b4f67a58e90542411474da733887f4b4
3,658,128
def create_LED_indicator_rect(**kwargs) -> QPushButton: """ Useful kwargs: text: str, icon: QIcon, checked: bool, parent checked=False -> LED red checked=True -> LED green """ button = QPushButton(checkable=True, enabled=False, **kwargs) button.setStyleSheet(SS_LED_INDICATOR_RECT) ...
3323a225b3f9ac6e687bb3a3d1c5f9d6a4459384
3,658,129
def getAlignments(infile): """ read a PSL file and return a list of PslRow objects """ psls = [] with open(infile, 'r') as f: for psl in readPsls(f): psls.append(psl) return psls
00d6c0c4e44dd3de46c3bc7f38d40fd169311164
3,658,131
import numpy def get_ring_kernel(zs,Rs): """Represents the potential influence due to a line charge density a distance *delta_z* away, at which the azimuthally symmetric charge distribution has a radius *R*.""" Logger.write('Computing ring kernels over %i x %i points...'%((len(zs),)*2)) ...
5cdbeb80c8658334245e4fa93f3acf9ac0f9dbc9
3,658,132
def dsdh_h(P, h, region = 0): """ Derivative of specific entropy [kJ kg / kg K kJ] w.r.t specific enthalpy at constant pressure""" if region is 0: region = idRegion_h(P, h) if region is 1: return region1.dsdh_h(P, h) elif region is 2: return region2.dsdh_h(P, h) elif reg...
0ecc9d783524873c2d8537e105c7d5e8814ec80c
3,658,133
from datetime import datetime def floor_datetime(dt, unit, n_units=1): """Floor a datetime to nearest n units. For example, if we want to floor to nearest three months, starting with 2016-05-06-yadda, it will go to 2016-04-01. Or, if starting with 2016-05-06-11:45:06 and rounding to nearest fifteen mi...
8c4b61b29bf9f254e2da46097e498834b54e960f
3,658,134
def get_dataset_descriptor(project_id, dataset_id): """Get the descriptor for the dataset with given identifier.""" try: dataset = api.datasets.get_dataset_descriptor( project_id=project_id, dataset_id=dataset_id ) if not dataset is None: return jsonif...
776c7f72730f52e07cf33a6f6b4c7a949810323d
3,658,135
def pe41(): """ >>> pe41() 7652413 """ primes = Primes(1000000) for perm in permutations(range(7, 0, -1)): n = list_num(perm) if primes.is_prime(n): return n return -1
bec7969b96f617848f8771dc6d85faf4b01ea648
3,658,136
def transit_flag(body, time, nsigma=2.0): """Return a flag that indicates if times occured near transit of a celestial body. Parameters ---------- body : skyfield.starlib.Star Skyfield representation of a celestial body. time : np.ndarray[ntime,] Unix timestamps. nsigma : float ...
271378e0a6558491f73968200fcb24ec694f8cbe
3,658,137
def _parse_port_ranges(pool_str): """Given a 'N-P,X-Y' description of port ranges, return a set of ints.""" ports = set() for range_str in pool_str.split(','): try: a, b = range_str.split('-', 1) start, end = int(a), int(b) except ValueError: log.error('Ig...
6926b326ea301f21e2282edda3bc16169ebe90b4
3,658,138