content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import test def AddDeviceTest() -> bool: """Test of adding Devices to a DeviceGraph.""" t = test('AddDeviceTest') graph = DeviceGraph() ltd = LibraryTestDevice('ltd') sub1 = LibraryTestDevice('sub1') sub2 = LibraryTestDevice('sub2') sub11 = LibraryTestDevice('sub11') sub1.add_submodul...
cea4b956de967f27841a853008773c184bcb9992
50,500
def get_name(scoring): """Get name of score. """ if not isinstance(scoring, str): scoring = get_scorer(scoring)._score_func.__name__.replace('_score', '') return scoring.replace('neg_', '').replace('maximum_', 'max_')
13bc2be060213392f44f740dc2f959686176066c
50,501
def community_portal_policies_page_data(): """ This function pulls and returns all data required for the community portal stories page and returns a json of this information """ return json_loader('./database/raw_data/portal/policiesPageData.json')
d16f5c4e2aea136aef76037f032470cbc7330843
50,502
def retrieve_redcap_events(url, token, max_time=30): """Read the list of events from the REDCap instance using the API""" data = redcap_api_call(url, token, content='event', fields={}, max_time=max_time) # print("events: {}".format(data)) return data
4815a0f5dc147f0c8c742d2db003bd828a5f7f08
50,503
import torch from typing import Optional def global_to_local_space( points: torch.Tensor, cam_pose: torch.Tensor, device: Optional[torch.device] = None, _validate_args: bool = True ) -> torch.Tensor: """Transform points from global space to local space Args: points (torch.tensor): points in shape (b,...
bb3d391e361089889bb03929c9cd36a35ebb2da6
50,504
def quantization_model_or_class_factory(args, *, model=None, cls=None): """Return either converted model for quantization or a quantized version of the class passed""" if model is not None and cls is not None: raise AttributeError( "Pass either model or class to be converted for quantization...
66c0391def8acd79563cddb14f14b8d20e014a6c
50,505
def get_user(user_id): """Get user by ID""" app.logger.info( 'Starting show user id: {} of request: {}'.format(user_id, g.request_id) ) response = user_schema.dump(UserService().find_or_404(user_id)) app.logger.info( 'Response of show user id: {} with response: {} of request: {}'.f...
10f7b2cd6f7281d8e44feccb22af3c5d4d38a1e8
50,506
import numpy def check_type_force_float(x, name): """ If an int is passed, convert it to a float. If some other type is passed, raise an exception. """ if type(x) is int: return float(x) elif type(x) is not float and type(x) is not numpy.float64: raise TypeError("%r should be a...
23469a7f5aedd2c0ec30969413a31330a7028dfc
50,507
def platform2str(platform: str) -> str: """ get full platform name """ if platform == "amd": return "AMD Tahiti 7970" elif platform == "nvidia": return "NVIDIA GTX 970" else: raise LookupError
083e38f45db482c9fe6761c719df4bf0f5719256
50,508
def pdf_single_grid(request: HttpRequest, calendar_id: int): """A PDF grid from start date to end date with a given style and size""" cal = get_object_or_404(models.Calendar, pk=calendar_id) try: style_index = int(request.GET.get('style_index', 0)) size_index = int(request.GET.get('layout_...
a732e1af59a808f1a21b5d59c21c5477c50358df
50,509
import tempfile import os import google def obtain_api_credentials(s3_client): """ Creates HTTP headers credentialed for access to the Global.health Source API. """ try: fd, local_creds_file_name = tempfile.mkstemp() with os.fdopen(fd) as _: logger.info( "Re...
bc051f5c6b6906c93b02b495f3326cd76aecb3ae
50,510
def enable_tpoint_group(client, name): """Enable trace on a specific tpoint group. Args: name: trace group name we want to enable in tpoint_group_mask. (for example "bdev"). """ params = {'name': name} return client.call('enable_tpoint_group', params)
3ff809632e3db683792b4c1f686e52f4fddd993e
50,511
def tags_for_talks(conference=None, status=None): """ Return the used tags by talks, filtered by conferences and state of the talk """ talks = models.Talk.objects.all().values('id') if conference: talks = talks.filter(conference=conference) if status: talks = talks.filter(sta...
160ebbad248331f5771dcce3454dd14c87b14d30
50,512
from pydeconz import DeconzSession from unittest.mock import Mock from unittest.mock import patch async def setup_gateway(hass, data): """Load the deCONZ switch platform.""" loop = Mock() session = Mock() config_entry = config_entries.ConfigEntry( 1, deconz.DOMAIN, 'Mock Title', ENTRY_CONFIG,...
a43f0caab87c0eb4184fe274a42c8cb885739b3c
50,513
def ldl_fft(G): """Compute the LDL decomposition of G. Args: G: a Gram matrix Format: FFT Corresponds to algorithm 8 (LDL) of Falcon's documentation. """ deg = len(G[0][0]) dim = len(G) L = [[[0 for k in range(deg)] for j in range(dim)] for i in range(dim)] D = [[[0 for k ...
9261fa6b7bc37da0a1f03aa1adc501f88e015b93
50,514
def get_time_step_data(data_in, time_step): """ Sparses data file for time steps specified by user. Parameters ---------- data_in : Density Data to be condensed into time steps time_step : float Time steps requested. Returns ------- data_out : Density Data in sp...
59f2cf665d42f6214c19f6f51c6d50d672821bb9
50,515
def handle_command(command, event): """ Executes bot command if the command is known """ # Finds and executes the given command, filling in response for cmd, callback in command_mapping.items(): if command.lower().startswith(cmd): # command cleanup command = command.r...
34ede12a632595d7d50593014e7019dd06dc6163
50,516
def select_from_context(context: TreeContext, criterion: CriteriaType, reverse: bool=False): """Yields all nodes from context which fulfill the criterion.""" return select_from_context_if(context, create_match_function(criterion), reverse)
d2ee05eb0e1f630d6c6ce96661b21bab1cd62a88
50,517
def combat_batch_correction(data, batch_col, index_cols): """ This function corrects processed data for batch effects. For more information visit: https://pypi.org/project/pycombat/ :param data: pandas dataframe with samples as rows and protein identifiers as columns. :param batch_col: column with the b...
2c54f1c64d737b03b357201d91e757d39698031c
50,518
def keyfunc(line): """Return the key from a TAB-delimited key-value pair.""" return line.partition("\t")[0]
39737389cd7a9e8046ff00700004b8864a242914
50,519
from typing import List from typing import Optional import logging def calculate_average_face_encoding( face_encodings: List[List[np.ndarray]], ) -> Optional[np.ndarray]: """ Calculates the average face encodings with numpy.mean() method. :param face_encodings: List of image face encodings """ ...
cf0ac7f92a67e734dd3be07aeed95774f8fa384a
50,520
def make_error_extraction_tests(get_messages): """ Create a test case class for testing extraction of fields from exceptions. @param get_messages: Callable that takes an exception instance, returns all message dictionaries generated by logging it. @return: ``TestCase`` subclass. """ c...
87546535a18703a3ee49d55ef3e64589564d0048
50,521
def lambda_handler(event, context): """ Lambda Handler (webhook via api gateway) """ update = telebot.types.Update.de_json(event["body"]) bot.process_new_updates([update]) return { "body": "ok", "statusCode": 200, "headers": {"Content-Type": "application/json"}, }
1d3a2d594d8059bc0cae2a2929257ad09ec6e3e5
50,522
def html_wrap(html_string): """Add an html-head-body wrapper around an html string.""" html_prefix="""<html> <head> <title>HTML CSS TESTS</title> <link rel="stylesheet" type="text/css" href="tests/manual html-css tests/html-css.css"> </head> <body>""" html_pos...
8510549f4de1de25ac98361f757210eafdb02631
50,523
import collections import time import tqdm def onpolicy_trainer(policy, train_collector, test_collector, max_epoch, step_per_epoch, collect_per_step, repeat_per_collect, e...
dcc6c2bc5b0aeb2a89045dd6260e2f146fa2bc5e
50,524
def split(ary, n): """Given an array, and an integer, split the array into n parts""" result = [] for i in range(0, len(ary), n): result.append(ary[i: i + n]) return result
27ae4f06603de17c993656fae9df07b61f333474
50,525
import textwrap import tempfile import click import os import shutil def default_to_test(app: Application): """Transfer Data From Default To Test""" temp_dir = tempfile.mkdtemp() try: # Convertion Contexts cvt_ctxs = [ AttrDict( { "file_nam...
59235edbc4d381256e2ce6043e7d20e671cc70d2
50,526
def get_blog_name(url: str) -> str: """get the name of the blog""" path = urlparse(url).path if path.endswith("/"): return path.split("/")[-2] + ".md" else: return path.split("/")[-1] + ".md"
bd281fba9fd0709d0967da8fc0201c16e2962b07
50,527
def fget_preds(subdict, limit_date=False, lcompdate=None, ucompdate=None): """ stack predictions over ensemble runs get predictions and targets from runs shape: (90, 20729, 3) (n_ensemble_runs, n_windows, H) limit_date to crop for comparison with cls, esa etc. """ # shorter lookbacks have m...
6c15d7c56c849da79aa027d9c8a842b837e55c8a
50,528
import os def gen_popden_feat(input_raw="./data/raw/popden/", output_folder="./data/features/popden", handicaps=None, remove_over=False): """This function process the raw CSV file with all the world's population density and creates the output CSV file wi...
0203cf97d918ff0cc20426e2abe58983be751a9d
50,529
def entity_is_available(hass: HomeAssistant, entity: str): """evaluate whether an entity is ready for targeting""" state = hass.states.get(entity) if state is None: return False elif state.state == STATE_UNAVAILABLE: return False elif state.state != STATE_UNKNOWN: return True...
eeb517f528d13ba886b1ced4c99ca70f3d3110d7
50,530
def preview_model(request, content_app, content_class, content_id, preview_mode='default', load_dynamic_element=False): """ preview_model """ model_class = apps.get_model(content_app, content_class) form_class = modelform_factory( model_class, fields=[field.name for field in model_...
070a8a4196f23a721dcdfdf597cd7bece46f902c
50,531
def is_valid_word_array(words_to_check): """ --------------------------------------------------------------------- DESCRIPTION Checks if the words in the word (string) array are part of the dictionary. --------------------------------------------------------------------- PARAMETERS words...
4e2fc556b47b56f9fda859b33593c0c06592bb9b
50,532
from operator import invert def _polydetrend_get_trend(da, *, dim, degree, preserve_mean, kind): """Polydetrend, atomic func on 1 group.""" if len(dim) > 1: da = da.mean(dim[1:]) dim = dim[0] pfc = da.polyfit(dim=dim, deg=degree) trend = xr.polyval(coord=da[dim], coeffs=pfc.polyfit_coeffic...
7a6c02fae18ddcea42828e7cc9fce3f7f110eb6d
50,533
def image_function(f='sin(x)*cos(y)', xmin=-1, xmax=1, ymin=-1, ymax=1, xsteps=100, ysteps=100, p="x,y", g=None, **kwargs): """ Plots a 2-d function over the specified range f takes two inputs and returns one value. Can also be a string function such as sin...
4d93dbf5ecaa71b0e6b4b4f9945209a2f16718b4
50,534
def manager(manager_maker): """ return an uninitialized AccountManager instance. """ return manager_maker(addid=False)
7557829687f7368a20fd52b6cba84a1c236b6ed8
50,535
def tcp_to_udp_data(d): """ Trim TCP packet to send it over UDP. :param d: (bytes) TCP DNS response :return: (bytes) UDP ready DNS response """ d = d[2:] return d
efdddfe8aaa9443b2fd2c194401708a12a6b2389
50,536
import types from typing import Tuple def coda_duration( tr: obspy.Trace, noise: float, ptype: str, cfg: types.ModuleType = config ) -> Tuple[float, float]: """Measure duration and associate quality control Args: tr: time series noise: noise level ptype: plo...
71e9173ddcd33af5335f47c83a9cb7b86948d71e
50,537
import multiprocessing import os import logging def seq_alignment_mask(base_dir, dada2_filtered_rep_seqs, cpu_count=None): """ :param base_dir: Main working directory filepath :param dada2_filtered_rep_seqs: DADA2 filtered representative sequence object :param cpu_count: Number of CPUs to use for anal...
a2db8b6039f35e32e6fd9ae086fd671a756dd6dc
50,538
def list_smc_files(path): """Lists all SMC files in a directory""" files = util.list_files(path, ".smc.gz") files.sort(key=get_smc_sample_iter) return files
edd4199ab1c88cc57c725708d1edefd48f1e41e6
50,539
import math def encMethodSave5(file, picture): """Save an picture to a file.""" file.writeBytes(bit32.rshift(picture[0], 8), bit32.band(picture[1], 0xff)) for i in range(2, len(picture), 4): file.writeBytes(color.to8Bit(picture[i]), color.to8Bit(picture[i+1]), math.floor(p...
83df364b62312c4d7def5b8f05fa9cb002230875
50,540
import json def get_settings(lang, mode): """Get the makefile settings.""" schema_json = make_schema(lang, mode) error = None try: settings = json.loads(request.values.get('settings', '{}')) except: log.exception("Error in json parsing the settings variable") error = escap...
4fd356040d811270ad569314da5d7e24049e2a42
50,541
import typing def vectorFactorization(vec: np.ndarray) -> typing.Tuple[np.ndarray, np.ndarray]: """I have probably reinvented a wheel. I have searched the Internet and haven't found this kind of factorization. Factors a vector vec into the product of an "upper-triangular-like" (mostly upper triangular, but with hol...
dafa2fa9452eb56777d29e555ccdaa0ff813c636
50,542
def random_funfact(): """Returns random funfact or None.""" if FunFact.objects.published().count(): return FunFact.objects.random() return None
296845df7553d3020be42f991f3cd0f6a887db04
50,543
def combine_results(results_list): """ Given different metrics based on the result lists provided. Inputs: results_list: dictionary containing the lists of all the results Returns: results_overall: dictionary containing the lists of all the results now with additional perfo...
0ce31b6f8ed226d9930173aa4cd4b83289b576b1
50,544
def files_permission_factory(obj, action=None): """Permission for files are always based on the type of record. Record bucket: Read access only with open access. Deposit bucket: Read/update with restricted access. """ # Extract bucket id bucket_id = None if isinstance(obj, Bucket): ...
6a565d45d2ff404ad4d9c9536c60e0595d131884
50,545
from typing import Optional def _generate_perfect_bst(height: int) -> Optional[Node]: """Generate a perfect BST (binary search tree) and return its root. :param height: Height of the BST. :type height: int :return: Root node of the BST. :rtype: binarytree.Node | None """ max_node_count = ...
f8fa91d06cde895697d515130c0fa17e62e4ba8b
50,546
import os def conference_title(): """Get conference title from environ variable""" return os.environ.get('CONFERENCE_TITLE', None)
adb13a2565f31af8d273690be10d5d39bcb709d4
50,547
def create_plotting_parameters_for_normal_distribution(mean, variance, num_std_dev_to_plot=3): """Create parameters to easily plot a normal distribution Arguments: mean {float} -- Mean of the normal distribution variance {float} -- Variance of the normal distribution """ sigma = sqrt(v...
00525affd974b2698661e1009cfb26b5ebd9df70
50,548
def create_skelgraph(R: nx.Graph, H: nx.DiGraph) -> nx.Graph: """Create a "skelgraph" from a bdc world `H` and its reeb graph, `R`. A skelgraph is a graph of the straight skeletons of each cell of a world `H`, joined by the midpoints of each cell wall on `H`. Traversing the skelgraph of `H` means visit...
7dc500e93b8d2a8d8831cd3d9a591466e55ee72c
50,549
def apply_bounds(grid, lVec): """ Assumes periodicity and restricts grid positions to a box in x- and y-direction. """ dx = lVec[1,0]-lVec[0,0] grid[0][grid[0] >= lVec[1,0]] -= dx grid[0][grid[0] < lVec[0,0]] += dx dy = lVec[2,1]-lVec[0,1] grid[1][grid[1] >= lVec[2,1]] -= dy gri...
34411b7cc1062ade4d45c922225a3364a6c84180
50,550
def is_ericsson_2g_supported(): """ Check if Ericsson 2G is supported :return: string parse_and_import_ericsson_2g | ericsson_2g_not_supported """ if bts_utils.is_vendor_and_tech_supported(1,1) is True : return 'ericsson_2g_supported' else: return 'ericsson_2g_not_supported'
fc48a6b18a800ae2795a8c9c333ab5b9cbc96f94
50,551
def check_env_vars(env_vars): """Checks if the env variables are set as required to run the test. Returns: True if all the env variables are set as required, otherwise False. """ if not env_vars: return True for key in env_vars: if env.get_env(key) != env_vars.get(key): return False retu...
70dc52308cfd049df02c16fd39d669398ac64008
50,552
def custom_sobel(shape, axis): """ shape must be odd: eg. (5,5) axis is the direction, with 0 to positive x and 1 to positive y """ k = np.zeros(shape) p = [(j,i) for j in range(shape[0]) for i in range(shape[1]) if not (i == (shape[1] -1)/2. and j == (shape[0] -1)/2.)] ...
cbf93d623c48c6a26a65862d1cdaca3cb25c8706
50,553
def _check(edges): """Check consistency""" res = True for src, dsts in edges.items(): for dst in dsts: if dst not in edges: print('Warning: edges[%d] contains %d, which is not in edges[]' % (src, dst)) res = False return res
e97a72e31fc99fdf35e3302ab7a6216d7cab924d
50,554
def getParserFile(theHelp, theEpilog=""): """ Get a commandline parser with the defaults of the commandline utils and a list of source files. """ parser = _getParser(theHelp, theEpilog) parser.add_argument("FILE", nargs='+', help="Input file") return parser
a93bf7b5c02da6387116e0ea91a1c3acca7b8d74
50,555
import six def from_pci_stats(pci_stats): """Create and return a PciDevicePoolList from the data stored in the db, which can be either the serialized object, or, prior to the creation of the device pool objects, a simple dict or a list of such dicts. """ pools = [] if isinstance(pci_stats, six...
4a5d3ad396b4677462b9cb698506ef8623c5b78e
50,556
def _cloned_intersection(a, b): """return the intersection of sets a and b, counting any overlap between 'cloned' predecessors. The returned set is in terms of the entities present within 'a'. """ all_overlap = set(_expand_cloned(a)).intersection(_expand_cloned(b)) return set(elem for elem in ...
7c7323a736fa2a9cfc45e07a7197c9245f986953
50,557
def validate(number): """Checks to see if the number provided is a valid EIN. This checks the length, groups and formatting if it is present.""" match = _ein_re.search(clean(number, '').strip()) if not match: raise InvalidFormat() get_campus(number) # raises exception for unknown campus ...
efcaf58702eb7b980275185e7723727b60ecc70f
50,558
import math import asyncio async def search(query_expr: str) -> str: """Search issues and PRs, the query_expr is an expression that GitHub search supports such as 'org:some_org label:some_label'.""" response = await _search(query_expr) items = [_map_search_item(item) for item in response.get("items")]...
9944beb2c500fd88ceb8a37a3f82c6bcef2f0350
50,559
import os def post(request, size, page): """ Route: /api/v1/search See config/api.yml for OpenAPI specification. :param request: JSON body :param size: int :param page: int :return: """ logger.info("Received search request: '{}'.".format(request)) # Check that paths are valid ...
471b9d80375135250ac2f0cc57bd29fe666fe032
50,560
import html def view_the_log() -> 'html': """Display the contents of the log file as a HTML table.""" contents = [] with open('vsearch.log') as log: for line in log: contents.append([]) for item in line.split('|'): contents[-1].append(escape(item)) title...
b14ba57767271056e58df7abb33761339399aeed
50,561
def fdr_rvalue(p1, p2, m, c2=0.5, l00=0.8): """Function for computing FDR r-values using the method suggested by Heller et al. Input arguments: ================ p1, p2 : ndarray [n_tests, ] The p-values that were selected for follow-up from the primary study (p1) and the correspondi...
1a0b0330c831a8e8756011142dc6632eca0321cf
50,562
def matches_filter(graph, props): """ Returns True if a given graph matches all the given props. Returns False if not. """ for prop in props: if prop != 'all' and not prop in graph['properties']: return False return True
8d53f198b7ad1af759203909a05cd28916512708
50,563
import torch def goal_pred_loss(grasp_pred, goal_batch, huber=False): """ PM loss for grasp pose detection """ grasp_pcs = transform_control_points( grasp_pred, grasp_pred.shape[0], device="cuda", rotz=True ) grasp_pcs_gt = transform_control_points( goal_batch, goal_batch.shape[0], device="cuda", ...
617a1c2c563e0fdafb4d1281093da2503df820d3
50,564
import os import html def generateIMSManifest(data): """ parse data from config file 'toIMSconfig.json' and recreate imsmanifest.xml """ # create magic yattag triple doc, tag, text = Doc().tagtext() # open tag 'manifest' with default content: doc.asis('<?xml version="1.0" encoding="UTF-8"?><manife...
ce412104e9937ae1a2f24a595d2844161b9a7ad3
50,565
def biweight_midvariance(a, c=15.0, M=None, axis=None, eps=1e-8, niter=1): """ Copyright (c) 2011-2016, Astropy Developers Compute the biweight midvariance for an array. Returns the biweight midvariance for the array elements. The biweight midvariance is a robust statistic for determining ...
19099001dedba03d6560acb172fa5bfa7d1ffcec
50,566
def card_dealer(cards_dealt, players=1, deck="standard", decks_number=1): """ This function return randomly dealt cards for defined number of players. Args: * `cards_dealt` : number of cards for each player (int) * `players` : number of players Kwargs: * `deck` : options are: * `st...
dd86dc8bbb7ede5a10f8ab75d08e4fd42af196a9
50,567
from typing import Optional def _debug_options(args) -> Optional[rdcp_command.RDCPCommand]: """[crashdump | dpctrace] [...] If no arguments are given, retrieves the currently active debug options. If at least one argument is given, enables that debug option and disables any options that are not given. ...
46389d434459563d8fe6f1b8500a05ac86d6563c
50,568
import json def vulndata(note, parsed_cpe, cve, namelen): """project vulndata object""" data_id = md5( f'{note.host.address}' f'|{note.service.proto if note.service else None}' f'|{note.service.port if note.service else None}' f'|{cve["id"]}'.encode() ).hexdigest() da...
00cdfb44daa80b7d149969746197f79997bfcdec
50,569
def plane_face_intersection(a,b,c,d,face): """ Finds the intersection line of a plane with the face of a solid. Returns the two points that make up the line of intersection. a,b,c,d are the coefficients of the plane ax+by+cz=d while face is a sequence of points which form the plane. args:...
2a731eeee51745bde9fa39bf992ac3085e5845fa
50,570
import requests from bs4 import BeautifulSoup def url2table(url): """From an url given, extract only the 'rangkingTable' using beautifulsoup""" logger.info('url2table') response = requests.get(url) page_html = response.text soup = BeautifulSoup(page_html, 'html.parser') rangkingtable = soup.fi...
326a7ece3cf6bb45688c3cb5aeef4dc5c689442a
50,571
def max(msg, out): """Builtin reduce function that aggregates messages by max. Parameters ---------- msg : str The message field. out : str The output node feature field. Examples -------- >>> import dgl >>> reduce_func = dgl.function.max(msg='m', out='h') The ...
2dc11960e2241b9fdb68ce0a524ba193695f8cf8
50,572
def get_popularity(obj, region=None): """ Returns popularity value for the given obj to use in Elasticsearch. If no region, uses global value. If region and region is not mature, uses global value. Otherwise uses regional popularity value. """ return _property_value_by_region(obj, region=r...
5d66c573fe4b97891c2a266b0ae508fec9abb35e
50,573
def feature_importances_plot(model, labels, **kwargs): """ Calcola l'importanza normalizzata delle variabili di un modello restituendo i dati e mostrando il plot. ----------- Parametri: model : modello di scikit-learn labels : list | np.array lista delle labels delle variabili ...
fd3486eb3e0d7b1a56a1f68c14c9ff0abe21ecdb
50,574
from typing import List from typing import Any from typing import Union import re def human_sort_key(key: str) -> List[Any]: """ Function that can be used for natural sorting, where "PB2" comes before "PB10" and after "PA3". """ def _convert(text: str) -> Union[int, str]: return int(text) ...
31c163250f5b040b18f3f2374825191ce3f61ff4
50,575
def clean_line_count_output(out): """Clean shell output into list based records""" record = [] count_lines = out.split(b"\n") #import ipdb;ipdb.set_trace() for line in count_lines: if line: line = line.split() log.debug(len(line)) if len(line) == 4: ...
64fef5593f65f0930a7162e786250567453b904f
50,576
def ParseColSpec( col_spec, max_parts=framework_constants.MAX_SORT_PARTS, ignore=None): """Split a string column spec into a list of column names. We dedup col parts because an attacker could try to DoS us or guess zero or one result by measuring the time to process a request that has a very long colum...
8bc1ff31ea5ed2e8ef58bc1d97f3d0109f55ff6d
50,577
def get_class(class_string): """ Returns class object specified by a string. Arguments: class_string -- The string representing a class. Raises: ValueError if module part of the class is not specified. """ module_name, _, class_name = class_string.rpartition('.') ...
a25573ac9cb6115e0b8ad1d28a286f86628d8235
50,578
import hashlib def flip_bloom_filter(string: str, bf_len: int, num_hash_funct: int): """ Hash string and return indices of bits that have been flipped correspondingly. :param string: string: to be hashed and to flip bloom filter :param bf_len: int: length of bloom filter :param num_hash_funct: in...
c245637b86cc16b68d069bf2359b1e5c7483a8fc
50,579
def multiclass_metrics(pred, gt): """ check precision and recall for predictions. Output: overall = {precision, recall, f1} """ eps=1e-6 overall = {'precision': -1, 'recall': -1, 'f1': -1} NP, NR, NC = 0, 0, 0 # num of pred, num of recall, num of correct for ii in range(pred.shape[0]): pred_ind = n...
c8394e2240be1734e387774e4a2bad0620ad4b94
50,580
def positionLogicPlan(problem): """ Given an instance of a PositionPlanningProblem, return a list of actions that lead to the goal. Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST} Note that STOP is not an available action. """ walls = problem.walls width, height = problem.getWi...
c57bb84ff0ddd1a54648b507358d13adbce79f70
50,581
from typing import Any def dataset_from_csv(csv_path: str, **kwargs) -> Any: """ Load dataset from a CSV file using Pandas. kwargs if any are forwarded to the `pandas.read_csv` function. Parameters: csv_path (str): Path of the CSV file to load dataset from. Returns: A...
4f950bc32137861a2a7a556ab6167b5d7b324611
50,582
def quick_sort(array, left: int = 0, right: int = None): """ Quick sort algorithm. :param array: the array to be sorted. :param left: the left index of sub array. :param right: the right index of sub array. :return: sorted array >>> import random >>> array = random.sample(range(-50, 50)...
11b97e008ac9e108a9aac77462fe9f093876c2c4
50,583
def calc_class_metrics(all_preds, all_labels, metric_type="group", span_type="exact"): """ Calculates a set of metrics for each class. :param all_preds, all_labels: A list of list of groups. If metric_type == "joint", the groups should in joint form with an "entities" key :param metric_type: A stri...
873d430596d4cc920fff0c3d8b506edee55a821c
50,584
def convert_to_text(web3, data): """ :param web3: :param data: :return: """ return web3.toText(data)
09f05e836978b38de2246b83e5d992738e83e546
50,585
def CallableParamRegistry(): # noqa: N802 """Callable registry with a keyword parameter.""" class CallableParamRegistry: registry = Registry('kwparam') return CallableParamRegistry
9171de2669d232ab80cc474e063918b8a4a5979d
50,586
def largest_product(product_list): """Find the largest product from a given list.""" largest = 1 for products in product_list: if largest < max(products): largest = max(products) return largest
7f9f2b151afc7d0e35203a5dda665ef100279c65
50,587
def shapes_equal_trailing(*shapes): """Test if shapes are equal, starting from trailing end, except for leading ones.""" for lengths in zip_longest(*[shape[::-1] for shape in shapes], fillvalue=1): if not all(length == lengths[0] for length in lengths): return False return True
bac06c7928f8ad65c34eac189dca33edb558ad8d
50,588
import os import stat def is_executable(path): """Tests if the specified path corresponds to an executable file. This is, it is a file and also has the appropriate executable bit set. :param path: Path to the file to test. :return: True if the file exists and is executable, False otherwise. :rtyp...
0926b6118688892db7446dadafa19c300ff29212
50,589
def generate_indices_filename(max_length, vocab_size, seed, inference, step3, set_type, multi_task, multi_task_lambda, disabled_properties): """ Generates a filename from baseline params (see baseline.py) """ name = f'{generate_unique_filename(max_length, vocab_size, seed, inference, step3, set_type, mu...
296c8c3f0654ccd0893d9449b9752402ba97a66e
50,590
import itertools def get_separable_problems(problem): """Return a list of separable problems whose sum is the original one. Parameters ---------- problem : Problem A problem that consists of separable (sub)problems. Returns ------- List A list of problems which are separa...
c823daa7926142c7717b07831fe3f3f6d8157f8c
50,591
def _padded_size(size, padding_multipe=8): """ Return the size of a field padded to be a multiple a give value. """ return int(ceil(size / padding_multipe) * padding_multipe)
95339d88bfa86ac5f84934c086318d7f112c485a
50,592
def add_api_component(logger, name, event_dict): """ Adds the component to the entry if the entry is not from structlog. This only applies to the API since it is handled by external WSGI servers. """ event_dict["component"] = "API" return event_dict
d510d8eb563ffd3b819abd3ec970790ed9d30083
50,593
def make_plans(*by_key, **plans): """ Given by_key which is a list of strings and plans which is a dictionary of key to plan, return a dictionary of key to plans. We will complain if: * A key in by_key is not a registered plan * A key in by_key is also in plans """ if not by_key and no...
0687cf74930143078657dcf391a8552a91e29478
50,594
def split_list(l, split, density=None): """ Splits a list into part a of b split should be a string of the form 'a/b'. For instance, '1/3' would give the split one of three. If the length of the list is not divisible by the number of splits, the last split will have more items. `density` ...
821876bef0034bd7017bc0436a9d85a4defae92b
50,595
def load_files(proof_fnames): """ From a list of XML filenames that contain a <proof> node, it returns a list of lxml root nodes. """ roots = [] parser = etree.XMLParser(remove_blank_text=True) for fname in proof_fnames: docs = etree.parse(fname, parser) roots.append(docs) ...
29ead39fedb4541fc116bd791687dc48db901915
50,596
def encoding(mctx, x): """File can be successfully decoded with the given character encoding. May not be useful for encodings other than ASCII and UTF-8. """ # i18n: "encoding" is a keyword enc = getstring(x, _("encoding requires an encoding name")) s = [] for f in mctx.existing(): ...
ece2169da87867254250b81c8518f46a50f29dd5
50,597
import random def shuffle_string(s: str) -> str: """ Mixes all the letters in the given string Parameters: s(str): the string to shuffle Returns: str: string with randomly reordered letters Examples: >>> shuffle_string('abc') 'cba' >>>...
9c68b276f539d6385e5393cb92fa971fbb6059d4
50,598
def get_data(input_text: str) -> list[Line]: """ returns list of Line objects """ lines = [Line.from_string(line_str) for line_str in input_text.splitlines()] return lines
4f910f080b3fbf8f43ea3ff2abf23f2087db32fa
50,599