id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1666802 | from rest_framework import serializers
class SendPasswordResetEmailSerializer(serializers.Serializer):
username = serializers.CharField(required=True)
publicUrl = serializers.CharField(required=True)
|
1666819 | import numpy as np
from ...utilities import get_num_atom_ids, normalize_ids
from .utilities import get_maximum_diameter
def test_get_maximum_diameter(case_data, get_atom_ids):
"""
Test :meth:`.Molecule.get_maximum_diameter`.
Parameters
----------
case_data : :class:`.CaseData`
A test cas... |
1666849 | import mxnet as mx
import logging
def get_setting_params(**kwargs):
# bn_params
bn_mom = kwargs.get('bn_mom', 0.9)
bn_eps = kwargs.get('bn_eps', 2e-5)
fix_gamma = kwargs.get('fix_gamma', False)
use_global_stats = kwargs.get('use_global_stats', False)
# net_setting param
workspac... |
1666850 | import tkinter
from command.DrawCommand import DrawCommand
from command.MacroCommand import MacroCommand
class CanvasFrame(tkinter.Frame):
def __init__(self, parent):
super().__init__(parent)
self.parent = parent
self.pack()
self.history = MacroCommand()
self.paintColor = "... |
1666853 | from arekit.contrib.source.common.labels import PositiveLabel, NegativeLabel
# Defaul label formattings.
POS_LABEL_STR = "pos"
NEG_LABEL_STR = "neg"
# Default label instances.
RUSENTREL_POS_LABEL_TYPE = PositiveLabel
RUSENTREL_NEG_LABEL_TYPE = NegativeLabel
|
1666934 | from cryptography.fernet import Fernet, InvalidToken
from django.conf import settings
class Fern:
# """
# Usage:
# encrypt('foo')
# decrypt('CIPHERTEXT_ENCRYPTED_TEXT')
# """
def __init__(self, key=None):
if key:
self.key = key
else:
self.key = setting... |
1666946 | import os
import shutil
import pytest
from flynt import api
from flynt import state
from flynt.api import _fstringify_file
# These "files" are byte-string constants instead of actual files to prevent e.g. Git or text editors from accidentally changing the encoding
invalid_unicode = b"# This is not valid unicode: " +... |
1666977 | import os
try:
from ufoLib.glifLib import GlyphSet
except ImportError:
from robofab.glifLib import GlyphSet
import pkg_resources
DATADIR = pkg_resources.resource_filename('cu2qu.test', 'data')
CUBIC_GLYPHS = GlyphSet(os.path.join(DATADIR, 'cubic'))
QUAD_GLYPHS = GlyphSet(os.path.join(DATADIR, 'quadratic'))
im... |
1667008 | import ujson
import redis
import falcon
from celery.result import AsyncResult
from app.tasks import invoke_predict
from app.logic.pipeline import verify_input
INFO_FILE = './app/assets/info.txt'
class InfoResource(object):
def on_get(self, req, resp):
"""Handles GET requests"""
resp.status = fa... |
1667052 | from hathor.conf import HathorSettings
from hathor.graphviz import GraphvizVisualizer
from hathor.simulator import FakeConnection
from tests import unittest
from tests.simulation.base import SimulatorTestCase
from tests.utils import add_custom_tx, gen_new_tx
settings = HathorSettings()
class BaseSoftVoidedTestCase(S... |
1667072 | import datetime
from codecs import utf_8_decode
from codecs import utf_8_encode
import hashlib
import os
import time
from wsgiref.handlers import _monthname # Locale-independent, RFC-2616
from wsgiref.handlers import _weekdayname # Locale-independent, RFC-2616
try:
from urllib.parse import urlencode, parse_qs... |
1667105 | import numpy as np
import logging
logger = logging.getLogger(__name__)
def get_n_unique_rows(edge):
new = [tuple(row) for row in edge]
edge_unique = np.unique(new)
edge_size = edge_unique.shape[0]
return edge_size
def get_unique_rows(edge):
edge_unique = np.unique(edge, axis=0)
return edge_... |
1667166 | import pandas as pd
def check_gtf_composition(gtf_file, annotation=None, feature_type='gene'):
"""
annotation can be either HAVANA or ENSEMBL
feature_type can be gene, transcript, exon
"""
# loading the gtf file
mtx = []
with open(gtf_file) as f:
for line in f:
if line[... |
1667170 | from django.conf.urls import url
from . import duo_auth
urlpatterns = [
url(r'^accounts/duo_login', duo_auth.login),
url(r'^accounts/duo_logout/$', duo_auth.logout),
]
|
1667195 | from typing import TYPE_CHECKING
if TYPE_CHECKING:
from bc4py.database.builder import *
"""
database object
====
warning: do not import bc4py.* on this file
"""
tables: 'Tables' = None
chain_builder: 'ChainBuilder' = None
tx_builder: 'TransactionBuilder' = None
account_builder: 'AccountBuilder' = None
__all__... |
1667222 | from enum import Enum
from grapheme.grapheme_property_group import GraphemePropertyGroup as G
from grapheme.grapheme_property_group import get_group
class FSM:
@classmethod
def default(cls, n):
if n is G.OTHER:
return True, cls.default
if n is G.CR:
return True, cls.c... |
1667258 | from .molecule import Molecule, might_be_variant, molecule_to_random_primer_dict
from .iterator import MoleculeIterator, ReadIterator
from .taps import *
from .chic import *
from .featureannotatedmolecule import *
from .nlaIII import *
from .rna import *
from .consensus import *
from .fourthiouridine import *
from .fil... |
1667301 | from __future__ import print_function
__author__ = "<NAME>, <NAME> and <NAME>"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
class VehicleData():
"""
Class describing the vehicle data corresponding to the timestamp
of the color image
Attributes:
velocity (float): Velocity of the vehicle ... |
1667334 | from kubernetes.client.rest import ApiException
import kube_vars as globalvars
import kube_factory as factory
import kube_pod
import re
def CheckContainerLog(Client,PodName,ContainerName,NameSpace,Message,Possization=0):
print("Run CheckContainerLog in kube_log model")
_CoreV1Api = Client
if _CoreV1Api ==... |
1667343 | from django.db import models
import requests
class Location(models.Model):
zip_code = models.IntegerField()
latitude = models.DecimalField(blank=True, max_digits=9, decimal_places=6)
longitude = models.DecimalField(blank=True, max_digits=9, decimal_places=6)
def save(self, *args, **kwargs):
r... |
1667372 | import neural_network_lyapunov.train_utils as train_utils
import unittest
import torch
import numpy as np
def setup_relu(relu_layer_width, params):
assert (isinstance(relu_layer_width, tuple))
dtype = torch.float64
def set_param(linear, param_count):
linear.weight.data = params[param_count:para... |
1667377 | import warnings as test_warnings
from unittest.mock import patch
import pytest
import requests
from rotkehlchen.assets.asset import WORLD_TO_GEMINI
from rotkehlchen.assets.converters import UNSUPPORTED_GEMINI_ASSETS
from rotkehlchen.constants.assets import A_BCH, A_BTC, A_ETH, A_LINK, A_LTC, A_USD
from rotkehlchen.co... |
1667402 | import os
import sys
from datetime import datetime, timedelta
import numpy as np
import pandas as pd
if len(sys.argv) != 2:
print(
"Usage: [100, biscotti_output_file_dir, biscotti_input_file_dir, fedsys_output_file_dir, fedsys_input_file_dir]")
sys.exit()
# Example Usage: python generateResults.py 100... |
1667405 | import azure.batch.models as batch_models
from azure.batch.models import BatchErrorException
from aztk.error import AztkError
def clean_up_cluster(spark_client, id):
try:
cluster = spark_client.cluster.get(id)
nodes = [node for node in cluster.nodes]
if not any([
node.stat... |
1667418 | import unittest
import sys
try:
from django.conf import settings
settings.configure(DEBUG=True, TEMPLATE_DEBUG=True)
except ImportError, e:
pass
from hamlpy.template.loaders import get_haml_loader, TemplateDoesNotExist
class DummyLoader(object):
"""
A dummy template loader that only loads templates fr... |
1667452 | import numpy as np
def topHatFilter(blueMovie,uvMovie,mask,topHat=300):
# Mask (spatial), resize, and rotate
# mask = np.array(Image.open('mask.tif').resize(downsampledSize, Image.BILINEAR).rotate(rotationAngle,Image.NEAREST,True))
rotatedSize3D = blueMovie.shape
# Reshape
blueMovie = blueMovi... |
1667453 | import numpy as np
from copy import copy, deepcopy
from itertools import product
from envs.env import DeterministicEnv, Direction
class TrainState(object):
'''
state of the environment; describes positions of all objects in the env.
'''
def __init__(self, agent_pos, vase_states, train_pos, train_inta... |
1667459 | from Crypto.PublicKey import RSA
key = RSA.generate(2048)
print("CREDENTIAL_STORAGE_PRIVATE_KEY = " + key.exportKey("DER").__repr__())
print("CREDENTIAL_STORAGE_PUBLIC_KEY = " + key.publickey().exportKey("DER").__repr__())
|
1667460 | from __future__ import print_function
import json
import os
import uuid
import boto3
import decimal
import sympy
# Converts DynamoDB items to JSON
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
if o % 1 > 0:
return float(o)
... |
1667490 | import time
import json
import boto3
REGION = ''
AWS_ACCOUNT = ''
DYNAMODB_TABLE = ''
STEP_FUNCTION_ARN = f'arn:aws:states:{REGION}:{AWS_ACCOUNT}:stateMachine:otter-state'
# Example Payload
payload = {
"assets": [
{
"hostname": "panos01.example.com",
"common_name": "panos01.examp... |
1667523 | import jsonschema
def test_if_schema_is_valid_schema():
# The input needs to be nonempty lists of strings for it to be a valid schema
schema = {}
jsonschema.Draft7Validator.check_schema(schema)
assert False
|
1667594 | import numpy as np, pandas as pd, random
import tensorflow as tf
from tqdm import tqdm
from matplotlib import pyplot as plt
from agent import BrawlAgent
from env.brawlstars import Brawlstars
from utilities.utilities import log_histogram, log_scalars, variable_summaries, PressKey, ReleaseKey
from utilities.directkeys im... |
1667607 | import asyncio
import asynctnt
from asynctnt import Response, PushIterator
from asynctnt._testbase import ensure_version
from asynctnt.exceptions import TarantoolDatabaseError, TarantoolNotConnectedError
from tests import BaseTarantoolTestCase
class PushTestCase(BaseTarantoolTestCase):
@ensure_version(min=(1, 10... |
1667620 | import pytest
from .speculos import SpeculosContainer
import base64
import msgpack
from algosdk import transaction
import algomsgpack
@pytest.fixture(scope='session')
def app(pytestconfig):
return pytestconfig.option.app
@pytest.fixture(scope='session')
def apdu_port(pytestconfig):
return pytestconfig.op... |
1667628 | import logging
import click
from diana.utils.gateways import suppress_urllib_debug
from diana_cli import __version__
from diana import __version__ as diana_version
from diana_cli.cli import cmds as cli_cmds
from .ssde import ssde
from .classify import classify
@click.group(name="diana-plus")
@click.option('--verbos... |
1667641 | ent_linker_out = open('predictions/entity_linker.txt', 'w', encoding='utf-8')
ent_emb_avg_out = open('predictions/entity_emb_avg.txt', 'w')
cosine_distance_out = open('predictions/cos_out.txt', 'w')
predicted_reln = open('predictions/pred_relations.txt', 'w')
predicted_reln_top3 = open('predictions/pred_relations_top3.... |
1667642 | def test_reusable_fixture(test_client):
_, response = test_client.get("/")
assert response.json == 3
_, response = test_client.get("/")
assert response.json == 4
_, response = test_client.get("/")
assert response.json == 5
|
1667775 | from django.db import models
class Quote(object):
def __init__(self, character, line, sketch):
self.character = character
self.line = line
self.sketch = sketch
class Snippet(models.Model):
title = models.CharField(max_length=80)
code = models.TextField()
linenos = models.Bo... |
1667782 | import torch
from reconstruction.model.model import *
from reconstruction.utils.inference_utils import CropParameters, IntensityRescaler, ImageFilter, ImageWriter, UnsharpMaskFilter
from reconstruction.utils.event_tensor_utils import EventPreprocessor
from reconstruction.utils.image_display_utils import ImageDisplay
fr... |
1667804 | from agpy import azimuthalAverage
from pylab import *
yy,xx = indices([10,10])
rr1 = hypot(xx-5,yy-5)
rr2 = hypot(xx-4.5,yy-4.5)
rr3 = hypot(xx-4.43,yy-4.53)
exp1 = exp(-(rr1**2)/(2.0*5**2))
exp2 = exp(-(rr2**2)/(2.0*5**2))
exp3 = exp(-(rr3**2)/(2.0*5**2))
exp1 /= exp1.max()
exp2 /= exp2.max()
exp3 /= exp3.max()
az... |
1667837 | from rest_framework import routers
from .api.views import AccountViewSet, ReporterViewSet, ArticleViewSet, \
TagViewSet, ReversedArticleViewSet, ReversedReporterViewSet, \
ReversedTagViewSet, ReversedAccountViewSet
# API
router = routers.DefaultRouter()
router.register(r'accounts', AccountViewSet, base_name='... |
1667845 | import os
import operator
import hashlib
import sys
import random
import requests
import randomcolor
import numpy
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot
from scipy.stats import gaussian_kde
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
def getcol... |
1667865 | import threading
thread_data = threading.local()
def set_thread_data(job_id):
if job_id and type(job_id) == int:
thread_data.job_id = job_id |
1667866 | import math
import unittest
import sycomore
from sycomore.units import *
class TestModel(unittest.TestCase):
def test_pulse(self):
model = sycomore.como.Model(
sycomore.Species(1*s, 0.1*s),
sycomore.Magnetization(0, 0, 1),
[["dummy", sycomore.TimeInterval(0*s)]])
... |
1667875 | from chalicelib.core import users
from chalicelib.utils import pg_client, helper
from chalicelib.utils.TimeUTC import TimeUTC
def update(tenant_id, user_id, role_id, changes):
admin = users.get(user_id=user_id, tenant_id=tenant_id)
if not admin["admin"] and not admin["superAdmin"]:
return {"errors": ... |
1667876 | import argparse
import filecmp
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Directory comparison")
parser.add_argument("--recurse", "-r", action="store_true", default=False)
parser.add_argument('dirs', nargs=2)
options = parser.parse_args()
dd = filecmp.dircmp(options.d... |
1667892 | from model import DeepJIT
from utils import mini_batches_test
from sklearn.metrics import roc_auc_score
import torch
from tqdm import tqdm
def eval(labels, predicts, thresh=0.5):
TP, FN, FP, TN = 0, 0, 0, 0
for lable, predict in zip(labels, predicts):
# print(predict)
if predict >= thresh ... |
1667950 | import gzip
import sys
import os
import argparse
import subprocess
import config_parser
import re
from binner_analysis import *
from genfunc import *
from checkm_analysis import *
from novel_analysis import *
from kraken_analysis import *
# default to look for polish contig, if polished contig not exist, use unpoli... |
1667957 | from pso import pso
from optitestfuns import ackley
import unittest
from numpy import isclose, array
'''Tests for the nD PSO implementation.
To run it please execute the following command in your terminal or cmd
python -m unittest test_pso.py
'''
class PSOfunctionMethodTests(unittest.TestCase):
def test_pso1D(se... |
1667965 | import sys
import unittest
import module_utils.helpers as helpers
sys.modules['ansible.module_utils.helpers'] = helpers
from library.cartridge_get_disabled_instances import count_disabled_instances
def call_count_disabled_instances(
instances_info,
play_hosts=None,
ignore_split_brain=False,
):
modul... |
1667970 | import os
from mlstabilitytest.stability.StabilityAnalysis import StabilityAnalysis, EdAnalysis
from shutil import copyfile
here = os.path.abspath(os.path.dirname(__file__))
def main():
models = ['ElFrac', 'Meredig', 'Magpie', 'AutoMat', 'ElemNet', 'Roost',
'CGCNN']
experiments = ['LiMnTMO', 'al... |
1668095 | import copy
import dlib
import os
import bz2
import random
from tqdm.notebook import tqdm
import shutil
from utils import image_to_array, load_image, download_data
from utils.face_detection import crop_face, get_face_keypoints_detecting_function
from mask_utils.mask_utils import mask_image
class DataGenerator:
de... |
1668138 | from typing import List
from pygls.lsp.types import Model
class LanguageServerConfiguration(Model): # type: ignore
enable_lint_on_save: bool
enable_code_action: bool
lint_targets: List[str]
format_targets: List[str]
@classmethod
def default(cls) -> "LanguageServerConfiguration":
ret... |
1668186 | import json
from .stitch.stitch import Stitch
import psutil
import traceback
# -------------------------------------------
# Pandoc JSON AST filter
# -------------------------------------------
def safe_spawn(func):
"""
Safely run function: if func spawns child processes they are closed even on python error.
... |
1668216 | import common as c
from config import ssl_dir, os_name
import sys
import xml.etree.ElementTree as ET
c.print('>> Downloading ssl for Qt for {}'.format(os_name))
if os_name == 'linux':
os_url = 'linux_x64'
tool_name = 'tools_openssl_x64'
root_path = 'Tools/OpenSSL/binary'
elif os_name == 'win32':
os_ur... |
1668239 | from .settings import ( # noqa
SECRET_KEY,
MIDDLEWARE_CLASSES,
INSTALLED_APPS,
ROOT_URLCONF,
MEDIA_ROOT,
BROKER_URL,
CELERY_RESULT_BACKEND,
WQ_DEFAULT_REPORT_STATUS,
)
SWAP = True
INSTALLED_APPS += ("tests.swap_app",)
WQ_SITE_MODEL = "swap_app.Site"
WQ_RESULT_MODEL = "swap_app.Result"... |
1668241 | from datetime import timedelta
class Config(object):
DEBUG = False
TESTING = False
SQLALCHEMY_DATABASE_URI = ''
APP_NAME = 'ApplicationName'
SECRET_KEY = 'add_secret'
JWT_EXPIRATION_DELTA = timedelta(days=30)
JWT_AUTH_URL_RULE = '/api/v1/auth'
SECURITY_REGISTERABLE = True
SECURITY... |
1668245 | import collections
class BasicBlock(object):
def __init__(self, st_instr_id, ed_instr_id, func_instr_id):
super(BasicBlock, self).__init__()
self.name = st_instr_id
self.st_instr_id = st_instr_id
self.ed_instr_id = ed_instr_id
self.func_instr_id = func_instr_id
clas... |
1668256 | class A:
def spam(self):
print('A.spam')
class B(A):
def spam(self):
print('B.spam')
super().spam() # Call parent spam()
if __name__ == '__main__':
b = B()
b.spam()
|
1668262 | from heybooster.helpers.database.mongodb import MongoDBHelper
NAME = "database_name"
URI = "database_uri"
"""
Usage 'with'
"""
with MongoDBHelper(uri=URI, database=NAME) as db:
result = db.find_one('test_collection', query={'email': '<EMAIL>'})
result = db.find('test_collection', query={'email': '<EMAIL>'})
... |
1668281 | import pymortar
import os
import pandas as pd
def _query_and_qualify(sensor):
"""
Build query to return zone air temperature measurements and qualify
which site can run this application
Parameters
----------
sensor : sensor name type to evaluate e.g. Zone_Air_Temperature
Returns
-----... |
1668296 | import unittest
import json
from discord_webhooks import DiscordWebhooks
class BaseTest(unittest.TestCase):
def test_standard_message(self):
"""
Tests a standard messgae payload with nothing but content.
"""
webhook = DiscordWebhooks('webhook_url')
webhook.set_content(content='Montezuma')
... |
1668312 | import re
import os
from pathlib import Path
import gdgen
from gdgen import common
from gdgen import methods
from gdgen import gdtypes
class TemplateWriter:
src = ''
dest = ''
def __init__(self, src, dest):
self.src = src
self.dest = dest
def write_out(self, template={}):
with open(self.src, 'r') as s... |
1668342 | from copy import deepcopy
import numpy as np
def complete_mol(self, labels):
"""
Take a cell and complete certain molecules
The objective is to end up with a unit cell where the molecules of interest
are complete. The rest of the atoms of the cell must remain intact. Note that
the input atoms are... |
1668350 | import setuptools
import codecs
import os.path
def read(rel_path):
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, rel_path), 'r') as fp:
return fp.read()
def get_version(rel_path):
for line in read(rel_path).splitlines():
if line.startswith('__version... |
1668365 | import os, sys, json, re, uuid, time
import logging, argparse
import requests
logging.basicConfig(
filename='publish_to_marketplace.log',
format='%(asctime)s %(levelname)-8s %(message)s',
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S'
)
headers = {'content-type': 'application/json'... |
1668382 | import FWCore.ParameterSet.Config as cms
from CommonTools.ParticleFlow.pfNoPileUpIso_cff import pfPileUpIso, pfNoPileUpIso, pfNoPileUpIsoTask
from RecoEgamma.EgammaIsolationAlgos.egmIsoConeDefinitions_cfi import IsoConeDefinitions as _IsoConeDefinitions
from RecoEgamma.EgammaIsolationAlgos.egmIsolationDefinitions_cff ... |
1668435 | from wx.lib.agw.aui import AuiNotebook
from wx.lib.agw.aui import AUI_NB_CLOSE_ON_ACTIVE_TAB, AUI_NB_MIDDLE_CLICK_CLOSE, \
AUI_NB_TAB_MOVE, AUI_NB_TAB_EXTERNAL_MOVE, AUI_NB_TAB_SPLIT, AUI_NB_CLOSE_BUTTON
from kurier.interfaces import IStateRestorable
from kurier.widgets.request.headers import RequestHeadersTab
fro... |
1668454 | class Node:
def __init__(self):
self.left = None
self.right = None
def count_nodes(root, lspine=0, rspine=0):
if not root:
return 0
if not lspine:
node = root
while node:
node = node.left
lspine += 1
if not rspine:
node = root
... |
1668478 | import os
import time
from copy import deepcopy
from pathlib import Path
from typing import List, Optional, cast
import hydra
import jax
import numpy as np
import ptvsd
import pytorch_lightning as pl
import wandb
from hydra.utils import instantiate
from omegaconf import OmegaConf
from pytorch_lightning.loggers import ... |
1668502 | import math
import cv2
import numpy as np
from dtld_parsing.calibration import CalibrationData
from typing import Tuple
__author__ = "<NAME>, <NAME> and <NAME>"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
class ThreeDPosition(object):
"""
Three dimensional position with respect to a defined frame_id.
... |
1668546 | from koursaros.gnes_addons import Flow
flow = (
Flow(check_version=True)
.add_client(name='postgres', yaml_path='clients/postgres/wikititles.yml')
.add_preprocessor(name='sentsplit', replicas=2,
yaml_path='services/preprocessors/sentsplit/jsonmode.yml')
.add_encoder(name='textbyte... |
1668569 | import struct
import numpy as np
import rospy
from sensor_msgs.msg import PointCloud2, PointField
from nclt2ros.extractor.base_raw_data import BaseRawData
from nclt2ros.converter.base_convert import BaseConvert
class VelodyneData(BaseRawData, BaseConvert):
"""Class to convert the velodyne binary file to ROS Poin... |
1668572 | import os
import unittest
import pprint
from google.protobuf.json_format import MessageToDict
from spaceone.core import utils, pygrpc
from spaceone.core.unittest.runner import RichTestRunner
class TestEndpoint(unittest.TestCase):
config = utils.load_yaml_from_file(
os.environ.get('SPACEONE_TEST_CONFIG_FI... |
1668600 | import json
import pytest
import yaml
from satosa.backends.base import BackendModule
from satosa.exception import SATOSAConfigurationError
from satosa.frontends.base import FrontendModule
from satosa.micro_services.base import RequestMicroService, ResponseMicroService
from satosa.plugin_loader import backend_filter, ... |
1668678 | import cv2
import numpy
import sys
import os
if len(sys.argv) == 2:
folder_path = str(sys.argv[1])
else:
print('## USAGE ## \n python readTiff_folder.py path_to_folder. \n Space Bar for next image. Any other key to exit. \n##')
exit
dirs = os.listdir(folder_path)
cv2.namedWindow(folder_path)
for imagePath in dir... |
1668684 | from dtcwt.coeffs import biort, qshift
from pytest import raises
def test_antonini():
h0o, g0o, h1o, g1o = biort('antonini')
assert h0o.shape[0] == 9
assert g0o.shape[0] == 7
assert h1o.shape[0] == 7
assert g1o.shape[0] == 9
def test_legall():
h0o, g0o, h1o, g1o = biort('legall')
assert h... |
1668713 | import numpy as np
from itertools import product
from analysis.utils import one_hot_to_int
def get_oq_keys(X_i, task, to_int=True):
"""extract obs/query keys from the input matrix, for one sample
Parameters
----------
X_i : np array
a sample from SequenceLearning task
task : object
... |
1668754 | from collections import Counter
from collections import defaultdict
from dataclasses import dataclass
from itertools import product
from math import ceil
from math import exp
from math import floor
from math import isclose
from math import log2
from math import sqrt
from typing import List
from typing import Tuple
imp... |
1668770 | import json
import logging
from datetime import datetime
from typing import List, cast
from chaos_genius.connectors import (
get_schema_names,
get_sqla_db_conn,
get_table_info,
get_table_list,
)
from chaos_genius.controllers.data_source_controller import get_datasource_data_from_id
from chaos_genius.da... |
1668775 | from httmock import HTTMock, with_httmock
from xml.dom.minidom import parseString
from django.test import TestCase
from authorizenet.models import CustomerProfile
from .utils import create_user, xml_to_dict
from .mocks import cim_url_match, customer_profile_success, delete_success
from .test_data import create_empty_p... |
1668811 | from chainer.backends import cuda
from chainerkfac.optimizers.fisher_block import compute_pi
from chainerkfac.optimizers.fisher_block import FisherBlock
class FisherBlockConnection(FisherBlock):
def __init__(self, *args, **kwargs):
self._A = None
self._G = None
super(FisherBlockConnectio... |
1668817 | import abc
import os
import SimpleITK as sitk
import numpy as np
import pymia.data.conversion as conversion
import common.evalutation.numpyfunctions as np_fn
import common.utils.labelhelper as lh
import rechun.eval.helper as helper
import rechun.eval.evaldata as evdata
import rechun.directories as dirs
class Loader... |
1668822 | from astropy.tests.helper import remote_data
from astropy.table import Table
from astropy.io import fits
from beast.tools.convert_hdf5_to_fits import st_file
from beast.tests.helpers import download_rename, compare_tables
@remote_data
def test_convert_hd5_to_fits():
# Pick some random .hd5 file to convert
d... |
1668874 | import torch
import torch.nn as nn
import math
import torch.nn.functional as F
from torch.autograd import Variable
from layers.slice_pool_layer.slice_pool_layer import *
from layers.slice_unpool_layer.slice_unpool_layer import *
class RSNet(nn.Module):
def __init__(self, pool_type, num_slice=[None, None, None]... |
1668884 | from filename_database.models import ExperimentType, ChargerDriveProfile, Category, SubCategory, ValidMetadata
import re
import datetime
import itertools
def guess_exp_type(file, root):
"""
This function takes a file as input and guesses what experiment type it is.
:param file:
:param root:
:return... |
1668887 | from rest_framework import exceptions
from pyplan.pyplan.common.baseService import BaseService
from .models import DashboardStyle
class DashboardStyleService(BaseService):
def getByStyleType(self, style_type):
"""Get By Style Type"""
if style_type and isinstance(style_type, int):
retur... |
1668896 | import torch.nn.functional as F
from torch import nn
from networks.layers.basic import DropPath, GroupNorm1D, GNActDWConv2d, seq_to_2d
from networks.layers.attention import MultiheadAttention, MultiheadLocalAttentionV2, MultiheadLocalAttentionV3
def _get_norm(indim, type='ln', groups=8):
if type == 'gn':
... |
1668911 | from flasgger import swag_from
from flask import current_app, request, jsonify
from flask_jwt_extended import jwt_refresh_token_required
from app.doc.account.auth import AUTH_POST, REFRESH_POST
from app.model import StudentModel, TokenModel
from app.util.json_schema import json_type_validate, AUTH_POST_JSON
from app.v... |
1668912 | import unittest
import gzip
import logging
import json
import os
import random
from multiprocessing.pool import ThreadPool
from SolrClient import SolrClient, IndexQ
from SolrClient.exceptions import *
from .test_config import test_config
from .RandomTestData import RandomTestData
import shutil
from functools import par... |
1668970 | import logging
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from django.core.cache import cache
from django.db.models.signals import post_save
from django.dispatch import Signal, receiver
from redis.lock import LockError
from influxdb_metrics.loader import log_metric
from apps.... |
1668974 | from .base_interpreter import BaseInterpreter
from .lexer import AstError, Lexer
from .parser import Parser, TopNode
class ValidationError(AstError):
pass
class ValidationWarning(AstError):
pass
class ValidationResult:
def __init__(self, is_valid=True, error=None, warning=None, tree=None):
self.i... |
1669002 | from django_dynamic_fixture import G
from tests.base import BaseTestCase
from tests.models import IdGenerateTestModel, TestIds
class TableStrategyTestCase(BaseTestCase):
def test_id_generation(self):
dummy_one = G(IdGenerateTestModel)
dummy_two = G(IdGenerateTestModel)
self.assertEqual(du... |
1669036 | import platform
from .location import Location
from .robot import Robot
from .sikulpy import unofficial
from ..version import VERSION
class Env(object):
@staticmethod
def addHotkey(key, modifiers, handler):
raise NotImplementedError(
"Env.addHotKey(%r, %r, %r) not implemented" % (key, mod... |
1669065 | import math
def D(xU, xL):
r = 0.61803
return r * (xU - xL)
def func(x):
return 2 * math.sin(x) - (x * x) / 10.0
def GoldenSection(xL, xU, f):
d = D(xU, xL)
x1 = xL + d
x2 = xU - d
f1 = f(x1)
f2 = f(x2)
while abs(x1 - x2) > 3E-8:
if (f1 > f2):
xL = x2
... |
1669076 | import datetime as dt
import uuid
from enum import Enum
from typing import List
from sqlalchemy import and_
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import backref
from sqlalchemy_utils import ChoiceType
from server.api.database import db
from server.api.database.mixins import (
Colum... |
1669087 | import numpy as np
import xarray as xr
def compute_dataset(ds, period='1W', incl_stdev=False):
if incl_stdev:
resample_obj = ds.resample(time=period)
ds_mean = resample_obj.mean(dim='time')
ds_std = resample_obj.std(dim='time').rename(name_dict={name: f"{name}_stdev" for name in ds.data_va... |
1669089 | from rnn_cell import RNNCell
from gru_cell import GRUCell
from cif_lstm_cell import CifLSTMCell
from lstm_cell import LSTMCell |
1669105 | import argparse
import atexit
import sys
from py4j.java_gateway import JavaGateway
from py4j.protocol import Py4JError
from pykukulcan.repl import PyKukulcanRepl
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="PyKukulcan REPL.")
parser.add_argument("--classpath", type=str, help="Clas... |
1669193 | from typing import Any, Collection, Dict
from ..constants.types import basic_types, key_value_types, named_types, sequence_types
from ..models.heap_object import HeapObject
from ..models.options import Options
from .base_heap_object_factory import HeapObjectFactory
from .basic_heap_object_factory import BasicHeapObjec... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.