content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import argparse def parse_options(): """Parses command line options""" parser = argparse.ArgumentParser() parser.add_argument("-o", "--output", help="Output file name (e.g oui.h)") parser.add_argument("-u", "--url", help="Wireshark oui/manuf file url") opt = parser.parse_args() return opt
f01013440685506ef3bef27e6c0d79147c2b896f
3,611,800
def gettext(msg, domain='python-apt'): # real signature unknown; restored from __doc__ """ gettext(msg: str[, domain: str = 'python-apt']) -> str Translate the given string. This is much faster than Python's version and only does translations after setlocale() has been called. """ return ""
a6d83a79110ec233f86878fc6aa9f37f2b3e61fa
3,611,801
def as_sparse_or_tensor_variable(x, name=None): """ If we can't make a sparse variable, we try to make a tensor variable. """ try: return as_sparse_variable(x,name) except (ValueError, TypeError): return theano.tensor.as_tensor_variable(x,name)
4e9560dc48bd0388b376b9ee29b303850b8ad2e1
3,611,802
def freeze(slug): """ Prevent a builder from updating it's source code to a newer version. The software will still be re-built if it's dependants are upated. """ freeze_file = settings.get('install_path') + 'etc/build-freeze' return file_filter.AppendUnique(freeze_file, slug).run()
e08b0146fc5c4eafaeba689a3aaf1dff04c06192
3,611,803
def get_compressor(alg): """Return an instance of a compressor This function returns an object that can be used for data compression. """ return _cmp_compressors[alg]()
a40274f069b2fb7bf5afc05efb10b39d5cea5179
3,611,804
import json import uuid import time def confirm(self, speech, timeout): """ Start the view 'confirm' :param speech: the text that will be use by the Local Manager for tablet and vocal :type speech: dict :param timeout: maximum time to wait for a reaction from the local manager :type timeout: ...
41a1061879dc14f32a567bb4860195221385609a
3,611,805
def generateAdjMatrix(edgeJsonList, sent_len): """ Function to generate Adjacency matrix from Depedency Parse Tree """ sparseAdjMatrixPos = [[], [], []] sparseAdjMatrixValues = [] deptags = [] gov_words = [0] * sent_len adjMatrix = [0] * sent_len for i in range(sent_len): adjMa...
ca8af1991b072c334cab20c317a3cb2e00d8f67f
3,611,806
import operator def assert_no_duplicate_router_ids( snapshot=None, nodes=None, protocols=None, soft=False, session=None, df_format="table", ): # type: (Optional[str], Optional[str], Optional[List[str]], bool, Optional[Session], str) -> bool """Assert that there are no duplicate router ...
51d987ece746ea481fa39490aba364765512ce5f
3,611,807
def __find_position_for_conclusion_of_argument(current_arg, list_todos, list_dones, positions): """ :param current_arg: Argument :param list_todos: List of Arguments :param list_dones: List of Argument.uids :param positions: List of Statements - return value :return: """ a = [arg.uid fo...
39a5c5f8e517a166b2e1bcb0072633af3fe2cf93
3,611,808
from typing import Generator def de_bruijn(alphabet: bytes, n: int) -> Generator[str, None, None]: """De Bruijn sequence for alphabet and subsequences of length n (for compat. w/ pwnlib).""" k = len(alphabet) a = [0] * k * n def db(t: int, p: int) -> Generator[str, None, None]: if t > n: ...
bc647a3e140a81c47703eaa2216d49e0aa78f088
3,611,809
def writexl_alt_getsheetref(path_wbrels, path_wb): """ Takes a file path for '/xl/_rels/workbook.xml.rels' and '/xl/workbook.xml' files and returns a dictionary relationship between sheetID, name and xml worksheet file path rId: xml's indexing between files (workbook.xml.rels defined rID to xml work...
84852fc99897b471834ce3a9dc721e18b41047e1
3,611,810
import re def createPattern(string): """Cria um padrรฃo de comandos de bot.""" return re.compile(f"/{string}|{string}")
b2b013dc71d5f49f041402ecf98db8b923f4d22a
3,611,811
def miner_predictions(): """ Returns a Model Template Prediction Status screen :return: HTML Template for Model Prediction Status """ logger.debug("/predictions - remote addr:" + request.remote_addr) # render the template return render_template('predictions.html', version='0.0')
472bb06ca785f7d3bd6e019cfaa0299ce19972fa
3,611,812
def gnomad_filtered_func(raw_value): """ We use FILTER in Gnomad3 (GRCh38 only) - need to convert back to bool """ return raw_value not in (None, "PASS")
6de1d4ef9395e89c11b08cdb43decb045656494b
3,611,813
from bs4 import BeautifulSoup def parse(html_bytes: bytes, *args, **kwargs) -> BeautifulSoup: """Convenience method for ``ZimHtmlParser(html_text).simplify()``.""" return ZimHtmlParser(html_bytes, *args, **kwargs).simplify()
2b1c711a9ead749e0e8b6279e4861c29b97aa968
3,611,814
def register(name): """Registers a new logs preprocessor function under the given name.""" def add_to_dict(func): _PREPROCESSORS[name] = func return func return add_to_dict
a07008f74ea4a93a6763d1062c78d50a64d9614e
3,611,815
import os import posixpath def _gather_proto_info_from_repo(repo): """Gathers all protos from the given repo. Args: * repo (RecipeRepo) - The repo to gather all protos from. Returns List[_ProtoInfo] """ # Tuples of # * fwd-slash path relative to repo.path of where to look for protos. # * fwd-s...
3382653c66d4ddbb1895998cdb21a9da2626d7a6
3,611,816
import torch def _project_z(z, project_method='clip'): """To be used for projected gradient descent over z.""" if project_method == 'norm': z_p = torch.nn.functional.normalize(z, p=2, dim=-1) #elif project_method == 'clip': #not reimplemented yet # z_p = tf.clip_by_value(z, -1, 1) else: raise Value...
6cabb462dcbfff7ffdc065601f4a68671822f93f
3,611,817
from datetime import datetime def __dirnames_matching_format(dirnames, format): """ Iterates through dirnames and returns a sorted array of directory names that match the provided format. """ matching_dates = [] for dirname in dirnames: try: dt = datetime.strptime(dirname, ...
52349f0992a0ac0366d75f5328f674ab179246be
3,611,818
import re def solve(s): """doc""" return "".join([w.capitalize() for w in re.split(r"(\W+)", s)])
28f075dd47c3ec57d6bb2a1675ae77815378786e
3,611,819
import requests def marco_china_hk_trade_diff_ratio() -> pd.DataFrame: """ ไธœๆ–น่ดขๅฏŒ-็ปๆตŽๆ•ฐๆฎไธ€่งˆ-ไธญๅ›ฝ้ฆ™ๆธฏ-้ฆ™ๆธฏๅ•†ๅ“่ดธๆ˜“ๅทฎ้ขๅนด็އ https://data.eastmoney.com/cjsj/foreign_8_7.html :return: ้ฆ™ๆธฏๅ•†ๅ“่ดธๆ˜“ๅทฎ้ขๅนด็އ :rtype: pandas.DataFrame """ url = "https://datainterface.eastmoney.com/EM_DataCenter/JS.aspx" params = { ...
7d60526def9c00944638b80311dbbd6913a11ca2
3,611,820
from typing import Optional def make_default_sim_env( interface: Optional[GymTrainedInterface] = None, ) -> CustomSimEnv: """ A simulator environment with the following characteristics: The action and observation spaces are continuous. An action in this environment is a pilot signal for each EVSE, ...
e023dc37fc81fb8d5e17f87d66b3035e9909a3aa
3,611,821
from iris.cube import Cube from iris.coords import DimCoord def make_dummy_1d_cube(job_n=0): """ Makes a dummy 1d cube filled with dummy data. It has a scalar job coordinate to make ensemble stacking convenient """ x = np.arange(100) y = np.sin(x) * np.cos(x + 0.3) obs = DimCoord(x, var_...
992251299f13bbfa7581f647602a349b98547635
3,611,822
def edit_delivery(request, delivery): """Edit a delivery as a full network admin: act upon its lifecycle, control which subgroups have been validated, change the products characteristics, change other users' orders.""" dv = m.Delivery.objects.get(id=delivery) if dv.network.staff.filter(id=request.user.i...
7d807af78d2b063555a529a525295352513af919
3,611,823
def get_fields_by_name(model_cls, *field_names): """Return a dict of `models.Field` instances for named fields. Supports wildcard fetches using `'*'`. >>> get_fields_by_name(User, 'username', 'password') {'username': <django.db.models.fields.CharField: username>, 'password': <django.d...
8ce9c845adbff9bb53da50c7d7e208aa8077e718
3,611,824
def pyramidnet110_a84_svhn(num_classes=10, **kwargs): """ PyramidNet-110 (a=84) model for SVHN from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915. Parameters: ---------- num_classes : int, default 10 Number of classification classes. pretrained : bool, default Fal...
085571ae5ab102de5e1bdeab100d6244608f899a
3,611,825
def list_of_comments(fname) : """Returns list of str objects - comment records from file. - fname - file name for text file. """ #if not os.path.lexists(fname) : raise IOError('File %s is not available' % fname) f=open(fname,'r') cmts = [] for rec in f : if rec.isspace() : conti...
5aea0668c006b4a4615cab01acd07db8dc1fb2b5
3,611,826
def publish_branch(branch): """Publishes given branch.""" repo_check() return repo.git.execute([git, 'push', '-u', remote.name, branch])
7335704d94efdc5dfba65dab914ab75a70bc24d9
3,611,827
import base64 def pil_to_base64(pilimage): # pragma: no cover """Returns base64 encoded image given a PIL Image""" buffer = BytesIO() pilimage.save(buffer, "png") return base64.b64encode(buffer.getvalue()).decode()
9c2673b97a86544c5281cbd43ff6dfdad31a4253
3,611,828
def save_result(x,time,lev,copy_from_source,dflt_units='k'): """Saves results from projection in netcdf output format. Input parameters: x: projection indices (2dim array with time,mode) time: coordinates from input netcdf file lev: level coordinates (PCA modes) copy_from_s...
704eb922bf8ccb4f8669df5ee0cf6b134ed4b55c
3,611,829
import os def pick_a_filename(i): """ Input: { (directory) - the directory name from which to pick a filename (defaults to '.' - current directory) (file_suffix) - the file type (defaults to '' - none) } Output: { return ...
1054e93bb0b7d747eec32e7e1fee868bdfe41ed5
3,611,830
def linkcode_resolve(domain, info, author, package): """Determine the URL corresponding to a Python object.""" try: module = import_module(info["module"]) except ModuleNotFoundError: # No URL is returned when the object is not in # any module, or the module cannot be imported ...
ec849260610890510f0686ab4b1150eb30efe99c
3,611,831
def _max(self, dim=None, keepdim=False): """Map of 'max' pytorch method.""" x = self dim_orig = dim if dim is None: dim = _build_fwd_tuple(x.shape) elif isinstance(dim, int): dim = (dim,) dim = _dim_tuple_explicit(x.shape, dim) ret_max = P.array_max(x, dim) ret_argmax =...
ecf96de331d24b0b692c12fa24269fb9863121bb
3,611,832
import os def main(list_packed_vars): """ Model simulation Parameters ---------- list_packed_vars : list list of packed variables that enable the use of parallels Returns ------- netcdf files of the simulation output (specific output is dependent on the output option) """...
56a7ab91c39883eadaf9dfe3ffe6dbe440731fd3
3,611,833
import re def minify(source): """ Removes comments from the source code """ multiline = re.compile("(/\*.*?\*/)", re.DOTALL) singleline = re.compile("//.*?\n") remove_multiline = lambda f: re.sub(multiline, "", f) remove_singleline = lambda f: re.sub(singleline, "", f) return map(remove_multiline, ...
3743e4071485d1ae085037a4bf4cd492f4f81d29
3,611,834
def configmap_data_keys(): """ Build keys for the ``data`` mapping of a ``ConfigMap``. """ return builds( lambda labels, dot: dot + u".".join(labels), labels=lists(object_name(), average_size=2, min_size=1, max_size=253//2), dot=sampled_from([u"", u"."]), ).filter( la...
4c88839707f37cfb334f6bedce080b4f97a84c58
3,611,835
from typing import Callable from typing import Any def handler_assertions( handler_name: str, test_case: str, error_name: str = None, ) -> Callable: """Configurable decorator for testing assertions for a given handler""" def decorator_function( decorated_function: Callable...
7abb8776e029c330c0ad4b060bdf8e0c1ea3af35
3,611,836
import random def create_bitmap_dataset(bitmap_data, output_dir, output_name, classnames, output_shards): """ Writes the provided bitmap_data as tf.Example in tf.Record :param bitmap_data: tuple of lists containing (x_train, y_train, x_test, y_test) :param output_dir: path where to write the outp...
050fe1ed5a66cf49741d24e21062fadba08a0c7c
3,611,837
import logging def with_logger(cls): """Class decorator to add a logger to a class.""" attr_name = '_logger' cls_name = cls.__qualname__ module = cls.__module__ if module is not None: cls_name = module + '.' + cls_name else: raise AssertionError setattr(cls, attr_name, logg...
77f854ac6d1cbe95ff7804184a1a67a513ac81ae
3,611,838
import itertools def _generate_mesh_simplices( *, limits, mesh_size, periodic=False, skip_origin=False ): """ Generate the starting simplices for given limits and mesh size. """ dim = len(limits) if len(mesh_size) != dim: raise ValueError( "Inconsistent dimensions: ...
7b2008906aaafb411c22128ffcdd4f2ce1c13471
3,611,839
def write_tfrecords(data_path,video_paths,action_labels, n_vids_per_batch,subset, n_frames_batch = 16, n_frames_chunk = 512): """Function to write tfrecords. :param data_path: name of tfrecords file to write :param video_paths: list contain...
4c6e27a2cc9a2079a8f2828d288ea65542b8e56a
3,611,840
def _set_up_thermo_mets(base_df: pd.DataFrame, mets_list: list, mets_conc_df: pd.DataFrame) -> tuple: """ Given the base excel input file, the list of metabolites in the model and a dataframe with metabolite concentrations averages and respective stdev, fills in the thermoMets sheet. First fills in conc...
c048a6c220de7055f5cb5ce0a65f969b3d0a9be7
3,611,841
def setup_constant(prefix, **kwargs): """ Set up a simple constant function model. :param prefix: Model prefix :type prefix: string :param kwargs: Keyword arguments :return: LMFIT model and parameters :rtype: (lmfit.Model, lmfit.Parameters) """ amplitude = kwargs.pop('amplitude', 5) ...
3d0c24887e81c34b499190a79185822fef641bd8
3,611,842
def subapp_css_static(filename): """ set css files. :param filename: css file name. :return: static path. """ return static_file(filename, root='kokemomo/plugins/subapp/view/resource/css')
bf29bc7a7f9cbab9e2db3da0841eab018c57d96b
3,611,843
def graph1D(n: int, pbc: bool = True) -> Graph: """ 1D PBC chain with n sites :param n: :return: """ g = nx.Graph() for i in range(n): g.add_node(i) for i in range(n - 1): g.add_edge(i, i + 1, weight=1.0) if pbc is True: g.add_edge(n - 1, 0, weight=1.0) ...
fdb809ee46c7b9d7ebdd241175e199db747f9227
3,611,844
def _solve_triangular_right(a, b, left_side, lower, trans_a): """An unrolled right-looking triangular solve on (blocked) LapaxMatrices.""" n = a.shape[-1] def solve(a, b): return _solve_triangular_left(a, b, left_side, lower, trans_a) if n == 1: return solve(a.bview(1), b.bview(1)) out = full_like(...
1dc6826bfb717a8b162bd2a5d997368276ae0b47
3,611,845
from numpy import linspace, meshgrid def _get_latlons(nlat, nlon): """Short summary. Parameters ---------- nlat : type Description of parameter `nlat`. nlon : type Description of parameter `nlon`. Returns ------- type Description of returned object. """ ...
f43553b4f758ac2a060f609e2781645b79466cb4
3,611,846
def abs(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.abs <numpy.abs>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in abs") return Array._new(np.abs(x._array))
cb37d3486fd82535de77f4df56a30c7e713127b9
3,611,847
def challenge_hash(peer_challenge, auth_challenge, user_name): """ RFC 2759 section 8.2 ChallengeHash :param peer_challenge: :param auth_challenge: :param user_name: :return: challenge example peer_challenge = "\x21\x40\x23\x24\x25\x5E\x26\x2A\x28\x29\x5F\x2B\x3A\x33\x7C\x7E" ...
153f33509e09ea140433d6ef46aab2225bbb5808
3,611,848
def var_historic(r, level=5): """ Returns the historic Value at Risk at a specified level i.e. returns the number such that "level" percent of the returns fall below that number, and the (100-level) percent are above """ if isinstance(r, pd.DataFrame): return r.aggregate(var_historic, le...
dd2b23c15b7aee470886621ba8d64bee571488f9
3,611,849
from typing import Dict def convert_to_km(distance: float, print_output: bool = True) -> Dict[str, float]: """Convert a miles distance into the double of km. Args: distance: a distance (in miles). print_output: if True, prints the progress. Returns: A dictionary with two keys ('o...
1fb9dbbeb890a348d0feeebaea1a308bc06b039d
3,611,850
import torch def discriminator_loss(D, real_images, fake_images): """Loss computed to train the GAN discriminator. Args: D: The discriminator. real_images of shape (batch_size, nc, 28, 28): Real images. fake_images of shape (batch_size, nc, 28, 28): Fake images produces by the generator. ...
397c1cd3c4ad8f90e78f4d2d0eb0501093133735
3,611,851
def Lucas_chain(n, f, g, x_0, x_1): """ Given an integer n, two functions f and g, and initial value (x_0, x_1), compute (x_n, x_{n+1}), where the sequence {x_i} is defined as: x_{2i} = f(x_i) x_{2i+1} = g(x_i, x_{i+1}) """ binary = arith1.expand(n, 2) u = x_0 v = x_1 while b...
514d9977434cbc5538d97e9622ea6c983a0bf604
3,611,852
import itertools def build_input_from_segments( history, reply, tokenizer, lm_labels=False, with_eos=True ): """ Build a sequence of input from 2 segments: history and candidate reply. """ bos, eos, speaker1, speaker2 = tokenizer.convert_tokens_to_ids(SPECIAL_TOKENS[:-1]) # build input sequence as: ...
1ab5a269a253e8042c920f8c74990923fee7ad3d
3,611,853
import aiohttp def aiohttp_socket_timeout(socket_timeout_s): """ Return a aiohttp.ClientTimeout object with only socket timeouts set. """ return aiohttp.ClientTimeout(total=None, connect=None, sock_connect=socket_timeout_s, ...
c17a40a532aee15557b4e507439b0a7b2e98989e
3,611,854
import json from datetime import datetime def get_contributions_from_file(site, username): """Get a list of Wikipedia-namespace contributions.""" with open("my-contribs.json") as my_contribs_file: data = json.load(my_contribs_file) for contrib in data: time = datetime.datetime.strp...
f4458c4882beadca212560f30da4d12b49d811e6
3,611,855
def alignment_to_search_path(algn): """ Given an alignment, make searchpath. Searchpath must step exactly one position in x XOR y at each time step. In the case of a block of deletions, the order found by DP is not meaningful. To make things consistent and to improve the probability of recoveri...
c5daa5c1bd9045527f588c8ca856f69b5d52838f
3,611,856
def getMulitples(indices): """Return a subset with no multiples (filters out the bad ones).""" multiples = [] added = [] for i in range(0, len(indices) - 1): if indices[i][0] == indices[i + 1][0]: added.append(indices[i]) elif added: added.append(indices[i]) ...
4846fe1950f7d1a5379595b93e18c3ed0eb2d160
3,611,857
def get_pourbaix_info(entry: dict) -> dict: """ Grabs the relevant pourbaix entries for a given mpid from Materials Project and constructs a pourbaix diagram for it. This currently only supports MP materials. Args: entry: bulk structure entry as constructed by catlas.load_bulk_st...
c53cb58af64a3b63909e56706dfee1d933db20da
3,611,858
def do_math(a, b, operator): """Helper function that performs computation between two numbers.""" if operator == "+": return int(b) + int(a) elif operator == "-": return int(b) - int(a) elif operator == "*": return int(b) * int(a) elif operator == "/": return int(b)...
5bffd1db1659c9f3420cc66a28525698de3beef5
3,611,859
def getFrequencyBands(sessionId): """ Get the frequency bands supported by this server. Returns: A list of frequency bands for the sensors managed by this server. """ @testcase def getFrequencyBandsWorker(sessionId): try: if not Config.isConfigured(): util.de...
904ee2c0ad5a35ae5acd66b96edc0737b2687db4
3,611,860
def deg_to_arcsec(angle: float) -> float: """ Convert degrees to arcseconds. Args: angle: Angle in units of degrees. Returns: angle: Angle in units of arcseconds. """ return float(angle) * 3600.
02fd099627970116bf5513af8b8d2d62bdc8ed41
3,611,861
def pixel_level_peak_finder_1d(correlation_lines: np.ndarray) -> np.ndarray: """ This function returns a numpy array containing the location of the maximum surface value to pixel level accuracy for each row of the input matrix. :return: The location of the maximum surface values to pixel level accuracy...
6afa9b3a9e565aeab9915e7c8b5699df0842d498
3,611,862
def Shift(**kwargs): """ Calculates register shifts between strands based on their pairing and length """ refbluefile = kwargs.get('refblue') seg1 = kwargs.get('seg1') seg2 = kwargs.get('seg2') refblue = Blueprint(refbluefile) nseg1 = len( refblue.segment_...
b0a377131df521e3d96790a0b6f9d1e2d1893a64
3,611,863
import time import os def ul_lands_download(save_dir = None): """ Downloads las files from University Lands Texas This function downloads files from the university lands ftp website located at publiftp.utlands.utsystem.edu. It inventories readable logs into a csv file containing header data in t...
912b9f75d0c4a93581d942b47f62fed2fa154765
3,611,864
async def test_ap_fails(injector): """Async providers must not be usable in sync consumers""" class A: pass a = A() @injector.consumer def consumer(a_: A): assert a_ is a @injector.provider async def bean() -> A: return a with pytest.raises(pyserp.InjectionErr...
f9cb09ec0a5c8246b1ed65c5f388a8904d4e60d4
3,611,865
def gru_run(params, x_t): """Run the Vanilla RNN T steps, where T is shape[0] of input. Args: params: dict of GRU parameters x_t: np array of inputs with dim ntime x u Returns: 2-tuple of np arrays (hidden states w dim ntime x n, outputs w dim ntim x o) """ return gru_run_with_h0(params, x_...
294dbd3e56d1a8ea337c03bd99b15443b6a908f5
3,611,866
def set_window_width(image, MIN_BOUND=-1000.0, MAX_BOUND=400.0): """่ฎพ็ฝฎ็ช—ๅฎฝ""" image[image > MAX_BOUND] = MAX_BOUND image[image < MIN_BOUND] = MIN_BOUND return image
0dfa6e858c74cacc2cc8724d33f9b7fd96835d0c
3,611,867
def _process_merge(p1_ctx, p2_ctx, ctx): """compute the appropriate changed files for a changeset with two parents This is a more advance case. The information we need to record is summarise in the following table: โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ diff...
8c3fedad5578c37eccf35a7fdd844ab3c244d57c
3,611,868
def create_mmt_encoder_inputs(data_cfg: cfg.DataConfig): """Creates inputs for `MmtEncoder`.""" patch_embedding_size = (data_cfg.patch_size ** 2) * 3 num_patch_per_row = data_cfg.image_size // data_cfg.patch_size num_patches = num_patch_per_row ** 2 max_seq_len = data_cfg.max_seq_len word_ids = tf.keras....
1ccbe6468e25cccd32049dd65300426819d9737a
3,611,869
import json def update_chart_info(_figure, chart_data_json_str): """ A callback function to set the sample count for the number of samples that have been displayed on the chart. Args: _figure (object): A figure object for a dash-core-components Graph for the strip chart - triggers...
fd28e28b7b48131bb56d6d9f29e4fe438b33bb7a
3,611,870
def record_copy_all(node, **kwargs): """ A default rcd implementation that copies all kwargs to the tape. the impl is used for the vjp and vjp primitives. the impl is can be used for the apl primitives if no rcd is given; but we use 'record_copy_autodiff' to save a much smaller subset ...
e7e957c1d9fb0cc36bf54c1ab431ba4c7892838c
3,611,871
from typing import Tuple def split_df_train_test(data: pd.DataFrame, perc_train: float) -> Tuple[list, list]: """Create train test split""" # get percentages assert perc_train >= 0.0 assert perc_train <= 1.0 # get number of examples to use for training num_train = int(perc_train * len(data)) ...
48a5de60273189e56969ab87588d236074d50de1
3,611,872
def read_file(filename): """ Return the content of a file as a list of strings, each corresponding to a line :param filename: string: location and name of the file :return: content of filename """ with open(filename, 'r') as ofile: content = ofile.read().splitlines() return content
58a2718265fef848e484178e407aee6f7017a52a
3,611,873
def parse_record(raw_record): """Parses a record containing a training example of an image. The input record is parsed into a label and image, and the image is passed through preprocessing steps (cropping, flipping, and so on). Args: raw_record: scalar Tensor tf.string containing a serialized ...
2f669bda6cec630e4fd81576532a96f1ec6d6a00
3,611,874
def helicsFederateRegisterGlobalTypeInput(fed: HelicsFederate, name: str, type: str, units: str) -> HelicsInput: """ Register a global publication with an arbitrary type. The publication becomes part of the federate and is destroyed when the federate is freed so there are no separate free functions for subs...
487179f3de8d9f72efaa696e50441250e49f5438
3,611,875
from typing import Optional from typing import Mapping def get_cluster(cluster_identifier: Optional[str] = None, tags: Optional[Mapping[str, str]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetClusterResult: """ Provides details about a specific redshift c...
bd5ca8151d0fafbeef735707b1971c03f05ec9e8
3,611,876
def translate_to_origin(structure, weight="mass", atom_mask=None, dimension=None): """Translate a structure to the origin based on the centroid of the whole system or a subset of atom(s). Parameters ---------- structure : str or :class:`parmed.Structure` Molecular structure containing coordinat...
269f566e4fbf43308bf4db8b2972adc3487fcde9
3,611,877
def score_1(game, player): # 82.14% """ Heuristics computing score using #player moves - k * #opponent moves :param game: game :param player: player :return: score """ if game.is_winner(player) or game.is_loser(player): return game.utility(player) opponent = game.get_opponent(p...
3995237f5d5474660c752c308e1077aad1743d06
3,611,878
def parse_line( line ): """Returns data located in the line.""" tokens = line.split() return int(tokens[1]), tokens[2], ( int(tokens[4]), # n_i int(tokens[6]), # s_i )
487421bcc50e4d542227e54a1362008a8a678b5b
3,611,879
def find_ancestors(starting_resource, full_name): """Find the ancestors for a given resource. Take advantage of the full name from the data model which has the entire hierarchy. Keeping this outside of the class, because the class is mocked out during testing. Args: starting_resource ...
e307c902422077405eb79171d6abc9038724f03b
3,611,880
import random def select_from_existing_derivations(): """ Which derivation does the user want to review? Alternatively, the user can generate a PDF >>> select_from_existing_derivations() """ trace_id = str(random.randint(1000000, 9999999)) logger.info("[trace page start " + trace_id + "]"...
ab6f18277f076d13141b5b7bacf5071510f7a26a
3,611,881
import asyncio async def is_streamable(filename: str) -> bool: """Return if a file is streamable by pyatv. This method will return if the file format of the given file is supported and streamable by pyatv. It will never raise an exception, e.g. because the file is missing or lack of permissions. ...
f924ed95b18c04cb9f9247fecaa92f903a0663cf
3,611,882
def forward_pass(x: np.ndarray, weights: np.ndarray, bias: float) -> np.ndarray: """ Method that calculates the activation of the sigmoid function from a given input, weights and biases. :param x: input data :param weights: tuple with the weights :param bias: value of the biases :return: ac...
2ae788aebe921f743cfa9379d1ea496b1b9881f5
3,611,883
def get_long_description(): """ Provides the long description. """ with open("README.rst", "r", encoding="utf-8") as file_stream: return file_stream.read()
35e8b7d1c4db25e1cf49328d4be1d1d2f9ddf581
3,611,884
def get_connections(ccs_path): """ Returns list of installed connection names. Searches "<ccs_path>/ccs_base/common/targetdb/connections" directory for installed connection names. Args: ccs_path (str): full path to ccs installation to use Returns: list: connection names Raise...
73bc6f875c61f792d746687277fe1a29c04539ac
3,611,885
def escape_latex(strng): """Consistently escape LaTeX special characters for _repr_latex_ in IPython Implementation taken from the IPython magic `format_latex` Examples -------- escape_latex('disease_rate') # 'disease\_rate' Parameters ---------- strng : str string to esc...
50958dc7c736b6c3b7fb3d4c2715fcd2e1855205
3,611,886
import json def list_subnets(sort_by='name'): """ Get list of subnets from maas server CLI Example: .. code-block:: bash salt 'maas-node' maasng.list_subnets """ subnets = {} maas = _create_maas_client() json_res = json.loads(maas.get(u'api/2.0/subnets/').read()) for ite...
313d917f6938ecd5ed3a9288fe3116493f128f7a
3,611,887
import os def stream_profile_sample(self, stream_data): # FileData object """Profiles a stream container: look at it as one big blob""" tracks = {} stream_data.crc32 = 0x0 # start value crc meta_length = 0 stream_data.crc32 = calc_crc32(stream_data.name) # do track stuff track = TrackData() track.track_nu...
048e17beb3ec82fb2aeca76b9a3fbd47d5812451
3,611,888
def multinomial_as_basic(multinomial, *symbols): """ Converts the multinomial to Add/Mul/Pow instances. multinomial is a dict of {powers: coefficient} pairs, powers is a tuple of python integers, coefficient is a python integer. """ l = [] for powers, k in multinomial.iteritems(): t...
0d481de0c572966b6fa99073173dc0cbef241fb7
3,611,889
from typing import List from typing import Tuple from typing import Any import joblib def topic_modelling(all_data_t: List[List[float]], tfidf: TfidfVectorizer, n_keywords: int, param_grid=TRAIN_PARAM_GRID_LDA, retrain=False, plot=False, ...
04a5d3f775bb9bc01f8815ba2d842edbbe43c597
3,611,890
from typing import List def get_gpu_memory() -> List[int]: """Query GPU's for amount of VRAM Modified from: https://stackoverflow.com/questions/59567226/how-to-programmatically-determine-available-gpu-memory-with-tensorflow Returns ------- VRAM, List[int] Total GPU VRAM in bits for ea...
facfe363c38b0d9d55b824fd48e79fb44b888ae2
3,611,891
import base64 def smiles2inchi(smiles): """ Converts SMILES to InChi. This method accepts urlsafe_base64 encoded string containing single or multiple SMILES optionally containing header line, specific to *.smi format. cURL examples: curl -X GET ${BEAKER_ROOT_URL}smiles2inchi/$(cat aspirin_with_header.smi | b...
b4bf76ba132d7f52fe5be503ec72ed5149e0a859
3,611,892
from typing import Dict from typing import Tuple def list_vaults_command(client: Client, args: Dict) -> Tuple[str, Dict, Dict]: """Lists all vaults. """ max_results = int(args.get('max_results', 0)) raw_response = client.list_vaults(max_results) vaults = raw_response.get('vault') if vaults: ...
9e8760eca79e94f0ad52a94aa205531592074b84
3,611,893
def strip_ddp_state_dict(state_dict): """ Workaround the fact that DistributedDataParallel prepends 'module.' to every key, but the sampler models will not be wrapped in DistributedDataParallel. (Solution from PyTorch forums.)""" clean_state_dict = type(state_dict)() for k, v in state_dict.items(): ...
f4cd6917db3df384e70c6b54dc4142dd760dd1d2
3,611,894
def parameter_attention(x, total_key_depth, total_value_depth, output_depth, memory_rows, num_heads, dropout_rate, name=None): """Attention over param...
199c0d205913a480ee67fce53030ab7d27c45df3
3,611,895
def plot_gp_plotly( model: GPModel, mins: TensorType, maxs: TensorType, grid_density=20 ) -> go.Figure: """ Plots 2-dimensional plot of a GP model's predictions with mean and 2 standard deviations. :param model: a gpflow model :param mins: list of 2 lower bounds :param maxs: list of 2 upper bou...
42203278f142dbfc30e00df21a2bbc3212e34f64
3,611,896
def pareto(all_y, maximize=False): """ Returns the indices of Pareto-optimal solutions. Args: Y [list]: A list of lists containing values to be evaluated for Pareto- optimality Returns: list - The indices of the entries which are Pareto-optimal """ all_y = np.asarra...
02985b54638d90b1ffc0026ff779ddbfaad77ebc
3,611,897
def _import(module_name, class_name): """ Return class of the module_name, where module_name is of the form package.module (testoob's Asserter, which does simple __import__, returns package, not package.module in this situation). """ mod = __import__(module_name) components = module_name.spl...
27a20935b305e3c387c861392429794976d7d866
3,611,898
def plot_roc(labels, score, title='ROC', verbose=True): """Plot ROC curve Parameters ---------- labels : np.ndarray vector of ground truth score : np.ndarray vector of scores assigned by classifier (i.e. clf.pred_proba(...)[-1] in sklearn) title : str title of p...
4b395988249e10fee803201997140debe3314739
3,611,899