id
stringlengths
3
8
content
stringlengths
100
981k
4845288
import serial import serial.tools.list_ports myports = [tuple(p) for p in list(serial.tools.list_ports.comports())] print(myports) ser = serial.Serial('/dev/ttyACM0',9600,timeout=0) ser2 = serial.Serial('/dev/ttyAMA00',9600,timeout=0) #ser2.close() #print(ser.inWaiting()) #print(ser2.inWaiting()) #ser.open() #ser.wri...
4845338
import requests from bs4 import BeautifulSoup import re from pyaparat.exceptions import QualityError qualities = { '144': 0, '240': 1, '360': 2, '480': 3, '720': 4, '1080': 5 } class Scraper: def __init__(self, url, quality): self.url = url self.quality = quality def get_all_links(self): """ takes ...
4845346
import unittest from regulations.uitests.base_test import BaseTest class SubheaderTests(BaseTest, unittest.TestCase): job_name = 'Subheader tests' def test_effective_date(self): self.driver.get(self.test_url + '/1005-1/2012-12121') effective = self.driver.find_element_by_class_name('effectiv...
4845375
class MultOp: def __init__(self, op, factor): self.op = op self.shape = op.shape self.factor = factor def nearfield_dot(self, v): return self.factor * self.op.nearfield_dot(v) def nearfield_no_correction_dot(self, v): return self.factor * self.op.nearfield_no_correc...
4845379
import re import math from datetime import datetime API_SUFFIX = '/api/json' NODE_SLAVE = 'hudson.slaves.SlaveComputer' NODE_LABELS = 'totalExecutors,busyExecutors,\ computer[_class,displayName,offline,numExecutors,monitorData[*]]' SWAP_SPACE_MONITOR = 'hudson.node_monitors.SwapSpaceMonitor' SWAP_SPACE_LABELS = [ ...
4845380
import os import random import sys from io import StringIO from unittest.mock import patch import pytest from multicrypto.address import get_address_range from multicrypto.base58 import base58 from multicrypto.coins import coins from multicrypto.commands.genaddress import generate_address, main from multicrypto.const...
4845387
import tensorflow_quantum as tfq import tensorflow as tf import cirq import sympy import random import matplotlib.pyplot as plt import numpy as np def make_data(n1, n2): qubit = cirq.GridQubit(0,0) train, test = [], [] train_label, test_label = [], [] for _ in range(n1): cir = cirq.Circuit() ...
4845391
from alibi_detect.base import BaseDetector, adversarial_prediction_dict import numpy as np from unittest import TestCase from adserver.ad_model import AlibiDetectAdversarialDetectionModel from adserver.constants import HEADER_RETURN_INSTANCE_SCORE from typing import Dict class DummyAEModel(BaseDetector): def __in...
4845393
import paddle import paddle.nn as nn def droppath(x, drop_prob=0., training=False): """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... See discussion: https://gi...
4845395
import re def is_dynamic_reference(input): """ Checks if the given input is a dynamic reference. Dynamic references follow the pattern '{{resolve:service-name:reference-key}}' This method does not validate if the dynamic reference is valid or not, only if it follows the valid pattern: {{resolve:service-n...
4845433
import tensorflowjs as tfjs import tensorflow as tf import subprocess import ssl ssl._create_default_https_context = ssl._create_unverified_context # load model from keras applications # see other models here: https://keras.io/api/applications model = tf.keras.applications.ResNet50(include_top=True, weights="im...
4845469
from __future__ import print_function import numpy as np import mahotas from mahotas.thresholding import soft_threshold from matplotlib import pyplot as plt from os import path # Let us load the data first: luispedro_image = path.join( path.dirname(path.abspath(__file__)), 'data...
4845474
from scapy.all import * from ccsds_base import CCSDSPacket class PL_IF_NOOP_CmdPkt(Packet): """Generate an info event message with app version app = PL_IF command = NOOP msg_id = PL_IF_CMD_MID = 0x19d9 = 0x1800 + 0x1d9 cmd_func_code = 0 data_len = 0 bytes """ name = "PL_IF_NOOP_CmdPkt...
4845479
from typing import Any, List, Optional from deep500.utils.metric import TestMetric from deep500.lv2.sampler import Sampler from deep500.lv2.event import SamplerEvent def test_sampler(sampler: Sampler, expected_output: Optional[Any] = None, metrics: List[TestMetric] = [], events: Lis...
4845480
import logging import os import torch from torch.utils.data import DataLoader from torchvision import datasets, transforms import models from pytorch_hebbian import config from pytorch_hebbian.evaluators import SupervisedEvaluator from pytorch_hebbian.utils import load_weights PATH = os.path.dirname(os.path.abspath(...
4845502
from __future__ import absolute_import, division, print_function, unicode_literals import subprocess from beast.util import String def execute(args, include_errors=True, **kwds): """Execute a shell command and return the value. If args is a string, it's split on spaces - if some of your arguments contain sp...
4845506
import numpy as np from . import xfrac_file from . import density_file from . import conv from .helper_functions import get_data_and_type def plot_slice(data, los_axis = 0, slice_num = 0, logscale = False, **kwargs): ''' Plot a slice through a data cube. This function will produce a nicely formatted image ...
4845507
from telegram import Update from telegram.ext import CallbackContext from src.exceptions import ResourceNotFoundException from src.services import SERVICES from src.utils import reply_html, unwrap def generate_user_list(chat: dict, users: list[dict]) -> str: if not users: return "There are no members in ...
4845593
import numpy as np import torch import torch.distributed as dist from self_supervised.model import MYOW, MLP3 from self_supervised.trainer import BYOLTrainer class MYOWTrainer(BYOLTrainer): def __init__(self, view_pool_dataloader=None, transform_m=None, myow_warmup_epochs=0, myow_rampup_epochs=N...
4845620
import os import requests from pytest import raises, skip from teuthology.config import config from teuthology import suite class TestSuiteOnline(object): def setup(self): if 'TEST_ONLINE' not in os.environ: skip("To run these sets, set the environment variable TEST_ONLINE") def test_cep...
4845637
import subprocess def shell(cmd): try: output = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()[0] return output.replace("\r", " - ").replace("\n", " - ") except: output = "FAILED" return output
4845657
from itertools import islice from typing import Dict, Generator, List, Tuple from urllib.parse import urlencode, unquote, unquote_plus from mangum.handlers.utils import ( get_server_and_port, handle_base64_response_body, maybe_encode_body, ) from mangum.types import ( Response, Scope, LambdaCon...
4845670
from block import block_mat, block_vec, block_bc from dolfin import * from xii import * import mshr dt, alpha, alpha_BJS, s0, mu_f, mu_p, lbd_f, lbd_p, K, Cp = [1] * 10 N = 10 EPS = 1E-3 R = 0.25 # box_domain = mshr.Box(dolfin.Point(0, 0, 0), dolfin.Point(1, 1, 1)) # _mesh = mshr.generate_mesh(box_domain, N) _mesh ...
4845676
import unittest import os import sys sys.path.append(os.path.abspath("..")) import xspf class XspfTest(unittest.TestCase): def testBySpiff(self): x = xspf.Spiff() self.assertTrue(isinstance(x, xspf.Xspf)) # self.assertEqual(sort.sorted_list(start), expected) def testEmptyPlaylist(self)...
4845741
from api.protocols.v1.connection.contact_status_updater import ContactStatusUpdater from api.protocols.v1.connection.reusable_invitation_processor import ( ReusableInvitationProcessor, ) def subscribe_connection_protocol_listeners(): ReusableInvitationProcessor() ContactStatusUpdater()
4845746
from kivy.app import App from kivy.clock import Clock from kivy.properties import ObjectProperty, StringProperty from kivy.uix.boxlayout import BoxLayout from kivy.uix.screenmanager import Screen from pywallet.utils import load_kv_from_py load_kv_from_py(__file__) class OverviewScreen(Screen): title_property =...
4845749
import sys sys.path.append("../../") from appJar import gui def reset(): print("breaking?") app.removeAllWidgets() app.label("Some text") app.button("Accessibility", app.showAccess, icon="ACCESS", tip="Click here for accessibility options") app.button("RESET", reset) with gui("COLOUR TEST", "400x4...
4845780
from __future__ import absolute_import, division, print_function # -*- mode: python; coding: utf-8; indent-tabs-mode: nil; python-indent: 2 -*- # # LIBTBX_SET_DISPATCHER_NAME cctbx.riso # # $Id: riso.py idyoung $ import iotbx.phil from dials.util.options import OptionParser from iotbx import mtz from cctbx.array_famil...
4845804
from typing import Optional from linky_note.adapters.references_db import tables from linky_note.dto.dto import Note, Reference, ReferenceBy from linky_note.interfaces.references_db import ( GetNoteByTitleQuery, GetNoteResponse, GetReferencesResponse, GetReferencesThatTarget, IReferenceDB, Upse...
4845805
from django import template from django.conf import settings from django.core.urlresolvers import resolve, reverse, NoReverseMatch from gipsy.toolbar.models import GipsyToolbarMenu from gipsy.toolbar.settings import LINK_CONTEXT_NAME, LINK_INCLUDED_MODELS, \ VERSION_INDICATOR, VERSION_INDICATOR_LOCATION register...
4845814
def main(request, response): token = request.GET.first(b"token", None) is_query = request.GET.first(b"query", None) != None with request.server.stash.lock: value = request.server.stash.take(token) count = 0 if value != None: count = int(value) if is_query: if count <...
4845826
from .decoder import Decoder from .discriminator import Discriminator, AdaptivePriorDiscriminator from .encoder import StandardEncoder, ReparametrisedGaussianEncoder, MomentEstimationEncoder
4845834
from bxcommon.test_utils.abstract_test_case import AbstractTestCase from bxcommon.utils import convert class ConvertTests(AbstractTestCase): def test_str_to_bool(self): self.assertTrue(convert.str_to_bool("True")) self.assertTrue(convert.str_to_bool("true")) self.assertTrue(convert.str_to...
4845892
from functools import wraps from aiohttp.web import View from . import create_scheduler __all__ = ('setup', 'spawn', 'get_scheduler', 'get_scheduler_from_app', 'atomic') def get_scheduler(request): scheduler = get_scheduler_from_request(request) if scheduler is None: raise RuntimeError( ...
4845893
from .dump import RefseqDumper from .ec_upload import EntrezECUploader from .genesummary_upload import EntrezGeneSummaryUploader
4845898
from __future__ import print_function import numpy as np import bayesiancoresets as bc import time import os import sys import argparse sys.path.insert(1, os.path.join(sys.path[0], '../common')) import results import plotting def plot(arguments): # load only the results that match (avoid high mem usage) to_mat...
4845913
import os import time from selenium.webdriver import Chrome, ChromeOptions def enable_download_in_headless_chrome(driver, download_dir): # hack founded in # https://stackoverflow.com/questions/45631715/downloading-with-chrome-headless-and-selenium # add missing support for chrome "send_command" to selen...
4845927
import os import numpy as np import cv2 import torch import torch.nn.functional as F from torch.utils.data import Dataset from utils import read_list_from_file from transforms import ResizeWithIntrinsic, RandomHorizontalFlipWithIntrinsic, EqualizeHist, CenterCropWithIntrinsic from torchvision.transforms import ToTenso...
4845931
import chainer from chainer.backend import get_array_module from chainer import functions from chainer_chemistry.functions import megnet_softplus from chainer_chemistry.links.readout.megnet_readout import MEGNetReadout from chainer_chemistry.links.update.megnet_update import MEGNetUpdate def reshaped_feat(feat, idx)...
4845943
from django import forms from django.contrib.auth import get_user_model, password_validation User = get_user_model() class UserCreationForm(forms.ModelForm): password = forms.CharField( label="Password", strip=False, widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}), ...
4845970
from setuptools import setup from setuptools import find_packages with open("README.rst") as readme_file: readme = readme_file.read() packages = find_packages() setup( name="mopyx", version="1.0.0", description="mopyx", long_description=readme, author="<NAME>", author_email="<EMAIL>", ...
4846001
expected_output = { "vrf": { "default": { "num_of_sa_cache": 1, "sa_cache": { "172.16.58.3 10.3.3.18": { "group": "172.16.58.3", "source_addr": "10.3.3.18", "up_time": "00:00:10", "expire"...
4846014
import FWCore.ParameterSet.Config as cms # Reshuffling using default option # It is not necessary to use this block since it is used by default # All the momenta are rescaled in the rest frame herwigppReshuffleSettingsBlock = cms.PSet( hwpp_reshuffle_Default = cms.vstring( 'set /Herwig/Shower/KinematicsReconstru...
4846016
from django.contrib import admin # Register your models here. from settings.models import Currency admin.site.register(Currency)
4846022
import os import csv import numpy from tabulate import tabulate def main(): import sys def usage(): print "usage: \n {} <file>.dat".format(sys.argv[0]) sys.exit(1) if len(sys.argv) != 2: usage() exit(1) fn = sys.argv[1] import chardet # $ pip install chardet wi...
4846030
from FeatureGenerator import * import pandas as pd import numpy as np import cPickle from nltk.sentiment.vader import SentimentIntensityAnalyzer from nltk.tokenize import sent_tokenize from helpers import * class SentimentFeatureGenerator(FeatureGenerator): def __init__(self, name='sentimentFeatureGenerator'): ...
4846044
import unittest from katas.kyu_7.cyclical_permutation import pattern class CyclicalPermutationTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(pattern(1), '1') def test_equals_2(self): self.assertEqual(pattern(4), '1234\n2341\n3412\n4123') def test_equals_3(self): ...
4846055
import pytest import mock from hcloud.actions.client import BoundAction from hcloud.certificates.client import CertificatesClient, BoundCertificate from hcloud.certificates.domain import Certificate, ManagedCertificateStatus class TestBoundCertificate(object): @pytest.fixture() def bound_certificate(self, he...
4846101
from abc import ABC, abstractmethod import typing from typing_extensions import Protocol, runtime_checkable @runtime_checkable class FuncBasedValidatorCallable(Protocol): """ Used to derive func to FuncBasedValidator with typings """ key: typing.Optional[str] = None def __call__(self, value: str, *args:...
4846151
from .server import WebTestHttpd, WebTestServer, Router # noqa: F401 from .request import Request # noqa: F401 from .response import Response # noqa: F401
4846165
from ._base import BaseGaussianMixture from ..weight_models import PitmanYorProcess class PitmanYorMixture(BaseGaussianMixture): def __init__(self, *, alpha=1, pyd=0, rng=None, **kwargs): weight_model = PitmanYorProcess(pyd=pyd, alpha=alpha, rng=rng) super().__init__(weight_model=weight_model, rng...
4846178
import numpy as np nx1 = 3 # number of elements in x direction of the first mesh of the composite mesh nx2 = 2 # number of elements in x direction of the second mesh of the composite mesh ny = 2 # number of elements in y direction # boundary conditions (for quadratic elements) dirichlet_bc = {} # Dirichlet bou...
4846187
train_triples = [l.strip().split("\t") for l in list(open("train.txt"))] valid_triples = [l.strip().split("\t") for l in list(open("valid.txt"))] test_triples = [l.strip().split("\t") for l in list(open("test.txt"))] ent2id = {} rel2id = {} ent_cnt = 0 rel_cnt = 0 for l in [train_triples,valid_triples,test_triples]: ...
4846196
import logging from p3d.singleTask import SingleTask from p3d.pandaManager import PandaManager as pMgr logger = logging.getLogger(__name__) class PandaBehaviour(SingleTask): cType = 'Script' def __init__(self, *args, **kwargs): SingleTask.__init__(self, *args, **kwargs) s...
4846215
import lbann from lbann.modules import Module from lbann.util import str_list import math class DenseGraphConv(Module): global_count = 0 def __init__(self, input_channels, output_channels, name=None): super().__init__() self.name = (name if name else 'DenseGraph_{}'.format(DenseGraphConv.glob...
4846247
import pytest import numpy as np import logging from qtpy.QtWidgets import QWidget from pydm.widgets.display_format import DisplayFormat, parse_value_for_display # -------------------- # POSITIVE TEST CASES # -------------------- @pytest.mark.parametrize("value, precision, display_format, widget, expected", [ ...
4846258
from __future__ import annotations import json import typing import toolcli import toolstr from ctc.protocols import fei_utils def get_command_spec() -> toolcli.CommandSpec: return { 'f': async_depth_command, 'help': 'output FEI liquidity depth information', 'args': [ { ...
4846307
import numpy as np import torch class THUmanPrior: def __init__(self): self.is_blank = np.array([0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1]) self.num_bone = 19 self.prev_seq = [-1, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 11, 11, 9, 10, ...
4846335
from django.core.management.base import BaseCommand from retirement_api.utils import ssa_check HELP_NOTE = """Checks a range of results from SSA's Quick Calculator \ to detect whether benefit formulas have changed.""" END_NOTE = "Checked SSA values; see results at {0}" class Command(BaseCommand): help = HELP_N...
4846337
import discord import os import config_discordbot as cfg from discordbot import gst_imgur from datetime import timedelta from matplotlib import pyplot as plt from gamestonk_terminal.config_plot import PLOT_DPI from gamestonk_terminal.stocks.dark_pool_shorts import stockgrid_model async def psi_command(ctx, arg): ...
4846347
import ctypes from ctypes import * import numpy as np from numpy.ctypeslib import ndpointer def str2arg(path): path_string = path.encode('utf-8') arg = c_char_p(path_string) return arg def get_temper_info(ip='192.168.1.65', username='admin', password='<PASSWORD>'): f = ctypes.CDLL('./libtemperature....
4846389
import json from django.urls import reverse from tests.api.apitestbase import ApiTestBase from tests.common.utils import apiurl class RepoTokensTest(ApiTestBase): def test_can_get(self): with self.get_tmp_repo() as repo: url = apiurl(reverse('api2-repo-tokens')) + '?repos=' + repo.repo_id ...
4846453
import torch import torch.nn as nn import torch.nn.functional as F import copy from functions_utils import * def Kron_BFGS_update(data_, params): i = params['i'] numlayers = params['numlayers'] data_['model_homo_grad_used_torch'] = get_homo_grad(data_['model_grad_used_torch'], params) delta = [...
4846463
import matplotlib.pyplot as plt import matplotlib.colors import numpy as np plt.rcParams['figure.figsize'] = [15, 7.5] from shutil import copyfile copyfile("../../build/renderer/RelWithDebInfo/Renderer.dll", "Renderer.dll") import imageio inputMask = imageio.imread("inpainting-mask.png")[:,:,0]/255.0 print(inputMask....
4846473
import logging import pandas as pd import elecsim.scenario.scenario_data from elecsim.agents.demand.demand import Demand logger = logging.getLogger(__name__) """demand.py: Agent which simulates the demand of the UK""" __author__ = "<NAME>" __copyright__ = "Copyright 2018, <NAME>" __license__ = "MIT" __email__ = "<E...
4846482
import functools import operator import pickle from .payload import function_key cache = {} def _hash_kwargs(kwargs): return sorted(kwargs.items(), key=operator.itemgetter(0)) def memoized(fn): """ Decorator. Caches a function's return value each time it is called. If called later with the same argu...
4846492
import os.path as osp import os import sys import numpy as np data_type = sys.argv[1] folder_no = sys.argv[2] filename = '../data/MTA_short/mta_data/images/' + data_type + '/cam_' + folder_no + '/coords_fib_cam_' + folder_no + '.csv' file = np.loadtxt(filename, dtype=int, delimiter=',') output = '../data/MTA_short/m...
4846508
import ctypes.wintypes SetEnvironmentVariable = ctypes.windll.kernel32.SetEnvironmentVariableW SetEnvironmentVariable.restype = ctypes.wintypes.BOOL SetEnvironmentVariable.argtypes = [ctypes.wintypes.LPCWSTR] * 2 GetEnvironmentVariable = ctypes.windll.kernel32.GetEnvironmentVariableW GetEnvironmentVariable.restype = ...
4846516
from unittest import mock import graphene from django.utils.functional import SimpleLazyObject from freezegun import freeze_time from ....channel.error_codes import ChannelErrorCode from ....webhook.event_types import WebhookEventAsyncType from ....webhook.payloads import generate_meta, generate_requestor from ...tes...
4846519
import FWCore.ParameterSet.Config as cms # import a full HLT menu import sys, os sys.path.append( '%s/src/HLTrigger/Configuration/test' % os.environ['CMSSW_BASE'] ) sys.path.append( '%s/src/HLTrigger/Configuration/test' % os.environ['CMSSW_RELEASE_BASE'] ) from OnData_HLT_GRun import process # options process.option...
4846528
import datamol as dm def test_find_mcs(): smiles_list = [ "C=CC(=O)NCCOc1cc2ncnc(Nc3ccc(Br)cc3F)c2cc1NC(=O)C=C", "C=CC(=O)Nc1cc2c(Nc3ccc(F)c(Br)c3)ncnc2cc1OCCCN1CCOCC1", "C=CC(=O)Nc1cc2c(Nc3ccc(Br)cc3F)ncnc2cc1OCCCNC(=O)CN(C)C", "C=CC(=O)Nc1cc2c(Nc3ccc(Br)cc3F)ncnc2cc1OCCNC(=O)NCC"...
4846532
from django.db import models from wagtail.core.fields import RichTextField from wagtail.core.models import Page from wagtail.snippets.models import register_snippet from taggit.managers import TaggableManager from wagtail_airtable.mixins import AirtableMixin class SimplePage(Page): intro = models.TextField() @r...
4846550
from random import random def make_key(key, key_prefix, version=None): return f"{key_prefix}:{version}:{key}" SECRET_KEY = "django-insecure-jv!jxo%un3wse2^#s2_e$awvo1-cpb1z-)f7o14nry-9se7=ui" INSTALLED_APPS = [ "django_dynamodb_cache", ] CACHES = { "default": { "BACKEND": "django_dynamodb_cach...
4846558
from typing import Dict from apprentice.agents.base import BaseAgent from apprentice.working_memory.representation import Sai class Stub(BaseAgent): """ Just a dummy agent that requests no actions, doesn't learn, and returns false for all checks. Made for testing the API. """ def request(self, st...
4846560
import datetime import pytest from django_test_migrations.db.checks.statement_timeout import ( CHECK_NAME, check_statement_timeout_setting, ) from django_test_migrations.logic.datetime import timedelta_to_miliseconds ALL_CONNECTIONS_MOCK_PATH = ( 'django_test_migrations.db.checks.statement_timeout.connec...
4846575
from Attr import Attr class EnumAttr(Attr): def __init__(self, attr): Attr.__init__(self, attr) # We expect that an 'Enums' key holds the enumeration values self._enums = [enum.strip() for enum in self['Enums'].split(',')] self._enumSet = dict((enum, i) for i, enum in enumerate(se...
4846584
import shlex import textwrap from datetime import date from pathlib import Path import responses from plumbum.cmd import git import changes from changes.commands import stage from .conftest import ( BUG_LABEL_JSON, ISSUE_URL, LABEL_URL, PULL_REQUEST_JSON, github_merge_commit, ) @responses.activ...
4846597
import numpy as np import torch from ..util import (ensure_spatial_array, ensure_tensor_with_channels, load_image, supports_memmap) # TODO pad images that are too small for the patch shape class ImageCollectionDataset(torch.utils.data.Dataset): def _check_inputs(self, raw_images, label_images...
4846620
import numpy as np from spatialmath import SE3 import roboticstoolbox as rtb import timeit from ansitable import ANSITable, Column import traceback # change for the robot IK under test, must set: # * robot, the DHRobot object # * T, the end-effector pose # * q0, the initial joint angles for solution example = 'pum...
4846682
import re import os import urllib.request from urllib.error import HTTPError def fetch(pdbid, outdir='.'): """Download PDB file from PDB website https://www.rcsb.org/. Args: pdbid(str): PDB ID outdir (str, optional): Output path. Defaults to '.'. Raises: ValueError: PDB ID is not ...
4846699
import unittest import sys class SampleTestBasic(unittest.TestCase): EXPECTED_RESULT = """ <tr class='errorClass'> <td>tests.SampleTestBasic.SampleTestBasic</td> <td>4</td> <td>2</td> <td>1</td> <td>1</td> <td><a href="javascript:showClassDetail('c3',4)">Detail</a></td> </tr> <tr id='pt3.1...
4846706
from math import log from numpy import exp def logit(u): return log(u / (1 - u)) def inverse_logit(v): return 1 / (1 + exp(-v)) def make_transform_func_with_lower_bound(lower_bound, func_type): assert func_type in ["direct", "inverse", "inverse_derivative"] if func_type == "direct": def f...
4846713
from Bio import SeqIO import sys import numpy for record in SeqIO.parse(sys.argv[1], "fastq"): print numpy.mean(record.letter_annotations["phred_quality"])
4846718
from flask_unchained.bundles.sqlalchemy import db class DataVendor(db.Model): class Meta: repr = ('id', 'abbrev', 'name') abbrev = db.Column(db.String(10), index=True, unique=True) name = db.Column(db.String(64), index=True, unique=True) data_vendor_assets = db.relationship( 'AssetDa...
4846747
from typing import Optional, Union, Callable, Dict from requests import Response from requests_oauthlib import OAuth2Session from oauthlib.oauth2 import TokenExpiredError from urllib.parse import urlencode AUTHORIZE_URL_SANDBOX = "https://gw.hml.api.enedis.fr/dataconnect/v1/oauth2/authorize" ENDPOINT_TOKEN...
4846760
from __future__ import absolute_import, division, print_function from .am_softmax import AMSoftmaxLoss, AngleSimpleLinear from .asl import AsymmetricLoss, AMBinaryLoss from .cross_entropy_loss import CrossEntropyLoss, PseudoCrossEntropyLoss from .entropy import MaxEntropyLoss, MinEntropyLoss, entropy from .fmix import...
4846863
import visualization.panda.world as wd import modeling.geometric_model as gm import basis.robot_math as rm import math import numpy as np base = wd.World(cam_pos=[1, 1, 1], lookat_pos=[0, 0, 0], toggle_debug=True) gm.gen_frame(length=.2).attach_to(base) gm.gen_torus(axis=[0, 0, 1], portion=1, radius=.2, thickness=.003...
4846887
from os.path import join, dirname from setuptools import setup, find_packages from dexguru_sdk.sdk import __version__ setup( name='dexguru-sdk', version=__version__, url='https://dex.guru', packages=find_packages(), license='MIT License', long_description_content_type='text/markdown', lon...
4846892
import setuptools import subprocess import os with open("README.md", "r") as fh: long_description = fh.read() requirements = [ 'osmium~=2.15', 'pyparsing~=2.4', 'pyyaml', 'shapely~=1.6', 'requests~=2.22.0', 'landez~=2.5.0' ] setuptools.setup( name="osm-export-tool", version="0.0.2...
4846912
from django.contrib import admin from .models import EducationSystem, University , College, Department,Course from import_export import resources, fields from import_export.admin import ImportExportModelAdmin from simple_history.admin import SimpleHistoryAdmin class EducationSystemList(admin.ModelAdmin): list_...
4846952
import numpy as np from tqdm import tqdm as tqdm import argparse import pandas as pd import csv import pysam from .contigs import Contigs """ Get contacts from mnd(merged nodups txt) or sam(sam r1 and sam r2). result is composed of DataFrame, pandas. """ def get_contacts_mnd(contigs, mnd_filename): """get Hi-C...
4846961
import base64 from cryptography.fernet import Fernet, MultiFernet from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC from django.conf import settings from .base import BaseSecretEngine class SecretEngine(BaseSecretEngine): kd_iterations = 100000 ...
4846963
import idc import idaapi import time from rpyc import classic c = classic.connect("127.0.0.1",port=18812) triton = c.modules.triton tast = c.modules['triton.ast'] aexprs = c.modules['arybo.lib.mba_exprs'] easm = c.modules['arybo.lib.exprs_asm'] atools = c.modules['arybo.tools'] triton.setArchitecture(triton.ARCH.X86...
4847003
import pytest import pytest_asyncio from tests.setup_nodes import setup_daemon from shibgreen.daemon.client import connect_to_daemon from tests.setup_nodes import bt from shibgreen import __version__ from tests.util.socket import find_available_listen_port from shibgreen.util.config import save_config class TestDaem...
4847010
import os import docutils.core from .converter import Converter class RstConverter(Converter): name = "RST" reference = True def _doConvert(self, txt): out = docutils.core.publish_string(txt, writer_name="html") return out.decode("utf-8") def supports(self, filename): _, ex...
4847013
import sys import pytest from plenum.test.batching_3pc.helper import node_caughtup from plenum.test.stasher import delay_rules from plenum.server.quorums import Quorum from stp_core.loop.eventually import eventually from plenum.test.delayers import cDelay, pDelay, ppDelay from plenum.test.helper import sdk_send_ba...
4847085
from rllab.envs.base import Step, Env from rllab.spaces.box import Box from rllab.core.serializable import Serializable from rllab.misc.overrides import overrides from rllab.misc import logger import numpy as np import math import random UB = 2 class PointEnv(Env, Serializable): def __init__(self, dim=2, state_...
4847093
import plotly.express as px import pytest @pytest.mark.parametrize("px_fn", [px.scatter, px.density_heatmap, px.density_contour]) @pytest.mark.parametrize("marginal_x", [None, "histogram", "box", "violin"]) @pytest.mark.parametrize("marginal_y", [None, "rug"]) def test_xy_marginals(px_fn, marginal_x, marginal_y): ...
4847127
import platform import pytest from dartpy.utils import DartLoader from dartpy.simulation import World from tests.util import get_asset_path def test_parse_joint_properties(): loader = DartLoader() robot = loader.parseSkeleton(get_asset_path('urdf/joint_properties.urdf')) assert robot is not None wo...
4847165
from .activation import ( leaky_relu, LeakyReLU, relu, ReLU, Sigmoid, sigmoid, Softmax, softmax, Softplus, softplus ) from .affine import Affine, Linear from .batch_normalization import BatchNormalization, SpatialBatchNormalization from .dropout import Dropout, SpatialDropout from .one_hot import OneHot from .s...