content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def allInstances(cls): """Return cls instances for each of this class's set""" items = [ (choice.value, cls(name=choice.name)) for choice in cls.set.values() ] items.sort() items = [v[1] for v in items] return items
702a77b9c247ec7976201cd0829a728c6c5fdd1f
3,600,689
def linspace(start: float = 0.0, stop: float = 1.0, num: int = 50): """ Returns evenly spaced numbers over a specified interval. See syntax here: https://numpy.org/doc/stable/reference/generated/numpy.linspace.html """ if not is_casadi_type([start, stop, num], recursive=True): return _onp.l...
aa6a2f003e43e399b7cb4e2eef4cf811860a1691
3,600,690
def define_G(input_nc, output_nc, ngf, netG, norm='batch', use_dropout=False, init_type='normal', init_gain=0.02, gpu_ids=[]): """Create a generator Parameters: input_nc (int) -- the number of channels in input images output_nc (int) -- the number of channels in output images ...
17e268540b344131130b022e2433a13d9e0d1330
3,600,691
def classify(train=None, test=None, data=None, res_dir="res/", disp=True, outfilename=None): """Description of compare compare multiple classifier and display the best one """ utils.print_success("Comparison of differents classifiers") if data is not None: train_features = data["train_featur...
4b8cfec3db44a5477fea766b2e676155121df95e
3,600,692
def _map_sbs_sigs( df: pd.DataFrame, ref_df: pd.DataFrame, ref_type: str, sub_index: str = 'Substitution Type', ) -> pd.Series: """ Map Single-Base Substitution Signatures. ----------------------- Args: * df: pandas.core.frame.DataFrame with index to be mapped * ref_d...
c93f170717b97981f27c642a7b64957d36d822c0
3,600,693
def _dvalid_checkfocus( focus=None, focus_half_width=None, lines_keys=None, lines_lamb=None, lamb=None, ): """ Check the provided focus is properly formatted and convert it focus specifies the wavelength range of interest in which S/N is evaluated It can be provided as: - a spec...
b4a49ae53b128efb6f93c8783cfa25685d7a7b78
3,600,695
def mu_calc(Wv, delta): """ Calculates the mu function used by Thm. 1 (Katz and Reggia 2017). Wv should be the (N by 1) numpy.array W.dot(v) for some point v. delta should be an (N by K) array of deltas to Wv. returns (N by K) numpy.array mu, where mu[i,j] is the maximum of tanh'' over (Wv[i] ...
9b891ca74c0f2b12972d7137d82c3227c97b7a89
3,600,696
from typing import Union def get_json_url(year: Union[str, int], kind: str = "photos") -> str: """Returns url for the json data from news-navigator for given `year` and `kind`""" return f"https://news-navigator.labs.loc.gov/prepackaged/{year}_{kind}.json"
0c7650f667cb1fceebbd73e7a6eaf00145061d38
3,600,697
def d_linalg_norm__d_x(x, return_norm=False): """ Last dimension is normalized. Calculate Jacobian xn = x * (x^2 + y^2 + z^2)^(-1/2) d xn / d x = (y^2 + z^2) * (x^2 + y^2 + z^2)^(-3/2) d yn / d y = (x^2 + y^2) * (x^2 + y^2 + z^2)^(-3/2) d zn / d z= (x^2 + z^2) * (x^2 + y^2...
a4b2eefc93daa0959668b2905beaddbb76403520
3,600,698
def SEQUENCE(*args) -> Function: """ Returns an array of sequential numbers, such as 1, 2, 3, 4. Learn more: https//support.google.com/docs/answer/9368244. """ return Function("SEQUENCE", args)
37ff63df9df9ebf3b2294aaeb3d6126b00641949
3,600,699
import re def _transform_endpoint(endpoint: URL) -> URL: """Transforms a URL endpoint containing variable with realistic values. Args: endpoint (URL): The URL to transform. Returns: URL: The transformed URL. """ endpoint = URL(re.sub(r"<uuid:[^>]*>", str(_create_uuid()), endpoint...
ce08f433bdda02cf51e0fdebed57e0f4b6bed37a
3,600,700
def problem_to_solve(radius_m): """ 안전률을 고려한 허용 응력 :param radius_m: :return: """ # 안전률 safety_factor = 2.0 # 허용 최대 응력 stress_max_Pa = 207e6 # 하중 force_N = 100 result = circular_section_stress(radius_m, force_N) - stress_max_Pa / safety_factor return result
7d06f9fd392074b7a00e9cbc2f30f1b1d75e7389
3,600,701
import collections import functools def get_config(): """Generates the config for the experiment.""" name = 'finite_simple_sanity' n_arm = 3 step_size = 0.01 step_count = 100 agents = collections.OrderedDict( [('Laplace TS', functools.partial(FiniteBernoulliBanditLaplace, n_arm)), ('Langevin ...
c871263f115b815d954a4d73b592caa676c19e2e
3,600,702
def list_grouper(iterable, n, fillvalue=None): """ Collect data into fixed-length chunks or blocks. From: https://docs.python.org/2.7/library/itertools.html#recipes Example: grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx zip_longest: Make an iterator that aggregates elements from each of the iterab...
b9e82907d4a0ff6d4d5b994e12e79590710a29d0
3,600,703
import itertools def map_DEgenes_to_pathways(sign_paths_to_cluster_df: pd.DataFrame, mathys_dict: dict, all_genes_in_pathways: list, path_dict: dict, clusters: list, path_name_to...
75843ab7446dbc4dcff61c02d87a891440e771f3
3,600,704
def capture_progress(config: ProgressConfig) -> t.Tuple[ProgressConfig, t.List[AbstractProgressMonitor]]: """ Creates a ``ProgressConfig`` which captures references to the progress monitor instances created with it. This is intended to be used for testing functions which create progress monitor instances internal...
e1673c7cacc21c8f9968152f0a8e9840618424d5
3,600,705
def move_right(l: list) -> list: """リストの各要素を1つ右に移動させる""" return [l[len(l) - 1]] + l[:len(l) - 1]
c645595532fa2bc89b58cc38eb79feaeb43cf9b2
3,600,706
def upsampling_python(data, scale, layout='NCHW'): """ Python version of scaling using nearest neighbour """ ishape = data.shape if layout == 'NCHW': oshape = (ishape[0], ishape[1], ishape[2]*scale, ishape[3]*scale) output_np = np.zeros(oshape, dtype=data.dtype) for b in range(oshap...
aea0b41998a4da5c33c8624df083d2f4a2cd0847
3,600,708
import json def jsonify(request, *args, **kwargs): """ jsonify with support for MongoDB ObjectId """ dumps = partial(json.dumps, cls=MongoJsonEncoder, indent=True) return json_response(dict(*args, **kwargs), dumps=dumps)
6817c2093aa0e938cdfd05e57ae66b8adbe3e747
3,600,709
def quantile_function(y_pdf, y_true, bins, bin_axis=1): """ Evaluates the quantile function at given y values. """ if len(y_pdf.shape) == 1: bin_axis = 0 n_y = y_pdf.shape[bin_axis] n_b = len(bins) n_dims = len(y_pdf.shape) _check_dimensions(n_y, n_b) xp = get_array_module(y_...
04b7bd1abea52fe75de9e6c7387a452be507c955
3,600,710
def _apple_framework_relative_headers_impl(ctx): """Implementation for apple_framework_relative_headers rule.""" output_dir = ctx.attr.framework_name + "_apple_framework_relative_headers" outputs = [] for f in ctx.files.hdrs: framework_path = "/".join([output_dir, ctx.attr.framework_name, f.basename]) ...
a3198c1054204b58624bbef06532bd8cb30136b5
3,600,711
from typing import Literal def prov_api_record_example(): """ This is a more complex record example :return: """ doc = ProvDocument() doc.add_namespace("ex", "http://example.com") doc.add_namespace("custom", "http://custom.com") attributes = attributes_dict_example() del attribut...
c76c34235a9769533a0b16b4d8de90c2062e64ad
3,600,712
def create_banded(mat, up=2, low=2, col_wise=True, dtype=None): """Create a banded matrix from a given quadratic Matrix. The Matrix will to be returned as a flattend matrix. Either in a column-wise flattend form:: [[0 0 Dup2[2] ... Dup2[N-2] Dup2[N-1] Dup2[N] ] [0 Dup1...
2dd1f2c25eb122a770de8cb62856baec5020c220
3,600,713
def _constant_value(ragged_factory, inner_factory, pylist, dtype, ragged_rank, inner_shape): """Constructs a constant RaggedTensor or RaggedTensorValue. Args: ragged_factory: A factory function with the signature: `ragged_factory(values, row_splits)` inner_factory: A factory funct...
9785af9dc48db70525365884ed45a3923e95ec3f
3,600,714
def gauss_jordan_elimination(arr_: np.ndarray) -> np.ndarray: """ This function is based on Gauss-Jordan elimination algorithm: k = 0, 1, 2, ..., n - 1 > a[k][j] <- a[k][j] / a[k][k] (j = k, k + 1, ..., n) > i != k > a[i][j] <- a[i][j] - a[i][k] * a[k][j] :param arr_: A np.n...
d0f71ce971add957a707bf6d289e6dc85b96cc88
3,600,716
def read_dataset(positive, negative, vocab): """ Create a pytorch SportsDataset for the train and test data. :param positive: Positive examples file pointer :param negative: Negative examples file pointer :param vocab: Vocabulary words file pointer """ # Below, we'll give you some code to ...
f5a826b2646c0b4b8a05e837559d4e9d60c5cb5a
3,600,717
def quantile(x, q, **kwargs): """ Return the values of the quantile cut points specified by fractions `q` of a sequence of data given by `x`. """ x = np.asarray(x) p = np.asarray(q) * 100 return np.nanpercentile(x, p, **kwargs)
2961d62e5834a5f1a402565741bf319f288a2636
3,600,718
def get_champion_by_id(id): """Retrieves a Champion object from the Riot database with the given ID :param id: the ID of the champion. :return: a :class:`pydrake.ddragon.Champion` object with the given ID .. warning:: This should only be called through :meth:`pydrake.PyDrake.get_champion_by_id...
8b058273fa73c5d71bcabed199860978a3416b31
3,600,720
def _mbondi3_radii(topology, all_bonds = None): """ Sets the mbondi3 radii """ if all_bonds is None: all_bonds = _get_bonded_atom_list(topology) radii = _mbondi2_radii(topology, all_bonds=all_bonds) for i, atom in enumerate(topology.atoms()): # carboxylate and HH/HE (ARG) if _is_...
eb2b45e7e5459492c9875d4b083f11c2dbe763ec
3,600,721
def load_and_clean_table(input_data, return_as_df=False): """load and clean table where the input format is a table record """ try: df = load_and_clean_dataframe(pd.DataFrame.from_dict(input_data)) if return_as_df: return df else: return df.to_dict(orient="records") except: print("# [warning] error c...
96bd865f17084a71313b91c00a3580f4cf8dbf1d
3,600,722
def _condition_3_13(A_1_norm, n0, m_max, ell): """ A helper function for the _expm_multiply_* functions. Parameters ---------- A_1_norm : float The precomputed 1-norm of A. n0 : int Number of columns in the _expm_multiply_* B matrix. m_max : int A value related to a ...
92bd4b2521571a1632051c3702b402e7ac8e3e48
3,600,723
import numpy def group(n, fft, grouping=lambda i: i): """ Put fft data into n bins by adding them. grouping function defines how things are grouped lambda i: i --> linear grouping lambda i: 2 ** i --> logarithmic """ if isinstance(n, (list,tuple)): splitPoi...
d7f69e3f575051c00023a5a0d6bb1d4c3ea8c428
3,600,724
import torch def kl_energy(potential_fn, rates_fn, passive_rates_fn): """ Calculates the mean log-likelihood ell of a trajectory. Compares Feynman-Kac measure with parametrized measure. Normalizes mean log-likelihood by dividing by total time and number of sites. """ def validate_fn(traj, dts, tr...
0d081d08e379c7cb5021f565e949dc7e7a48a7d5
3,600,725
def wrap_binary(executable, dotnet, extra = None): """Wraps provided executable with appropriate runfiles and providers. Args: executable: [DotnetLibraryInfo](api.md#DotnetLibraryInfo) to provide launcher for. dotnet: [DotnetContextInfo(api.md#DotnetContextInfo)] for current rule. extra: deps...
e94d29242e0e6d0d2a314e64879670ded440c90a
3,600,727
def predict(x, P, F=1, Q=0, u=0, B=1, alpha=1.): """ Predict next state (prior) using the Kalman filter state propagation equations. Parameters ---------- x : numpy.array State estimate vector P : numpy.array Covariance matrix F : numpy.array() State Transition ma...
ca1adfb97087e96e6fe07bb56bf55ebad71d75ce
3,600,728
from typing import Dict def non_renewables_production_mix(zone_key: str, session) -> Dict[str, dict]: """Retrieves production mix for non renewables using CAMMESA's API""" params = {"id_region": 1002} api_cammesa_response = session.get(CAMMESA_DEMANDA_ENDPOINT, params=params) assert api_cammesa_respo...
dfde41b00930f4590ce6a38ef6c617bef262cf29
3,600,729
def id_for_dst(value): """generate a test id for dest""" return f"dst->{value.comment}"
8db759514d720fd15f437a45ad320edaf3b51c93
3,600,730
def a_from_ssig(ssig, ncounts): """Amplitude of a sinusoid corresponding to a given Z/PDS value From Leahy et al. 1983, given a pulse profile p = lambda * (1 + a * sin(phase)), The theoretical value of Z^2_n is Ncounts / 2 * a^2 Note that if there are multiple sinusoidal components, one can use ...
1485f78a6a8a9da1f29083d8793843b080849c2b
3,600,732
def does_not_contain(token, value): """ Validate that `token` is not a substring of `value` :param: token: string e.g. : | . :param: value: dictionary, list, or str """ if isinstance(value, str): if token in value: raise ValueError(f"{value} cannot contain {token}") if ...
06acdf6643a84f2991180c54cb116d5450bf0a9c
3,600,733
def sample_random_configs(random_config, samples=1, seed=None): """ Sample random configurations from the specified search space. Parameters ---------- random_config: dict dict where each key is a parameter and the value defines how the random sample is drawn. The samples will be dr...
0bde490d77b349a466de3e55230b579eabf265c9
3,600,734
def get_welcome_response(mycity_request): """ Welcomes the user and sets initial session attributes. Is triggered on initial launch and on AMAZON.HelpIntent. If we wanted to initialize the session to have some attributes we could add those here. :param mycity_request: MyCityRequestDataModel ob...
fab9645e49d5eb5f1a16cbb04a78faeef00538c6
3,600,735
def get_dummy_metadata(): """ Incase of a temporal gap, the following metadata is used """ return dict({"product_file": "None"})
71a8a053579a153b9f78fffefe935ed4e9e40d01
3,600,736
def _crc_sign_full_packet_com_key(data: str) -> str: """Calculate the crc for packets before send. Args: data: packet data to sign. Return: The calculated and signed packet data. Raises: aioswitcher.erros.EncodingError: when failed to sign the packet. Note: This is a priv...
ad72b7e9d6b0a1683181874e1f0f128c1db0bca1
3,600,737
def annotate_phased_variants( unphased_isovar_results, min_shared_fragments_for_phasing=MIN_SHARED_FRAGMENTS_FOR_PHASING): """ Annotate IsovarResult objects with phasing information. Phasing is determined by looking at RNA fragments used for assembled protein sequences and counting the n...
ca355bd0c35fd84cbcffc5e84d3929cc9ab8e51b
3,600,739
def get_visualization(name, **kwargs): """ Returns visualization_fn(endnodes, image_info) Args: name: The name of the task. Returns: visualization_fn: A function that visualize the results. Raises: ValueError: If visualization `name` is not recognized. ...
2f257e014cb932cf8f19896f1e78a1e548eb005e
3,600,740
def get_callback_result(callback, res_str): """ 根据callback后的jsonp语句 :param callback: :param res_str: :return: """ if callback is None: return res_str else: return '%s(%s)' % (callback.encode("utf-8"), res_str)
c78d7ff07b9fa07499f9dad41805c67308aa8646
3,600,741
def helpers(request): """return a dict of app helpers""" app = request.app return dict( app_title=app.title, app_url=request.app.url, app_menu=request.app.menu, app_name=request.app.name, app_class=zoom.utils.id_for(request.app.name.strip()), app_description=r...
0bba6085b2e4103813395e76bea7b42dda783cac
3,600,742
def round_nearest(dt, delta): """Round the datetime to the nearest timedelta (e.g. 5 minutes, 2 hours, etc.)""" c = ceil_dt(dt, delta) f = floor_dt(dt, delta) dc = c - dt df = dt - f return c if dc < df else f
67172665f53547d693d2d3814d559af459837614
3,600,743
def find_nearest(array, value): """ Thanks StackOverflow! Parameters ---------- array : np.array of ints or floats 1-D array of numbers to search through. Should already be sorted from low values to high values. value : int or float The value you want to find the closes...
0c490569c52567c498110953b776eba722f27ec5
3,600,744
def compute_output(dims, kernel_size, stride, padding=0): """ Computes the output shape given an input shape, kernel size, stride and padding. """ dims = vectorize(dims) padding = vectorize(padding) kernel_size = vectorize(kernel_size) stride = vectorize(stride) # Vectorized computation ...
37c131263822f54579566e6db2289082cb7b3b58
3,600,745
def _trac_to_github_wiki_links(text: str): """ Takes content with Trac wiki link directives and coverts the directives to inline GitHub wiki links. """ link_matchers = [ # RST markup: ':trac:`wiki:(.+?)`', '`wiki:(.+?)`:trac:', # TracWiki markup: r'`\[wiki:"...
4d8dbcd96540b0dbef3603e9ecb81c6978ef087b
3,600,746
def stouffer_p_value(z_scores, k, rho=0.): """ Parameters ---------- z_scores: array [n, b] Return ------ p_value of the double sided gaussian """ if z_scores.ndim == 2: z_scores = z_scores.sum(axis=1) z_agr = z_scores / np.sqrt(k * (1 + (k - 1) * rho)) return 2 * (1...
893a6413ed12253855b0a21c992b9bdf06ce69bd
3,600,747
def expand_mask(masks, bboxes, im_shape, scores=None, thresh=0.5, scale=1.0, sortby=None): """Expand instance segmentation mask to full image size. Parameters ---------- masks : numpy.ndarray Binary images with shape `N, M, M` bboxes : numpy.ndarray Bounding boxes with shape `N, 4`. ...
7d964ef7e4d24f9128ddfd26e4e9e8d69d9e9c9f
3,600,748
def solve_bernoulli(A, E, B, trans=False, maxiter=100, after_maxiter=3, tol=1e-8): """Compute a solution factor of a Bernoulli equation. Returns a matrix :math:`Y` with identical dimensions to the matrix :math:`A` such that :math:`X = Y Y^H` is an approximate solution of a (generalized) algebraic Bernoulli...
d8dd4483be3208d23b4ecbe22f35d0116dd83d1f
3,600,749
import time def error_2d(nx_power_min, nx_power_max, nx_power_step, mode='O', dielectric=dt.ColdElectronColdIon, max_harmonic=2, max_power=2, has_main_phase=False): """ nx_step: the step size in nx power """ nx_power_array = np.arange(nx_power_min, nx_power_max+1, nx_power_step) ...
ab1d3f90f6352f61e85340fa0ec4d9e653c068e0
3,600,750
def import_dialout_primers(filename): """Returns an array of (forward, reverse) primer pairs. """ return pd.read_csv('kosuri_dialout_primers.csv').values
a1af85aa3805c09b33dfcc8a4fdce3eaf36a9025
3,600,751
def white_noise_block(vary=False, inc_ecorr=False, gp_ecorr=False, efac1=False, select='backend', name=None): """ Returns the white noise block of the model: 1. EFAC per backend/receiver system 2. EQUAD per backend/receiver system 3. ECORR per backend/receiver syst...
b15553f18dc44ed916492af6f8d80e124a804743
3,600,752
def fully_connected_inference(lhs, rhs, nthreads=1): """Create an extern op that compute fully connected of 1D tensor lhs and 2D tensor rhs with nnpack. Parameters ---------- lhs : Tensor lhs 1D array input[input_channels] of FP32 elements rhs : Tensor lhs 2D matrix kernel[outpu...
89770b75704a5c0c93aa715ae84f7c1f49e02083
3,600,753
def MPC_VcGetLastErrorCode() -> int: """Gets the last VICC error code Returns ------- int Last error code field """ err_code = c_uint8() CTS3Exception._check_error(_MPuLib.MPC_VcGetLastErrorCode( c_uint8(0), byref(err_code))) return err_code.value
af16de29df6744342c44662e1e1b43f11e4e291f
3,600,754
def load_into_tf_Dataset(tokenizer, train_texts, val_texts, y_train, y_valid, test_df, batch_size=BATCH_SIZE, prefetch_buffer_size=AUTO): """ Load splitted dataset of training, validation, and test into Tensorflow Dataset API for a more efficient input pipeline, especially for parallelism. Parameters: ...
fb1a8256fdd32bb04fc9fbd06cf94beb1a69908e
3,600,755
def vdecomp(v, m=None, minlen=None, maxlen=None): """ Decompose a vector into components. an nD stack of m-element vectors will return a tuple with up to m elements, each of which will be an nD stack of scalars :param v: nD stack of m-element vectors, a numpy (n+1)D array with shape (n_stack0,n...
cbc846be6a07082711e5c9faa191181c8cdc75f8
3,600,756
def get_credentials(): """Returns the credentials that will be sent to plotly.""" credentials = tools.get_credentials_file() session_credentials = get_session_credentials() for credentials_key in credentials: # checking for not false, but truthy value here is the desired behavior sessio...
db40c16cd024fac8f7a613b629b83ddab4ca8cc0
3,600,757
def extract_group2(filename, refpix): """Read in the PEDESTAL values from a *fitopt.fits file Parameters ---------- filename : str Name of uncalibrated file. This should be a *uncal.fits file. refpix : tup 4-element tuple listing the number of outer rows and columns that ar...
0bf87eea8559d3a8bcef7302e54c71c2d50fa6b3
3,600,758
def plus97_modulus26_minus97(number): """ Replica algunas operaciones realizadas por el DGA a cada caracter. Suma 97, realiza el modulo 26 y vuelve a sumar 97 :param number: entero que representa el carácter en base a la tabla ASCII :return: el carácter resultante """ return chr(((number - 9...
ddf68bb67775fd033d20a6662602a2c0ef34a628
3,600,759
def fixture(names=None, scope="test", per_thread=False): """ Decorator, declare a function as a fixture. :param names: an optional list of names that can be used to access the fixture value, if no names are provided the decorated function name will be used :param scope: the fixture scope, avai...
080cea531f7c4e75b3f54a7aa1f87b5f13be2e66
3,600,760
def browser_to_use(webdriver, browser): """Recover the browser to use with the given webdriver instance. The browser string is case insensitive and needs to be one of the values from BROWSERS_CFG. """ browser = browser.strip().upper() # Have a look the following to see list of supported brows...
0e6bca7bad48c7c2934b81fce080f848e9bcdb22
3,600,761
import gzip import bz2 def open(filename, *args): """ Return a file-like object for various compressed format. """ if filename.endswith('.gz'): opener = gzip.open elif filename.endswith('.bz2'): opener = bz2.BZ2File else: opener = file return opener(filename, *args)
3da3517a6381510a4e901083a3b6cbbde0157873
3,600,762
def update_appliance_hostname( self, ne_pk: str, hostname: str, ) -> bool: """Add or update hostname to Edge Connect appliance. This operation will take a few seconds to run. .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * -...
c08af64efe2e9c1e31faec0845e6bf61606b527b
3,600,763
import functools def get_callable_id(c): """ Get an reasonably good id of any commonly used callable. """ if c is None: return None elif isinstance(c, functools.partial): return get_callable_id(c.func) elif hasattr(c, '__wrapped__'): # @functools.wraps() return get_callable_id...
1e61dbba5a9feace6c2b7f8658c6ef389424cda6
3,600,764
def make_thermostat( device: hm_device.HmDevice, address: str, group_base_channels: list[int] ) -> list[hm_entity.BaseEntity]: """Creates RfThermostat entities.""" return make_custom_entity( device, address, RfThermostat, EntityDefinition.RF_THERMOSTAT, group_base_cha...
3f61caed764578ce36a9d416ef2aa5f10927ef22
3,600,765
def _matrix_multiply(left, right): """Perform symbolic matrix multiply of two 1D or 2D arrays.""" if not (left.ndim in (1, 2) and right.ndim in (1, 2)): raise NotImplementedError( 'Matrix multiplication only implemented for 1D and 2D operands.') elif not left.shape[-1] == right.shape[0]:...
6cf9ebd1a5e0b355c85e0c1d854d555441d4f297
3,600,766
def get_config(path=None): # type: (str) -> RawConfigParser """ Returns a ConfigParser with our current configuration. """ if path is None: path = default_config_path() defaults = { 'base_url': DEFAULT_BASE_URL, } config = RawConfigParser(defaults) config.read([path...
2b965a0bb4a949bd8a852ecd32b4cd18acbe3621
3,600,767
def A_forecast(submodel, horizon, seasonality): """Computing the forecast for the trend=A models ŷ_t+h|t = l_t + h * b_t ŷ_t+h|t = l_t + h * b_t + s_f(s, h) (if seasonality = "A") ŷ_t+h|t = (l_t + h * b_t) * s_f(s,h) (if seasonality = "M") """ points = [] final_state = submodel.get("final_st...
e3511608085b6345e7bfc4a42389fc1ce858c5a8
3,600,768
def get_inspector(): """Reuse inspector""" global _INSPECTOR if _INSPECTOR: return _INSPECTOR bind = op.get_bind() _INSPECTOR = reflection.Inspector.from_engine(bind) return _INSPECTOR
ab4c0459f87c1843cc006e3d44f54199bf43f732
3,600,769
def get_max_table_size(final_tables): """ Compute the maximum number of elements that appear in one of the table generated inside the main process. Parameters ---------- final_tables : list list of the tables generated inside the loop for each bucket. Returns: -------- ...
a562d6f944a03785034028e8b2e83bdb19a8d9aa
3,600,770
def IIR1(q_inst, x, a): """ Rekursives Fixpoint-Filter mit y[i] = Q< x[i-1] + a y[i-1] > Da y immer von der Vorgeschichte abhängt, kann die Rechnung nicht vekto- risiert werden : Langsam! """ y = zeros(len(x)) for i in range(0,len(x)-1): # y[i+1] = x[i] + a * y[i] # no quantization ...
f8f751f3e04d8ef56ffe7d721514d5f1df101934
3,600,771
def StudentTCDF(degree_of_freedom, X): """Student's T distribution CDF. Returns probability that a value x < X. Ported from Java: http://jsci.sourceforge.net/""" A = 0.5 * incompleteBeta(degree_of_freedom / (degree_of_freedom + X * X), 0.5 *degree_of_freedom, 0.5) if X > 0: ret...
dd7773728301b2ea0be77a6167e7e57c301f99b3
3,600,772
def load_or_create_troubleshoot(): """To troubleshoot, replace the load_or_create function in main This forces recreation of dataframes from scratch""" path = pathS3DF.take(1) pathDF = spark.sparkContext.parallelize(path).toDF() cityDF, nearbyDF, cityDayDF, weatherDF, forecastDF = path_to_dfs(path) ...
f91fa6aab0ff45af41a5c635b59ac56333b2a56f
3,600,773
def queuing(training_subjects, validation_subjects, patch_size, n, samples_per_volume=10, max_length=200, num_workers=2): """ Queue used for stochastic patch-based training. See :class:`tio.data.Queue`. :param n: # structures, :type n: int :param training_subjects: train dataset. ...
2712a0ac1ff9cd95ca21113678de53e7a3067175
3,600,774
def init_nfov_projector(imsize, fov): """Creates an equirectangular to perspective projector. Args: imsize: The width and height of the square perspective image. fov: Field of view of the square perspective image. Returns: nfov.NFOV projector. """ horizontal_fov_frac = float(fov) / 360 vertical...
bf9398b5b396ecf86e121f87b2492510a24cffc7
3,600,775
import gzip def read_vocab(input_file): """Read vocabulary file and return a dict""" if input_file is None: return None vocab = {} if input_file.endswith('.gz'): f = tf.gfile.Open(input_file, 'r') fin = gzip.GzipFile(fileobj=f) else: fin = tf.gfile.Open(input_file,...
54f7f55e2b3d66b3e887c9e07757294c4f664f25
3,600,776
def s_block(name=None, group=None, encoder=None, dep=None, dep_value=None, dep_values=None, dep_compare="=="): """ Open a new block under the current request. The returned instance supports the "with" interface so it will be automatically closed for you:: with s_block("header"): s_stati...
eef58ab77168f7ccd48a72a9e0f8726fbf48ad53
3,600,778
from typing import Optional def get_timedelta_from_time_frame(time_frame: Optional[str]) -> timedelta: """Get the timedelta for the given time frame option.""" if time_frame == "year": return timedelta(days=356) if time_frame == "month": return timedelta(days=30) if time_frame == "week...
ee23ad8446a12e3ecd5466a13f2814622b13baf3
3,600,779
def resize_and_threshold(img, thresh, high): """Resizes the image to (216, 64) and does Otsu's thresholding on it. Args: img (np.array[np.uint8]): Image to be processed. mid (int|float): Initial threshold for Otsu's method. high (int|float): Max value of the image for Otsu's thresholdin...
0cfd2fea247661e0d6bc7fde5d35db160c58163c
3,600,781
def build_list(*args): """ Converts an arbitrary list of resources into a dict modeling a kube List. :param args: The incoming arguments can be json/yaml strings, dicts, or apiobjects. :return: A dict modeling a kube dict """ return _to_dict_list(args)
c7b164addb2dd4652267bbd8e7dbe10d8837be47
3,600,782
def _extract_bars(data, metric, exp_num_ticks_init=100000, num_prev_bars=3, num_ticks_ewma_window=20, cache=None, flag=False, num_ticks_bar=None): """ For loop which compiles the various imbalance bars: dollar, volume, or tick. :param data: Contains 3 columns - date_time, price, and volum...
6ea9b39002392ff6d08c362eb5b0fabe4cd26cd8
3,600,783
import itertools def next_bigger(n: int) -> int: """ A function that takes a positive integer number and returns the next bigger number formed by the same digits. If no bigger number can be composed using those digits, return -1 """ numbers = sorted(set(sorted(int(''.join(i)) for i in iterto...
8800040f3e88054bcacdb432131f8a9e0a872277
3,600,784
async def async_setup(hass, config): """Set up the KEF platform.""" if DOMAIN not in hass.data: hass.data[DOMAIN] = {} for conf in config[DOMAIN]: host = conf[CONF_HOST] if host not in hass.data[DOMAIN]: hass.data[DOMAIN][host] = {} mode = get_ip_mode(host) ...
53926dee4084c2ef6dc2be8d0d8a84dff055af48
3,600,785
def decode_ec_public_key(der, encode_ec_point=True): """ Decode a DER-encoded EC public key as stored by OpenSSL into a dictionary of attributes able to be passed to :meth:`pkcs11.Session.create_object`. .. note:: **encode_ec_point** For use as an attribute `EC_POINT` should be DER-encoded (Tr...
5bec5a93ee811b1559cc8ee43d092472be8c1e49
3,600,786
def getItemPos(item, inList): """ get item position from the list """ for i, j in enumerate(inList): if j == item: return i return -1
a77bc384641881582625d6c48187de8d23e7154b
3,600,787
import requests import socket def _get_response_tuple(url): """Return a tuple which contains a result of url test Arguments: url -- a string containing url for testing Result tuple content: result[0] -- boolean value, True if the url is deemed failed result[1] -- unchange url argumen...
786f7ff4e731b968fc502847d1b96b9f3a8274bc
3,600,788
from datetime import datetime from contextlib import suppress def _from_string(value: str) -> tuple[str, TemporalType, datetime]: """Guess the temporal date type from a given string. This function should not be called by the end user. It is used internally by the `parse()` function. Parameters -----...
f1d3205ebdcf486078eb6f521037970006449918
3,600,789
import re def ReplaceResourceZoneWithRegion(ref, args, request): """Replaces the request.name 'locations/{zone}' with 'locations/{region}'.""" del ref, args # Unused. request.name = re.sub( r'(projects/[-a-z0-9]+/locations/[a-z]+-[a-z]+[0-9])[-a-z0-9]*((?:/.*)?)', r'\1\2', request.name) return re...
97f416e77799c28699b251ccd45a89f29cd34c65
3,600,790
from typing import Optional from typing import List def build_transform_gen( cfg: CfgNode, is_train: bool, tfm_gen_repr_list: Optional[List[str]] = None ) -> List[d2T.Transform]: """ This function builds a list of TransformGen or Transform objects using a list of strings (`tfm_gen_repr_list). If list ...
b53e599edc892c4b571a3fc05f03154ec33c3a4a
3,600,791
import re def _squash_column_spec(mif): """Modify MIF column specification. Makes it lok like there is only one column. Returns modified contents and list of original column names. """ with open(mif) as fp: col_start = _find_column_start(fp) data_point = _find_data_line(fp) ...
c40a22ab4344f341ec4184672d77ad9697a9219f
3,600,792
def get_mac_addr_from_datapath(datapath): """ Return the MAC address from the datapath ID. According to OpenFlow switch specification, the lower 48 bits of the datapath ID contains the MAC address. """ mac_addr_int = datapath.id & 0x0000ffffffffffff mac_addr = format(mac_addr_int, '02x') return...
539c0b0a92f3eead947aed65ed62a1e630dcb30f
3,600,793
from typing import Optional def read_devices( skip: int = 0, limit: int = 100, group: Optional[str] = None, db: Session = Depends(get_db), ): """ Get Devices """ if group: db_devices = crud.get_devices_by_group( db=db, group=group, skip=skip, limit=limit ) ...
2e59eb3cee3e31238422d263b5190c7d9f08017d
3,600,794
import math def psnr(img1, img2, max_val=255.): """ computer by batch image: shape (N,H,W,C), or (N,C,H,W) compute in dB psnr = 10log """ mse = F.mse_loss(img1, img2, reduction="none").mean((1,2,3)) return 10. * (2*math.log10(max_val) - mse.log()/LOG10)
80d4ccbfe37c9b884aa489f18bfa8d6eb1a772ae
3,600,796
from typing import Tuple from operator import pos def return_linear_scalarisation( source_coord: Tuple[float, float], target_coord: Tuple[float, float], weight: float ): """Get shortest path where each edge cost is weight * distance + (1-weight) * pollution""" # find vertices in the graph that are close e...
541889dc2bfc34883449a41a71f03323211794a4
3,600,797
def store_to_DB(DB_pano_base, DB_panos, DB_connectors, DB_roads): """ store road data to DB """ config_local = {"con": ENGINE, 'if_exists':'replace'} DB_pano_base_bak = DB_pano_base.copy() try: # transfer the `list` to `str`, for it not compable for saving in pandas dataframe fo...
e0ff92141e26770c7085e21f16ceefbb8fd4a7e1
3,600,798