id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3244722 | import unittest
import dvach
import filecompare
import os
class TestAnalytics(unittest.TestCase):
def read_file(self, file_name) -> str:
"""Прочитать файл в директории test_files/
В директории `test_files/` собраны файлы которые используются для тестирования
Args:
file_name ... |
3244761 | from scrapy import Spider
from scrapy.http import Request
from firmware.items import FirmwareImage
from firmware.loader import FirmwareLoader
import json
import urlparse
class UbiquitiSpider(Spider):
name = "ubiquiti"
allowed_domains = ["ubnt.com"]
start_urls = ["http://www.ubnt.com/download/"]
def... |
3244767 | from rest_framework import serializers
import ethereum.lib
from reputation.models import Withdrawal, Contribution
from researchhub.serializers import DynamicModelFieldSerializer
from user.serializers import UserSerializer, DynamicUserSerializer
from summary.serializers import SummarySerializer, SummaryVoteSerializer
... |
3244841 | from cffi import FFI
def link_clib(block_cell_name):
ffi = FFI()
ffi.cdef(r'''
/* --- primary CSparse routines and data structures ------------------------- */
typedef struct cs_sparse /* matrix in compressed-column or triplet form */
{
ptrdiff_t nzmax ; /* maximum number of entries */
ptrdiff_t ... |
3244857 | import discord
import asyncio
import difflib
from redbot.core import Config
from redbot.core import commands
from redbot.core import checks
from redbot.core.utils.predicates import MessagePredicate
from redbot.core.utils.predicates import ReactionPredicate
from redbot.core.utils.menus import start_adding_reactions
de... |
3244904 | from django.apps import AppConfig
class WorkGroupsAppConfig(AppConfig):
name = 'work_groups'
|
3244909 | from typing import Callable
import torch
from torch import nn
from torch.optim import Optimizer
from torch.optim.lr_scheduler import _LRScheduler
from tqdm import tqdm
from ..chemprop.data import MoleculeDataLoader
from ..chemprop.nn_utils import compute_gnorm, compute_pnorm, NoamLR
def train(model: nn.Module, data_... |
3244918 | from Qt import QtGui,QtCore,QtWidgets
from PyFlow.UI.Canvas.UICommon import *
from PyFlow.Packages.PyFlowOpenCv.UI.UIOpenCvBaseNode import UIOpenCvBaseNode
import os
import math
class TransformItem(QtWidgets.QGraphicsWidget):
"""docstring for TransformItem"""
_MANIP_MODE_NONE = 0
_MANIP_MODE_MOVE = 1
_M... |
3244919 | import random
import sys
import unittest
SettingsManagerModule = sys.modules["SpotifyWeb.src.spotify.SettingsManager"]
SettingsManager = SettingsManagerModule.SettingsManager
class TestSettingsManager(unittest.TestCase):
def test_redirect_port_should_default_to_8080_if_load_settings_raises_an_exception(self):
... |
3244942 | import sqlite3
from typing import List, Optional
class WikiMapper:
""" Uses a precomputed database created by `create_wikipedia_wikidata_mapping_db`. """
def __init__(self, path_to_db: str):
self._path_to_db = path_to_db
def title_to_id(self, page_title: str) -> Optional[str]:
""" Given ... |
3244952 | import mmcv
from mmcls.models import build_classifier
from mmcv.runner import load_checkpoint
from argparse import ArgumentParser
import torch
import kaldiio
import os
import numpy as np
parser = ArgumentParser("feach_fc")
parser.add_argument("--ckpt", type=str, required=True)
parser.add_argument("--targe... |
3244955 | import asyncio
from aiocouch import CouchDB
async def main_with() -> None:
async with CouchDB(
"http://localhost:5984", user="admin", password="<PASSWORD>"
) as couchdb:
db = await couchdb["recipes"]
doc = await db["apple_pie"]
print(doc["incredients"])
new_doc = awai... |
3245036 | import numpy as np
import libs.configs.config_v1 as cfg
from PIL import Image, ImageFont, ImageDraw, ImageEnhance
from scipy.misc import imresize
FLAGS = cfg.FLAGS
_DEBUG = False
def draw_img(step, image, name='', image_height=1, image_width=1, rois=None):
img = np.uint8(image/0.1*127.0 + 127.0)
img = Image.f... |
3245062 | from __future__ import annotations
from datetime import date, datetime
from enum import Enum
from typing import List, Optional
from pydantic import BaseModel, Field, conint
from . import model_s
class Pet(Enum):
ca_t = 'ca-t'
dog_ = 'dog*'
class Error(BaseModel):
code: int
message: str
class Ho... |
3245069 | import re,os
import xml.etree.ElementTree as ET
from .Webby import Webby
from .Common import *
class Harvester(object):
def __init__(self,verbosity):
self.webbies = set()
self.verbosity = verbosity
def harvest_nessus_dir(self,nessus_dir):
for dirpath,directories,files in os.walk(nessus... |
3245070 | from __future__ import unicode_literals, division, print_function, absolute_import
from builtins import object
from collections import defaultdict
from copy import deepcopy
import numpy as np
from scipy.sparse import csr_matrix, lil_matrix
class ContextModel(object):
def __init__(self, sentences, min_count=5, wi... |
3245102 | from setuptools import setup, find_packages
from m2r import parse_from_file
from os import path
import bolt.about as about
readme_file = path.join(path.dirname(path.abspath(__file__)), 'README.md')
readme = parse_from_file(readme_file)
packages = find_packages()
entry_points = {
'console_scripts': [
'bolt... |
3245103 | import sys
from typing import List, Tuple
import re
import numpy as np
from abnumber.exceptions import ChainParseError
try:
from anarci.anarci import anarci
except ImportError:
# Only print the error without failing - required to import
print('ANARCI module not available. Please install it separately or ins... |
3245107 | from functools import partial
from typing import Callable, Sequence, Union
from warnings import warn
import torch
import torch.nn as nn
from torch.nn import functional
import numpy as np
from dpipe.itertools import zip_equal, lmap
from dpipe.im.utils import identity
from dpipe.torch.utils import order_to_mode
from .s... |
3245123 | import byt2str
import unittest
from test import support
class ConvertTest(unittest.TestCase):
def test_min(self):
# Check that the "convert" min range is correct.
self.assertEqual(byt2str.convert(1), '1 Byte')
with self.assertRaises(AssertionError):
byt2str.convert(0)
def ... |
3245138 | from testcontainers.core.generic import DbContainer
class OracleDbContainer(DbContainer):
"""
Oracle database container.
Example
-------
::
with OracleDbContainer():
e = sqlalchemy.create_engine(oracle.get_connection_url())
result = e.execute("select 1 from dual")... |
3245150 | import numpy as np
from typing import Union
import anndata
from .scatters import (
scatters,
docstrings,
)
from ..tl import compute_smallest_distance
from ..dynamo_logger import main_critical, main_info, main_finish_progress, main_log_time, main_warning
docstrings.delete_params("scatters.parameters", "adata",... |
3245161 | import pyqtgraph as pg
import datetime
class DateAxis(pg.AxisItem):
"""
This class takes in tplot time variables and creates ticks/tick labels
depending on the time length of the data.
"""
def tickStrings(self, values, scale, spacing):
strns = []
if not values:
... |
3245187 | import unittest
import numpy as np
import sys
import vigra
import luigi
import z5py
try:
from ..base import BaseTest
except ValueError:
sys.path.append('..')
from base import BaseTest
class TestRelabel(BaseTest):
input_key = 'volumes/segmentation/watershed'
output_key = 'data'
assignment_key... |
3245212 | from build.management.commands.build_ligands_from_cache import Command as BuildLigandsFromCache
class Command(BuildLigandsFromCache):
pass |
3245222 | from .policylearner import PolicyLearner
from .unit_selection import CounterfactualUnitSelector
from .utils import get_treatment_costs, get_actual_value, get_uplift_best
from .value_optimization import CounterfactualValueEstimator
|
3245225 | from test import TCBase
from test.request import NoticeRequest
class TestGetNotice(TCBase, NoticeRequest):
# @check_status_code(201)
# def test_post_stay_successful(self):
# rv: Response = self.request_stay_post(self.access_token, 1)
# status = StayApplyModel.get_stay_apply_status('test')
... |
3245284 | import FWCore.ParameterSet.Config as cms
from IOMC.EventVertexGenerators.VtxSmearedParameters_cfi import FlatVtxSmearingParameters,VtxSmearedCommon
VtxSmeared = cms.EDProducer("FlatEvtVtxGenerator",
FlatVtxSmearingParameters,
VtxSmearedCommon
)
|
3245353 | import numpy as np
import itertools
import raam
import pickle
from raam import features
from scipy import cluster
from warnings import warn
def degradation(fun,charge,discharge):
"""
Constructs a capacity degradation function from given parameters.
The functions are D- and D+: the anti-derivatives. Se... |
3245370 | class Solution:
def findJudge(self, N: int, trust: List[List[int]]) -> int:
if N==1:
return 1
d1={}
d2={}
for i, j in trust:
if j in d1:
d1[j]+=1
else:
d1[j]=1
if i in d2:
d2[i]+=1
... |
3245373 | import numpy as np
from sklearn import metrics
def auc(t, p, **kwargs):
# y_pred.shape = (N,)
if p.ndim == 2 and t.ndim == 2:
p = p[:,0]
t = t[:,0]
return {'auc': metrics.roc_auc_score(t, p)}
def multi_auc(t, p, **kwargs):
# y_pred.shape = (N,C)
metrics_dict = {}
for i in ra... |
3245388 | import random
random.seed('hyperion') # ensure that random numbers are the same every time
import numpy as np
from hyperion.model import Model
from hyperion.util.constants import pc, lsun
# Define cell walls
x = np.linspace(-10., 10., 101) * pc
y = np.linspace(-10., 10., 101) * pc
z = np.linspace(-10., 10., 101) * p... |
3245409 | import re
import string
from nltk.tokenize import word_tokenize
from nltk.stem.porter import PorterStemmer
from nltk.corpus import stopwords
import itertools
from nltk.collocations import BigramCollocationFinder
from nltk.metrics import BigramAssocMeasures
class FeatureFinder:
def __init__(self):
self.featureVec... |
3245410 | import redis
import json
from simplekiq import KiqQueue
from simplekiq import EventBuilder
from simplekiq import Worker
from config import Config
import crud
import models
import database
def get_db():
return database.Session()
class MyEventWorker(Worker):
def __init__(self, queue, failed_queue):
s... |
3245440 | import tak.symmetry
import tak.ptn
W = tak.Piece(tak.Color.WHITE, tak.Kind.FLAT)
WC = tak.Piece(tak.Color.WHITE, tak.Kind.CAPSTONE)
WS = tak.Piece(tak.Color.WHITE, tak.Kind.STANDING)
B = tak.Piece(tak.Color.BLACK, tak.Kind.FLAT)
BC = tak.Piece(tak.Color.BLACK, tak.Kind.CAPSTONE)
BS = tak.Piece(tak.Color.BLACK, tak.... |
3245482 | from cmlkit.engine import Data, load_data, Component
import cmlkit
import numpy as np
from unittest import TestCase
import unittest.mock
import shutil
import pathlib
class DataExample(Data):
kind = "test_data"
class DataExampleComponent(Component):
kind = "test_data_component"
def __init__(self, a, ... |
3245526 | import sys
from .utils.run import main
if __name__ == "__main__":
# Check major and minor python version
if sys.version_info[0] < 3:
sys.stdout.write(
"\n/!\\ h8mail requires Python 3.6+ /!\\\nTry running h8mail with python3 if on older systems\n\neg: python --version\neg: python3 h8mail v ... |
3245595 | import os
import unittest
from typing import List, Tuple
import pkg_resources
import yaml
PRE_COMMIT_CONFIG_FILE = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "..", ".pre-commit-config.yaml"
)
REQUIREMENTS_DEV_FILE = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "..", "requirements... |
3245601 | import FWCore.ParameterSet.Config as cms
# Intentionally reversing the order of process names in this series
process = cms.Process("PROD1")
process.options = cms.untracked.PSet(
numberOfStreams = cms.untracked.uint32(1),
numberOfConcurrentRuns = cms.untracked.uint32(1),
numberOfConcurrentLuminosityBlocks ... |
3245604 | from os import path, chdir, getcwd
import numpy as np
class NumDiffException(Exception):
""" Raised when the difference bewtween the 2 Matrices is too high """
pass
def assert_all_close(A, B, threshold):
""" Assert analytical derivatives against NumDiff using the error norm.
:param A: Matrix A
... |
3245627 | from django.db import transaction
from django.db.models import F
from jet_django.deps.rest_framework import serializers, relations
def reorder_serializer_factory(build_queryset):
class ReorderSerializer(serializers.Serializer):
ordering_field = serializers.CharField()
forward = serializers.Boolean... |
3245630 | import json
from adapters.base_adapter import Adapter
from devices.switch.on_off_switch import OnOffSwitch
class TS0012(Adapter):
def __init__(self):
super().__init__()
self.devices.append(OnOffSwitch('left', 'state_left'))
self.devices.append(OnOffSwitch('right', 'state_right'))
def... |
3245647 | from tensorflow.keras.layers import Input, Dense, Dropout, Activation, Concatenate, BatchNormalization
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Conv2D, GlobalAveragePooling2D, AveragePooling2D
from tensorflow.keras.regularizers import l2
def DenseNet(input_shape=None, dens... |
3245683 | import sys
from unittest import expectedFailure
from ..utils import TranspileTestCase
class SysModuleTests(TranspileTestCase):
############################################################
# __displayhook__
@expectedFailure
def test___displayhook__(self):
self.assertCodeExecution("""
... |
3245698 | from Entity.attack_suite import AttackSuite
from coap_payload_size_fuzzer import *
from coap_random_payload_fuzzing import *
import multiprocessing
import unittest
class CoAPFuzzingAttackSuite(AttackSuite):
def __init__(self):
attacks = [CoAPRandomPayloadFuzzingAttack(), CoAPPayloadSizeFuzzerAttack()]
... |
3245702 | from datetime import date, time
import pandas as pd
from visions.backends.pandas.series_utils import (
class_name_attrs,
series_handle_nulls,
series_not_empty,
)
from visions.types.date import Date
from visions.types.date_time import DateTime
@Date.register_relationship(DateTime, pd.Series)
@series_hand... |
3245735 | from scripts.usefullFunctions import *
import ssp.models as t
import json
import os
import shutil
import sys
added_nist_controls = 0
updated_nist_controls = 0
control_baseline = t.control_baseline
def break_up_catalog(file_path, file_name):
"""
Takes an OSCAL Catalog file and breaks it into seperate json file... |
3245741 | import time
import datetime
class Ticket():
def __init__(self):
self.today = datetime.date.today().strftime("%Y-%m-%d")
def getNewCoupon(self,oldData,newData): #用這個key去送出newDict裡面的新折價卷
newKeys = []
for data in newData.keys():
if data not in oldData:
newKeys.... |
3245778 | from enum import Enum, auto
class EUnrealEngineObjectLicenseeUE4Version(Enum):
VER_LIC_NONE = 0
VER_LIC_AUTOMATIC_VERSION_PLUS_ONE = auto()
VER_LIC_AUTOMATIC_VERSION = VER_LIC_AUTOMATIC_VERSION_PLUS_ONE - 1
|
3245824 | import os
import traceback
import re
import sys
import json
import sqlite3
import random
from os import listdir, makedirs
from collections import OrderedDict
from nltk import word_tokenize, tokenize
from os.path import isfile, isdir, join, split, exists, splitext
from ..process_sql import get_sql
from .schema import S... |
3245833 | class SwiggyCliQuitError(Exception):
pass
class SwiggyCliAuthError(Exception):
pass
class SwiggyCliConfigError(Exception):
pass
class SwiggyAPIError(Exception):
pass
class SwiggyDBError(Exception):
pass
|
3245887 | import re
import sys
def patch(tag):
print(f"Patching version: {tag}")
with open("pyproject.toml", "r") as f:
lines = f.readlines()
if "version" not in lines[2]:
raise Exception(f"Invalid pyproject.toml. Could not patch version.")
lines[2] = f'version = "{tag}"\n'
... |
3245915 | import os
from tqdm import tqdm
from torchvision import utils
from renderer.face_model import FaceModel
from options.options import Options
from utils.util import create_dir, load_coef
if __name__ == '__main__':
opt = Options().parse_args()
create_dir(os.path.join(opt.src_dir, 'reenact'))
alpha_list = ... |
3245928 | import unittest
from io import StringIO
from collections import namedtuple
import pandas as pd
from pandas.testing import assert_frame_equal, assert_series_equal
import xlsxwriter
import gptables
from gptables.core.wrappers import GPWorkbook
from gptables.core.wrappers import GPWorksheet
from gptables import Theme
fr... |
3245940 | lst = [3, 6, 2, 1, 0]
lst2 = [1, 2]
print map(bool, lst)
def outer():
def inner(item):
return 2 * item
print map(inner, lst)
outer()
print map(None, lst, lst2)
#filter with builtin functions
print filter(bool, [0,1,"",False,42,[1]])
#reduce with global variables
adder = 100
def add(x, y):
ret... |
3245944 | import os
from pathlib import Path
import pytest
from s3fetch import __version__
from s3fetch.command import S3Fetch
from s3fetch.exceptions import DirectoryDoesNotExistError, NoObjectsFoundError
@pytest.fixture(scope="function")
def aws_credentials():
"""Mocked AWS Credentials for moto."""
os.environ["AWS_A... |
3245980 | import o3seespy as o3 # for testing only
import pytest
def test_elastic_beam_column2d():
osi = o3.OpenSeesInstance(ndm=2)
coords = [[0, 0], [1, 0]]
ele_nodes = [o3.node.Node(osi, *coords[x]) for x in range(2)]
transf = o3.geom_transf.Linear2D(osi, [])
o3.element.ElasticBeamColumn2D(osi, ele_nodes... |
3246032 | import os
if not os.path.exists('data'):
os.mkdir('data')
if not os.path.exists('data/raw'):
os.mkdir('data/raw')
print('Installing requirements...')
os.system('pip install --no-deps gutenberg')
os.system('pip install -r requirements.txt')
|
3246041 | import copy
import warnings
from collections import OrderedDict
from typing import List, Union
import numpy as np
import torch
__all__ = [
"normalize_image",
"channels_first",
"scale_intrinsics",
"pointquaternion_to_homogeneous",
"poses_to_transforms",
"create_label_image",
]
def normalize_i... |
3246064 | import json
from types import SimpleNamespace
import relogic.utils.crash_on_ipy
from relogic.logickit.base.constants import DOCIR_TASK
from relogic.logickit.dataflow import TASK_TO_DATAFLOW_CLASS_MAP, DocPointwiseDataFlow
from relogic.logickit.tokenizer.tokenization import BertTokenizer
config = SimpleNamespace(
**... |
3246079 | from __future__ import absolute_import
import logging
import requests
import snooze.constants as constants
def clear_snooze_label_if_set(github_auth, issue, snooze_label):
issue_labels = {label["name"] for label in issue.get("labels", [])}
if snooze_label not in issue_labels:
logging.debug(
... |
3246146 | import os
import cv2
from . import find_tools as ft
def find_right_lung_lbp(image):
right_lung = cv2.CascadeClassifier(os.path.dirname(__file__) + os.sep + "right_lung_lbp.xml")
found = right_lung.detectMultiScale(image, 1.8, 5)
right_lung_rectangle = ft.find_max_rectangle(found)
return right_lung_re... |
3246184 | from django.test import TestCase
from django.urls import reverse
from django.contrib.auth import get_user_model
from on_demand.models import SupplierProfile, UserDetails
from on_demand.serializers import SupplierProfileSerializer
import json
class FindSupplierTest(TestCase):
def test_find_suppliers_url_exists_at_de... |
3246227 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import TransformerEncoder, TransformerEncoderLayer
class UGformerV1(nn.Module):
def __init__(self, feature_dim_size, ff_hidden_size, num_classes,
num_self_att_layers, dropout, num_GNN_layers):
sup... |
3246249 | import os
import sys
import subprocess
def main():
set_size = 35
chunk_sizes = [10, 14, 17, 20, 24, 26, 27, 28, 29, 30]
max_num = 10000
null = open(os.devnull, 'w')
for chunk_size in chunk_sizes:
dirname = 'data/%d' % chunk_size
if not os.path.exists(dirname):
os.makedi... |
3246257 | N = [
[1.536719390948438],
[1.570254485250484],
[1.560258218586837],
[1.556135060859314],
[1.555005035001635],
[1.554716411629528],
]
grau = 6
b = 2
for i in range(grau - 1):
for j in range(grau - i - 1):
N[j].append(
((2 ** (i * b + b) * N[j + 1][i]) - N[j][i]) / (2 **... |
3246260 | from transformers_sklearn import BERTologyNERClassifer
def get_X_y(input_file):
X = []
y = []
tag = input_file.split('/')[-2]
with open(input_file, 'r') as reader:
for doc in reader.read().split('\n\n'):
X_ = []
y_ = []
for line in doc.split('\n'):
... |
3246274 | from __future__ import print_function
import PyTorch
from test.test_helpers import myeval, myexec
def test_float_tensor():
PyTorch.manualSeed(123)
print('dir(G)', dir())
print('test_float_tensor')
a = PyTorch.FloatTensor(3, 2)
print('got float a')
myeval('a.dims()')
a.uniform()
myeval(... |
3246359 | import torch
import torch.nn as nn
import torch.nn.functional as F
class hsigmoid(nn.Module):
def forward(self, x):
out = F.relu6(x + 3, inplace=True) / 6
return out
class AttentionWeights(nn.Module):
def __init__(self, num_channels, k, attention_mode=0):
super(AttentionWeights, self... |
3246381 | class Solution:
def isMatch(self, s: str, p: str) -> bool:
sn, pn = len(s), len(p)
si = pi = 0
save_si, save_pi = None, None
while si < sn:
if pi < pn and (p[pi] == '?' or p[pi] == s[si]):
si += 1
pi += 1
elif pi < pn and p[pi] ... |
3246417 | import os
import matplotlib.pyplot as plt
import numpy as np
#check_file='without_gps_log.log'
def get_position_by_lines(line):
if line.find('position')>=0:
print line
return map(float,line.split()[-1].split(',')[-4:])
return None
def get_checkfile(check_file_name):
return open(check_file_... |
3246419 | import os
import shutil
import stat
import time
import shlex
from subprocess import Popen, check_output, PIPE, CalledProcessError
from threading import Timer
from ...utils.security import switch_to_site_user
from .models import Site
from ..users.models import User, Group
from django.conf import settings
from django.... |
3246431 | input_strings = ['1', '5', '28', '131', '3']
output_integers = [int(n) for n in input_strings if len(n) < 3]
|
3246437 | from ..factory import Type
class inputPassportElementErrorSourceDataField(Type):
field_name = None # type: "string"
data_hash = None # type: "bytes"
|
3246493 | from unittest import TestCase
import os
import numpy as np
from phi.data.fluidformat import Scene
from phi.data.dataset import Dataset
from phi.data.stream import SOURCE, FRAME, SCENE
from phi.data.reader import BatchReader, SourceStream
def build_test_database(path='data'):
for scene in Scene.list(path):
... |
3246608 | from typing import TYPE_CHECKING
if TYPE_CHECKING:
from timeatlas.time_series import TimeSeries
class Scaler:
@staticmethod
def minmax(ts: 'TimeSeries') -> 'TimeSeries':
r"""Scale a TimeSeries within a [0,1] range (so called min max)
.. math::
x_{scaled} = \frac{x - x_{min}}... |
3246663 | import app.helpers.producer
import tests.fixtures.messages as message_fx
class TestMessages:
_messages = []
def fake_send(self, messages):
self._messages.append(messages)
def test_messages(self, client, monkeypatch, mocker):
"""Test if the command sent to broker created appropriately.
... |
3246686 | from globalconst import KING
class Operator(object):
pass
class OneKingAttackOneKing(Operator):
def precondition(self, board):
plr_color = board.to_move
opp_color = board.enemy
return (board.count(plr_color) == 1 and board.count(opp_color) == 1 and
any((x & KING for x... |
3246743 | from rest_framework import serializers
from shared.serializer import OfficerYearlyPercentileSerializer
class OfficerSerializer(serializers.Serializer):
id = serializers.IntegerField()
allegation_count = serializers.IntegerField()
full_name = serializers.CharField()
percentiles = OfficerYearlyPercenti... |
3246760 | from vit.formatter.until import Until
class UntilEpoch(Until):
def format_datetime(self, until, task):
return self.epoch(until)
|
3246771 | import model_utils
import corpus_utils
import sence2vec_utils
import operator
import utils
import config as cfg
# Run configs can be changed in the config.py file.
# each experiment will create a log file named by the seed items.
# if you don't want to evaluate (or don't have the full set) simply comment out the utils... |
3246802 | import os, math, ctypes
import numpy as np
from OpenGL import GL
from art import VERT_LENGTH
from palette import MAX_COLORS
# inactive layer alphas
LAYER_VIS_FULL = 1
LAYER_VIS_DIM = 0.25
LAYER_VIS_NONE = 0
class TileRenderable:
"""
3D visual representation of an Art. Each layer is rendered as grids of
r... |
3246805 | def get_students_with_grade(students, grade):
return list(filter(lambda student: student[1] == grade, students))
def get_second_lowest_grade(students):
unique_grades = set(map(get_grade, students))
ascending_grades = sorted(unique_grades)
return ascending_grades[1] # return second lowest grade
def ... |
3246807 | from globals import *
import life as lfe
import judgement
import survival
import chunks
import sight
import brain
import smp
import logging
def tick(life):
if not lfe.execute_raw(life, 'discover', 'discover_type'):
_lost_method = lfe.execute_raw(life, 'discover', 'when_lost')
if _lost_method:
if not life['p... |
3246820 | import os
import sys
import shutil
from subprocess import call
from annogesiclib.multiparser import Multiparser
from annogesiclib.helper import Helper
from annogesiclib.TSS_upstream import upstream, del_repeat_fasta
from annogesiclib.gen_promoter_table import gen_promoter_table
class MEME(object):
'''detection of... |
3246827 | r"""Solve Navier-Stokes equations for the lid driven cavity using a coupled
formulation
The equations are in strong form
.. math::
\nu\nabla^2 u - \nabla p &= (u \cdot \nabla) u) \\
\nabla \cdot u &= 0 \\
i\bs{u}(x, y=1) = (1, 0) \, &\text{ or }\, \bs{u}(x, y=1) = ((1-x)^2(1+x)^2, 0) \\
u(x, y=-1) &=... |
3246853 | import json
import os
from citeomatic.config import App
from citeomatic.models.options import ModelOptions
from citeomatic.traits import Unicode, Enum
import copy
class GenerateOcConfigs(App):
dataset_type = Enum(('dblp', 'pubmed', 'oc'), default_value='pubmed')
input_config_file = Unicode(default_value=No... |
3246865 | from . import register
from .util import TInferiorRefList
from ..runtimeobjects import Statement
@register(13)
def cmd_block(table, id, size):
t = table.loader.read_u8()
type_info, bytecode_start, bytecode_end = [table.loader.read_u16() for i in range(3)]
refloader = TInferiorRefList(size + 3, ... |
3246874 | import logging
from swiftclient.service import SwiftService, SwiftError
from sys import argv
logging.basicConfig(level=logging.ERROR)
logging.getLogger("requests").setLevel(logging.CRITICAL)
logging.getLogger("swiftclient").setLevel(logging.CRITICAL)
logger = logging.getLogger(__name__)
def is_png(obj):
return (... |
3246889 | input = """
a(1) v a(2).
b(1) v b(2).
okay :- not #count{X:a(X),b(X)}>1, #count{V:a(V),b(V)}>0.
"""
output = """
{a(1), b(1), okay}
{a(1), b(2)}
{a(2), b(1)}
{a(2), b(2), okay}
"""
|
3246890 | from torch.optim.lr_scheduler import _LRScheduler
from colossalai.registry import LR_SCHEDULERS
from .delayed import WarmupScheduler
@LR_SCHEDULERS.register_module
class PolynomialLR(_LRScheduler):
"""Polynomial learning rate scheduler.
Args:
optimizer (:class:`torch.optim.Optimizer`): Wrapped optim... |
3246920 | import os
import pandas as pd
import sqlite3
db_path = "m:\Documents\@Projects\Covid_consolidate\output_pivot"
list_of_files = os.listdir(db_path)
db_files = [ os.path.join(db_path,each) for each in list_of_files]
ID_COLS = ["chain", "run", "scenario", "times"]
for each in db_files:
conn = sqlite3.connect... |
3246922 | from __future__ import print_function
import random
import math
import numpy as np
import torch
import torchnet as tnt
class FewShotDataloader:
def __init__(
self,
dataset,
nKnovel=5,
nKbase=-1,
nExemplars=1,
nTestNovel=15*5,
nTestBase=15*5,
batch_... |
3246990 | import test_common
import spartan
from spartan.examples.sklearn.cluster import KMeans
from spartan import expr
from spartan.util import divup
from spartan.config import FLAGS
from datetime import datetime
from test_common import millis
N_PTS = 10*10
N_CENTERS = 10
N_DIM = 5
ITER = 5
class TestKmeans(test_common.Clust... |
3247007 | from distutils.command.build_ext import build_ext
from distutils import sysconfig
#from distutils.core import setup
from setuptools import setup, Extension
import os, sys
from os import chdir, getcwd
from os.path import abspath, dirname, split
import shlex, glob
from subprocess import check_output
import re
import ar... |
3247021 | from dash import html
from dash import dcc
import plotly.graph_objects as go
from dash.dependencies import Input, Output
from ...callbacks.util.helpers import privacy_check, privacy_notice, get_postal_code
colors = [
'#4182C8', '#2E94B2',
'#39A791', '#6FB26C',
'#C0C15C', '#F9BD24',
'#F3903F', '#EC6546... |
3247049 | from typing import List, NamedTuple
from .raw_sample import RawSample, RawContextualFeatures, RawCompFeatures
from enum import Enum
import numpy as np
def encode_enum(enum_feature: Enum) -> List[float]:
res = [0.0]*len(type(enum_feature))
res[enum_feature.value] = 1.0
return res
def encode_number(featu... |
3247064 | import argparse
from datetime import datetime
import numpy as np
import random
import tensorflow as tf
import socket
import os
import sys
import h5py
import struct
BASE_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(BASE_DIR) # model
sys.path.append(os.path.join(BASE_DIR... |
3247071 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
import random
class ReplayBuffer:
def __init__(self, capacity):
self.capacity = capacity # 经验回放的容量
self.buffer = [] # 缓冲区
self.position = 0
... |
3247081 | import autograd.numpy as anp
from pymoo.model.problem import Problem
class MyProblem(Problem):
def __init__(self):
super().__init__(n_var=2,
n_obj=2,
n_constr=2,
xl=anp.array([-2, -2]),
xu=anp.array([2, 2]... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.