Best Python code snippet using autotest_python
sampling.py
Source:sampling.py  
1import time2from typing import List, Dict3import numpy as np4import pymc as mc5import theano as th6import theano.tensor as tt7class Sampler(object):8    def __init__(self, n_query:int, dim_features:int, update_func:str="pick_best", beta_demo:float=0.1, beta_pref:float=1.):9        """10        Initializes the sampler.11        :param n_query: Number of queries.12        :param dim_features: Dimension of feature vectors.13        :param update_func: options are "rank", "pick_best", and "approx". To use "approx", n_query must be 2. Will throw an assertion14            error otherwise.15        :param beta_demo: parameter measuring irrationality of human in providing demonstrations16        :param beta_pref: parameter measuring irrationality of human in selecting preferences17        """18        self.n_query = n_query19        self.dim_features = dim_features20        self.update_func = update_func21        self.beta_demo = beta_demo22        self.beta_pref = beta_pref23        if self.update_func=="approx":24            assert self.n_query == 2, "Cannot use approximation to update function if n_query > 2"25        elif not (self.update_func=="rank" or self.update_func=="pick_best"):26            raise Exception(update_func + " is not a valid update function.")27        # feature vectors from demonstrated trajectories28        self.phi_demos = np.zeros((1, self.dim_features))29        # a list of np.arrays containing feature difference vectors and which encode the ranking from the preference30        # queries31        self.phi_prefs = []32        self.f = None33    def load_demo(self, phi_demos:np.ndarray):34        """35        Loads the demonstrations into the Sampler.36        :param demos: a Numpy array containing feature vectors for each demonstration.37            Has dimension n_dem x self.dim_features.38        """39        self.phi_demos = phi_demos40    def load_prefs(self, phi: Dict, rank):41        """42        Loads the results of a preference query into the sampler.43        :param phi: a dictionary mapping rankings (0,...,n_query-1) to feature vectors.44        """45        result = []46        if self.update_func == "rank":47            result = [None] * len(rank)48            for i in range(len(rank)):49                result[i] = phi[rank[i]]50        elif self.update_func == "approx":51            result = phi[rank] - phi[1-rank]52        elif self.update_func == "pick_best":53            result, tmp = [phi[rank] - phi[rank]], []54            for key in sorted(phi.keys()):55                if key != rank:56                    tmp.append(phi[key] - phi[rank])57            result.extend(tmp)58        self.phi_prefs.append(np.array(result))59    def clear_pref(self):60        """61        Clears all preference information from the sampler.62        """63        self.phi_prefs = []64    def sample(self, N:int, T:int=1, burn:int=1000) -> List:65        """66        Returns N samples from the distribution defined by applying update_func on the demonstrations and preferences67        observed thus far.68        :param N: number of samples to draw.69        :param T: if greater than 1, all samples except each T^{th} sample are discarded.70        :param burn: how many samples before the chain converges; these initial samples are discarded.71        :return: list of samples drawn.72        """73        x = tt.vector()74        x.tag.test_value = np.random.uniform(-1, 1, self.dim_features)75        # define update function76        start = time.time()77        if self.update_func=="approx":78            self.f = th.function([x], tt.sum([-tt.nnet.relu(-self.beta_pref * tt.dot(self.phi_prefs[i], x)) for i in range(len(self.phi_prefs))])79                            + tt.sum(self.beta_demo * tt.dot(self.phi_demos, x)))80        elif self.update_func=="pick_best":81            self.f = th.function([x], tt.sum(82                [-tt.log(tt.sum(tt.exp(self.beta_pref * tt.dot(self.phi_prefs[i], x)))) for i in range(len(self.phi_prefs))])83                            + tt.sum(self.beta_demo * tt.dot(self.phi_demos, x)))84        elif self.update_func=="rank":85            self.f = th.function([x], tt.sum( # summing across different queries86                [tt.sum( # summing across different terms in PL-update87                    -tt.log(88                        [tt.sum( # summing down different feature-differences in a single term in PL-update89                            tt.exp(self.beta_pref * tt.dot(self.phi_prefs[i][j:, :] - self.phi_prefs[i][j], x))90                        ) for j in range(self.n_query)]91                    )92                ) for i in range(len(self.phi_prefs))])93                            + tt.sum(self.beta_demo * tt.dot(self.phi_demos, x)))94        print("Finished constructing sampling function in " + str(time.time() - start) + "seconds")95        # perform sampling96        x = mc.Uniform('x', -np.ones(self.dim_features), np.ones(self.dim_features), value=np.zeros(self.dim_features))97        def sphere(x):98            if (x**2).sum()>=1.:99                return -np.inf100            else:101                return self.f(x)102        p = mc.Potential(103            logp = sphere,104            name = 'sphere',105            parents = {'x': x},106            doc = 'Sphere potential',107            verbose = 0)108        chain = mc.MCMC([x])109        chain.use_step_method(mc.AdaptiveMetropolis, x, delay=burn, cov=np.eye(self.dim_features)/5000)110        chain.sample(N*T+burn, thin=T, burn=burn, verbose=-1)111        samples = x.trace()112        samples = np.array([x/np.linalg.norm(x) for x in samples])113        # print("Finished MCMC after drawing " + str(N*T+burn) + " samples")...pyxel_framework.py
Source:pyxel_framework.py  
...54    def update(self):55        if not self.is_update:56            return57        # print(f"update '{self.name}' background")58        self.update_func(self)59    def draw(self):60        if not self.is_draw:61            return62        pyxel.cls(self.col)63class ObjRect:64    def __init__(self, name, xy, wh, col, update_func=_pass):65        self.name = name66        self.xy = xy67        self.wh = wh68        self.col = col69        self.update_func = update_func70        self.is_update = True71        self.is_draw = True72    73    def is_hover(self, xy):74        return all(self.xy[i] <= xy[i] < self.xy[i]+self.wh[i] for i in range(2))75    def update(self):76        if not self.is_update:77            return78        self.update_func(self)79    def draw(self):80        if not self.is_draw:81            return82        pyxel.rect(*self.xy, *self.wh, self.col)83class ObjRectFrame:84    def __init__(self, name, xy, wh, col, update_func=_pass):85        self.name = name86        self.xy = xy87        self.wh = wh88        self.col = col89        self.update_func = update_func90        self.is_update = True91        self.is_draw = True92    93    def update(self):94        if not self.is_update:95            return96        self.update_func(self)97    def draw(self):98        if not self.is_draw:99            return100        pyxel.rectb(*self.xy, *self.wh, self.col)101class ObjImg:102    def __init__(self, name, xy, bank_num, uvwh, colkey=-1, update_func=_pass):103        self.name = name104        self.xy = xy105        self.bank_num = bank_num106        self.uvwh = uvwh107        self.colkey = colkey108        self.update_func = update_func109        self.is_update = True110        self.is_draw = True111    112    def is_hover(self, xy):113        return all(self.xy[i] <= xy[i] < self.xy[i]+self.uvwh[2+i] for i in range(2))114    def update(self):115        if not self.is_update:116            return117        self.update_func(self)118    def draw(self):119        if not self.is_draw:120            return121        pyxel.blt(*self.xy, self.bank_num, *self.uvwh, self.colkey)122class ObjText:123    def __init__(self, name, xy, text, col, update_func=_pass):124        self.name = name125        self.xy = xy126        self.text = text127        self.col = col128        self.update_func = update_func129        self.is_update = True130        self.is_draw = True131    132    def update(self):133        if not self.is_draw:134            return135        self.update_func(self)136    def draw(self):137        if not self.is_draw:138            return...test_adapters.py
Source:test_adapters.py  
1import logging2from unittest import mock3import uuid4from driftwood.adapters import StatusUpdateAdapter5class TestStatusAdapter:6    def test_1(self):7        update_func = mock.MagicMock()8        log = logging.getLogger(uuid.uuid4().hex)9        adapter = StatusUpdateAdapter(update_func, log)10        update_func.assert_call_count == 011        adapter.info("test")12        update_func.assert_called_with(20, "INFO")13        update_func.assert_call_count == 114        adapter.debug("test")15        update_func.assert_call_count == 116        adapter.error("test")17        update_func.assert_called_with(40, "ERROR")18        update_func.assert_call_count == 219        adapter.warning("test")20        adapter.info("test")21        adapter.warning("test")22        update_func.assert_call_count == 223        ...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
