content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def print_ofpt_packet_out(msg): """ Args: msg: OpenFlow message unpacked by python-openflow ; PAGE 107 MANUAL """ print('PacketOut: buffer_id: %s in_port: %s actions_len: %s' % (hex(msg.buffer_id.value), green(dissector.get_phy_port_no(msg.in_port.value)), ...
a5f459e835b168480e1cd3c6fdeea1ebd7601bdb
3,612,905
def convert_to_example_temporal( image_datas, image_paths, image_shapes, labels, centers, gt3ds, scale_factors, start_pts, cams, poses=None, shape=None, phis=None, image_datas_og=None, time_pts=None): """...
9ce82538e5dc68b64ec171b7b26723fea3923d3c
3,612,906
def conformance(source): """ Creates a function that does a shallow comparison between a given object and the `source` dictionary using :func:`conforms`. Examples: >>> conformance({'a': 1})({'b': 2, 'a': 1}) True >>> conformance({'a': 1})({'b': 2, 'a': 2}) False Arg...
9c4c56e7ce5de819b6392a3c3ac734298fdb0896
3,612,908
from typing import Optional def stack_v1( x: tf.Tensor, filters: int, blocks: int, stride1: int = 2, dilation_rate: int = 1, name: Optional[Text] = None, ) -> tf.Tensor: """Create a set of stacked ResNetv1 residual blocks. Args: x: input tensor. filters: integer, filte...
7d5674589147fe2797126cb02c085b259e04aedc
3,612,909
import torch def get_params(model): """Aggregates model parameters of all linear layers into a vector. Args: model: A (pre-trained) torch.nn.Module or torch.nn.Sequential model. Returns: The aggregated parameters. """ weights = list() biases = list() for module in model.m...
c6a66f3a013f62e79e51f47d130e65b12b38ff33
3,612,910
def as_series(alist, trim=True) : """Return arguments as a list of 1d arrays. The return type will always be an array of double, complex double. or object. Parameters ---------- [a1, a2,...] : list of array_like. The arrays must have no more than one dimension when converted. trim ...
4117ec228be723b4d445eaa1d8f67a7ce303c134
3,612,911
import math def hist16bit(array, bins=64, step=None, low=None, high=None, use_numba=True): """ stepsize should be power of 2 array should be 8 or 16 bit integer """ if array.dtype == 'uint8': length = 256 offset = 0 elif array.dtype == 'int8': length...
d18dde94e5d947407741d7acf82a0f6f459903bf
3,612,912
import requests def get_circ_supply_on_chain(chain:str): """ chain: Allowed: ethereum ┃ avalanche ┃ bsc ┃ polygon ┃ arbitrum ┃ fantom ┃ harmony ┃ boba ┃ optimism ┃ moonriver ┃ aurora direction: Allowed: in ┃ out """ chain = chain.lower() chains = ["ethereum", "avalanche", "bsc", "polygon", "...
3ed143a35d697c52f42696f14dfa8ea3c90c712b
3,612,913
def test(epoch, max_epoch): """ Test model """ loss_meter = AverageMeter() acc_meter = AverageMeter() for ind, (x, target) in enumerate(testing_loader): # x is NxCxHxW => WxNx(HxC) x = preprocess_data(x) act_lengths = get_seq_length(x) # target is a list of `torch.In...
74f038b9c38cbaaaff70fb64fa146454a1e7309a
3,612,914
from typing import List def find_response(triggers: List[Trigger], message: str, is_gauchito: bool): """ Returns the first matching trigger in a list of triggers given the message contents and whether or not the author is a gauchito. Returns None if the message matches none of the triggers """ ...
5f78dd309bee3b16ecd87cd5f16d116dc2f5cd86
3,612,915
from typing import List def create_sql_endpoint_class( name: str, method: str, url: str, sql: str, repository: DataRepository, query_parameters: List, tags: List, request_schema: type = None, response_schema: dict = None, description: str = None, is_from_template: bool = Fa...
4f96eb7042885699612cd5d25ec0274d9f7bd714
3,612,916
def loss(logits, labels): """Add L2Loss to all the trainable variables. Add summary for "Loss" and "Loss/avg". Args: logits: Logits from inference(). labels: Labels from distorted_inputs or inputs(). 1-D tensor of shape [batch_size] Returns: Loss tensor of type float. """ # Calculate...
4b743f554123776fe8240ab273de997c1b967488
3,612,917
def make_production_app(): """ Configure logging before creating the application. Useful with application servers, where it's pretty impossible to run code other than the app factory. :return: standard app created by make_app """ configure_logging() return make_app()
f3dc6118ae55b2706e174924a89bd64c55429f3e
3,612,918
from re import IGNORECASE def high_light(pattern, content, option): """ Will find pattern every pattern in content ignore upper or lower and highlight that pattern in content """ patterns = findall(pattern, content, IGNORECASE) if option != '--case-sensitive' else findall(pattern, content) for...
b83a363ea82e61ef022d7937ca0c71dcc5159867
3,612,919
def _lst_for_pes(pes_dct, run_pes_idxs): """ Get a dictionary of requested species matching the PES_DCT format """ red_pes_dct = {} for (form, pidx, sidx), chnls in pes_dct.items(): # Grab PES if idx in run_pes_idx dct run_chnl_idxs = run_pes_idxs.get(pidx, None) if run_chnl_idx...
75307b871588b5a9c04a95e29c315c7528fc1259
3,612,920
def cholesky_decomposition(matrix): """ Compute the Cholesky decomposition of a symmetric positive definite matrix """ # compute the decomposition gsl.linalg_cholesky_decomp(matrix.data) # and return the matrix return matrix
1d15a86aeb579985f0c46df3c250c7eac6aa2e31
3,612,921
def _cvt_names_to_graph(srcpath, destpath): """Translates model pathnames into pathnames in term of our 'fake' graph nodes @xin, @bin, @bout, and @xout. """ srcvar, _ = _split_expr(srcpath) srccompname, _, srcvarname = srcvar.partition('.') destcompname, _, destvarname = destpath.partition(...
47cb7a50e2a20515cd012c90eb00f372e187db79
3,612,922
import math def math_pow(x, y): """Implement the SQLite3 math built-in 'pow' via Python. """ try: return math.pow(x, y) except: pass
d8e1ad37b0fc2f0df6f525cae282478417a919b7
3,612,924
def grid_search(estimator, param_grid, X_train, y_train, X_test, y_test, batch_size=10000, nn=False): """ Performs grid search over parameter grid. Function iterates over the combinations of parameters in the parameter grid. Trains the estimator on the X_train. Evaluation is done on both the training set a...
2cb0a85ead51c0aacbfc6989e76a7948a9101a59
3,612,925
def get_voted_content_for_user(user): """Returns a dict where: - The key is the content_type model - The values are list of id's of the different objects voted by the user """ if user.is_anonymous(): return {} user_votes = {} for (ct_model, object_id) in user.votes.values_li...
799eff5efd184da0b5121f59025c39d0ddb593a3
3,612,926
def get_bbx_from_seg(label): """ Get a bounding box from a binary mask """ border_list = [-1, 40, 80, 120, 160, 200, 240, 280, 320, 360, 400, 440, 480, 520, 560, 600, 640, 680] img_width = 480 img_length = 640 rows = np.any(label, axis=1) cols = np.any(label, axis=0) rmin, rmax = n...
0cd040a9e37ee8808bc8fa7b79d3ce8cd26e60f9
3,612,927
def odd_occurences_in_array(a): """ Finds the odd number of occurences of an element in an array. XOR of all elements gives us odd occurring element. Note that XOR of two elements is 0 if both elements are same and XOR of a number x with 0 is x :param a """ result = 0 for number in a: ...
8085fb8ffa5df9628caa5fef541b5d7b78c372b0
3,612,928
def new_pm(): """ function that is called when you visit /portfolio_manager/new, creates a new PM """ token = request.headers.get("token") headers = {"Content-type": "application/x-www-form-urlencoded", "token": token} message, info = verify_token(token) if message != None: return create_...
8d46547351ef0650a0189a2a039d42afa6374584
3,612,929
import array def to_envelopes(path,num_bands,freq_lims,downsample=True): """Generate amplitude envelopes from a full path to a .wav, following Lewandowski (2012). Parameters ---------- filename : str Full path to .wav file to process. num_bands : int Number of frequency bands ...
e66ee3e5cab282247b4ce91f5834641fa966a447
3,612,931
def separe_liste(points): """ Parameters ---------- points : TYPE DESCRIPTION. Returns ------- points_1 : TYPE DESCRIPTION. points_2 : TYPE DESCRIPTION. """ centroide = trouver_coordonnees_centroide(points) distances = [] for point in points: ...
22a50b79744119814ba723c13335bda6767ce045
3,612,932
def fdq(node_results, Qstar, average_times=False, average_nodes=False): """ Compute fraction delivered quality (FDQ), equations modified from [1]. The metric can be averaged over times and/or nodes. Parameters ---------- node_results : pd.Panel A pandas Panel containing node result...
b27be4f8dc1d40d9fee2ee901f43f0a256d35f02
3,612,933
import time import random import json def lambda_handler(event: dict, _context: dict): """Sample Lambda function that notifies back the Step function that invoked it, using the Task Token id passed along with its payload Parameters ---------- event: dict, required Input event to the Lambd...
0cb0c0b042bf886d953a8b5310f16409f3d26332
3,612,934
import yaml def read_documents(*paths, uri=False): """ Read and parse documents from the filesystem or remote URLs (yaml or json). Note that a single yaml file can contain multiple documents. This function will load any dates in the documents as strings. In Data Cube we store JSONB in PostgreSQL...
c81beb6a90105cbc7288d5910a67091c86867c74
3,612,935
def delete_service(service_handle): """See: DeleteService function https://msdn.microsoft.com/en-us/library/windows/desktop/ms682562(v=vs.85).aspx """ DeleteService_Fn = windll.Advapi32.DeleteService #BOOL WINAPI DeleteService( DeleteService_Fn.argtypes = [ # wintypes.SC_HANDLE # _In_ SC_HANDLE hServ...
3f5cb513e3fde57982472f3744cba22b175151aa
3,612,936
def dns_installation(instance, arg, verbose=True): """ Install bind9 package on the remote instance and configure name resolution for his own domain name """ if install(instance, {"module":"bind9"}, verbose=False) == 1: return 1 # execute_command(instance, {"command":["truncate", "-s", "0", "/etc/bi...
aa2825e60d8ebbe16064858e370646431389de06
3,612,937
import collections def get_inv_aliases(): """Return a mapping from target to list of sources for all alias targets in either the default alias table or the unknown_flag alias table.""" inv_aliases = collections.defaultdict(list) standard_aliases = add_aliases.read_default_emoji_aliases() for k, v in sta...
c2d8f4b44503b0fd17cae73c5757d3126ae92289
3,612,938
from typing import Union from typing import List from typing import Tuple def region_expand( region: RegionLike, expansion: Union[int, List[int], Tuple[int, int]], ) -> Union[Tuple[int, int], sublime.Region]: """ @brief Expand the region by given amount. @param region The region @param exp...
0b2db5cbc5810290c073cb8cae3d6c032286ac83
3,612,939
def median(embedding, neighbors, verbose=False): """Initialize points onto an existing embedding by placing them in the median position of their nearest neighbors on the reference embedding. Parameters ---------- embedding: TSNEEmbedding neighbors: np.ndarray verbose: bool Returns ...
29af122e2b04f712ea4d0e0c8fcfd72341d6bce6
3,612,940
def checkExtention(files): """ This function will check extention of each file. """ for file in files: if file.name.lower().split(".")[-1] not in ['pdf', "jpeg", "png", "jpg"]: return file.name + " is not accepted. We accept only 'pdf', 'jpeg', 'png', 'jpg' file format." return ...
247f43087d9e85d360900c5da2b8bfa1581117ef
3,612,942
def accuracy(output, target, topk=(1,)): """Derived directly from the reference NIPS2017 Workshop. Computes the precision@k for the specified values of k, used for semi-supervised learning. """ maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = p...
00b77a713e5ab26d7614981666eb35e111dde992
3,612,943
def merge_pairs(seq1, seq2, qual1, qual2, ins1=None, ins2=None, q_cutoff=10, minimum_q_delta=5): """ Combine paired-end reads into a single sequence. Manage discordant base calls on the basis of ...
0e3863359488aceca8ae388a5b672c22842188b8
3,612,944
def activation_func(func_type, z): """ Implements the different kind of activation functions including: sigm - sigmoidal tanh - hyperbolic tangent relu - Rectfied step - Heavside (binary step 0 or 1) """ if func_type == 'sigm': return (1 / (1 + np.exp(-z))) ...
2e4cd2e4679beb54f1f34f3e2985167ef99978d8
3,612,945
def ldns_dnssec_zone_sign_nsec3_flg(*args): """LDNS buffer.""" return _ldns.ldns_dnssec_zone_sign_nsec3_flg(*args)
888886c068b4bc626f20bb068fca9c4775ad4666
3,612,949
def sub(x, y): """values are subtracted and return""" return y - x
d07223d6866d27e926952b74d29274f7de1b7a9f
3,612,950
def _to_numpy_array(arr): """ Help function for converting an iterable to a Numpy array. :param arr: Array we want to convert. :type arr: Iterable[float] :return: Input array converted to a Numpy array. :rtype: :class:`Numpy array <numpy.ndarray>` >>> _to_numpy_array([1.0, 2.0, 3.0]) a...
c0ef84dae59418e21f268171dbf75e1feb2e68d7
3,612,951
from typing import Counter def infer_dependency(op): """ Infer the dependency of all operations with the given op as the last operation. Operator A is depending on B if A uses the output(s) of B. Args: op: an Operator instance, e.g. the loss operation. Return: a Counter insta...
0c916c7f5535845460084ed1d4846e9c6cd0a39b
3,612,952
def softmax_loss(x, y): """ Computes the loss and gradient for softmax classification. Inputs: - x: Input data, of shape (N, C) where x[i, j] is the score for the jth class for the ith input. - h: Vector of labels, of shape (N,) where h[i] is the label for x[i] and 0 <= h[i] < C Re...
b38c7dff075499ec1de2bb1f742614f484951a31
3,612,953
import json def stopOscProgress(request): """中止该SQL的pt-OSC进程""" workflowId = request.POST['workflowid'] sqlID = request.POST['sqlID'] if workflowId == '' or workflowId is None or sqlID == '' or sqlID is None: context = {"status":-1 ,'msg': 'workflowId或sqlID参数为空.', "data":""} return Htt...
36b9d2a8e4eb516084e728269c8f1846ec22c794
3,612,954
import re def extract_length(value): """ extract length data from a provided value Returns a tuple of a detected length value and a length unit. If no unit type can be extracted, it will be assumed that the provided value has no unit. Args: value: the value to parse Returns: ...
b418b76114fafe24c86c2e0dcfa62bb19b29ff59
3,612,956
def get_session(role_arn, region_name): """ Returns a session for the specified accountId """ sts_connection = boto3.client('sts') acct_a = sts_connection.assume_role( RoleArn=PIVOTAL_ROLE, RoleSessionName='AWS-Tower' ) access_key = acct_a['Credentials']['AccessKeyId'] s...
513d910de2f18bfc4a7a7257a74072f4fe0aefe0
3,612,957
def get_node_by_name(node_name): """ Returns pymxs node object with the given name, if exists in the scene; otherwise returns None :param node_name: str, name of the node we want to retrieve :return: variant, pymxs object or None """ return rt.getNodeByName(str(node_name))
fe56a4c10bda6d1fe9237dc48d0bb47dd4ab8ec9
3,612,958
def get_cache_file_metadata_path(cache_file_path): """Return metadata file path for a cache file.""" return '%s%s' % (cache_file_path, CACHE_METADATA_FILE_EXTENSION)
b9eed0a52f49c64e64a48b8d92f9d20e4ad6b3f5
3,612,959
def undo_grad_transforms(grad, tasks, transformers): """DEPRECATED. DO NOT USE.""" logger.warning( "undo_grad_transforms is DEPRECATED and will be removed in a future version of DeepChem. " "Manually implement transforms to perform force calculations.") for transformer in reversed(transformers): i...
c6a2f51704ecf5ab941e5720c74377b1b858669a
3,612,960
def check_agency_status(msg): """ checks to see if message contains an agency slug (i.e., char string between two # hashtags) and, if so, looks up to see what if any agency it belongs to. returns agency name """ slug = check_agency_hashtag(msg) # sender_agency = check_sender_agency(msg) ...
b5bf5e29304a48aa2abf85fe0e316f64ecdc0485
3,612,961
def euclidean_distance(x: np.array, y: np.array) -> float: """Calculates euclidean distance. This function calculates euclidean distance between two points x and y in Euclidean n-space. Args: x, y: points in Euclidean n-space. Returns: length of the line segment connecting giv...
c62f2e374dd523b676476a75f8a45d3b5c8cc249
3,612,962
def transform_geojson_wgs_to_epsg(geojson, EPSG): """ Takes a geojson dictionary and converts it from WGS84 (EPSG:4326) to desired EPSG Parameters ---------- geojson: dict a geojson dictionary containing a 'geometry' key, in WGS84 coordinates EPSG: int numeric code for the EPSG ...
8dff1f786fa5bfeddd9ff63c43a042da4a6a9a68
3,612,963
def time_offset(tds, insttime, utctime): """Calculate and apply time offset to SBE56 time series Parameters ---------- tds : xarray.DataArray SBE56 data structure insttime : np.datetime64 Instrument time at end of time series utctime : np.datetime64 UTC...
a8c7ef290f09c6b6975575715233986ff171e24a
3,612,964
def gaussian_kernel(kernel_shape: tuple, centre: tuple, sigma: float, amplitude: int = 1) -> np.ndarray: """Returns a 2D Gaussian kernel array.""" y, x = np.ogrid[0:kernel_shape[0], 0:kernel_shape[1]] h = np.exp(-(pow(x - centre[0], 2) + pow(y - centre[1], 2)) / (2. * sigma * sigma)) h[h < np.finfo(h.dt...
245d61bd3c33b082658cbcd8cf57c6a968ece6ae
3,612,965
def web_hook(): """ transfer station of teambition's webhook to feishu's webhook """ # resolve teambition's request, maybe we need some authentication signature = request.headers.get('X-Signature', '') response = request.json type = response['event'] task_state_map = {'task.create'...
1f221f0a2e88dec136fa3fbe11ce9db35a2172ac
3,612,966
def flip_op(input, dims): """ Reverse the order of a n-D tensor along given axis in dims. .. note:: `flow.flip` makes a copy of :attr:`input`'s data. This is different from NumPy's `np.flip`, which returns a view in constant time. Since copying a tensor's data is more work than viewing...
0c08e3f0713f99e17b2276de51593c981a5e5073
3,612,967
def deserialize_timestamp_from_binance(time: int) -> Timestamp: """Deserializes a timestamp from a binance api query result entry Kraken has timestamps in integer but also including milliseconds Can throw DeserializationError if the data is not as expected """ if not isinstance(time, int): ...
94f4ced79fe3bf026fcb37e4e40d6265b7eacf3a
3,612,968
def intersect(set_a, set_b): """ """ return [x for x in set_a if x in set_b]
be1bf6cb55d0ab94e68cc05fc6d9fb5d68f5dd4c
3,612,969
def refine_general(splits, sigma, n=1, combine=lambda a, b: a + b, key=lambda a: a): """ Do a general refinement of up to n steps """ oldsplits = splits[:] N = splits[-1] counter = 0 k = len(splits) n = n or np.inf while counter < n: splits = [bestsplit_general(sp...
6a99beec1dde51689f1f9bd9e18d0408f884c39a
3,612,970
def matrix_exponential(matrix:tf.Tensor, dt): """Computes the matrix exponential of one or more square matrices. $$exp(A) = \sum_{n=0}^\infty A^n/n!$$ The exponential is computed using a combination of the scaling and squaring method and the Pade approximation. Details can be found in: Nicholas J. H...
baef93f6eaf2af00ddf43098fd6f0f5039f7f67e
3,612,971
def enumerate_param(param, values): """Builds a dictionary of an enumerated parameter, using the param string and some values. If values is not a list, tuple, or set, it will be coerced to a list with a single item. Example: enumerate_param('MarketplaceIdList.Id', (123, 345, 4343)) Returns: ...
27e109224c1315a34ebac6e78f47a7cf6136cd29
3,612,972
def enumerate_paths(src): """flatten out a nested dictionary into an iterable DIODE metadata is a nested dictionary; One could easily query a particular scene and scan, but sequentially enumerating files in a nested dictionary is troublesome. This function recursively traces out and aggregates the l...
d9195cba20b9d370e762f9ff839bb8b294368a20
3,612,973
def tweet_decode(tweet): """ Gets data from tweet and returns a simplified data structure tweet = { 'full_text': 'This is a tweet #hello #world http://t.co/13456', 'urls': [ 'http://en.wikipedia.org/' ] 'hashtags': [ '#hello', '#world' ] } """ tweet_simple...
b7c9667bd3bd755e3e7120f366faf6d19419c316
3,612,974
def load_clonotypes_csv_general(fname: str, single_return: bool = True) -> pd.DataFrame: """ Load clonotypes.csv file. This file is expected to be a comma-delimited table with columns "clonotype_id" and "cdr3s_aa". Returned data frame is the df contained in fname with added columns TRA_aa and TRB_aa ...
5f03f56e02d75d34e85b3d631d558361472645bb
3,612,975
def pattern_search(search_pattern): """ Search for search_pattern in pattern. Convert from hex if needed Looking for needle in haystack """ needle = search_pattern try: if needle.startswith("0x"): # Strip off '0x', convert to ASCII and reverse needle = needle[2:]...
c7eb27988b951888b753849a62b8680742ef1055
3,612,976
import unittest def suite(): """Define all the tests of the module.""" suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(SearchV2TestCase)) return suite
e9e4d3ebeb95dab99a154730218c074ef5389e1d
3,612,977
def manhattan_distance(pointA: tuple[int], pointB: tuple[int]) -> int: """Returns the Manhattan distance between points A and B, assuming a weight of 1""" return abs(pointA[0] - pointB[0]) + abs(pointA[1] - pointB[1])
6ad8b15519d577f9cb5d0b86e2bc89674f190155
3,612,978
import asyncio def forecast(latitude: float, longitude: float) -> list[Forecast]: """Main function for retrieving forecast for a longitude and latitude""" loop = asyncio.get_event_loop() *information, request = loop.run_until_complete(_get_gridpoint(latitude, longitude)) res = loop.run_until_complete(...
40ffbdb73bb9603532e65d6bd9f9f4a5e83cdbb2
3,612,980
def get_berkeley_format(): """Creates a configuration for images saved in Berkeley format. Returns: the configuration. """ config = {} config['image_name'] = '{}/image_aux1/encoded' config['state_name'] = '{}/endeffector_pos' config['action_name'] = '{}/action' config['state_dim'] = 3 config['act...
521df1a7244d796f5d8a91075c5723ac6c4557ae
3,612,981
def cxyz_to_xyzc( v ): """ Takes a torch array and returns it as a numpy array on the cpu :param v: torch array :return: numpy array """ dim = len(v.shape)-2 if dim ==2: v = v.permute(0,2,3,1) if dim ==3: v = v.permute(0,2,3,4,1) return v
65dcaf573bf53f0b78bdea83d0ce809bd335a480
3,612,982
import time import functools import logging def monorail_api_method( request_message, response_message, **kwargs): """Extends endpoints.method by performing base checks.""" time_fn = kwargs.pop('time_fn', time.time) method_name = kwargs.get('name', '') method_path = kwargs.get('path', '') http_method = ...
60f13597b89cbdddd113c705a0b752d7a6874b3e
3,612,984
from typing import Union def _extend_dict(main_dict: Union[PerArraySequenceDict, PerArrayDict], added_dict: Union[PerArraySequenceDict, PerArrayDict]): """ We can't do anything like main_dpp.extend(added_dpp). Doing as in nibabel.streamlines.tests.test_tractogram. """ for k, v in ...
657bd195324e63fa03ffbbfb20295e33428d0179
3,612,985
def expool(CONST_STRING): """expool(ConstSpiceChar * CONST_STRING)""" return _cspyce0.expool(CONST_STRING)
7a88c120b9a0f02d03f1e9f63dd811523e419da0
3,612,986
def stackop(func, stack): """Returns a function, that operates on the elements of a given stack. Example for creating a multiply stack operation, which takes two arguments: >>> stack = [1, 2, 3, 4] >>> multiply = stackop(lambda x, y: x * y, stack) >>> multiply() >>> stack ...
5c6a06ef6dcb8c3fdbc31ee61fb769c5b254f960
3,612,987
def get_seed_catalog(seedname="DeveloperSeed"): """Returns the developer seed sucatalog""" try: seed_catalogs = read_plist(SEED_CATALOGS_PLIST) return seed_catalogs.get(seedname) except (OSError, IOError, ExpatError, AttributeError, KeyError) as err: log.warn(err) return ""
59c3a86dda7e27673fd496c1a59504156d380471
3,612,988
def generate_all_valid_patterns(): """Generate all valid dot patterns, as strings representing 16 bit binary numbers. Valid patterns are made up of dots and blanks in an 8x2 pattern which are - made up of exactly 10 dots, where 4 dots always make up the left-most and right-most column - not rot...
4ea136ab06901179d786e9e205484485017f8813
3,612,989
def get_id(serving_name): """ Gets the id of a serving with a given name Example use-case: >>> from hops import serving >>> serving.get_id(serving_name) Args: :serving_name: name of the serving to get the id for Returns: the id of the serving, None if Serving does not ex...
32198ec978df268bfbfd328f4031593e0f53a38b
3,612,990
def ImageMLP_Imagenet16_Relu256x256x256(): """A 3 hidden layer MLP trained on 16x16 resized imagenet.""" datasets = image.imagenet16_datasets(batch_size=128) return _MLPImageTask(datasets, [256, 256, 256])
819d08976fa9479f4d51aaf6e40fe3eb1334aef3
3,612,992
def _ros(veos, vpos, eos, pos): """ ROG = Rate of Senescing (Days) """ return (veos - vpos) / (eos - pos)
6a944f9c7719866fcd862f8d4b9f088d277b48aa
3,612,993
def bollinger_lband_indicator(close, n=20, ndev=2, fillna=False): """Bollinger Low Band Indicator Returns 1, if close is lower than bollinger low band. Else, return 0. https://en.wikipedia.org/wiki/Bollinger_Bands Args: close(pandas.Series): dataset 'Close' column. n(int): n period. ...
3336001233ab4055ba0a867dd698878a271faf53
3,612,994
def _create_missing_method(name): """Create a drop-in callable for a missing role method with the given name.""" def bridge(roles, compound, *args, **kwargs): return proceed(name, roles, compound, *args, **kwargs) return bridge
ffbca1da0748091c3fa24ad3ec927e047f64b07c
3,612,996
def werCalc(s1, s2): """ Computes the Word Error Rate, defined as the edit distance between the two provided sentences after tokenizing to words. Arguments: s1 (string): space-separated sentence s2 (string): space-separated sentence """ s1 = s1.lower() s2 = s2.lower() # b...
ea3738f96496da2fc2d9f1a9a366f1c24a4302f4
3,612,997
def not_found_error(error): """404 Page Missing handling""" if wants_json_response(): return api_error_response(404) return render_template('errors/404.html'), 404
ed48f02611ac8cc45b69ac7209be61d9a01398ec
3,612,998
def read_general_arr(fpath, txt=True, compress=False): """ Reads general data array (txt, npy, or compressed npz) """ if txt: assert not compress return np.loadtxt(fpath, delimiter=',') else: X = np.load(fpath) if compress: return X['a'] else: ...
86904cbb619eaa350f458cb26321756333531d8f
3,612,999
import time def timer(fcn): """Returns the runtime in ms of the function fcn""" def wrapper(*args, **kwargs): t0 = time.time_ns() res = fcn(*args, **kwargs) t = time.time_ns() - t0 print(f"{fcn.__name__}: {round(t * 10**-6, 1)} 'ms'") return res return wrapper
9a76c7222f9f427abdde9194535acdf9880a2807
3,613,001
def read_landmarks(f_landmarks): """ Reads file containing landmarks for image list. Specifically, <image name> x1 y1 ... xK yK is expected format. :param f_landmarks: text file with image list and corresponding landmarks :return: landmarks as type dictionary. """ landmarks_lut = {} ...
9c4bf6b405f4fb49ace8badb4b3151cc457bbf84
3,613,002
def parse_char(ch): """ 'A' or '\x41' or '0x41' or '41' '\x00' or '0x00' or '00' """ if ch is None: return None if len(ch) == 1: return ord(ch) if ch[0:2] in ("0x", "\\x"): ch = ch[2:] if not ch: raise ValueError("Empty char") if len(ch) > 2: r...
b3726d00839caf92b64d976ed447f8c1824efb9f
3,613,003
def validate_parameters(self, parameters, task_id=None): """Validate parameters generated by the parameter parsing task All validation should be done here - are there data restrictions? Combinations that aren't allowed? etc. Returns: parameter dict with all keyword args required to load data. ...
98e8e67d192dcc791c6585f76410bc516d88c4ae
3,613,004
def Get_Entry(): """ get the entry number of customers at every minute """ df['timestamp'] = df.index.time time_spent = df.groupby(['weekday','customer_no'], as_index=False).agg({'timestamp':'min'}) time_spent.head() entry = time_spent.groupby('timestamp').count() //5 entry['timestamp'] ...
e1760346b8b1852cfa0cb1a312d028d0a991b013
3,613,005
def revert_version(request, revision_id): """Roll back the object saved in a Version to the previous Version""" referer = request.META.get("HTTP_REFERER", "/") revision_obj = Revision.objects.get(pk=revision_id) revision_obj.revert() # revert all associated objects too msg = "Rolled back revision %...
70e7d541b2c700a88f0b718999acd4ca847b53a8
3,613,007
from typing import Optional from typing import Tuple def get_or_create_permission( session: Session, name: str, description: Optional[str] = None ) -> Tuple[Optional[Permission], bool]: """Get a permission or create it if it doesn't already exist. Returns: (permission, is_new) tuple """ p...
4a837f3ca9f5942368d75572b83de4f05e6d2c70
3,613,008
import json def trigger_oauth_expires_test(limit): """ Test data for IFTTT trigger bunq_oauth_expires """ result = [{ "created_at": "2018-01-05T11:25:15+00:00", "expires_at": "2018-01-05T11:25:15+00:00", "meta": { "id": "1", "timestamp": "1515151515" } ...
6f0bf5ed1f2749bf67d9068ac9eb85cc6fd86e17
3,613,011
def translate_subset_type(subset_type): """Maps subset shortcut to full name. Args: subset_type (str): Subset shortcut. Returns: str: Subset full name. """ if subset_type == 'max': model = 'best' elif subset_type == 'random': model = 'random' elif subset_typ...
ff40e230c403818b55897ff96bee131d0c687096
3,613,012
def mid2aud(n_mid): """Return an audio segment from a mid file and build a wav meanwhile""" m2a.FluidSynth().midi_to_audio(mid_dir + n_mid + '.mid', wav_dir + n_mid + '.wav') seg = AudioSegment.from_file(wav_dir + n_mid + '.wav') return seg
f3573736541125dbb75439c038371e796a05ea02
3,613,013
import json def lambda_handler(event, context): """ expected event: { "body-json" : {}, "params" : { "path" : {}, "querystring" : { "game" : "string" }, "header" : {} }, "stage-variables" : { } """ if type(event) is not dict: ...
2e20e4bd02bba3de2b3dc416bad58243357120a4
3,613,014
def open_file_on_worker(view): """Open the file on the worker process""" service = cli.get_service() if not service: return None service.open_on_worker(view.file_name(), view.substr(sublime.Region(0, view.size())))
4260a77791932ed95b1851411c06b06ccc7ccccf
3,613,015
def solar_offset(geom: Geometry, precision: str = "h") -> timedelta: """ Given a geometry compute offset to add to UTC timestamp to get solar day right. This only work when geometry is "local enough". :param precision: one of ``'h'`` or ``'s'``, defaults to hour precision """ lon = mid_longitud...
afab5f060516584866a9c0d1c954ecadf4aa850b
3,613,016
def bgr_to_y(image): """Convert a bgr image to grayscale. :param image: an image denoted by a numpy array, which is HWC, and channels are in gbr :type image: np.array :return: the grayscale image :rtype: np.array (with dtype np.float32), in range 0~255 """ image = image.astype(np.float32) /...
d556f3e02a434be9283615e9ac833e9368d65df5
3,613,017
import email def _create_email( to_field="to_user@test1.com", from_field="from_user@test2.com", subject="This is a test email", body="Almost empty text message", attachment=None, maintype=None, subtype=None, ): """ Builds and returns an ``email.message.EmailMessage`` instance w...
7a918c4b49b7f68707e88a329bdde52eced01b46
3,613,018
def by_user_recipe_id(user_id, recipe_id): """ Get Recipe owned by a user """ session = query_session.get_session() return session.query(Recipe).filter(Recipe.id == recipe_id) \ .filter(Recipe.user_id == user_id) \ .first()
26c6425982d62cd92f50a43f8690e81aef40b324
3,613,019
def Z_score(data): """ Z_score标准化 :param data: :return: """ x, y, z = data.shape def z_score(data): return (data - np.mean(data)) / np.maximum(np.std(data), 1 / 256) for i in range(z): data[:, :, i] = z_score(data[:, :, i]) return data
97c16a46209cee792e6fbfa6688b70d6b06e495f
3,613,020