content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def is_abs_blank(str): """ To check out whether str is NONE or empty or blank. """ return not is_not_abs_blank(str)
f308b5c472a435a2d913d40213b247af304abc84
3,613,247
def get_vnf_package_data(vnf_package_obj, **kwargs): """Get the vnf package data from a FakeVnfPackage dict object. :param vnf_package_obj: A FakeVnfPackage dict object :return: A list which may include the following values: [{'packageContent': {'href': 'string'}, 'self': {'href': '...
7c95c8ac7885f3f468d599e6ff58597ec6bd80dd
3,613,248
def get_latest_pip_command() -> lib_bash.BashCommand: """ >>> assert get_latest_pip_command() is not None >>> assert 'pip' in get_latest_pip_command().command_string """ try: pip_command = lib_bash.get_bash_command('pip3') return pip_command except ValueError: pass ...
ee41c577725b8dfa05dbffe5dc6f663021990cd9
3,613,249
def desympify_homfly(p): """Takes a sympy HOMFLY polynomial p, and returns a tuple of (coefficient, index_a, index_z) tuples. """ if p == 1: return (1, ) p = p.expand() terms = p.as_terms()[0] coeffs = n.zeros((len(terms), 3), dtype=int) for i in range(len(terms)): entry ...
4ece442195ac11288153bffd4e97231fecb9f136
3,613,250
def triples_from_centre(k): """ Gets all the triples k positions from the centre :param k: The distance from the center. :return: A set of all the triples from the centre. """ return all_triples(neighbours_from_centre(k))
84592182ba2b197566e8c40142614bb9d5aea761
3,613,252
def _minmaxhash_add_ngrams( heap: list, heapmap: dict, maxsize: int, nsize: int, subs, nsubs: int, hashbuffer, heaptop, extracthash, make_elt, update_elt, replace, anynew, minmax_op) -> int: """ Process/add elements to the sketch (See warning below). ...
0a9000ab3f151c0c6621532930aa9c26fe3cdda8
3,613,253
def load_data(labels_fl, test_size=None): """ Load and split the data into training and testing sets. :param labels_fl: directory of the labels (measurement logs) CSV file :param test_size: size of the testing set :return: training and testing input and output sets if a test_size parameter is prov...
facd2a3ea47abb3a6b5e4e69831c044e687291e9
3,613,254
def stream_name_to_dict(stream_name, separator='-'): """Transform stream name string to dictionary""" catalog_name = None schema_name = None table_name = stream_name # Schema and table name can be derived from stream if it's in <schema_nama>-<table_name> format s_parts = stream_name.split(separ...
389826fe03f1f5e1c704e2ce54f90da443e1d23c
3,613,255
from typing import Union from typing import List from typing import Any from typing import Dict from typing import Optional def run_value_search_from_example( inputs: Union[List[Any], Dict[Text, Any]], output: Any, settings: Optional[settings_module.Settings] = None, **kwargs) -> ValueSearchResults: ...
13d90d6f22a188e8422fdba5aee47608234744af
3,613,256
import stat def compress(filename, output_filename=None, img_width=2048, img_format='png'): """Compress images in IPython notebooks. Parameters ---------- filename : string Notebook to compress. Will take any notebook format. output_filename : string If you do not want to overwrit...
1c6cd34271e69ae136c8a6521a7485bf730f55d6
3,613,257
def top_prior(name, z_shape, learn_prior="normal", temperature=1.0): """Unconditional prior distribution. Args: name: variable scope z_shape: Shape of the mean / scale of the prior distribution. learn_prior: Possible options are "normal" and "single_conv". If set to "single_conv", the g...
4dc849c8fb605f64f4f329d722d3a95933c8d23e
3,613,258
def create_label(text = ""): """ Create a Label. :param text: Label Text :return: QTWidget Label """ label = QLabel(text) return label
98fa4817ad7f76e2f5c77b808f7f58a75bbfd6a2
3,613,259
import time def create_short_timestamp_uuid(): """ Generate short uuid plus timestamp """ short_uuid = create_short_uuid() return "{}{}".format(short_uuid, time.time())
fae722699c2f8c2e05deb32524f38aeb6845362e
3,613,261
def batch_action_list_assign_election_to_rows_process_view(request): """ :param request: :return: """ # admin, analytics_admin, partner_organization, political_data_manager, political_data_viewer, verified_volunteer authority_required = {'verified_volunteer'} if not voter_has_authority(requ...
0d74313a273dedc08c5c9925a5ec8986b8fc10eb
3,613,262
from typing import Union from typing import Optional import typing def best_partition(G: Union[nx.DiGraph, nx.Graph], starting_alpha: Optional[float] = 0.1, threshold_function: Optional[ typing.Callable] = np.mean, cluster_function: Optional[typing.Callable] = None, weight: Optional[str] = "wei...
ce4886490e1ee3c11b0f1cdd446be8d05f2eab82
3,613,263
import signal import time import json import textwrap def process_nick_list(nicks, platforms=None, rutaDescarga="./", avoidProcessing=True, avoidDownload=True, nThreads=12, verbosity=1, logFolder="./logs"): """ Process a list of nicks to check whether they exist. This method receives as a parameter a ser...
0af2ee1190b3b46dbf3742082b44d1b290941305
3,613,264
import copy def make_hash(o): """ Makes a hash from a dictionary, list, tuple or set to any level, that contains only other hashable types (including any lists, tuples, sets, and dictionaries). https://stackoverflow.com/questions/5884066/hashing-a-dictionary """ if isinstance(o, (set, tupl...
93b32d35f8c23886ae0cf0bae7cd3427ffc54599
3,613,265
def uivec4(x, y, z, w): """returns an ivec4-compatible numpy array""" return np.array([x, y, z, w], dtype=np.uint32)
783a316f883a07dfafca75d0743f1483e6b7489a
3,613,266
def compute_spectral_wcut(A, w=None, K=2, max_iter=50): """ Solves weighted ratio cut as a relaxed trace maximization problem with Yu and Shi postprocessing.""" N = A.shape[0] if w is None: w = np.ones(N) L = np.diag(np.sum(A, axis=1)) - A # Solve eigenvalue problem w_inv_sqrt = w ** (-...
65542b3acfb96b4c09ddc4a9490d680d31ca2a7a
3,613,267
def relpath(target, base=os.curdir): """ Return a relative path to the target from either the current dir or an optional base dir. Base can be a directory specified either as absolute or relative to current dir. """ if not os.path.exists(target): raise OSError, 'Target does not exist: '+tar...
73df64bd8e6f7b52a6b9ec9c3e6bf3e5afff89ba
3,613,268
def mock(connectable, replace_new_patch_aliases=None): """Creates a mock selector that can be patched. This is intended to be used as a context manager with a given SQLAlchemy connectable (e.g. an engine, session, connection, etc). For example:: with pgmock.mock(engine) as mocker: mock...
4320901a2c36eca2c331298aabee94ca18a8d2af
3,613,269
def map_statements(stmts, source, outfile=None): """Tabulate valid, invalid, and mapped sites from a set of Statements.""" # Look for errors in database statements sm = SiteMapper(default_site_map) valid_stmts, mapped_stmts = sm.map_sites(stmts) # Collect stats from SiteMapper itself sites = [] ...
1106bd3c545e5447fe24b3bc17462936e71849f0
3,613,271
def getCriterion(): """Criterion (Loss function) for training and validation""" def loss_func(output, target, batch_size): output_for_loss = output.view(-1, output.size(2)) # seq_len * N, ntokens target_for_loss = target.view(-1) # seq_len * N loss = F.cross_entropy(output_for_loss, targ...
feb9ee8f8de675cadb793cfe75d5d732f2ead609
3,613,272
import struct def parse_variable_array(buf, lenbytes): """ Parse an array described using the 'Type name<x..y>' syntax from the spec Read a length at the start of buf, and returns that many bytes after, in a tuple with the TOTAL bytes consumed (including the size). This does not check that the arr...
b9c0f27975f852bb92634244eaba4762031d2ce3
3,613,273
def snake_split(s): """ Split a string into words list using snake_case rules. """ s = s.strip().replace(" ", "") return s.split("_")
af70dfa1190ec783b8431630be2ae92434af146a
3,613,275
def task_estimates(iterations=None): """Discrete task iteration converted to array""" task_iteration_list = [] for _ in range(iterations): r_float = random_float() min_val, max_val, a_val, b_val = 24, 90, 2, 4 beta_value = beta_values( random_number=r_float, ...
2e96596957628ee60507c44558ffc981d5bfa513
3,613,276
from typing import Tuple from typing import Optional def subroutine_definition(line: str) -> Tuple[bool, Optional[list]]: """ Indicates whether a line in the program is the first line of a subroutine definition and extracts subroutine name and the arguments. Args: line Returns: (Tr...
a6d62db40631cf31ba315c76e39a8f13e3e2a8c5
3,613,277
import decimal from typing import Iterable def try_parse(text, valid_types=None): """try to parse a text string as a number. Returns (valid, value) where valid represents whether the conversion was successful, and value is the result of the conversion, or None if failed. Accepts a string, and one opt...
c210a88c86b55404cf620f504da7e229a033eeed
3,613,278
import time def throttle(wait): """Second order decorator for rate-limiting a function within an asyncio concurrent app - The first call will always happen *without* delay. - Subsequent calls, within wait seconds, are dropped, even if argurments differ. - The final call will always execute, sometimes...
272c638a836bf8892f2cbcad63e57c1ad80fff56
3,613,279
import warnings def plot_tsne( arrays, legends, filename=None, use_umap=False, **kwargs ): """ Plot tSNE and return the figure. Parameters: arrays (List of ndarray): Vectors to be plotted. Each array will be colored and named differently. legends (List of s...
84b51b897640e7e2d4ee84485dfb931ac3f5fd12
3,613,280
def find_from(board, word, y, x, seen): """Can we find a word on board, starting at x, y?""" # This is called recursively to find smaller and smaller words # until all tries are exhausted or until success. # Base case: this isn't the letter we're looking for. if board[y][x] != word[0]: pr...
0e1911f90dd4eb4729d7e896e62bdc2b70ff8ee9
3,613,281
def hello(): """ Basic hello world route to check if server is running. """ return "Welcome to Codenames."
0b12cc94bc266485199c9737d2cc016c8b4da8fd
3,613,282
from typing import List def partition_labels(S: str) -> List[int]: """ consumed: 68ms 64ms :param S: :return: >>> partition_labels('ababcbacadefegdehijhklij') [9, 7, 8] >>> partition_labels('eccbbbbdec') [10] """ first_index: int = 0 res = [] while first_index < len(S):...
cdc1154ce54116edcc7df52ee97727964289b891
3,613,285
from typing import List def orderings2() -> List[List[int]]: """Enumerates the storage orderings an input with rank 2.""" return [[0, 1], [1, 0]]
f85f26b79aa25d980877e57cbcdbdb9f7295ac7d
3,613,286
def building_2d_to_3d(citygml_writer, zone_shp_path, district_shp_path, tin_occface_list, height_col, nfloor_col): """ This script extrudes buildings from the shapefile and creates intermediate floors. :param citygml_writer: the cityGML object to which the buildings are gonna be created. ...
9ab4580431610632647d0f21c759de196bbb5225
3,613,287
def get_sloc_lines(path): """Determine the lines in file `path` that are source code. i.e. Not space or comments. This requires a parser for this file type, which exists for most source code files in the Pygment module. Returns: If a Pygment lexer can be found for file `path` ...
b85f923556b071cfb2bf25a28ec76830d31c2eed
3,613,288
from typing import OrderedDict def alpha_canonicalize(equation): """Alpha convert an equation in an order-independent canonical way. Examples -------- >>> oe.parser.alpha_canonicalize("dcba") 'abcd' >>> oe.parser.alpha_canonicalize("Ĥěļļö") 'abccd' """ rename = OrderedDict() ...
b374d3ea508aa010160fd4a59b549b68d7870fa1
3,613,289
def get_raster_records(host=config.PYCSW_URL, params=config.PYCSW_GET_RECORD_PARAMS): """ This function will return all records of raster's data :param host: pycsw server's entrypoiny url :param params: request parameters for GetRecords API request with json result :return: Dict -> list of records -...
f13a21d1be84dadd032d0d5898e966846d3e69df
3,613,290
def read_file(filepath): """Reads text file and returns each line as a list element. Parameters: filepath (str): path to file Returns list: list of strings """ data = [] with open(filepath, 'r', encoding='utf-8') as file_obj: for line in file_obj.readlines(): ...
da1db5ffb99b746271b0fd0f9779da4e6f520246
3,613,291
def _get_table_index(data_group, table_id): """Get attr table.""" table = _get_table(data_group, table_id) return dict( zip( list(map(lambda d: d['entity_id'], table)), table, ) )
300c87d8474b38570487453fbbb6e8d5cf37278e
3,613,293
def xml_api() -> XMLClient: """ Sets up a client to communicate with UK Carbon Intensity API using XML structure as the response format. """ return XMLClient()
bf577ed3b4e5e422dd1aa111e6af802680ed3868
3,613,294
def clear(num: int, start: int, end: int) -> int: """ Sets zeros on bits of num from start to end non inclusive """ if start == end: raise ValueError('Start value same as end') # Builds group of 1s the size of the start - end mask: int = (1 << (end - start)) - 1 return num & ~(mask << start)
68dd669bd9df5ce260daf09375c6ed872580e475
3,613,295
def delete_coa(): """ Delete a certificate of analysis from storage. """ # Remove certificate from storage. # Remove the certificate data. return NotImplementedError
3e8248b6cf87521aae31b4b4eabb601411f38d54
3,613,296
import json def get_incident_by_query(query): """ Get a query and return all incidents details matching the given query. Args: query: Query for the incidents that should be returned. Returns: dict. The details of all incidents matching the query. """ # In order to avoid perform...
0c2ec5190321a9a21ff691512fd8c490c587522d
3,613,297
def bethe_bloch(KE, Z=3., A=6., rho=1., relativistic=True, I=None): """Returns the differential energy loss per depth for protons of speed v (not relativistic) in a medium with density rho as a function of the kinetic energy KE = m * v**2 / 2 in MeV units https://en.wikipedia.org/wiki/Bethe_formul...
b96976c2cdc735aafc5678ebb9b8f1ddb47ab798
3,613,298
from pathlib import Path from datetime import datetime def loadhires(fn: Path, downsample: int = None) -> xarray.DataArray: """ loads and modifies GOES data """ if netCDF4 is None: raise ImportError("netCDF4 needed for hires data. pip install netcdf4") with netCDF4.Dataset(fn, "r") as f...
c57fe19cb6071a0548a9b1003d826da28c334342
3,613,299
def get_connector_cluster_by_conf(channel_name, project_id=None, bk_biz_id=None, cluster_type=None): """ :param channel_name: channel_name :param project_id: 项目id :param bk_biz_id: 业务id :param cluster_type: 集群类型 :return: 优先根据project_id,bk_biz_id选择集群 """ project_route_config = model_mana...
8ef3f40639fca1785c9328aa0a07f82c05e17ab6
3,613,300
import struct def convert_to_unsigned64(value): """Convert an integer to 64-bit unsigned.""" if value > 0xffffffffffffffff: raise TahuInterfaceError(f"Cannot convert large integer {value} to 64-bit") if value > 0: return value if value < -0x8000000000000000: raise TahuInterfa...
cc17af6d32507279ff524f529e7dc715bc06447e
3,613,301
import torch def f(x): """A transformation that has both a fully-predictable part and an inherently-random part.""" a, b = torch.split(x, 16, -1) return torch.cat((a+1, b-1 + torch.randn_like(b)/3), -1)
0da307982a0af0823a1928da097235bf3214b559
3,613,302
def msd(r): """ Mean square displacement Parameters ---------- r: numpy array. dimensions: (t, 3) Array containing the coordinates along t """ shifts = np.arange(len(r)) msds = np.zeros(shifts.size) for i, shift in enumerate(shifts): diffs = r[:-shift if shift els...
a767f611f4c99baebda583bbf7bfe90785304005
3,613,303
import re def align_shiplabels(text): """Return the announcement with the ship labels aligned.""" # See comment in is_unscheduled() for a description of the regex, def monospace(matched): return '`{}`'.format(matched.group(0)) return re.sub('^\d\d:(?!\d\d\s)', monospace, text, flags=re.MULTILI...
c266846f67d212f8cc996f65b46cccc3cb51ff31
3,613,304
def _get_data_type( version: str, name: str, property_definition: dict, entity_class_name: str ) -> kuber_maker.DataType: """...""" setter_type_hint = None reference = property_definition.get("$ref") reference_type = (reference or "").rsplit(".", 1)[-1] api_type = property_definition.get("type")...
9635849b3e67a9d75ffa4f83b21550d0e66bf27b
3,613,305
def create_api_client(base_path, access_token): """ Function for creating api clinet, to interact with docusign. input :: - base_path : base path uri - access_token : auth token received from docusign output :: api_client object """ api_client = ApiClient() api_client.host = base_pa...
dc6d84a6adc743c9bd52f6b50ff0b25f07a4a0be
3,613,306
def stopsNearby(coordX, coordY, maxRadius=None, maxNumber=None, timeout=5): """ Finds stops close to given coordinates. Args: coordX (float): Longitude. coordY (float): Latitude. maxRadius (int): The radius in meters to search within. maxNumber (int): The number of results to re...
aaca1eddd16cbf37ff84580057eeba683d6bf953
3,613,307
def _healpix_bot_left(p, nside, steps=10, reverse=False): """Returns the boundary on the bottom left side of a healpix pixel in healpix x and y coordinates. Parameters ---------- p : int Healpix pixel index. nside : int Healpix Nside. steps : int, optional Number of ...
53adf6b40c3697cafc00a8807240039b5ec7f25d
3,613,308
def imag(x): """Returns the imaginary part of a complex tensor. :param x: The complex tensor :type x: torch.Tensor :returns: The imaginary part of `x`; will have one less dimension than `x`. :rtype: torch.Tensor """ return x[1, ...]
e2a9a3ba22a4ec896a60b3991618f32014d088fd
3,613,309
def crossing_from_taper(taper=lambda: taper(width2=2.5, length=3.0)) -> Component: """Returns Crossing based on a taper. The default is a dummy taper Args: taper: taper function. """ taper = gf.get_component(taper) c = Component() for i, a in enumerate([0, 90, 180, 270]): _tape...
5b78df94084fa08a529a1e6209ef8350e807cd54
3,613,310
async def send_group_forward_msg(group_id: int, msg): """ 发送合并转发 (群) """ try: await nonebot.get_bot().call_api('send_group_forward_msg', **{ 'group_id': group_id, 'messages': msg }) except exception.NetworkError as ne: logger.warning(f'向{group_id}发送 合并...
07caa7209b8f9e87d3e3a30e83daa51e3a7953d0
3,613,311
import torch def unflatten_array(X, N, param_shapes): """Takes flattened array and returns in natural shape for network parameters.""" return [torch.reshape(X[N[i]:N[i + 1]], s) \ for i, s in enumerate(param_shapes)]
1b127de0d8389d2b44d4f50c3cb85429d2629107
3,613,312
def quantize_values(values, centers=None): """On a particular 1d latice, quantize points to nearest Args: values (ndarray[Float]): Array of values to quantize to the centers centers (ndarray[Float]): Center values to quantize to. If None it will attempt to get the centers from the v...
424aea184208942c8b52349c312a9a8ef9acdef5
3,613,313
def bs_se(bs_pdf): """ Calculates the bootstrap standard error estimate of a statistic """ N = len(bs_pdf) return np.std(bs_pdf) * np.sqrt(N / (N - 1))
d08dc819f72e9c288e85b597eb5764980475cd58
3,613,314
import six def _create_subnetwork_report_proto(materialized_subnetwork_report): """Creates a Subnetwork proto.""" def _update_proto_map_from_dict(proto, field_name, dictionary): """Updates map field of proto with key-values in dictionary. Args: proto: the proto to be updated in place. field_...
9aff035cb7b8ae08c59a3f7508164c62f023c18d
3,613,315
import time import re def parse_timestamp(timestamp, time_format=None): """ parse_timestamp(timestamp, time_format=None) -> struct_time Does NOT raise ValueError. Return None on formatting error. """ if time_format is None: time_format = '%a, %d %b %Y %H:%M:%S %Z' try: return time.strptime(timest...
f1a9064a5da4791b1a652c3acfc6ee092144c21f
3,613,316
def decrypt(value): """decoding""" print(value) src = signing.loads(value) print(src) return src
93b113b695b6927bda88e8ed4d6a1c59b05380b9
3,613,317
def calculate_activation_statistics(act): """Calculation of the statistics used by the FID. Params: -- images : Numpy array of dimension (n_images, hi, wi, 3). The values must lie between 0 and 255. -- sess : current session -- batch_size : the images numpy array is...
3dc8702a7af8edb5ebed4583ad0c35d630adee2b
3,613,318
def user_view_list_data(): """ Fixture for testing VideoDetail view permissions with a collection view_list """ video = VideoFactory() collection = video.collection moira_list = factories.MoiraListFactory() collection.view_lists.set([moira_list]) return SimpleNamespace(video=video, moira...
2b3dcef2cec60f87fdf25c7e10f0b7eb8f4cb717
3,613,319
import time def amountValidation(amount, minWithdrawAccount, maxWithdrawAccount, atmCash, accountBalance, minBill): """Validate the amount of money. Args: amount (int): Amount of money. minWithdrawAccount (int): Minimum amount of money allowed to withdraw. maxWithd...
5a0b70da29832cbf31f114c5941471ff69762016
3,613,321
def catchItem(f, theSpider=None): """Decorador, ejecuta la función parse y procesa el resultado como una lista de items, ejecutando la función 'saveitem' que corresponda.""" def new_f(*args, **kwargs): #print("thepath "+os.getcwd()) #print("the spider") #print(str(theSpider)) ...
2f2bba543a2ecf783d7372a39cc1edc4a9fc788c
3,613,322
def _MatchGlobToken_Fast(line, start_pos): """Returns (id, end_pos).""" tok_type, end_pos = fastlex.MatchGlobToken(line, start_pos) return IdInstance(tok_type), end_pos
3dd3c7e117e2237ea4f7659240af90faaddf3a9a
3,613,323
import math def roundoff(a, digit=2): """ roundoff the number with specified digits. :param a: float :param digit: :return: :Examples: >>> roundoff(3.44e10, digit=2) 3.4e10 >>> roundoff(3.49e-10, digit=2) 3.5e-10 """ if a > 1: return round(a, -int(math.log10...
c2bded960f9fa6431a03f6562b49f73477379a32
3,613,324
def trial(car, initial, change, verbose=False): """Perform the simulation of one trial Parameters ---------- car : int The door the car is behind (1, 2 or 3) initial : int The player's initial door selection (1, 2 or 3) change : bool If true, the player will change their...
cd6f328f18b7ea22281f3993b43f89e3118064c1
3,613,325
def imgMI(inImg, refImg, inMask=None, refMask=None, numBins=128, samplingFraction=1.0): """ Compute mattes mutual information between input and reference images """ # In SimpleITK the metric can't be accessed directly. # Therefore we create a do-nothing registration method which uses an ...
60a94e7029978a3b567a4d7569f08b6ed49b1f7d
3,613,326
import re def natsort(alist): """ Sort the given iterable in the way that humans expect. From: https://stackoverflow.com/questions/2669059/how-to-sort-alpha-numeric-set-in-python """ convert = lambda text: int(text) if text.isdigit() else text alphanum_key = lambda key: [convert(c) for ...
3ceabceab67a78d41966095f4a2b51c4e8cf1a72
3,613,327
def get_field(data, ml=0, member=None): """ Arguments: data: N-D array of data ml: Prefer this model level, if there are several levels Returns: np.array: 3D array: Time X, Y """ if(len(data.shape) == 4): # Extract the right model level, if multip...
be81c095097bfa77c0043cc31a5913dcd3c7419a
3,613,328
def validate_unreal_paths(properties): """ This function checks each of the entered unreal paths to see if they are correct. :param object properties: The property group that contains variables that maintain the addon's correct state. :return bool: True if the objects passed the validation. """...
732182c239e8166964f49350aa7b51e37bc04111
3,613,330
def parse_args(): """Parse the command line arguments and perform some validation on the arguments Returns ------- args : argparse.Namespace The namespace containing the arguments """ parser = ArgumentParser( description='''Run GIST calculations through command-line.''') ...
8efbbc7b56e27661bef95661491ce065c630cdb7
3,613,331
def parse_labels_yolo(label_file, labels, img_width, img_height): """ Definition: Parses label files to extract label and bounding box coordinates. Converts (x1, y1, x1, y2) KITTI format to (x, y, width, height) normalized YOLO format. Parameters: label_file - file with KITTI label(s) inside labels - list ...
73a892f87c1419bf24e3b99cbda49f3c489a4a83
3,613,332
import six def build_dict(min_word_freq=50, train_filename="", test_filename=""): """ Build a word dictionary from the corpus, Keys of the dictionary are words, and values are zero-based IDs of these words. """ with open(train_filename) as trainf: with open(test_filename) as testf: ...
fb9dd7832d38d1c71ba36b2fcaf1118d8a23ce3c
3,613,333
from typing import Tuple from typing import List def deltaG_fwd(model, sys_params) -> Tuple[Tuple[float, List], np.array]: """same signature as DeltaG_from_results, but returns the full tuple""" results = run_model_simulations(model, sys_params) return _deltaG_from_results(model=model, results=results, sy...
79aa0ad79e66246b7bfb8aff37315d235c192464
3,613,334
from datetime import datetime def parse_iso8601tz(date_string): """return a datetime object for a string in ISO 8601 format. This function parses strings in exactly this format: '2012-12-26T13:31:47.823-08:00' Sadly, datetime.strptime's %z format is unavailable on many platforms, so we can't use...
a4a3c233ebad1d2ea3537c40b8f6114a791d5311
3,613,335
def sp_compute_adj_att(node_features, adj_matrix_sp): """Self-attention for edges as in GAT with sparse adjacency.""" out_dim = node_features.shape[-1] # Self-attention mechanism a_row = tf.get_variable( initializer=WEIGHT_INIT, dtype=tf.float32, name='selfatt-row', shape=(out_dim, 1)) ...
31b4e3fc3b3508d3a631252b27574c0a1fdbef8c
3,613,336
def mat_mul2(A, B, alpha=1): """ https://www.benjaminjohnston.com.au/matmul """ return alpha * np.matmul(A, B) # return LA.blas.sgemm(alpha, A, B)
7a92469cd5348dc636eead8b9965a8d507cfa59e
3,613,337
def observation_encoder(o): """ """ with tf.variable_scope('observation_encoder_module'): std1 = tf.nn.space_to_depth(o, 4) cs1 = conv_stack(std1, 3, 16, 5, 16, 3, 64) std2 = tf.nn.space_to_depth(cs1, 2) cs2 = conv_stack(std2, 3, 32, 5, 32, 3, 64) e = tf.nn.relu(cs2) ...
6602d13a74bab4175c0c1edc94a9523ce9a4a875
3,613,338
def getSuperUserTimezone(): """ For the calculation of correct datetimes for payment gateways on when exactly to charge recurring payments Assumption: the superuser has set the correct local timezone which matches with the payment gateway's timezone setting """ su = User.objects.get(is_superuser=1) ...
4d1d625628854f561465abe9a1863c87b956b0af
3,613,339
import numpy def empirical(datafile,vavg,crew,rigging,tstroke,trecovery,doplot=1): """ Reads in empirical acceleration data to be compared with acceleration plot """ lin = rigging.lin lscull = rigging.lscull lout = lscull - lin tempo = crew.tempo mc = crew.mc mb = rigging.mb ...
ce3e3c67c424fac7bf579373e0058181c8d26dc1
3,613,340
def dup_zz_factor(f, K): """ Factor (non square-free) polynomials in `Z[x]`. Given a univariate polynomial `f` in `Z[x]` computes its complete factorization `f_1, ..., f_n` into irreducibles over integers:: f = content(f) f_1**k_1 ... f_n**k_n The factorization is computed by redu...
fc501028de0908bea8d36d78baac2c007e987413
3,613,341
def non_net_metering(tfr_dfs): """ Transform the EIA 861 Non-Net Metering table. Args: tfr_dfs (dict): A dictionary of transformed EIA 861 DataFrames, keyed by table name. It will be mutated by this function. Returns: dict: A dictionary of transformed EIA 861 dataframes, ke...
ced698f5636872a241578f667d61aa323fb6e14f
3,613,342
def create_user(**params): """Create and return a new user.""" return get_user_model().objects.create_user(**params)
73d8b30547229b2a8d2d0478d5830a7ce3c289ac
3,613,343
def napari_get_reader(path): """Show OME XML if an ome.xml file is dropped on the viewer.""" if isinstance(path, str) and path.endswith("ome.xml"): return view_ome_xml
189215539c83c192f0eb036d946761edeb91d8e6
3,613,346
def Hx(sk, messages): """A helper function Hx""" assert len(messages) == len(sk) - 1 total = sk[0] for xi, mi in zip(sk[1:], messages): total = total + (xi * mi) return total
609794cc6bcf7b6321192d23a0d4903ffce05b91
3,613,347
def _unsur(s: str) -> str: """Merge surrogates.""" return s.encode("utf-16", "surrogatepass").decode("utf-16", "surrogatepass")
d6bc230a77c735c9922ec66aa6a3537beea5b42f
3,613,349
def chatload(): """ Load all chat messages on a conversation channel """ rq = RequestData(request) channel = rq["channel"] if not channel: # We must have a valid channel return jsonify(ok=False) user_id = current_user_id() game = None if channel.startswith("game:"): ...
237a00a580609709c16a79f4a9440837ca6c4935
3,613,350
def newgpg(ui, **opts): """create a new gpg instance""" gpgpath = ui.config(b"gpg", b"cmd") gpgkey = opts.get('key') if not gpgkey: gpgkey = ui.config(b"gpg", b"key") return gpg(gpgpath, gpgkey)
7f82c1b1413c5940b109d9968266ad487981fabd
3,613,352
def main(args=None): """Console script for cli_password_manager.""" pass_mgr = PasswordManager() pass_mgr.screen() return 0
5a82b952e11fc9d9db4ac5af49d7c64ed08d9140
3,613,353
from typing import TextIO from typing import List import textwrap from datetime import datetime def test(general: _general.Params, command: Params, stdout: TextIO) -> List[str]: """ Test the specified functions. Return errors if any. """ if not command.path.exists(): return ["The file to ...
84fa55fa07378b7b7471be4873c3282dd90ac324
3,613,354
def make_routing_table(obj, keys, prefix='on_'): """ :return: a dictionary roughly equivalent to ``{'key1': obj.on_key1, 'key2': obj.on_key2, ...}``, but ``obj`` does not have to define all methods. It may define the needed ones only. :param obj: the object :param keys: a list of keys ...
79006027e74869b4de663f8d908c66f0c22e9de8
3,613,355
def series_greater_than_zero(series: pd.Series): """Return a bool series indicating whether the elements of s are > 0""" return series > 0
1e5ed1eae2a8e2cfb20ac4220652eaf672475f04
3,613,356
def Seq_of_t(tau,Te,R): """ Python implementation of Seq(tau) Time domain auto-correlation of a tunnel junction at thermal equilibrium Latex : S_{eq} = - \frac{\pi (k T)^2}{R \hbar} \sinh^{-2} \bigg( \frac{\pi k T}{\hbar} \tau \bigg) See Also -------- Thesis : Mesu...
047b5e6b28a095560fb6f2b817a6a514b7d34c5b
3,613,357
import urllib3 from bs4 import BeautifulSoup def get_html_page(page_url): """ Get the whole page source code""" http = urllib3.PoolManager() response = http.request('GET', page_url) soup = BeautifulSoup(response.data, 'html.parser') response.release_conn() return soup
5c535322f713d94c541d423e79e780016977d4e6
3,613,358
def get_aname(value: str) -> str: """Pass.""" return strip_right(obj=str(value or ""), fix="_adapter")
ef586cfbccb5a81ff561024967771827456adc1e
3,613,359