id
stringlengths
3
8
content
stringlengths
100
981k
3275432
import numpy as np import time import matplotlib.pyplot as plt import pandas as pd import json # get gekko package with: # pip install gekko from gekko import GEKKO # get tclab package with: # pip install tclab from tclab import TCLab # Connect to Arduino a = TCLab() # Make an MP4 animation? make_mp4 = False if m...
3275481
env = [ [8, 2], [8, 3], [8, 4], [16, 0], [16, 1], [16, 3], [16, 4], [32, 0], [32, 1], [32, 2], [32, 3] ] import unittest from math import * from PySigmoid import Posit, Quire, set_posit_env, Math class TestTrig(unittest.TestCase): def test_small_sin(self): st...
3275585
from __future__ import absolute_import # flake8: noqa # import apis into api package from yapily.api.accounts_api import AccountsApi from yapily.api.application_api import ApplicationApi from yapily.api.application_users_api import ApplicationUsersApi from yapily.api.balances_api import BalancesApi from yapily.api.ca...
3275609
import asyncio import json from urllib.parse import urljoin import websockets from jigu.error import RpcError, get_rpc_error from jigu.util import hash_amino from jigu.util.serdes import JiguBox class WebSocketClient(object): def __init__(self, terra, ws_url: str = "", ssl_context=None): self.terra = te...
3275612
from urllib.parse import unquote from common.repository import Repository from common.logger import get_logger from common.utils import Utils, generate_lambda_response, handle_exception_with_slack_notification from contract_api.config import NETWORKS, NETWORK_ID, SLACK_HOOK from contract_api.registry import Registry ...
3275640
from mayan.apps.rest_api import generics from .permissions import ( permission_message_create, permission_message_delete, permission_message_edit, permission_message_view ) from .serializers import MessageSerializer class APIMessageDetailView(generics.RetrieveUpdateDestroyAPIView): """ delete: Delete...
3275666
import tensorflow as tf def get_var_wrap(name, shape, initializer, regularizer, trainable, cpu_variable): if cpu_variable: with tf.device('/cpu:0'): return tf.get_variable(name, ...
3275670
import os import time import datetime from PIL import Image log_path = 'G:/PGGAN_face/log.txt' resize_x = 256 resize_y = 256 def transimg(inputfolder,outputfolder): names = os.listdir(inputfolder) nameslen = len(names) print('# of file in {} is : {}'.format(inputfolder,nameslen)) pngcount = 0 notp...
3275707
class NumbersError(Exception): """Base class for other exceptions""" pass class UnsupportedError(NumbersError): """Raised for unsupported file format features""" pass class NotImplementedError(NumbersError): """Raised for missing Protobufs""" pass class FileError(NumbersError): """R...
3275718
from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from ..versioning import Version, VersionSpec from ..url import URL, get_domain, urlencode from ..compat import ( text_type, py2bytes, string_types, int_types, number_types, unic...
3275752
from django.conf.urls import url urlpatterns = [ url(r'^list/$', 'screenshots_listing', prefix='crits.screenshots.views'), url(r'^list/(?P<option>\S+)/$', 'screenshots_listing', prefix='crits.screenshots.views'), url(r'^add/$', 'add_new_screenshot', prefix='crits.screenshots.views'), url(r'^find/$', 'f...
3275756
import pytest from waio.keyboard.reply import QuickReply, QuickReplyContentText, KeyboardButton, QuickReplyContentImage def test_reply_keyboard_text(): kb_content = QuickReplyContentText( header="this is the header", text="this is the body", caption="this is the footer" ) kb = Quic...
3275780
from yowsup.structs import ProtocolEntity, ProtocolTreeNode from .notification import NotificationProtocolEntity class StatusNotificationProtocolEntity(NotificationProtocolEntity): ''' <notification offline="0" id="{{NOTIFICATION_ID}}" notify="{{NOTIFY_NAME}}" type="status" t="{{TIMESTAMP}}" from="...
3275793
import os import time import unittest import threading try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen from .mixins import BallotAPITestMixin import ballotapi.utils.db import ballotapi.runserver class CommandlineTestCase(BallotAPITestMixin, unittest.TestCase): def ...
3275822
class PekerjaTambang: # protected variabel _nama = None _jabatan = None # membuat konstruktor def __init__(self, nama, jabatan): self._nama = nama self._jabatan = jabatan # membuat fungsi protected def _menampilkan(self): print("jabatan: ", self._jabatan) # kelas ...
3275839
from __future__ import absolute_import import signal # Ctrl + C to quit # https://gist.github.com/lechup/d886e89490b2f6c737d7#comment-1253485 import gevent.monkey gevent.monkey.patch_all() import gevent import gevent.pool from rq import Worker from rq.timeouts import BaseDeathPenalty, JobTimeoutException from rq.wor...
3275848
import numpy as np import pandas as pd # from scipy.stats import gamma np.random.seed(181336) number_regions = 5 number_strata = 10 number_units = 5000 units = np.linspace(0, number_units - 1, number_units, dtype="int16") + 10 * number_units units = units.astype("str") sample = pd.DataFrame(units) sample.rename(c...
3275855
import collections from supriya.enums import CalculationRate from supriya.ugens.PV_ChainUGen import PV_ChainUGen class FFTTrigger(PV_ChainUGen): """ :: >>> ffttrigger = supriya.ugens.FFTTrigger.ar( ... buffer_id=buffer_id, ... hop=0.5, ... polar=0, ... ...
3275884
import os import h5py import math import copy from tqdm import tqdm import torch import torch.nn as nn import itertools from torch.utils.data import DataLoader import torch.optim as optim from torch.utils.tensorboard import SummaryWriter import numpy as np import skimage.io as skio import utils.io as io from utils.con...
3275917
from types import SimpleNamespace COLORS_DICT = { "blue_light": "#CADEF7", "blue": "#29335C", "blue_dark": "#0A2342", "green": "#297373", "yellow": "#E8C547", "red": "#E4572E", "red_dark": "#92140C", "grey": "#CDD1C4" } colors = SimpleNamespace(**COLORS_DICT)
3275934
import pytest from chains.services import MessageSender pytestmark = [pytest.mark.django_db] @pytest.fixture def message_sender(): return MessageSender @pytest.fixture(autouse=True) def owl(mocker): return mocker.patch('app.tasks.mail.TemplOwl')
3275958
import logging import os import numpy as np import torch import torch.nn.functional as F from torch.autograd import Variable from tasks.config import cfg from pdb import set_trace as pause logger = logging.getLogger(__name__) def clip_gradient(model, clip_norm): """Computes a gradient clipping coefficient bas...
3275959
from typing import List from backend.common.cache_clearing import get_affected_queries from backend.common.manipulators.manipulator_base import ManipulatorBase from backend.common.models.cached_model import TAffectedReferences from backend.common.models.event_team import EventTeam class EventTeamManipulator(Manipula...
3275995
import codecs import re import sys def quote(s): return '"' + s + '"' title = re.compile(u'(.*) \((.*) (\\d*)\)$') def split_title(doc): m = title.match(doc) return [m.group(3),quote(m.group(2)),quote(m.group(1))] def run(docs,gammas,topic,num_papers): print "Showing top " + str(num_papers) + " pape...
3276013
from restaurant import Restaurant channel_club = Restaurant('the channel club', 'steak and seafood') channel_club.describe_restaurant() channel_club.open_restaurant()
3276015
from setuptools import setup setup( name='fauxtograph', version='1.0.3', author='<NAME>', author_email='<EMAIL>', license='MIT', description='Python module for training unsupervised deep, generative models on images.', packages=['fauxtograph'], long_description='Python module for traini...
3276044
from write_tfrecords import write_seg_data_to_tfrecords, load_name from read_data import DataReader import os import random data_path = "D:/data/MPI-FAUST_training/normalized/reg_dataset/" label_path = "D:/data/MPI-FAUST_training/normalized/matching_labels/" output_path = "D:/data/MPI-FAUST_training/normalized/" tra...
3276128
import os from PIL import Image import glob import numpy as np from utils import make_folder color_list = [[0, 0, 0], [204, 0, 0], [76, 153, 0], [204, 204, 0], [51, 51, 255], [204, 0, 204], [0, 255, 255], [255, 204, 204], [102, 51, 0], [255, 0, 0], [102, 204, 0], [255, 255, 0], [0, 0, 153], [0, 0, 204], [255, 51, 153],...
3276143
import json from django.utils.dateformat import DateFormat from seahub.share.models import UploadLinkShare from seahub.test_utils import BaseTestCase class SharedUploadLinksTest(BaseTestCase): def tearDown(self): self.remove_repo() def test_can_list(self): ls = UploadLinkShare.objects.create...
3276146
threemul = [value*3 for value in range(1,7)] print(threemul) threechu = [value/3 for value in range(3,31)] print(threechu)
3276163
import torch from torch.nn import functional as F class WSDDNLossComputation(object): """ Computes the loss for WSDDN, which is a multi-label image-level binary cross-entropy loss """ def __init__(self, cfg): self.config = cfg self.background_weight = cfg.MODEL.ROI_BOX_HEAD.LOSS_WEIGHT_...
3276191
from __future__ import absolute_import, print_function import logging import pprint import json from googleapiclient.discovery import build as google_build from oauth2client.client import GoogleCredentials from six import iteritems from . import utils from .s3 import events_s3 from .schema import mk_bigquery_schema ...
3276240
from .explicit_shooting.explicit_shooting import ExplicitShooting from .pseudospectral.gauss_lobatto import GaussLobatto from .pseudospectral.radau_pseudospectral import Radau from .solve_ivp.solve_ivp import SolveIVP
3276342
def test_extrapolate_coverage(): from pycobertura.utils import extrapolate_coverage lines_w_status = [ (1, True), (4, True), (7, False), (9, False), ] assert extrapolate_coverage(lines_w_status) == [ (1, True), (2, True), (3, True), (4, Tr...
3276358
from __future__ import unicode_literals import json import requests from mock import patch, MagicMock import django from django.conf import settings from django.test import TestCase, TransactionTestCase from error.models import Error from vault.secrets_handler import SecretsHandler from vault.exceptions import Inva...
3276386
from pathlib import Path from cfpq_data import RSM from pyformlang.cfg import CFG from pygraphblas import Matrix, BOOL from src.graph.graph import Graph from typing import Iterable, Union from src.grammar.rsa import RecursiveAutomaton from src.graph.label_graph import LabelGraph from src.problems.AllPaths.algo.tensor....
3276464
import json from flask import Blueprint, Markup, render_template, request from flask_app import WebVRConfig, get_overlay_content from three import * blueprint = Blueprint(__name__, __name__) @blueprint.route('/%s' % __name__) def cannon(): scene = Scene() scene.add(DirectionalLight(color=0xffffff, castSh...
3276513
import sys import json from suiron.core.SuironVZ import visualize_data from suiron.utils.file_finder import get_latest_filename # Load image settings with open('settings.json') as d: SETTINGS = json.load(d) # Visualize latest filename filename = get_latest_filename() # If we specified which file if len(sys.arg...
3276517
import pathlib import os import pickle def join(*paths): paths = [str(path) for path in paths] return str(pathlib.Path(*paths)) def mkdir(path): pathlib.Path(path).mkdir(parents=True, exist_ok=True) def exist(path): return os.path.exists(str(path)) def parent(path): path = pathlib.Path(path)...
3276569
from typing import List class Solution: def smallestRangeI(self, A: List[int], K: int) -> int: a, b = max(A), min(A) return max(a - b - 2 * K, 0)
3276605
from fairness.data.objects.Data import Data import numpy as np import pandas as pd import math ############################################################################## TOTAL_ITEMS = 200 class TwoGaussians(Data): def __init__(self, percent_pos): Data.__init__(self) self.dataset_name = 'two-...
3276619
import cv2 import numpy as np import multiprocessing class Consumer(multiprocessing.Process): def __init__(self, task_queue, result_queue): multiprocessing.Process.__init__(self) self.task_queue = task_queue self.result_queue = result_queue #other initialization stuff def run(...
3276622
import random from collections import deque import pygame from blocks import * import numpy as np NUM_CHANNELS = 17 NUM_ACTIONS = 3 class SnakeStateTransition: DX, DY = [-1, 0, 1, 0], [0, 1, 0, -1] def __init__(self, field_size, field, num_feed, initial_head_position, initial_tail_position, initial_snake):...
3276650
from django.conf import settings from django.apps import apps from hypereditor import utils WAGTAIL_EXISTS = apps.is_installed('wagtail.core') HYPER_SETTINGS = { 'BLOCK_CONFIG': {}, 'STYLESHEETS': [], 'IMAGE_API_URL': '#', 'AUTHENTICATION_MIXIN': 'hypereditor.views.AuthMixin' } utils.merge_dict(HYPER...
3276677
from torch.utils.data import DataLoader, TensorDataset import torch import numpy as np class KSLoader(): ''' Class used for creating data loaders for the burgers equation ''' def __init__(self, shuffle=True): self.shuffle = shuffle def createTrainingLoader(self, data_dir, cases, n_init...
3276679
import re from django.contrib.postgres.aggregates import StringAgg from django.forms import CheckboxSelectMultiple from django.urls import reverse_lazy from additional_codes import models from common.filters import ActiveStateMixin from common.filters import LazyMultipleChoiceFilter from common.filters import StartYe...
3276680
import h5py import pickle import numpy as np def load_weights(): fff = h5py.File('Mybase/mask_rcnn_coco.h5','r') #打开h5文件 #print(list(f.keys())) mydict = {} mydict['global_step:0'] = 1000 ########res1######## dset = fff['conv1'] a = dset['conv1'] b = np.array(a['kernel:0'], dtype=np....
3276699
import unittest from pprint import pprint from securify.grammar import Grammar from securify.grammar.transformer import DictTransformer from tests.grammar.grammars import simple class DictTransformerTest(unittest.TestCase): grammar = Grammar.from_modules(simple) transformer = DictTransformer( gramma...
3276711
from marshmallow import pre_load, validate from marshmallow_sqlalchemy import field_for from CTFd.models import Pages, ma from CTFd.utils import string_types class PageSchema(ma.ModelSchema): class Meta: model = Pages include_fk = True dump_only = ("id",) title = field_for( P...
3276712
import os, inspect, time, scipy.misc, pickle import tensorflow as tf import numpy as np import matplotlib.pyplot as plt PACK_PATH = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))+"/.." def make_dir(path): try: os.mkdir(path) except: print("%s is already exists." %(path)) def data2...
3276758
from abc import ABC import torch import torch.nn.functional as F class Loss(ABC): def compute(self, *args, **kwargs): pass class TableLoss(Loss): """ Compute the loss for training joint entity and relation extraction.""" def __init__(self, rel_criterion, entity_criterion, model, optimizer ...
3276830
import uuid from datetime import datetime from datahub.api.entities.datajob import DataFlow, DataJob from datahub.api.entities.dataprocess.dataprocess_instance import ( DataProcessInstance, InstanceRunResult, ) from datahub.emitter.rest_emitter import DatahubRestEmitter emitter = DatahubRestEmitter("http://lo...
3276845
from __future__ import division, absolute_import, print_function from .image import * from .midi import *
3276923
import glob, os.path, time, sys def pack(): output = open('./src/lib/shaders.js', 'wt') files = glob.glob('./src/shaders/*.glsl') output.write('export var shaders = {\n') for file in files: f = open(file, 'rt') shader = f.read() f.close() var = '_'.join(os.path.basename(file).split('.')[:-1]...
3276947
import pytest from .conftest import _make_step, _test_doc def yes(from1, to1, val1, from2, to2, val2): def inner(): step1 = _make_step(from1, to1, val1) step2 = _make_step(from2, to2, val2) merged = step1.merge(step2) assert merged assert merged.apply(_test_doc).doc.eq( ...
3276951
import os import numpy as np import torch from torchvision import datasets, transforms from datasets.sbmnist import load_sbmnist_image class StackedMNIST(datasets.MNIST): def __init__(self, root, train=True, transform=None, target_transform=None, download=False): super().__init__(root=root, transform=tran...
3276985
from emulator.assembler import Assembler SEG_INIT = { 'DS': int('0000', 16), # Initial value of data segment 'CS': int('1000', 16), # Initial value of code segment 'SS': int('0000', 16), # Initial value of stack segment 'ES': int('0000', 16) # Initial value of extra segment } def load_ivt(memory): #...
3276988
from bottle_utils.common import basestring, unicode try: from bottle_utils.i18n import lazy_gettext as _ except ImportError: _ = lambda x: x from .exceptions import ValidationError from .validators import DateValidator class ErrorMixin(object): """ Mixin class used to provide error rendering functio...
3276990
from .utils import iter_flatten, set_seed, get_config_from_args, \ default_argument_parser, log_args, generate_kfold, cross_validation from .logging import setup_logger from .get_dataset_api import get_dataset_api
3276994
from logger import logger logging = logger.getChild('sessions.gui.main') #Graphical session import wx from core.sessions.session import Session class Gui (Session): def __init__(self, name=None, *args, **kwargs): logging.debug("%s: Creating GUI frame." % name) self.frame = wx.Frame(None, wx.ID_AN...
3277003
from protorpc import messages class Kind(messages.Enum): RENDERED = 1 STATIC = 2 SITEMAP = 3 class RouteMessage(messages.Message): path = messages.StringField(1) kind = messages.EnumField(Kind, 2) locale = messages.StringField(3) class Format(messages.Enum): YAML = 1 MARKDOWN = 2 ...
3277029
import os import numpy as np import cv2 from tqdm import tqdm from utils.img_processing import read_image from rfcn_model import RFCN_ResNet101 from trainer import RFCN_Trainer from config import opt from utils.vis_tool import visdom_bbox from utils.bbox_tools import tonumpy def predict(load_path, **kwargs): """...
3277030
from __future__ import absolute_import from __future__ import division from __future__ import print_function import pytest from mock import Mock from stopwatch_global import ( global_sw, global_sw_del, global_sw_init, ) @pytest.fixture def global_sw_fixture(request): request.addfinalizer(global_sw_...
3277045
from statsmodels.regression.quantile_regression import QuantReg import statsmodels.api as sm class QuantileRegression: """Quantile regression wrapper It can work on sklearn pipelines Example ------- >>> from sktools import QuantileRegression >>> from sklearn.datasets import load_boston >...
3277052
from submission_code.nlp_tools import tokenizer from onmt.translate.translator import build_translator from argparse import Namespace import math import os def tokenize_eng(text): return tokenizer.ner_tokenizer(text)[0] def predict(invocations, model_dir, model_file, result_cnt=5): """ Function called...
3277058
print("Input: ",end="") string = input() def stack(s): if (len(s) == 0): return x = s[-1] s.pop() stack(s) print(x, end="") s.append(x) def min(s): Stack = [] Stack.append(s[0]) for i in range(1, len(s)): if (len(Stack) == 0): Stack.append(s[...
3277074
from backpack.core.derivatives.flatten import FlattenDerivatives from backpack.extensions.secondorder.hbp.hbpbase import HBPBaseModule class HBPFlatten(HBPBaseModule): def __init__(self): super().__init__(derivatives=FlattenDerivatives())
3277148
import demistomock as demisto from CommonServerPython import * def get_query(cre_name_null): if cre_name_null == "False": query = "SELECT *,\"CRE Name\",\"CRE Description\",CATEGORYNAME(highlevelcategory) " \ "FROM events WHERE \"CRE NAME\" <> NULL AND INOFFENSE({0}) START '{1}'" else:...
3277161
import meilisearch import structlog from django.conf import settings from django.core.management.base import BaseCommand log = structlog.get_logger() class Command(BaseCommand): help = "Create initial MeiliSearch indexes" def add_arguments(self, parser): # Optional argument parser.add_argume...
3277250
from utils.db.mongo_orm import * # 类名定义 collection class TestReportDetail(Model): class Meta: database = db collection = 'testReportDetail' # 字段 _id = ObjectIdField() # reportDetailId reportId = ObjectIdField() projectId = ObjectIdField() testSuiteId = ObjectIdField() tes...
3277263
from builtins import object import re from orderedmultidict import omdict class GroupNotExists(Exception): def __str__(self): return "Group not exists" class UserAlreadyInAGroup(Exception): def __str__(self): return "User already in a group" class UserNotInAGroup(Exception): def __s...
3277289
import json import time from abc import ABC, abstractclassmethod, abstractmethod from pathlib import Path from elpis.engines.common.utilities import hasher # Design constraint # Since there are four classes that must have their states saved to the # operating system, this single class was made to provide some common #...
3277304
class GeneralException(BaseException): def __init__(self, resp_data): if isinstance(resp_data, dict): if 'detail' in resp_data: self.err = resp_data['detail'] else: self.err = ''.join('{} '.format(val[0]) for key, val in resp_data.items()) else...
3277334
import os import unittest import time from measure_performance import MeasurePerformance class MeasurePerformanceTests(unittest.TestCase): def setUp(self): self.filename = 'test_measure_performance.txt' def test_get_exceeded_time_returns_correct_value(self): meter = MeasurePerformance(self.f...
3277342
import sys import ethpow import math import utils import json import Queue import threading import multiprocessing import subprocess import base64 from rlp.sedes import big_endian_int, BigEndianInt, Binary from rlp.utils import decode_hex, encode_hex, ascii_chr, str_to_bytes f = open(sys.argv[1],'r') valuejson = base...
3277346
import numpy as np import pickle, os NUM_HEROES = 108 NUM_FEATURES = NUM_HEROES * 2 NUM_IN_QUERY = 0 # Lower this value to speed up recommendation engine TRAINING_SET_SIZE = 10000 def my_distance(vec1,vec2): '''Returns a count of the elements that were 1 in both vec1 and vec2.''' return np.sum(np.logical_and(...
3277348
import discord import asyncio from discord.ext import commands, tasks TOKEN = "YOUR_TOKEN" bot = commands.Bot(command_prefix="!") startup_extensions = [] @bot.event async def on_ready(): # On read, after startup print(f"Connecting...\nConnected {bot.user}\n") # Send message on connected if __name__ == "_...
3277374
from openwisp_users.tests.test_admin import ( TestBasicUsersIntegration as BaseTestBasicUsersIntegration, TestMultitenantAdmin as BaseTestMultitenantAdmin, TestUsersAdmin as BaseTestUsersAdmin, ) from openwisp_users.tests.test_models import TestUsers as BaseTestUsers additional_fields = [ ('social_secu...
3277429
import json def metadata(name, data): info = {} info['name'] = name if type(data) is dict: info['entries'] = [metadata(k, v) for (k, v) in data.items()] else: info['shape'] = data.shape return info def tolist(array): depth = len(array.shape) if depth == 1: return [...
3277516
from django.core.management.base import BaseCommand from document.models import Document import openkamer.dossier class Command(BaseCommand): def handle(self, *args, **options): documents = Document.objects.all() counter = 0 for document in documents: if not document.content_...
3277521
import os import sys from concurrent import futures from datetime import datetime import aion.common_library as common import grpc import numpy as np import open3d as o3d from arena_api.__future__.save import Writer from .pcdproto import ndarray_to_proto from .PointCloud_pb2_grpc import (MainServerServicer, ...
3277564
from gloro.layers.network_layers import MinMax from gloro.layers.network_layers import InvertibleDownsampling from gloro.layers.network_layers import Scaling from gloro.layers.network_layers import Bias from gloro.layers.network_layers import ResnetBlock
3277574
import pytest from specklepy.api.models import Stream from specklepy.logging.exceptions import GraphQLException @pytest.mark.run(order=2) class TestStream: @pytest.fixture(scope="session") def stream(self): return Stream( name="a wonderful stream", description="a stream created...
3277585
from mock import MagicMock, mock_open, patch from unittest import TestCase from warnings import simplefilter import pconf from pconf.store.env import Env TEST_ENV_BASE_VARS = { "env__var": "result", "env__var_2": "second_result", } TEST_ENV_MATCHED_VARS = {"matched_var": "match"} TEST_ENV_WHITELIST_VARS = {"...
3277649
import string class Decoder(object): decoder_name = "" decoder_version = 1 decoder_author = "" decoder_description = "" file_info = object def set_file(self, file_info): self.file_info = file_info def get_config(self): pass class PreProcessor(object): preprocessor_n...
3277655
from billing.integrations.amazon_fps_integration import AmazonFpsIntegration as Integration from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect import urlparse class FpsIntegration(Integration): def transaction(self, request): """Ideally at this method, you will check ...
3277680
import pytest from pygears.hls.translate import translate_gear from pygears import gear, find from pygears.typing import Uint, Tuple from pygears.hls import HLSSyntaxError from pygears.lib import const # Should report that this is unsupported # @gear # def test() -> Uint[8]: # yield -1 # def test_out_cast_fail()...
3277711
import numpy as np import os from utils import data_paths, data_splitting def test_write_numpy_array_to_file_returns_none(): input_array = np.ones((4, 3)) array_file_name = 'array_test_file.npy' array_file_path = os.path.join(data_paths.DATA_DIR_PATH, array_file_name) try: return_value = data...
3277752
description = 'Basic Setup for Experiments in Experimental Chamber 2' group = 'basic' excludes = ['antares_s'] includes = ['basic', 'sbl', 'lbl', 'servostar']
3277757
import time import unittest from alerta.app import create_app, db from alerta.models.metrics import Gauge, Timer class MetricsTestCase(unittest.TestCase): def setUp(self): self.app = create_app() self.client = self.app.test_client() def tearDown(self): db.destroy() def test_met...
3277768
from django.db import transaction from django.contrib.postgres.aggregates import ArrayAgg from ..models import Media from ..models import MediaType from ..models import StateType from ..models import State from ..models import Project from ..schema import StateTypeListSchema from ..schema import StateTypeDetailSchema ...
3277808
from typing import Optional def try_int(text: str) -> Optional[int]: try: return int(text) except: return None
3277821
from splitcli.split_apis import workspaces_api, environments_api, traffic_types_api from splitcli.ux import menu def selection_environment(workspace_id): environments = environments_api.list_environments(workspace_id) if len(environments) == 1: environment = environments[0]["name"] return envi...
3277864
from __future__ import annotations import logging from collections import defaultdict from typing import TYPE_CHECKING, Any from ..events import Event if TYPE_CHECKING: from collections.abc import Awaitable, Callable from .app import App # Type aliases HandlerType = Callable[[Event], Awaitable[Non...
3277868
class ValueIteration: def __init__(self, mdp): self.refresh(mdp) def refresh(self, mdp): self.mdp = mdp self.states = mdp.getStates() self.actions = mdp.getActions() self.transition = mdp.transition self.reward = mdp.reward self.terminal = mdp.terminal ...
3277882
from eve import Eve from eve_sqlalchemy import SQL from eve_sqlalchemy.examples.simple.tables import Base, Invoices, People from eve_sqlalchemy.validation import ValidatorSQL app = Eve(validator=ValidatorSQL, data=SQL) # bind SQLAlchemy db = app.data.driver Base.metadata.bind = db.engine db.Model = Base db.create_al...
3277963
from .evolution import * from .asynchronous_rule import * from .hopfield_net import * from .reversible_rule import * from .analysis import * from .rule_tables import * from .hexplot import * from .sandpile import * from .turing_machine import * from .utils import * from .hopfield_tank_tsp_net import * from .substitutio...
3277988
timeline_csv = """1992, Wolfenstein 3D 1993, Doom 1994, Doom II 1996, Quake 1997, Quake II 1998, Half-Life 1999, Quake III 2003, Call of Duty, Half-Life 2 2004, Doom 3 2007, The Orange Box 2011, Portal 2, Rage 2014, Titanfall 2016, Doom (2016), Titanfall 2, Dishonored 2 2019, Apex Legends""" # 18 game skeleton timelin...
3278027
from nlpmodels.utils import tokenizer def test_tokenizer_removes_punctuation(): text = [ 'Hi. How2 are you doing?? ', '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' ] exp_text = [['hi', 'how', 'are', 'you', 'doing']] tokenized_text = tokenizer.tokenize_corpus_basic(text) assert tokenized...
3278038
import geom import os POSITION_COLOUR = 'ff70ff' def MakeCurveFromD(d, group_name): curve = geom.Curve() mode = 'x' # x y h v cx1 cx2 cy1 cy2 nums = '' curp = geom.Point(0,0) absolute = True move = True d += ' ' for c in d: if c == 'm': absolute = False ...