text
stringlengths
2
999k
# Copyright (c) 2019 NVIDIA Corporation import os import random import time import matplotlib import numpy as np from matplotlib import pyplot as plt from sklearn.metrics import classification_report, confusion_matrix import nemo __all__ = ['eval_iter_callback', 'eval_epochs_done_callback'] def tensor2list(tensor...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import template register = template.Library() @register.filter def return_item(l, i): try: return l[i] except: return None
import contextvars import sys import time import pytest from joulehunter import stack_sampler from .util import do_nothing class SampleCounter: count = 0 def sample(self, stack, time, async_state): self.count += 1 def test_create(): sampler = stack_sampler.get_stack_sampler() assert samp...
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Profile.accept_pysv_conferences' db.add_column(u'accounts_profile', 'accept_pysv_conferences...
# control a pair of TI SN76489 programmable sound generator ICs # wiring: base pin on LSB (both chips in parallel) # base pin + 8 on left chip /WE # base pin + 9 on right chip /WE # base pin + 10 on left chip /OE # base pin + 11 on right chip /OE # both chips' READY disconnected ...
# Copyright 2019 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
from datetime import datetime def datetimeIsoFormatCleanup(isoFormat): return isoFormat[:-1]+".000000"+"+00:00" def getNowWithFormat(): return datetime.now().timestamp() #return datetime.now().isoformat(timespec="seconds", sep=" ")
import math import sys from abc import ABC from argparse import ArgumentParser from typing import List, Dict, Tuple, Optional from numpy.random import RandomState from rlai.actions import Action from rlai.agents import Agent from rlai.environments import Environment from rlai.meta import rl_text from rlai.states impo...
coordinates_0009FF = ((105, 88), (105, 89), (105, 90), (105, 91), (105, 92), (105, 93), (105, 94), (105, 95), (105, 96), (105, 97), (105, 98), (105, 99), (105, 100), (105, 101), (105, 102), (105, 103), (106, 85), (106, 104), (106, 105), (106, 106), (106, 107), (106, 108), (106, 109), (107, 83), (107, 87), (107, 88), ...
import os import argparse import tensorflow as tf from models.yolo_v3 import yolo_v3 from models.loss_functions.yolo_v3_loss import yolo_v3_loss from utils.utils import get_anchors, get_classes, get_training_batch, prepare_data def str2bool(v): if v.lower() in ('yes', 'true', 't', 'y', '1'): return True ...
from neuron import h import neuron import unittest import sys from multiprocessing import Process scalar_bistable_data = { 'rxd': [3.872370530242001e-24, 2.411674445771420e-23, 1.667524717451771e-22, 1.132417447670439e-21, 7.529718703964290e-21, 4.898967465170301e-20, 3.116791696748720e-19, 1.937757198340029e-18, 1.17...
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
import sys sys.path.append("../residual-sample-nn") # for finding the source files import GenerateData as generate_data import Network as Network import numpy as np import pandas as pd import matplotlib.pyplot as plt import configparser import mnist_loader def RSNN_param_test(X_train, X_test, y_train, y_test, h_nodes,...
# -*- coding: utf-8 -*- import os, sys import numpy as np import matplotlib.pyplot as plt import openslide import cv2 from skimage import io from pydaily import filesystem from pydaily import format from pyimg import combine def annotate_images(data_dir, cur_set, cur_cat, slide_level): slides_dir = os.path.join...
import pandas as pd import numpy as np class ValidationError(Exception): """Raised when an error related to the validation is encountered. """ def validate_ref_point_with_ideal_and_nadir( dimensions_data: pd.DataFrame, reference_point: pd.DataFrame ): validate_ref_point_dimensions(dimensions_data, r...
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import logging impor...
"""VectorND class implementation. """ from __future__ import annotations import array import numbers from functools import total_ordering from math import sqrt from typing import Any from typing import Union from .dtypes import Number from .dtypes import float32 @total_ordering class VectorND: """VectorND class...
import copy import logging import re from prettytable import PrettyTable from collections import defaultdict from subprocess import TimeoutExpired from ocs_ci.ocs.machine import get_machine_objs from ocs_ci.framework import config from ocs_ci.ocs.exceptions import TimeoutExpiredError from ocs_ci.ocs.ocp import OCP f...
"""Filters passed to the BeaconScanner to filter results.""" class DeviceFilter(object): """Base class for all device filters. Should not be used by itself.""" def __init__(self): """Initialize filter.""" self.properties = {} def matches(self, filter_props): """Check if the filter...
# -*- coding: utf-8 -*- # Copyright (c) 2016-2021 by University of Kassel and Fraunhofer Institute for Energy Economics # and Energy System Technology (IEE), Kassel. All rights reserved. import pandas as pd from numpy import nan, isnan, arange, dtype, isin, any as np_any, zeros, array, bool_, \ all as np_all, fl...
import zengl from window import Window window = Window(1280, 720) ctx = zengl.context() window.set_caption('Hello World | Vendor: %s | Renderer: %s | Version: %s' % ctx.info) image = ctx.image(window.size, 'rgba8unorm', samples=4) image.clear_value = (1.0, 1.0, 1.0, 1.0) triangle = ctx.pipeline( vertex_shader=...
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
"""Light for Shelly.""" from __future__ import annotations from typing import Any, cast from aioshelly.block_device import Block from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_EFFECT, ATTR_RGB_COLOR, ATTR_RGBW_COLOR, ATTR_TRANSITION, ColorMode, Lig...
# Copyright (c) 2021 kamyu. All rights reserved. # # Google Code Jam 2021 Round 1C - Problem C. Double or NOTing # https://codingcompetitions.withgoogle.com/codejam/round/00000000004362d7/00000000007c1139 # # Time: O(|E| + |S|) # Space: O(|E| + |S|) # # KMP solution # # from re import match def modified_KMP(text, pa...
#!/usr/bin/env python3 import argparse import random import sys ENGLISH_LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' ENGLISH_FREQUENCIES = [ 0.08167, 0.01492, 0.02202, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.01292, 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327,...
"""Classes and functions for representing prior distributions and constraints.""" import numpy as N NEGINF = -N.inf # # Prior Models # class Prior: """ Class for representing prior model. Priors have two aspects: * soft priors: weights for each possible edge. * hard priors: constraints that M...
from contextlib import contextmanager from itertools import product, repeat import numpy as np import yt.geometry.particle_deposit as particle_deposit import yt.geometry.particle_smooth as particle_smooth from yt.data_objects.data_containers import YTSelectionContainer from yt.funcs import issue_deprecation_warning, ...
from optics import hex2xyz import bpy import math from mathutils import Matrix, Vector clip_name = 'clip' start_angle = math.pi / 3 + math.pi / 6 arc_angle = 5 * math.pi / 6 # 2 equilateral triangle wide basis # + 1 triangle row (triangle height = 0.5 * math.sqrt(3) * triangle side) # + almost half circles centered o...
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modif...
from django.shortcuts import render from .models import Course, CourseSemester def index(request): courses = Course.objects.order_by('name') context = { 'courses': courses } return render(request, 'exams/index.html', context) def exams_for_course(request, department, number): course = Course.objects.filter(...
# Generated by Django 2.0.9 on 2018-12-10 21:33 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('products', '0014_itemtype_inform_staff'), ] operations = [ migrations.AlterField( model_name='p...
msg = 'Hello world' print(msg) input()
from flask import Flask, request import base64 import json import bcrypt app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" @app.route("/hw4/ex2", methods=['POST']) def login(): data = json.loads(request.data.decode('utf-8')) user = data["user"] pwd = data["pass"].encode('utf-8') pwd_...
#! /usr/bin/env python ############################################################################### # aruco_generator.py # # script testing basic generation of Aruco markers # # Code modified from that at: # http://www.philipzucker.com/aruco-in-opencv/ # # NOTE: Any plotting is set up for output, not viewing on sc...
#!/usr/bin/env python3 import sys import yaml import ipaddress import urllib.parse import subprocess import socket import requests import re import logging import random import string import hashlib import os def checksum(filename, hashfunc): with open(filename,"rb") as f: for byte_block in iter(lambda: f...
# -*- coding: utf-8 -*- # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: # https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code from ccxt.base.exchange import Exchange # ----------------------------------------------------------------------------- try: basestri...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings import django.core.validators import boardinghouse.base class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MOD...
from pynput.mouse import Button, Controller as MouseController from pynput.keyboard import Key, Controller as KeyboardController from typing import Callable, Any import time from pynput import keyboard as KeyboardBase from pynput import mouse as MouseBase mouseController= MouseController() keyboardController = Keyboa...
import sqlalchemy as sql from configparser import ConfigParser from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, relationship from authentication import * from exc import * from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, Table, Foreign...
# Copyright 2016 Cloudbase Solutions Srl # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless r...
from .PBXItem import * class PBXTargetDependency(PBXItem): def __init__(self, identifier, dictionary): super(self.__class__, self).__init__(identifier, dictionary) def resolveGraph(self, project): super(self.__class__, self).resolveGraph(project) self.resolveGraphNodeForKey(kPBX_TARGETD...
from django.test import TestCase from django.contrib.auth import get_user_model from core import models def sample_user(email='test@jordanjones.dev', password='testpass'): """Create a sample user""" return get_user_model().objects.create_user(email, password) class ModelTests(TestCase): def test_creat...
from output.models.ms_data.regex.re_s30_xsd.re_s30 import Doc __all__ = [ "Doc", ]
class UnexpectedValueError(Exception): ''' An unexpected value error is thrown whenever the value specified for a parameter is outside the bounds of what is expected. For example, if the parameter **a** is expected to have a value of 1, 2, or 3, and it is instead passed a value of 0, then it is an ...
# Generated by Django 2.2.1 on 2019-05-26 11:36 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('products', '0003_auto_20190525_1245'), ] operations = [ migrations.RenameField( model_name='product', old_name='title', ...
from optparse import OptionParser from pathlib import Path import sys import platform import time # import os # import re import getpass parser = OptionParser() parser.add_option("--spath", type=str, default="src") parser.add_option("--dpath", type=str, default="build") parser.add_option("--version", type=...
import math from dataclasses import dataclass, field from typing import NamedTuple import numpy as np class N(NamedTuple): """A node in the hidden Markov model.""" ID: str prob: float klass: float ts: int = 0 @dataclass class Rsamp: k: float = field(default=1.35) La: float = field(defa...
""" Copyright 2020 ICES, University of Manchester, Evenset Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or ...
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use th...
""" This is HuggingFace transformers' DPRTokenizer, but with a small bug fixed. See: https://github.com/huggingface/transformers/issues/9555 """ from typing import Optional, Union from transformers.tokenization_utils_base import BatchEncoding, TensorType from transformers.models.bert.tokenization_bert import BertToken...
__version__ = '0.0.7' from consul.base import ACLDisabled # noqa from consul.base import ACLPermissionDenied # noqa from consul.base import Check # noqa from consul.base import ConsulException # noqa from consul.base import NotFound # noqa from consul.base import Timeout # noqa from consul.std import Consul # n...
from time import sleep import json import config import mister import cores import time from flask import Flask, request, Response, redirect, send_file, render_template import openvgdb app = Flask(__name__) quit = False SETTINGS = config.get_config() maps = cores.read_file_map() RECENTS_FOLDER = '/media/{}/config/'.fo...
import numpy as np #Return the covariance matrix and its svd decomposition def CovMat(f_exact,f): D=f_exact-f MCOV=np.cov(D) U, S, Vt = np.linalg.svd(M) V = Vt.T return MCOV,U,S,V ######################################################################################### # Covariance matrix from trun...
import webbrowser import os from spotipy.oauth2 import SpotifyOAuth CLIENT_ID = os.environ["SPOTIFY_APP_ID"] APP_SECRET = os.environ["SPOTIFY_APP_SECRET"] REDIRECT_URI = os.environ["REDIRECT_URI"] CACHE_PATH = os.path.join(os.path.split(__file__)[0], "cached_data/auth_token.json") SCOPES = " ".join(["user-read-recen...
# Local imports from .app import Decko # Function decorators from .decorators import ( deckorator, execute_if, freeze, filter_by_output, ) from .debug import ( try_except, stopwatch, log_trace, slower_than, raise_error_if, ) __version__ = "0.0.3.2" PROJECT_NAME = "decko"
from typing import Callable from PyQt5.QtCore import Qt from PyQt5.QtGui import QResizeEvent from PyQt5.QtWidgets import QPushButton, QSizePolicy class Button(QPushButton): def __init__(self, text: str, slot: Callable) -> None: super().__init__(text) self.clicked.connect(slot) self.setMi...
"""Mobjects generated from an SVG file.""" __all__ = ["SVGMobject", "string_to_numbers"] import itertools as it import re import os import string import warnings from xml.dom.minidom import Element as MinidomElement, parse as minidom_parse from typing import Dict, List from .style_utils import cascade_element_st...
# This file is part of Indico. # Copyright (C) 2002 - 2022 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from sqlalchemy.dialects.postgresql import JSONB from indico.core.db import db from indico.core.db.sqlalc...
import time import pytest @pytest.mark.parametrize(["p_save"], [ [True], [False] ]) def test_progress(worker, p_save): worker.start(flags="--report_interval 1") assert worker.send_task( "tests.tasks.general.Progress", {"save": p_save}, block=False) time.sleep(5) assert worker.mongo...
# Copyright (C) 2020 GreenWaves Technologies, SAS # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # This progr...
import torch from torch import nn from einops import rearrange, repeat ################################## # Linformer ################################## def get_EF(input_size, dim, method="learnable", head_dim=None, bias=True): """ Retuns the E or F matrix, initialized via xavier initialization. ...
from __future__ import absolute_import import json import warnings from django.utils import six from django.utils.six.moves.urllib.parse import urlparse from elasticsearch import Elasticsearch, NotFoundError from elasticsearch.helpers import bulk from django.db import models from django.utils.crypto import get_rand...
# Always prefer setuptools over distutils import re from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # read the version from classla/_version.py version_file_contents = open(path.join(here, 'classla/_ver...
#!python3 #encoding:utf-8 import os.path import shlex import subprocess import database.src.license.insert.Main import database.src.TsvLoader class Main: def __init__(self, db, client): self.__db = db self.__client = client self.__path_dir_this = os.path.abspath(os.path.dirname(__file__)) ...
''' centering of matplotlib axes so that 0,0 point is in the middle of the figure ''' # %% import matplotlib.pyplot as plt x = [] y = [] # create a plotting area and get the figure, axes handle in return fig, ax = plt.subplots() # plot data on the axes handle ax.plot(x, y) # Move left y-axis and bottim x-axis to cen...
"""Support for Tuya switches.""" from __future__ import annotations from typing import Any from tuya_iot import TuyaDevice, TuyaDeviceManager from homeassistant.components.switch import ( SwitchDeviceClass, SwitchEntity, SwitchEntityDescription, ) from homeassistant.config_entries import ConfigEntry from...
#!/usr/bin/env python # -*- coding: utf-8 -*- import requests import html2text from pattern.fr import parsetree sources = [ "http://www.jeuxdemots.org/HACK/hack_texts/Au%20bonheur%20des%20dames_1%20-%20Wikisource.htm", "http://www.jeuxdemots.org/HACK/hack_texts/Au%20bonheur%20des%20dames_10%20-%20Wikisource.htm", "ht...
import numpy as np import os os.environ["TOKENIZERS_PARALLELISM"] = "false" # disable warning when using smart batching import pandas as pd from torch.utils.data import Dataset from sklearn.model_selection import StratifiedKFold from torch.utils.data import Dataset from pytorch_lightning.callbacks import ModelCheckpo...
"""RTmission URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-bas...
# -*- coding: utf-8 -*- """Cisco DNA Center GetChassisDetailsForDevice data model. Copyright (c) 2019-2021 Cisco Systems. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, incl...
"""art_app URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-bas...
from flask_appbuilder import GeneralView from flask_appbuilder.models.datamodel import SQLAModel from flask_appbuilder.charts.views import ChartView, TimeChartView from flask_babel import lazy_gettext as _ from app import session, appbuilder from .models import Group, Gender, Contact def fill_gender(): try: ...
# -*- coding: utf-8 -*- """ test_generate_context --------------------- Tests formerly known from a unittest residing in test_generate.py named TestGenerateContext.test_generate_context TestGenerateContext.test_generate_context_with_default TestGenerateContext.test_generate_context_with_extra TestGenerateContext.test...
from .core import ROHSA
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. import unittest import torch from reagent.core.parameters import NormalizationData, NormalizationParameters from reagent.core.types import FeatureData from reagent.net_builder import value from reagent.net_builder.unions im...
import pandas as pd import time import matplotlib.pyplot as plt from Kbatch_KNNunlearning import KNNbase_Unlearning # from KNNbaseline import KNNbase_Unlearning from surprise import dump from KnnPred import knnpred if __name__ == "__main__": shards = 5 shuffle = True shuffled_ordered_str = 'shuffled' if sh...
import copy import logging import random import re import time from collections import Counter from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Tuple, Union import numpy as np import tree # pip install dm_tree import yaml from gym.spaces import Box import ray from ray.rllib.utils.framework impo...
#!/usr/bin/env python # -*- coding: utf-8 -*- # fakes.py - 2021/11/4 # 生成虚拟数据 import random from faker import Faker from sqlalchemy.exc import IntegrityError from blog import db from blog.models import Admin, Category, Post, Comment, Link fake = Faker() # noinspection PyArgumentList def fake_admin(): admin = A...
import json import os import unittest from pathlib import Path import cadquery as cq import paramak import pytest class TestReactor(unittest.TestCase): def setUp(self): self.test_shape = paramak.RotateStraightShape( points=[(0, 0), (0, 20), (20, 20)], name='test_shape' )...
# coding: utf-8 """ OpenPerf API REST API interface for OpenPerf # noqa: E501 OpenAPI spec version: 1 Contact: support@spirent.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class BulkStopCpuGeneratorsRequest(object)...
#!/usr/bin/env python import portio portio.iopl(3) portio.ioperm(0x2E, 2, 1) portio.outb_p(0x87, 0x2E) portio.outb_p(0x01, 0x2E) portio.outb_p(0x55, 0x2E) portio.outb_p(0x55, 0x2E) portio.outb_p(0x07, 0x2E) portio.outb_p(0x03, 0x2F) portio.outb_p(0xF0, 0x2E) f = portio.inb_p(0x2F) f ^= 0x08 portio.outb_p(f, 0x2F)
import io import re from setuptools import setup with io.open("README.md", "rt", encoding="utf8") as f: readme = f.read() with io.open("starter/__init__.py", "rt", encoding="utf8") as f: version = re.search(r'__version__ = "(.*?)"', f.read()).group(1) setup( name="starter", version=version, url=...
import collections import random from typing import Sequence, Callable, List, Union import numpy as np import pandas as pd import itertools import dateutil from numpy import nan import re from autopandas_v2.generators.specs import df as s_df, dfgroupby as s_dfgroupby from autopandas_v2.generators.ml.traindata.randuti...
import sys, getopt import time, datetime, calendar import jwt def printHelp(): with open("help", "r") as f: for line in f: print(line) def generate(secret, keyId, teamId, expDays, algorithm="ES256"): time_now = int(time.time()) time_exp = int(calendar.timegm((datetime.datetime.now() + ...
import os os.environ["CUDA_VISIBLE_DEVICES"] = "3" import pandas as pd import numpy as np from tqdm import tqdm import time import logging from sklearn.model_selection import StratifiedKFold from keras_bert import load_trained_model_from_checkpoint, Tokenizer from keras.optimizers import Adam import pandas as pd from s...
import unittest import sys from py65816.devices.mpu65c816 import MPU from py65816.db_disassembler import dbDisassembler as Disassembler from py65.utils.addressing import AddressParser class DisassemblerTests(unittest.TestCase): def _dont_test_disassemble_wraps_after_top_of_mem(self): ''' TODO: Th...
"""Basic checks for HomeKit button.""" from aiohomekit.model.characteristics import CharacteristicsTypes from aiohomekit.model.services import ServicesTypes from tests.components.homekit_controller.common import Helper, setup_test_component def create_switch_with_setup_button(accessory): """Define setup button c...
import os BASE_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), os.pardir) SECRET_KEY = 'dqkkdmfkwef45knngjfngnjgk' DEBUG = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test.db', } } INSTALLED_APPS = ('no_delete', 'tests',)
import random import numpy as np from torch_geometric.utils import to_networkx import networkx as nx import matplotlib.pyplot as plt from read_dataset import Dataset dataset = Dataset(name="AIDS", device="cpu", load_from_disk=False) # bbb = [x for x in fin[:,0]] # ccc = [x for x in fin[:,1]] yy = np.array(dataset.y...
class Solution: def merge(self, lhs, rhs): r_value = [] while lhs and rhs: if lhs[0] < rhs[0]: r_value.append(lhs[0]) del lhs[0] else: r_value.append(rhs[0]) del rhs[0] if lhs: r_...
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class BaseModel(db.Model): ''' A model detailing the base properties to be inherited ''' __abstract__ = True id = db.Column(db.Integer, primary_key=True) date_created = db.Column(db.DateTime, default=db.func.current_timestamp()) date_modif...
import urllib.request import urllib.parse import re from bs4 import BeautifulSoup import json def main(): keyword = input("please input your keyword") keyword = urllib.parse.urlencode({"word": keyword}) response = urllib.request.urlopen("http://baike.baidu.com/search/word?%s" % keyword) html = respons...
from core.advbase import * from module.bleed import Bleed from slot.a import * def module(): return Ieyasu class Ieyasu(Adv): a1 = ('cc',0.13,'hp70') a2 = ('cd',0.3) conf = {} conf['slots.a'] = RR()+United_by_One_Vision() conf['acl'] = ''' `dragon.act('c3 s end') `s3, not self...
import hypothesis import numpy as np import torch from hypothesis.diagnostic import BaseDiagnostic from scipy.integrate import nquad class DensityDiagnostic(BaseDiagnostic): def __init__(self, space, epsilon=0.1): super(DensityDiagnostic, self).__init__() self.epsilon = epsilon self.are...
# Copyright 2011 The Emscripten Authors. All rights reserved. # Emscripten is available under two separate licenses, the MIT license and the # University of Illinois/NCSA Open Source License. Both these licenses can be # found in the LICENSE file. from __future__ import print_function from subprocess import PIPE im...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
# -*- coding: utf-8 -*- import time import re from random import shuffle import string import numpy as np printable = set(string.printable) class Corpus(object): """ A data generator that takes care of all the data loading and preparation required for training. """ def __init__(self, train_file, val_file, ...
# Generated by Django 3.2.5 on 2021-08-02 03:34 from django.conf import settings import django.contrib.auth.models import django.contrib.auth.validators from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import uuid class Migration(migrations.Migration): initi...
import json import logging from logging import Logger from typing import Optional from botocore.client import BaseClient from slack_sdk.oauth.installation_store.async_installation_store import ( AsyncInstallationStore, ) from slack_sdk.oauth.installation_store.installation_store import InstallationStore from slac...