content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Sequence from typing import List from typing import cast def try_rules( context: Sequence[Expression], goal: Expression, general_rules: Sequence[Expression], verbosity: int = 0, ) -> List[Expression]: """context and context_rules are disjoint, all in context_rules satisfy is...
6bfe3b3e46d5591f3a68ab9d6cf68eeacf4f8ca2
3,612,555
def dissimilarity_loss(latents, mask): """ Minimize the similarity between the different instrument latent representations Arguments: latents {torch.tensor} -- latent matrix from the encoder of shape: (B, 1, T', N) mask {torch.tensor} -- boolean mask: True when the signal is 0.0; shape (B, ...
988e86a535f70425975f178c3dbcd396b340990e
3,612,556
def _stdin_ready_other(): """Return True, assuming there's something to read on stdin.""" return True
934e97ba18f9f60ad8e2d77f227dd98b70891b56
3,612,557
def text_objects(text, font, color): """ Function for creating text and it's surrounding rectangle. Args: text (str): Text to be rendered. font (Font): Type of font to be used. color ((int, int, int)): Color to be used. Values should be in range 0-255. Returns: Text surf...
a9ed3d8a68c80930e2594b4dbef06e828de10513
3,612,558
from typing import List def split_list(a: List, chunk_size: int): """ split a large list to small chunk with the specified size :param a: :param chunk_size: :return: """ chunks = [] list_length = len(a) start_pos = 0 end_pos = start_pos + chunk_size while end_pos <= list_l...
24ec6e5c2a86deabb4abb9fd1c8e6a0f86cfb7ed
3,612,559
def process_results(news_list): """ Function that processes the news result and transform them to a list of Objects Args: news_list: A list of dictionaries that contain news sources Returns : news_results: A list of news objects """ news_results = [] for news_item in news_l...
0d2f5b3ca85d7b6aec770bc71de9f1ef749915d7
3,612,561
def slice_slice(old_slice, applied_slice, size): """Given a slice and the size of the dimension to which it will be applied, index it with another slice to return a new slice equivalent to applying the slices sequentially """ step = (old_slice.step or 1) * (applied_slice.step or 1) # For now, u...
97cbf20100da58e3d6712b7fa9d9a2fb04c3322f
3,612,562
import re def _parse_compile_log(log): """parses the pdflatex compile log""" if log is None: return {} IMAGES = {} i = 0 image_found = False for line in log.split('\n'): if not image_found: m = re.match("^File: (.*) Graphic file", line) if m: ...
a3888ed3d2664866d47265f2c06720a8a3e757df
3,612,564
def is_correct(list): """ 判断一个list中单词是否正确 :param list:待识别的单词列表 :return: 正确的单词列表 """ temp = [] rightlist = spell.known(list) # {'morning'} global count global num count = count + len(list) - len(rightlist) num = num + len(list) for item in rightlist: temp.append(item)...
2a0e09b009c13b03810979c903969e2b4719879c
3,612,565
def spellcheck(request): """ Spellcheck some POST data. """ jsondata = request.POST.get("data") print "Spellcheck data: %s" % jsondata if not jsondata: return HttpResponseServerError( "No data passed to 'spellcheck' function.") data = json.loads(jsondata) aspell =...
80f50c26f4f777499018af02e8ad2939d0eb1af2
3,612,566
def contains(value, lst): """ (object, list of list of object) -> bool Return whether value is an element of one of the nested lists in lst. >>> contains('moogah', [[70, 'blue'], [1.24, 90, 'moogah'], [80, 100]]) True """ found = False # We have not yet found value in the list. for i in...
9d3690943c05b4220afabfa65402b7f12c1cb279
3,612,567
import re def filter_component_names(raw_npm_list): """Filter the raw NPM list to get list of proper component names.""" pattern = re.compile("^[0-9]+.") components = [] for line in raw_npm_list.splitlines(): if pattern.match(line): try: i1 = line.index("[") ...
7d8a102781a32ddd263d1c4364f261e6f1191e70
3,612,568
def dispImg(img): """ This does the min-max scaling the images to 0 and 1 """ try: h, w, d = img.shape img_tmp = (img - np.min(img)) / (np.max(img) - np.min(img)) plt.matshow(img_tmp) plt.show(block=False) except ValueError: try: h, w = img.shape ...
b93bcbd644026cbb51082a2a3314d2340f8db278
3,612,569
import urllib def download_metadata_file_for_1minute_data(metadatafile: str) -> BytesIO: """ A function that simply opens a filepath with help of the urllib library and then writes the content to a BytesIO object and returns this object. For this case as it opens lots of requests (there are approx 1000 differ...
9fafc7c72c2b35055bbcc62b60254c01e442233d
3,612,571
def check_format_input_obj( inp, allow: str, recursive=True, typechecks=False, ) -> list: """ Returns a flat list of all wanted objects in input. Parameters ---------- input: can be - objects allow: str Specify which object types are wanted, separate by +, ...
306075bc72c1f79dc1e47997b8bcee33a3ee240f
3,612,572
def sleeper(sleep_time): """ Function to execute in parallel. """ sleep(sleep_time) return {"sleep_time": sleep_time}
4b158988eefc6300d02e2c1f110bfb842b0f3679
3,612,573
import random def construct_sent(word, table): """Prints a random sentence starting with word, sampling from table. >>> table = {'Wow': ['!'], 'Sentences': ['are'], 'are': ['cool'], 'cool': ['.']} >>> construct_sent('Wow', table) 'Wow!' >>> construct_sent('Sentences', table) 'Sentences ar...
238a0391b104d15db50d33904308c827851ffb62
3,612,576
def process_sources(source_list): """ We now want to process the dictionary and output a list of objects - news_results. We process results will transform our dictionary into a list of objects. """ news_results = [] for source in source_list: id = source.get('id') print(id) ...
47f5acfb5e98ca71b8c2605cb38229ba910d4b36
3,612,577
def _preprocess(expr, func=None, hint='_Integral'): """Prepare expr for solving by making sure that differentiation is done so that only func remains in unevaluated derivatives and (if hint doesn't end with _Integral) that doit is applied to all other derivatives. If hint is None, don't do any different...
49ff4fdce77f64a9e1f48d46b09452f88a8fcd1f
3,612,578
def read_lisp_filter(path): """Reads a lisp filter from a file. For example: (> (/ (+ (- (field "00000") 4.4) (field 23) (* 2 (field "Class") (field "00004"))) 3) 5.5) """ return read_description(path)
411027ca42d6e81bc149ab1186bed5c21212195e
3,612,579
def team_games(results, team='Northeastern'): """ Collect all games by given team. Parameters ---------- results : TYPE DESCRIPTION. team : TYPE, optional DESCRIPTION. The default is 'Northeastern'. Returns ------- teamGames : TYPE DESCRIPTION. """ ...
93a7260cdb97cd1ac19348af3908010905953e6c
3,612,580
def get_dataset_phase(prefixf): """ Return the execution time dataset from a folder "prefixf" and return the execution time for the phases Also filter out the zero values. """ #start_time = timeit.default_timer() tmp = pd.read_csv(prefixf+"/dataset_ph1.cs...
759773a4ad4d5438d85526351c0cbaac30d3e89c
3,612,582
def UnbiasPmf(pmf, label=''): """Returns the Pmf with oversampling proportional to 1/value. Args: pmf: Pmf object. label: string label for the new Pmf. Returns: Pmf object """ new_pmf = pmf.Copy(label=label) for x, p in pmf.Items(): new_pmf.Mult(x, 1.0/x) ...
1146d952bbac0ef3031e3259d98e0f343103598e
3,612,584
def constant_init(value=0): """ Constant Initializer The resulting tensor is populated with values of type dtype, as specified by arguments value following the desired shape. The argument value can be a constant value, or a list of values of type dtype. If value is a list, then the length of the l...
fc9788f68a9fe3a2bd96b52ff2c153a237ce6bb2
3,612,585
def ConfusionMatrix(ftrue, fpred, nf): """ CONFUSION MATRIX Computes the confusion matrix of a discrete classification. Written by Dario Grana (August 2020) Parameters ---------- ftrue : array_like true model fpred : array_like predicted model nf : int nu...
332fa870544a3bbcfc842a78e6840837ed19a0ab
3,612,586
def drop_na_1d(df, axis=0, how='all'): """ :param df: :param axis: int; :param how: :return: """ if axis == 0: axis_name = 'column' else: axis_name = 'row' if how == 'any': nas = df.isnull().any(axis=axis) elif how == 'all': nas = df.isnull().al...
c321191150208cddc49a150aa08f5f1e452f74dd
3,612,587
def solve_1(x): """Returns the checksum (sum of the difference between the biggest and smallest number in each row)""" return sum(map(get_diff, format_input(x)))
90c904789f95318c4e57f3cd9e1d33aff3adc46d
3,612,588
def resnet34(pretrained=False, filter_size=1, pool_only=True, **kwargs): """Constructs a ResNet-34 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(BasicBlock, [3, 4, 6, 3], filter_size=filter_size, pool_only=pool_only, **kwargs) if pretrain...
9653156bbbcd6773e5479ca31f2c95a9bf9edec5
3,612,589
def selvita_sukupuoli(hetu): """Selvittää järjestynumeron perusteella sukupuolen: parillinen -> nainen, pariton -> mies Args: hetu (string): Henkilötunnus Returns: string: Nainen tai mies """ # Otetaan hetusta järjestysnumero-osa jarjestysnumero_str = hetu[7:10] # Muuteta...
243982f89e2e9edf4aa62972275a87e571327550
3,612,590
import re def search_unknown(filename, dictionary): """ Searches the words that are misspelled/not in the dictionary""" numbers = re.findall('[\d]+', filename) words = filename.lower().replace('?', ' ').replace('!',' ').replace('.',' ').replace('-',' ').replace(':',' ').replace(';',' ').replace(',',' ').replace('(...
8e91ea65f7a1f04074e68d061677cfa365c762c2
3,612,591
def cpp_bindata_subtype_type_name(name): # type: (unicode) -> unicode """Return the C++ type name for a bindata subtype.""" assert is_valid_bindata_subtype(name) return _BINDATA_SUBTYPE[name]['bindata_enum']
3cdc6a5bb7fe2977f39a26d78c6bc6146a31301d
3,612,592
def avg_spectra(im): """ avg_spectra(im) Returns numpy.ndarray of mean spectrum, averaged over the image pixels Parameters ---------- im : image passed as numpy array Returns ------- out : ndarray An array object satisfying the specified requirements. """ ...
013bec790da9e27837fc83859c7b2e73c8845181
3,612,593
def moving_average(x, n, type='simple'): """ compute an n period moving average. type is 'simple' | 'exponential' """ x = np.asarray(x) if type == 'simple': weights = np.ones(n) else: weights = np.exp(np.linspace(-1., 0., n)) weights /= weights.sum() # print ("Weigh...
faa14d2ac7c0b08e1cdfaae33d18dd308083b11d
3,612,594
def changeContagion(G, A, i): """ change statistic for Contagion (partner attribute) *--* """ delta = 0 for u in G.neighbourIterator(i): if A[u] == 1: delta += 1 return delta
e6acd316f9fe618f7ca592c5aeae7b902fb774a4
3,612,595
def collect(config, pconn): """ All the heavy lifting done here """ branch_info = get_branch_info(config) pc = InsightsUploadConf(config) output = None collection_rules = pc.get_conf_file() rm_conf = pc.get_rm_conf() blacklist_report = pc.create_report() if rm_conf: logg...
222fc49ab5dc49eddeda5bc2e992ca931f9b30f4
3,612,596
def _check_verbosity(verbosity: str) -> str: """ Check function used by verbosity setter as a callback. :param verbosity: verbosity level to apply to resto_client. :raises ValueError: when verbosity has a wrong value :returns: the uppercase verbosity level """ if verbosity is not None: ...
449c3c632b0c9dba92aca5d42e49c750e4f21f02
3,612,597
import unittest def local(): """Run all local tests""" suite = ServiceTestSuite() suite.addTest(unittest.makeSuite(HomelandTestCase, 'test_local')) return suite
ae8f24abf632c5b376e71151ef6ef813f1546d2d
3,612,598
def cycle_check(classes): """ Checks for cycle in clazzes, which is a list of (class, superclass) Based on union find algorithm """ sc = {} for clazz, superclass in classes: class_set = sc.get(clazz, clazz) superclass_set = sc.get(superclass, superclass) if class_set !=...
8079f5e7044318570424a309b6cd16ce78b6e343
3,612,599
def bivariate_histogram(xsample, ysample, reference_value_mean=None,\ reference_value_covariance=None, bins=None, matplotlib_function='imshow',\ xlabel='', ylabel='', title='', fontsize=28, ax=None, show=False,\ contour_confidence_levels=0.95, reference_color='r', reference_alpha=1,\ minima=None, maxima...
01e479b80dca6b87494b323f9fa76a8a4a08d4e1
3,612,600
def arrayToVec(array, arrType=carmcmcLib.vecD): """ Convert the input numpy array to a python wrapper of a C++ std::vector<double> object. """ vec = arrType() vec.extend(array) return vec
efdbe2ae33821ff6aadfd699aa535eacf962efe3
3,612,601
import six def moma(model, reference=None, cache=None, reactions=None, *args, **kwargs): """ Minimization of Metabolic Adjustment[1] Parameters ---------- model: cobra.Model reference: FluxDistributionResult, dict cache: ProblemCache reactions: list Returns ------- FluxDi...
87397e01b8ddba25c1d92d652aecb2c85d8239df
3,612,602
def api_v2_url(path_str, params=None, base_route=settings.API_BASE_URL, **kwargs): """ Convenience function for APIv2 usage: Concatenates parts of the absolute API url based on arguments provided For example: given path_str = '/nodes/abcd3/contributors/' and par...
71d7efeb9d6e6279776f3e28257428ee3c09b9f7
3,612,603
import json def serialize_timingsession(session_pk, pk_offset=0): """Serialize all data associated with a timing session into JSON.""" session = TimingSession.objects.get(pk=session_pk) data_to_dump = [ [session], [session.coach], [session.coach.user], Split.objects.filter(...
9de0ccf0a0eb2644fc7cf2289815f5e39d9a5416
3,612,604
def send_via_mail_to(request): """ send email to list of freinds :param request: in the square represented by : west < longitude < east north < latitude < south """ idAlert = int(request.POST['id']) emails = request.POST['list'] text = request.POST['text'] lis...
68e17f426ea3ba15f3e95cb9ce3daf1a65c7cbed
3,612,605
def get_tables_from_url(url, url_to_html='requests'): """Get's a list of pandas dataframes from tables scraped from a url. Note that this will only work with static pages. If the html needs to be rendered dynamically, you'll have to get your needed html otherwise (like with selenium). >>> url = 'https:...
767a99ca64ce840c04b993c48d9b861c73211da9
3,612,607
import random import math import tqdm import time def matrix_split(interaction_dataset, user_test_ratio=0.2, item_test_ratio=0.2, min_user_interactions=0, seed=0, max_concurrent_threads=4, **kwds): """Dataset split method that uses a matrix split strategy. More specifically, item_test_ratio items...
d983e27c162835616c855dd54f7d9cf89708d458
3,612,608
import copy def Loadexc(casefile_dyn): """ Loads exciter data. @param casefile_dyn: m-file or struct with dynamic data @return: exciter parameter matrix @see: U{http://www.esat.kuleuven.be/electa/teaching/matdyn/} """ # Load data if isinstance(casefile_dyn, dict): exc = casefile_...
f5fcfb34bd6b9a430aed208173ee633b61d957d8
3,612,609
def _num_requests_needed(num_repos, factor=2, wiggle_room=100): """ Helper function to estimate the minimum number of API requests needed """ return num_repos * factor + wiggle_room
525af1e3aa5e1c0b35195fcd8e64cd32101bb6f2
3,612,610
import re def linebreakshtml(value, autoescape=True): """ Replaces double line breaks in HTML to a paragraph break (``</p>``). This tag ignores single line breaks. """ autoescape = autoescape and not isinstance(value, SafeData) value = normalize_newlines(force_text(value)) if autoescape: ...
bdd38b299f297194d9e3ca3c31c20ba2203ed622
3,612,611
from typing import Generator def find_files(base_path: str, annotation_path: str or None = None) -> Generator[str, Annotation, None]: """Get each file and its proper annotation object. Parameters ---------- base_path : srt Base path of input files. annotation_path : str or None Pa...
8ee544a6ec876f395caa0be6dcc2de2ccb2fc541
3,612,613
def request_course_creator(request): """ User has requested course creation access. """ user_requested_access(request.user) return render(request)
ad036a1852e39c7c626f4013c4d8b6e3958b1d2c
3,612,614
def _generate_monthly_price_materialized_view_sql(): """ Generate the SQL used to generate the materialized view used by the last point view :return: """ return """ CREATE MATERIALIZED VIEW instancedata_monthly_price_mv ENGINE = SummingMergeTree PARTITION BY crawlMonth ...
8cbe81bd07074accf6f621ab68d795282e0e844d
3,612,615
def number_constructors(): """A decorator for parametrized tests that test particular number operations. """ return pytest.mark.parametrize( "newobj", [ lambda: weakget(0), lambda: pep505(0), lambda: _weakget__nothing, # a singleton ], ids...
8b8c1534f1285f03b2219dba58ed9490236d87a3
3,612,616
import threading def approve_paper(request): """API approve_paper""" if not request.user.is_authenticated: return JsonResponse({'status': 'false'}, status=401) if request.method == 'POST': id = request.POST['id'] comment = request.POST['comment'] paper = get_object_or_404(...
0f5c48e747d4b5fea890de5586561da3f13e18ac
3,612,617
def dopamine_eval(runner, patient0, seed=100): """Evaluate an agent.""" base_env = runner._environment.environment # pylint: disable=protected-access initial_health_state = np.zeros_like( base_env.initial_params.initial_health_state) initial_health_state[patient0] = 1 base_env.set_initial_health_state...
b5d497923ff62e953bb6a6df717645b886b0138a
3,612,618
import torch def pad_data(data_list, fill=0): """ Pad tensors with fill-value such that list of variable shaped tensors can be stacked """ n_samples = len(data_list) #first determine longest time series: lengths = [x.shape[0] for x in data_list] max_len = max(lengths) output = fil...
d6d978d0247b7481f5eb33a23292addaa10ba792
3,612,619
import json def market(request): """ Consulta a API procurando por informações sobre o mercado """ conn.request("GET", "/market/v2/get-summary?region=BR", headers=headers) res = conn.getresponse() data = res.read() summary = json.loads(data.decode("utf-8"))['marketSummaryAndSparkResponse'] ret...
1bb8cbc8bd44811a8e0f50b328ec0a2b858a82d3
3,612,620
def setup_invalid_yaml(tmpdir): """Returns a list containing three Vector instances""" test_config_data = """ test: 1 test2: 1 """ default_dict = {'test': 'testing', 'test2': 'still testing'} test_cfg = tmpdir.mkdir("sub").join('test_config.yml') test_cfg.write(test_config_data) ...
0f16cc6e8974b077996957b3f26f0d5f3c194ad3
3,612,621
import torch def fuse_features(features1, features2, frame_batch_size=64, device='cuda'): """feature fusion""" video_length = features1.shape[0] frame_start = 0 frame_end = frame_start + frame_batch_size features = np.empty(shape=[0, 4096], dtype=np.float32) if video_length <= frame_batch_siz...
539838c30cb9ac1e01af7f9b5d15df9cf4663275
3,612,622
def raHMS2deg(angle): """ EXAMPLE: Angle("10:42:44",unit=u.hourangle).deg """ return astropy.coordinates.Angle(angle,unit=u.hourangle).deg
f0b910131e8802c029f8f7a6758f4fe1184f24e0
3,612,623
def same_padding_for_kernel(shape, corr, strides_up=None): """Determine correct amount of padding for `same` convolution. To implement `'same'` convolutions, we first pad the image, and then perform a `'valid'` convolution or correlation. Given the kernel shape, this function determines the correct amount of p...
8d956c75a2e0609a04ec56374a4cb9b3b367b90a
3,612,626
import re def dedeidentify(text): """ MIMIC-specific :param text: The text to de-de-identify :return: """ return re.sub(r"\[\*\*.*\*\*\]", xxxx, text).lower()
033c04bb61ce26fa2e7af902cc4d3ffbb9c88004
3,612,627
def embed_net_siam1(): """ This is a siamese type network to compare two patches. """ data1 = mx.sym.Variable("data1") data2 = mx.sym.Variable("data2") conv_weight = [] conv_bias = [] for i in range(3): conv_weight.append(mx.sym.Variable('conv' + str(i) + '_weight')) conv...
0817dcead9060991d9fe0bf951b0cb4790823166
3,612,628
def get_time_ms(frame, position): """Get time in ms and string based on the finishing position :param frame: A frame from AsyncVideoCapture / cv2.VideoCapture :type frame: numpy.ndarray :param position: Position 1-4 :type position: int :return: Time in milliseconds, time as string :rtype: (...
ffd10436170823a2c3a4b08c0d2d262355a12bb7
3,612,630
def _extract_license_outliers(license_service_output): """Extract license outliers. This helper function extracts license outliers from the given output of license analysis REST service. :param license_service_output: output of license analysis REST service :return: list of license outlier package...
101a916fec08a3a5db1a09a2817e82314ca19f6b
3,612,631
def maxout(x, pool_size, axis=1): """Maxout activation function. It accepts an input tensor ``x``, reshapes the ``axis`` dimension (say the size being ``M * pool_size``) into two dimensions ``(M, pool_size)``, and takes maximum along the ``axis`` dimension. Args: x (:class:`~chainer.Variab...
5e30761e4abefb5d823690c4c92c9a8666e2aded
3,612,632
from tests.fpga_drivers import FpgaDriverBase from ctypes import c_uint32 def test_fpga_drivers_base(): """ Test accelize_drm.fpga_drivers.FpgaDriverBase. """ library = 'fpga_library.so' fpga_slot_id = 5 base_address = 0x10 fpga_image = 'fpga_image' class Fpga: """Fake FPGA""...
c7d6d59e00a1167ded304170a81b960ac17f5fb6
3,612,633
from typing import Set def GetNumDistinctChromeVersions(db, build_config, start_date, end_date): """Get the number of distinct chrome versions. This represents the number of successful chrome uprevs. Args: db: cidb.CIDBConnection object. build_config: Name of build config of master builder. start_...
83a7fd123a3154990629406b2c3d5e2ccb3b1e6f
3,612,634
def install_pip(): """ Install pip using apt-get install. """ #we need to upgrade pip package using pip itself return apt_get_install("python-pip") + pip_install("pip")
16df3a5d123735f1d3b1ba85eb55849ddcbf1e26
3,612,635
def center(map, object): """ Center an ee.Image or ee.Feature on the map. Args: map: The map to center the object on. object: The ee.Image or ee.Feature to center. Returns: The provided map. """ coordinates = object.geometry().bounds().coordinates().getInfo()[0] ...
60a2baa1c4f83b0e9b1221bcc474f109c35cbd7a
3,612,638
from datetime import datetime def login_user(): """ Login user in api :return: token """ print('Login') auth = request.authorization # print(request.authorization) if not auth or not auth.username or not auth.password: return make_response('could not verify', 401, {'WWW.Authent...
3e371f9dde691a19ccb72b1f1255e0569034ac24
3,612,639
import warnings def normalized_diff(b1, b2): """Take two numpy arrays and calculate the normalized difference. Math will be calculated (b1-b2) / (b1+b2). Parameters ---------- b1, b2 : arrays with the same shape Math will be calculated (b1-b2) / (b1+b2). Returns ---------- n_...
e905b76c7dced3b8194b98bf83339be6a6e16d46
3,612,640
import tkinter as tk from tkinter import filedialog def get_json_file_path(): """Opens dialog box for user to choose where to save the measurements. Uses default directory in case of failure. Requires very hacky work-around of installing tk and tcl in NX directories""" try: root = tk.Tk(...
ce234384a6d2c98693a7a52b0d22ec8716ad7a76
3,612,642
import shlex def parse_config_string(config_string, issue_warnings=True): """ Parses a config string (comma-separated key=value components) into a dict. """ config_dict = {} my_splitter = shlex.shlex(config_string, posix=True) my_splitter.whitespace = "," my_splitter.whitespace_split = Tru...
1decd3b203b779099111e949b2757a3f52b8c25d
3,612,643
def load_data_clf(ds_name): """ Load the data for classification by the specified dataset name. Parameters ---------- ds_name : str Returns ------- data : DataFrame """ ds_load_func = None if ds_name in DS_LOAD_FUNC_CLF.keys(): ds_load_func = DS_LOAD_FUNC_CLF[ds_na...
159a3a7b347400416f17cedf0dc04037b133431c
3,612,645
def parse_file_name(file_name): """ <Purpose> Parses a file name to identify its module and its descriptor <Arguments> file_name: the name of the test file <Exceptions> InvalidTestFileError: if you provide a test file which does not follow the naming convention of 'ut_<module>_<descriptor>...
55698a5934b639ce0ddb40cb6eb2edf1614ec04f
3,612,646
def _proto_builder_test_impl(ctx): """The implementation of the 'proto_builder_test' rule. Tests the files generated by the 'proto_builder' rule. The test performs a textual comparison of the generated source and header with the expected source and header respectively. Args: ctx: The current...
705ffebeb126ca04c7f4ea35aa82e81f44210b8f
3,612,647
def _make_nxm_w (*args, **kw): """ Make a simple wildcarded NXM entry class """ t = _fix_types(kw.pop('type', _nxm_maskable_numeric_entry)) ok = False for tt in t: if _issubclass(tt, _nxm_maskable): ok = True break if not ok: t.insert(0, _nxm_maskable) return _make_nxm(*args, type=t...
5a4f3b020a3cc91b908f8a8892716865dd7decf9
3,612,648
def process_datasets(dataset_class, dataset_args, unc_model, device, test_fn=test_unc_model, N=1000, **forward_kwargs): """ calls test_fn(unc_model, dataset) for every dataset in datasets """ results = {} for name in dataset_args: print("Testing", name) print(N) dataset = dat...
8a049e099715b5315524fea15f168964bb49f500
3,612,649
def accuracy_metric(actual, predicted, correct=0) -> float: """calculate accuracy of the dataset comparing the actual test label vs the predicted label""" for i in range(len(actual)): if actual[i] == predicted[i]: correct += 1 return correct / len(actual) * 100.0
d7f19ccd1da426e00043ee3887261c85d963b47d
3,612,650
from typing import Any import copy def get_test_case( data: pd.DataFrame, model: Any, key: str, add: ARITHEMETIC_OPERATIONS = None, multiply: ARITHEMETIC_OPERATIONS = None, ) -> SCORES: """ Helper method to create the different test cases that alter the keys in a dictionary """ ...
6996c1ef020ae12c65eebbe9275ff0ad3d0c155f
3,612,651
def realign_mol(mol,conf,coord_Map, alg_Map, mol_template, maxsteps): # RAUL: This function requires a clear separation between minimization and alignment. """ Minimizes and aligns the molecule provided freezing the atoms that match the mol_template. Parameters ---------- mol : rdkit.Chem.Mol...
325d324693c5b0e064b56209ba2029a357b7fe91
3,612,652
def measure_shadow_work(simulation, n_steps): """Run the simulation for n_steps and return a vector of the shadow work accumulated during integration. * Check whether simulation.integrator has bookkeeping variables W_shad and/or heat. * If only W_shad is available, measure shadow work as W_shad * I...
c3ef18a0caf040f5d34316bf0d7b5b51b6a6cd43
3,612,653
def cumulative_cross_corr(I1, I2): """ doing normalized cross correlation on distance imagery :param I1: NP.ARRAY (_,_) binary array :param I2: NP.ARRAY (_,_) binary array :return result: NP.ARRAY (_,_) similarity surface ...
082ee285ba75c72ff1d9b1551b2b882212bde291
3,612,654
def getGbdbTables(database, tableset): """ Remove tables that aren't pointers to Gbdb files.""" sep = "','" tablestr = sep.join(tableset) tablestr = "'" + tablestr + "'" hgsqlOut = qaUtils.callHgsql(database, "select table_name from information_schema.columns where\ ...
31c591104698eb50b8ecc63c08609ebf08dd9a10
3,612,655
def four_bar_plane_truss(num_samples: int = 100, distribution: str = "lhs") -> list: """Four bar plane truss problem. As found in Multiobjective structural optimization using a microgenetic algorithm. Parameters ---------- x : list or ndarray Should have 4 elements Returns ------- ...
952d57cf9cbc89dca61046e7a06f6eee1a93a953
3,612,656
def parseFile (pomFile): """ Parses a pom.xml file and returns a Maven object or None """ with open (pomFile, 'rb') as f: return parseString (f.read()) return None
cd6baa8bfd141a0778dca5bd0cfe2b2d2b86a9ae
3,612,657
def evaluations_to_columns(evaluation): """Convert the results of :meth:`metrics.ScoringMixIn.evaluate` to a pandas DataFrame-ready format Parameters ---------- evaluation: dict of OrderedDicts The result of consecutive calls to :meth:`metrics.ScoringMixIn.evaluate` for all given dataset types ...
26c5f4b2a9830f7547f6b59d9653fea25345b43d
3,612,659
import abc import functools def get_metric(name: str, **kwargs) -> abc.Callable: """Returns metric function for given metric name Parameters ---------- name : str Metric name kwargs : any Additional keyword-arguments for metric Returns ------- metric : callable ...
ddd94ad7d39538f7308dc5bdf6b57f238a6173b4
3,612,660
def resource_exists(env, resource): """Checks for resource existence without actually instantiating a model. :return: `True` if the resource exists, `False` if it doesn't and `None` in case no conclusion could be made (i.e. when `IResourceManager.resource_exists` is not ...
270d55de9b6fa29628ea996af16af2971a9487de
3,612,661
def run_dqmc(p, unequal_time=True, callback=None, progress=False, *args, **kwargs): """Runs a DQMC simulation. Parameters ---------- p : Parameters The input parameters of the DQMC simulation. unequal_time : bool If `True`, unequal-time measurements will be performed. callback :...
661f725d21e819fc1c656fec8c8c395cc23f3c42
3,612,662
def merge(left: list, right: list) -> list: """Merges 2 sorted lists (left and right) in 1 single list, which is returned at the end. Time complexity: O(m), where m = len(left) + len(right).""" mid = [] i = 0 # Used to index the left list. j = 0 # Used to index the right list. while i < ...
9f6c501469e79a9f5ecfd8e23ee3384fc56c5a48
3,612,663
def replace(i_list: list, target: int,new_value: int)-> list: """ Replace all the target value with a new value :param i_list: the list to be analyzed :param value: the value to replace :param target: the value to be replaced :return: the new list """ return list(map(lambda value: new_va...
d0d2bc928c915d3456a25cc4ff341b23a66c4098
3,612,664
def single(request, id, template_name="microblogging/single.html"): """ A single tweet. """ tweet = get_object_or_404(Tweet, id=id) return render_to_response(template_name, { "tweet": tweet, }, context_instance=RequestContext(request))
117ab58d3626740f91929f8c4e9dd2bfd9d07f21
3,612,665
import warnings def astropy_tabular_data(*args, **kwargs): """ Build a data set from a table. We restrict ourselves to tables with 1D columns. All arguments are passed to astropy.table.Table.read(...). """ result = Data() with warnings.catch_warnings(): warnings.simplefi...
bcaa8fe58be57ff93618ec0a89ec7070e39c49f9
3,612,667
def words_cmp(a, b): """ word比较器 :param a: (word, 词频) :param b: (word, 词频) :return: [-1|0|1] """ a_word, a_freq = a b_word, b_freq = b if a_freq != b_freq: return b_freq - a_freq elif a_word != b_word: return -1 if a_word < b_word else 1 else: return 0
b758a5a685b81f5fbca5840529272727e5fcf5d7
3,612,668
def _load_data(args): """Load data from path.""" if args.data_format == 'CULANE': return vega.dataset("AutoLaneDataset", dataset_format="CULane", data_path=args.data_path, mode="test", batch_size=args.batch_size).loader elif args.data_format == 'COCO': return ...
908cab2892fb0661e31cb65c2273ba811ef0427b
3,612,669
def extract_u_nk(xvg, T): """Return reduced potentials `u_nk` from a Hamiltonian differences XVG file. Parameters ---------- xvg : str Path to XVG file to extract data from. T : float Temperature in Kelvin the simulations sampled. Returns ------- u_nk : DataFrame ...
81f24762f0bd637ef46e0d7e1236aaa657853050
3,612,670
def group(query, fields=None, step=None): """Group results by `fields` and/or `step`.""" if fields is None: fields = [] if isinstance(fields, string_types): fields = [fields] fields = ['"%s"' % f for f in fields] if step: fields.insert(0, 'time(%s)' % step) return '%s GRO...
819e14714bc3e376cca8c7610466d37c0d599511
3,612,671
def first_level_directory(path): """Return the first level directory of a path. >>> first_level_directory('home/syt/work') 'home' >>> first_level_directory('/home/syt/work') '/' >>> first_level_directory('work') 'work' >>> :type path: str :param path: the path for which we want...
3e151912f7ed43c8d3ec9593179ea3016ff1ce2c
3,612,672