id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
188519 | from collections import namedtuple
from primitives import primitives
# ----- Expression types -----
fundef = namedtuple('fundef', ('name', 'argnames', 'body'))
vardef = namedtuple('vardef', ('name', 'exp'))
call = namedtuple('call', ('funname', 'args'))
kyif = namedtuple('kyif', ('cond... |
188597 | import gc
import pytest
from msl.loadlib import Client64
from msl.examples.loadlib import Cpp64
from conftest import skipif_no_server32
@skipif_no_server32
def test_unclosed_pipe_warning_1(recwarn):
# recwarn is a built-in pytest fixture that records all warnings emitted by test functions
# The following ... |
188640 | import abc
class Rule(abc.ABC):
@abc.abstractmethod
def check_status(self):
pass
@abc.abstractmethod
def take_action(self):
pass
|
188666 | from __future__ import print_function
import networkx as nx
import argparse
import multiprocessing
from rdkit import Chem
NUM_PROCESSES = 8
def get_arguments():
parser = argparse.ArgumentParser(description='Convert an rdkit Mol to nx graph, preserving chemical attributes')
parser.add_argument('smiles', type=... |
188692 | from DaPy.core import SeriesSet, is_iter, Series
from DaPy.matlib import describe
from collections import namedtuple
from operator import itemgetter
__all__ = ['_label', 'score_binary_clf']
_binary_perf_result = namedtuple('binary_clf', ['TP', 'FN', 'FP', 'TN'])
def plot_reg(y_hat, y, res):
try:
from ma... |
188703 | class AtomClass:
def __init__(self, Velocity, Element = 'C', Mass = 12.0):
self.Velocity = Velocity
self.Element = Element
self.Mass = Mass
def Momentum(self):
return self.Velocity * self.Mass
|
188710 | import pandas as pd
class Bookkeeper:
def __init__(self):
# Instantiate a new data frame.
self.metric = pd.DataFrame(
columns=["Strategy Name", "Percent Change", "Trades Made"]
)
def log(self):
# Log the data frame while ignoring the index.
print(self.metri... |
188746 | from . import _TestHarness, HarnessConfig
import json
from tempfile import NamedTemporaryFile
from pydantic_cli.examples.simple_with_json_config import Opts, runner
class TestExample(_TestHarness[Opts]):
CONFIG = HarnessConfig(Opts, runner)
def _util(self, d, more_args):
with NamedTemporaryFile(mod... |
188763 | import unittest
from tir import Webapp
class TSSMANAGERMONITOR(unittest.TestCase):
@classmethod
def setUpClass(inst):
# Endereco do webapp e o nome do Browser
inst.oHelper = Webapp()
# Utilizando usuário de teste
inst.oHelper.SetTIRConfig("User", "teste")
inst.oHelper... |
188767 | from random import randint
from typing import Any
from typing import Dict
from retrying import retry
import apysc as ap
from apysc._expression import var_names
class TestTimerEvent:
def on_timer(self, e: ap.Event, options: Dict[str, Any]) -> None:
"""
The handler would be called f... |
188783 | import pyb
import stm
@micropython.asm_thumb
def _write_packet(r0, r1, r2): # uart(r0) buf(r1) len(r2)
movw(r3, 0xffff) # uart(r0) &= 0x7fffffff
movt(r3, 0x7fff) #
and_(r0, r3) #
# Disable the Receiver
ldr(r3, [r0, stm.USART_CR1]) # ua... |
188786 | import json
import os
import socket
import sys
import time
import subprocess
import re
import html
from collections import deque
from ipykernel.kernelbase import Kernel
from dyalog_kernel import __version__
from notebook.services.config import ConfigManager
if sys.platform.lower().startswith('win'):
from winreg... |
188800 | from wtforms import Form, TextField
from wtforms.validators import InputRequired, ValidationError
class SimpleForm(Form):
""" The basic test form. """
first_name = TextField("First name", validators=[InputRequired()])
last_name = TextField("Last name", validators=[InputRequired()])
|
188809 | import json
import time
import requests
from django.conf import settings
from django.http import HttpResponse, JsonResponse
from .base import Connector as ConnectorBase
class Connector(ConnectorBase):
def __init__(self, connector, message, type, request=None):
self.connector = connector
self.typ... |
188830 | import doctest
import mock
import unittest
from test import helpers, models
from collections import defaultdict
from sqlalchemy.orm.properties import RelationshipProperty
from sir.querying import iterate_path_values
from sir.schema.searchentities import defer_everything_but, merge_paths
from sir.schema import generate... |
188836 | from itertools import islice
from hwt.doc_markers import internal
from hwt.hdl.statements.assignmentContainer import HdlAssignmentContainer
from hwt.hdl.statements.codeBlockContainer import HdlStmCodeBlockContainer
from hwt.hdl.statements.utils.reduction import HdlStatement_merge_statement_lists, \
is_mergable_sta... |
188865 | import tensorflow as tf
tf.random.set_seed(4323)
x = tf.random.normal([1, 3])
w = tf.random.normal([3, 2])
b = tf.random.normal([2])
y = tf.constant([0, 1])
with tf.GradientTape() as tape:
tape.watch([w, b])
logits = (x @ w + b)
loss = tf.reduce_mean(tf.losses.categorical_crossentropy(y, logits, from_... |
188870 | from opensextant import load_major_cities, load_countries, get_country, load_us_provinces, load_provinces
from unittest import TestCase
# These fundamental data sets are flat-file resources in the API,... they are all varations of
# "official" gazetteer data. Whereas the opensextant.gazetteer.DB class operates with th... |
188955 | import os
import logging
import logging.handlers
import networkn
import client
root = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
log_path = os.path.join(root, 'logs')
def get_logger(name, level=logging.DEBUG):
logger = logging.getLogger(name)
logger.setLevel(level)
logger.handlers = []... |
188979 | import inspect
import io
import json
import logging
import os
import sys
import six
def ensure_path_exists(path):
path = os.path.expanduser(path)
if not os.path.exists(path):
os.makedirs(path)
return path
logger = logging.getLogger(__name__)
class ConfigurationRegistry(object):
def __ini... |
189005 | from io import BytesIO
from re import match
from PyPDF2 import PdfFileWriter, PdfFileReader
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from reportlab.lib.colors import Color
from webcolors import hex_to_rgb
import click
@click.command()
@click.argument('filename')
@click.option('-w', ... |
189039 | from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
class FileBrowser(QWidget):
def __init__(self):
QWidget.__init__(self)
self.init_gui_elements()
self.construct_gui()
self.update_gui()
def init_gui_elements(self):
self.layout = QVBox... |
189061 | from helpers.test_case import AioChatTestCase, unittest_run_loop
class LoginTestCase(AioChatTestCase):
""" Testing for LoginView """
url_name = 'login'
def setUp(self):
super().setUp()
self.url = str(self.app.router[self.url_name].url_for())
@unittest_run_loop
async def test_ur... |
189069 | from math import *
from functools import partial
from sympy import cot
from PySide6.QtWidgets import *
from PySide6.QtUiTools import *
from PySide6.QtCore import *
class Window(QMainWindow):
def __init__(self):
super().__init__()
loader = QUiLoader()
self.ui = loader.load('form.ui'... |
189078 | import unittest
from bulletphysics import *
class TransformTest(unittest.TestCase):
def setUp(self):
self.transform = Transform( Quaternion(0.0, 1.0, 2.0, 1.0), Vector3(0.0, 1.1, 2.2))
def test_opengl(self):
matrix = [0.0] * 5
self.assertRaises(TypeError, self.transform.getOpenGLMatri... |
189124 | import FWCore.ParameterSet.Config as cms
from HLTrigger.HLTfilters.hltHighLevel_cfi import hltHighLevel
hcalfilter = hltHighLevel.clone(
TriggerResultsTag = cms.InputTag('TriggerResults'),
HLTPaths = cms.vstring('user_step' )
)
hcalfilterSeq = cms.Sequence( hcalfilter )
|
189168 | import os
import logging
import unittest
from pysnptools.util.filecache import Hashdown
import doctest
pysnptools_hashdown = Hashdown.load_hashdown(
os.path.join(
os.path.dirname(os.path.realpath(__file__)), "pysnptools.hashdown.json"
),
directory=os.environ.get("PYSNPTOOLS_CACHE_HOME", None),
)
d... |
189170 | def relax():
neopixel.setAnimation("Color Wipe", 0, 0, 20, 1)
sleep(2)
neopixel.setAnimation("Ironman", 0, 0, 255, 1)
if (i01.eyesTracking.getOpenCV().capturing):
global MoveBodyRandom
MoveBodyRandom=0
global MoveHeadRandom
MoveHeadRandom=0
i01.setHandSpeed("left", 0.85, 0.85, ... |
189190 | import yaml
import torch
import cv2
import json_tricks as json
from torchvision.utils import make_grid
def load_config(path):
with open(path, 'r') as file:
cfg = yaml.load(file)
return cfg
def draw_shape(pos, sigma_x, sigma_y, angle, size):
"""
draw (batched) gaussian with sigma_x, sigma_y ... |
189235 | class Director:
__builder = None
def setBuilder(self, builder):
self.__builder = builder
def getOrden(self):
orden = Orden()
pan = self.__builder.preparaPan()
orden.setPan(pan)
carne = self.__builder.agregaCarne()
orden.setCarne(carne)
verduras = self.... |
189249 | from fastapi import FastAPI
from pydantic import BaseModel, validator
from simsity.service import Service
class Params(BaseModel):
"""Parameters for the query endpoint."""
query: dict
n_neighbors: int = 5
@validator("n_neighbors")
def n_neighbors_must_be_positive(cls, value):
"""Gotta m... |
189267 | import tkinter as tk
from unittest import TestCase
class TkTestCase(TestCase):
"""A test case designed for Tkinter widgets and views"""
keysyms = {
'-': 'minus',
' ': 'space',
':': 'colon',
# For more see http://www.tcl.tk/man/tcl8.4/TkCmd/keysyms.htm
}
@classmethod
... |
189299 | class Solution:
def nthUglyNumber(self, n: int) -> int:
if n < 0: return 0
dp = [1] * n
index2 = index3 = index5 = 0
for i in range(1, n):
dp[i] = min(2 * dp[index2], 3 * dp[index3], 5 * dp[index5])
if dp[i] == 2 * dp[index2]: index2 += 1
if dp[i] ... |
189342 | from .constants import EMPTY_RESULT
class UASMatcher(object):
def __init__(self, data):
self._data = data
def _match_robots(self, useragent, result):
try:
res = self._data['robots'][useragent]
result.update(res['details'])
return True
except KeyErr... |
189374 | import numpy as np
import torch
import torch.nn as nn
import torchvision
from torchvision import transforms
def get_device():
return torch.device("cuda" if torch.cuda.is_available() else "cpu")
def get_mnist_loaders(root, batch_size):
def _get_dataset(train):
return torchvision.datasets.MNIST(
root=ro... |
189402 | from experiments.localization.aachen import AachenLocalizer
class LocalizersFactory(object):
def __init__(self, cfg):
self.cfg = cfg
def get_localizer(self):
localizer = None
loc_name = self.cfg.task.task_params.dataset
if loc_name == 'aachen_v11':
localizer = Aach... |
189407 | from enum import IntEnum
__version__ = "1.4"
class formats(IntEnum):
i, b, blockquote, searchresult, h1, h2, h, pre, code, \
divpadding, divborder = (1 << i for i in range(11))
|
189468 | import cfile as C
import os
import io
import autosar
innerIndentDefault=3 #default indendation (number of spaces)
def _genCommentHeader(comment):
code = C.sequence()
code.append(C.line('/********************************************************************************************************************... |
189514 | from .model import BaseModel
from .tiramisu import DenseUNet, DenseBlock, DenseLayer
from .tiramisu import (
ModuleName,
DEFAULT_MODULE_BANK,
UPSAMPLE2D_NEAREST,
UPSAMPLE2D_PIXELSHUFFLE,
UPSAMPLE2D_TRANPOSE,
)
__all__ = [
"BaseModel",
"DenseUNet",
"DenseBlock",
"DenseLayer",
"Mo... |
189538 | import os
from os.path import isfile, isdir, pardir
from pathlib import Path
from typing import List, Tuple
from node_launcher.constants import NODE_LAUNCHER_RELEASE
from node_launcher.logging import log
from PySide2.QtCore import QFileSystemWatcher, Signal, QObject
from node_launcher.node_set.lib.configuration_prope... |
189562 | from pathlib import Path
def db_synchronous_on(setting: str, db_path: Path) -> str:
if setting == "on":
return "NORMAL"
if setting == "off":
return "OFF"
if setting == "full":
return "FULL"
# for now, default to synchronous=FULL mode. This can be made more
# sophisticated ... |
189622 | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.advanced_construction import SurfaceConvectionAlgorithmInsideUserCurve
log = logging.getLogger(__name__)
class TestSurfaceConvectionAlgorithmInsideUserCurve(unittest.TestCase):
... |
189655 | from chef.base import ChefObject
class Environment(ChefObject):
"""A Chef environment object.
.. versionadded:: 0.2
"""
url = '/environments'
api_version = '0.10'
attributes = {
'description': str,
'cookbook_versions': dict,
'default_attributes': dict,
'o... |
189662 | from Cut import cut
import pytest
@pytest.mark.parametrize('value,delimiter,fields,expected', [
('A-B-C-D-E', '-', '1,5', 'A-E'),
('a,ב,c', ',', '2,3', 'ב,c'),
])
def test_cut(value, delimiter, fields, expected):
"""
Given:
Case 1: A-B-C-D-E to split by - from char 1 to 5
Case 2: a,ב,... |
189679 | import random
from datetime import datetime
import factory
import pytz
from factory.alchemy import SQLAlchemyModelFactory
from factory.faker import Faker
from factory.fuzzy import FuzzyChoice, FuzzyDateTime, FuzzyText
from app.enums import userenums
from app.models import rolemodels, shopmodels, usermodels
from app.s... |
189680 | from cryptography.hazmat.primitives.ciphers.algorithms import AES
from cryptography.hazmat.primitives.ciphers import modes, Cipher
from cryptography.hazmat.backends import default_backend
def xor(x, y):
# assert len(x) == len(y)
a = int.from_bytes(x, "big")
b = int.from_bytes(y, "big")
return (a ^ b).... |
189687 | from rest_framework import authentication
from rest_framework import exceptions
from dataloaderinterface.models import SiteRegistration
class UUIDAuthentication(authentication.BaseAuthentication):
def authenticate(self, request):
if request.META['REQUEST_METHOD'] != 'POST':
return None
... |
189691 | from __future__ import print_function, absolute_import, division #makes KratosMultiphysics backward compatible with python 2.6 and 2.7
# Import kratos core and applications
import KratosMultiphysics
import KratosMultiphysics.SolidMechanicsApplication
import KratosMultiphysics.PfemApplication
import MainSolid
class Pf... |
189698 | from icolos.core.containers.generic import GenericData
import unittest
import os
from icolos.core.containers.gmx_state import GromacsState
from icolos.core.composite_agents.workflow import WorkFlow
from icolos.core.workflow_steps.gromacs.editconf import StepGMXEditConf
from icolos.utils.enums.step_enums import StepBase... |
189718 | import pexpect
def show_version(device, prompt, ip, username, password):
device_prompt = prompt
child = pexpect.spawn('telnet ' + ip)
child.expect('Username:')
child.sendline(username)
child.expect('Password:')
child.sendline(password)
child.expect(device_prompt)
child.sendline('show v... |
189826 | import os
import pandas as pd
from datetime import datetime
from geopy import distance
from libcity.data.dataset.trajectory_encoder.abstract_trajectory_encoder import AbstractTrajectoryEncoder
from libcity.utils import parse_time, parse_coordinate
parameter_list = ['dataset', 'min_session_len', 'min_sessions', 'traj_... |
189833 | import discord
from discord.ext import commands
import json
class GuildEvents(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_ready(self):
print("GuildEvents are ready!")
@commands.Cog.listener()
async def on_guild_join(self, g... |
189854 | from lms.lmstests.sandbox.config import celery as celery_config
from lms.lmstests.sandbox.linters import tasks as flake8_tasks
celery_app = celery_config.app
__all__ = ('flake8_tasks', 'celery_app')
|
189856 | import PCA as pc
import numpy as np
from sklearn.decomposition import PCA
if __name__ == "__main__":
data = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
pca = pc.PCA(n_components=1)
pca.fit(data,rowvar=False)
res = pca.transform(data,rowvar=False)
ratio = pca.variance... |
189861 | import unittest
import os
import binascii
import blocktrail
class ApiClientTestCase(unittest.TestCase):
def setUp(self):
self.cleanup_data = {}
def tearDown(self):
#cleanup any records that were created after each test
client = self.setup_api_client(debug=False)
#webhooks
... |
189874 | import logging
from .object import ObjectStore
from openpathsampling.netcdfplus.cache import LRUChunkLoadingCache
logger = logging.getLogger(__name__)
init_log = logging.getLogger('openpathsampling.initialization')
class ValueStore(ObjectStore):
"""
Store that stores a value by integer index
Usually us... |
189902 | import torch
import torch.nn as nn
import torch.nn.functional as F
import os
import numpy as np
import time
import cv2
from tqdm import tqdm
from model_wrappers.ldf_wrapper import LDF_Wrapper
import logging
def get_mae(img1, img2):
# get mae from two gray scale images
ims = []
for pred in [img1, img2]:
... |
189906 | from django.contrib import admin
from .models import Page
# Register your models here.
admin.site.register(Page) |
189959 | from beanborg.rule_engine.rules import *
class My_Custom_Rule(Rule):
def __init__(self, name, context):
# invoking the __init__ of the parent class
Rule.__init__(self, name, context)
def execute(self, csv_line, tx = None, ruleDef = None ):
self.checkAcco... |
189961 | import argparse
import sys
from loguru import logger
from genomepy import Genome, install_genome
def parse_genome(auto_install=False, genomes_dir=None):
"""
Argparse action for command-line genome option.
Parameters
----------
auto_install : bool, optional
Install a genome if it... |
189966 | import torch
import random
import dataclasses
from collections import OrderedDict
from .utils import format_belief
class NegativeSamplingDatasetWrapper(torch.utils.data.Dataset):
def __init__(self, inner, transform=None):
self.inner = inner
self.transform = transform
assert hasattr(self.in... |
189967 | from marshmallow import fields
from paramtools.schema import (
OrderedSchema,
BaseValidatorSchema,
ValueObject,
get_type,
get_param_schema,
ParamToolsSchema,
)
from paramtools import utils
class SchemaFactory:
"""
Uses data from:
- a schema definition file
- a baseline specifi... |
189990 | from setuptools import setup, find_packages
from codecs import open
import os
import re
with open("README.md", "r") as f:
long_description = f.read()
with open("requirements.txt", "r") as f:
requirements = f.read().splitlines()
setup(
name='utilspack',
version="0.0.1",
author='<NAME>',
autho... |
190013 | import pytest
from django_api_client.client import api_client_factory
from django_api_client.client.exceptions import APINotFound
def test_get_api_name_error():
with pytest.raises(APINotFound) as error:
api_client_factory('CRAZY NAME')
assert str(error.value) == "API name Not Found."
|
190018 | from termcolor import colored
import logging
import time
import os
import json
from pathlib import Path
import shutil
class Logger:
def __init__(self):
self.__logger = logging.getLogger()
Logger.mkdir_if_not_exist('logs')
__file_name = 'logs/' + time.strftime('%Y-%m-%d', time.localtime(tim... |
190019 | import numpy as np
import numba as nb
@nb.jit("(f8[:])(f8[:], f8[:])", nopython=True, nogil=True, cache=True)
def nb_safe_divide(a, b):
# divide each element in a by each element in b
# if element b == 0.0, return element = 0.0
c = np.zeros(a.shape[0], dtype=np.float64)
for i in range(a.shape[0]):
if b[i] != 0.... |
190079 | import discord
from discord.ext import commands
import DiscordUtils
from discord.ext.commands import has_permissions, MissingPermissions
import datetime
class Snipe(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.description = (
" <:sucess:935052640449077248> Commands to sn... |
190084 | from jplephem.names import (
target_name_pairs as code_name_pairs,
target_names as code_names
)
name_codes = dict((name, code) for code, name in code_name_pairs)
def numbered_name_of(code):
"""Given a code, return a string giving both the code and name.
>>> numbered_name_of(301)
'301 Moon'
"... |
190097 | import os
from .settings_dev import *
#########
# Setup #
#########
FIXTURE_DIRS = (
PROJECT_ROOT,
)
#############
# Overrides #
#############
RUN_TASKS_ASYNC = False # avoid sending celery tasks to queue -- just run inline
SUBDOMAIN_URLCONFS = {}
DEBUG = False
TESTING = True
ADMINS = (
("<NAME>", '<E... |
190105 | import numpy
import cv2
def Area(rectangle):
"""
Returns rectangle area.
Args:
rectangle: Rectangle
Returns:
Area
"""
w = rectangle[2] - rectangle[0]
h = rectangle[3] - rectangle[1]
return w * h
def Max(rectangles):
"""
Returns the maximum rectangle.
Args:
... |
190124 | import myssl, select, handleHTTP, socket
import sys, struct, os, random, hashlib, time, threading
import json
import logging
#MAXSYN = 2 ** 15
MAXSYNBUFFER = 64
MAXSYN = 1024
#REMOTE_lines = 4
def filepath(f):
return os.path.join(os.path.split(os.path.realpath(__file__))[0], f)
def random_data(len):
d = ''
... |
190125 | import logging
import subprocess
import glob
import pkgutil
import hashlib
import importlib
from karton.core import Config, Karton, Task, Resource
from typing import Optional
from .__version__ import __version__
log = logging.getLogger(__name__)
def unpacker_module_worker(sample, user_config, module) -> Task:
sp... |
190130 | import os
class Resource:
"""Helper class to facilitate mounting. On assign, Seamless will mount "filename" """
def __init__(self, filename, data=None):
self.filename = filename
if data is None and os.path.exists(filename):
with open(filename) as f:
data = f.read()
... |
190142 | from unittest.mock import patch, Mock
from Crypto.Cipher import AES
from lxml import etree
from federation.protocols.diaspora.encrypted import pkcs7_unpad, EncryptedPayload
from federation.tests.fixtures.keys import get_dummy_private_key
def test_pkcs7_unpad():
assert pkcs7_unpad(b"foobar\x02\x02") == b"foobar"... |
190145 | import unittest
import mock
from reppy import ttl
class TTLPolicyBaseTest(unittest.TestCase):
'''Tests about TTLPolicyBase.'''
def test_does_not_implement_ttl(self):
'''Does not implement the ttl method.'''
with self.assertRaises(NotImplementedError):
ttl.TTLPolicyBase().ttl(obj... |
190181 | from unittest.mock import patch
from bag_transfer.lib.clients import (ArchivesSpaceClient,
ArchivesSpaceClientError)
from django.test import TestCase
class ClientTestCase(TestCase):
@patch("requests.Session.get")
@patch("requests.Session.post")
def test_get_resource... |
190201 | from deepee import __version__, PrivacyWrapper, UniformDataLoader
import torch
import toml
from pathlib import Path
def test_version():
path = Path(__file__).resolve().parents[1] / "pyproject.toml"
pyproject = toml.loads(open(str(path)).read())
assert __version__ == pyproject["tool"]["poetry"]["version"]
... |
190209 | from ..tree_layer import TreeSparseMarginalsFast
import torch
from torch.autograd import gradcheck, Variable
def test_fasttree_sparse_decode():
torch.manual_seed(42)
n_nodes = 5
tsm = TreeSparseMarginalsFast(n_nodes, max_iter=1000)
for _ in range(20):
W = torch.randn(n_nodes, n_nodes + 1).vi... |
190220 | import numpy as np
from sklearn.model_selection import KFold
from sklearn.metrics import f1_score
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
import fasttext
def run_kfold_test(clf, x, y, k=10):
'''
Runs k-Fold test for model benchmarking.
o Inputs:
... |
190249 | from collections import defaultdict
from typing import Dict, List, Optional, Type
from nuplan.common.maps.maps_datatypes import TrafficLightStatusData, TrafficLightStatusType
from nuplan.planning.scenario_builder.abstract_scenario import AbstractScenario
from nuplan.planning.simulation.history.simulation_history_buffe... |
190262 | import starry
import matplotlib.pyplot as plt
import numpy as np
import os
# Settings
lmax = 5
res = 300
# Set up the plot
fig, ax = plt.subplots(lmax + 1, 2 * lmax + 1, figsize=(9, 6))
fig.subplots_adjust(hspace=0)
for axis in ax.flatten():
axis.set_xticks([])
axis.set_yticks([])
axis.spines["top"].set_v... |
190263 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import scipy.linalg
import scipy.special
from . import thops
def nan_throw(tensor, name="tensor"):
stop = False
if ((tensor!=tensor).any()):
print(name + " has nans")
stop = True
if (to... |
190267 | try:
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
except ImportError: # mpl is optional
pass
import numpy as np
from keanu.vartypes import sample_types, numpy_types
from typing import Any, List, Tuple, Union
def traceplot(trace: sample_types, labels: List[Union[str, Tuple[st... |
190272 | from typing import Any, Dict, List, Tuple
from src.db.models.event import Event
from src.db.models.match import Match
from src.db.models.team import Team
from src.db.models.team_event import TeamEvent
from src.db.models.team_match import TeamMatch
from src.db.models.team_year import TeamYear
from src.db.models.year im... |
190276 | import nose
import requests
import fixture
@nose.with_setup(fixture.start_tangelo, fixture.stop_tangelo)
def test_version():
response = requests.get(fixture.plugin_url("tangelo", "version"))
expected = "0.10.0-dev"
assert response.content == expected
|
190288 | import numpy as np
def fUi_VortexSegment11_smooth(xa = None,ya = None,za = None,xb = None,yb = None,zb = None,visc_model = None,t = None,bComputeGrad = None):
# !!!!! No intensity!!!
norm_a = np.sqrt(xa * xa + ya * ya + za * za)
norm_b = np.sqrt(xb * xb + yb * yb + zb * zb)
denominator = norm_a * ... |
190299 | import glob
from abc import ABC, abstractmethod
from contextlib import ExitStack, contextmanager
from dataclasses import dataclass
from functools import reduce
from logging import getLogger
from pathlib import Path
from sys import stderr
from tempfile import TemporaryDirectory
from typing import Iterator, List, Optiona... |
190311 | from user_accounts import exceptions
from intake.tests.base_testcases import IntakeDataTestCase
class TestUserProfile(IntakeDataTestCase):
fixtures = [
'counties', 'groups',
'organizations', 'mock_profiles',
'mock_2_submissions_to_cc_pubdef',
'mock_2_submissions_to_sf_pubdef',
... |
190389 | import pandas as pd
import tushare as ts
from StockAnalysisSystem.core.config import TS_TOKEN
from StockAnalysisSystem.core.Utility.common import *
from StockAnalysisSystem.core.Utility.time_utility import *
from StockAnalysisSystem.core.Utility.CollectorUtility import *
# -------------------------------------------... |
190393 | import os
import time
from collections import deque
import torch
import torch.distributions
import torch.nn as nn
from torch.optim.lr_scheduler import LambdaLR
from common.util import scale_ob, Trajectories
def learn(logger,
device,
env, nenv,
number_timesteps,
network, optim... |
190396 | import os
from hashlib import sha256
import importlib
import json
import logging
import textwrap
from uuid import uuid4
from pathlib import Path
from pkg_resources import resource_filename
from tempfile import NamedTemporaryFile
from docutils import nodes
from docutils.parsers.rst import Directive
from docutils.parser... |
190401 | from itertools import count
from typing import Iterable, Dict, List
class IndexMapper:
"""
This class maps between the different atoms objects in a MAZE-sim project.
It is essential for keeping track of the various
"""
id = 0
@staticmethod
def get_id():
"""
Get a unique i... |
190411 | from threading import Thread
import queue
from . import packet_util
from .message_consumer import MessageConsumer
import logging
class MessageWorker(Thread):
def __init__(self, socket, room_id):
Thread.__init__(self)
self.need_stop = False
self.socket = socket
self.room_id = room_i... |
190424 | import unittest
from unittest.mock import patch
from simple_dwd_weatherforecast import dwdforecast
from tests.dummy_data import parsed_data
from datetime import datetime, timezone
import time
class WeatherUpdate(unittest.TestCase):
def setUp(self):
self.dwd_weather = dwdforecast.Weather("H889")
se... |
190439 | import json
import numpy as np
import os
import pickle
from azureml.core.model import Model
def wind_turbine_model(x):
# cut-in speed vs cut-out speed
if x<4.5 or x>21.5:
return 0.0
# standard operability
return 376.936 - 195.8161*x + 33.75734*x**2 - 2.212492*x**3 + 0.06309095*x**4 - 0.000... |
190460 | import os
from cfdata.tabular import *
from cfml import *
# datasets
boston = TabularDataset.boston()
prices_file = os.path.join("datasets", "prices.txt")
prices = TabularData(task_type=TaskTypes.REGRESSION).read(prices_file).to_dataset()
breast_cancer = TabularDataset.breast_cancer()
digits = TabularDataset.digits(... |
190473 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
__version__ = "0.1.0"
__author__ = "<NAME>"
from flask import flash
from flask import Flask
from flask import render_template
from flask import request
from keras.models import load_model
import os
import nump... |
190506 | import json
import pytchat
from pytchat.parser.live import Parser
from pytchat.processors.speed.calculator import SpeedCalculator
parser = Parser(is_replay=False)
def test_speed_1():
stream = pytchat.create("Hj-wnLIYKjw", seektime = 6000,processor=SpeedCalculator())
while stream.is_alive():
speed = s... |
190522 | import torch
import torch.nn as nn
from modelzoo.normalisers import NormalisedSigmoid
from modelzoo.redistributions import Gate
from modelzoo.redistributions import get_redistribution
class MCModel(nn.Module):
def __init__(self, cfg: dict):
super().__init__()
self.mclstm = MCLSTMv2(cfg['mass_inp... |
190539 | import numpy as np
from tree.DecisionTreeClassifier import DecisionTreeClassifier
from scipy import stats # 用于求众数
class RandomForestClassifier:
def __init__(self, n_estimators: int = 5, min_samples_split: int = 5,
min_samples_leaf: int = 5, min_impurity_decrease: float = 0.0):
'''
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.