id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
175457 | import json
from json import JSONDecodeError
import pandas as pd
from requests import post
import yaml
# General class for necessary file imports
class FileImport():
def read_app_key_file(self, filename: str = "keys.json") -> tuple:
"""Reads file with consumer key and consumer secret (JSON)
Args:... |
175464 | from .models import print_image_classifiers, image_classifier
from .models import print_image_regression_models, image_regression_model
from .data import show_image, show_random_images, preview_data_aug, get_data_aug
from .data import images_from_folder, images_from_csv, images_from_array, images_from_fname, preprocess... |
175481 | from .all_pass import all_pass
def positive(x):
return x > 0
def less_than_ten(x):
return x < 10
def all_pass_nocurry_test():
assert all_pass([], "foo")
assert all_pass([positive, less_than_ten], 5)
assert not all_pass([positive, less_than_ten], 10)
assert not all_pass([positive, less_than... |
175501 | from copy import deepcopy
from typing import Any, Optional, Union
import pandas as pd
from pycaret.internal.logging import get_logger
from pycaret.internal.Display import Display
from sklearn.base import clone
from sklearn.utils.validation import check_is_fitted
from sklearn.pipeline import Pipeline
def is_sklearn_p... |
175509 | from requests import Session
from bs4 import BeautifulSoup
import re
class tiktok:
def __init__(self) -> None:
self.request = Session()
self.url = "https://ssstik.io"
self.html = self.request.get(self.url).text
self.key = BeautifulSoup(self.html, "html.parser").find_all("... |
175513 | def less_or_equal(value):
if value : # Change this line
return "25 or less"
elif value : # Change this line
return "75 or less"
else:
return "More than 75"
# Change the value 1 below to experiment with different values
print(less_or_equal(1))
|
175532 | import os
import json
import argus
from argus.callbacks import MonitorCheckpoint, EarlyStopping, LoggingToFile
from torch.utils.data import DataLoader
from src.dataset import SaltDataset, SaltTestDataset
from src.transforms import SimpleDepthTransform, SaltTransform
from src.lr_scheduler import ReduceLROnPlateau
fro... |
175549 | from measurement.measures import Energy
class TestEnergy:
def test_dietary_calories_kwarg(self):
calories = Energy(Calorie=2000)
kilojoules = Energy(kJ=8368)
assert calories.si_value == kilojoules.si_value
|
175644 | from typing import Tuple
import numpy as np
from PyGenetic.crossover import CrossoverDecidor
from PyGenetic.mutation import MutationDecidor
class FactoryPopulation():
def __init__(self):
self.crossover_decidor = CrossoverDecidor(self.crossover_type,
self.... |
175689 | from django.conf.urls import url
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
schema_view = get_schema_view(
openapi.Info(
title="West Oakland Air Quality API",
default_version="v1",
description=(
"West Oakland Air Quality (WOAQ) is a project of OpenOa... |
175693 | import os
import datetime
import torch
def run(parser, dev):
args = parser.parse_args()
## Set gpu ids
str_ids = args.gpu_ids.split(',')
args.gpu_ids = []
for str_id in str_ids:
gpu_id = int(str_id)
if gpu_id >= 0:
args.gpu_ids.append(gpu_id)
if len(args.gpu_ids) > ... |
175717 | from contextlib import closing
import psycopg
class PostgreSQLConnectionChecker:
def __init__(self, **kwargs):
self.host = kwargs.get('host')
self.port = kwargs.get('port')
self.user = kwargs.get('user')
self.password = kwargs.get('password')
self.database = kwargs.get('dat... |
175745 | import tensorflow as tf
import datetime
import numpy as np
import zutils.tf_math_funcs as tmf
from zutils.py_utils import *
from scipy.io import savemat
class OneEpochRunner:
def __init__(
self, data_module, output_list=None,
net_func=None, batch_axis=0, num_samples=None, disp_time_interv... |
175766 | from simple_zpl2 import ZPLDocument
def add_to_zdoc(upc):
zdoc = ZPLDocument()
zdoc.add_barcode(upc)
return zdoc
|
175773 | import unittest, sys, os, io, copy
import numpy as np
import cctk
if __name__ == '__main__':
unittest.main()
class TestOrca(unittest.TestCase):
def test_write(self):
read_path = "test/static/test_peptide.xyz"
path = "test/static/test_peptide.inp"
new_path = "test/static/test_peptide_co... |
175803 | import numpy as np
def sigmoid(x):
indp = np.where(x>=0)
indn = np.where(x<0)
tx = np.zeros(x.shape)
tx[indp] = 1./(1.+np.exp(-x[indp]))
tx[indn] = np.exp(x[indn])/(1.+np.exp(x[indn]))
return tx
def sigmoid_prime(x):
return sigmoid(x) * (1 - sigmoid(x))
def KL_divergence(x, y)... |
175816 | import json
import traceback
import uuid
import datetime
from isodate import duration_isoformat
from motorway.utils import DateTimeAwareJsonEncoder
import logging
class Message(object):
"""
:param ramp_unique_id: the unique message ID delivered back upon completion to the ramp
:param content: any json ser... |
175828 | from __future__ import absolute_import
import sys
from collections import Iterable, Mapping
from kombu.five import string_t
__all__ = ['lazy', 'maybe_evaluate', 'is_list', 'maybe_list']
class lazy(object):
"""Holds lazy evaluation.
Evaluated when called or if the :meth:`evaluate` method is called.
Th... |
175857 | from django.db import transaction
class AtomicMixin(object):
"""
Ensures we rollback db transactions on exceptions.
Idea from https://github.com/tomchristie/django-rest-framework/pull/1204
"""
@transaction.atomic()
def dispatch(self, *args, **kwargs):
return super(AtomicMixin, self).dis... |
175871 | from .windows import add_dock, window, run, persist_layout
from mpldock.common import named
from . import tweaks, backend
__all__ = ['window', 'add_dock', 'tweaks', 'backend', 'run', 'persist_layout']
|
175936 | import pytest
@pytest.mark.parametrize(('f', 't'), [(sum, list), (len, int)])
def test_foo(f, t):
assert isinstance(f([[1], [2]]), t)
def test_bar(): # unparametrized
pass
|
175962 | from chainerui.models.argument import Argument # NOQA
from chainerui.models.asset import Asset # NOQA
from chainerui.models.bindata import Bindata # NOQA
from chainerui.models.command import Command # NOQA
from chainerui.models.log import Log # NOQA
from chainerui.models.project import Project # NOQA
from chainer... |
175981 | BZX = Contract.from_abi("BZX", "0xc47812857a74425e2039b57891a3dfcf51602d5d", interface.IBZx.abi)
TOKEN_REGISTRY = Contract.from_abi("TOKEN_REGISTRY", "0x2fA30fB75E08f5533f0CF8EBcbb1445277684E85", TokenRegistry.abi)
list = TOKEN_REGISTRY.getTokens(0, 100)
for l in list:
iTokenTemp = Contract.from_abi("iTokenTemp", ... |
176000 | from sre_parse import Pattern, SubPattern, parse
from sre_compile import compile as sre_compile
from sre_constants import BRANCH, SUBPATTERN
class _ScanMatch(object):
def __init__(self, match, rule, start, end):
self._match = match
self._start = start
self._end = end
self._rule = ... |
176005 | import pandas as pd
import numpy as np
from os.path import join, exists, split
from os import mkdir, makedirs, listdir
import gc
import matplotlib.pyplot as plt
import seaborn
from copy import deepcopy
from time import time
import pickle
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('split_na... |
176035 | import numpy as np
import pandas as pd
from vimms.old_unused_experimental.PythonMzmine import get_base_scoring_df
from vimms.Roi import make_roi
QCB_MZML2CHEMS_DICT = {'min_ms1_intensity': 1.75E5,
'mz_tol': 2,
'mz_units': 'ppm',
'min_length': 1,
... |
176057 | from django.test import TestCase
from django.test import Client
class Exercise4TestCase(TestCase):
def test_template_content(self):
"""Test that the index view returns the set names from the paramaters, or defaults to 'world'"""
c = Client()
response = c.get('/')
self.assertEqual(r... |
176062 | import connexion
import six
from tapi_server.models.inline_object1 import InlineObject1 # noqa: E501
from tapi_server.models.inline_object12 import InlineObject12 # noqa: E501
from tapi_server.models.inline_object13 import InlineObject13 # noqa: E501
from tapi_server.models.inline_object14 import InlineObject14 # ... |
176082 | from enum import IntEnum
import struct
from .parser import MsftBandParser
from datetime import datetime
from .filetimes import datetime_to_filetime
class NotificationTypes(IntEnum):
"""Complete list of all Notification types"""
SMS = 1
Email = 2
IncomingCall = 11
AnsweredCall = 12
MissedCall =... |
176089 | class Solution:
def rob(self, num):
ls = [[0, 0]]
for e in num:
ls.append([max(ls[-1][0], ls[-1][1]), ls[-1][0] + e])
return max(ls[-1])
|
176099 | import torch.nn as nn
def conv_relu(in_channels, out_channels, kernel_size=3, stride=1,
padding=1, bias=True):
return [
nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size,
stride=stride, padding=padding, bias=bias),
nn.ReLU(inplace=True),
]
def conv_bn_rel... |
176171 | from pathlib import Path
from typing import Tuple
import re
from itertools import groupby
def find_suggestion_for_return(suggestions):
for s in suggestions:
if s.symbol_kind == "class-or-function":
return s
else:
return None
def annotate_line(line, suggestions):
... |
176274 | import torch
import torchvision.transforms as T
import numpy as np
import cv2
from PIL import Image
class DictBatch(object):
def __init__(self, data):
"""
:param data: list of Dict of Tensors.
"""
self.keys = list(data[0].keys())
values = list(zip(*[list(d.values()) for d ... |
176322 | from netaddr import IPAddress
def test_reverse_dns_v4():
assert IPAddress('172.24.0.13').reverse_dns == '192.168.3.11.in-addr.arpa.'
def test_reverse_dns_v6():
assert IPAddress('fe80::feeb:daed').reverse_dns == ('d.e.a.d.b.e.e.f.0.0.0.0.0.0.0.0.'
'0.0.0... |
176326 | def main():
# equilibrate then isolate cold finger
info('Equilibrate then isolate coldfinger')
close(name="C", description="Bone to Turbo")
sleep(1)
open(name="B", description="Bone to Diode Laser")
sleep(20)
close(name="B", description="Bone to Diode Laser")
|
176370 | import vcs
import sys
import os
# This test checks that png size is indeed controled by user
import struct
def get_image_info(fnm):
data = open(fnm,"rb").read()
w, h = struct.unpack('>LL', data[16:24])
width = int(w)
height = int(h)
return width, height
x=vcs.init()
x.drawlogooff()
x.setantiali... |
176374 | import nose.tools as nt
import numpy as np
import theano
import theano.tensor as T
import treeano
import treeano.nodes as tn
from treeano.sandbox.nodes import resnet
fX = theano.config.floatX
def test_zero_last_axis_partition_node():
network = tn.SequentialNode(
"s",
[tn.InputNode("i", shape=(No... |
176408 | import os
from dataloaders.visual_genome import VG, vg_collate
from lib.utils import define_model, load_ckpt, do_test
from config import cfg
from torch.utils.data import DataLoader
test_data = VG(cfg.test_data_name, num_val_im=5000, filter_duplicate_rels=True,
use_proposals=cfg.use_proposals, filter_no... |
176423 | from abc import ABC
from abc import abstractmethod
class GAN(ABC):
@property
@abstractmethod
def generators(self):
raise NotImplementedError
@property
@abstractmethod
def discriminators(self):
raise NotImplementedError
@abstractmethod
def predict(self, inputs):
... |
176429 | import numpy as np
import pytest # noqa: F401
from pandas_datareader._utils import RemoteDataError
from epymetheus.datasets import fetch_usstocks
# --------------------------------------------------------------------------------
def test_toomanyasset():
"""
Test if fetch_usstocks raises ValueError
when... |
176440 | from franka_interface_msgs.msg import SensorData, SensorDataGroup
def sensor_proto2ros_msg(sensor_proto_msg, sensor_data_type, info=''):
sensor_ros_msg = SensorData()
sensor_ros_msg.type = sensor_data_type
sensor_ros_msg.info = info
sensor_data_bytes = sensor_proto_msg.SerializeToString()
sensor... |
176457 | import re
def get_pars(text):
pars = re.findall(r'\[[0-9]+\]\n*(.*)', text)
pars = [p.strip() for p in pars]
return pars
def get_claims(text):
claims = re.findall(r'.*claim.*', text, re.IGNORECASE)
return claims
def get_claim_body(text):
match = re.search(r'^claim[s*]$', text, re.IGNORECASE |... |
176487 | from petisco.base.domain.message.message import Message
from petisco.base.domain.message.message_bus import MessageBus
class NotImplementedMessageBus(MessageBus):
def publish(self, message: Message):
self._check_is_message(message)
meta = self.get_configured_meta()
_ = message.update_meta(... |
176490 | import asyncio
import time
from telegram import main
import json
from sql_util import get_phone, change_status
from message_util import get_phone_test, cancel_all_recv
from config import message_token
from check_util import check_main
from myLogger import log_main
def run(phone, category):
loop = asyncio.get_eve... |
176514 | import numpy as np
import torch
import torch.nn as nn
from habitat_baselines.common.utils import Flatten
from habitat_baselines.rl.models.simple_cnn import SimpleCNN
class Contiguous(nn.Module):
r"""Converts a tensor to be stored contiguously if it is not already so.
"""
def __init__(self):
super... |
176527 | import time
import cv2
import pyscreenshot as ImageGrab
import numpy as np
class Screenshot(object):
def get_frame(self):
img = np.array(ImageGrab.grab().convert('RGB'), dtype=np.uint8)
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
ret2, jpeg = cv2.imencode('.jpg', img)
return jpeg.tos... |
176576 | import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import GraphConv
class DominantModel(nn.Module):
def __init__(self, A_norm, dim_in, dim_out=16):
super(DominantModel, self).__init__()
self.gcn1 = GraphConv.GCN(A_norm, dim_in, 64)
self.gcn2 = GraphConv.GC... |
176588 | from qgis.core import *
from osgeo import gdal
import math
import numpy as np
import os
MARGIN = 0.01
def weightedFunction(x, y, x0, y0, weight):
# the current weighted Function is a simple sqrt((x-x0)^1 + (y-y0)^2)/w
return math.sqrt((x - x0) ** 2 + (y - y0) ** 2) / weight
#Get the points vector layer
pointsVecto... |
176606 | import warnings
from math import ceil
import numpy as np
import openmdao.api as om
from wisdem.landbosse.model.Manager import Manager
from wisdem.landbosse.model.DefaultMasterInputDict import DefaultMasterInputDict
from wisdem.landbosse.landbosse_omdao.OpenMDAODataframeCache import OpenMDAODataframeCache
from wisdem.l... |
176616 | from collections import deque
class PushSwapStacks:
"""
describe stacks for push-swap algorithm
"""
def __init__(self, initstate):
""" initstate: Iterable[_T]=..."""
self.stack_a = deque()
self.stack_b = deque()
self.new_data(initstate)
self.cmd = {
'pa': self.pa,
'pb': self.pb,
'sa': self.sa,... |
176619 | import logging
from datetime import datetime
import zmq
from .handler import Handler
LOGGER = logging.getLogger(__name__)
class ZmqHandler(Handler):
"""Zmq handler.
"""
def __init__(self, connection, **kwargs):
"""Constructor.
"""
super().__init__(**kwargs)
self._connec... |
176624 | import gpu
import bgl
from gpu_extras.batch import batch_for_shader
class BL_UI_Widget:
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.x_screen = x
self.y_screen = y
self.width = width
self.height = height
self._bg_color = (0.8, 0.8... |
176642 | import math
import torch
from torch import nn as nn
class JSD(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x, eps=1e-8):
logN = math.log(float(x.shape[0]))
y = torch.mean(x, 0)
y = y * (y + eps).log() / logN
y = y.sum()
x = x * (x + e... |
176646 | import os
import sys
sys.path.append(os.path.normpath(os.path.join(os.path.abspath(__file__), '..', '..', '..', "common")))
from env_indigo import *
indigo = Indigo()
# indigo::SmilesLoader::Error
try:
m = indigo.loadMolecule('CX')
except IndigoException as e:
print(getIndigoExceptionText(e))
# IndigoError
t... |
176660 | from numpy import genfromtxt
import matplotlib
# matplotlib.use('Agg')
import matplotlib.pyplot as plt
''' ResNet-56 '''
train_error_52 = './epoch_error_train_52.csv'
train_error_52 = genfromtxt(train_error_52, delimiter=',')
valid_error_52 = './epoch_error_valid_52.csv'
valid_error_52 = genfromtxt(valid_error_52, de... |
176663 | import subprocess
from ctypes import *
# I know, i know, this is probably the worst solution to a trivial challenge. Still, if it aint broke...
class Ambient:
def __init__(self):
self.user32 = WinDLL("user32.dll")
def change_color(self, r,g,b):
rgb = r + (g<<8) + (b<<16)
self.user32.S... |
176738 | import sys
from progress.bar import FillingSquaresBar
from time import sleep
from colored import fg, bg, attr, fore, style
from colored import stylize
from functools import wraps
from colored import fg, bg, attr, fore, style
def prefix(item):
'''
This function decorates the other functions with bars
''' ... |
176783 | import os
import importlib
path = __file__.replace("__init__.py", "")
for file in os.listdir(path):
if "__" not in file:
globals()[file[:-3]] = getattr(importlib.import_module(__name__+"."+file[:-3]), file[:-3])
|
176791 | import base64
import datetime
import hashlib
from io import BytesIO
from logging import getLogger
import OpenSSL.crypto
import asn1crypto.ocsp
import pytz
from OpenSSL import crypto
from OpenSSL.crypto import X509StoreContextError
from asn1crypto import pem
from bankid.experimental.helper import CompletionDataContain... |
176801 | import rqalpha
config = {
"extra": {
"log_level": "verbose",
},
"mod": {
"live_trade": {
"lib": "./mod",
"enabled": True,
"priority": 100,
}
}
}
def run(baseConf):
config["base"] = baseConf
return rqalpha.run(config)
|
176818 | print(open('teste_win1252.txt', errors='strict').read())
print(open('teste_win1252.txt', errors='replace').read())
print(open('teste_win1252.txt', errors='ignore').read())
print(open('teste_win1252.txt', errors='surrogateescape').read())
print(open('teste_win1252.txt', errors='backslashreplace').read())
|
176827 | import pytest
import grpc
import uuid
from threading import Event
import yandex.cloud.compute.v1.zone_service_pb2_grpc as zone_service_pb2_grpc
import yandex.cloud.compute.v1.zone_service_pb2 as zone_service_pb2
from yandexcloud import RetryInterceptor
from yandexcloud import default_backoff, backoff_linear_with_jit... |
176834 | class FakeConfig(object):
def __init__(
self,
src_dir=None,
spec_dir=None,
stylesheet_urls=None,
script_urls=None,
stop_spec_on_expectation_failure=False,
stop_on_spec_failure=False,
random=True
):
self._src_... |
176837 | import os
import shutil
import time
import glob
import subprocess
import web
from libs import utils, form_utils
from libs.logger import logger
import settings
subscription_versions = ['normal', 'nomail', 'digest']
def __get_ml_dir(mail):
"""Get absolute path of the root directory of mailing list account."""
... |
176856 | import numpy
from amuse.test import amusetest
from amuse.units import units, nbody_system
from amuse.ic.brokenimf import *
# Instead of random, use evenly distributed numbers, just for testing
default_options = dict(random=False)
class TestMultiplePartIMF(amusetest.TestCase):
def test1(self):
print(... |
176863 | import logging
from sqlalchemy.orm import joinedload
import smartdb
from model import Machine, Schedule, MachineInterface
logger = logging.getLogger(__file__)
class ScheduleRepository:
__name__ = "ScheduleRepository"
def __init__(self, smart: smartdb.SmartDatabaseClient):
self.smart = smart
@... |
176896 | from djangoevents.domain import BaseAggregate
from djangoevents.domain import DomainEvent
from djangoevents.utils_abstract import abstract
from ..utils import camel_case_to_snake_case
from ..utils import list_aggregate_events
from ..utils import list_concrete_aggregates
from ..utils import _list_subclasses
from ..utils... |
176944 | from pybluemonday import UGCPolicy, StrictPolicy, NewPolicy
from collections import namedtuple
Case = namedtuple("Case", ["input", "output"])
def test_StrictPolicy():
cases = [
Case(input="Hello, <b>World</b>!", output="Hello, World!"),
Case(input="<blockquote>Hello, <b>World</b>!", output="Hello... |
176980 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from builtins import *
import numpy as np
from .rnn_base import RNNBase
from .utils import SymbolTable
class TextRNN(RNNBase):
"""TextRNN for strings of text."""
... |
176989 | import numpy as np
import matplotlib
# matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
from typing import *
import pandas as pd
import seaborn as sns
import math
sns.set()
class Accuracy(object):
def at_radii(self, radii: np.ndarray):
raise NotImplementedError()
class ApproximateAccuracy(Accur... |
177050 | from .trainer import Trainer, STOP_TIME
from .my_checkpoint_management import MyCheckpointManager
import signal
class EvolutionTrainer(Trainer):
def __init__(
self,
root_dir,
evolutions,
keep_checkpoint_steps,
save_interval_minutes=30,
signal_handler_signals=(signa... |
177127 | from typing import List
from deeppavlov.core.common.registry import register
@register("sentseg_restore_sent")
def SentSegRestoreSent(batch_words: List[List[str]], batch_tags: List[List[str]]) -> List[str]:
ret = []
for words, tags in zip(batch_words, batch_tags):
if len(tags) == 0:
ret.a... |
177130 | import os
import numpy as np
import pandas as pd
import h5py
from bmtk.utils.sonata.utils import add_hdf5_magic, add_hdf5_version
def create_single_pop_h5():
h5_file_old = h5py.File('spike_files/spikes.old.h5', 'r')
node_ids = h5_file_old['/spikes/gids']
timestamps = h5_file_old['/spikes/timestamps']
... |
177140 | from .imgurdownloader import ImgurDownloader # NOQA
# defining __version__ variable is pointless
__author__ = '<NAME> <<EMAIL>>'
__all__ = []
|
177156 | import hashlib
import hmac
import time
class BitfinexAuth():
def __init__(self, api_key: str, secret_key: str):
self.api_key = api_key
self.secret_key = secret_key
self.last_nonce = 0
def _sign_payload(self, payload) -> str:
sig = hmac.new(self.secret_key.encode('utf8'),
... |
177178 | import functools
import glob
import os
import shlex
from typing import Callable, Iterable, List, Optional, Tuple
from bs4 import BeautifulSoup, Comment, Doctype
from mitmproxy import ctx, http
import modules.arguments as A
import modules.constants as C
import modules.csp as csp
import modules.inject as inject
import ... |
177220 | from marshmallow import INCLUDE, Schema, fields, post_load, pre_load
class Urls:
def __init__(
self,
digital_purchase_date=None,
foc_date=None,
onsale_date=None,
unlimited_date=None,
wiki=None,
detail=None,
**kwargs,
):
self.digital_purch... |
177235 | import os
import shutil
import readdy
import tempfile
import unittest
import numpy as np
class TestTopologyReactionCount(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
cls.dir = tempfile.mkdtemp("test-topology-reaction-count")
@classmethod
def tearDownClass(cls) -> None:
... |
177272 | Import("env")
import os
import tempfile
def cprint(*args, **kwargs):
print(f'pre_script_patch_debug.py:', *args, **kwargs)
def get_winterrupts_path():
winterrupts_path = None
for pio_package in env.PioPlatform().dump_used_packages():
pio_dir = env.PioPlatform().get_package_dir(pio_package['name... |
177332 | import pytest
from ymmsl import Reference, Settings
from libmuscle.settings_manager import SettingsManager
@pytest.fixture
def settings_manager() -> SettingsManager:
return SettingsManager()
def test_create(settings_manager):
assert len(settings_manager.base) == 0
assert len(settings_manager.overlay) =... |
177350 | import logging
import codecs
from scribeui_pyramid.modules.maps.models import Map
from scribeui_pyramid.modules.workspaces.models import Workspace
from BeautifulSoup import BeautifulStoneSoup
from pyramid.view import view_config
from pyramid.response import FileResponse
from sqlalchemy.orm.exc import NoResultFound
l... |
177378 | from django.test import TestCase
from rest_framework import serializers
class EmptySerializerTestCase(TestCase):
def test_empty_serializer(self):
class FooBarSerializer(serializers.Serializer):
foo = serializers.IntegerField()
bar = serializers.SerializerMethodField('get_bar')
... |
177414 | from datetime import datetime
import os
from collections import defaultdict
import os
import yaml
from .postgresql_manager import PostgreSQL_Manager
ROOT_DIR = os.path.abspath(os.path.dirname(__file__))
class OpenDataWriter(object):
def __init__(self, config):
self._config = config
allowed_fie... |
177415 | import json
import logging
import os
import re
import sys
import urllib.parse
from urllib.error import HTTPError, URLError
from urllib.request import Request
import praw
import requests
import yaml
from shared.exceptions import AlreadyProcessed
def load_configuration():
conf_file = os.path.join(os.path.dirname(... |
177493 | from __future__ import division, print_function
import tensorflow as tf
import wave, os, sys
import soundfile as sf
import numpy as np
import librosa
from datetime import datetime
def create_adam_optimizer(learning_rate, momentum):
return tf.train.AdamOptimizer(learning_rate=learning_rate, epsilon=1e-6)
def cre... |
177577 | from app.extensions import db
class User(db.Document):
"""User model """
username = db.StringField()
password = db.StringField()
def to_json2(self):
"""Returns a json representantion of the user.
:returns: a json object.
"""
return {
'id': str(self.id),... |
177580 | class Marker(object):
def __init__(self):
self._body = None
def make(self):
raise NotImplementedError
def update(self, marker):
pass
def show(self):
if self._body is None:
self._body = self.make()
self.update(self._body)
def hide(self):
... |
177626 | from bs4 import BeautifulSoup
import urlparse
import datetime
from scraper import *
class General(Scraper):
def log_index_page(self):
"""Logs the index page, used for test purposes"""
url = self.url_provider.get_page_url('overview')
res = self.open_url(url)
self.logger.info(res.rea... |
177658 | import torch
import torch.optim as optim
import torch.nn.functional as F
import numpy as np
import thinplate as tps
from numpy.testing import assert_allclose
def test_pytorch_grid():
c_dst = np.array([
[0., 0],
[1., 0],
[1, 1],
[0, 1],
], dtype=np.float32)
c_src =... |
177671 | import io
import asyncio
import threading
import queue
import logging
from starlette import concurrency
logger = logging.getLogger('vaex.file.async')
class WriteStream(io.RawIOBase):
'''File like object that has a sync write API, and a generator as consumer.
This is useful for letting 1 thread write t... |
177681 | import unittest
from katas.kyu_7.sum_squares_of_numbers_in_list_that_may_contain_more_lists \
import SumSquares
class SumSquaresTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(SumSquares([1, 2, 3]), 14)
def test_equal_2(self):
self.assertEqual(SumSquares([[1, 2], 3]... |
177684 | import numpy as np
import pybullet as p
import pybullet_data as pd
import pybullet_utils.bullet_client as bc
from gym import spaces
try:
from .. import Environment
from .robots import get_robot
from .tasks import get_task
except ImportError:
from karolos.environments import Environment
from karolos... |
177685 | from typing import Any
from graphscale.grapple.graphql_printer import print_graphql_defs
from graphscale.grapple.parser import parse_grapple
def assert_graphql_def(snapshot: Any, graphql: str) -> None:
result = print_graphql_defs(parse_grapple(graphql))
snapshot.assert_match(result)
def test_basic_type(sna... |
177773 | def test_logout(ui):
driver = ui.driver
driver.find_element_by_css_selector(".user-dropdown").click()
driver.find_element_by_css_selector(".logout-button").click()
assert driver.find_element_by_css_selector('.login-form')
def test_recorded_sessions_visible(ui_session):
assert ui_session is not Non... |
177807 | user_input = 999
while user_input != "0":
user_input = input("์ญ์ง์ ์ซ์๋ฅผ ์
๋ ฅํด์ฃผ์ธ์ : ")
try:
decimal_number = int(user_input)
print(bin(decimal_number))
except ValueError as e:
print(e)
print("Error - 10์ง์ ์ซ์๋ง ์
๋ ฅํด์ฃผ์๊ธฐ ๋ฐ๋๋๋ค.")
|
177847 | import json
import re
import requests
from rich.console import Console
LOGIN_URL = "https://www.headspace.com/login"
AUTH_URL = "https://auth.headspace.com/co/authenticate"
BEARER_TOKEN_URL = "https://auth.headspace.com/authorize"
session = requests.Session()
console = Console()
headers = {
"User-Agent": "Mozil... |
177873 | import ctypes
import numpy as np
from devito.tools.utils import prod
__all__ = ['numpy_to_ctypes', 'numpy_to_mpitypes', 'numpy_view_offsets']
def numpy_to_ctypes(dtype):
"""Map numpy types to ctypes types."""
return {np.int32: ctypes.c_int,
np.float32: ctypes.c_float,
np.int64: ctype... |
177895 | import argparse
import fnmatch
import os
import pathlib
import sys
import textwrap
import yaml
def write_header(output):
header='''
###
# This file is automatically generated by {}. Do not edit!
###
'''
output.write(textwrap.dedent(header.format(os.path.basename(__file__))).lstrip())
outp... |
177909 | class CloudWatchEvent:
def __init__(self,
schedule_expression: str,
is_active: bool,
name: str =None):
self.name = name
self.schedule_expression = schedule_expression
self.is_active = is_active
|
177964 | from app import __metadata__ as meta
from configparser import ConfigParser, ExtendedInterpolation
from pathlib import Path
from shutil import copy
import os
import io
import logging
log = logging.getLogger(__name__)
APP = meta.APP_NAME
'''
This component is responsible for configuration management.
If this is the fir... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.