Best Python code snippet using hypothesis
ImportSeed.js
Source:ImportSeed.js  
1import React, { Component } from 'react'2import styled from 'styled-components'3import { createObserver, collect } from 'dop'4import styles from '/const/styles'5import { minpassword, recovery_phrase_words } from '/const/'6import { bigNumber } from '/api/numbers'7import { Coins } from '/api/coins'8import { validateSeed } from '/api/bip39'9import { setHref, createAsset, setSeed, addNotification } from '/store/actions'10import state from '/store/state'11import {12    isAssetRegisteredBySeed,13    getAssetId,14    getParamsFromLocation,15} from '/store/getters'16import { routes, Show } from '/store/router'17import Input from '/components/styled/Input'18import Div from '/components/styled/Div'19import RadioButton from '/components/styled/RadioButton'20import Textarea from '/components/styled/Textarea'21import Password from '/components/styled/Password'22import Button from '/components/styled/Button'23import Help from '/components/styled/Help'24import Alert from '/components/styled/Alert'25import { Label, SubLabel } from '/components/styled/Label'26import {27    FormField,28    FormFieldLeft,29    FormFieldRight,30    FormFieldButtons,31} from '/components/styled/Form'32import {33    ItemsList,34    ItemList,35    ItemListInner,36    ItemListItemRadio,37    ItemListItemLeft,38    ItemListItemRight,39} from '/components/styled/ItemList'40const STEP = {41    typing: 'typing',42    addresses: 'addresses',43}44export default class ImportPrivate extends Component {45    componentWillMount() {46        const collector = collect()47        state.view.step = STEP.typing48        state.view.is_valid_input = false49        state.view.is_valid_seed = true50        state.view.seed_input = ''51        state.view.seed_input_error = ''52        state.view.seed_password = ''53        state.view.seed_repassword = ''54        state.view.discovering = false55        state.view.addresses = []56        state.view.address_selected = 057        collector.destroy()58        this.observer = createObserver((m) => this.forceUpdate())59        this.observer.observe(state.view)60        this.observer.observe(state.view.addresses, 'length')61        const { symbol } = getParamsFromLocation()62        this.Coin = Coins.hasOwnProperty(symbol) ? Coins[symbol] : Coins.ETH63        this.already_blur = false64        this.onChangeInput = this.onChangeInput.bind(this)65        this.onBlurInput = this.onBlurInput.bind(this)66        this.onChangePassword = this.onChangePassword.bind(this)67        this.onChangeRepassword = this.onChangeRepassword.bind(this)68        this.onNext = this.onNext.bind(this)69        this.onBack = this.onBack.bind(this)70        this.onChangeSelected = this.onChangeSelected.bind(this)71        this.onLoadMore = this.onLoadMore.bind(this)72        this.onSubmit = this.onSubmit.bind(this)73    }74    componentWillUnmount() {75        this.observer.destroy()76    }77    shouldComponentUpdate() {78        return false79    }80    onUpdateSeed() {81        const seed = state.view.seed_input82        if (seed.length > 0) {83            const collector = collect()84            // const { address } = this.Coin.getWalletFromSeed({85            //     seed: seed86            // })87            state.view.is_valid_seed = validateSeed(seed) //&&88            // seed.trim().split(/\s+/g).length === recovery_phrase_words89            if (isAssetRegisteredBySeed(this.Coin.symbol, seed)) {90                state.view.seed_input_error = 'You already have this asset'91                state.view.is_valid_input = false92            } else {93                state.view.seed_input_error = ''94                state.view.is_valid_input = true95            }96            collector.emit()97        }98    }99    onChangeInput(e) {100        const collector = collect()101        const value = e.target.value.trim().replace(/\s+/g, ' ')102        state.view.seed_input = value103        if (this.already_blur) this.onUpdateSeed()104        collector.emit()105    }106    onBlurInput(e) {107        if (!this.already_blur && state.view.seed_input.length > 0) {108            this.already_blur = true109            this.onUpdateSeed()110        }111    }112    onChangePassword(e) {113        state.view.seed_password = e.target.value114    }115    onChangeRepassword(e) {116        state.view.seed_repassword = e.target.value117    }118    onNext(e) {119        e.preventDefault()120        const seed = state.view.seed_input121        const collector = collect()122        state.view.step = STEP.addresses123        this.discoverWallet(seed)124        collector.emit()125    }126    discoverWallet(seed) {127        const collector = collect()128        const addresses = state.view.addresses129        state.view.discovering = true130        this.Coin.discoverWallet({ seed }, (wallet) => {131            // console.log(addresses === state.view.addresses)132            if (addresses === state.view.addresses) {133                state.view.addresses.push(wallet)134            }135        })136            .then((wallet) => {137                // console.log(wallet)138                if (addresses === state.view.addresses) {139                    this.wallet = wallet140                    this.wallet.seed = seed141                    state.view.discovering = false142                }143            })144            .catch((error) => {145                console.log(error)146            })147        collector.emit()148    }149    onLoadMore() {150        state.view.discovering = true151        this.Coin.discoverAddress(this.wallet).then((wallet) => {152            // console.log(wallet)153            const collector = collect()154            this.wallet.index += 1155            state.view.discovering = false156            console.log(1, wallet)157            state.view.addresses.push(wallet)158            collector.emit()159        })160    }161    onBack(e) {162        e.preventDefault()163        const collector = collect()164        state.view.addresses = []165        state.view.step = STEP.typing166        collector.emit()167    }168    onChangeSelected(index) {169        state.view.address_selected = index170    }171    onSubmit(e) {172        e.preventDefault()173        const collector = collect()174        const seed = state.view.seed_input175        const symbol = this.Coin.symbol176        const address = this.Coin.multiaddress177            ? this.wallet.address178            : state.view.addresses[state.view.address_selected].address179        const addresses = state.view.addresses.map((wallet) => wallet.address)180        const asset = createAsset(this.Coin.type, symbol, address, addresses)181        const asset_id = getAssetId(asset)182        setSeed(asset_id, seed, state.view.seed_password)183        setHref(routes.asset({ asset_id: asset_id }))184        addNotification(`New "${symbol}" asset has been imported`)185        collector.emit()186    }187    get isInvalidRepassword() {188        return (189            state.view.seed_password.length > 0 &&190            state.view.seed_repassword.length > 0 &&191            state.view.seed_password.length ===192                state.view.seed_repassword.length &&193            state.view.seed_password !== state.view.seed_repassword194        )195    }196    get isValidForm() {197        return (198            state.view.is_valid_input &&199            state.view.seed_input.length > 0 &&200            state.view.seed_password.length >= minpassword &&201            state.view.seed_password === state.view.seed_repassword202        )203    }204    render() {205        const addresses = state.view.addresses206        const total = addresses.reduce(207            (t, addr) => t.add(addr.balance),208            bigNumber(0)209        )210        return React.createElement(ImportPrivateTemplate, {211            Coin: this.Coin,212            step: state.view.step,213            seed_input: state.view.seed_input,214            seed_input_error: state.view.seed_input_error,215            seed_password: state.view.seed_password,216            seed_repassword: state.view.seed_repassword,217            discovering: state.view.discovering,218            addresses: state.view.addresses,219            address_selected: state.view.address_selected,220            total: total,221            is_valid_seed: state.view.is_valid_seed,222            isValidForm: this.isValidForm,223            isInvalidRepassword: this.isInvalidRepassword,224            onChangeInput: this.onChangeInput,225            onBlurInput: this.onBlurInput,226            onChangePassword: this.onChangePassword,227            onChangeRepassword: this.onChangeRepassword,228            onNext: this.onNext,229            onBack: this.onBack,230            onChangeSelected: this.onChangeSelected,231            onLoadMore: this.onLoadMore,232            onSubmit: this.onSubmit,233        })234    }235}236function ImportPrivateTemplate({237    Coin,238    step,239    seed_input,240    seed_input_error,241    seed_password,242    seed_repassword,243    discovering,244    addresses,245    address_selected,246    total,247    is_valid_seed,248    isValidForm,249    isInvalidRepassword,250    onChangeInput,251    onBlurInput,252    onChangePassword,253    onChangeRepassword,254    onNext,255    onBack,256    onChangeSelected,257    onLoadMore,258    onSubmit,259}) {260    return (261        <div>262            <Show if={step === STEP.typing}>263                <div>264                    <FormField>265                        <FormFieldLeft>266                            <Label>Recovery Phrase</Label>267                            <SubLabel>268                                Type your 12 words in the exact order.269                            </SubLabel>270                        </FormFieldLeft>271                        <FormFieldRight>272                            <Textarea273                                width="100%"274                                value={seed_input}275                                onChange={onChangeInput}276                                onBlur={onBlurInput}277                                error={seed_input_error}278                                invalid={279                                    seed_input_error && seed_input.length > 0280                                }281                            />282                            <Show if={!is_valid_seed && seed_input.length > 0}>283                                {/* <Div padding-top="10px"> */}284                                <Alert>285                                    You typed a non-standard or invalid Recovery286                                    Phrase. But coinfy allow you to import any287                                    other format that comes from other wallets.288                                    Including other languages.289                                </Alert>290                                {/* </Div> */}291                            </Show>292                        </FormFieldRight>293                    </FormField>294                    <FormField>295                        <FormFieldLeft>296                            <Label>Password</Label>297                            <Help>298                                Make sure that you remember this. This password299                                can't be restored because we don't store it. For300                                security reasons you will be asked often for301                                this password.302                            </Help>303                            <SubLabel>304                                This password encrypts your seed key.305                            </SubLabel>306                        </FormFieldLeft>307                        <FormFieldRight>308                            <Password309                                minlength={minpassword}310                                value={seed_password}311                                onChange={onChangePassword}312                                width="100%"313                                type="password"314                            />315                        </FormFieldRight>316                    </FormField>317                    <FormField>318                        <FormFieldLeft>319                            <Label>Repeat Password</Label>320                        </FormFieldLeft>321                        <FormFieldRight>322                            <Input323                                minlength={minpassword}324                                error={'Passwords do not match'}325                                invalid={isInvalidRepassword}326                                value={seed_repassword}327                                onChange={onChangeRepassword}328                                width="100%"329                                type="password"330                            />331                        </FormFieldRight>332                    </FormField>333                    <FormField>334                        <FormFieldButtons>335                            <Button336                                width="100px"337                                disabled={!isValidForm}338                                onClick={onNext}339                            >340                                Next341                            </Button>342                        </FormFieldButtons>343                    </FormField>344                </div>345            </Show>346            <Show if={step === STEP.addresses}>347                <div>348                    <ItemsList>349                        {addresses.map((addr, index) => {350                            const selected =351                                Coin.multiaddress ||352                                (!Coin.multiaddress &&353                                    index === address_selected)354                            return (355                                <ItemList selected={selected}>356                                    <ItemListInner>357                                        <Show if={!Coin.multiaddress}>358                                            <ItemListItemRadio>359                                                <RadioButton360                                                    onClick={(e) =>361                                                        onChangeSelected(index)362                                                    }363                                                    checked={selected}364                                                />365                                            </ItemListItemRadio>366                                        </Show>367                                        <ItemListItemLeft>368                                            {addr.address}369                                        </ItemListItemLeft>370                                        <ItemListItemRight371                                            error={addr.fetched !== true}372                                        >373                                            {`${addr.balance} ${Coin.symbol}`}374                                        </ItemListItemRight>375                                    </ItemListInner>376                                </ItemList>377                            )378                        })}379                    </ItemsList>380                    <ResultAddress>381                        <Show if={!discovering}>382                            <LoadMore onClick={onLoadMore}>383                                Load more Addresses384                            </LoadMore>385                        </Show>386                        <Total>387                            {total} {Coin.symbol}388                        </Total>389                    </ResultAddress>390                    <Div margin-top="35px">391                        <FormField>392                            <FormFieldButtons>393                                <Button394                                    width="100px"395                                    loading={discovering}396                                    loadingIco="/static/image/loading.gif"397                                    onClick={onSubmit}398                                >399                                    Import400                                </Button>401                            </FormFieldButtons>402                            <FormFieldButtons>403                                <Button width="100px" onClick={onBack}>404                                    Back405                                </Button>406                            </FormFieldButtons>407                        </FormField>408                    </Div>409                </div>410            </Show>411        </div>412    )413}414export const ResultAddress = styled.div`415    border-top: 2px solid ${styles.color.background1};416    padding: 12px;417    font-size: 16px;418`419export const LoadMore = styled.a`420    font-size: 13px;421    color: ${styles.color.background2};422    text-decoration: underline;423    cursor: pointer;424    display: block;425    float: left;426    &:hover {427        color: ${styles.color.background3};428    }429`430export const Total = styled.div`431    color: ${styles.color.background2};432    font-weight: 900;433    float: right;434    font-size: 16px;...btc.js
Source:btc.js  
1import test from 'tape'2import fetch from 'node-fetch'3import BigNumber from 'bignumber.js'4import {5    TYPE_COIN,6    MAINNET,7    TESTNET,8    ASSET_LOGO,9    LOCALSTORAGE_NETWORK10} from '/const/'11import {12    setupNetwork,13    networks,14    type,15    symbol,16    symbol_fee,17    name,18    color,19    ascii,20    coin_decimals,21    price_decimals,22    satoshis,23    multiaddress,24    changeaddress,25    labels,26    logo,27    derivation_path,28    format,29    cutDecimals,30    toSatoshis,31    getWalletFromSeed,32    getWalletsFromSeed,33    isAddress,34    isPrivateKey,35    formatAddress,36    getAddressFromPrivateKey,37    getSegwitAddressFromPrivateKey,38    urlInfo,39    urlInfoTx,40    urlDecodeTx,41    encryptSeed,42    decryptSeed,43    encryptPrivateKey,44    decryptPrivateKey,45    decryptPrivateKeyFromSeed,46    getNextWalletFromSeed,47    decryptWalletFromSeed,48    encryptBIP38,49    decryptBIP38,50    discoverAddress,51    discoverWallet,52    fetchBalance,53    fetchRecomendedFee,54    fetchTxs,55    createSimpleTx,56    getSendProviders57} from '/api/coins/BTC'58global.fetch = fetch59const seed =60    'civil void tool perfect avocado sweet immense fluid arrow aerobic boil flash'61const private_key = 'L5YsAenc5eCuDFhEcC9DNe8sw47ttEevfMieRWKjGK5cP6ZpvxyE'62const addresses = ['34QtpB4V3ETz2p3QuNEdEqTCYjTHHP2XMY']63test('setupNetwork', t => {64    t.equal(setupNetwork(MAINNET, networks), true, 'setupNetwork')65    t.end()66})67test('Exists / Types', t => {68    t.equal(typeof networks, 'object', 'networks')69    t.equal(typeof networks[MAINNET], 'object', 'networks 2')70    t.equal(typeof networks[MAINNET].url, 'string', 'networks 3')71    // t.equal(typeof networks[MAINNET].network, 'object', 'networks 4')72    t.equal(typeof setupNetwork, 'function', 'setupNetwork')73    t.equal(type, TYPE_COIN, 'type')74    t.equal(typeof symbol, 'string', 'symbol')75    t.equal(typeof symbol_fee, 'string', 'symbol_fee')76    t.equal(typeof name, 'string', 'name')77    t.equal(typeof color, 'string', 'color')78    t.equal(typeof color, 'string', 'color')79    t.equal(typeof ascii, 'string', 'ascii')80    t.equal(typeof coin_decimals, 'number', 'coin_decimals')81    t.equal(typeof price_decimals, 'number', 'price_decimals')82    t.equal(typeof satoshis, 'number', 'satoshis')83    t.equal(typeof multiaddress, 'boolean', 'multiaddress')84    t.equal(typeof changeaddress, 'boolean', 'changeaddress')85    t.equal(typeof labels, 'string', 'labels')86    t.equal(typeof logo, 'string', 'logo')87    t.equal(typeof derivation_path, 'object', 'derivation_path')88    t.equal(typeof derivation_path.mainnet, 'function', 'derivation_path 2')89    t.end()90})91test('Numbers', t => {92    t.equal(format(12), `12 ${symbol}`, 'format')93    t.equal(format(12.12345, 4), `12.1234 ${symbol}`, 'format 2')94    t.equal(cutDecimals(12.123456789), `12.12345678`, 'cutDecimals')95    t.end()96})97test('Wallets / Address / Accounts / PrivateKeys', t => {98    const wallet = getWalletFromSeed({ seed })99    const wallet2 = getWalletFromSeed({ seed, segwit: false })100    t.equal(isAddress(wallet.address), true, 'isAddress')101    t.equal(isPrivateKey(wallet.private_key), true, 'isPrivateKey')102    t.deepEqual(103        wallet,104        {105            address: '39hFXsmKPPNuKmMspjLvi5BT1n5XjbA4CT',106            private_key: 'L16cg8Azn34WH8BKGqAQsJ1c59UJDhCuLR3JZafUi1ASJEVZ96FH'107        },108        'getWalletFromSeed'109    )110    t.deepEqual(111        getWalletFromSeed({ seed, segwit: false }),112        {113            address: '1KMyB2466uJzWuJgwxMEYud6xhAexJHwyM',114            private_key: 'L1FAYi6Hk6X9fa8NGDp5Whh7GBUfpuHeU6wcEdHQeZ6rfb4VG2y7'115        },116        'getWalletFromSeed'117    )118    t.deepEqual(119        getWalletsFromSeed({ seed, count: 2 }),120        [121            {122                address: '39hFXsmKPPNuKmMspjLvi5BT1n5XjbA4CT',123                private_key:124                    'L16cg8Azn34WH8BKGqAQsJ1c59UJDhCuLR3JZafUi1ASJEVZ96FH'125            },126            {127                address: '3QTyfe1J3CETz99TGynuip4DTGWAwfEpu6',128                private_key: private_key129            }130        ],131        'getWalletsFromSeed'132    )133    t.equal(134        getSegwitAddressFromPrivateKey(wallet.private_key),135        wallet.address,136        'getSegwitAddressFromPrivateKey'137    )138    t.equal(139        getAddressFromPrivateKey(wallet2.private_key),140        wallet2.address,141        'getAddressFromPrivateKey'142    )143    t.equal(formatAddress(wallet.address), wallet.address, 'formatAddress')144    t.end()145})146test('Urls', t => {147    t.equal(typeof urlInfo('addres'), 'string', 'urlInfo')148    t.equal(typeof urlInfoTx('addres'), 'string', 'urlInfoTx')149    t.equal(typeof urlDecodeTx('addres'), 'string', 'urlDecodeTx')150    t.end()151})152test('encryptSeed decryptSeed', t => {153    const pass = '1234'154    const wallet = getWalletFromSeed({ seed })155    const encrypted = encryptSeed(seed, pass)156    const decrypted = decryptSeed([wallet.address], encrypted, pass)157    t.equal(typeof encrypted, 'object', 'encryptSeed')158    t.equal(typeof encrypted.ciphertext, 'string', 'encryptSeed 2')159    t.equal(encrypted.cipher, 'aes-128-ctr', 'encryptSeed 2')160    t.equal(encrypted.kdf, 'scrypt', 'encryptSeed 3')161    t.equal(typeof encrypted.kdfparams, 'object', 'encryptSeed 4')162    t.equal(decrypted, seed, 'decryptSeed')163    t.end()164})165test('encryptPrivateKey decryptPrivateKey', t => {166    const pass = '1234'167    const address = getAddressFromPrivateKey(private_key)168    const encrypted = encryptPrivateKey(private_key, pass)169    const decrypted = decryptPrivateKey(address, encrypted, pass)170    t.equal(typeof encrypted, 'object', 'encryptPrivateKey')171    t.equal(typeof encrypted.ciphertext, 'string', 'encryptPrivateKey 2')172    t.equal(encrypted.cipher, 'aes-128-ctr', 'encryptPrivateKey 2')173    t.equal(encrypted.kdf, 'scrypt', 'encryptPrivateKey 3')174    t.equal(typeof encrypted.kdfparams, 'object', 'encryptPrivateKey 4')175    t.equal(decrypted, private_key, 'decryptPrivateKey')176    t.end()177})178test('decryptPrivateKeyFromSeed', t => {179    const pass = '1234'180    const wallets = getWalletsFromSeed({ seed, count: 2 })181    const encrypted = encryptSeed(seed, pass)182    const private_key = decryptPrivateKeyFromSeed(183        wallets[1].address,184        wallets.map(wallet => wallet.address),185        encrypted,186        pass187    )188    t.equal(private_key, wallets[1].private_key)189    t.end()190})191test('getNextWalletFromSeed', t => {192    const pass = '1234'193    const wallets = getWalletsFromSeed({ seed, count: 3 })194    const encrypted = encryptSeed(seed, pass)195    const wallet = getNextWalletFromSeed(196        wallets[1].address,197        wallets.map(wallet => wallet.address),198        encrypted,199        pass200    )201    t.deepEqual(wallet, wallets[2])202    t.end()203})204test('decryptWalletFromSeed', t => {205    const pass = '1234'206    const wallets = getWalletsFromSeed({ seed, count: 3 })207    const encrypted = encryptSeed(seed, pass)208    const wallet = decryptWalletFromSeed(209        wallets[1].address,210        wallets.map(wallet => wallet.address),211        encrypted,212        pass213    )214    t.equal(wallet.address, wallets[1].address, 'decryptWalletFromSeed.address')215    t.equal(216        wallet.private_key,217        wallets[1].private_key,218        'decryptWalletFromSeed.private_key'219    )220    t.equal(wallet.seed, seed, 'decryptWalletFromSeed.seed')221    t.end()222})223test('encryptBIP38 decryptBIP38', t => {224    const pass = '1234'225    const encrypted = encryptBIP38(private_key, pass)226    const decrypted = decryptBIP38(encrypted, pass)227    t.equal(private_key, decrypted)228    t.end()229})230test('discoverAddress', t => {231    const wallet = getWalletFromSeed({ seed, segwit: false })232    return discoverAddress({ seed }).then(233        ({ address, balance, totalReceived }) => {234            t.equal(address, wallet.address)235            t.equal(typeof balance, 'string')236            t.equal(typeof totalReceived, 'string')237            t.end()238        }239    )240})241test('discoverAddress segwit', t => {242    const wallet = getWalletFromSeed({ seed, segwit: true })243    return discoverAddress({ seed, segwit: true }).then(244        ({ address, balance, totalReceived }) => {245            t.equal(address, wallet.address)246            t.end()247        }248    )249})250test('discoverWallet', t => {251    return discoverWallet({ seed }).then(252        data => {253            t.equal(Array.isArray(data.addresses), true)254            t.equal(typeof data.index, 'number')255            t.equal(typeof data.segwit, 'boolean')256            t.equal(data.address, data.addresses[data.addresses.length - 1])257            t.end()258        },259        wallet => {260            // to do261        }262    )263})264test('fetchRecomendedFee', t => {265    return fetchRecomendedFee({266        addresses: addresses267    }).then(fee => {268        t.equal(typeof fee, 'string')269        t.equal(typeof Number(fee), 'number')270        t.equal(isNaN(Number(fee)), false)271        t.end()272    })273})274test('fetchTxs', t => {275    return fetchTxs(addresses).then(txs => {276        t.equal(typeof txs, 'object')277        t.equal(typeof txs.totalTxs, 'number')278        t.equal(Array.isArray(txs.txs), true)279        if (txs.txs.length > 0) {280            t.equal(typeof txs.txs[0].value, 'string', 'value')281            t.equal(282                BigNumber(txs.txs[0].value).toFixed(),283                txs.txs[0].value,284                'value fixnumber'285            )286            t.equal(typeof txs.txs[0].fees, 'string', 'fees')287            t.equal(288                BigNumber(txs.txs[0].fees).toFixed(),289                txs.txs[0].fees,290                'fees fixnumber'291            )292            t.equal(typeof txs.txs[0].time, 'number')293            t.equal(typeof txs.txs[0].txid, 'string')294        }295        t.end()296    })297})298test('createSimpleTx', t => {299    setupNetwork(TESTNET, networks) // changing to testnet300    return createSimpleTx({301        from_addresses: ['mm42obtLkUesaHxj5i236B9hJ7m6yv4Ujg'],302        private_keys: ['cRkNqWAK64qSooKnadaFLa9uhSK1QtgkD5ezJQcsn1Fz5LQSnHT5'],303        to_address: '2N9Cki8ABz6oXuoF24rd5eAFPwwVpEWYctt',304        amount: 1,305        fee: 0.01306    }).then(txsigned => {307        t.equal(typeof txsigned, 'string')308        t.end()309    })310})311test('getSendProviders', t => {312    setupNetwork(MAINNET, networks) // changing to testnet313    const providers = getSendProviders()314    t.equal(Array.isArray(providers), true)315    t.equal(typeof providers[0].name, 'string')316    t.equal(typeof providers[0].url, 'string')317    t.equal(typeof providers[0].send, 'function')318    t.end()...test_all_random_functions.py
Source:test_all_random_functions.py  
...5from networkx.algorithms import approximation as approx6from networkx.algorithms import threshold7progress = 08# store the random numbers after setting a global seed9np.random.seed(42)10np_rv = np.random.rand()11random.seed(42)12py_rv = random.random()13def t(f, *args, **kwds):14    """call one function and check if global RNG changed"""15    global progress16    progress += 117    print(progress, ",", end="")18    f(*args, **kwds)19    after_np_rv = np.random.rand()20    # if np_rv != after_np_rv:21    #    print(np_rv, after_np_rv, "don't match np!")22    assert np_rv == after_np_rv23    np.random.seed(42)24    after_py_rv = random.random()25    # if py_rv != after_py_rv:26    #    print(py_rv, after_py_rv, "don't match py!")27    assert py_rv == after_py_rv28    random.seed(42)29def run_all_random_functions(seed):30    n = 2031    m = 1032    k = l = 233    s = v = 1034    p = q = p1 = p2 = p_in = p_out = 0.435    alpha = radius = theta = 0.7536    sizes = (20, 20, 10)37    colors = [1, 2, 3]38    G = nx.barbell_graph(12, 20)39    deg_sequence = [3, 2, 1, 3, 2, 1, 3, 2, 1, 2, 1, 2, 1]40    in_degree_sequence = w = sequence = aseq = bseq = deg_sequence41    # print("starting...")42    t(nx.maximal_independent_set, G, seed=seed)43    t(nx.rich_club_coefficient, G, seed=seed, normalized=False)44    t(nx.random_reference, G, seed=seed)45    t(nx.lattice_reference, G, seed=seed)46    t(nx.sigma, G, 1, 2, seed=seed)47    t(nx.omega, G, 1, 2, seed=seed)48    # print("out of smallworld.py")49    t(nx.double_edge_swap, G, seed=seed)50    # print("starting connected_double_edge_swap")51    t(nx.connected_double_edge_swap, nx.complete_graph(9), seed=seed)52    # print("ending connected_double_edge_swap")53    t(nx.random_layout, G, seed=seed)54    t(nx.fruchterman_reingold_layout, G, seed=seed)55    t(nx.algebraic_connectivity, G, seed=seed)56    t(nx.fiedler_vector, G, seed=seed)57    t(nx.spectral_ordering, G, seed=seed)58    # print('starting average_clustering')59    t(approx.average_clustering, G, seed=seed)60    t(nx.betweenness_centrality, G, seed=seed)61    t(nx.edge_betweenness_centrality, G, seed=seed)62    t(nx.edge_betweenness, G, seed=seed)63    t(nx.approximate_current_flow_betweenness_centrality, G, seed=seed)64    # print("kernighan")65    t(nx.algorithms.community.kernighan_lin_bisection, G, seed=seed)66    # nx.algorithms.community.asyn_lpa_communities(G, seed=seed)67    t(nx.algorithms.tree.greedy_branching, G, seed=seed)68    t(nx.algorithms.tree.Edmonds, G, seed=seed)69    # print('done with graph argument functions')70    t(nx.spectral_graph_forge, G, alpha, seed=seed)71    t(nx.algorithms.community.asyn_fluidc, G, k, max_iter=1, seed=seed)72    t(73        nx.algorithms.connectivity.edge_augmentation.greedy_k_edge_augmentation,74        G,75        k,76        seed=seed,77    )78    t(nx.algorithms.coloring.strategy_random_sequential, G, colors, seed=seed)79    cs = ["d", "i", "i", "d", "d", "i"]80    t(threshold.swap_d, cs, seed=seed)81    t(nx.configuration_model, deg_sequence, seed=seed)82    t(83        nx.directed_configuration_model,84        in_degree_sequence,85        in_degree_sequence,86        seed=seed,87    )88    t(nx.expected_degree_graph, w, seed=seed)89    t(nx.random_degree_sequence_graph, sequence, seed=seed)90    joint_degrees = {91        1: {4: 1},92        2: {2: 2, 3: 2, 4: 2},93        3: {2: 2, 4: 1},94        4: {1: 1, 2: 2, 3: 1},95    }96    t(nx.joint_degree_graph, joint_degrees, seed=seed)97    joint_degree_sequence = [98        (1, 0),99        (1, 0),100        (1, 0),101        (2, 0),102        (1, 0),103        (2, 1),104        (0, 1),105        (0, 1),106    ]107    t(nx.random_clustered_graph, joint_degree_sequence, seed=seed)108    constructor = [(3, 3, 0.5), (10, 10, 0.7)]109    t(nx.random_shell_graph, constructor, seed=seed)110    mapping = {1: 0.4, 2: 0.3, 3: 0.3}111    t(nx.utils.random_weighted_sample, mapping, k, seed=seed)112    t(nx.utils.weighted_choice, mapping, seed=seed)113    t(nx.algorithms.bipartite.configuration_model, aseq, bseq, seed=seed)114    t(nx.algorithms.bipartite.preferential_attachment_graph, aseq, p, seed=seed)115    def kernel_integral(u, w, z):116        return z - w117    t(nx.random_kernel_graph, n, kernel_integral, seed=seed)118    sizes = [75, 75, 300]119    probs = [[0.25, 0.05, 0.02], [0.05, 0.35, 0.07], [0.02, 0.07, 0.40]]120    t(nx.stochastic_block_model, sizes, probs, seed=seed)121    t(nx.random_partition_graph, sizes, p_in, p_out, seed=seed)122    # print("starting generator functions")123    t(threshold.random_threshold_sequence, n, p, seed=seed)124    t(nx.tournament.random_tournament, n, seed=seed)125    t(nx.relaxed_caveman_graph, l, k, p, seed=seed)126    t(nx.planted_partition_graph, l, k, p_in, p_out, seed=seed)127    t(nx.gaussian_random_partition_graph, n, s, v, p_in, p_out, seed=seed)128    t(nx.gn_graph, n, seed=seed)129    t(nx.gnr_graph, n, p, seed=seed)130    t(nx.gnc_graph, n, seed=seed)131    t(nx.scale_free_graph, n, seed=seed)132    t(nx.directed.random_uniform_k_out_graph, n, k, seed=seed)133    t(nx.random_k_out_graph, n, k, alpha, seed=seed)134    N = 1000135    t(nx.partial_duplication_graph, N, n, p, q, seed=seed)136    t(nx.duplication_divergence_graph, n, p, seed=seed)137    t(nx.random_geometric_graph, n, radius, seed=seed)138    t(nx.soft_random_geometric_graph, n, radius, seed=seed)139    t(nx.geographical_threshold_graph, n, theta, seed=seed)140    t(nx.waxman_graph, n, seed=seed)141    t(nx.navigable_small_world_graph, n, seed=seed)142    t(nx.thresholded_random_geometric_graph, n, radius, theta, seed=seed)143    t(nx.uniform_random_intersection_graph, n, m, p, seed=seed)144    t(nx.k_random_intersection_graph, n, m, k, seed=seed)145    t(nx.general_random_intersection_graph, n, 2, [0.1, 0.5], seed=seed)146    t(nx.fast_gnp_random_graph, n, p, seed=seed)147    t(nx.gnp_random_graph, n, p, seed=seed)148    t(nx.dense_gnm_random_graph, n, m, seed=seed)149    t(nx.gnm_random_graph, n, m, seed=seed)150    t(nx.newman_watts_strogatz_graph, n, k, p, seed=seed)151    t(nx.watts_strogatz_graph, n, k, p, seed=seed)152    t(nx.connected_watts_strogatz_graph, n, k, p, seed=seed)153    t(nx.random_regular_graph, 3, n, seed=seed)154    t(nx.barabasi_albert_graph, n, m, seed=seed)155    t(nx.extended_barabasi_albert_graph, n, m, p, q, seed=seed)156    t(nx.powerlaw_cluster_graph, n, m, p, seed=seed)157    t(nx.random_lobster, n, p1, p2, seed=seed)158    t(nx.random_powerlaw_tree, n, seed=seed, tries=5000)159    t(nx.random_powerlaw_tree_sequence, 10, seed=seed, tries=5000)160    t(nx.random_tree, n, seed=seed)161    t(nx.utils.powerlaw_sequence, n, seed=seed)162    t(nx.utils.zipf_rv, 2.3, seed=seed)163    cdist = [0.2, 0.4, 0.5, 0.7, 0.9, 1.0]164    t(nx.utils.discrete_sequence, n, cdistribution=cdist, seed=seed)165    t(nx.algorithms.bipartite.random_graph, n, m, p, seed=seed)166    t(nx.algorithms.bipartite.gnmk_random_graph, n, m, k, seed=seed)167    LFR = nx.generators.LFR_benchmark_graph168    t(169        LFR,170        25,171        3,172        1.5,173        0.1,174        average_degree=3,175        min_community=10,176        seed=seed,177        max_community=20,178    )179    t(nx.random_internet_as_graph, n, seed=seed)180    # print("done")181# choose to test an integer seed, or whether a single RNG can be everywhere182# np_rng = np.random.RandomState(14)183# seed = np_rng184# seed = 14185@pytest.mark.slow186# print("NetworkX Version:", nx.__version__)187def test_rng_interface():188    global progress189    # try different kinds of seeds190    for seed in [14, np.random.RandomState(14)]:191        np.random.seed(42)192        random.seed(42)193        run_all_random_functions(seed)194        progress = 0195        # check that both global RNGs are unaffected196        after_np_rv = np.random.rand()197        #        if np_rv != after_np_rv:198        #            print(np_rv, after_np_rv, "don't match np!")199        assert np_rv == after_np_rv200        after_py_rv = random.random()201        #        if py_rv != after_py_rv:202        #            print(py_rv, after_py_rv, "don't match py!")203        assert py_rv == after_py_rv204#        print("\nDone testing seed:", seed)...test_random_noise.py
Source:test_random_noise.py  
1from numpy.testing import assert_array_equal, assert_allclose, assert_raises2import numpy as np3from skimage.data import camera4from skimage.util import random_noise, img_as_float5def test_set_seed():6    seed = 427    cam = camera()8    test = random_noise(cam, seed=seed)9    assert_array_equal(test, random_noise(cam, seed=seed))10def test_salt():11    seed = 4212    cam = img_as_float(camera())13    cam_noisy = random_noise(cam, seed=seed, mode='salt', amount=0.15)14    saltmask = cam != cam_noisy15    # Ensure all changes are to 1.016    assert_allclose(cam_noisy[saltmask], np.ones(saltmask.sum()))17    # Ensure approximately correct amount of noise was added18    proportion = float(saltmask.sum()) / (cam.shape[0] * cam.shape[1])19    assert 0.11 < proportion <= 0.1520def test_pepper():21    seed = 4222    cam = img_as_float(camera())23    data_signed = cam * 2. - 1.   # Same image, on range [-1, 1]24    cam_noisy = random_noise(cam, seed=seed, mode='pepper', amount=0.15)25    peppermask = cam != cam_noisy26    # Ensure all changes are to 1.027    assert_allclose(cam_noisy[peppermask], np.zeros(peppermask.sum()))28    # Ensure approximately correct amount of noise was added29    proportion = float(peppermask.sum()) / (cam.shape[0] * cam.shape[1])30    assert 0.11 < proportion <= 0.1531    # Check to make sure pepper gets added properly to signed images32    orig_zeros = (data_signed == -1).sum()33    cam_noisy_signed = random_noise(data_signed, seed=seed, mode='pepper',34                                    amount=.15)35    proportion = (float((cam_noisy_signed == -1).sum() - orig_zeros) /36                  (cam.shape[0] * cam.shape[1]))37    assert 0.11 < proportion <= 0.1538def test_salt_and_pepper():39    seed = 4240    cam = img_as_float(camera())41    cam_noisy = random_noise(cam, seed=seed, mode='s&p', amount=0.15,42                             salt_vs_pepper=0.25)43    saltmask = np.logical_and(cam != cam_noisy, cam_noisy == 1.)44    peppermask = np.logical_and(cam != cam_noisy, cam_noisy == 0.)45    # Ensure all changes are to 0. or 1.46    assert_allclose(cam_noisy[saltmask], np.ones(saltmask.sum()))47    assert_allclose(cam_noisy[peppermask], np.zeros(peppermask.sum()))48    # Ensure approximately correct amount of noise was added49    proportion = float(50        saltmask.sum() + peppermask.sum()) / (cam.shape[0] * cam.shape[1])51    assert 0.11 < proportion <= 0.1852    # Verify the relative amount of salt vs. pepper is close to expected53    assert 0.18 < saltmask.sum() / float(peppermask.sum()) < 0.3254def test_gaussian():55    seed = 4256    data = np.zeros((128, 128)) + 0.557    data_gaussian = random_noise(data, seed=seed, var=0.01)58    assert 0.008 < data_gaussian.var() < 0.01259    data_gaussian = random_noise(data, seed=seed, mean=0.3, var=0.015)60    assert 0.28 < data_gaussian.mean() - 0.5 < 0.3261    assert 0.012 < data_gaussian.var() < 0.01862def test_localvar():63    seed = 4264    data = np.zeros((128, 128)) + 0.565    local_vars = np.zeros((128, 128)) + 0.00166    local_vars[:64, 64:] = 0.167    local_vars[64:, :64] = 0.2568    local_vars[64:, 64:] = 0.4569    data_gaussian = random_noise(data, mode='localvar', seed=seed,70                                 local_vars=local_vars, clip=False)71    assert 0. < data_gaussian[:64, :64].var() < 0.00272    assert 0.095 < data_gaussian[:64, 64:].var() < 0.10573    assert 0.245 < data_gaussian[64:, :64].var() < 0.25574    assert 0.445 < data_gaussian[64:, 64:].var() < 0.45575    # Ensure local variance bounds checking works properly76    bad_local_vars = np.zeros_like(data)77    assert_raises(ValueError, random_noise, data, mode='localvar', seed=seed,78                  local_vars=bad_local_vars)79    bad_local_vars += 0.180    bad_local_vars[0, 0] = -181    assert_raises(ValueError, random_noise, data, mode='localvar', seed=seed,82                  local_vars=bad_local_vars)83def test_speckle():84    seed = 4285    data = np.zeros((128, 128)) + 0.186    np.random.seed(seed=seed)87    noise = np.random.normal(0.1, 0.02 ** 0.5, (128, 128))88    expected = np.clip(data + data * noise, 0, 1)89    data_speckle = random_noise(data, mode='speckle', seed=seed, mean=0.1,90                                var=0.02)91    assert_allclose(expected, data_speckle)92def test_poisson():93    seed = 4294    data = camera()  # 512x512 grayscale uint895    cam_noisy = random_noise(data, mode='poisson', seed=seed)96    cam_noisy2 = random_noise(data, mode='poisson', seed=seed, clip=False)97    np.random.seed(seed=seed)98    expected = np.random.poisson(img_as_float(data) * 256) / 256.99    assert_allclose(cam_noisy, np.clip(expected, 0., 1.))100    assert_allclose(cam_noisy2, expected)101def test_clip_poisson():102    seed = 42103    data = camera()                             # 512x512 grayscale uint8104    data_signed = img_as_float(data) * 2. - 1.  # Same image, on range [-1, 1]105    # Signed and unsigned, clipped106    cam_poisson = random_noise(data, mode='poisson', seed=seed, clip=True)107    cam_poisson2 = random_noise(data_signed, mode='poisson', seed=seed,108                                clip=True)109    assert (cam_poisson.max() == 1.) and (cam_poisson.min() == 0.)110    assert (cam_poisson2.max() == 1.) and (cam_poisson2.min() == -1.)111    # Signed and unsigned, unclipped...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!!
