content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Iterable def IncrementMetricsSpecsCounters(pipeline: beam.Pipeline, metrics_specs: Iterable[config.MetricsSpec]): """To track count of all metrics specs in TFMA.""" def _MakeAndIncrementCounters(_): for metrics_spec in metrics_specs: for metric in me...
f1c6e4cc60f89b8f48cd6df6f8688a924d444f5c
3,625,900
def make_random_circuit(n_rows, n_cols, depth): """Generate a random unparameterized circuit of fixed depth.""" return cirq.experiments.generate_boixo_2018_supremacy_circuits_v2_grid( n_rows=n_rows, n_cols=n_cols, cz_depth=depth - 2, # Account for beginning/ending Hadamard layers ...
79f3978cffcbdffe2d7e9cede7052fd4c513a2d2
3,625,901
def update_worker( *, db_session: Session = Depends(get_db), worker_id: int, worker_in: WorkerUpdate, ): """ Update a worker contact. """ worker = get(db_session=db_session, worker_id=worker_id) if not worker: raise HTTPException(status_code=204, detail="The worker with this ...
367ec0c6ee4047f1e1687150cbf834e872feb300
3,625,902
def save(filename, ax=None): """Save figure. Parameters ---------- filename : string The filepath into which the current figure will be saved. ax : `matplotlib.pyplot.Axes`, `None` by default The axis from which the plot to be saved derives. If left as `None`, `matplotlib.p...
c0ee2112d056270339eda604548be291b391464c
3,625,903
from typing import List from typing import Mapping import functools import tqdm import pickle def process_reader_outputs(fnames: List[str], reader: str, dart_ids: Mapping[str, str] = None, extract_filter: List[str] = None, ...
d8fef42f36010fd1fb8b4924c161a4fa7b31031c
3,625,904
from typing import Callable from typing import Type def add_arg_type_after_self(t: Callable, arg_type: Type) -> Callable: """Add an argument with the given type to a callable type after 'self'.""" return Callable([t.arg_types[0], arg_type] + t.arg_types[1:], [t.arg_kinds[0], nodes.ARG_POS]...
aabd77204b7b7ab5849f69c07b545446f7893370
3,625,905
def extract_constraints(input_def): """ :param input_def: an input definition. :return: Constraint instances in respect to the constraint defined in the input definition. """ return [parse(c) for c in input_def.get(CONSTRAINT_CONST, [])]
c49944f559a28cc429f59bd925646748e661a24c
3,625,906
def load_italy_power_demand(split=None, return_X_y=False): """ Loads the ItalyPowerDemand time series classification problem and returns X and y Parameters ---------- split: None or str{"train", "test"}, optional (default=None) Whether to load the train or test partition of the problem....
2b37d4aa1035a936d5315308a262e40e41f677c7
3,625,907
def softmax(arr, axis=None): """softmax""" return np.exp(arr) / np.sum(np.exp(arr), axis=axis, keepdims=True)
202850edd408d835089601619be651ff978d052e
3,625,908
def get_target_project_select(site, project): """Return remote target project level selection HTML""" current_level = None try: rp = RemoteProject.objects.get( site__mode=SODAR_CONSTANTS['SITE_MODE_TARGET'], site=site, project_uuid=project.sodar_uuid, ) ...
0b15e03e6cdb907cc1eeca46eb64ef779c7386c0
3,625,909
def form_SelectWithOtherChoice(request): """ A basic select choice with input option """ schema = schemaish.Structure() schema.add('mySelect', schemaish.Integer()) options = [(1,'a'),(2,'b'),(3,'c')] form = formish.Form(schema, 'form') form['mySelect'].widget = formish.SelectWithOtherCh...
d55dc7f2ee30f50d86cdc3eb0f85c52cb33e5f51
3,625,910
def default_handler(request): """ The default handler gets invoked if no handler is set for a request type """ return alexa.respond(get_pool_weather_handler(request))
6616979f40106538b14d26cc82a63c827107b910
3,625,911
def check_ghi_limits_QCRad(ghi, solar_zenith, dni_extra, limits=None): """ Tests for physical limits on GHI using the QCRad criteria. Test passes if a value > lower bound and value < upper bound. Lower bounds are constant for all tests. Upper bounds are calculated as .. math:: ub = min + m...
f4c158a6358c618d291caa288ea36c0cf5ecc146
3,625,912
from typing import Callable def register(func: Callable, module: ModuleType, generate_lm=False) -> KscStub: """ Main Knossos entry point. The @register decorator transforms a TorchScript function into a KscAutogradFunction which implements the function and its derivatives. ``` @knosso...
555a70e36e5de0db4ad16c5da326dd03e6ceca0a
3,625,913
import json import os import logging def load_and_save_params(default_params, exp_dir, ignore_existing=False): """Update default_params with params.json from exp_dir and overwrite params.json with updated version.""" default_params = json.loads(json.dumps(default_params)) param_path = os.path.join(exp_dir...
4a0e9c1e24ec914abe1540ad9dd7d655b96c0e39
3,625,914
def endpoint_registry_contract(deploy_tester_contract): """Deployed SecretRegistry contract""" return deploy_tester_contract(CONTRACT_ENDPOINT_REGISTRY)
484bd3804b20a2d450149a52ca562f4e7284a599
3,625,915
def generate_input_with_unknown_words(file_path): """Reads the file with the given file_path. Replaces every first occurance of a (word, tag) pair with ("<UNK>", tag). Creates dictionary of all words encountered in following format: {(word, tag) : count}""" seen_tuples = [] label_matches = dict() file_lines = []...
21479c1953dc1779a28bc49a38de55c383513fbf
3,625,916
def get_file_at_commit(directory, commit, path): """ Get the contents of repository `path` at commit `commit` given the Git working directory `directory`. :param directory: Git working directory. :param commit: Commit ID :param path: In-repository path :return: File contents as bytes :r...
4abc4d352188ebf0a6cfac215fb506fa6e75017b
3,625,917
def three_body_force_en(env1, env2, d1, hyps, cutoffs, cutoff_func=cf.quadratic_cutoff): """3-body single-element kernel between a force component and a local energy. Args: env1 (AtomicEnvironment): Local environment associated with the force component. env2 (AtomicEnvironment):...
8ca680d774ceb70de8923f53a88a4d9d87a91533
3,625,918
import os def _GetTipOfTrunkVersionFile(root): """Returns the current Chromium version, from a file in a checkout. Args: root: path to the root of the chromium checkout. """ version_file = os.path.join(root, 'src', 'chrome', 'VERSION') chrome_version_info = cros_build_lib.RunCommand( ['cat', ver...
c4cb64d1a5695fb482d0e543d44f0c0b4eabf2fa
3,625,919
def include_silently(parser, token): """ Include template if it exists. If it doesn't exist then will not raise any exception. {% include_silently "mytemplate.html" %} """ try: tag_name, template_name = token.split_contents() except ValueError: raise template.TemplateSyntaxEr...
432024729e5e212e3bf9ce837f42f57e3ced6822
3,625,920
def parse_array(a, separator=' ', dtype=DEFAULT_FLOAT_DTYPE): """ Converts given string or array of strings to :class:`ndarray` class. Parameters ---------- a : unicode or array_like String or array of strings to convert. separator : unicode Separator to split the string with. ...
e8e737b4f224b16feb1037d1ad715f4db676a7d2
3,625,921
def dAdzmm_ron_s0_nm2(u0,u0_conj, M1, M2, Q, tsh, dt, hf, w_tiled, gam_no_aeff): """ calculates the nonlinear operator for a given field u0 use: dA = dAdzmm(u0) """ M3 = uabs_nm2(u0,u0_conj,M2) M4 = dt*fftshift(ifft(fft(M3)*hf), axes = -1) # creates matrix M4 N = nonlin_ram_nm2(M1, Q, u0, M3...
e54853454952e2df7c71c51177da6ed9472d2e44
3,625,922
def run(): """Requirements for Task 1B""" # Build list of stations stations = build_station_list(False) #Find stations within the radius stations_in_radius = stations_within_radius(stations, (52.2053, 0.1218), 10) #function to print the station details in a parsable form def stations_in_r...
dbb4c45735de532d8ffe2429f8a7c8b4168db60f
3,625,923
def capsules_init(inputs, filter_size, stride, OUT, pose_shape, padding='VALID', add_reg=False, use_bias=True, name=None): """This constructs a primary capsule layer from a regular convolution layer.""" with tf.variable_scope(name): sum_list = [] num_filters = OUT * pose_shape[...
876e9d3daddde934c80fc5eebefe0ac85fc68517
3,625,924
def secure_erase_key( key_path ): """ 'Securely' erase a key at key_path. Fill it with random data first, flush the data, and then unlink it. Return True on success Return False on error. """ try: size = os.stat( key_path ).st_size except OSError, oe: log.error("Failed to stat %s"...
dde39b0814e0bf210d53bb1f07a3a16387b9ec92
3,625,925
def get_chamber_bills( session, chamber, page_size=None, page=None ) -> ChamberBillList: # noqa: E501 """get_chamber_bills Retrieving a list of bills # noqa: E501 :param session: Congress session :type session: str :param chamber: The chamber of Congress to query :type chamber: str :p...
e5ee8e215292790af0e0565148ff2b9c72712019
3,625,926
def from_nested_to_multi_index(X, instance_index=None, time_index=None): """Converts nested pandas DataFrame (with time series as pandas Series or NumPy array in cells) into multi-indexed pandas DataFrame. Can convert mixed nested and primitive DataFrame to multi-index DataFrame. Parameters ------...
b728854b5a04371e785d53419075575fd5d21370
3,625,927
import enum def lt24lcd_driver(glbl, lcd, cmd, datalen, data, datasent, datalast, cmd_in_progress, maxlen=76800): """ :param glbl: :param lcd: :param cmd: :param datalen: number of data xfer to do :param data: data to be sent :param data_sent: one cycle strobe indicati...
9db645aa1b29421ad9f6defde7a9697e216baaf4
3,625,928
from typing import Any async def craete(*args: Any, **kwargs: Any) -> Page: """[Deprecated] miss-spelled function. This function is undocumented and will be removed in future release. """ logger.warning( '`craete` function is deprecated and will be removed in future. ' 'Use `Page.crea...
f88267f1e7ca717b37b2bb95cbaf4a621b786ba2
3,625,929
def __get_candidate_set(previous: int, candidates: np.ndarray, visited: np.ndarray) -> int: """ Рандомный из кандидатов """ candidates = np.array([idx for idx in candidates[previous] if idx != -1 and not visited[idx]]) if len(candidates) != 0: return np.random.choice(candidates) return -1
1087a3e4b9fd1d7eb9395a747bf3acce8d45b9c9
3,625,930
import logging def filter_by_period( obj, start_time, end_time, axis=None, mode=None, verbosity=logging.DEBUG ): """ Filter an obj that can be sliced with [start_time:end_time] reporting stats. """ log.log(verbosity, "# Filtering in [%s, %s]", start_time, end_time) if isinstance(obj, pd.Pa...
d3f0cfabf2c826c2c5674db23d3d9320ca20cf33
3,625,931
def trim_jumps(sweep, jump_size, trim=1, x_column=None): """ Clean up jumps in the data by removing several data points around them. Remove `trim` datapoints on both sides of jumps if at least `jump_size`. For multi-column data, `x_column` specifies the columns of interest. """ if not isinstanc...
3901bda9c4b68ea86629bf8aea385ab316fc1bfd
3,625,932
def load_unknown_sample(sample_file_name, stomp_map, args): """ Method for loading a set of objects with unknown redshifts into the-wizz. This function maskes the data and returns a STOMP.iTreeMap object which is a searchable quad tree where each object stored has a unique index. If a name of an index c...
e3868e91c8037c17413353283a52b5afec28ad59
3,625,933
def _left_to_right_overlap(biluov, sentence): """ LEFTMOST TAG MUST BE 'V' >>> _left_to_right_overlap(['V', 'V', 'O', 'V', 'I', 'L', 'O', 'I', 'L'], range(9)) [[0, 1, 3, 4, 5], [0, 1, 3, 7, 8]] >>> _left_to_right_overlap(['V', 'O', 'V', 'O'], range(4)) [] >>> _left_to_right_overlap(['V', 'O...
efadec066b9bd7654ebbefc8d8988eecfa4642d7
3,625,934
def terminal_values(rets): """ Computes the terminal values from a set of returns supplied as a T x N DataFrame Return a Series of length N indexed by the columns of rets """ return (rets+1).prod()
bea1f2a668deac3e915f7531ab68aea207e57d91
3,625,935
import SumWithElectronegativities as descriptor def assemble_batch(folder_list, species="C", descriptor=None): """Looks in all folders for results to create a large batch to test the network on. Args: - folder_list <list<str>>: a list of full paths to data base folders w/ molecule resul...
3316f31c0ce01f23d8ffc2526d689d5589de3c7c
3,625,936
def stretch_mat_creation(refcc, str_range=0.01, nstr=1001): """ Matrix of stretched instance of a reference trace. From the MIIC Development Team (eraldo.pomponi@uni-leipzig.de) The reference trace is stretched using a cubic spline interpolation algorithm form ``-str_range`` to ``str_range`` (in %) for...
ddc78aa83b2444517b564fb9cbd1d073cbfff33b
3,625,937
import numpy def clip_matrix(left, right, bottom, top, near, far, perspective=False): """Return matrix to obtain normalized device coordinates from frustrum. """ if left >= right or bottom >= top or near >= far: raise ValueError("invalid frustrum") if perspective: if near <= _EPS: ...
7de5ba1522bbe3ecd46f9bc2ddcbadf452dead6c
3,625,938
def flip_horizontal(old_img): """ flip the image over the y axis """ rows = old_img.shape[0] cols = old_img.shape[1] new_img = np.zeros((rows, cols), np.uint8) # create a black grayscale image having same size as original for c in range(1, cols + 1): # iterate over the image columns (+1 because ra...
0fb9beda2dded322ac639e41e05521467ccb017b
3,625,939
def position_delta(trades, price_currency=None, volume_currency='BTC'): """ This function calculates our position across a list of trades for both the price and volume currencies. This is equivalent to calculating the total amount our balance in the two currencies have changed, and to the difference bet...
5a3491848321cf38bb050de5863703e5fd19ffe7
3,625,940
def is_grammar_correct(grammar): """ This function checks if the grammar "grammar" is correct Input: - "grammar" is a grammar """ allrules = set(grammar.keys()) for rule_key in grammar: if isinstance(grammar[rule_key], ConstructorRule): for parameter in grammar[rule_key]....
4e06efaf9350b608ae984c0d0482227b9e02fbbf
3,625,941
def countTransactions(Transaction_list): """ A list like the following [ [1,1,1], [0,0,0], [1,1,1], [1,1,0], [1,1,1] ] should be converted to a list without any duplicates and count of each list should be appended to the list items [ [1, 1, 0, 1], [0, 0, 0, 1], [1, 1, 1...
cc5814009b610d0869912cf1ee4b58c6f102579e
3,625,942
def flatten_tree_depth_first(tree, exclude=None, exclude_children=False, return_only_run_id=False, return_trace=False): """ Flatten a run tree in a depth-first manner. May return a list of run ids or runs. :param tree: dict The tree to flatten :param exclude: A function to exclude nodes...
0f30d2903e1cdbe4b838deebcd747d009919c632
3,625,943
import math def michalewicz(x: TensorType, d: int = 2, m: int = 10) -> TensorType: """ The Michalewicz function over :math:`[0, \\pi]` for all i=1,...,d. Dimensionality is determined by the parameter ``d`` and it features steep ridges and drops. It has :math:`d!` local minima, and it is multimodal. Th...
3af0f6992ba5c28a0a61bb1fed5b6efad5ddcfb9
3,625,944
def check_stitching(stitch_file): """ Take a stitch log file from MIPWrangler output, return summary datframe. """ with open(stitch_file) as infile: stitch = [] for line in infile: newline = line.strip() stitch.append(newline) sti_sum = [] for l in stitch:...
6c6b68ec910ad0dd63504eff9fe0d644bdaa2df3
3,625,945
def levelConditions(state,stage): """ This is specifically created for purpose of the game plot. It sets the conditions for when the game level changes and the plot moves forward. It also updates what music is playing and can come with a noise as the level changes. If the music is updates it returns Tru...
8f84b1ca0d8083e90c730d47ebbd34d86d346462
3,625,946
import re def parse_vehicle_type(vehicle, include_number=False): """ Takes a vehicle string (BE.NMBS.IC504) and returns a human-readable version of its type (e.g. IC, L) """ matches = re.match(r'(?:BE.NMBS.)?([A-Z]{1,3})(\d{1,4})', vehicle) try: train_type = matches.group(1) ex...
de1d184406b55a8c44ee3d104ba3f9882c95b4da
3,625,947
import torch def make_train_step(model, optimizer): """ Builds function that performs a step in the train loop. Extracted from: https://towardsdatascience.com/understanding-pytorch-with-an-example-a-step-by-step-tutorial-81fc5f8c4e8e#58f2 """ def train_step(xdata, ydata): # Zeroes gra...
946e499586494acbdedcc94594b625896569b7b5
3,625,948
def get_writer(settings): """ Get a :py:class:`gnsq.Nsqd` instance configured to connect to the nsqd writer address configured in settings. The writer communicates over the nsq HTTP API and does not hold a connection open to the nsq instance. """ ns = settings.get('nsq.namespace') addr = set...
de3eaab55756ebe5790e0275e6ce5aeb67803169
3,625,949
def get_names_times(*args, **kwargs): """ Wrapper for get_names_dates: def get_names_dates(ftp, fname=None): Examples -------- import ftplib import os ftp = ftplib.FTP("ftp.server.de") ftp.login("user", "password") ftp.cwd('ftp/directory'...
dc4ad23ccfbea8fc10824b1f1add052bb7ab80e4
3,625,950
from typing import Union import os from typing import IO from typing import Optional import warnings def load_raw_resource_description( source: Union[dict, os.PathLike, IO, str, bytes, raw_nodes.URI, RawResourceDescription], update_to_format: Optional[str] = None, ) -> RawResourceDescription: """load a ra...
8f79b3d0c91189867914f617c375c6d7bf584313
3,625,951
def get_context(template, line, num_lines=5, marker=None): """ Returns debugging context around a line in a given string Returns:: string """ template_lines = template.splitlines() num_template_lines = len(template_lines) # In test mode, a single line template would return a crazy line num...
36dd6dc91340c1297057f4d5905589bfca041ac3
3,625,952
def sequence_conv(num_filters, filter_size=3, filter_stride=1, padding=None, bias_attr=None, param_attr=None, act=None, name=None): """ Return a function that creates a paddle.fluid.laye...
a6e39fe0e01ce676234df94a004021f2b688d124
3,625,953
import os def get_designer_path(): """ Get the path of the Designer directory. """ return os.path.dirname(designer.__file__) + '/'
844ccfc1757265b61e1add385d10d7059348975b
3,625,954
def getColumnNames(hdu): """Get names of columns in HDU.""" return [d.name for d in hdu.get_coldefs()]
9ac8fefe6fcf0e7aed10699f19b849c14b022d47
3,625,955
def read_bed(bed_path): """Reads bed file into a DataFrame.""" bed_cols = [ 'chrom', 'chromStart', 'chromEnd', 'name', 'score', 'strand', 'thickStart', 'thickEnd', 'itemRgb', 'blockCount', 'blockSizes', 'blockStarts' ] data = pd.read_csv(bed_path, sep='\t', header=None) dat...
08dd42808f6e089e9fe65a5c6e68fb28b47afcd6
3,625,956
import torch def embedding_to_probability(embedding: torch.Tensor, centroids: torch.Tensor, sigma: torch.Tensor) -> torch.Tensor: """ Vectorizing this is slower than the loop!!! # / (e_ix - C_kx)^2 (e_iy - C_ky)^2 (e_iz - C_kz)^2 \ # prob_k(e_i) = exp |-1 * ----...
133b7b81bb00db2110b6ec9709ab89924dee2dc4
3,625,957
def check_if_session_accepted(data): """ Check if the session can be accepted given the criteria in config Note: qualification and setup are skipped as they are checked in JS. Workers cannot continue if they do not pass. :param data: :return: """ msg = "Make sure you follow the instruction:...
f392a28e8e9805adfac8459e054a909c4c4905f3
3,625,958
def _get_fingerprint(arg, controller): """ Resolves user input into a relay fingerprint. This accepts... * Fingerprints * Nicknames * IPv4 addresses, either with or without an ORPort * Empty input, which is resolved to ourselves if we're a relay :param str arg: input to be resolved to a relay fi...
106a482dc9e33b158e466c736f82aea24e40e345
3,625,959
import decimal def versions_rank_algorithm(quality, popularity): """ Generate a score for this version of an ebook. The quality score and the popularity score are ratioed together 70:30 Since popularity is a scalar and can grow indefinitely, it's divided by the number of total system users. ...
830138290357b4978513b74453e78e8379f4b153
3,625,960
def get_colors(colormap, ncol, alpha=1.0, hide_traceback=True): """ Get a list of rgb values for a matplotlib colormap Parameters ---------- colormap : str, default "WORM" Name of the colormap to color the scatterpoints. Accepts "WORM", "colorblind", or matplotlib colormaps. ...
2f5c99d8e5b99c32103e169da90571ddf7e1cd68
3,625,961
def get_url(server_name, listen_port): """ Generating URL to get the information from namenode/namenode :param server_name: :param listen_port: :return: """ if listen_port < 0: print ("Invalid Port") exit() if not server_name: print("Pass valid Host...
097e347a75eb581ae97734552fa6f9e7d3b11ce6
3,625,962
def alpha_shape(points, alpha, only_outer=True): """ Compute the alpha shape (concave hull) of a set of points. :param points: np.array of shape (n,2) points. :param alpha: alpha value. :param only_outer: boolean value to specify if we keep only the outer border or also inner edges. :return: set of (i,j) pairs r...
e93a899a643b2a4be426a31c0dc0de27cbaea42d
3,625,963
def _botocore_resolver(): """Get the DNS suffix for the given region. Args: region (str): AWS region name Returns: str: the DNS suffix """ loader = botocore.loaders.create_loader() return botocore.regions.EndpointResolver(loader.load_data("endpoints"))
02d025b75d99daaefe1b37874be3404572ba10ed
3,625,964
def euler97(): """Solution for problem 97.""" mod = 10 ** 10 return (1 + 28433 * pow(2, 7830457, mod)) % mod
ab04cf67431a434f147f3615bee5a211b58ccbde
3,625,965
import math def getBoundaryBoxes(uint64Img): """Extracts boundary boxes from a labelled image. Args: uint64Img (1-chan uint64 numpy array): A grayscale image, which contains a specific label for each region. Returns: anchors (integer tuple list): A list which contains the anchor points...
cb50c59a877597af7d4167672e0a3006465b0a10
3,625,966
def reddening(wave, a_v, r_v=3.1, model='od94'): """Inverse of flux transmission fraction at given wavelength(s). Parameters ---------- wave : float or list_like Wavelength(s) in angstroms at which to evaluate the reddening. a_v : float Total V band extinction, in magnitudes. A(V) =...
75aed1ec5371f0ec99d97e904a173ff2cf8eb455
3,625,967
import requests import json def callJenkinsApi(jenkinsApi, jenkinsFolders): """ Call the Jenkins API and fetch the JSON response List jobs: api/json?tree=jobs[name] """ targetUrl = "" folderUrl = "" responseValue = "" # Create proper url for folders if len(jenkins...
72423664211205b5b4409a308c6821b5602d8da3
3,625,968
def frame_shift(array, shift_y, shift_x, lib='opencv', interpolation='bicubic'): """ Shifts an 2d array by shift_y, shift_x. Boundaries are filled with zeros. Parameters ---------- array : array_like Input 2d array. shift_y, shift_x: float Shifts in x and y directions. lib : {'...
bf2614c58c5be61c7697cea32c804d0a6579b892
3,625,969
import base64 import email def GetMimeMessage(service, user_id, msg_id): """Get a Message and use it to create a MIME Message. Args: service: Authorized Gmail API service instance. user_id: User's email address. The special value "me" can be used to indicate the authenticated user. msg_id: The ID...
f59c67ed90b47ec30d69f4c61ca47b656fa5ec2b
3,625,970
import string def is_palindrome_recursive(text, left=None, right=None): """ is_palindrome_recursive() checks to see if a given text is a palindrome meaning its characters flipped would be the same word from the beginning. Args: text (string) Returns: is_palindrome (bool) ...
9385b5cb468594e7eead38e18803dab1c4d4959c
3,625,971
def latex_code(size): """ Get LaTeX code for size """ return "\\" + size + " "
03478f8f62bb2b70ab5ca6ece66d4cdca3595dd6
3,625,972
def create_inner_out_logp(value_map): """Create a log-likelihood inner-output. This is intended to be use with `get_random_outer_outputs`. """ res = [] for old_inner_out_var, new_inner_in_var in value_map.items(): logp = logprob(old_inner_out_var, new_inner_in_var) if new_inner_in_...
0a448fda87f8abc2e4ad9eba4d0a45f67aa9f527
3,625,973
def GRUCell(input_size: int, hidden_size: int, bias: bool = False): """ Simple wrapper for GRUCell that handles initialization Args: input_size – The number of expected features in the input x hidden_size – The number of features in the hidden state h bias – If False, then the layer ...
ffa7b26a3f2c79efae02854839a5dcbc009c6ce5
3,625,974
def embedding(x, vocab_size, dense_size, name=None, reuse=None, multiplier=1.0, symbol_dropout_rate=0.0, embedding_var=None, dtype=tf.float32): """Embed x of type int64 into dense vectors, reducing to max 4...
0bcac81be1d314637662cd82efc6c9ae91dfe868
3,625,975
def has_cycle_visit(visiting, parents, adjacency_list, s): """ Check if there is a cycle in a graph starting at the node s """ visiting[s] = True for u in adjacency_list[s]: if u in visiting: return True if u in parents: continue parents[u] = s if has_cycle_visit(visiting, paren...
5f87f6f39d88cbae93e7e461590002ca6a94aa20
3,625,976
def _show_interactive_menu(test_session): """Display an interactive menu based on the current test session state. This will return when the user invokes one of the exit menu items. """ # A menu item for all menus, so that test_session.state is checked again refresh_test_session_state = FunctionItem...
ffcb8ebef18b7030d5d8b459c8a4f01c7f5d37a0
3,625,977
def create_lock(objects, lock_name): """Create locks for list of objects""" locks_list = list() for obj in objects: if isinstance(obj, dict): lock = distributedlock(lock_name % obj['id']) else: lock = distributedlock(lock_name % obj) lock.__enter__() ...
27cdc21e76a03e4a87845b1a34a557b536e8db66
3,625,978
import traceback import sys def verify_event_trigger_node(self): """ This function verifies the event trigger is present in the database :param self: server details :return event_trigger: event trigger's expected details :rtype event_trigger: dict """ try: connection = get_db_conne...
b762b0355cbf414260490b23bc46ff731449f8e2
3,625,979
def get_trans_func(): """ Returns the next status (modifier) based on the current status, the event on the new modifier (pressed or released) and the new modifier typed. next_status = f(event, modifier, curr_status) event can be {'press', release}; modifier is one of the possible modifier in m...
43cfb73f3cb4c5dabb43a47dcae5cfa53aa0cc1f
3,625,980
def remove_trailing_whitespace(line): """Removes trailing whitespace, but preserves the newline if present. """ if line.endswith("\n"): return "{}\n".format(remove_trailing_whitespace(line[:-1])) return line.rstrip()
2c5f7b3a35152b89cda6645911569c9d2815f47e
3,625,981
def process_settings(pelicanobj): """Sets user specified Katex settings""" katex_settings = {} katex_settings['auto_insert'] = True katex_settings['process_summary'] = True return katex_settings
9799d9ea6bf17fabd1640c4e69ca3b1da5406829
3,625,982
def install(**kwargs): """setup entry point""" return setup( name="pysachi", version=__pkginfo__["version"], packages=[ 'pysachi', 'pysachi/rules', 'pysachi/checkers' ], entry_points={'pysachi.renderers': [ "html = pysachi.r...
3df42d5aa342e08bceaa79e8e3ea206f7d7454a3
3,625,983
def total_infection_rate_60(): """ Real Name: b'total infection rate 60' Original Eqn: b'infection rate asymptomatic self 60+infection rate quarantined self 60+infection rate symptomatic self 60 +infection rate asymptomatic 80x60+infection rate symptomatic 80x60 +infection rate asymptomatic 70x60+infection ...
6a231ae069437002dfe610db654fd51c7a5d69a6
3,625,984
from typing import AnyStr from typing import Dict def get_source(source_string: AnyStr) -> Dict: """ This method finds the rss feed object based on source string :param source_string: String acting as key to find RSS feed source :return: """ source = "_".join([word.lower() for word in source_s...
7454234b864675e68d8329f71c2c14557ae136ff
3,625,985
from typing import Optional from typing import Sequence import argparse def main(argv: Optional[Sequence[str]] = None) -> int: """Main Function""" parser = argparse.ArgumentParser() parser.add_argument("filenames", nargs="*", help="Filenames to fix") parser.add_argument( "--textfiles", help="c...
302fed991988abb69c462d728fe401a936c65c87
3,625,986
import time def run_epoch(session, model, data, is_train=False, verbose=False, sv=None, epoch=None): """Runs the model on the given data.""" epoch_size = ((len(data[0]) // model.batch_size) - 1) // model.num_steps start_time = time.time() costs = 0.0 iters = 0 state = session.run(model.initial...
b146c75caf6f750b64072070fb65784107b760d6
3,625,987
def gconnect(): """Log users into their Google accounts and the Web app. Log users into Google and the Web app if their login details are correct, and their session state and server states match (indicating the no 3rd party is attempting to hi-jack the session). Create new user in the User table of...
e8ebd71de91e01435d9872a0633ba4b1f9f49dd1
3,625,988
import re def _collect_models(container, json_reference, models, swagger_spec): """ Callback used during the swagger spec ingestion to collect all the tagged models and create appropriate python types for them. NOTE: this callback creates the model python type only if the container represents a v...
3cf1898333b309642258d99e19926553d8f6a073
3,625,989
def non_usd_ois(asset: Asset, tenor: str = None, *, source: str = None, real_time: bool = False) -> Series: """ GS end-of-day non domestic USD ois rate curve for G10 cross currencies. :param asset: asset object loaded from security master :param tenor: relative date representation of expiration date e....
bb61c9f5d4ebd9dc6dc265ce4d4f1518fc60d49d
3,625,990
import networkx def make_cross(length=20, width=2) -> networkx.Graph: """Builds graph which looks like a cross. Result graph has (2*length-width)*width vertices. For example, this is a cross of width 3: ... +++ +++ ...+++++++++++... ...+++++++++++... ...+++++...
f0be683fd8971ea8b3cc0b40977a939c117e9906
3,625,991
def _send_cmd(obj_session, **kwargs): """method to send command based on the type of object """ if isinstance(obj_session, WNetwork.warrior_cli_class.WarriorCli): result, response = obj_session._send_cmd(**kwargs) elif isinstance(obj_session, pexpect.spawn): wc_obj = WNetwork.warrior_cli_cl...
dc438e42180ac406aa85c73a9c303db05e9d895d
3,625,992
def get_all_versions(appdir,include_partial_installs=False): """Get a list of all usable version directories inside the given appdir. The list will be in order from most-recent to least-recent. The head of the list will be the same directory as returned by get_best_version. """ # Find all potenti...
2e3565a9f09734794c5e33cd379359ea07651f53
3,625,993
import itertools def noise(nblock=None, state=None, color='white', ntaps=None): """Generate white noise with standard Gaussian distribution. :param nblock: Amount of samples per block. :param state: State of PRNG. :type state: :class:`np.random.RandomState` :returns: When `nblock=None`, individua...
2186639de56646ca5ef118d4821090ce660c9612
3,625,994
def euler2SO3_left(pitch, yaw, roll): """ Convert euler angles in degrees to a rotation matrix using XYZ order (valid)""" cos_pitch = np.cos(pitch*np.pi/180) sin_pitch = np.sin(pitch*np.pi/180) cos_yaw = np.cos(yaw*np.pi/180) sin_yaw = np.sin(yaw*np.pi/180) cos_roll = np.cos(roll*np.pi/180) ...
5c57836698ade9445186d88fc0009f0ea4877ed0
3,625,995
def clear_cache(query=None): """ clears cache in redis by query string :param query: :return: """ def search_key(q): def wrapper(key): if query in key: return 1 return 0 return wrapper is_low_cache_mem = False is_redise = False ...
dedb0a66d7f7ba14248bf664a29a0f79566f61ab
3,625,996
def get_pc_topk_shift(tensor, sparsity): """Input tensor must be batch of vectors. Returns a vector per batch sample of the shift required to make Hopfield converge. Assumes knowledge of Hopfield fixed sparsity.""" # Intuition: The output distribution must straddle the zero point to make hopfield work. # The...
3d4d98a36dec4294c4a0c0537794e960d690056d
3,625,997
def monthly_network_triplets_per_mno_indices(): """Index metadata for monthly_network_triplets_per_mno partitions.""" return [ IndexMetadatum(idx_cols=cols, is_unique=is_uniq, partial_sql=partial) for cols, is_uniq, partial in [ (['triplet_hash'], True, None), (['imei_nor...
72a68e586d4383b7bb6c73e30cf1b5f0e245697e
3,625,998
def print_table(input_dict, title='', header=('Key', 'Value'), style=('', '-')): """Print the dict in a table form""" assert input_dict.__class__ is dict, "Only accept class='dict'" if input_dict is None: return None max_string = 110 key_list = list(input_dict.keys()) val_list = list(ma...
47844b6526723fbf63bc347ed1487442fc497904
3,625,999