id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3380628 | import unittest
import numpy as np
import pandas as pd
import unittest
from numpy import testing as nptest
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import KFold
import sys
from operational_analysis.toolkits.machine_learning_setup import MachineLearningSetup
class TestMLToolkit(unitt... |
3380664 | import random
import os
import sys
import numpy as np
import subprocess as sub
from functools import partial
from base import Sim, Env, ObjectiveDict
from networks import CPPN, DirectEncoding
from softbot import Genotype, Phenotype, Population
from tools.algorithms import ParetoOptimization
from tools.checkpointing im... |
3380722 | import unittest
import mock
from kazoo.client import KazooState
from paasta_tools.deployd.leader import PaastaLeaderElection
class TestPaastaLeaderElection(unittest.TestCase):
def setUp(self):
with mock.patch(
"paasta_tools.deployd.leader.Election.__init__", autospec=False
):
... |
3380776 | import enum
from typing import Tuple, List, Dict, Optional
from collections import namedtuple
# We split the information about a metric into two parts: the MetricMetadata
# and MetricRecord. Metadata is declared at creation time and include names
# and the label names. The label values will be supplied at observation ... |
3380808 | import os, argparse
from scipy.io import wavfile
import numpy as np
from scipy.ndimage.filters import gaussian_filter
import SyncNetInstance
import avsnap_utils as utils
import imageio
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
parser = argparse.ArgumentParser()
parser.add_argument('--moda... |
3380824 | from __future__ import print_function
import torch
import torch.nn as nn
from torch.nn import functional as F
from utils.metric import AverageMeter, Timer
import numpy as np
from models.resnet import BiasLayer
from .default import NormalNN, accumulate_acc, loss_fn_kd, Teacher
import copy
class LWF(NormalNN):
def... |
3380911 | from __future__ import absolute_import
import time
import traceback
from multiprocessing import Process
import pytest
import six
from thriftpy2.thrift import TType, TPayloadMeta
try:
from thriftpy2.protocol import cybin
except ImportError:
cybin = None
import thriftpy2
from thriftpy2.http import (
make_s... |
3380922 | import collections
class Solution:
def maxPoints(self, points: List[List[int]]) -> int:
def gcd(a, b):
while b:
a, b = b, a%b
return a
maxNum = 0
for i in range(len(points)):
same = localMax = 0
table = collections.Coun... |
3380932 | from openprocurement.tender.core.procedure.state.tender import TenderState
from openprocurement.tender.core.procedure.state.award import AwardStateMixing
from openprocurement.tender.belowthreshold.constants import STAND_STILL_TIME
class AwardState(AwardStateMixing, TenderState):
award_stand_still_time = STAND_STI... |
3380933 | import numpy as np
import random
import sys
class data_t(object):
def __init__(self, data, labels=None):
self.labels = labels
self.data = data
self.num_examples = data.shape[0]
def next_batch(self, batch_size, index):
idx = index * batch_size
n_idx = index * batch_size ... |
3380967 | import tensorflow as tf
from keras.preprocessing import image
import numpy as np
def prepare_image(file):
img_path = ''
img = tf.keras.preprocessing.image.load_img(img_path + file, target_size=(224, 224))
img_array = tf.keras.preprocessing.image.img_to_array(img)
img_array_expanded_dims = np.expand_di... |
3380988 | import sys
import test_cases
import pytest
from csvprint import parser
from csvprint import printer
@pytest.mark.parametrize("args, expected_output", test_cases.test_cases)
def test_correct_features(args, expected_output):
sys.argv = [sys.argv[0]]
csvparser = parser.create()
sys.argv += args
args = par... |
3380990 | from typing import Optional, Union, Tuple
import torch
from torch import Tensor
from torch.nn import Module
class Surrogate(Module):
"""Base class for attacker or defenders that require
a surrogate model for estimating labels or computing
gradient information.
Parameters
----------
... |
3380993 | from torch.utils import data
from torchvision import transforms as T
from torchvision.datasets import ImageFolder
from PIL import Image
import torch
import os
import random
def get_loader(image_dir, crop_size=256, image_size=286,
batch_size=16, dataset='Market', mode='train', num_workers=1):
"""B... |
3380996 | import ctypes
from ctypes import *
import ctypes.util
import sys
import pdb
import os
import struct
#Original here: https://github.com/secretsquirrel/osx_mach_stuff/blob/master/inject.c
#http://www.newosxbook.com/src.jl?tree=listings&file=inject.c
STACK_SIZE = 65536
VM_FLAGS_ANYWHERE = 0x0001
VM_PROT_READ = 0x01
VM_... |
3381011 | import json
from datetime import datetime
from simple_salesforce.exceptions import SalesforceMalformedRequest
from cumulusci.tasks.salesforce import BaseSalesforceApiTask
from cumulusci.core.exceptions import SalesforceException
class CreateCommunity(BaseSalesforceApiTask):
api_version = "48.0"
task_docs = ""... |
3381080 | from polyglotdb.io.helper import (inspect_directory, find_wav_path,
normalize_values_for_neo4j,
guess_type, text_to_lines)
def test_inspect_directory(textgrid_test_dir, buckeye_test_dir, timit_test_dir):
likely, _ = inspect_directory(textgrid_tes... |
3381109 | import rvo.math as rvo_math
from .obstacle import Obstacle
MAX_LEAF_SIZE = 10
class AgentTreeNode:
def __init__(self):
self.begin_ = None
self.end_ = None
self.left_ = None
self.right_ = None
self.maxX_ = None
self.maxY_ = None
class ObstacleTreeNode:
def __... |
3381111 | from doorenv.envs.doorenv import DoorEnv
# from gym_foo.envs.foo_extrahard_env import FooExtraHardEnv |
3381148 | from flask import url_for
from flask_security import SQLAlchemySessionUserDatastore
from flexmeasures.ui.tests.utils import logout
def test_dashboard_responds(client, setup_assets, as_prosumer_user1):
dashboard = client.get(
url_for("flexmeasures_ui.dashboard_view"), follow_redirects=True
)
asser... |
3381199 | from django.http import HttpResponse
from django.views.decorators.http import require_POST
from django.views.decorators.csrf import csrf_protect
from django.shortcuts import render, redirect
from tapiriik.services import Service
from tapiriik.auth import User
import json
def auth_login(req, service):
return redir... |
3381249 | import math
import unittest
import numpy as np
from pyspark import RDD
from pyspark.serializers import AutoBatchedSerializer
from geopyspark.geotrellis import Tile
from geopyspark.geotrellis.protobufserializer import ProtoBufSerializer
from geopyspark.geotrellis.protobufcodecs import tile_decoder, tile_encoder, to_pb_... |
3381252 | import os
import cv2
import numpy as np
import numpy.random as random
import tensorflow as tf
from keras.utils import to_categorical
from classification import squeezenet_v1_1
n_test = 4000
n_class = 43
image_width_height = 90
# https://jdhao.github.io/2017/11/06/resize-image-to-square-with-padding/
def resize_ima... |
3381267 | import pkg_resources
import setuptools
setuptools_version = pkg_resources.parse_version(setuptools.__version__)
if setuptools_version < pkg_resources.parse_version('39.2'):
raise SystemExit('setuptools 39.2 or greater required for installation')
setuptools.setup()
|
3381287 | import os, sys
from shutil import move
from pathlib import Path
from telethon import (
TelegramClient,
events,
utils
)
from ..utils.args import (
tgsend_args
)
from ..utils.utils import (
target_username_handler,
session_retriever
)
args = tgsend_args()
# Get session name from CLI
unique_nam... |
3381311 | from srsly import json_loads
from pathlib import Path
from ..util import get_file
from .._registry import register_loader
SNLI_URL = "http://nlp.stanford.edu/projects/snli/snli_1.0.zip"
THREE_LABELS = {"entailment": 2, "contradiction": 1, "neutral": 0}
TWO_LABELS = {"entailment": 1, "contradiction": 0, "neutral": 0}... |
3381335 | import numpy as np
import tensorflow as tf
from util.Comparator_model import Model
from util.Reference_selection import ref_select
from util.Test_feature_extraction import test_feature_extract
from util.Predict_age import predict_age
import os
import math
import argparse
import pandas as pd
os.environ["CUD... |
3381397 | import unittest
import acpc_python_client as acpc
from evaluation.exploitability import Exploitability
from tools.game_tree.builder import GameTreeBuilder
from tools.game_tree.node_provider import StrategyTreeNodeProvider
from tools.game_tree.nodes import ActionNode
from tools.walk_trees import walk_trees
KUHN_POKER... |
3381407 | import pytest
from tartiflette.language.ast import DirectiveDefinitionNode
def test_directivedefinitionnode__init__():
directive_definition_node = DirectiveDefinitionNode(
name="directiveDefinitionName",
locations="directiveDefinitionLocations",
description="directiveDefinitionDescription... |
3381423 | import calendar
import datetime
import pytz
from django import template
from django.conf import settings
from ..models import Account, Album, Artist, Scrobble, Track
from ...core.utils import get_annual_item_counts
register = template.Library()
def check_top_kwargs(**kwargs):
"""
Used to check the supplie... |
3381446 | import random
import time
from augmentation.operations import OperationPipeline
from image_grabber.grab_settings import DEBUG_MODE
from utils.utils import FileUtil, ProgressBarUtil, NoImageFoundException, ExceptionUtil
class DatasetGenerator(OperationPipeline):
folder_path = None
num_files = None
save_t... |
3381461 | import functools
from abc import ABCMeta
from collections import KeysView, MutableMapping, defaultdict
import torch
import numpy as np
from toolz import curry, first
mathfuns = [
'__add__', '__rmul__', '__mul__', '__sub__', '__radd__', '__rmul__',
'__truediv__', '__floordiv__', '__pow__', '__rpow__'
]
dictfu... |
3381468 | from typing import Any, Callable, Dict, List
from tartiflette.execution.collect import collect_subfields
from tartiflette.execution.execute import execute_fields
from tartiflette.utils.errors import located_error
__all__ = ("complete_value_catching_error", "complete_object_value")
def handle_field_error(
raw_er... |
3381498 | from PySide2.QtCore import QRegExp
from PySide2.QtGui import QSyntaxHighlighter, QTextCharFormat, QFont, QColor
class CodeEditor_Highlighter(QSyntaxHighlighter):
def __init__(self, parent=None):
super(CodeEditor_Highlighter, self).__init__(parent)
keyword_format = QTextCharFormat()
keywor... |
3381523 | import pandas as pd
import numpy as np
def getDailyVol(close,
span0=100):
"""SNIPPET 3.1 DAILY VOLATILITY ESTIMATES
Daily vol reindexed to close
"""
df0=close.index.searchsorted(close.index-pd.Timedelta(days=1))
df0=df0[df0>0]
df0=(pd.Series(close.index[df0-1],
... |
3381527 | import os
def test_comments(interpreter, capfd):
assert interpreter.in_comment == False
assert interpreter.feed('# Hello') == False
captured = capfd.readouterr()
assert captured.out == ''
assert captured.err == ''
assert interpreter.in_comment == False
assert interpreter.feed('#===') == True
assert interpret... |
3381528 | import time
import numpy as np
from epg import utils
from epg.launching import logger
def run_batch_rl(env, agent, inner_opt_freq, inner_max_n_epoch, inner_buffer_size, pool_rank, ppo_factor,
epoch=None,
render=False,
verbose=False):
from collections import deq... |
3381532 | import warnings
import matplotlib.pyplot as plt
import cv2
import mmcv
import random
from PIL import Image
import numpy as np
import torch
from mmcv.runner import load_checkpoint
from mmcv.parallel import collate, scatter
from openselfsup.models import build_model
from openselfsup.utils import build_from_cfg
from o... |
3381538 | import aiohttp
import json
import logging
from os import getenv
from rethinkdb import RethinkDB
from typing import Tuple
from .functions import dogstatsd
r = RethinkDB()
async def request_api(path: str, *, method: str = 'GET', params: dict = None, data: any = None) -> Tuple[dict, int]:
headers = {
'Host... |
3381546 | import pytest
import tensorflow as tf
from fastmri_recon.models.utils.pad_for_pool import pad_for_pool
@pytest.mark.parametrize('dim, n_pools, n_pad_expected',[
(454, 2, 2),
(454, 1, 0),
(320, 3, 0),
(322, 3, 6),
(372, 4, 12),
(320, 0, 0),
(213, 0, 0),
(213, 1, 1),
(213, 4, 11),
]... |
3381553 | import time
from contextlib import asynccontextmanager
from functools import partial
from typing import Any, AsyncContextManager, AsyncGenerator, Awaitable, Callable, Optional, Type
from types import TracebackType
import anyio
from discord_gateway import Opcode
__all__ = ('race', 'DefaultGatewayLimiter')
async def ... |
3381608 | import ipaddress
import pprint
import re
from jschon import create_catalog, JSON, JSONSchema
# define a "hostname" format validation function
def validate_hostname(value):
hostname_regex = re.compile(
r"^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0... |
3381701 | from unittest import TestCase
from pydmd import SpDMD, DMD
import scipy.io
import numpy as np
data = np.load("tests/test_datasets/heat_90.npy")
gammas = [1.0e-1, 0.5, 2, 5, 10, 20, 40, 50, 100]
class TestSpDmd(TestCase):
def test_number_nonzero_amplitudes_rho1(self):
zeros = np.load("tests/test_datasets/... |
3381702 | import pytest
import time
from itertools import product
import numpy as np
import torch
from ding.rl_utils import ppg_data, ppg_joint_error
use_value_clip_args = [True, False]
random_weight = torch.rand(4) + 1
weight_args = [None, random_weight]
args = [item for item in product(*[use_value_clip_args, weight_args])]
... |
3381712 | from manimlib.imports import *
class CodeLine(Text):
CONFIG = {
't2c': {
'RIGHT': ORANGE,
'LEFT': ORANGE,
'DOWN': ORANGE,
'UP': ORANGE,
'UR': ORANGE,
'UL': ORANGE,
'DR': ORANGE,
'DL': ORANGE,
'ORIGI... |
3381719 | from kaishi.core.file import File
from kaishi.core.file_group import FileGroup
def test_validation_and_test():
test = FileGroup(recursive=True)
test.load_dir("tests/data", File, recursive=True)
test.configure_pipeline(["LabelerValidationAndTest"])
test.pipeline.components[0].configure(val_frac=0.2, te... |
3381722 | from prettytable import PrettyTable
class Song:
def __init__(self, id, name, singers, album, interval, tags, source, token):
self.id = id
self.name = name
self.singers = singers
self.album = album
self.interval = interval
self.tags = tags
self.source = source... |
3381745 | import datetime
from pyxl.utils import escape
from pyxl.base import x_base
class x_rss_element(x_base):
def _to_list(self, l):
l.extend((u'<', self.__tag__))
for name, value in self.__attributes__.iteritems():
name, value = self._handle_attribute(name, value)
l.extend((u' '... |
3381760 | import os
import random
import argparse
import numpy as np
import pandas as pd
import torch
from torch.utils.data import DataLoader
from torch.utils.data.sampler import SubsetRandomSampler
from torchtext.data import Field, LabelField, BucketIterator
class Data_Prepper:
def __init__(self, name, train_batch_size, n_pa... |
3381761 | import random
from config.base import Config
class Experiment:
"""
Experiment provides a layer of abstraction to avoid that all models implement the same interface
"""
def __init__(self, model_configuration, exp_path):
self.model_config = Config.from_dict(model_configuration)
self.exp... |
3381773 | import torch.optim
from typing import Dict, Union
import torch
import numpy as np
# Initialize device:
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
def convert_double_to_float(data: Union[Dict, torch.Tensor]):
"""
Utility function to convert double tensors to float tensors in nest... |
3381825 | import numpy as np
import random
from torch.utils.data.dataset import Dataset
class CutMixCrossEntropyLoss(Module):
def __init__(self, size_average=True):
super().__init__()
self.size_average = size_average
def forward(self, input, target):
if len(target.size()) == 1:
targe... |
3381837 | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
DEFAULT_THEME = 'lumen'
# Boolean: True if you == <NAME>; False otherwise :)
FLASK_PRACTICE_ADMIN = os.getenv('true')
# Activates the cross-site request forgery prevention.
WTF_CSRF_ENABLED = True
# Used to create cr... |
3381876 | import time, struct, base64
from roundup.cgi.actions import RegisterAction
from roundup.cgi.exceptions import *
def timestamp():
return base64.encodestring(struct.pack("i", time.time())).strip()
def unpack_timestamp(s):
return struct.unpack("i",base64.decodestring(s))[0]
class Timestamped:
def check(self... |
3381927 | from enum import Enum
# Keep these the same as const/userRoles.ts
class UserRoleType(Enum):
ADMIN = 0
|
3381961 | import tensorflow as tf
import tensorflow.keras.backend as K
from tensorflow.keras.initializers import RandomNormal
from tensorflow.keras.layers import Dense, Flatten, Layer, TimeDistributed
from nets.resnet import resnet50_classifier_layers
from nets.vgg import vgg_classifier_layers
class RoiPoolingConv(La... |
3381978 | import gym.envs
from gym_puyopuyo.agent import (
LargeTreeSearchAgent, SmallTreeSearchAgent, TsuTreeSearchAgent,
WideTreeSearchAgent)
ENV_NAMES = {
"small": "PuyoPuyoEndlessSmall-v2",
"wide": "PuyoPuyoEndlessWide-v2",
"tsu": "PuyoPuyoEndlessTsu-v2",
"large": "PuyoPuyoEndlessLarge-v2",
"bo... |
3382011 | class Image(object):
def __init__(self, ec2, ami_info):
self._ec2 = ec2
self._ami_info = ami_info
@staticmethod
def get_by_name(ec2, ami_name: str):
"""Returns a AMI by its name."""
res = ec2.describe_images(Owners=['self'], Filters=[
{'Name': 'name', 'Values': ... |
3382077 | from channels.routing import URLRouter
from django.urls import path, re_path
from . import consumers
websocket_urlpatterns = URLRouter([
path('', consumers.VoteConsumer.as_asgi()),
re_path(r'spectator/(?P<uuid>.+)$', consumers.VoteConsumer.as_asgi()),
])
|
3382080 | from django.urls import re_path
from .views import release_notes_list
from .feed import ReleaseNotesFeed
urlpatterns = [
re_path(r"^$", release_notes_list, name="release-notes"),
re_path(r"^feed/$", ReleaseNotesFeed(), name="release-notes-feed"),
]
|
3382084 | import json
import os
import argparse
from torch.utils.data import DataLoader
from torch.optim import Adadelta, Adam
from torch.nn import BCELoss, DataParallel
from torchvision.utils import save_image
from PIL import Image
import torchvision.transforms as transforms
import torch
import numpy as np
from tqdm import tqdm... |
3382087 | import pdb
import pickle
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.utils.prune as prune
def prunning_and_rewind(model, sim_ckpt, px):
print("INFO: Pruning Percent: [{}]".format(px))
pruning_model(model.module, px, False)
prun_model_dict... |
3382094 | import tensorflow as tf
import os
flags = tf.flags
FLAGS = flags.FLAGS
# os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
tf.logging.set_verbosity(tf.logging.INFO)
flags.DEFINE_string("buckets", "", "oss buckets")
flags.DEFINE_string(
"model_path", None,
"Input TF example files (can be a glob or comma separated).")
fla... |
3382155 | import numpy as np
# input: coeff with shape [1,257]
def Split_coeff(coeff):
id_coeff = coeff[:, :80] # identity(shape) coeff of dim 80
ex_coeff = coeff[:, 80:144] # expression coeff of dim 64
tex_coeff = coeff[:, 144:224] # texture(albedo) coeff of dim 80
angles = coeff[:, 224:227] # ruler angles(x,y,z) ... |
3382161 | from appdirs import AppDirs
from pathlib import Path
import os
dirs = AppDirs("Momiji", "Kyuunex")
if os.environ.get('MOMIJI_DATA_DIR'):
BOT_DATA_DIR = os.environ.get('MOMIJI_DATA_DIR')
else:
BOT_DATA_DIR = dirs.user_data_dir
if os.environ.get('MOMIJI_CACHE_DIR'):
BOT_CACHE_DIR = os.environ.get('MOMIJI_C... |
3382173 | from .sample_le_success import SampleLeSuccess
from .sample_le_average import SampleLeAverage
__all__ = [
'SampleLeSuccess',
'SampleLeAverage'
]
|
3382180 | import sys
sys.path.insert(1, "../../")
import h2o
def demo_glm():
h2o.demo(funcname="glm", interactive=False, test=True)
if __name__ == "__main__":
from tests import pyunit_utils
pyunit_utils.standalone_test(demo_glm)
else:
demo_glm()
|
3382196 | import math
import numpy as np
from cereal import log
from common.realtime import DT_CTRL
from common.numpy_fast import clip, interp
from common.op_params import opParams
from selfdrive.car.toyota.values import SteerLimitParams
from selfdrive.car import apply_toyota_steer_torque_limits
from selfdrive.controls.lib.driv... |
3382214 | import numpy as np
from mockseries.interaction.interaction import Interaction
class AdditiveInteraction(Interaction):
"""Implementation of the additive relation for timeseries."""
BASE_VALUE = 0.0
def interact(self, *component: np.ndarray) -> np.ndarray:
"""Compute the additive interaction of m... |
3382286 | from twisted.web import server, static
from twisted.web.resource import Resource
from .server_websocket import WebSocketServerFactory
from autobahn.twisted.resource import WebSocketResource
class Root(Resource):
# child_FOO is a nevow thing, not a twisted.web.resource thing
def __init__(self):
Resource... |
3382301 | from django.conf.urls import patterns, include, url
from rest_framework import routers
import views
router = routers.DefaultRouter()
router.register(r'attempt', views.AttemptViewSet, base_name='attempt')
router.register(r'repository', views.RepositoryViewSet, base_name='repository')
urlpatterns = patterns('',
url... |
3382312 | from .dataset import TransformedDataset
from .ood import OodDataset, scale_oodom, tabular_ood_dataset
from .split import dataset_train_test_split, tabular_train_test_split
from .transforms import IdentityScaler, StandardScaler
__all__ = [
"IdentityScaler",
"OodDataset",
"scale_oodom",
"StandardScaler",... |
3382366 | from flask_restplus import Namespace
from app.api.variances.resources.variance_resource import VarianceResource
from app.api.variances.resources.variance_application_status_code import VarianceApplicationStatusCodeResource
from app.api.variances.resources.variance_document_category_code import VarianceDocumentCategory... |
3382387 | from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List, # noqa: F401
NoReturn,
Optional,
Sequence,
Tuple,
Union,
)
from uuid import UUID
from web3._utils.threads import ThreadWithReturn, spawn # noqa: F401
from web3.datastructures import NamedElementOnion
from web3.mana... |
3382480 | import ctypes
import re
def ValidHandle(value, func, arguments):
if value == 0:
raise ctypes.WinError()
return value
import serial
from serial.win32 import ULONG_PTR, is_64bit
from ctypes.wintypes import HANDLE
from ctypes.wintypes import BOOL
from ctypes.wintypes import HWND
from ctypes.... |
3382482 | import argparse
import os
import torch
import logging
from init_tool import init_all
from config_parser import create_config
from train_tool import train
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt='%m/%d/%Y %H:%M:%S',
level=logg... |
3382491 | class Do(object):
# 0-19 为HTTP key 20-39为Dubbo 40-59为 UI 200-230为服务通信
KEY_DO = "do"
TYPE_DEBUG_INTERFACE = 1
TYPE_DEBUG_CASE = 2
TYPE_TASK_EXECUTE = 3
TYPE_TASK_CANCEL = 4
TYPE_TASK_EXECUTE_DONE = 5
TYPE_TASK_INIT_DONE = 6
TYPE_TASK_CANCEL_DONE = 8
TYPE_DEBUG_INTERFACE_DON... |
3382574 | from collections import Counter
import numpy as np
from .helpers import get_sequence_at_position_and_report_features
def smart_gap_threshold_determination(
alignment
) -> float:
# loop through alignment and determine site-wise gappyness
alignment_length = alignment.get_alignment_length()
# get distr... |
3382626 | import os.path
import yaml
from .. import error
def load_yaml(path):
if not os.path.exists(path):
raise error.NoConfigError
try:
with open(path) as yamlfile:
data = yaml.load(yamlfile)
assert(data is not None)
return data
except AssertionError:
... |
3382630 | from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QWidget
from brainframe_qt.extensions import WindowedActivity
from .stream_view import StreamView
class StreamActivity(WindowedActivity):
_built_in = True
@staticmethod
def icon() -> QIcon:
return QIcon(":/icons/stream_toolb... |
3382636 | from collections import deque
import logging
import sys
from .commands import CliCommand
from ..runtime import Environment
class LogCommand(CliCommand):
description = 'Display logged messages'
@classmethod
def init_parser_args(cls, parser):
"""Add custom options to CLI subcommand parser.
... |
3382686 | from django.urls.base import reverse_lazy
from django.views.generic import CreateView
from django.contrib import messages
from .forms import FeedbackForm, ContactForm
FEEDBACK_MESSAGE = "Thanks for your feedback!"
class FeedbackView(CreateView):
form_class = FeedbackForm
template_name = 'feedback.html'
... |
3382696 | from tilecloud.store.wmts import WMTSTileStore
tilestore = WMTSTileStore(
url="http://v2.suite.opengeo.org/geoserver/gwc/service/wmts/",
layer="medford:buildings",
style="_null",
format="image/png",
tile_matrix_set="EPSG:900913",
tile_matrix=lambda z: f"EPSG:900913:{z:d}",
)
|
3382722 | import os
import re
import uuid
import json
import logging
import operator
import tornado.web
import tornado.ioloop
import tempfile
from tornado.concurrent import Future
from tornado import gen
import sandstone.lib.decorators
from sandstone import settings
from sandstone.lib.handlers.base import BaseHandler
from sand... |
3382733 | from setuptools import setup, find_packages
import re
with open('README.md') as f:
readme = f.read()
with open('requirements.txt') as f:
requirements = []
for line in f:
requirements.append(line.rstrip())
with open('manga109api/__init__.py') as f:
# Version is written in manga109api/__init__.... |
3382829 | import web
import settings
from libs.utils import get_auth_token, api_render
from libs.logger import logger
def _is_allowed_client(ip):
if settings.RESTRICT_ACCESS:
if ip not in settings.ACCEPTED_CLIENTS:
return False
return True
def api_acl(func):
def proxyfunc(self, *args, **kw):
... |
3382830 | from feeds import TestRssFeed, TestAtomFeed, TestCustomFeed, ComplexFeed
from django.conf.urls.defaults import patterns
feed_dict = {
'complex': ComplexFeed,
'rss': TestRssFeed,
'atom': TestAtomFeed,
'custom': TestCustomFeed,
}
urlpatterns = patterns('',
(r'^feeds/(?P<url>.*)/$', 'django.contr... |
3382897 | import logging
from concurrent.futures import ThreadPoolExecutor
from os import listdir
from os import path as osp
import netifaces
import defaults
import errors
import utils.async
from system.drive_manager import DRIVE_MANAGER
from API.handlers import APIHandler
from tornado.concurrent import run_on_executor
from tra... |
3382906 | import os
import pickle
from tqdm import tqdm
input_folder = "../pretrain_data/data"
output_folder = "../pretrain_data/data"
if not os.path.exists(output_folder):
os.mkdir(output_folder)
normal_data_path = os.path.join(output_folder, 'normal')
if not os.path.exists(normal_data_path):
os.mkdir(normal_data_path... |
3382909 | import cadquery as cq
import cadquery.selectors as cqs
import logging, importlib
from types import SimpleNamespace as Measures
from math import cos, radians, sqrt
import utilities # Local directory import.
# Selective reloading to pick up changes made between script executions.
# See: https://github.com/CadQuery/CQ-ed... |
3382919 | import numpy as np
import pytz
import datetime as rdatetime
from datetime import datetime
from dateutil import tz
from utils import fill_in, qdump, qload
data_loc = 'C:/Users/Andrea/Documents/DSSG/Energy project/Codigos prueba/Temperature/'
tz_used = pytz.timezone("US/Central")
def temps_to_building_pkl(facili... |
3382921 | import logging
import os
import re
import subprocess
import utils.dockerutils
from icrawl_plugin import IContainerCrawler
from utils.namespace import run_as_another_namespace, ALL_NAMESPACES
logger = logging.getLogger('crawlutils')
class PythonPackageCrawler(IContainerCrawler):
def get_feature(self):
... |
3382953 | import time
import os
import surreal.utils as U
from surreal.session import get_tensorplex_client, get_loggerplex_client
from surreal.distributed import ExperienceCollectorServer
from caraml.zmq import ZmqServer
class Replay:
"""
Important: When extending this class, make sure to follow the init
m... |
3382976 | import alarm
import board
import time
import microcontroller
import sdioio
import storage
import neopixel
np = neopixel.NeoPixel(board.NEOPIXEL, 1)
np[0] = (50, 0, 0)
# SD Card
sd = sdioio.SDCard(
clock=board.SDIO_CLOCK, command=board.SDIO_COMMAND, data=board.SDIO_DATA, frequency=25000000
)
vfs = storage.VfsFat(s... |
3382988 | from electrodomestico import Electrodomestico
#Clase lavadora que hereda de la clase Electrodomesticos
class Lavadora(Electrodomestico)
def __init__(self, modelo, marca, color, numSerie, voltaje):
super().__init__(modelo, marca, color, numSerie, voltaje)
self.ciclos = ciclos
#Metodos getter y set... |
3382989 | def check_sort(array):
for index, element in enumerate(array):
if index+1 != len(array):
if element >= array[index+1]:
return False
return True
def remove_element(array, index, length):
return array.pop(index)
# if length == 2 and index == 0:
# return [6,3,5]
# if index == 0 :
# return [2,6,3,5]
# ... |
3383037 | import pandas as pd
import unittest
import ray
from ray import tune
from ray.tune import session
def _check_json_val(fname, key, val):
with open(fname, "r") as f:
df = pd.read_json(f, typ="frame", lines=True)
return key in df.columns and (df[key].tail(n=1) == val).all()
class TrackApiTest(unitt... |
3383061 | import os
from universal_build import build_utils
from universal_build.helpers import build_docker
COMPONENT_NAME = "opyrator-playground"
DOCKER_IMAGE_PREFIX = "mltooling"
HERE = os.path.abspath(os.path.dirname(__file__))
def main(args: dict) -> None:
# set current path as working dir
os.chdir(HERE)
v... |
3383062 | import json
import os
import re
from glob import glob
from typing import Callable, Dict, Any
import optuna
from .config import Config
from .helpers import Loggable
class OptunaTemplateParser(Loggable):
"""
Parser for dynamic configuration file templates.
Will find placeholders wrapped in triple curly br... |
3383105 | import pytest
import torch
from nnrl.nn.model import SME
from raylab.policy.losses import MaximumLikelihood
@pytest.fixture
def loss_fn(models):
return MaximumLikelihood(models)
def test_init(loss_fn, models):
assert hasattr(loss_fn, "batch_keys")
assert hasattr(loss_fn, "models")
assert isinstance... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.