id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
153768 | import dill
import json
import os
def load(path):
"""
Loads a saved model and returns it.
Args:
path: Name of the model or full path to model.
Example::
import backprop
backprop.save(model_object, "my_model")
model = backprop.load("my_model")
"""
# Try to loo... |
153776 | import os
import re
from weakref import WeakKeyDictionary
from io import StringIO
import trafaret as _trafaret
from yaml import load, dump, ScalarNode
from yaml.scanner import ScannerError
try:
from yaml import CSafeLoader as SafeLoader
except ImportError:
from yaml import SafeLoader
from .error import Config... |
153815 | from symsynd.heuristics import get_ip_register
def test_ip_reg():
assert get_ip_register({'pc': '0x42'}, 'arm7') == int('42', 16)
assert get_ip_register({}, 'arm7') == None
assert get_ip_register({}, 'x86') == None
|
153818 | import cv2
import numpy as np
from PIL import Image
from torch.utils.data import Dataset
# imagenet
imagenet_mean = [0.485, 0.456, 0.406]
imagenet_std = [0.229, 0.224, 0.225]
class CustomDataset(Dataset):
def __init__(self, all_img_path_list, transform, ):
self.all_img_paths = all_img_path_list
s... |
153849 | def test_get_uptimez(client):
response = client.get("/uptimez/")
assert response.status_code == 200
def test_get_healthz(client):
response = client.get("/healthz/")
assert response.status_code == 200
|
153874 | from typing import Optional
import cv2
from pymba import Frame
# todo add more colours
PIXEL_FORMATS_CONVERSIONS = {
'BayerRG8': cv2.COLOR_BAYER_RG2RGB,
}
def display_frame(frame: Frame, delay: Optional[int] = 1) -> None:
"""
Displays the acquired frame.
:param frame: The frame object to display.
... |
153891 | from sonosco.inputs.audio import SonoscoAudioInput
import webrtcvad
import collections
import pyaudio
import sys
import logging
class VadInput(SonoscoAudioInput):
def __init__(self):
super().__init__()
self.FORMAT = pyaudio.paInt16
self.CHANNELS = 1
self.RATE = 16000
self.... |
153900 | from haystack.query import SearchQuerySet
from search.services.suggest import SuggestBase
class SuggestInvestigator(SuggestBase):
@classmethod
def _query(cls, term):
sqs = SearchQuerySet()
raw_results = sqs.filter(investigator_name=term).order_by('-investigator_complaint_count')[:5]
... |
153906 | import behave
@behave.given(u'There are no annotations')
def step_impl(context):
assert True
@behave.when(u'I list all annotations')
def step_impl(context):
context.annotations_list = context.item.annotations.list()
@behave.then(u'I receive a list of all annotations')
def step_impl(context):
assert le... |
153946 | import subprocess
import os
os.chdir('./')
ST = 'python '
stand = dict()
conf = dict()
stand = dict()
stand['ds'] = 'cifar10'
stand['bs'] = 128
stand['defense'] = 'adr_pgd'
stand['model'] = 'resnet18'
stand['epsilon'] = 0.031
stand['trades_beta'] = 1.0
stand['lccomw'] = 1.0
stand['lcsmtw'] = 1.0
stand['gbcomw'] =... |
153954 | import shelve
import os
import re
from resource_api.interfaces import Resource as BaseResource, Link as BaseLink, AbstractUriPolicy
from resource_api.schema import StringField, DateTimeField, IntegerField
from resource_api.service import Service
from resource_api.errors import ValidationError
RE_SHA1 = re.compile("^... |
153955 | import os
import json
from string import Template
from functools import total_ordering
import argparse
from os import path
def generate(sitedir, siteBaseUrl, codeBaseUrl, logoPath):
versions = loadVersions(sitedir)
print(versions.asList())
generateVersions(sitedir, versions)
generateIndex(sitedir, siteBaseUrl, ver... |
153976 | import pytest
from waterbutler.providers.figshare.metadata import (FigshareFileMetadata,
FigshareFolderMetadata,
FigshareFileRevisionMetadata)
from tests.providers.figshare.fixtures import (project_article_type_1... |
154026 | import time
import pytest
from py_ecc import (
bn128,
optimized_bn128,
bls12_381,
optimized_bls12_381,
)
from py_ecc.fields import (
bls12_381_FQ,
bls12_381_FQ2,
bls12_381_FQ12,
bn128_FQ,
bn128_FQ2,
bn128_FQ12,
optimized_bls12_381_FQ,
optimized_bls12_381_FQ2,
optim... |
154038 | import iotbx.file_reader
from cctbx.array_family import flex
def run(hklin):
arrays = iotbx.file_reader.any_file(hklin).file_server.miller_arrays
for arr in arrays:
if not arr.anomalous_flag():
continue
print arr.info()
if arr.is_complex_array():
arr = arr.as_am... |
154068 | def fahrenheit_to_celsius(F):
C = 0
# Your code goes here: calculate the temperature in Celsius,
# store in a variable (we called it C), and return it.
return C
|
154090 | from django.test import SimpleTestCase
from corehq.form_processor.models import XFormInstanceSQL
class FormDocTypesTest(SimpleTestCase):
def test_doc_types(self):
for doc_type in XFormInstanceSQL.DOC_TYPE_TO_STATE:
self.assertIn(doc_type, XFormInstanceSQL.ALL_DOC_TYPES)
def test_deleted(... |
154103 | import sys
from Bio import SeqIO
input_file = sys.argv[1]
output_file = "".join(input_file.split(".")[:-1]) + ".rachel.fa"
print input_file
print output_file
fasta_sequences = SeqIO.parse(open(input_file,'r'),'fasta')
with open(output_file, 'w') as out_file:
for fasta in fasta_sequences:
name, description... |
154121 | from .abstract_conjunction import AbstractConjunction
from .condition_type import ConditionType
class OrConjunction(AbstractConjunction):
def __init__(self, conditions):
super().__init__(type_=ConditionType.OR.value, conditions=conditions)
|
154123 | import asyncio
import pytest
from aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop
from aiohttp import web
from asynctest import mock as async_mock
from ....core.in_memory import InMemoryProfile
from ....utils.stats import Collector
from ...wire_format import JsonWireFormat
from ..base import OutboundTr... |
154127 | import unittest
from unittest import mock
from django.contrib.auth.models import User, Group
from tethys_compute.job_manager import JobManager, JOB_TYPES
from tethys_compute.models.tethys_job import TethysJob
from tethys_compute.models.condor.condor_scheduler import CondorScheduler
from tethys_apps.models import Tethy... |
154182 | import unittest
import sys
from pathlib import Path
TEST_DIR = str(Path(__file__).parent.resolve())
BASE_DIR = str(Path(__file__).parent.parent.resolve())
sys.path.append(BASE_DIR)
# Run tests without using GPU
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
from core.sensible_span_extractor import SensibleSpanEx... |
154246 | import shutil
import tempfile
from unittest import TestCase, mock
import pytest
from lineflow import download
from lineflow.datasets.squad import Squad, get_squad
class SquadTestCase(TestCase):
@classmethod
def setUpClass(cls):
cls.default_cache_root = download.get_cache_root()
cls.temp_dir... |
154292 | from __future__ import annotations
from typing import Dict
from whyqd.base import BaseCategoryAction
class Action(BaseCategoryAction):
"""`CATEGORISE` support function which must be run *before* it to derive unique category terms from unique
values in a source data column.
`ASSIGN` subset of unique valu... |
154345 | from .issuer_credential_revocation_updater import IssuerCredentialRevocationUpdater
from .issuer_credential_status_updater import IssuerCredentialStatusUpdater
def subscribe_issuer_protocol_listeners():
IssuerCredentialStatusUpdater()
IssuerCredentialRevocationUpdater()
|
154353 | import time
from pyscf import scf
import os, time
import numpy as np
from mldftdat.lowmem_analyzers import RHFAnalyzer, UHFAnalyzer
from mldftdat.workflow_utils import get_save_dir, SAVE_ROOT, load_mol_ids
from mldftdat.density import get_exchange_descriptors2, LDA_FACTOR, GG_AMIN
from mldftdat.data import get_unique_c... |
154355 | import os
import numpy as np
import time
import subprocess
import sys
setups = ['spec', 'spec', 'spec']
GPU = 0
script = 'train.py'
if __name__ == '__main__':
start = time.time()
for stp in setups:
str_exec = 'CUDA_VISIBLE_DEVICES=' + str(GPU) + ' python ' + str(script) + ' ' + str(stp)
#str_e... |
154393 | from common import *
from logcatcolor.column import *
from logcatcolor.config import *
from logcatcolor.layout import *
from logcatcolor.profile import *
from logcatcolor.reader import *
import unittest
class ProfileTest(unittest.TestCase):
def setUp(self):
pass
def test_package_name_filter(self):
... |
154421 | from pathlib import Path
from typing import Tuple
import numpy as np
import pandas as pd
import torch
import torch.nn.functional as F
import torchaudio
from constants import INPUT_SAMPLE_RATE, TARGET_SAMPLE_RATE
from torch.utils.data import DataLoader, Dataset
from tqdm import tqdm
class SegmentationDataset(Dataset)... |
154434 | import torch.nn as nn
import math
import torch
from collections import namedtuple
from maskrcnn_benchmark.layers import FrozenBatchNorm2d
# s0 = top layer idx
# name = sub op name
# s1 = sub layer idx
GraphPath = namedtuple("GraphPath", ['s0', 'name', 's1']) #
def conv_bn(inp, oup, stride, norm_func):
return nn.S... |
154449 | from finviz.config import connection_settings
class NoResults(Exception):
""" Raise when there are no results found. """
def __init__(self, query):
super(NoResults, self).__init__(f"No results found for query: {query}")
class InvalidTableType(Exception):
""" Raise when the given table type is i... |
154471 | import allure
from pages.web_page import WebPage
from pages.web_elements import *
class ArticlePage(WebPage):
def title(self): return el(self.page, selector='.container > h1')
def author_link(self): return el(self.page, selector='.author')
def subject(self): return el(self.page, selector='div[class*="art... |
154487 | from requests.auth import HTTPBasicAuth
def apply_updates(doc, update_dict):
# updates the doc with items from the dict
# returns whether or not any updates were made
should_save = False
for key, value in update_dict.items():
if getattr(doc, key, None) != value:
setattr(doc, key, v... |
154495 | import unittest
from IDM import IDM, IDMAuto
from Constants import *
from LaneChange import LaneChange
from Cars import *
from copy import copy, deepcopy
from CarFactory import *
from Street import *
class MyTestCase(unittest.TestCase):
def test_IDM(self):
# using the initial value of Cars
... |
154506 | import os
import json
import re
import subprocess
import sys
import logging
from datetime import datetime
def install(package):
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
install('boto3')
import boto3
LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO").upper()
logger = logging.getLogger()
lo... |
154511 | from torchsampler.__about__ import * # noqa: F401 F403
from torchsampler.imbalanced import ImbalancedDatasetSampler
__all__ = [
'ImbalancedDatasetSampler',
]
|
154528 | from django.db import models
# Create your models here.
from myuser.models import TemplateUser
class Event(models.Model):
description = models.CharField(max_length=300, blank=True,null=True, unique=False)
title = models.CharField(max_length=300, blank=False, null=False, unique=False)
enabled = models.Boo... |
154556 | import os
import sys
import pytest
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
from base import TestBaseClass
class TestClassOelintVarsFileSettingsDouble(TestBaseClass):
@pytest.mark.parametrize('id', ['oelint.vars.filessetting.double'])
@pytest.mark.parametrize('occurrence', [1])
@p... |
154569 | from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
cls = get_driver(Provider.EC2)
driver = cls('temporary access key', 'temporary secret key',
token='<PASSWORD>', region="us-west-1")
|
154586 | import torch,math
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from roialign.roi_align.crop_and_resize import CropAndResizeFunction
def log2(x):
"""Implementatin of Log2. Pytorch doesn't have a native implemenation."""
ln2 = Variable(torch.log(torch.FloatTensor([2.... |
154597 | from typing import Sequence
from eth_typing import BLSSignature
from eth_utils import ValidationError
from eth2._utils.bls import bls
from eth2._utils.hash import hash_eth2
from eth2.beacon.attestation_helpers import (
validate_indexed_attestation_aggregate_signature,
)
from eth2.beacon.committee_helpers import g... |
154607 | import pandas as pd
import numpy as np
import glob
import math
import re
import sys
import multiprocessing
def downsampleRow(args):
row, targetSum = args
currentCount = row.sum()
downsampledRow = row.copy()
while currentCount > targetSum and currentCount != 0:
possible = downsamp... |
154628 | from torch import nn as nn
from torch.nn import functional as F
from torch.nn.utils import spectral_norm
import torch
from torch import nn as nn
from torch.nn import functional as F
from torch.nn.utils import spectral_norm
from basicsr.utils.registry import ARCH_REGISTRY
import torch
class add_attn(nn.Module):
... |
154635 | import uuid
from django.db import models
class TimestampedModel(models.Model):
updated_at = models.DateTimeField(auto_now=True)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
abstract = True
class KeyModel(TimestampedModel):
key = models.CharField(
max_length=255,... |
154648 | import rq
from rq import Queue
from rq import Connection
from redis import Redis
class Worker(object):
def __init__(self, job_queue_name_list):
self.queues = job_queue_name_list
def run(self, redis):
redis_connection = Redis(redis[0], redis[1], password=redis[2])
with Connection(redis... |
154678 | from .saver import CheckpointSaver
from .data_loader import CheckpointDataLoader, CheckpointSampler
from .data_loader import RandomSampler, SequentialSampler
from .base_trainer import BaseTrainer
from .base_options import BaseOptions
|
154682 | import json
import logging
import math
import os
import pathlib
import subprocess
import numpy as np
import shapely.geometry
import shapely.affinity
import venn7.bezier
ROOT = pathlib.Path(os.path.realpath(__file__)).parent
class VennDiagram:
"""A simple symmetric monotone Venn diagram. The diagram is encoded ... |
154692 | import pytest
import util.cli
import core.config
import modules.contrib.amixer
@pytest.fixture
def module_mock(request):
def _module_mock(config = []):
return modules.contrib.amixer.Module(
config=core.config.Config(config),
theme=None
)
yield _module_mock
@pytest.fix... |
154721 | from unittest import TestCase
from camunda.variables.variables import Variables
class VariablesTest(TestCase):
def test_get_variable_returns_none_when_variable_absent(self):
variables = Variables({})
self.assertIsNone(variables.get_variable("var1"))
def test_get_variable_returns_value_when_... |
154724 | import hashlib
from assemblyline.common import entropy
from assemblyline.common.charset import safe_str
DEFAULT_BLOCKSIZE = 65536
# noinspection PyBroadException
def get_digests_for_file(path, blocksize=DEFAULT_BLOCKSIZE,
calculate_entropy=True,
on_first_block=lambd... |
154734 | import py
from pypy.rpython.lltypesystem import lltype
from pypy.jit.timeshifter import rvalue
from pypy.jit.timeshifter import rcontainer
from pypy.jit.timeshifter.test.support import *
def test_create_int_redbox_var():
jitstate = FakeJITState()
gv = FakeGenVar()
box = rvalue.IntRedBox("dummy kind", gv)
... |
154745 | from lxml import etree
import lxml
import pickle
with open('/Users/billchen/OneDrive/Workspace/LearningRepo/Python3/专利检索爬虫/20050101_20101231_B09B_PAGE1.pickle', 'rb') as f:
source = ''
p = pickle.load(f)
html = etree.HTML(p)
|
154757 | import os
import torch
import create_data
from model import shape_net
import numpy as np
def align_bone_len(opt_, pre_):
opt = opt_.copy()
pre = pre_.copy()
opt_align = opt.copy()
for i in range(opt.shape[0]):
ratio = pre[i][6] / opt[i][6]
opt_align[i] = ratio * opt_align[i]
... |
154787 | import info
class subinfo(info.infoclass):
def setTargets(self):
self.versionInfo.setDefaultValues()
self.description = "GUI to profilers such as Valgrind"
self.defaultTarget = 'master'
def setDependencies(self):
self.runtimeDependencies["libs/qt5/qtbase"] = None
self.... |
154841 | from __future__ import absolute_import
from __future__ import print_function
from loqui.client import LoquiClient
client = LoquiClient(('localhost', 4001))
print(len(client.send_request('hello world'))) |
154864 | from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt
from PyQt5 import QtCore, QtGui
from .views import *
from .models import State, StateListener, KeyboardNotifier
from .styles import Theme
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("UltimateLa... |
154874 | from ..mapper import PropertyMapper, ApiInterfaceBase
from ..mapper.types import Timestamp, AnyType
__all__ = ['RewriteRule', 'RewriteRuleInterface']
class RewriteRuleInterface(ApiInterfaceBase):
matcher: str
replacer: str
class RewriteRule(PropertyMapper, RewriteRuleInterface):
pass
|
154883 | import os
import sys
import inspect
from unittest import TestCase
from chatterbot import corpus
from chatterbot import languages
from chatterbot.constants import STATEMENT_TEXT_MAX_LENGTH
from chatterbot_corpus.corpus import DATA_DIRECTORY
class CorpusUtilsTestCase(TestCase):
"""
This test case is designed t... |
154899 | from django import forms
from .models import Member, get_config
from .util import validate_country
class MemberForm(forms.ModelForm):
class Meta:
model = Member
fields = ('fullname', 'country', 'listed')
def clean_country(self):
if self.instance.country_exception:
# No co... |
154928 | from datetime import datetime
import os
from pathlib import Path
import warnings
import pickle
from typing import List, Dict, Any
from thunderbolt.client.local_cache import LocalCache
from tqdm import tqdm
class LocalDirectoryClient:
def __init__(self, workspace_directory: str = '', task_filters: List[str] = []... |
154955 | import os
if 'DJANGO_SETTINGS_MODULE' not in os.environ:
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
from drf_typescript_generator.utils import (
_get_method_return_value_type, _get_typescript_name, _get_typescript_type, export_serializer,
get_serializer_fields
)
from drf_typescript_generator.g... |
155015 | from scripts.simulation.SimulationWorld import SimulationWorld
from scripts.Robot.Robot import Robot
import numpy as np
import scripts.utils.yaml_paser as yaml
from scripts.utils.utils import Utils as utils
import logging
import os
from collections import OrderedDict
from scripts.DB.Mongo_driver import MongoDriver
impo... |
155030 | from ploomber.clients import SQLAlchemyClient
def get_client():
return SQLAlchemyClient('sqlite:///data.db')
|
155068 | from django.shortcuts import render
from django.core import serializers
from django.http import HttpResponse
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.conf import settings
import json
import datetime
from registrar.models import Course
from registr... |
155141 | import socket
if socket.gethostname() == 'Faramir': #for CNN_B
data_root = '/home/tencia/Documents/data/heart/'
data_kaggle = data_root + 'kaggle'
data_sunnybrook = data_root + 'sunnybrook'
local_root = '/home/tencia/Dropbox/heart/diagnose-heart/'
data_manual = local_root + 'manual_data'
data_in... |
155161 | from __future__ import annotations
from e2cnn import gspaces
from e2cnn import kernels
from e2cnn import diffops
from .general_r2 import GeneralOnR2
from .utils import rotate_array
from e2cnn.group import Representation
from e2cnn.group import Group
from e2cnn.group import DihedralGroup
from e2cnn.group import O2
fr... |
155192 | import netomaton as ntm
if __name__ == '__main__':
network = ntm.topology.cellular_automaton2d(60, 60, r=1, neighbourhood="Hex")
initial_conditions = ntm.init_simple2d(60, 60)
def activity_rule(ctx):
return 1 if sum(ctx.neighbourhood_activities) == 1 else ctx.current_activity
trajectory = nt... |
155198 | from ..utils import load_pretrained
from .blocks import ResNet, ResNetBasicBlock, ResNetBlock
__all__ = ['resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152']
META = {
'resnet18': ['resnet18.pth', 'https://drive.google.com/open?id=1d-AgSMO7HcKihDEXHqzDX2dAxYtH7N2m'],
'resnet34': ['resnet34.pth', 'http... |
155248 | from keras.models import *
from keras.callbacks import *
import keras.backend as K
from model import *
from data import *
import cv2
import argparse
import pydot, graphviz
from keras.utils import np_utils, plot_model
def visualize_class_activation_map(model_path, img_path, output_path, run_count, write_to_file, post_... |
155275 | from scramjet.streams import Stream, StreamAlreadyConsumed
import asyncio
import pytest
@pytest.mark.asyncio
async def test_simple_stream_piping():
s1 = Stream.read_from(range(8)).map(lambda x: 2*x)
s2 = Stream().filter(lambda x: x > 5)
s1.pipe(s2)
assert await s2.to_list() == [6, 8, 10, 12, 14]
@pyte... |
155328 | from collections import namedtuple
from datetime import datetime
def parse_datetime(datetime_str):
if datetime_str:
return datetime.strptime(datetime_str, "%Y-%m-%dT%H:%M:%S.%fZ")
class Price(
namedtuple(
"price",
[
"quantity",
"vwap",
"price",
... |
155342 | from flask_script import Manager
from app import application
manager = Manager(application)
# Not sure if I need a database yet
# db = SQLAlchemy(application)
# migrate = Migrate(application, db)
# manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
|
155373 | import os
from billy.utils.generic import get_git_rev
here = os.path.abspath(os.path.dirname(__file__))
VERSION = '0.0.0'
version_path = os.path.join(here, 'version.txt')
if os.path.exists(version_path):
with open(version_path, 'rt') as verfile:
VERSION = verfile.read().strip()
REVISION = None
revision_... |
155387 | import glob,sys
import numpy as np
sys.path.append('../../flu/src')
import test_flu_prediction as test_flu
import matplotlib.pyplot as plt
import analysis_utils_toy_data as AU
file_formats = ['.svg', '.pdf']
plt.rcParams.update(test_flu.mpl_params)
line_styles = ['-', '--', '-.']
cols = ['b', 'r', 'g', 'c', 'm', 'k'... |
155416 | import collections
import datetime
import itertools
import os
import subprocess
from hyperparameters_config import (paraphrase, inverse_paraphrase)
class SafeDict(dict):
def __missing__(self, key):
return '{' + key + '}'
def get_run_id():
filename = "style_paraphrase/logs/expts.txt"
if os.path.... |
155451 | import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pytest
from cycler import cycler
def test_colorcycle_basic():
fig, ax = plt.subplots()
ax.set_prop_cycle(cycler('color', ['r', 'g', 'y']))
for _ in range(4):
ax.plot(range(10), range(10))
assert [l.get_color() ... |
155482 | from sympy.solvers import solve
from sympy.simplify import simplify
def singularities(expr, sym):
"""
Finds singularities for a function.
Currently supported functions are:
- univariate real rational functions
Examples
========
>>> from sympy.calculus.singularities import singularities
... |
155484 | import torch
from cogdl import oagbert
tokenizer, bert_model = oagbert()
bert_model.eval()
sequence = ["CogDL is developed by KEG, Tsinghua.", "OAGBert is developed by KEG, Tsinghua."]
tokens = tokenizer(sequence, return_tensors="pt", padding=True)
with torch.no_grad():
outputs = bert_model(**tokens)
print(outp... |
155485 | SAMPLE_YEAR = 1983
SAMPLE_YEAR_SHORT = 83
SAMPLE_MONTH = 1
SAMPLE_DAY = 2
SAMPLE_HOUR = 15
SAMPLE_UTC_HOUR = 20
SAMPLE_HOUR_12H = 3
SAMPLE_MINUTE = 4
SAMPLE_SECOND = 5
SAMPLE_PERIOD = 'PM'
SAMPLE_OFFSET = '-00'
SAMPLE_LONG_TZ = 'UTC'
def create_sample(template: str) -> str:
return (
template
.repl... |
155553 | from sklearn.decomposition import PCA
import pandas as pd
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
df = pd.read_csv("Iris.csv")
labels = df['Species']
X = df.drop(['Id','Species'],axis=1)
X_std = StandardScaler().fit_transform(X)
pca = PCA(n_components=4)
X_transform = p... |
155563 | import hmac
from urllib.parse import quote
import httpx
from fastapi import HTTPException, Query
from fastapi.responses import RedirectResponse
from idunn import settings
client = httpx.AsyncClient()
base_url = settings.get("BASE_URL")
secret = settings.get("SECRET").encode()
def resolve_url(url: str) -> str:
... |
155688 | import glob
import numpy as np
import pandas as pd
from collections import OrderedDict
#from . import metrics
import metrics
from .csv_reader import csv_node
__all__ = ['tune_threshold',
'assemble_node',
'assemble_dev_threshold',
'metric_reading',
'Ensemble']
def tune_thres... |
155716 | from __future__ import print_function
import subprocess
import tempfile
import numpy as np
import warnings
import astropy.units as u
_quantity = u.Quantity
from collections import defaultdict
import os
import sys
from . import utils
from . import synthspec
from .utils import QuantityOff,ImmutableDict,unitless,grouper
... |
155742 | import six
import multiprocessing
import pytest
from .run_functions import log_observation, upload_artifact
from operator import itemgetter
from functools import partial
class TestConcurrency:
def test_multiple_runs_log_obs(self, client):
client.set_project()
client.set_experiment()
pool... |
155755 | import numpy as np
from collections import defaultdict
from .loss import compute_rre, compute_rte
class Logger:
def __init__(self):
self.store = defaultdict(list)
def reset(self):
self.store = defaultdict(list)
def add(self, key, value):
self.store[key].append(valu... |
155763 | import unittest
from expand_region_handler import *
class UndoRedoTest(unittest.TestCase):
def test_dont_crash_with_blank_json (self):
settingsJson = ''
newSettingsJson = add_to_stack(settingsJson, "teststring", 2, 3, 1, 1);
newSettings = json.loads(newSettingsJson)
self.assertEqual(newSettings.get... |
155769 | import numpy as np
import torch
import math
def TLift(in_score, gal_cam_id, gal_time, prob_cam_id, prob_time, num_cams, tau=100, sigma=200, K=10, alpha=0.2):
"""Function for the Temporal Lifting (TLift) method
TLift is a model-free temporal cooccurrence based score weighting method proposed in
<NAME> and ... |
155836 | import stackless
class MyChannel:
def __init__(self):
self.queue = []
self.balance = 0
self.temp = None
def send(self, data):
if self.balance < 0:
receiver = self.queue.pop(0)
self.temp = data
receiver.insert()
self.balance += 1... |
155844 | from distutils.core import setup
with open('README.md', encoding='utf-8') as f:
long_description = f.read()
setup(
name='pytago',
version='0.0.12',
packages=['pytago', 'pytago.go_ast'],
url='https://github.com/nottheswimmer/pytago',
license='',
author='<NAME>',
author_email='<EMAIL>',
... |
155848 | import datetime
from airflow import DAG
from airflow.operators.python_operator import PythonOperator
from airflow.contrib.operators.aws_athena_operator import AWSAthenaOperator
import googleapiclient.discovery
from jinja2 import PackageLoader
from kite_airflow.plugins.google import GoogleSheetsRangeOperator
from kite... |
155874 | import sqlite3
from flask_restplus import Resource, reqparse
class User:
def __init__(self, _id, username, password):
self.id = _id
self.username = username
self.password = password
@classmethod
def find_by_username(cls, username):
connection = sqlite3.connect('data.db')
cursor = connection.cursor()
... |
155917 | import pyfits
import numpy
import scipy
import math
import os
import toVac
import prueba
from scipy import optimize
import matplotlib.pylab as plt
import readcol
def gauss1(params,x):
C = params[0]
A = params[1]
med = params[2]
sig = params[3]
g = C+A*numpy.exp(-0.5*(x-med)*(x-med)/(sig*sig))
return g
def res_ga... |
155933 | import pytest
# from snovault.schema_utils import load_schema
pytestmark = [pytest.mark.setone, pytest.mark.working, pytest.mark.schema]
@pytest.fixture
def biosample_cc_w_diff(testapp, de_term, lab, award):
item = {
"culture_start_date": "2018-01-01",
"differentiation_state": "Differentiated to... |
156008 | import re
from random import randint
from typing import Match
from typing import Optional
from retrying import retry
import apysc as ap
from apysc._expression import expression_data_util
from apysc._expression.event_handler_scope import HandlerScope
from apysc._type.copy_interface import CopyInterface
from... |
156058 | import pandas as pd
from pytest import mark
from pytest import approx
@mark.inflation
@mark.usefixtures('_init_inflation')
class TestInflation:
def test_get_infl_rub_data(self):
assert self.infl_rub.first_date == pd.to_datetime('1991-01')
assert self.infl_rub.pl.years == 10
assert self.in... |
156060 | from __future__ import print_function
from __future__ import division
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padded_sequence
from torch.nn.utils.rnn import pad_packed_sequence
def l2norm(inputs, dim=-1):
# inputs: (batch, dim_ft)
norm = torch.norm(... |
156081 | from __future__ import annotations
from jsonclasses import jsonclass, types
@jsonclass
class SuperFilter:
list1: list[int] | None = types.listof(int).filter(lambda i: i % 2 == 0)
list2: list[int] | None = types.listof(int).filter(types.mod(2).eq(0))
|
156302 | import decimal
from protoactor.actor import PID
class AccountCredited:
pass
class AccountDebited:
pass
class ChangeBalance:
def __init__(self, amount: decimal, reply_to: PID):
self.amount = amount
self.reply_to = reply_to
class Credit(ChangeBalance):
def __init__(self, amount: d... |
156304 | from winrm.protocol import Protocol
import argparse
parser = argparse.ArgumentParser(description='Run command on Windows host')
parser.add_argument("--host", required=True)
parser.add_argument("--port", default=5985)
parser.add_argument("--socksport", default=1234)
parser.add_argument("--username", required=True)
pars... |
156318 | import csv
import os
import numpy as np
import sentencepiece as spm
import torch
class DataLoader:
def __init__(self, directory, parts, cols, spm_filename):
"""Dataset loader.
Args:
directory (str): dataset directory.
parts (list[str]): dataset parts. [parts].tsv files mu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.