Best Python code snippet using fMBT_python
old_DarkMatterShapes.Plots.py
Source:old_DarkMatterShapes.Plots.py  
1import argparse,pickle2import numpy as np3import matplotlib.pylab as plt4import matplotlib.colors as colors5from osxmetadata import OSXMetaData6from scipy.stats import kde7def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):8    new_cmap = colors.LinearSegmentedColormap.from_list(9        'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval),10        cmap(np.linspace(minval, maxval, n)))11    return new_cmap12parser = argparse.ArgumentParser()13parser.add_argument("-c","--cross_section",required=True,choices=['cdm','3','10','30','50'])14parser.add_argument("-p","--pynbody",action="store_true")15parser.add_argument("-i","--inner",action="store_true")16parser.add_argument("-t","--top",action="store_true")17args = parser.parse_args()18topfile = '.Top200' if args.top else ''19topapp = '.top' if args.top else ''20if args.cross_section == 'cdm':21    filename = f'../DataFiles/DarkMatterShapes{topfile}.CDM.pickle'22    im = 'CDM'23else:24    filename = f'../DataFiles/DarkMatterShapes{topfile}.SI{args.cross_section}.pickle'25    im = f'SI{args.cross_section}'26app = '.Inner' if args.inner else ''27lab = 'Inner ' if args.inner else ''28data = pickle.load(open(filename,'rb'))29halo_list = [h for h in data]30b,c,bpyn,cpyn = [[],[],[],[]]31for halo in halo_list:32    b.append(data[halo]['b'])33    c.append(data[halo]['c'])34    if not np.isnan(data[halo]['rbins'][0]):35        if not args.inner:36            bpyn.append(data[halo]['b_pyn'][-1])37            cpyn.append(data[halo]['c_pyn'][-1])38        else:39            i_inner = np.argmin(abs(data[halo]['rbins'] - (data[halo]['rbins'][-1]*.1 )))40            bpyn.append(data[halo]['b_pyn'][i_inner])41            cpyn.append(data[halo]['c_pyn'][i_inner])42f,ax = plt.subplots(1,1,figsize=(8,8))43ax.set_xlim([0,1])44ax.set_ylim([0,1])45ax.tick_params(length=5,labelsize=15)46ax.set_xlabel('b/a [AHF]',fontsize=25)47ax.set_ylabel('c/a [AHF]',fontsize=25)48ax.set_title(im,fontsize=25)49ax.plot([0,1],[0,1],c='0.5',linestyle='--')50ax.scatter(b,c,c='k',marker='.',s=.75**2)51f.savefig(f'../Plots/DarkMatterShapes{topapp}.{im}.AHF.png',bbox_inches='tight',pad_inches=.1)52meta = OSXMetaData(f'../Plots/DarkMatterShapes{topapp}.{im}.AHF.png')53meta.creator='DarkMatterShapes.Plots.py'54nbins=10055bins = np.linspace(0,1,101)56k = kde.gaussian_kde([b,c])57xk, yk = np.mgrid[min(b):max(b):nbins*1j, min(c):max(c):nbins*1j]58zk = k(np.vstack([xk.flatten(), yk.flatten()]))59f,ax = plt.subplots(1,1,figsize=(8,8))60ax.set_xlim([0,1])61ax.set_ylim([0,1])62ax.tick_params(length=5,labelsize=15)63ax.set_xlabel(f'b/a [AHF]',fontsize=25)64ax.set_ylabel(f'c/a [AHF]',fontsize=25)65ax.set_title(im,fontsize=25)66ax.plot([0,1],[0,1],c='0.5',linestyle='--')67ax.scatter(b,c,c='k',marker='.',s=.75**2)68ax.contour(xk,yk,zk.reshape(xk.shape),levels=3,cmap='spring')69f.savefig(f'../Plots/DarkMatterShapes{topapp}.{im}.AHF.Contour.png',bbox_inches='tight',pad_inches=.1)70meta = OSXMetaData(f'../Plots/DarkMatterShapes{topapp}.{im}.AHF.Contour.png')71meta.creator='DarkMatterShapes.Plots.py'72f,ax = plt.subplots(1,1,figsize=(8,8))73ax.set_xlim([0,1])74ax.set_ylim([0,1])75ax.tick_params(length=5,labelsize=15)76ax.set_xlabel(f'b/a [AHF]',fontsize=25)77ax.set_ylabel(f'c/a [AHF]',fontsize=25)78ax.set_title(im,fontsize=25)79ax.plot([0,1],[0,1],c='0.5',linestyle='--')80ax.hist2d(b,c,[bins,bins],cmap='Greys',density=True)81ax2 = ax.twinx()82ax2.set_ylim([0,50])83ax2.set_yticks([])84ax2.hist(b,bins,histtype='step',facecolor='None',edgecolor='k',density=True)85ax3 = ax.twiny()86ax3.set_xlim([0,50])87ax3.set_xticks([])88ax3.hist(c,bins,histtype='step',facecolor='None',edgecolor='k',density=True,orientation='horizontal')89f.savefig(f'../Plots/DarkMatterShapes{topapp}.{im}.AHF.Histogram.png',bbox_inches='tight',pad_inches=.1)90meta = OSXMetaData(f'../Plots/DarkMatterShapes{topapp}.{im}.AHF.Histogram.png')91meta.creator='DarkMatterShapes.Plots.py'92if args.pynbody:93    f,ax = plt.subplots(1,1,figsize=(8,8))94    ax.set_xlim([0,1])95    ax.set_ylim([0,1])96    ax.tick_params(length=5,labelsize=15)97    ax.set_xlabel(f'{lab}b/a [Pynbody]',fontsize=25)98    ax.set_ylabel(f'{lab}c/a [Pynbody]',fontsize=25)99    ax.set_title(im,fontsize=25)100    ax.plot([0,1],[0,1],c='0.5',linestyle='--')101    ax.scatter(bpyn,cpyn,c='k',marker='.',s=.75**2)102    f.savefig(f'../Plots/DarkMatterShapes{topapp}.{im}{app}.Pynbody.png',bbox_inches='tight',pad_inches=.1)103    meta = OSXMetaData(f'../Plots/DarkMatterShapes{topapp}.{im}{app}.Pynbody.png')104    meta.creator='DarkMatterShapes.Plots.py'105    nbins=100106    bins = np.linspace(0,1,101)107    k = kde.gaussian_kde([bpyn,cpyn])108    xk, yk = np.mgrid[min(bpyn):max(bpyn):nbins*1j, min(cpyn):max(cpyn):nbins*1j]109    zk = k(np.vstack([xk.flatten(), yk.flatten()]))110    f,ax = plt.subplots(1,1,figsize=(8,8))111    ax.set_xlim([0,1])112    ax.set_ylim([0,1])113    ax.tick_params(length=5,labelsize=15)114    ax.set_xlabel(f'{lab}b/a [Pynbody]',fontsize=25)115    ax.set_ylabel(f'{lab}c/a [Pynbody]',fontsize=25)116    ax.set_title(im,fontsize=25)117    ax.plot([0,1],[0,1],c='0.5',linestyle='--')118    ax.scatter(bpyn,cpyn,c='k',marker='.',s=.75**2)119    ax.contour(xk,yk,zk.reshape(xk.shape),levels=3,cmap='spring')120    f.savefig(f'../Plots/DarkMatterShapes{topapp}.{im}{app}.Pynbody.Contour.png',bbox_inches='tight',pad_inches=.1)121    meta = OSXMetaData(f'../Plots/DarkMatterShapes{topapp}.{im}{app}.Pynbody.Contour.png')122    meta.creator='DarkMatterShapes.Plots.py'123    f,ax = plt.subplots(1,1,figsize=(8,8))124    ax.set_xlim([0,1])125    ax.set_ylim([0,1])126    ax.tick_params(length=5,labelsize=15)127    ax.set_xlabel(f'{lab}b/a [Pynbody]',fontsize=25)128    ax.set_ylabel(f'{lab}c/a [Pynbody]',fontsize=25)129    ax.set_title(im,fontsize=25)130    ax.plot([0,1],[0,1],c='0.5',linestyle='--')131    ax.hist2d(bpyn,cpyn,[bins,bins],cmap='Greys',density=True)132    ax2 = ax.twinx()133    ax2.set_ylim([0,50])134    ax2.set_yticks([])135    ax2.hist(bpyn,bins,histtype='step',facecolor='None',edgecolor='k',density=True)136    ax3 = ax.twiny()137    ax3.set_xlim([0,50])138    ax3.set_xticks([])139    ax3.hist(cpyn,bins,histtype='step',facecolor='None',edgecolor='k',density=True,orientation='horizontal')140    f.savefig(f'../Plots/DarkMatterShapes{topapp}.{im}{app}.Pynbody.Histogram.png',bbox_inches='tight',pad_inches=.1)141    meta = OSXMetaData(f'../Plots/DarkMatterShapes{topapp}.{im}{app}.Pynbody.Histogram.png')142    meta.creator='DarkMatterShapes.Plots.py'143    f,ax = plt.subplots(1,2,figsize=(15,8))144    plt.subplots_adjust(wspace=0)145    for i in [0,1]:146        ax[i].set_xlim([0,1])147        ax[i].set_ylim([0,1])148        ax[i].tick_params(length=5,labelsize=15)149        ax[i].plot([0,1],[0,1],c='0.5',linestyle='--')150    ax[0].set_xlabel(f'{lab}b/a [AHF]',fontsize=25)151    ax[0].set_ylabel(f'{lab}c/a [AHF]',fontsize=25)152    ax[1].set_xlabel(f'{lab}b/a [Pynbody]',fontsize=25)153    ax[1].set_ylabel(f'{lab}c/a [Pynbody]',fontsize=25)154    ax[0].set_xticks([0,.2,.4,.6,.8])155    ax[1].set_yticks([])156    ax[1].yaxis.set_label_position("right")157    f.suptitle(im,fontsize=25)158    ax[0].hist2d(b,c,[bins,bins],cmap='Greys',density=True)159    ax[1].hist2d(bpyn,cpyn,[bins,bins],cmap=truncate_colormap(plt.get_cmap('seismic'), 0.5, 1),density=True)160    ax02 = ax[0].twinx()161    ax02.set_ylim([0,50])162    ax02.set_yticks([])163    ax02.hist(b,bins,histtype='step',facecolor='None',edgecolor='k',density=True)164    ax03 = ax[0].twiny()165    ax03.set_xlim([0,50])166    ax03.set_xticks([])167    ax03.hist(c,bins,histtype='step',facecolor='None',edgecolor='k',density=True,orientation='horizontal')168    ax04 = ax[0].twinx()169    ax04.set_ylim([0,50])170    ax04.set_yticks([])171    ax04.hist(bpyn,bins,histtype='step',facecolor='None',edgecolor='r',density=True)172    ax05 = ax[0].twiny()173    ax05.set_xlim([0,50])174    ax05.set_xticks([])175    ax05.hist(cpyn,bins,histtype='step',facecolor='None',edgecolor='r',density=True,orientation='horizontal')176    ax12 = ax[1].twinx()177    ax12.set_ylim([0,50])178    ax12.set_yticks([])179    ax12.hist(b,bins,histtype='step',facecolor='None',edgecolor='k',density=True)180    ax13 = ax[1].twiny()181    ax13.set_xlim([0,50])182    ax13.set_xticks([])183    ax13.hist(c,bins,histtype='step',facecolor='None',edgecolor='k',density=True,orientation='horizontal')184    ax14 = ax[1].twinx()185    ax14.set_ylim([0,50])186    ax14.set_yticks([])187    ax14.hist(bpyn,bins,histtype='step',facecolor='None',edgecolor='r',density=True)188    ax15 = ax[1].twiny()189    ax15.set_xlim([0,50])190    ax15.set_xticks([])191    ax15.hist(cpyn,bins,histtype='step',facecolor='None',edgecolor='r',density=True,orientation='horizontal')192    f.savefig(f'../Plots/DarkMatterShapes{topapp}.{im}{app}.Comparison.Histogram.png',bbox_inches='tight',pad_inches=.1)193    meta = OSXMetaData(f'../Plots/DarkMatterShapes{topapp}.{im}{app}.Comparison.Histogram.png')...top.py
Source:top.py  
1from argparse import ArgumentParser2from datetime import datetime, timedelta3import pytz4import time5import curses6from attrdict import AttrDict7from hydra.app import HydraApp8from hydra.rpc.base import BaseRPC9from hydra.test import Test10COLOR_GOOD = 211COLOR_WARN = 812COLOR_ERROR = 413COLOR_ETC = 1014@HydraApp.register(name="top", desc="Show status periodically", version="0.1")15class TopApp(HydraApp):16    scr = None17    ljust = None18    @staticmethod19    def parser(parser: ArgumentParser):20        parser.add_argument("-i", "--interval", type=float, default=10, help="polling interval.")21        parser.add_argument("-c", "--count", type=int, default=None, help="exit after (count) iterations.")22        parser.add_argument("-z", "--timezone", type=str, default="America/Los_Angeles", help="time zone.")23        parser.add_argument("-C", "--curses", action="store_true", help="use curses display.")24        parser.add_argument("-x", "--extended", action="store_true", help="show extended info.")25    def setup(self):26        super().setup()27        self.ljust = (30 if not self.args.full else 40)28        if self.args.curses:29            self._curses_setup()30    def run(self):31        interval = self.args.interval32        count = self.args.count33        display = self.display if not self.args.curses else self.display_curses34        try:35            while True:36                display()37                if count is not None:38                    count -= 139                    if count <= 0:40                        break41                time.sleep(interval)42        finally:43            if self.args.curses:44                self._curses_cleanup()45    def read(self):46        result = AttrDict()47        result.now = datetime.now(tz=pytz.timezone(self.args.timezone))48        result.utcnow = datetime.utcnow()49        result.connectioncount = self.rpc.getconnectioncount()50        result.apr = self.rpc.getestimatedannualroi()51        stakinginfo = self.rpc.getstakinginfo()52        stakinginfo["search-interval"] = timedelta(seconds=stakinginfo["search-interval"])53        stakinginfo.expectedtime = timedelta(seconds=stakinginfo.expectedtime)54        stakinginfo.weight /= 10**855        stakinginfo.netstakeweight /= 10**856        if "errors" in stakinginfo and not stakinginfo.errors:57            del stakinginfo["errors"]58        if not self.args.extended:59            TopApp.__try_delete(stakinginfo, "pooledtx")60            61        result.stakinginfo = stakinginfo62        walletinfo = self.rpc.getwalletinfo()63        if "unlocked_until" in walletinfo:64            walletinfo.unlocked_until = datetime.fromtimestamp(walletinfo.unlocked_until)65        if not self.args.extended:66            TopApp.__try_delete(walletinfo, "walletversion")67            TopApp.__try_delete(walletinfo, "keypoololdest")68            TopApp.__try_delete(walletinfo, "keypoolsize")69            TopApp.__try_delete(walletinfo, "keypoolsize_hd_internal")70            TopApp.__try_delete(walletinfo, "paytxfee")71            TopApp.__try_delete(walletinfo, "private_keys_enabled")72            if "unconfirmed_balance" in walletinfo and not walletinfo.unconfirmed_balance:73                del walletinfo.unconfirmed_balance74            if "immature_balance" in walletinfo and not walletinfo.immature_balance:75                del walletinfo.immature_balance76        TopApp.__try_delete(walletinfo, "hdseedid")77        if not len(walletinfo.walletname) and not self.args.json:78            walletinfo.walletname = "''"79            80        result.walletinfo = walletinfo81        if self.args.extended:82            mininginfo = self.rpc.getmininginfo()83            if "errors" in mininginfo and not mininginfo.errors:84                del mininginfo.errors85            if "warnings" in mininginfo and not mininginfo.warnings:86                del mininginfo.warnings87            result.mininginfo = mininginfo88        return result89    # noinspection PyShadowingBuiltins90    def display(self, print=print):91        result = self.read()92        if not self.args.json:93            for key, value in result.items():94                if not isinstance(value, AttrDict):95                    print(key.ljust(self.ljust) + str(value))96                else:97                    print()98                    self.render(value, name=key, print_fn=print, ljust=self.ljust)99        else:100            self.render(result, name="top", print_fn=print, ljust=self.ljust)101    def display_curses(self):102        self.scr.clear()103        self.display(print=self.__print_curses)104        self.scr.refresh()105    def __print_curses(self, text=""):106        text = str(text)107        if not text.endswith("\n"):108            text += "\n"109        return self.scr.addstr(text)110    @staticmethod111    def __try_delete(dic: dict, key: str):112        if key in dic:113            del dic[key]114    # noinspection PyMethodMayBeStatic115    def _curses_cleanup(self):116        curses.echo()117        curses.nocbreak()118        curses.endwin()119    def _curses_setup(self):120        self.scr = curses.initscr()121        curses.noecho()122        curses.cbreak()123        curses.start_color()124        curses.use_default_colors()125        if curses.can_change_color():126            curses.init_color(curses.COLOR_BLACK, 0, 0, 0)127            curses.init_color(curses.COLOR_WHITE, 255, 255, 255)128            curses.init_color(curses.COLOR_GREEN, 0, 255, 0)129            curses.init_color(curses.COLOR_YELLOW, 255, 255, 0)130            curses.init_color(curses.COLOR_RED, 255, 0, 0)131            curses.init_color(curses.COLOR_MAGENTA, 255, 0, 255)132        curses.init_pair(1, curses.COLOR_WHITE, -1)133        curses.init_pair(2, curses.COLOR_GREEN, -1)134        curses.init_pair(3, curses.COLOR_YELLOW, -1)135        curses.init_pair(4, curses.COLOR_RED, -1)136        curses.init_pair(5, curses.COLOR_MAGENTA, -1)137        curses.init_pair(6, curses.COLOR_BLACK, curses.COLOR_WHITE)138        curses.init_pair(7, curses.COLOR_BLACK, curses.COLOR_GREEN)139        curses.init_pair(8, curses.COLOR_BLACK, curses.COLOR_YELLOW)140        curses.init_pair(9, curses.COLOR_BLACK, curses.COLOR_RED)141        curses.init_pair(10, curses.COLOR_YELLOW, -1)142@Test.register()143class TopAppTest(Test):144    MY_FIRST_TEST_FIX = False145    def test_0_top_runnable(self):146        self.assertHydraAppIsRunnable(TopApp, "-h")147if __name__ == "__main__":...test_urltool.py
Source:test_urltool.py  
1"""2Tests of the urltool command-line program3"""4from inspect import cleandoc5from click.testing import CliRunner6from pytest import fixture7import yaml8from werkzeug.routing import Rule9from crosscap import urltool10from crosscap.test.conftest import TopApp, SubApp11def test_dumpRule():12    """13    Do I produce the correct data structure for a rule?14    """15    rule = Rule('/end/', endpoint='end')16    cor = urltool.dumpRule(SubApp, rule, '/sub')17    expect = urltool.ConvertedRule(18            operationId='SubApp.end',19            rulePath='/sub/end/',20            doco=urltool.OpenAPIExtendedDocumentation('This is an endpoint\n\nIt takes nothing and returns "ended"')21            )22    assert cor == expect23    rule2 = Rule('/sub/', endpoint='subTree_branch')24    utr2 = urltool.dumpRule(TopApp, rule2, '')25    expect2 = urltool.ConvertedRule(26            operationId='TopApp.subTree',27            rulePath='/sub/',28            doco=urltool.OpenAPIExtendedDocumentation(''),29            branch=True,30            subKlein='crosscap.test.conftest.SubApp',31            )32    assert utr2 == expect233@fixture34def runner():35    return CliRunner()36def test_filter(runner):37    """38    Do I filter correctly? Forwards and reverse?39    """40    res = runner.invoke(urltool.urltool, ['crosscap.test.conftest.TopApp', 'hasqueryarg'])41    assert res.output.strip() == cleandoc("""42        openapi: 3.0.043        info:44          title: TODO45          version: TODO46        paths:47          /sub/hasqueryarg:48            get:49              summary: This is an endpoint that can be filtered out50              description: |-51                This is an endpoint that can be filtered out52                It takes a query arg and returns it53              operationId: SubApp.hasQueryArg54              parameters:55              - name: color56                in: query57                required: true58    """)59    res = runner.invoke(urltool.urltool, ['crosscap.test.conftest.TopApp', 'hasqueryarg', '--reverse'])60    assert res.output.strip() == cleandoc("""61        openapi: 3.0.062        info:63          title: TODO64          version: TODO65        paths:66          /sub/end:67            get:68              tags:69              - a70              - z71              summary: What is the end?72              description: |-73                What is the end?74                This is the end.75              operationId: SubApp.getEnd76              responses:77                default:78                  content:79                    text/html:80                      x-page-class: crosscap.test.conftest.PageClass81              x-fish:82              - red83              - blue84            post:85              summary: This is an endpoint86              description: |-87                This is an endpoint88                It takes nothing and returns "ended"89              operationId: SubApp.end90            put:91              operationId: SubApp.putEnd92              responses:93                default:94                  content:95                    text/html:96                      x-page-class: crosscap.test.conftest.OtherPageClass97        """)98def test_postOptions(runner):99    """100    Do I produce some nicely-formatted output101    """102    res = runner.invoke(urltool.urltool, ['crosscap.test.conftest.TopApp'])103    assert res.output.strip() == cleandoc("""104        openapi: 3.0.0105        info:106          title: TODO107          version: TODO108        paths:109          /sub/end:110            get:111              tags:112              - a113              - z114              summary: What is the end?115              description: |-116                What is the end?117                This is the end.118              operationId: SubApp.getEnd119              responses:120                default:121                  content:122                    text/html:123                      x-page-class: crosscap.test.conftest.PageClass124              x-fish:125              - red126              - blue127            post:128              summary: This is an endpoint129              description: |-130                This is an endpoint131                It takes nothing and returns "ended"132              operationId: SubApp.end133            put:134              operationId: SubApp.putEnd135              responses:136                default:137                  content:138                    text/html:139                      x-page-class: crosscap.test.conftest.OtherPageClass140          /sub/hasqueryarg:141            get:142              summary: This is an endpoint that can be filtered out143              description: |-144                This is an endpoint that can be filtered out145                It takes a query arg and returns it146              operationId: SubApp.hasQueryArg147              parameters:148              - name: color149                in: query150                required: true151        """)152def test_yamlMultilineString():153    """154    Do I properly represent strings using multiline syntax155    """156    obj = {'thing': 'a\nb'}...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!!
