content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def nan_to_num(X: np.ndarray, value: float = 0.0): """Sets all NaN values in X to the given value. :type X: np.ndarray :type value: float, optional """ return np.nan_to_num(X, value)
3b5dd81670bf072521e865f55bcafb71f6e78611
54,857
def preimage(target, aut): """Return predecessor states of `target`, conjoining player actions.""" action = sym.conj_actions_of(aut.players, aut) vrs = aut.vars_of_all_players qvars = aut.prime_vars(vrs) # \E x', y', i' primed_target = aut.replace_with_primed(vrs, target) u = action & primed...
6aed568f6cadba69c7964b5d0696fdc211db106f
54,859
import binascii def int_to_base64(number): """Convert int -> base64.""" number_bytes = int_to_bytes(number) return binascii.b2a_base64(number_bytes)[:-1].decode('utf-8')
6c420e26551022e55ec3e12caec53df05294c1bd
54,860
def fit_frap(bkgnd_corr_int, frame_interval=1.0, bleach_n_frames=1): """Normalize and fit each fluorescence trace to a standard FRAP curve. Args: bkgnd_corr_int (list): List of numpy arrays (one for each track in track_intensities) storing background-subtracted track intensities ...
2c1f55183ea1199ec530f5df5980d27e6ded3e0e
54,861
def read_raw_parse(path): """ Read GamParse's forum output into a list. :param path: path to a file containing GamParse output :return: a list containing the lines of the input file """ with open(path, 'r') as input_handle: return input_handle.read().splitlines()
26926ca6a164c29681a0cf45a4114ffc5cff0fa9
54,862
from typing import Optional def get_network_region(network_region: str) -> Optional[str]: """ Trim the numbers off the end of nem regions """ if ( network_region and type(network_region) is str and len(network_region) > 1 ): if is_number(network_region[-1:]): ...
59668cae05bae5138d0b71166be59b197b4aaa27
54,863
def aes_cbc_no_padding_encrypt(key, data, iv): """ Encrypts plaintext using AES in CBC mode with a 128, 192 or 256 bit key and no padding. This means the ciphertext must be an exact multiple of 16 bytes long. :param key: The encryption key - a byte string either 16, 24 or 32 bytes long ...
7e21631a0cbd7a6c555f3f156a656a71f592d985
54,864
import math def position_check(inlat, inlon): """ Simple check to make sure that the latitude and longitude are within the bounds specified by the ICOADS documentation. Latitude is between -90 and 90. Longitude is between -180 and 360 :param inlat: latitude :param inlon: longitude :type ...
7f9e6d92667cd81ad02b034fcba231fd4763f966
54,865
from typing import Dict from typing import Any import json def _get_node_provider(provider_config: Dict[str, Any], cluster_name: str, use_cache: bool = True) -> Any: """Get the instantiated node provider for a given provider config. Note that this may be used by ...
2ab2c7d61d9976f447954fe1b24e60287a436359
54,867
def eval_poly_model(theta, obj_dict): """ Routine to evaluate a star spectrum model as a true model spectrum times a polynomial. Parameters ---------- theta : array shape (ntheta,) Array containing the polynomial coefficients obj_dict : dict Dictionary containing additional argum...
28d1e543107c9c0cab568f92057a4876f37d01ec
54,868
import itertools def compute_rank_wr(wr): """ Compute intervals for each ranks in order to plot them. Parameter: wr -- list of Decimal Return: rank_wr -- list of tuples """ # Transform Decimal into float getcontext().prec = 8 wr = [float(w) for w in wr] # Sort by w wr = sorted(wr) rank, wr = find...
a0d7ff4eb7b474015ab408a28ec289f709574a89
54,869
def normalize_email(email): """ Email Address Normalization. 1. Remove leading and trailing spaces. 2. Convert all ASCII characters to lowercase. 3. In gmail.com email addresses, remove the following characters from the username part of the email address: 1) The period (. (ASCII code 46)). ...
e128952a38cd699dffa55de0e486ee6bb245697a
54,870
def make_perfect_cd(wcs): """ Create a perfect (square, orthogonal, undistorted) CD matrix from the input WCS. """ def_scale = (wcs.pscale) / 3600. def_orientat = np.deg2rad(wcs.orientat) perfect_cd = def_scale * np.array( [[-np.cos(def_orientat),np.sin(def_orientat)], [np.s...
68e5c5a55e43aff78485798a4be5a2f5a92e262f
54,871
def urljoin(url, suffix=""): """ Will join url and its suffix Example: "https://google.com/", "/" => "https://google.com/" "https://google.com", "/" => "https://google.com/" "https://google.com", "api" => "https://google.com/api" "https://google.com", "/api" =...
cd8a81d7b427678330d1258fa5644f9d4cf631a0
54,872
import collections def _get_variable_nodes_from_graph_def(graph_def): """Get the list of Variable nodes from `graph_def`. Args: graph_def: An instance of `GraphDef`. This GraphDef *must* have already been optimized by Grappler. In particular, function inlining must have already happened. Ret...
59a7c8b6b0ab6b3ae8d93526127252ed5866329c
54,874
def deprecated(filename, msg=''): """Decorator which will print a warning message on the first call. Use it like this:: @deprecated('myfile', 'do something different...') def fn_name(...) ... And it will print:: WARNING myfile.fn_name deprecated. do something different... ...
75b2774d019665a27aec4432c695163a8e535f2c
54,875
def construct_dataset(df, past_lags, future_intervals): """Construct demand dataset""" # Total NEM demand for a given week df_t = df.sum(axis=1).rename('total_demand') # Add an interval ID df_t = df_t.reset_index().rename_axis('interval').set_index(['year', 'week'], append=True) # Get lags ...
ada01368eb23b01ea9c13f11042088818d6dab81
54,876
def lists( stype="spotify", sort="followers", country="US", limit=100, offset=0, indie=False, ): """ Get the list of playlists, given the streaming platform. https://api.chartmetric.com/api/playlist/:streamingType/lists **Parameters** - `stype`: string streaming plat...
b506a22fd70f69be582484fdb1dabbdfc58ae22a
54,879
def convert_edu_categories_to_years(categories,age_finished_education): """ Converts education categories to years based ob the dictionary 'CamCan2eduyrs'. inputs: categories: list of categories separated with semicolon age_finished_education: age finished full-time education. outp...
88e7ad2502919a6f61aab6f3e7dfba325af76aed
54,880
import struct def ReadUint64(fileBytesIO:BytesIO): """ Reads an unsigned long (uint32) from the current position. """ format = ">Q" rawbytes = ReadRawBytes(fileBytesIO, struct.calcsize(format)) val, = struct.unpack(format, rawbytes) return val
180f4188bf7f7bd4b8f272666340ad9acdc69961
54,881
import logging import requests def fetch_exchange_forecast( zone_key1="JP-TH", zone_key2="JP-TK", session=None, target_datetime=None, logger=logging.getLogger(__name__), ) -> dict: """Gets exchange forecast between two specified zones.""" if not session: session = requests.session(...
a8d1e824d5a254b34f15ead03c100671f69ef017
54,883
def get_dx_dims(fname, dataset): """ Read array size of a specific group of Data Exchange file. Parameters ---------- fname : str String defining the path of file or file name. dataset : str Path to the dataset inside hdf5 file where data is located. Returns ------- ...
38c32b6ae65670e84296186ea33a2ce54ea7ea77
54,884
def adaptive_pixel_signals_from( pixels: int, pixel_weights: np.ndarray, signal_scale: float, pix_indexes_for_sub_slim_index: np.ndarray, pix_size_for_sub_slim_index: np.ndarray, slim_index_for_sub_slim_index: np.ndarray, hyper_image: np.ndarray, ) -> np.ndarray: """ Returns the (hyp...
a5af9249ffa8a9a2665a31b1bfba405c0c9e7247
54,885
import yaml def get_info(dirs, parallel, resources=None): """Retrieve cluster or local filesystem resources from pre-retrieved information. """ # Allow custom specification of cores/memory in resources if resources and isinstance(resources, dict) and "machine" in resources: minfo = resources["...
cc805fe6406a1a803c60825c086c9dc0fb156e5a
54,888
def poly_gcd(a, b): """ Finds the greatest common divisor of two polynomials :math:`a(x)` and :math:`b(x)` over :math:`\\mathrm{GF}(q)`. This implementation uses the Extended Euclidean Algorithm. Parameters ---------- a : galois.Poly A polynomial :math:`a(x)` over :math:`\\mathrm{G...
1e0160426698747a959e38d3ca30906e22e6dd9f
54,889
def keyphrase_label_from(candidate_span, element, generic_label=True): """Receive candidate_span and element from dataset and return keyphrase label""" label = "NON-KEYPHRASE" if "keyphrases" in element and\ "keyphrase-id" in candidate_span and \ candidate_span["keyphrase-id"] in ele...
d9f6e4a0697c441f6b597eaf0695cbdc1cc81d61
54,890
def _calc_fracture_step_sizes(start_yx, ang): """ Calculate the sizes of steps dx and dy to be used when "drawing" the fracture onto the grid. Parameters ---------- start_yx : tuple of int Starting grid coordinates ang : float Fracture angle relative to horizontal (radians) ...
deb7a6c9c13b72005ff986ba0271044450af1c6c
54,891
def delete_user(email): """Delete an existing user. :param email: email of the user :return: True if user could be deleted or False if the user doesn't exist. """ db.connect() try: user = User.get(User.email == email) user.delete() return True except User.DoesNotExis...
cd586b930b47d8b0721300bd895eb863039c366c
54,892
import re def stripper(song: str, artist: str) -> str: """ Generate the url path given the song and artist to format the Genius URL with. Strips the song and artist of special characters and unresolved text such as 'feat.' or text within braces. Then concatenates both with hyphens replacing the blank spaces. Eg....
dc680085d61de798bf45c632106730a0b690ee29
54,893
def _generate_synthetic_gaps( mean: np.ndarray, covariance: np.ndarray, size: int, offset: int, threshold: int, seed: int ) -> np.ndarray: """Return numpy array with the coordinates of gaps in matrix mask. Parameters ------------------ mean: np.ndarray, Mean of biologica...
25872d2de9169f010ab40cdb49cce5eb6764969b
54,894
def score_string(lm, s, k, c): """k: UID exponent; c: string cost""" return lm.score_string_UID(s, k) + c * len(s)
35533d52ec7f1c65f9b49c38b51d52c9fe8c0ef0
54,897
import random def formula_49(r, log, eps=1.e-7): """ Generate shifts from group translation. """ tx0, ty0, tz0 = 0, 0, 0 if(r.tx>eps): tx0 = random.normalvariate(0,r.tx) if(r.ty>eps): ty0 = random.normalvariate(0,r.ty) if(r.tz>eps): tz0 = random.normalvariate(0,r.tz) d_r_V = matrix.col((tx0,ty0,tz0)) ...
a5dc0039aec751738b117cfd263fe6d4f1161e18
54,898
def get_promising_zeros(mtx, R=3): """ Runs over the matrix and finds all indices of zeros that are neighboring a one. The same rule as in the greedy algorithm is used to determine if a position is promising. Result: positionList """ N = 2*R + 1 k = np.ones((N, N)) k[R, R] = 0 mt...
fe876072864d5adfadd47d6d32cc2b4c0d4be948
54,899
def process(command, outfile=None, appendfile=None, dequote=False, shell=False, dependency=None, cwd=None): """Spawns a new process Runs command provided as a new process and returns process info Args: command (str): Command t...
ba1408357ebc82a62fcfe440af9fffb75a0b5832
54,900
from typing import Iterator import types from typing import Callable def pure_functions() -> Iterator[None]: """ Context manager to resolve all ``Callable`` as pure functions. It is not a default in ``hypothesis``. """ def factory(thing) -> st.SearchStrategy: like = (lambda: None) if len(...
f34a42762caae8d0d88c99c4810bdd125077f1a6
54,901
import statistics def ft_compute_median_pmi(path, dropdown_topic_list, n_topic_pmi): """ Computes the pmi score for topics in dropdown list. Takes the stored pmi scores and computes their median. Return a dict with {<topicnbr>: <pmiscore>...} """ dict_pmi = dict() for i in dropdown_topic_l...
b9a9a24aceb07c37c8d30fbe4c1e4461d9a347e4
54,902
def build_next_gen_network_flow_environment( environment_config, episode_length, order_gen: str, reward_function_name: str ): """ Second generation of shipping point assignment environment. Args: environment_config: A dictionary with the config to build the environment, see any PTL run for an ex...
3964a82ecb1e4ad80eeb7d6a0694f6b080fed3dc
54,904
def not_found_or_method_not_allowed(request): """ Overrides the default is HTTPNotFound [404] by appropriate HTTPMethodNotAllowed [405] when applicable. Not found response can correspond to underlying process operation not finding a required item, or a completely unknown route (path did not match any e...
699c573874056639b37492acad0ac2d0c3b0bcbf
54,905
def get_dot_file_path(gname): """ For a graph named gname, this method returns the path to its dot file in the dot_atlas directory. Parameters ---------- gname : str Returns ------- str """ return "dot_atlas/good_bad_trols_" + gname + ".dot"
4ead9a2c3656718a8c088e879742962a9782ef02
54,906
def template(str, template_context, strict_undefined=False): """ Return the value of string templated through the dictionary 'template_context' """ if strict_undefined: env = Environment(undefined=StrictUndefined) else: env = Environment() t = env.from_string(str) result = t....
9f3abe599cbabc676781d096e4609c06fa92f3ea
54,907
def get_dataset(bridge, num_classes): """ Create a tf.data dataset which yields batches of samples for training. Args: bridge: the isaac sample accumulator node which we will acquire samples from Returns: A tf.data dataset which yields batches of training examples. """ dataset = tf.data.D...
9d432f5c7bcbbc7992d03a4cf3e0477940ac3a10
54,908
import numpy import math def monteCarlo(temp, size, trials): """ Calculate the energy and magnetization (\"straight\" and squared) for a given temperature Input: - temp: Temperature to calculate for - size: dimension of square matrix - trials: Monte-carlo trials (how many times do we ...
4221e656dc9bc094b6bde9a6a2a7c629009bd1a9
54,909
def test_api(request, n): """ The API test request handler :param request: the request itself :param n: request path parameter :return: the HTTP response """ if "exception" in request.GET.keys(): try: exception = import_string(request.GET['exception']) raise ...
586c6db94be9b1d294a5f83437aca68f636c28cc
54,910
def parse_sample(sample_text, genotypic): """Parse a single Sample.""" d = {} d['SampleName'] = clean_up(RE_SAMPLENAME.search(sample_text).group(1)) d['SampleSize'] = int(RE_SAMPLESIZE.search(sample_text).group(1)) d['SampleData'] = parse_sampledata(RE_SAMPLEDATA.search(sample_text).group(1), genoty...
6147c11cb78e6ae22ab3cf40537a1d6770edcff5
54,911
def login(): """ Allows user to login to their user account """ if request.method == "POST": # check if username exists in db existing_user = mongo.db.users.find_one( {"username": request.form.get("username").lower()}) if existing_user: # ensure hashed password m...
71cc495eb107e1749737d0757d88a87b4872a6a3
54,912
def rgbi3d(include_top=True, weights=None, input_tensor=None, input_shape=(64, 112, 112, 3), dropout_prob=0.5, channel_axis=4, endpoint_logit=True, classes=10): """ RGB Iception 3D model for video action recognition :param include_...
e9813a1f21c5ebfd1cfdf3db8173964d5d5e0975
54,913
def demand_r2_score(regr, X, y, sample_weight=None): """ Return r2 score of the predicted demand X is a matrix of features with X[:, 0] being the M1 time y is the observed M3 time """ y_true, y_pred = predict_demand(regr, X, y) return r2_score(y_true, y_pred, sample_weight)
0915b0fcd3cf46b5089871960e39d174767dca98
54,914
def widgets_match_pixel_mapping( pixel_mapping: PixelMapping, pixel_options: PixelOptions ) -> bool: """ Checks that the contents of the pixel mapping widgets match the contents of a PixelMapping object. :param pixel_mapping: The Pixel Mapping object that is being edited via the PixelOptions interface. ...
787dcee1cb27ef1bb50abc5f3eb00ee12e426b01
54,915
import json def listExportFilesJson(request): """ Generates a JSON file containing a list of exportfiles and their properties. """ data_header = [ "format", "datatype", "year", "status", "approved", "export_name", "export_file_name", "generated_d...
6a8ad0bee34584c9c05e586c25042e3bd374538d
54,916
import requests import time import json def retrieve_regional_weather_data(box, start_date, end_date, regional_output=RegionalOutput.AVERAGE, output_format=OutputFormat.DATAFRAME, data_request_delay=10): """ This function is useful to retrieve weather data on a rectangle...
6de07b0a379fc9d07e6466bb94b13fcc89a84cc2
54,917
def learn_loop(dataset, answers, target): ### Just the digits from main dataset """Takes a dataset with expected values returns proper weights for each element of the vector space """ # set initial guess, initial weights, threshold, and learning rate binary_dataset = convert_dataset(dataset) [vector.append(1) f...
323626d79a7cc2dd234519eaf2c5417b83124044
54,918
def _invert_signs(signs): """ Shall we invert signs? Invert if first (most probable) term is negative. """ return signs[0] < 0
4135340cfbeb4fce67513a160b63304a3199cf1a
54,919
def cms_open_profile_from_bytes(profile_bytes: bytes) -> qc3const.PyCapsule: """Returns a handle to lcms profile wrapped as a Python object. The handle doesn't require to be closed after usage because on object delete operation Python calls native cms_close_profile() function automatically. :param ...
e6d499a74c57990db925851093fb51455f74d72f
54,920
def main(): """Simple wrapper to call absltest.main().""" return absltest.main()
ad58d4411c2b2dc8ea054dfb9532893b46e8a055
54,921
import requests def get_http_codes_to_retry(): """ :return: set of http codes that should be retried """ return set(x for x in requests.status_codes._codes if should_retry_http_code(x))
ade17904a68d1d5381803909074fc7f63da00c06
54,922
def is_within_r_periodic(structure, central_pos, neighbor_pos, radius): """ :param structure: :param central_pos: :param neighbor_pos: :param radius: :return: """ images = structure.get_periodic_images(neighbor_pos, super_check=2) # Check to see if images are within the radius f...
a536354649ff24de72535170c4cea87a2ac8266f
54,923
import numpy import math import itertools def balanced_synthetic_dataset_uniform(D, N, B, within_noise = 0.5, between_noise = 0.1, cluster_percentage = 1, association_type = 'parabola', number_of_cat = None ): """ D: int number of features N: int number of samples ...
e0b72fac790e597cf21444cd8da0868a4c61328e
54,924
import watchlists def CMDupload(change_info, args): """Uploads the changelist to the server for review. This does not submit a try job; use gcl try to submit a try job. """ if '-s' in args or '--server' in args: ErrorExit('Don\'t use the -s flag, fix codereview.settings instead') if not change_info.Get...
b186efd15cdf1b3410a70b8622fc0b427fecc7bf
54,925
def GetListArgParser(subparser): """Return the list arg parser. Args: subparser: argparse.ArgumentParser that is attached to main acloud cmd. Returns: argparse.ArgumentParser with list options defined. """ list_parser = subparser.add_parser(CMD_LIST) list_parser.required = False...
90ad014be9eab058712a1702b0d16b4517169868
54,926
import math def calculateAllImpactsUsing(treesMap, traversals): """ tressMap - obvious traversals - A list of tuples with right, down traversal steps """ impactsList = [calculateImpactsFrom(treesMap, traversal[0], traversal[1]) for traversal in traversals] return math.prod(impactsList)
435f5e69b1f788edbcf7d86ff4633bcc6d0d7f60
54,927
import importlib def _import_class(module_and_class_name: str) -> type: """Import class from a module, e.g. 'text_recognizer.models.MLP'""" module_name, class_name = module_and_class_name.rsplit(".", 1) module = importlib.import_module(module_name) class_ = getattr(module, class_name) return clas...
0943f237dd8a3e22611c45ac4e640af18a86b90e
54,928
def detail(): """ Serve up details of a specific exploitdb item """ if request.args(0) is None: redirect(URL('index')) record = db(db.t_exploitdb.f_eid == request.args(0)).select(cacheable=True).first() if not record: redirect(URL('default', 'error', vars={'msg': T('Exploit DB r...
849ab44edfc8e1165afbd0b2c7fedb49161f7c34
54,929
def parse_directive(source_text, directive): """ <Purpose> Given the file source, 'source-text', this function will search for the given directive. <Arguments> source_text: The source in which we are searching for a pragma directive. directive: The pragma directive we are searching for. <Excep...
1fb538a75a530ff5c9d368dcc3601be0419fc150
54,933
def minimum_filter(input, size = None, footprint = None, output = None, mode = "reflect", cval = 0.0, origin = 0): """Calculates a multi-dimensional minimum filter. Either a size or a footprint with the filter must be provided. An output array can optionally be provided. The origin parameter ...
a907b7dc75f4e31af76bf211ec7342582d0490a4
54,934
def and_operation(entites , set): """ Helper function.. Reduces the set on every iteration. """ for elem in entites: r = find(elem[1] , set) set = r return set
5db8976d94baed3d99de54c08b45e916164d0712
54,936
def get_projection_matrix(w, centroid, centroid_vec): """ Output: projection matrix P that projects a vector onto the subspace spanned by w, centroid, and centroid_vec P is 3 x num_features """ subspace = np.concatenate(( w.reshape(1, -1), centroid.reshape(1, -1), ...
565c78eaa02e7c09bd08d957b7a7a62cd83e574c
54,937
def safe_xml_tag_name( name: str, numeric_prefix: str = "tag-", empty_fallback: str = "empty-tag" ) -> str: """ Returns a safe xml tag name by replacing invalid characters with a dash. :param name: The name that must be converted to a safe xml tag name. :param numeric_prefix: An xml tag name can't ...
fea34367fbc7f2a4b9dbe23d11c70ecb75dad3da
54,938
def channel(target, pem=None, opts=None): """Construct a grpc channel. Args: target: url of target include host:port pem: ssl/tls pem location opts: grpc channel options grpc.default_authority: default authority grpc.ssl_target_name_override: ssl target n...
7c8880c79662bab3a6d92f1acc12bf31b0456945
54,939
def get_diagnostics(obsname, beamnum, obstype, versionnum, directory): """Get diagnostic to common DB. Inputs: obsname: Observation name in the format: {Project ID}.{Source name}.{MJD}.{Sequence number} beamnum: ALFA beam number (an integer between 0 ...
fc1c863c401af4265ec96ae871013a6917e8345d
54,940
def override_dataframe(dataframe1, dataframe2, index_cols): """override data from dataframe2 in dataframe1 using index_cols as a key to compare. """ dx = dataframe1.to_dict(orient="records") dy = dataframe2.to_dict(orient="records") ddx = {tuple(r[c] for c in index_cols): r for r in dx} ddy...
5daa8b33c98ddb230f13ddf5fe22f3d7e982b9a0
54,941
def create_list(user): """ @api {post} /user/list Create a reading list @apiName Create a reading list @apiGroup List @apiUse AuthorizationTokenHeader @apiParam {String} name List name. @apiParamExample {json} Request (Example) { "name": "CMPUT495 Seminar" } ...
4750f8acd1e6a94a51fb4462c23c8c00cd16582c
54,942
def _opstr_to_meas_circ(op_strings): """Constructs circuits with the correct post-rotations for measurements. Parameters ---------- op_strings : list of str List of strings representing the operators needed for measurements. Returns ------- circs : list of qiskit.QuantumCircuit ...
28fae80f5c874132646101d4620fd622ebd177bb
54,943
import pathlib from typing import Optional def _local_sync_map(local_path: pathlib.Path) -> Optional[_SyncMap]: """ List all the files and directories beneath the ``local_path``. All paths are given as relative paths to the ``local_path``. :param local_path: path to a local directory :return: co...
68dcde7ba2486865ecad7de90a89afa01643ab7b
54,944
def short_long_peak_detector(t_stats, thresholds, window_lengths, peak_height): """Peak detector for two signals. Signal derived from shorter window length takes precedence. Transcribed from find_events_single_scale in wavelet_util.cpp. Equivalent to the MinKNOW implementation as of 25/06/2014. :p...
849d74057b774c42fd233363140770b27e450021
54,945
def ATOL(*new_atol): """Alias for `cfdm.atol`.""" return atol(*new_atol)
6f0cf612ce30af83fdb846ceb3a9cd45417bb647
54,948
def pos_extractor(sentence): """ extract Noun, Adjective, Verb only """ tokens = [] pos = tw.pos(sentence, norm=True, stem=True) for token, p in pos: if p == 'Noun' or p == 'Adjective' or p == 'Verb': tokens.append(token) return tokens
ee2b47e94395b554740bfa286ade5871b1d94dc6
54,949
import numpy def _plot_composite( composite_file_name, composite_name_abbrev, composite_name_verbose, plot_saliency, output_dir_name): """Plots one composite. :param composite_file_name: Path to input file. Will be read by `_read_composite`. :param composite_name_abbrev: Abbrevia...
e115f9bc5158c8aad25688a533ab59131373c8d4
54,951
import logging import json def open_json(filename): """ Given a filename unpacks a json object into an annotation list """ logging.info('Opening json file {}'.format(filename)) with open(filename) as infile: try: logging.info('Decoding .json into annotations'.format(filename)) ...
693b1d07f98e658d004459337da7b97c0405c906
54,952
def lensing_efficiency(x, zx, nz): """Lensing efficiency. This function computes the general form of the lensing efficiency function given in [1]_. Parameters ---------- x: (nx,) array_like Array of comoving distances at which evaluate the lensing efficiency function. zx: ar...
0a775747aa4a3912ef972ce507e92b3d797828d8
54,953
from typing import List from typing import Dict def get_columns_from_tables(tables: List[Table]) -> List[Column]: """ Return the superset of columns from a list of tables. """ columns: Dict[str, Column] = {} for table in tables: for column in table.columns: name = column.name ...
685664217040256f0ad420aafd44a5384af19354
54,954
def build_model(input_size: int, output_size: int, hidden_sizes: list) -> nn.Sequential: """Create the neural network model""" return nn.Sequential( nn.Linear(input_size, hidden_sizes[0]), nn.Tanh(), nn.Linear(hidd...
77970c09cd2553ae64e6da8b3cc9a3dfe1b28871
54,955
def list_multipart_upload(resource, bucket_name, prefix=""): """List in-progress multipart uploads""" client = resource.meta.client mpupload = client.list_multipart_uploads(Bucket=bucket_name, Prefix=prefix) return { "Uploads": mpupload.get("Uploads"), "CommonPrefixes": mpupload.get("Co...
669b852a8c38acc58f1a4dad833a03d011bb4e14
54,957
from re import A def sbox(x): """AES S-Box.""" y = mpc.to_bits(x**254) z = mpc.matrix_prod([y], A, True)[0] w = mpc.vector_add(z, B) v = mpc.from_bits(w) return v
ff201bbdc1982f5c4ec92ecaaf07c8893839a98f
54,958
import scipy def makePermutationMatrix(permList): """ Takes a list defining the permutation and makes the appropriate matrix. """ permList = scipy.array(permList) n = len(permList) if 0 not in permList: permList = permList - 1 permMat = scipy.zeros((n,n),'d') for ii, jj in enum...
bdd04dc4deb15aa69228f0d3004c299dcf1a55a8
54,959
from typing import Tuple def compute_daily_change(series: pd.Series) -> Tuple[Tuple[pd.Series, str], Tuple[pd.Series, str], Tuple[pd.Series, str]]: """returns (change, smooth, smooth2) where 'change' is ...
2867e27344410f9e80dcc1c5c633a91a14aaae9c
54,960
def tcl_prep_otaver(ota=None): """ Prepare variables for OTA versus full check. :param ota: The starting version if OTA, None if not. Default is None. :type ota: str """ if ota is not None: mode = 2 fvver = ota else: mode = 4 fvver = "AAA000" return mode,...
b42c9af8abd9b6c2b361d906737429acf967182b
54,961
def aboutme_view(request): """About me static page""" cl = CategoryLister(request.LANGUAGE_CODE) t = loader.get_template('blog/aboutme.html') c = RequestContext(request, { 'cat_list': cl.get_categories(), 'link_list': Link.objects.all().order_by('order'), 'about_text': AboutMe....
1ce2b147b11cc672d753caa9546ef9e3abc6a55b
54,962
def test4(dims,fout): """ Cylinder defined as a dataset in an otherwise empty box. As per test 3, but the cylinder is along the third dimension instead, to be able to store it more efficiently """ def circle(idx1,idx2,cd1,cd2,r) : d = np.sqrt(abs(idx2-cd2)**2 + abs(idx1-cd1)**2) ...
d00a8365a16eaa6225595b52b95bbfd8dc7bacbb
54,963
def view_specific_post(post_id: int): """...""" form = forms.NewReplyForm() post = models.db.session.query(models.Post).get(post_id) replies = models.db.session.query(models.Post).filter(models.Post.reply_to == post_id) return render_template( 'post.html', form=form, post=po...
75e3fa5afb26d4b07ee8dc04916699ef892d55d5
54,965
from datetime import datetime def child_elem_as_datetime(elem,qname,format): """Returns the content of the child element as datetime.""" child = elem.find_child_element(qname) if child: return datetime.datetime.strptime(str(child.schema_actual_value),format) return None
5cb025448c96a3ed336f7403be622f161bf9d8c3
54,966
def count_large_cell_angle_regions(field, /, min_angle, direction=None, units='rad'): """Count regions with large angles between neighbouring cells. This method counts regions, where the angle between neighbouring cells is above the given threshold. If ``direction`` is no...
2a636d0574ef36d37efc93e29de2e190d4555dc5
54,967
def get_location_count(): """ Get the total number of locations. Returns ------- count : int The total number of locations. """ count = Location.query.count() return count
562d7b6c762ca77d13f74413bb0089db739ca580
54,968
def delete_keyword_metadata(request, hs_file_type, file_type_id, **kwargs): """deletes a keyword for a given logical file The keyword to be deleted is expected as part of the request.POST NOTE: This view function must be called via ajax call """ logical_file, json_response = _get_logical_file(hs_fi...
c1068ab70706b459a38388ed572a7c7c3c270a34
54,969
import numpy def nc_read_var(ncFile,ThisOne): """ Reads a variable from a netCDF file and returns the data, the QC flag and the variable attribute dictionary. """ # check the number of dimensions nDims = len(ncFile.variables[ThisOne].shape) if nDims not in [1,3]: msg = "nc_read_var...
bdd59a3314a44f5cd8d82a36101e16c15d5ba64b
54,970
def whereis_file(self, path): """Same as `whereis_file_()`, but for a single path and return-dict""" #return list(self.whereis_file_([path]))[0] return list(whereis_file_(self, [path]))[0]
d921a2370eaa4369bd0afa589e1b4e12443570e8
54,971
def _build_doxygen_main(args, env): """Customize the doxygen input file. Run the doxygen command, copy in any images, and put the output in the right place.""" if isinstance(args, list): if len(args) < 2: base.die("Need subs dictionary and dummy file arg for the doxygen command " + ...
52ded17816f96e427f3a7b7aaf345dd6065b4aac
54,972
import math def cov(x, y, mean_x=None, mean_y=None, return_gram=False, return_mean=False): """ Computes a covariance between two matrices using the form Cov(X, Y) = E(XY) - E(X)E(Y) This function prevents the need to explicitly compute the outer product E(X)E(Y) by taking advantage of...
d0346d76baf32c30d23df7b6622c904efb340443
54,973
def evaluation(logits, labels): """Evaluate the quality of the logits at predicting the label. Args: logits: Logits tensor, float - [batch_size, NUM_CLASSES]. labels: Labels tensor, int32 - [batch_size], with values in the range [0, NUM_CLASSES). Returns: A scalar int32 tensor with the number ...
d4106c57be1a27758cf51fbfc0774ed337ecc5e2
54,974
def pessoa(texto): """ :param texto: :return: """ while True: p = input(texto).strip().upper() if p.isdigit() or p == '': print('Erro, digite um nome válido por favor.') else: return p
e07755638c291a726b7681dbc013a43b21a3890b
54,975
def get_r_intmit(q_HPU_ave, q_HPU_min): """1時間平均のヒートポンプユニットの断続運転率 (5) Args: q_HPU_ave(ndarray): 1時間平均のヒートポンプユニットの平均暖房出力 (W) q_HPU_min(ndarray): 1時間平均のヒートポンプユニットの最小暖房出力 (W) Returns: ndarray: 1時間平均のヒートポンプユニットの断続運転率 (5) """ r_intmit = np.clip(q_HPU_ave / q_HPU_min, None, 1.0) r...
8598d5f325f90c722b83bcd784a2151f3318299c
54,976