id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11425984 | import io
import os
from setuptools import setup, find_packages
version = '0.0.6'
install_requires = [
'numpy',
'scikit-learn',
'pandas',
]
CURRENT_DIR = os.path.abspath(os.path.dirname(__file__))
def read(filename):
return io.open(os.path.join(CURRENT_DIR, filename), encoding='utf-8').read()
setup... |
11425989 | import click
from arbol.arbol import aprint, asection
from dexp.cli.defaults import _default_clevel, _default_codec, _default_store
from dexp.cli.parsing import _get_output_path, _parse_slicing
from dexp.datasets.open_dataset import glob_datasets
from dexp.datasets.operations.isonet import dataset_isonet
@click.comm... |
11425990 | from typing import Any, Dict, Iterable, List
from fugue.dataframe import ArrayDataFrame
from fugue.exceptions import FugueInterfacelessError
from fugue.extensions.transformer import Transformer, _to_transformer, transformer
from pytest import raises
from triad.collections.schema import Schema
def test_transformer():... |
11426003 | import sys
import groundstation.audio as audio
import quietnet.quietnet as quietnet
import pyaudio
import alltheFSKs.MFSKModulator as modulator
import alltheFSKs.MFSKDemodulator as demodulator
import groundstation.ue_encoder
from groundstation import logger
log = logger.getLogger(__name__)
# TODO Unify this with Br... |
11426014 | import torch
import torch.nn as nn
from pytorch_wavelets.dtcwt.coeffs import biort as _biort, qshift as _qshift
from pytorch_wavelets.dtcwt.lowlevel import prep_filt
from .lowlevel import mode_to_int
from .lowlevel import ScatLayerj1_f, ScatLayerj1_rot_f
from .lowlevel import ScatLayerj2_f, ScatLayerj2_rot_f
class S... |
11426015 | IMG_H = 40
IMG_W = 40
IMG_C = 1
DEPTH = 17
BATCH_SIZE = 32
EPOCHS = 50
SIGMA = 25
EPSILON = 1e-10
|
11426016 | from keras.models import Model
from keras.layers import Input, Dropout, Masking, Dense, Embedding
from keras.layers import Embedding
from keras.layers.core import Flatten, Reshape
from keras.layers import LSTM
from keras.layers.recurrent import SimpleRNN
from keras.layers import merge
from keras.layers.merge imp... |
11426031 | import os
from pathlib import Path
import flash
import numpy as np
import pandas as pd
import torch
from flash.tabular import TabularClassificationData, TabularClassifier
from sklearn.metrics import accuracy_score, f1_score, roc_auc_score
SEED = 42
def generate_cross_cols(self, df: pd.DataFrame, crossed_cols):
... |
11426070 | from dockerscan import SharedConfig, String
class DockerAnalyzeInfoModel(SharedConfig):
registry = String()
class DockerAnalyzeUploadModel(SharedConfig):
registry = String()
local_file = String()
remote_filename = String(default="")
class DockerAnalyzePushModel(SharedConfig):
registry = String... |
11426079 | import datetime
from gengine.app.cache import clear_all_caches
from gengine.app.tests.base import BaseDBTest
from gengine.app.tests.helpers import create_user, create_achievement, create_variable, create_goals, create_achievement_user
from gengine.app.model import Achievement, Value
class TestEvaluationForMultipleUs... |
11426085 | import os
from django.core.management.base import BaseCommand, CommandError
from uwsgiconf.utils import Fifo
from ...toolbox import SectionMutator
class FifoCommand(BaseCommand):
"""Base for uWSGI control management commands using master FIFO."""
def run_cmd(self, fifo: Fifo, options: dict):
"""Mus... |
11426104 | import binascii
import hashlib
import json
import os
import shutil
import subprocess
import tempfile
class UniversalBinary:
def __init__(self, name, libraries, needy):
self.__name = name
self.__libraries = libraries
self.needy = needy
def name(self):
return self.__name
de... |
11426153 | from . import sklearn_regression as regression
from . import sklearn_classification as classification
|
11426173 | import rospy
from std_msgs.msg import String, Bool
pub = None
def callback(data):
print(data)
pub.publish(True)
def main():
rospy.init_node('Subscriber')
pub = rospy.Publisher('got_it', Bool, queue_size=10)
sub = rospy.Subscriber('chatter', String, callback)
rospy.spin()
if __name__ == "__main__":
try:
... |
11426181 | import sys
import os.path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
from filters import sav_golay
import numpy as np
from numpy.testing import assert_array_equal
import pytest
@pytest.fixture
def my_data():
data = np.array([[100, 1000, 2000, 3000],
[200, 1500, 500,... |
11426187 | import sys
import torch
import torchvision
def main():
m1, m2 = map(load_model, sys.argv[1:3])
d = compare_models(m1, m2)
print("\n%d differences in total." % d)
def load_model(model_path):
model = torchvision.models.resnet50(num_classes=365)
c = torch.load(model_path, map_location="cpu")
st... |
11426189 | from rebus.agent import Agent
@Agent.register
class Wait(Agent):
_name_ = "wait"
_desc_ = "Output any past or future descriptor whose selector starts "\
"with provided string to stdout. Display first 500 characters only."
_operationmodes_ = ('automatic', )
@classmethod
def add_arguments(c... |
11426199 | from lxml import html
import requests
def get_page_title(url):
"""
This is a simple function that returns the title of an HTML page.
:param str url: the URL to an HTML page
:return str: the title (from the HTML "head" section) of the page
"""
response = requests.get(url)
parsed_tree = htm... |
11426238 | import json
import logging
import os
# noinspection PyCompatibility
from dataclasses import dataclass
from io import StringIO
from typing import Any, Dict, List, NewType, Optional, Tuple, Union
from mypy.main import main as mypy_main
from dataclasses_json import DataClassJsonMixin, CatchAll
@dataclass
class User(Da... |
11426248 | import pytest
from Cryptodome import Random
from Cryptodome.Cipher import AES
from sqlalchemy.exc import IntegrityError
from lms.models import ApplicationInstance, ApplicationSettings, ReusedConsumerKey
from tests import factories
class TestApplicationInstance:
def test_it_persists_application_instance(self, db_... |
11426288 | import os,shutil
from ub.utils import admin_cmd
from ub import bot
from ub import bot as borg
spath="./shivamwriter/"
if not os.path.isdir(spath):
os.makedirs(spath)
#made by shivam
# <NAME>
# Keep credits
@bot.on(admin_cmd(pattern=r"replace"))
async def replace(event):
ss=event.text
shivam=ss[9:]
... |
11426289 | import ipywidgets as widgets
from traitlets import List, Unicode
@widgets.register("bonobo-widget.bonobo")
class BonoboWidget(widgets.DOMWidget):
_view_name = Unicode("BonoboView").tag(sync=True)
_model_name = Unicode("BonoboModel").tag(sync=True)
_view_module = Unicode("bonobo-jupyter").tag(sync=True)
... |
11426295 | from boa3.builtin import public
from boa3.builtin.interop.contract import CallFlags, get_call_flags
@public
def main() -> CallFlags:
return get_call_flags()
|
11426300 | import torch
import torch.nn.functional as F
import numpy as np
from utils import logMinExp
from .etc import broadcastSize, selectArgs
def logLogistic(x, mean, logscale, testBroadcastSize=False):
mean, logscale = broadcastSize(x.shape, [mean, logscale], testBroadcastSize)
u = (x - mean) / torch.exp(logscale)
... |
11426311 | from abc import ABC, abstractmethod
class LightSource(ABC):
@abstractmethod
def __init__(self):
pass
@abstractmethod
def get_E(self, E, xx, yy, λ):
pass
|
11426314 | import frappe
def set_item_price_from_bin(bin):
settings = frappe.get_single("POS Bahrain Settings")
if settings.valuation_price_list and settings.valuation_warehouse == bin.warehouse:
item_price = frappe.db.exists(
"Item Price",
{"item_code": bin.item_code, "price_list": setti... |
11426344 | import types
# gives do notation for python, with "yield" statements and enabling python code in between binds
# take from http://www.valuedlessons.com/2008/01/monads-in-python-with-nice-syntax.html
# just made a few changes to let mreturn handle a tuple, and to convert python 2 to 3
# I actually have no idea how this... |
11426373 | import torch
import numpy as np
# tensor size is (batchsize, ...)
# channel0 is void and isn't counted.
def computeIOU(output, label, num_classes = 12):
output1, output2 = torch.max(output, 1)
batchsize = output2.size(0)
output2 = output2.view(batchsize, -1)
label2 = label.view(batchsize, -1)
... |
11426383 | from python.layers.linear_base import SecretLinearLayerBase
from python.linear_shares import secret_op_class_factory
class SecretMatmulLayer(SecretLinearLayerBase):
def __init__(self, sid, LayerName, batch_size, n_output_features, n_input_features=None):
self.batch_size = batch_size
self.n_output_... |
11426396 | import json
from django.http import Http404, HttpResponse, HttpResponseForbidden
from django.shortcuts import get_object_or_404, redirect, render
from django.views import static
from django.views.decorators.http import require_POST
from .conf import settings
from .forms import RevisionForm
from .hooks import hookset
... |
11426435 | from ..util import set_numpy_threads
set_numpy_threads(1)
import numpy as np
import vigra
try:
import hdbscan
except ImportError:
hdbscan = None
from scipy.ndimage import shift
from sklearn.cluster import MeanShift
from sklearn.decomposition import PCA
from .features import (compute_grid_graph,
... |
11426455 | import jax.numpy as np
from jax.scipy.linalg import cho_factor, cho_solve
from utils import inv, symmetric_cubature_third_order, symmetric_cubature_fifth_order, gauss_hermite, \
ensure_positive_precision
pi = 3.141592653589793
def compute_cavity(post_mean, post_cov, site_mean, site_cov, power):
"""
remove... |
11426457 | from requests import request
import pandas
import xml
from io import StringIO
import math
'''
item_data_url: str = "https://raw.githubusercontent.com/gatheringhallstudios/MHWorldData/master/source_data/items/item_base.csv"
crafting_data_url: str = "https://raw.githubusercontent.com/Haato3o/MHWorldData/items-data/source... |
11426470 | import numpy as np
import gym
from gym import error
from gym_cryptotrading.strings import *
class ActionSpace(gym.Space):
lookup = {
0: NEUTRAL,
1: LONG,
2: SHORT
}
def __init__(self):
super(ActionSpace, self).__init__()
def sample(self):
ret... |
11426477 | import numpy as np
import scipy.interpolate as sci
import gzip
import matplotlib
# matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
try:
from matplotlib.backends.backend_tkagg import NavigationToolbar2TkAgg
except ImportError:
from matplotlib.backends.backend_tkagg import... |
11426478 | import pynlpir
import re
from nltk.classify.scikitlearn import SklearnClassifier
from sklearn.svm import SVC, LinearSVC, libsvm, liblinear
from sklearn.naive_bayes import MultinomialNB, BernoulliNB
from sklearn.linear_model import LogisticRegression
from random import shuffle
from nltk.probability import FreqDist, Cond... |
11426503 | import tensorflow as tf
import keras
from keras.datasets import cifar10
from keras.datasets import cifar100
import DenseNet as net
import numpy as np
import sys
from keras.preprocessing.image import ImageDataGenerator
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
device_name = tf.test.gpu_device_name()
if device_... |
11426510 | import sys
import logging
from typing import Union
import numpy as np
import jax
import jax.numpy as jnp
from evojax.algo.base import NEAlgorithm
from evojax.util import create_logger
class CMA_ES(NEAlgorithm):
"""A wrapper around evosax's CMA-ES.
Implementation: https://github.com/RobertTLange/evosax/blob/... |
11426513 | import unittest
class FileHeaderSize(unittest.TestCase):
def runTest(self):
from peachpy.formats.elf.file import FileHeader
import peachpy.arm.abi
file_header = FileHeader(peachpy.arm.abi.arm_gnueabi)
file_header_bytes = file_header.as_bytearray
self.assertEqual(len(file_he... |
11426525 | import sys
import logging
from pydantic import BaseModel
from pydantic_cli import run_and_exit, DefaultConfig
log = logging.getLogger(__name__)
class Options(BaseModel):
"""For cases where you want a global configuration file
that is completely ignored if not found, you can set
CLI_JSON_VALIDATE_PATH =... |
11426542 | import tensorflow as tf
import numpy as np
from .dcsmb import DCSBM
class PAICAN:
"""
Implementation of the method proposed in the paper:
'Bayesian Robust Attributed Graph Clustering: Joint Learning of Partial Anomalies and Group Structure'
by <NAME> and <NAME>,
published at the 32nd AAAI Conferen... |
11426553 | import torch
def weighted_average(predictions, weights):
assert predictions.shape == weights.shape
weights = weights / (torch.sum(weights, dim=0) + 1e-9)
average = torch.sum(weights * predictions, dim=0)
return average
|
11426556 | from typing import Any, Type
import ssz
from eth2.beacon.fork_choice.scoring import BaseForkChoiceScoring, BaseScore
from eth2.beacon.types.blocks import BaseBeaconBlock
from eth2.beacon.types.states import BeaconState
def _score_block_by_higher_slot(block: BaseBeaconBlock) -> int:
return block.slot
class Hig... |
11426564 | import os
from launch import LaunchDescription
from launch_ros.actions import Node
from ament_index_python.packages import get_package_share_directory
from launch_ros.substitutions import FindPackageShare
from launch.substitutions import PathJoinSubstitution
def generate_launch_description():
config_yaml_file = ... |
11426572 | from unittest import TestCase
from unittest.mock import MagicMock
from waves_gateway.storage.coin_block_height_storage_proxy_impl import CoinBlockHeightStorageProxyImpl
from waves_gateway.storage.key_value_storage import KeyValueStorage
from typing import cast
class CoinBlockHeightStorageProxyImplSpec(TestCase):
... |
11426590 | import logging
import voluptuous as vol
from datetime import timedelta
from homeassistant.const import TEMP_CELSIUS ,CONF_LATITUDE, CONF_LONGITUDE,CONF_API_KEY
from homeassistant.helpers.entity import Entity
from homeassistant.components.sensor import PLATFORM_SCHEMA
import homeassistant.helpers.config_validation as c... |
11426594 | from ._fragment import brics
from ._fragment import frag
from ._fragment import recap
from ._fragment import anybreak
from ._fragment import mmpa_frag
from ._fragment import mmpa_cut
from ._assemble import assemble_fragment_iter
from ._assemble import assemble_fragment_order
from ._assemble import break_mol
from ._ass... |
11426613 | import pytest
from parsl import python_app
from parsl.dataflow.memoization import id_for_memo
# this class should not have a memoizer registered for it
class Unmemoizable:
pass
# this class should have a memoizer that always raises an
# exception
class FailingMemoizable:
pass
class FailingMemoizerTestErro... |
11426733 | import logging
from django.conf import settings
from django.db.models import Q
from django.db.models.signals import m2m_changed, post_save
from django.dispatch import receiver
from django.utils import timezone
from qatrack.parts import models
from qatrack.qatrack_core.email import send_email_to_users
logger = loggin... |
11426737 | import asyncio
import binascii
from typing import Dict
from spruned.application.context import ctx
from spruned.application.exceptions import InvalidPOWException
from spruned.application.logging_factory import Logger
from spruned.daemon import exceptions
from spruned.application.tools import blockheader_to_blockhash, d... |
11426827 | white_region = cv2.inRange(cropped, (200, 200, 200), (255, 255, 255))
cv2.imwrite('car_scene_white_region.png', white_region)
cv2.imshow('white_region', white_region)
cv2.waitKey(10000)
|
11426828 | import click
from .abstract import ObjectFormatter
class ShortFormatter(ObjectFormatter):
def format_object_row(self, object):
return object.id
def format_file_detailed(self, object):
return object.id
def format_config_detailed(self, object):
return object.id
def format_blob... |
11426883 | from connect.cli.plugins.product.utils import (
get_col_limit_by_ws_type,
get_ws_type_by_worksheet_name,
)
# This tests exists just to have them on code coverage, real test depends on sync action
def test_get_col_limit_unknown_type():
assert 'Z' == get_col_limit_by_ws_type('UNKNOWN')
def test_get_ws_ty... |
11426919 | import sys
from PyQt5.QtWidgets import *
from PyQt5.uic import loadUi
import os
import cv2
import threeD.loaddicomfile as ldf
import numpy as np
from threeD.vol_view_module import C3dView
class CthreeD(QDialog):
def __init__(self):
super().__init__()
path = os.getcwd()
os.chdir(path + '/th... |
11426935 | from abc import abstractmethod
from typing import Optional
from psqlextra.backend.schema import PostgresSchemaEditor
from psqlextra.models import PostgresPartitionedModel
class PostgresPartition:
"""Base class for a PostgreSQL table partition."""
@abstractmethod
def name(self) -> str:
"""Generat... |
11426967 | from .publish_plugins import (
PublishValidationError,
KnownPublishError,
OpenPypePyblishPluginMixin
)
from .lib import (
DiscoverResult,
publish_plugins_discover
)
__all__ = (
"PublishValidationError",
"KnownPublishError",
"OpenPypePyblishPluginMixin",
"DiscoverResult",
"pub... |
11426984 | from django.conf.urls.defaults import *
urlpatterns = patterns('quran.views',
url(r'^$', 'index', name='quran_index'),
url(r'^(?P<sura_number>\d+)/$', 'sura', name='quran_sura'),
url(r'^(?P<sura_number>\d+)/(?P<aya_number>\d+)/$', 'aya', name='quran_aya'),
url(r'^(?P<sura_number>\d+)/(?P<aya_number>\d+... |
11426995 | from __future__ import absolute_import, division
# import __builtin__
import math
import random
import time
def median(x, use_float=True):
# there exist better algorithms...
y = sorted(x)
if not y:
raise ValueError('empty sequence!')
left = (len(y) - 1)//2
right = len(y)//2
sum = y[lef... |
11426997 | import asyncio
import json
import pytest
from .util import i3msg, i3event
pytestmark = pytest.mark.asyncio
msg_tests = [
(lambda c: c.command('border normal'), 0,
'border normal', '[{"success":true}]'),
(lambda c: c.get_workspaces(), 1, '', '[]'),
(lambda c: c.subscribe(['window', 'output', 'b... |
11427012 | from collections import defaultdict
NO_DEFAULT = object()
class Observable:
"""
:class: Observables are properties that one can bind methods to.
Notes
-----
We store method names instead of methods themselves. This so we can dynamically patch methods on widgets and the new
method will be ca... |
11427059 | palindrome = input("Enter a palindrome : ")
isPalindrome = True;
def palindromeChecker(palindrome):
global isPalindrome
if isPalindrome:
if len(palindrome) < 2:
print("this is a valid palindrome")
else:
if palindrome[0] == palindrome[-1]:
palindro... |
11427118 | import datetime
import logging
import typing
import pandas as pd
from atpy.data.ts_util import overlap_by_symbol
from pyevents.events import EventFilter
class DataReplay(object):
"""Replay data from multiple sources, sorted by time. Each source provides a dataframe."""
def __init__(self):
self._sou... |
11427154 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from pytorch_pretrained_bert.modeling import BertModel, BertPreTrainedModel
from torch.nn import CrossEntropyLoss
class BertForQuestionAnswering(BertPreTrainedModel):
def __init__(self, config):
super(BertForQuestionAnswering,... |
11427187 | import json
import argparse
import spacy
from multiprocessing import Pool
nlp = spacy.load('en')
parser = argparse.ArgumentParser()
parser.add_argument('--input', required=True)
parser.add_argument('--output', required=True)
args = parser.parse_args()
def isalpha(word):
for k in range(len(word)):
if wo... |
11427211 | from vapoursynth import core, GRAYS, RGBS, GRAY, YUV, RGB
# If yuv444 is True chroma will be upscaled instead of downscaled
# If gray is True the output will be grayscale
def Debilinear(src, width, height, yuv444=False, gray=False, chromaloc=None):
return Descale(src, width, height, kernel='bilinear', taps=None, ... |
11427346 | from __future__ import division
import torch
import torch.nn.functional as F
import numpy as np
def horisontal_flip(img, targets):
img = torch.flip(img, [-1])
if targets is not None:
targets[:, 2] = 1 - targets[:, 2]
return img, targets
|
11427402 | import os
import numpy as np
import tensorflow as tf
from models_gqa.model import Model
from models_gqa.config import build_cfg_from_argparse
from util.gqa_train.data_reader import DataReader
# Load config
cfg = build_cfg_from_argparse()
# Start session
os.environ["CUDA_VISIBLE_DEVICES"] = str(cfg.GPU_ID)
sess = tf... |
11427444 | import numpy as np
import sys
import gzip
allS = open(sys.argv[1])
allPeaks = {}
allScores = {}
scores = []
for line in allS:
parts = line.strip().split()
name = parts[0] + ":" + parts[1]
score = float(parts[3])
scores.append(score)
allScores[name] = score
allS.close()
pcs = []
for x in range(1,... |
11427448 | from __future__ import annotations
import json
import re
import subprocess
from itertools import chain, groupby, permutations, product
from operator import itemgetter
from os.path import abspath, dirname, join
from shutil import which
from string import ascii_uppercase, digits
from monty.fractions import gcd
from pym... |
11427449 | import typing
import ast
class Type: pass
class TARR(Type):
def __init__(self, ty):
self.ty = ty
def __str__(self):
return f'List[{self.ty}]'
def __repr__(self):
return self.__str__()
class TTUP(Type):
def __init__(self, ty):
self.ty = ty
... |
11427452 | import re
STRONG_MATCH = "strong"
WEAK_MATCH = "weak"
NO_MATCH = "nomatch"
WITHIN_EXAMPLE_DELIM = "----------------------"
EXAMPLE_DELIM = "----------------------------------------------"
def matches_known_error_patterns(line):
strong_error_patterns = [
r"error:[^=]",
r"fatal:[^=]",
r"pan... |
11427554 | from fontbakery.callable import check
from fontbakery.callable import condition
from fontbakery.checkrunner import Section, PASS, FAIL, WARN
from fontbakery.fonts_profile import profile_factory
from tests.test_general import (
font_family,
font_style,
is_italic,
com_roboto_fonts_check_italic_angle,
... |
11427558 | import unittest
import xml.etree.ElementTree as ET
from mock import MagicMock
from datetime import date
from dexter.models import db
from dexter.models.seeds import seed_db
from dexter.processing import DocumentProcessor
from dexter.processing.extractors import AlchemyExtractor
class TestDocumentProcessor(unittes... |
11427581 | import re
import datetime
import ssl
import shotgun_api3
from vfxClientToolkit.api.config import ConfigBundle
import vfxClientToolkit.api.entities as vfxEntities
ssl._create_default_https_context = ssl._create_unverified_context
cb = ConfigBundle()
CONFIG_DATA = cb.getContexts()
def getShotgunHandle():
"""
... |
11427592 | import tensorflow as tf
import csv
import numpy as np
import os
from func.expression import ENGINE_CONSTANT
import random
class Model():
def __init__(self):
self.X = tf.placeholder(tf.float32,[None,2304])
self.Y = tf.placeholder(tf.int32,[None]) # 0=Angry, 1=Disgust, 2=Fear, 3=Happy, 4=Sad, 5=Surpr... |
11427646 | import warnings
from ..feature_extraction import FPCA
warnings.warn(
'The module "projection" is deprecated. Please use "feature_extraction"',
category=DeprecationWarning,
)
|
11427654 | from django.contrib import admin
# Model import
from news.models import News, NewsTag, CategoryNews
# Register News
class NewsAdmin(admin.ModelAdmin):
list_display = ('__str__', 'status',)
exclude = ('slug',)
autocomplete_fields = ('category',)
admin.site.register(News, NewsAdmin)
# Register Category... |
11427655 | from typing import Union
import torch
from ppq.api.setting import QuantizationSetting
from ppq.core import (ChannelwiseTensorQuantizationConfig,
OperationQuantizationConfig, QuantizationPolicy,
QuantizationProperty, QuantizationStates, RoundingPolicy,
T... |
11427661 | import pandas as pd
import os,sys
from os.path import join
import itertools
def splitall(path):
allparts = []
while 1:
parts = os.path.split(path)
if parts[0] == path: # sentinel for absolute paths
allparts.insert(0, parts[0])
break
elif parts[1] == path: # sent... |
11427721 | try:
import ujson as json
except ImportError:
import json
from uuid import UUID
from flask import Response, request
from pyservice_registry.models import Service
from pyservice_registry.helpers import crossdomain
def _check_input_params(input_vars):
"""
Check all input values are filled
"""
for name, value in... |
11427763 | from __future__ import annotations
from app.utils.geolocation import get_ip_from_request
from decimal import Decimal
from typing import Optional
from uuid import uuid4
from fastapi import Query
from fastapi.exceptions import HTTPException
import pydantic
from pydantic import BaseModel, Field
from pydantic.types import... |
11427778 | from datetime import datetime
BUILD_NUMBER = 'DEV'
BUILD_DATE = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')
BUILD_VCS_NUMBER = 'HEAD'
|
11427780 | from rest_framework.viewsets import ReadOnlyModelViewSet
class BaseReadOnlyModelViewset(ReadOnlyModelViewSet):
"""Amends API response to add CORS headers."""
def dispatch(self, request, *args, **kwargs):
response = super(BaseReadOnlyModelViewset, self).dispatch(request, *args, **kwargs)
respon... |
11427802 | import unittest
from core.cardanopy_config import CardanoPyConfig
from core.cardanopy_common import CardanoPyCommon
from pathlib import Path
import tempfile
import shutil
import os
import yaml
import json
import jsonschema
class TestCardanoPyConfig(unittest.TestCase):
def setUp(self):
self.test_dir = Pat... |
11427825 | import logging
from typing import TYPE_CHECKING, Any, Dict, List, Literal, Tuple
from rotkehlchen.accounting.structures.balance import Balance
from rotkehlchen.assets.asset import EthereumToken, UnderlyingToken
from rotkehlchen.assets.utils import get_or_create_ethereum_token
from rotkehlchen.chain.ethereum.trades imp... |
11427842 | import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
import time
app = dash.Dash()
app.layout = html.Div([
html.Label([
'Input 1',
dcc.Input(id='input-1', type="text")
]),
html.Label([
'Input 2',
... |
11427858 | from a10sdk.common.A10BaseClass import A10BaseClass
class SamplingEnable(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param counters1: {"enum": ["all", "hits"], "type": "string", "description": "'all': all; 'hits': Number of times the IP was selected; ", "format": "e... |
11427860 | from .sca import create_sca
from .sca import create_temporal_reg
from .utils import compute_fisher_z_score
from .utils import check_ts, map_to_roi
# List all functions
__all__ = ['create_sca', \
'compute_fisher_z_score', \
'create_temporal_reg', \
'check_ts', \
'map_to_roi'... |
11427876 | import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
import helpers
class ExtrafieldsPlugin(plugins.SingletonPlugin, toolkit.DefaultDatasetForm):
plugins.implements(plugins.IDatasetForm)
plugins.implements(plugins.IPackageController, inherit=True)
plugins.implements(plugins.IConfigurer)
... |
11427878 | from pypif.util.serializable import Serializable
class MultiQuery(Serializable):
"""
Base class for all multi-search requests.
"""
def __init__(self, queries=None, **kwargs):
"""
Constructor.
:param queries: One or more queries to run.
"""
self._queries = None... |
11427911 | import asyncio
class BaseDecorator:
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def _add_request_payload(self, message):
if message.platform == 'telegram':
kwargs = self.prepare(message)
message._request_payload.update(kwargs)
... |
11427917 | import os, sys
import unittest
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../..'))
from test_environment_device import WuTest
from configuration import *
import random
import string
class TestLocation(unittest.TestCase):
def setUp(self):
self.test = WuTest(False, False)
... |
11427939 | from aerosandbox import ImplicitAnalysis, Opti
import aerosandbox.numpy as np
class IBL2(ImplicitAnalysis):
"""
An implicit analysis for a 2-dimensional integral boundary layer model.
Implements a 2-equation dissipation-based model, partly based on:
* Drela, Mark. "Aerodynamics of Viscous Fluids... |
11428036 | from rest_framework import serializers
from . import models
class BankSerializer(serializers.ModelSerializer):
class Meta:
model = models.Bank
fields = '__all__' |
11428091 | from pygears.lib import check, drv, flatten
from pygears.typing import Uint, Queue
drv(t=Queue[Uint[4]], seq=[[0, 1, 2]]) \
| flatten \
| check(ref=[0, 1, 2])
|
11428096 | def get_image_url_from_request(request, image):
if not image:
return None
return request.build_absolute_uri(image.url)
|
11428103 | import unittest
import xr
class TestVector3f(unittest.TestCase):
def setUp(self):
self.p = xr.Posef()
def tearDown(self):
pass
def test_posef(self):
self.assertEqual(1, self.p.orientation.w)
if __name__ == '__main__':
unittest.main()
|
11428105 | from . import TestGramex
from nose.tools import eq_, ok_
class TestSession(TestGramex):
def test_sms_setup(self):
info = self.get('/sms/info').json()
sms = info['amazonsns']
eq_(sms['cls'], 'AmazonSNS')
eq_(sms['smstype'], 'Transactional')
ok_('botocore.client.SNS' in sms['... |
11428112 | from django.db import models
# Create your models here.
# Create your models here.
class Contact(models.Model):
id = models.AutoField(primary_key=True)
firstname = models.CharField(max_length=40)
lastname = models.CharField(max_length=40)
email = models.EmailField(max_length=40)
content = models.Te... |
11428118 | from model.AbstractRecommender import SocialAbstractRecommender
import tensorflow as tf
import numpy as np
from time import time
from util import learner, tool
from util.tool import csr_to_user_dict
from util import timer
from util import l2_loss
from data import PointwiseSampler
class DiffNet(SocialAbstractRecommend... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.