id
stringlengths
3
8
content
stringlengths
100
981k
11526343
import os settings = { "static_path": os.path.join(os.path.dirname(__file__), "static/"), "cookie_secret": "hotpoorinchina", "debug": True, }
11526359
from keras.models import Model from keras.layers import Dense, Dropout from keras.applications.nasnet import NASNetLarge from config import IMAGE_SIZE class NimaModel(object): def __init__(self): self.base_model = NASNetLarge(input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3), includ...
11526405
from import_export import resources, fields from .models import ChoiceLibrary class ChoiceResource(resources.ModelResource): choice_question = fields.Field(attribute='choice_question', column_name='问题描述') choice_a = fields.Field(attribute='choice_a', column_name='选项A') choice_b = fields.Field(attribute='...
11526417
from collections import defaultdict from datetime import datetime, timedelta, timezone from unittest.mock import MagicMock import pytest CERT1_ZO_NE = {'CertificateArn': 'arn:aws:acm:eu-west-1:cert1', 'CreatedAt': datetime(2016, 4, 1, 12, 13, 14, tzinfo=timezone.utc), 'DomainName': '*.zo...
11526434
expected_output = { 'index': { 1: { 'descr': 'Cisco Systems Cisco 7600 6-slot Chassis System', 'name': 'CISCO7606', 'pid': 'CISCO7606', 'sn': 'FOX11140RN8', }, 2: { 'descr': 'OSR-7600 Clock FRU 1'...
11526441
import os from functools import partial import torch.nn as nn import torch.optim as optim import torch.optim.lr_scheduler as lr_scheduler from fsgan.datasets.opencv_video_seq_dataset import VideoSeqPairDataset from fsgan.datasets.img_landmarks_transforms import RandomHorizontalFlip, Pyramids, ToTensor from fsgan.criter...
11526446
from sklearn import svm from sklearn import tree from sklearn.metrics import accuracy_score, confusion_matrix from sklearn.ensemble import AdaBoostClassifier from sklearn.ensemble import GradientBoostingClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import ExtraTreesClassifier from...
11526455
import json import os import unittest from aptos.parser import SchemaParser from aptos.schema.visitor import AvroSchemaVisitor BASE_DIR = os.path.dirname(__file__) class AvroSchemaTestCase(unittest.TestCase): def runTest(self): with open(os.path.join(BASE_DIR, 'schema', 'product')) as fp: s...
11526465
import torch from torch.nn.utils.rnn import pad_sequence def collate_input_sequences(samples): """Returns a batch of data given a list of samples. Args: samples: List of (x, y) where: `x`: A tuple: - `torch.Tensor`: an input sequence to the network with size ...
11526474
from pysys.basetest import BaseTest import time """ Validate end to end behaviour for a failing installation When we install a package that cannot be installed with the apt package manager Then we receive a failure from the apt plugin """ import time import sys from environment_sm_management import SoftwareManagem...
11526476
from rpython.flowspace.model import Constant from rpython.annotator.model import SomeNone from rpython.rtyper.rmodel import Repr, TyperError, inputconst from rpython.rtyper.lltypesystem.lltype import Void, Bool, Ptr, Char from rpython.rtyper.lltypesystem.llmemory import Address from rpython.rtyper.lltypesystem.rpbc imp...
11526477
import os import sys import argparse import platform import pathlib from signal import signal, SIGINT import debugpy ### This block is only for debugging from samples/simple_demo directory. ### You don't need it when have azdebugrelay module installed. import pkg_resources _AZDEBUGRELYNAME = "azdebugrelay" _required_a...
11526487
from django.conf import settings from django.conf.urls import patterns, include, url urlpatterns = patterns('editor.views', url(r'^login/$', 'login_view'), url(r'^logout/(.*)$', 'logout_view'), url(r'^generate-api-key$', 'gen_api_key'), url(r'^ekey$', 'ekey'), url(r'^get-ekey$', 'get_ekey'), url(r'^e...
11526492
from keras.layers import Input, Dense, Reshape, Add, Activation, Lambda, Conv1D from keras import layers from keras.models import Model from keras.optimizers import RMSprop import keras.backend as K import numpy as np def stop_grad(ys): return K.stop_gradient(ys[0] - ys[1]) + ys[1] class WGAN(object): def _...
11526503
from decimal import Decimal import unittest.mock import hummingbot.strategy.cross_exchange_market_making.start as strategy_start from hummingbot.connector.exchange_base import ExchangeBase from hummingbot.strategy.cross_exchange_market_making.cross_exchange_market_making_config_map import ( cross_exchange_market_ma...
11526517
import sys fi=open(sys.argv[1]) fo=open(sys.argv[2],'w') header=fi.readline().rstrip().split('\t') h=[] for one in header: h.append(one.split('#')[0]) header=h G={} i=1 while i<len(header): if header[i] in G: G[header[i]].append(i) else: G[header[i]]=[i] i=i+1 n...
11526548
from typing import Any, Dict from pytest import Session def _patch_plotly_show() -> None: """Monkey patch ``plotly.io.show`` as to not perform any rendering and, instead, simply call ``plotly.io._utils.validate_coerce_fig_to_dict``""" from typing import Union import plotly.io from plotly.graph_o...
11526562
import os import sys import logging import subprocess from setuptools import setup, find_packages # setup logging logging.basicConfig(stream=sys.stderr, level=logging.INFO) log = logging.getLogger() # package description and keywords description = 'Python Tools for reading and writing data from the ESA CryoSat-2 miss...
11526585
import numpy as np def softmax(X, theta=1.0, axis=None): """ Compute the softmax of each element along an axis of X. Source: https://nolanbconaway.github.io/blog/2017/softmax-numpy Parameters ---------- X: ND-Array. Probably should be floats. theta (optional): float parameter, used as a mu...
11526601
from collections import defaultdict from typing import List from sqlalchemy import select from app.models import async_session, DatabaseHelper from app.models.schema.testcase_data import PityTestcaseDataForm from app.models.testcase_data import PityTestcaseData from app.utils.logger import Log class PityTestcaseDat...
11526675
import itertools import math from functools import lru_cache from typing import Tuple, Iterator import cv2 import numpy as np import numpy.ma as ma from tqdm import tqdm from vidgear.gears import WriteGear from .pose import Pose class PoseVisualizer: def __init__(self, pose: Pose, thickness=None): self.pose =...
11526795
import pytest from pyle38.errors import Tile38IdNotFoundError, Tile38KeyNotFoundError key = "fleet" id = "truck1" @pytest.mark.asyncio async def test_command_pdel(tile38): response = await tile38.set(key, id).point(1, 1).exec() assert response.ok response = await tile38.get(key, id).asObject() asse...
11526806
import torch import torch.nn as nn from collections import OrderedDict from models.resnet import _weights_init from utils.kfac_utils import fetch_mat_weights from utils.common_utils import (tensor_to_list, PresetLRScheduler) from utils.prune_utils import (filter_indices, filter_indices_ni...
11526870
from genmod.annotate_models.models import check_X_dominant from genmod.vcf_tools import Genotype from ped_parser import FamilyParser FAMILY_FILE = "tests/fixtures/recessive_trio.ped" def get_family(family_file = None, family_lines = None): """Return a family object """ family = None if family_fi...
11526889
from matplotlib import pyplot as plt import matplotlib as mpl import numpy as np %config InlineBackend.figure_format='retina' %matplotlib inline """ Log scale discrete colormaps with matplotlib which you can happily copy-paste in jupyter notebook (inspired by http://stackoverflow.com/questions/14777066/matplotlib-disc...
11526905
import pytest import sklearn.metrics from isic_challenge_scoring import metrics def test_binary_accuracy_reference( real_cm, real_truth_binary_values, real_prediction_binary_values ): value = metrics.binary_accuracy(real_cm) reference_value = sklearn.metrics.accuracy_score( real_truth_binary_valu...
11526916
import io import logging import pytest from abcvoting.output import Output, VERBOSITY_TO_NAME, DETAILS, INFO @pytest.mark.parametrize("verbosity", VERBOSITY_TO_NAME.keys()) def test_verbosity(capfd, verbosity): output = Output(verbosity=verbosity) output.debug2("debug2") output.debug("debug") output....
11526922
from django.urls import path from django.views.generic import TemplateView from . import views urlpatterns = [ path('pdf', views.pdf), # path('docx', views.docx), path('preview', TemplateView.as_view(template_name='dashboard/stattalon_preview.html')), path('extra-nofication', views.extra_nofication), ...
11526935
import z3 MIN_BASE = 0x10000 def bvs(name: str, size: int): return z3.BitVec(name, size) def bvv(val: int, size: int): return z3.BitVecVal(val, size) def split_bv_in_list(bv: z3.BitVecRef, size: int) -> list: assert size % 8 == 0 res = [] for i in range(0, bv.size, size): b = z3.simpl...
11526945
from blobrl.explorations import AdaptativeEpsilonGreedy def test_adaptative_epsilon_greedy_step_min(): exploration = AdaptativeEpsilonGreedy(0.8, 0.1, 0.99) exploration.be_greedy(0) def test_adaptative_epsilon_greedy_step(): exploration = AdaptativeEpsilonGreedy(0.8, 0.1, 0.99) exploration.be_gree...
11527007
def headerprint(label): print "\n\033[94m{0}\033[0m".format(label) print "------------------------------------------------------------------\n" def cprint(label, val): print "\033[92m{0}:\033[0m {1}".format(label, val)
11527036
import argparse def get_parser(): parser = argparse.ArgumentParser(description="Implementation of Semantic Image Synthesis with Spatially-Adaptive Normalization") # Dataloader parser.add_argument('--path', required=True, help='path to the image folder') parser.add_argument('--img-size', dest='img_size...
11527049
import sys import numpy as np from .. import face from ..utils import utils from ..utils.recognize import distance class Face_test: def __init__(self, model): self.model = model self.labels = np.array(model['labels']) self.encodes = np.array(model['encodes']) self.label_map = mode...
11527052
import asyncio import gc import pytest from async_class import AsyncObject, TaskStore, link, task class GlobalInitializedClass(AsyncObject): pass global_initialized_instance = GlobalInitializedClass() async def test_global_initialized_instance(loop): await global_initialized_instance assert not glob...
11527061
from typing import Dict, List def parse_version_requirements(packages: str) -> Dict[str, Dict[str, str]]: """ Parses a list of requirements in the format <package_name><PEP_OPERATOR><SEM_VER> into a dictionary with the format. { <package_name>: { "operator": <PEP_OPERATOR>, ...
11527064
from setuptools import find_packages, setup with open('requirements.txt') as f: required = f.read().splitlines() with open("README.rst", "r", encoding="utf-8") as f: README = f.read() setup( name='scrapy-x', packages=find_packages(), install_requires=required, version='3.0', author='<NAME...
11527074
import os from easyreg.reg_data_utils import write_list_into_txt, loading_img_list_from_files,generate_pair_name from glob import glob def generate_atlas_set(original_txt_path,atlas_path,l_atlas_path, output_path,phase='train',test_phase_path_list=None, test_phase_l_path_list=None): if phase!="test": sourc...
11527087
from persian_tools import digits def test_convert_to_fa(): assert digits.convert_to_fa('123٤٥٦') == '۱۲۳۴۵۶' assert digits.convert_to_fa(123456) == '۱۲۳۴۵۶' def test_convert_to_ar(): assert digits.convert_to_ar('123۴۵۶') == '١٢٣٤٥٦' assert digits.convert_to_ar(123.456) == '١٢٣.٤٥٦' def test_conver...
11527117
from multiprocessing import * # TODO: return ProcessContext if join is False def spawn(fn, args=(), nprocs=1, join=True, daemon=False, start_method="spawn"): fn(0, *args)
11527122
import torch import torch.nn as nn import torchvision import numpy as np # 2D CNN # Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift # https://arxiv.org/abs/1502.03167 class Cnn(nn.Module): def __init__(self, input_size, num_classes=2): super().__init__() ...
11527127
import numpy as np from ..graph_io import TensorProtoIO, OpsProtoIO from ..operations import OpsParam def shape_2_ak_shape(shape): """ onnx shape to anakin shape :param shape: :return: """ mini_shape = [i for i in shape if (i is not None and i > 0)] return map(int, [1] * (4 - len(mini_shape...
11527141
from Chapter_03 import DecisionTree_CART_RF as CART import pprint filename = 'bcancer.csv' dataset = CART.load_csv(filename) # convert string attributes to integers for i in range(0, len(dataset[0])): CART.str_column_to_float(dataset, i) #Now remove index column from the data set dataset_new = [] for row...
11527149
import sys val=0 sys.path.append("../") from appJar import gui def press(btn): print(btn) print(app.getEntry("a")) app.setButton("Name", "b") def num(btn): global val app.setEntry("ne1", "hiya"+str(val)) val += 1 app=gui() app.addEntry("a") app.setEntryDefault("a", "This is the default") app.s...
11527171
from __future__ import annotations from typing import List, Union, Optional, Any, TYPE_CHECKING import numpy as np from pyNastran.bdf.cards.aero.utils import ( points_elements_from_quad_points) from pyNastran.converters.avl.avl_helper import integer_types, get_spacing, save_wing_elements if TYPE_CHECKING: # prag...
11527243
import os import numpy as np import torch from datasets.dataset_seq2seq import DatasetSeq2seq from models import IdleLayer def _read_ocr_dataset(root): file_data = os.path.join(root, 'letter.data') if not os.path.isfile(file_data): raise(RuntimeError("Could not found OCR dataset (file letter.data) in...
11527246
def main(nums): pd = [-1] * len(nums) pd[0] = 0 for i, element in enumerate(nums): for j in range(i + 1 , i + element + 1 ): if j >= len(nums) or pd[j] != -1: continue pd[j] = pd[i]+1 return pd[-1] # pd = None # def min_numers_jumps(nums, i): # glo...
11527304
import subprocess import os import infra.basetest class TestUbi(infra.basetest.BRTest): config = infra.basetest.BASIC_TOOLCHAIN_CONFIG + \ """ BR2_TARGET_ROOTFS_UBIFS=y BR2_TARGET_ROOTFS_UBIFS_LEBSIZE=0x7ff80 BR2_TARGET_ROOTFS_UBIFS_MINIOSIZE=0x1 BR2_TARGET_ROOTFS_UBI=y ...
11527399
import os import json import base64 import random from mock import patch import pytest from mapboxgl.viz import * from mapboxgl.errors import TokenError, LegendError from mapboxgl.utils import create_color_stops, create_numeric_stops from matplotlib.pyplot import imread @pytest.fixture() def data(): with open(...
11527431
import asyncio import pytest from tests.utils_for_test import NumbersComparer from throttled.exceptions import RateLimitExceeded from throttled.strategies import Strategies numbers_almost_equals = NumbersComparer(error=1e-2).almost_equals def function() -> bool: """Boilerplate function to test the limiter deco...
11527450
from __future__ import absolute_import, division, print_function import pytest import tensorflow as tf import numpy as np from lucid.optvis import objectives, param, render, transform from lucid.modelzoo.vision_models import InceptionV1 np.random.seed(42) NUM_STEPS = 3 @pytest.fixture def inceptionv1(): retu...
11527460
from tasks.salesforce_robot_library_base import SalesforceRobotLibraryBase class Data(SalesforceRobotLibraryBase): def bulk_delete(self, objects, *, where=None, hardDelete=False): self._run_subtask("delete_data", objects=objects, where=where, hardDelete=hardDelete)
11527520
import time, pytest, inspect from utils import * from PIL import Image def test_mixer_from_config(run_brave, create_config_file): subtest_start_brave_with_mixers(run_brave, create_config_file) subtest_assert_two_mixers(mixer_1_props={'width': 160, 'height': 90, 'pattern': 6}) subtest_change_mixer_pattern(...
11527575
from support import lib,ffi from qcgc_test import QCGCTest import unittest class ObjectTestCase(QCGCTest): def test_write_barrier(self): o = self.allocate(16) self.push_root(o) arena = lib.qcgc_arena_addr(ffi.cast("cell_t *", o)) o.hdr.flags = o.hdr.flags & ~lib.QCGC_GRAY_FLAG ...
11527576
import argparse import fnmatch import os import re import sys from itertools import chain from pathlib import Path import toml from robot.utils import FileReader from robocop.exceptions import ( ArgumentFileNotFoundError, NestedArgumentFileError, InvalidArgumentError, ConfigGeneralError, ) from roboco...
11527624
import os import sqlite3 import unittest from contextlib import redirect_stdout from linkml_runtime.utils.compile_python import compile_python from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from linkml.generators.sqlddlgen import SQLDDLGenerator from tests.test_generators.environment imp...
11527650
from django.conf.urls import re_path from .views import ( proposal_submit, proposal_submit_kind, proposal_detail, proposal_edit, proposal_speaker_manage, proposal_cancel, proposal_pending_join, proposal_pending_decline, document_create, document_delete, document_download, ) ...
11527729
from __future__ import absolute_import input_name = '../examples/linear_elasticity/linear_elastic_damping.py' output_name_trunk = 'test_linear_elastic_damping' from tests_basic import TestInputEvolutionary class Test( TestInputEvolutionary ): pass
11527731
from django.core.management import BaseCommand from ...models import Metric from ...utils import reset_generation_key class Command(BaseCommand): def handle(self, **options): verbose = int(options.get('verbosity', 0)) for MC in Metric.__subclasses__(): for metric in MC.objects.all(): ...
11527743
from builtins import chr from builtins import object class Observable(object): def __init__(self): self.Callbacks = [] def addHandler(self, h): if h not in self.Callbacks: self.Callbacks.append(h) def notify(self, rows, cols): for cbk in self.Callbacks: cb...
11527803
import math def main(): s1 = float(raw_input("Enter the sides: ")) s2 = float(raw_input("Enter the sides: ")) s3 = float(raw_input("Enter the sides: ")) area1 = area(s1,s2,s3) print "The area is", area1 def area(p1,p2,p3): s = (p1+p2+p3)/ 2 print s a = math.sqrt(float(s*(s-p1)*(s-p2)*(...
11527807
import os from click.testing import CliRunner from hatch.cli import hatch from hatch.env import ( get_editable_packages, get_installed_packages, install_packages ) from hatch.utils import env_vars, temp_chdir from hatch.venv import create_venv, is_venv, venv from ..utils import requires_internet, wait_until def...
11527830
import django.http def django_response(request): resp = django.http.HttpResponse() resp.set_cookie("name", "value", secure=False, httponly=False, samesite='None') return resp def django_response(): response = django.http.HttpResponse() response['Set-Cookie'] = "name=value; Sa...
11527863
import base64 import json import os import time from mock import patch from threading import Thread from rancher_gen.handler import RancherConnector, MessageHandler from rancher_gen.compat import b64encode class TestRancherConnector: @classmethod def setup_class(cls): template = os.path.join(os.path....
11527881
from falcor import * def render_graph_ToneMapping(): loadRenderPassLibrary("ImageLoader.dll") loadRenderPassLibrary("ToneMapper.dll") loadRenderPassLibrary("BlitPass.dll") testToneMapping = RenderGraph("ToneMapper") ImageLoader = createPass("ImageLoader", {'filename' : "LightProbes/hallstatt4_hd.hd...
11527944
from .base import TestCase import mock from urllib3.response import HTTPResponse from graphite.finders.remote import RemoteFinder from graphite.readers.remote import RemoteReader from graphite.util import pickle, BytesIO, msgpack from graphite.wsgi import application # NOQA makes sure we have a working WSGI app #...
11527960
import core.modules import core.modules.module_registry from core.modules.vistrails_module import Module, ModuleError from Array import * import scipy import scipy.signal from scipy import sparse, fftpack import numpy class WindowModule(object): my_namespace = 'scipy|signals|windows' class HanningWindow(WindowMod...
11527969
class Solution: def threeSumClosest(self, nums: List[int], target: int) -> int: nums.sort() closestSum = sum(nums[:3]) for i in range(len(nums) - 2): if i == 0 or nums[i] != nums[i - 1]: start = i + 1 end = len(nums) - 1 while start...
11527990
import sys import glob from datetime import datetime, timedelta import traces from traces.utils import datetime_range def parse_iso_datetime(value): return datetime.strptime(value, "%Y-%m-%dT%H:%M:%S") def read_all(pattern='data/lightbulb-*.csv'): """Read all of the CSVs in a directory matching the filena...
11527999
import ApplicationRegisterService_pb2_grpc import ApplicationRegisterService_pb2 import grpc import urllib import json class SkyWalking(object): def __init__(self, agentstream=["app.danoolive.com:10800"], applicationCode="python-test-service", debug=False): if isinstance(agentstream, string): agentstreams...
11528046
from lakesuperior.dictionaries.namespaces import ns_collection as nsc srv_mgd_subjects = { nsc['fcsystem'].root, } srv_mgd_predicates = { nsc['fcrepo'].created, nsc['fcrepo'].createdBy, nsc['fcrepo'].hasFixityService, nsc['fcrepo'].hasParent, nsc['fcrepo'].lastModified, nsc['fcrepo'].lastM...
11528058
import base64 from flask import render_template, url_for, redirect, session, request, current_app from flask_login import LoginManager from ..models.user import User login_manager = LoginManager() def handle_bad_request(e): return render_template('errors/400.html', code=400, message=e), 400 def handle_unautho...
11528125
import FWCore.ParameterSet.Config as cms JetIDParams = cms.PSet( useRecHits = cms.bool(True), hbheRecHitsColl = cms.InputTag("hbhereco"), hoRecHitsColl = cms.InputTag("horeco"), hfRecHitsColl = cms.InputTag("hfreco"), ebRecHitsColl = cms.InputTag("ecalRecHit", "EcalRecHits...
11528132
import torch import logging import pdb import os import datetime import warnings warnings.filterwarnings("ignore") from config import cfg from data import make_data_loader from solver import build_optimizer, build_scheduler from utils.check_point import DetectronCheckpointer from engine import ( default_argument_...
11528157
import pytest import xmltodict from jmeter_api.samplers.jdbc_request.elements import JdbcRequest, ResultSetHandler, QueryType class TestJdbcRequestArgsTypes: def test_name(self): with pytest.raises(TypeError): JdbcRequest(name=123) def test_comments(self): with pytest.raises(Typ...
11528204
from datetime import datetime, timezone import scrapy class Page(scrapy.Item): """ General scrapy item to store entire HTTP body """ url = scrapy.Field() body = scrapy.Field() crawled_at = scrapy.Field() def __repr__(self): """ Omit body to shorten logs. """ ...
11528220
from shadowlands.tui.effects.cursor import Cursor from shadowlands.tui.debug import debug import pdb class DynamicSourceCursor(Cursor): def __init__(self, screen, renderer, x, y, refresh_period=None, **kwargs): super(DynamicSourceCursor, self).__init__(screen, renderer, x, y, **kwargs) self._previ...
11528225
import argparse import logging import os import shutil from overrides import overrides from subprocess import Popen, PIPE from typing import List from sacrerouge.commands import MetricSetupSubcommand from sacrerouge.common import DATA_ROOT, TemporaryDirectory from sacrerouge.data import MetricsDict from sacrerouge.dat...
11528226
FIELD_CACHE = {} def Nullable(cls, **kwargs): if cls in FIELD_CACHE: return FIELD_CACHE[cls](**kwargs) class new(cls): class Meta: name = f"Nullable{cls._meta.name}" @staticmethod def serialize(value): if not value: return None ...
11528256
from . import Task class DummyTask(Task): def setup(self): return self.success() def compile(self): return self.success() def run(self): return self.success()
11528279
import json import argparse import sys import logging import random from datetime import datetime import os import numpy as np import pickle from tqdm import tqdm, trange import torch from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler, TensorDataset) from torch.uti...
11528304
from reportlab.graphics.barcode import createBarcodeDrawing from reportlab.graphics.shapes import Drawing from reportlab.lib import units class Barcode: @staticmethod def get_barcode(value, width, barWidth=0.05 * units.inch, fontSize=30, humanReadable=True): barcode = createBarcodeDrawing( ...
11528315
from urllib.parse import urlencode, urlsplit from django.contrib.auth.tokens import default_token_generator from django.urls import reverse from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode from templated_email import send_templated_mail from ..account.models import Use...
11528339
import tensorflow as tf import tensorflow.contrib.slim as slim import numpy as np from .augment import random_affine, random_photometric from .flow_util import flow_to_color from .util import resize_area, resize_bilinear from .losses import compute_losses, create_border_mask from ..ops import downsample from .image_wa...
11528367
from __future__ import unicode_literals from datetime import datetime from django.contrib.auth.models import User from reviewboard.changedescs.models import ChangeDescription from reviewboard.testing.testcase import TestCase class ChangeDescTests(TestCase): """Tests for the ChangeDescription model.""" def...
11528386
from django.conf.urls import url from dojo.development_environment import views urlpatterns = [ # dev envs url(r'^dev_env$', views.dev_env, name='dev_env'), url(r'^dev_env/add$', views.add_dev_env, name='add_dev_env'), url(r'^dev_env/(?P<deid>\d+)/edit$', views.edit_dev_env, name='edit...
11528393
import os from invoke import task WHEELHOUSE_PATH = os.environ.get('WHEELHOUSE') CONSTRAINTS_FILE = 'constraints.txt' @task def wheelhouse(ctx, develop=False): req_file = 'dev-requirements.txt' if develop else 'requirements.txt' cmd = 'pip wheel --find-links={} -r {} --wheel-dir={} -c {}'.format(WHEELHOUSE_...
11528395
import os import time import numpy as np import psutil from classicML import CLASSICML_LOGGER def _format_and_display_the_time_spent(start_time=None, end_time=None, time_spent_list=None, repeat=None): """格式化并显示运行时间. Arguments: start_time: float, default=None, 函数开始运行的时间. end_time...
11528504
from __future__ import absolute_import from __future__ import division from __future__ import print_function import shutil import sys import tempfile from observations.r.icecream import icecream def test_icecream(): """Test module icecream.py by downloading icecream.csv and testing shape of extracted data h...
11528530
import os import sys import numpy import theano import theano.tensor as T from theano.tensor.shared_randomstreams import RandomStreams import cPickle from dataset import CIFAR10 from layer import StackedLayer from classifier import LogisticRegression from model import ClassicalAutoencoder, ZerobiasAutoencoder, LinearA...
11528546
from django.core.management.base import BaseCommand from datetime import date from intake import models from formation.fields import DateOfBirthField class Command(BaseCommand): help = "Fills dob column from answers['dob'] field" def handle(self, *args, **options): subs = models.FormSubmission.object...
11528547
import unittest from asq.queryables import Queryable from asq.test.test_queryable import infinite __author__ = "<NAME>" class TestEqualOperator(unittest.TestCase): def test_eq_positive(self): a = [1, 2, 3, 4, 16, 32] b = (1, 2, 3, 4, 16, 32) c = Queryable(a) == b self.assertTrue(c...
11528565
from arekit.common.data.input.providers.columns.opinion import OpinionColumnsProvider from arekit.common.data.input.providers.columns.sample import SampleColumnsProvider from arekit.common.data.input.providers.opinions import InputTextOpinionProvider from arekit.common.data.input.providers.rows.opinions import BaseOpin...
11528582
import os import tempfile import unittest import logging from pyidf import ValidationLevel import pyidf from pyidf.idf import IDF from pyidf.electric_load_center import GeneratorFuelCellAuxiliaryHeater log = logging.getLogger(__name__) class TestGeneratorFuelCellAuxiliaryHeater(unittest.TestCase): def setUp(self...
11528584
from setuptools import setup, find_packages with open("README.md", "r") as fh: long_description = fh.read() setup( name="archivy_extra_metadata", version="0.1.0", author="Uzay-G", description=( "Archivy extension to add some metadata at the end of your notes / bookmarks." ), long_d...
11528586
import math import os import unittest import numpy as np import pandas as pd from scripts.utils.import_patstat import convert_patstat_data_to_data_frame def create_df_with_unused_columns(df_dict, unused_keys): dict_key = list(df_dict.keys())[0] num_copies = len(df_dict[dict_key]) for unused_key in unuse...
11528614
from __future__ import print_function import gdbremote_testcase from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class TestGdbRemoteExpeditedRegisters( gdbremote_testcase.GdbRemoteTestCaseBase): mydir = TestBase.compute_mydir(__file__) ...
11528635
from collections import defaultdict import torch import torch.nn as nn import torch.nn.functional as F from layers import * from models.resnet import resnet50 from utils.calc_acc import calc_acc class Model(nn.Module): def __init__(self, num_classes=None, drop_last_stride=False, joint_training=False, mix=False,...
11528643
def binary_to_string(binary): return ''.join(chr(int(binary[a:a + 8], 2)) for a in xrange(0, len(binary), 8))
11528663
import ctypes import numpy as np import matplotlib.pyplot as plt import time import os.path import cv2 rows = 800 cols = 700 height = 36 path = '/mnt/ssd2/od/KITTI/training/velodyne' print ('LiDAR data pre-processing starting...') # initialize an np 3D array with 1's indata = np.zeros((rows, cols, height), dtype = n...
11528671
import tensorflow as tf import numpy as np def smoothed_metric_loss(input_tensor, name='smoothed_triplet_loss', margin=1): ''' input_tensor: require a tensor with predefined dimensions (No None dimension) Every two consecutive vectors must be a positive pair. There should no...