content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import re def convert_s3_label_to_bytes(s3_size: str) -> int: """convert 12MiB to 12 * 1024**2""" match = re.match(r"([0-9.]+)(\w+)", s3_size) if match: return int(float(match.groups()[0]) * 1024 ** LABELS_POWER[match.groups()[1]]) return -1
161c494b53322737b39e8dd3e8ec3226797abc59
52,200
import networkx as nx import tabix def ld_prune(df, ld_beds, snvs=None): """ Prune set of GWAS based on LD and significance. A graph of all SNVs is constructed with edges for LD >= 0.8 and the most significant SNV per connected component is kept. Parameters ---------- df : pandas.Dat...
dde8f3ac2b1cb3ef265b1986d61f8ee474b199a6
52,201
def perm_to_string(p): """ Convert p to string, slightly more compact than list printing. """ s = "(" for x in p: s = s + "%2d "%x s += ")" return s
d5922275b7e0b677957309e1bab5f3b9b1ff0cb7
52,202
def pg_capital(s : str) -> str: """ If string contains a capital letter, wrap it in double quotes returns: string """ if '"' in s: return s needs_quotes = False for c in str(s): if ord(c) < ord('a') or ord(c) > ord('z'): if not c.isdigit(): needs_...
bfb928b88e837c78ddd46f7d231217442ef4e24c
52,203
def get_client(host, port=None, username=None, password=None, tenant=None, auth_url=None, auth_strategy=None, auth_token=None, region=None, is_silent_upload=False, insecure=False): """ Returns a new client heat client object based on common kwargs. ...
a01bd41b2f61f6c993589e16484f2175877588be
52,204
def ht_syn_one(): """Hash table of words and their synonyms.""" ht = HashTable(10) # import pdb; pdb.set_trace() ht.set('fond', 'enamored') ht.set('wrath', 'anger') ht.set('diligent', 'employed') ht.set('outfit', 'garb') ht.set('guide', 'usher') return ht
b1ec5ca5a59f1cda737540e7c383217d2c54e733
52,205
def all_inactive_converter( intersection, DEBUG= False, emergency= False): """ changes all the traffic lights to active if all are inactive\n else remains the same\n if the emergency condition is there then it is also reset\n """ all_inactive = True for index, tl in enumerate( intersection)...
319168849c960ab62cbb148c8cdfb2a89bda9af0
52,206
import string def escape_bytes(bytes_): """ Convert a bytes object to an escaped string. Convert bytes to an ASCII string. Non-printable characters and a single quote (') are escaped. This allows to format bytes in messages as f"b'{utils.escape_bytes(bytes)}'". """ res = "" for byte i...
c1a6c2875824d8576e7d9c349f19548e2c3313e8
52,207
import six def _minimize_towers(tower_specs, optimizer): """Aggregate and apply gradients for computed losses.""" grad_lists = {} for tower_spec in tower_specs: with ops_lib.device(tower_spec.loss.device): for grad, var in optimizer.compute_gradients(tower_spec.loss): if grad is not None: ...
530f8d4a2b1dca5591bc612ac57a82be99bcbb2d
52,208
def shrink_dimensions(width, height, max_dimension): """ Resize dimensions so max dimension is max_dimension. If dimensions are too small no resizing is done Args: width (int): The width height (int): The height max_dimension (int): The maximum size of a dimension Returns: ...
60d4a6ec9b310f7c22f341f1309b4677c3617fd2
52,209
def relu_backward(dA, cache): """ This function implements the backward propagation for a single Relu unit @params dA = post-activation gradient, of any shape cache = Retrieve cached Z for computing backward propagation efficiently Returns: dZ = Gradient of the cost with respect to Z ...
f1847b8b7a24798437b2862c0fba806376121df8
52,210
def keccak256(value): """Thin wrapper around keccak function.""" return HexBytes(keccak(value))
581b621d8fc5b4a1e4643a6cd18176226cda2fdc
52,211
def slerp(pt1, pt2, intervals): """Spherical linear interpolation. Args: pt1: Array of points. When interval is 0, the result is pt1. pt2: Array of points. When interval is 1, the result is pt2. intervals: Array of intervals at which to evaluate the linear interpolation ...
eba8087a0733cff54a382b294cfe946d90453967
52,212
def make_cumvalues(xvalues): """ Takes a Pandas dataframe with one column as input value. Tries to create a cumulative series. """ newvalues = 0.0 * xvalues dx = xvalues.diff() dxpos = dx mask = -xvalues.diff() > 0.9 * xvalues nrsteps = len(dx.loc[mask]) lapidx = np.cumsum((-dx + a...
8aeb6e360ddf53a3ce612659da597e8e378c48ee
52,213
def payment_success(request): """ Renders status page after donation passed successfully." """ return render(request, 'payment_success.html')
a9ca900213fbe57495c6100e68839b68ff38ccb6
52,214
def should_workfile_tool_start( project_name, host_name, task_name, task_type, default_output=False ): """Define if host should start workfile tool at host launch. Default output is `False`. Can be overridden with environment variable `OPENPYPE_WORKFILE_TOOL_ON_START`, valid values without case sensiti...
14dc2293633b7acd151e17cdec6691dd3cb7e947
52,215
def create(): """ $ curl -i -X POST -H "Content-Type: application/json" -d '{"username":"user","password":"python"}' http://localhost:5000/api/user """ username = request.json.get("username") password = request.json.get("password") if username is None or password is None: abort(400) #...
9c99eff1c84c26527e5605b286d207a39c37e489
52,216
def display_hour_range_dash(value): """ Function that just calls the display_hour_range function. This function is decorated by the Dash Application decorator. Such an arrangement is used as unit testing decorated functions is complex. """ display = display_hour_range(value) return displa...
03f4100d0deb0a6eb185da0480aa1d91b78ca07a
52,217
def sample_ingredient(user, name='Cinnamon'): """membuat dan mengembalikan sampel ingredient""" return Ingredient.objects.create(user=user, name=name)
bc6627c0d485d78f0d2158664eef4dd4191ac1b5
52,218
def _get_np_complex_dtype(float_dtype): """ Get equivalent complex type given current float dtype """ if float_dtype == np.float32: return np.complex64 elif float_dtype == np.float64: return np.complex128 else: return np.complex256
c5b342f5ddf95e63acaa2a3559fd4d373a1aa63c
52,219
def ResizePad(mask, image_shape): """ Resize and Pad mask back to original shape -- reverse action of CropResize for masks """ if mask.shape == image_shape: return mask h, w = image_shape side = min(h, w) mask = cv2.resize(mask, (side, side), interpolation=cv2.INTER_NEAREST) ...
b5bf84ff35e169a2533d78000ce83a73d760cef8
52,220
def read(filename, *args, **kwds): """Loads a graph from the given filename. This is just a convenience function, calls L{Graph.Read} directly. All arguments are passed unchanged to L{Graph.Read} @param filename: the name of the file to be loaded """ return Graph.Read(filename, *args, **kwds)
49d2b2503b93808e1db8ea487db49553e603023a
52,221
def create_instance_from_template_with_overrides( project_id: str, zone: str, instance_name: str, instance_template_name: str, machine_type: str, new_disk_source_image: str, ) -> compute_v1.Instance: """ Creates a Compute Engine VM instance from an instance template, changing the machine...
32f75a8a5de539ef5ab000c028cd91469fbfac90
52,222
import argparse import os import logging def arg_parse_params(): """ parse the input parameters :return dict: {str: any} """ # SEE: https://docs.python.org/3/library/argparse.html parser = argparse.ArgumentParser() parser.add_argument('-i', '--path_images', type=str, required=True, ...
4d5670c87e8302b81010819097189e3e94ba05db
52,223
def getPossibleWordInner(str, triedWords, maxAllowTry, i = 0): """ get a possible word that we haven't tried before @BUG if this recursion run over 1000 (997 in fact) times, it will throw RecursionError because it reaches the system maximum """ # if this interaction has reach the max allow n...
7e88d8032623d9cf661995d22a48681b706f5be2
52,224
from typing import List from typing import Union from typing import Callable import torch def evaluate(model: Module, dataloader: DataLoader, metrics: List[Union[str, Callable]], prepare_batch: Callable = lambda x: x, loss_fn: Callable = None, prefix: s...
32ef765a8d2a33da627f3c0839425ba3e305c931
52,225
def ensureGrayscale(np_image, info=False): """Ensures that given image is in grayscale Keyword argument: np_image -- image as NumPy array Return: np_image as grayscale image """ isConverted = False if len(np_image.shape) == 3: if np_image.shape[2] == 3: np_image = ge...
88349603b8b71064805fa9c24534745c10acaaa6
52,226
from typing import List def load_unlabelled(filename: str) -> List: """Helper function to load unlabelled dataset for unsupervised training. Args: filename (str): filename of dataset Returns: List: list of dataset by line. """ data = [] with open(filename, "r") as F: ...
e88f94457763e6b291b850e6fe6374935dae7015
52,227
import six def is_key_attribute(df, attr, verbose=False): """ Check if an attribute is a key attribute Args: df (pandas dataframe): Input dataframe attr (str): Attribute in the pandas dataframe verbose (bool): Flag to indicate whether warnings should be printed out Returns: ...
c73697e72bf553f6d7114edcf014960b976f9db3
52,228
def break_rest(time, flux, flux_err, cadences): """ Breaks up the non-signal cases into bite-sized cadence-length chunks. Parameters ---------- time : np.ndarray Array of time. flux : np.ndarray Array of fluxes. flux_err : np.ndarray Array of flux errors. cade...
2255f2aed7184c86590c66964eee92e37e5e8ef9
52,229
def login_required(fn): """ login required as decorator """ @wraps(fn) def decorated_view(*args, **kwargs): if not 'user' in session or session['user'] == None: return redirect(url_for("login")) return fn(*args, **kwargs) return decorated_view
31f017429275ed8c89017ef9b43906d84b97a301
52,230
def addAge(data, ages): """ The new format in CMD v3.2 does not include the commented line with the 'Age' value, and the logAge column is rounded to 3 decimal places so this value it can not be taken from there. Add this line back to each age for each metallicity file. """ data = data.spli...
e9c6145dd424ed2149d950246172004bea24d2ca
52,231
def group_spans(article_id, span_intervals): """ Groups together spans from the same article """ dictionary = dict.fromkeys(article_id, span_intervals) spans = {} for key, value in dictionary.items(): spans.setdefault(key, []) spans[key].append(value) return spans
3be0f2cb8b07a9fef7f116171b81829a86301a04
52,232
def conjugate_gradient_solve(a_mat, b_mat, tol=1e-10): """Returns `X` such that `A * X = B`. Uses Conjugate Gradient to solve many linear systems of equations with the same matrix `a_mat` and multiple right hand sides provided as columns in the matrix `b_mat`. Args: a_mat: a Symmetric Positive Definite ...
6346dc3b2398a8d919188396c22399f7ca5a47ea
52,233
def list_lateral_movement_template_command(client: Client) -> CommandResults: """Retrieve a list of all lateral movement templates. Args: client (Client): Cymulate client. Returns: CommandResults: A CommandResults object that is then passed to 'return_results', cont...
a2eab8e97fdb2e2291a5f4994c2d2d410e6eb06b
52,234
def create_download_response_zip(file_format: str, experiment: Experiment) -> \ FileResponse: """Creates a FileResponse containing a ZIP with all data of the provided experiment, in the desired format. """ # Create the zip using the desired methods if file_format == 'raw': zip_file = _c...
f5ec26f4c0ff6c349f265e0b5eb23815048c5583
52,235
def ids_to_names(ven_id, ven_name, dev_id, dev_name): """Uses an internal lookup table to return canonical names when known. Returns: tuple(vendor name, device name). """ m = _VENDOR_MAPPING.get(ven_id) if not m: return ven_name, dev_name return m[0], m[1].get(dev_id, dev_name)
098748c5efec05065e0f3b6853d4a5e22b636658
52,236
import subprocess import re import sys def ns_domain(domain, rtype = "A", dns = ""): """list rtype NS records from domain using provided or default dns, returns dict with hostnames as keys""" hosts = subprocess.Popen(nsls_cmd % {'d': domain, 't': rtype, 's': dns}, stdin = subproce...
230a542d0850680f0ea66cd21b354395b5a16a42
52,237
def pixel_matrix_from_hash(hash_value): """Sets pixels of the image to on or off based on hash value. Args: hash_value (int): The hash value of the username of user Returns: np.array: A symmetric black and white pixel map matrix """ pixel_matrix = np.zeros((5,5)) # first 25 cha...
72b96cbae28e23278979f110288486a202b4ff91
52,238
def portfolio_vol(weights, covmat): """ Weights to vol Turns lists,arrays into float volatility figure Last updated 24/12/2020 """ if isinstance(weights, list): weights = np.array(weights) return (weights.T @ covmat @ weights) ** 0.5
e3c15f3e2b657afd78ab9f750010172fe1b146ac
52,239
import math def find_pulsars_in_fov(obsid, psrbeg, psrend, fwhm=None, search_radius=0.02, meta_data=None, full_meta=None, no_known_pulsars=False, no_search_cands=False, offset=0, angle_offset=0): """ Find all pulsa...
165510766aadf0dba681f976866165ac386c4420
52,240
def get_zone(zone_uuid): """Get the Redfish Zone. Return Resource Zone redfish JSON. Logs exception of any error and return Internal Server Error or Not Found. Returns: JSON: Redfish json with Resource Zone. """ template_id, enclosure_id = ZoneService.\ ...
25ba927c7501550a3e634b1a24e7162792459526
52,241
def _get_fargs(func, no_self=False, no_varargs=False): # pragma: no cover """ Same as putil.pinspect.get_function_args """ is_parg = lambda x: (len(x) > 1) and (x[0] == '*') and (x[1] != '*') is_kwarg = lambda x: (len(x) > 2) and (x[:2] == '**') par_dict = signature(func).parameters # Mark position...
12446caff85ee70787e05abdbb255c178c90a059
52,242
def new_game_nd(dimensions, bombs): """ Start a new game. Return a game state dictionary, with the 'dimensions', 'state', 'board' and 'mask' fields adequately initialized. Args: dimensions (tuple): Dimensions of the board bombs (list): Bomb locations as a list of lists, each an ...
fd307b5f2bf619dcec6bcca2289f2a57bafad537
52,243
from typing import Any def deprecation_versions(): """Create a list of valid version for deprecation entries, current+4""" major, minor = [int(version) for version in __version__.split('.')[0:2]] return Any(*['{0}.{1}'.format(major, minor + increment) for increment in range(0, 5)])
e2e860d3cdb6d13e4fba01396b8e37a0b38f4518
52,244
def fitness_score(individual: list) -> int: """ Calculate the fitness score of an individual @param individual: @return: score: int """ score = 0 for row in range(Constants.NUMBER_OF_QUEENS.value): col = individual[row] for other_row in range(Constants.NUMBER_OF_QUEENS.value)...
24718331231d71ac67773faf4c2c24957c98ecee
52,245
import platform def get_main_dir_path(): """ returns the path to the main speech directory for mac and linux depending on the OS """ # checks if I am on my local (mac) or a VM (linux) system = platform.system() if system == 'Linux': path_prefix = '/home/dzubke/awni_speech/speech/' ...
0038bb8360e5431a3be9ecbd375e1c7f2f0e196a
52,246
from typing import Callable from typing import Optional import logging def __generate_linear_plot_func( cloudpair: tuple[Cloud, Cloud], ax: Axes, distance: list[float], y: list[float], color: str, series_name: str, semilogy: bool, ) -> Callable[[Optional[int]], list[PathCollection]]: "...
2a97e08feb19b7f06fb0ce69f818b7578fb43d8e
52,247
import json def get_id_set(id_set_path: str) -> dict: """ Parses the content of id_set_path and returns its content. Args: id_set_path: The path of the id_set file Returns: The parsed content of id_set """ with open(id_set_path, 'r') as id_set_file: id_set = json.load(...
244495603bf423324ef4b3ffe4b1fdc3ca7fdf74
52,248
async def update_recipe_category(category: str, new_category: CategoryIn, session: Session = Depends(generate_session)): """ Updates an existing Tag in the database """ try: return db.categories.update(session, category, new_category.dict()) except Exception: raise HTTPException(status.HTTP...
bc864f0c7c1945a5271363345c024e00ace25500
52,249
import traceback def get_station_id(pool, latitude, longitude, station_type) -> str: """ Retrieve station id :param pool: database connection pool :param latitude: :param longitude: :param station_type: StationEnum: which defines the station type such as 'CUrW', 'WRF' :return: str: sta...
60c08d3b9db51bd505e516be97beb0f31a8933d3
52,250
def get_bgp_summary( device, address_family=None, vrf=None, rd=None, all_summary=False ): """ Get neighbors from show bgp summary command Args: device ('obj'): Device object address_family ('str'): address family vrf ('str'): vrf name all_summary ('bool')...
f1a1dc06e8ae8224aaf69e38e005f0dcb9f3649b
52,251
def give_stats(list_of_scores, list_of_dates, selected_date, over_all): """returning the stats of a list of scores""" if not over_all: total = 0 ctr = 0 best = 9999 worst = 0 for score in list_of_scores: if score[0].text == list_of_dates[selected_date].text: ...
21c2c88a931c4595e0134d3bff8e37120655ebd7
52,252
from typing import Union from typing import Optional from typing import Tuple def get_swt( sig: Union[pd.DataFrame, pd.Series], wavelet: Optional[str] = None, depth: Optional[int] = None, timing_mode: Optional[str] = None, output_mode: Optional[str] = None, ) -> Union[pd.DataFrame, Tuple[pd.DataFr...
87841c7ead5b0b297821d42f467f7cd19961ceac
52,253
def get_structure_AlN(): """Set up AlN primitive cell Al N 1.0 3.1100000000000000 0.0000000000000000 0.0000000000000000 -1.5550000000000000 2.6933390057696038 0.0000000000000000 0.0000000000000000 0.0000000000000000 4.9800000000000000 Al N 2 2 ...
1f4f7ad8ad6ce381d5dfe3dcc61e3feeb0b84ae7
52,254
def transpose(transform, df, dicts): """Transposes the given dataframe""" df = df.reset_index().set_index('index').T.reset_index() df.columns = df.iloc[0] return (df[1:], dicts)
fc80a8a471ddf4af4329dc069b45d442f5bab0a0
52,255
def format_label_value(*values): """ Construct a label value. If multiple value components are provided, they are joined by underscores. """ return '_'.join(values)
46bb4e968577c95d5dd0df8b9687efbfdcc0568e
52,256
import logging def get_ticker_from_user(): """ This function prompts a user for an input, and returns it as the ticker :return: """ logging.info('Prompting user to enter a ticker symbol') print('Note: Data up to 1 month from today will be fetched from Yahoo Finance') return raw_input('Ente...
c5e90df462e0845883e7c54e6582f6bcf53a4502
52,257
def get_failed_info(res): """获取失败用例信息""" intf_summary_list, full_summary_list = res failed_intf_dic = {} for system_dic in intf_summary_list: if system_dic['failCaseNum'] == 0: continue for intf_dic in system_dic['children']: if intf_dic['failCaseNum'] == 0: ...
cb038319617f82a36fcc9ce5b45abac20fac89d7
52,258
def delete(targets, branch_name): """ delete command: delete target associated with <branch_name> local branch Returns the updated targets dict """ if branch_name not in targets: logging.error('No such deploy target: {0}'.format(branch_name)) return targets print 'You are about t...
ddc013caf0f1db81aa5af07cec9ed6c1c2367728
52,259
def _singularity_prefix( singularity_cmd=DEFAULT_SINGULARITY_COMMAND, sudo=DEFAULT_SUDO, sudo_cmd=DEFAULT_SUDO_COMMAND, **kwds ): """Prefix to issue a singularity command.""" command_parts = [] if sudo: command_parts.append(sudo_cmd) command_parts.append(singularity_cmd) retu...
b781ed66901696b5cc06406824c68193f34e712c
52,260
def build_in_mem_cube(gene_ids, cube_index, other_attrs, cube_sum, cube_nnz): """ Build the cube in memory, calculating the gene expression value for each combination of attributes """ logger.info("Building in-mem cube") # Count total values so we can allocate buffers once total_vals = 0 fo...
b0c7c6808f081e7e8b92aa74c4493453d6dd7167
52,261
def set_country(request, response, country_code): """Set region instance.""" info = get_cookie(request) if country_code and Country.objects.filter(country=country_code): info["country_code"] = country_code set_cookie(request, response, info) return True else: return Fals...
ed7d521b3168519477c82c5423c37f2eced7dccb
52,262
from typing import Union from typing import Sequence from typing import List def filter_from_strings(filter_strings: Union[str, Sequence[str]]) -> StringFilter: """Create a string filter from a sequence of input strings. Each string in the sequence can have the following format: - `ALL`: Accept all strin...
46ec071adbb8096863065179731bdc9dbcb5e798
52,263
def get_data_train_in_candidates(): """ Return artificial datasets when train_in_candidates = True """ sent_idx_to_idx = {} # Manually set alias map alias2wpids = { 'alias1': [["Q1", 10], ["Q4", 6]], 'multi word alias2': [["Q2", 5], ["Q1", 3], ["Q4", 2]], 'alias3': [["Q1", 30]]...
1a320b464daee656487a6c7511ab6576dcbfa686
52,264
def first_true(iterable, default=False, pred=None): """Returns the first true value in the iterable. If no true value is found, returns *default* http://docs.python.org/3.4/library/itertools.html#itertools-recipes """ return next(filter(pred, iterable), default)
de983517cfcc5d7ac57551e7ac57952fb7f69ec2
52,265
def _fHN(phi, const, lamb, omega, alpha, beta, gamma, S, K, t, r, real=True): """ real=True to return fstarHN, real=False to return fHN """ # Internal Function: # Model Parameters: gamma = gamma + lamb + 1 / 2 lamb = -1 / 2 sigma2 = (omega + alpha) / (1 - beta - alpha * gamma ** 2) ...
b8c2552f04bf650284fc1fc19086c561447ba012
52,266
def build_season_div(num, nomen, season): """ Build the string for the HTML div representing an entire season """ txt = SEASON_START % {'season': str(num), 'name': nomen} for episode_num in sorted(season.keys()): txt += build_episode_row(season[episode_num]) txt += SEASON_END return txt
445469a592f7a8902c4d6a22b080d30e4ba1c579
52,267
def create_batch_groups(test_groups, batch_size): """Return batch groups list of test_groups.""" batch_groups = [] for test_group_name in test_groups: test_group = test_groups[test_group_name] while test_group: batch_groups.append(test_group[:batch_size]) test_group =...
70de6428ab94a104b8a2573e2dc920a55712351a
52,268
import itertools def _random_menu(update, context): # pylint: disable=unused-argument """Present the user the comic options""" comics = database_query("SELECT name FROM sources") buttons = [InlineKeyboardButton(f"{name}", callback_data=name) \ for name in itertools.chain.from_iterable(comics)] ...
0214acaa908ae0ecc8010e9012a707c30a88f33b
52,269
def process_single(path, save=True): """ Process single image segment """ # Parse file name name = parse_name(path) if save: print(f"{name.full}:") # Get file fields header, data = load_hrit(path) # Get image properties from HRIT header h, v, bpp = get_image_properties(hea...
11c6a60207c43f40897bf2173acfb03da7a5174d
52,270
def pr_hr_series(): """Return hourly time series.""" def _pr_hr_series(values, start="1/1/2000"): coords = pd.date_range(start, periods=len(values), freq=pd.DateOffset(hours=1)) return xr.DataArray( values, coords=[coords], dims="time", name="pr",...
ad891960b7dabe135708d98164f36cff70b4096c
52,271
def calculate_derivative(contour_points, target_index): """ Calculates derivative. Calculates the derivative of the current point(contour_points[target_index]) and returned it. Args: contour_points:: [RPoint, RPoint, ...] RContour's points(RPoint objects) to be derivative. ...
fa942868f0b4841a96417ac2a28a8ab200832be9
52,272
def _get_timeout(value): """ Turn an input str or int into a float timeout value. :param value: the input str or int :type value: str or int :raises ValueError: :returns: float """ maximum_dbus_timeout_ms = 1073741823 # Ensure the input str is not a float if isinstance(value, ...
b8205cb34b90b856b4dda2a028f801b4cd70d7b4
52,273
def addScriptTestsTo(TestClassFactory, tests): """Add all the tests to the test class""" TestClass = TestClassFactory() for idx in range(len(tests)): setattr(TestClass, "test%d" % idx, getScriptTestMethod(tests[idx])) return TestClass
7ae1780004ae13ec05fa9d45fb6b99ac525d778e
52,274
def _latest_snapshot_path(experiment_name): """Return the latest pkl file""" return osp.join(DATA_DIR, "%s.latest" % (experiment_name))
6d1030b2140c28a2049741a38c91a9dd40a853ad
52,275
import json def lambda_handler(evt, ctx): """AWS Lambda entrypoint""" try: return awsgi.response(app, evt, ctx) except Exception as err: print(f'{err}') return { 'statusCode': 500, 'body': json.dumps({ 'message': 'internal server error', }) }
863841f416390415f7c3d2f6fc8d1b574ea50b49
52,276
import xml def get_next_pid(custom_xml): """Get highest pid from XML file.""" maxPid = 0 e = xml.fromstring(custom_xml) for prop in e: if 'pid' in prop.keys(): thisPid = int(prop.get('pid')) if maxPid < thisPid: maxPid = thisPid return str(maxPi...
3e3c351415d8b24ec51cb541ba588ed2604b9b4c
52,277
def pad_input_ids_msmarco(input_ids, max_length, pad_on_left=False, pad_token=0): """An original padding function that is used only for MS MARCO data.""" padding_length = max_length - len(input_ids) padding_id = [pad_token] * padding_length if padding...
dc75d5d72e4e1633301ff083936e08420ef17883
52,278
def get_child_context(xml_node: XmlNode, parent_node: Node, _: RenderingContext) -> RenderingContext: """Return""" return RenderingContext({ 'parent_node': parent_node, 'node_globals': InheritedDict(parent_node.node_globals), 'xml_node': xml_node })
32d1dd184e86561895d22882ff3551a152363830
52,279
def generate_map(lat, lon): """ Generate a map object for a given set of latitude and longtitude """ distances = _distance_from_coordinates(lat, lon) # Sort distances in ascending order sorted_distances = sorted(distances) split_distances = sorted_distances[:2 * app.config["NUM_OF_HOTSPOTS"]...
a43ea1955ca2e22d6ce0c94d71323136fe01b04a
52,280
def build_grid_ds_tf(sorted_keys, num_cells, batch_size, name=None): """ Method to build a fast access data structure for point clouds. Creates a 2D regular grid in the first two dimension, saving the first and last index belonging to that cell array. Args: sorted_keys: An `int` `Tensor` of shape `[N]`, t...
ecb8c71bbf0f5782371c8c816c733692ede2b46d
52,281
def check_class(module_name, class_name, packages=None, pip_args=None): """ Checks whether a class is present in the specified module and (tries to) install if packages have been provided. :param module_name: the module to check :type module_name: str :param class_name: the name of the class to che...
feaca6bb43bebba4e80784b196cb50a0977b6fa6
52,282
def getsyncat(word): """Returns a list of all syntactic categories of the word as strings or an empty list if no results.""" syncats = ', '.join(list(SYNCAT_ORDER.values())) tup = (word.upper(),) c.execute('''SELECT {0} FROM syncat WHERE word=?'''.format(syncats), tup) result = c.fetchone() re...
ed91a2ad01616e720b11a6a436304dcdcac39898
52,283
def prompt_for_instances(ecs_instances, asg_contents, scale_down=False, sort_by="launch_time"): """ sorts the instances into an order that tries not to cause an AZ imbalance when removing instances. Also, prompts the user if there are issues. @param ecs_instances: list of ECSInstance() objects @para...
6f553330e84dc824ddd9f75cd7f4fb03c19211f6
52,284
def classifier_extra_metrics(features, labels, predictions): """Returns extra metrics to use with classifier.""" if 'logistic' in predictions: return { 'my_mean_prediction': tf.compat.v1.metrics.mean(predictions['logistic']), 'my_mean_age': tf.compat.v1.metrics.mean(featu...
6999ddc6257b7a65c9b71d3ce8e57de2cdce62da
52,285
def getAnswer(x,input_string): """Iegūst mainīgajam x vērtību 1 vai 2, parādot tekstu input_string. Ja ievadīta nepareiza vērtība, tad tiek paradīta kļūdas ziņa.""" while True: try: x = int(input(input_string)) if x < 1: raise ValueError elif x > 2: r...
66f8b1cccef5fb710713f1c6498248dd0f3517ea
52,286
import requests def get_model_version_uri(project_id: int, model_id: Text, version: Text) -> Text: """Get model version URI. Args: project_id {int}: project id model_id {Text}: model id (name) version {Text}: model version Returns: Text: path to model package for model vers...
946c5a1b9b5dabf6350bc3c6c3167d5d8389fea4
52,287
def _depc_factory(name, cache_dir): """DependencyCache factory for the examples Args: name (str): name of the cache (e.g. 'annot') cache_dir (str): name of the cache directory """ cache_dpath = HERE / cache_dir controller = DummyController(cache_dpath) depc = DependencyCache( ...
5b7eab9882e43b27ca4e58dace32e1dbe9b3d5bd
52,288
def nx_to_pandas(g): """ Convert directed multigraph stored as NetworkX MultiDiGraph into Pandas DataFrame. Parameters ---------- g : networkx.MultiDiGraph Directed multigraph to convert. Returns ------- df_node : pandas.DataFrame Node attributes. The NetworkX identifie...
344d0ee7dce5885a2f73709fefbe916cc0dbe125
52,289
def get_case_properties(patient, importer): """ Returns case name and dictionary of case properties to update Raises ConfigurationError if a value cannot be deserialized using the data types given in a column mapping. """ name_columns = importer.name_columns.split(' ') case_name = ' '.join(...
28e6bfc7d052f6d289b8984ca2d455e6e32d0a24
52,290
def review_log(request, type, ctype_id, obj_id): """ Display list of record changes and allow user to select status (approved/not approved) """ current_user = request.user log_list = LogEntry.objects.filter(content_type_id=ctype_id, object_id=obj_id) if type == 'user': # exclude chang...
087ba64d4bc829a66b0a4e35a68d5abebcb0c760
52,291
def left2right_decode( symbols_to_logits_fn, start_symbols, context_BxU_dict, batch_size, max_decode_len, vocab_size, top_p, temperature, beam_size = 1, beam_start = 5, beam_alpha = 0.6, beam_min = 0, beam_max = -1, eos_id = 1, ): """left to right decode. N...
e19b89c284235936c6acef43863f0f1f9ae3ad2c
52,292
from typing import Optional from typing import Union import struct def encode_key( key: str, value: Optional[Union[int, float, str]] = None, value_type: str = "str" ) -> bytes: """Encode given header key to a bytes string. Parameters ---------- key : str header key value : Optional[Un...
b38e04fdbd761bd121f0e08a9eee9dfb692f616c
52,293
import json def loads(*args, **kwargs): """ calls json.loads """ return json.loads(*args, **kwargs)
2696e9a9482898d4dfe8fc9cf9f4bb47ec1da050
52,294
def hashIter(bytesiter, hasher, ashexstr=True): """Will hash the blockIter generator and return digest""" for block in bytesiter: hasher.update(block) return hasher.hexdigest() if ashexstr else hasher.digest()
216435e32901661f3f7c90953dd86e5a00a5b703
52,295
from operator import add from operator import sub from operator import mul from operator import mod def parse(code, delimiter=' '): """Return the result of the RPN calculation of the `code` string or list. Supported operatorations are * +, -, *, mult, /, div, //, idiv, pow, %, mod * sin, cos,...
d55073d730f48cab74b94e9de99c8a7a20b298d7
52,296
def get_session(autocommit=True, expire_on_commit=False, use_slave=False): """Helper method to grab session.""" facade = _create_facade_lazily() return facade.get_session(autocommit=autocommit, expire_on_commit=expire_on_commit, use_slave=use_slave...
45093328345652f54afddeca9834941e9c90903b
52,297
def test_141_parseWind_nonstd(): """Check parsing of nonstandard wind groups.""" def report(wind_group): """(Macro) Return Metar object from parsing the given wind group.""" return Metar.Metar(sta_time + wind_group) assert report("OOOOOKT").wind_speed.value() == 0 assert report("OOOOOK...
5260be6a67771e92a599c8f434132e17dc053809
52,298
def query_aisc_shapes(shape=None, metric=False, version=None): """ Queries the AISC steel shape database and returns a list of the shape names in the specified shape category. Parameters ---------- shape : str The shape for which names will be returned. If None, all shape names ...
765b814d1a77c95eddee9496aee3a2f147662f61
52,299