id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
464469 | import re
import string
from urllib.parse import quote as urlquote, urlsplit
from libweasyl.cache import region
from weasyl import define as d
_BANDCAMP_EMBED = re.compile(r"(album|track)=(\d+)")
_OEMBED_MAP = {
"youtube": "https://www.youtube.com/oembed?url=%s&maxwidth=640&maxheight=360",
"vimeo": "https... |
464520 | import json
from django.core.exceptions import ValidationError
from django_sorcery import fields
from django_sorcery.forms import (
apply_limit_choices_to_form_field,
modelform_factory,
)
from .base import TestCase
from .testapp.models import CompositePkModel, Owner, Vehicle, VehicleType, db
class TestEnumF... |
464533 | from unittest import TestCase
import pyrealsense as pyrs
from pyrealsense.utils import RealsenseError
class Test_Service_Device(TestCase):
def test_is_started(self):
try:
service = pyrs.Service()
except RealsenseError as e:
self.assertTrue(e.function == 'rs_create_context')... |
464535 | from torch.onnx import register_custom_op_symbolic
# Register symbolic op for torch.quantize_function op.
def _fake_quantize_learnable_per_tensor_affine(g, x, scale, zero_point, quant_min, quant_max, grad_factor):
return g.op("::LearnablePerTensorAffine", x, scale, zero_point, quant_min, quant_max)
register_cus... |
464537 | from FWCore.PythonFramework.CmsRun import CmsRun
import FWCore.ParameterSet.Config as cms
process = cms.Process("Test")
process.source = cms.Source("EmptySource")
nEvents = 10
process.maxEvents = cms.untracked.PSet(input = cms.untracked.int32(nEvents))
var = 5
outList = []
process.m = cms.EDProducer("edmtest::Pyth... |
464590 | import json
import os
import re
import datetime
import tempfile
import six
from requests_toolbelt.multipart import decoder
import asposewordscloud.models
from asposewordscloud.api_client import rest
class BaseRequestObject(object):
PRIMITIVE_TYPES = (float, bool, bytes, six.text_type) + six.integer_types
NAT... |
464594 | from bip.gui import *
import pytest
"""
Test for class :class:`BipUserSelect` in ``bip/gui/userselect.py``.
"""
def test_bipuserselect00():
# staticmethod
# as complicated to test only call them for checking of API problems
BipUserSelect.get_curr_highlighted_str()
BipUserSelect.get_curr_highlight... |
464602 | import numpy as np
import scipy.signal
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
import utils_hw as utils
from dataset import BaseDataset
class HandWritingDataset(BaseDataset):
"""
Customized for handwriting dataset.
Stroke data is assumed to be consi... |
464614 | from neuron.neuron import Neuron
import numpy as np
class NeuronBuilder:
zero_quantization_error = None
def __init__(self, tau_2, growing_metric):
self.__growing_metric = growing_metric
self.__tau_2 = tau_2
def new_neuron(self, weights_map, position):
assert self.zero_quantizatio... |
464625 | import torch
import numpy as np
def get_sigmas(config):
if config.model.sigma_dist == 'geometric':
sigmas = torch.tensor(
np.exp(np.linspace(np.log(config.model.sigma_begin), np.log(config.model.sigma_end),
config.model.num_classes))).float().to(config.device)
... |
464654 | default_app_config = "rest_live.apps.RestLiveConfig"
DEFAULT_GROUP_BY_FIELD = "pk"
def get_group_name(model_label) -> str:
return f"RESOURCE-{model_label}"
CREATED = "CREATED"
UPDATED = "UPDATED"
DELETED = "DELETED"
|
464675 | import yaml, os
from github import Github
class GitHubController(object):
def __init__(self):
token = self.__get_token_from_env_variable()
if not token:
token = self.__get_token_from_config()
self.github = Github(token)
def __get_token_from_env_variable(self):
if ... |
464699 | from torch.utils.data import Dataset
import glob
import os
from PIL import Image
import cv2
import numpy as np
import h5py
import skimage.io
import skimage.color
import scipy.io as io
class BigDataset(Dataset):
def __init__(self, mode="train", **kwargs):
self.big_list = self.get_big_data()
self.r... |
464725 | while True:
num = int(input())
if num == 0:
break
a = 0
b = 0
turn_a = True
i = 0
while num != 0:
bit = num & 1
num = num >> 1
if bit == 1:
if turn_a:
a ^= (1 << i)
else:
b ^= (1 << i)
turn_a = not turn_a
i += 1
print ("{} {}".format(a, ... |
464727 | import scipy.optimize as opt
import numpy as np
import pylab as plt
#define model function and pass independant variables x and y as a list
def twoD_Gaussian(xy, amplitude, xo, yo, sigma_x, sigma_y, theta, offset):
x = xy[0]
y = xy[1]
xo = float(xo)
yo = float(yo)
a = (np.cos(theta)**2)/(2*sig... |
464741 | import uuid
import kubernetes
import pytest
import pykorm
class Score(pykorm.models.Nested):
exterior: int = pykorm.fields.DataField('exterior')
delicious: int = pykorm.fields.DataField('delicious', 10)
class ScoreMixin(object):
score: Score = pykorm.fields.DictNestedField(Score, path=['spec', 'score'... |
464754 | from . import vocab
from . import tokenizers
from . import batchify
from .vocab import *
__all__ = ['batchify', 'tokenizers'] + vocab.__all__
|
464797 | from pybilt.bilayer_analyzer import BilayerAnalyzer
def test_leaflet_builder():
sel_string = "resname POPC DOPE TLCL2"
name_dict = {'DOPE':['P'],'POPC':['P'],'TLCL2':['P1','P3']}
analyzer = BilayerAnalyzer(structure='../pybilt/sample_bilayer/sample_bilayer.psf',
trajectory... |
464802 | import cv2
import numpy as np
import matplotlib.pyplot as plt
# Nereset Neighbor interpolation
def nn_interpolate(img, ax=1, ay=1):
H, W, C = img.shape
aH = int(ay * H)
aW = int(ax * W)
y = np.arange(aH).repeat(aW).reshape(aH, -1)
x = np.tile(np.arange(aW), (aH, 1))
y = np.round(y / ay).astype(np.int)
x = np... |
464884 | import cmath
import math
import numpy
import scipy.sparse.linalg
import time
import sys
from pauxy.propagation.operations import local_energy_bound
from pauxy.utils.linalg import exponentiate_matrix, reortho
from pauxy.walkers.single_det import SingleDetWalker
class PlaneWave(object):
"""PlaneWave class
"""
... |
464885 | class DistanceMeasureBase(object):
@staticmethod
def distances(fixed_x, fixed_y, x_vec, y_vec):
'''
:param fixed_x: float
:param fixed_y: float
:param x_vec: np.array[float]
:param y_vec: np.array[float]
:return: np.array[float]
'''
raise NotImple... |
464921 | from schema.parsers.opengraph import format_og
def test_format_og():
data = {
"namespace": {"og": "http://ogp.me/ns#"},
"properties": [
("og:description",
"Free Shipping on orders over $35. Buy Dungeons & Dragons Player's Handbook (Dungeons & Dragons Core Rulebooks) at Wal... |
465012 | import sys
import GPUtil
import importlib
import logging
import multiprocessing as mp
import os
import traceback
import click
from toml import TomlDecodeError
from tqdm import tqdm
from multiprocessing import Queue, Event, Process
from multiprocessing.queues import Empty as QueueEmpty
from exp.params import ParamSpac... |
465050 | from .entity import EntityType, Entity
from .validator import PropertyValidator
from .endpoint import EndpointType
# Endpoint Payload
class EndpointPayloadType(EntityType):
__schema_name__ = "EndpointPayload"
__openapi_type__ = "endpoint_payload"
class EndpointPayloadValidator(PropertyValidator, openapi_t... |
465057 | import panel as pn
from .compatibility import logger
from .sigslot import SigSlot
TEXT = """
Convert data variables to coordinates to use them as axes. For more information,
please refer to the [documentation](https://xrviz.readthedocs.io/en/latest/interface.html#set-coords).
"""
class CoordSetter(SigSlot):
"""
... |
465059 | from lepo.apidef.doc import APIDefinition
from lepo.parameter_utils import read_parameters
from lepo_tests.tests.utils import make_request_for_operation
doc = APIDefinition.from_yaml('''
openapi: 3.0.0
servers: []
paths:
/single/{thing}/data{format}:
get:
parameters:
- name: format
in: pa... |
465070 | import re
from dateutil.parser import parse
from django.utils.translation import ugettext_lazy as _
from .classes import MetadataParser
class DateAndTimeParser(MetadataParser):
label = _('Date and time parser')
def execute(self, input_data):
return parse(input_data).isoformat()
class DateParser(... |
465110 | import logging
import typing
from .node_data import NodeData, NodeDataModel, NodeDataType
from .type_converter import TypeConverter
logger = logging.getLogger(__name__)
class DataModelRegistry:
def __init__(self):
self.type_converters = {}
self._models_category = {}
self._item_creators =... |
465138 | import random
from rlkit.exploration_strategies.base import RawExplorationStrategy
class EpsilonGreedy(RawExplorationStrategy):
"""
Take a random discrete action with some probability.
"""
def __init__(self, action_space, prob_random_action=0.1):
self.prob_random_action = prob_random_action
... |
465181 | import os
class Config:
API_KEY = os.environ['OST_KYC_API_KEY']
API_SECRET = os.environ['OST_KYC_API_SECRET']
API_BASE_URL = os.environ['OST_KYC_API_ENDPOINT']
test_obj_for_signature = {
'k1': 'Rachin',
'k2': 'tejas',
'list2': [
{'a': 'L21A', 'b': 'L21B'},
... |
465191 | from typing import List
import numpy as np
from bartpy.mutation import TreeMutation
from bartpy.node import TreeNode, LeafNode, DecisionNode, deep_copy_node
class Tree:
"""
An encapsulation of the structure of a single decision tree
Contains no logic, but keeps track of 4 different kinds of nodes within... |
465259 | import pytest
from .conftest import CollectingQueryRunner
from graphdatascience.graph_data_science import GraphDataScience
from graphdatascience.model.graphsage_model import GraphSageModel
from graphdatascience.model.model import Model
from graphdatascience.server_version.server_version import ServerVersion
MODEL_NAM... |
465335 | from gazette.spiders.base.fecam import FecamGazetteSpider
class ScPresidenteGetulioSpider(FecamGazetteSpider):
name = "sc_presidente_getulio"
FECAM_QUERY = "cod_entidade:211"
TERRITORY_ID = "4214003"
|
465350 | import numpy as np
import tensorflow as tf
def f_net(dimH, name):
print 'add in 1 hidden layer mlp...'
W1 = tf.Variable(tf.random_normal(shape=(dimH, ))*0.01, name = name + '_W1')
b1 = tf.Variable(tf.random_normal(shape=(dimH, ))*0.01, name = name + '_b1')
#W2 = tf.Variable(tf.random_normal(shape=(dimH... |
465365 | from stix2.v21 import (Bundle)
for obj in bundle.objects:
if obj == threat_actor:
print("------------------")
print("== THREAT ACTOR ==")
print("------------------")
print("ID: " + obj.id)
print("Created: " + str(obj.created))
print("Modified: " + str(obj.modified))
... |
465376 | from django.utils.timezone import now
from model_bakery.recipe import Recipe
from tests.generic.models import Person
person = Recipe(
Person,
name="Uninstalled",
nickname="uninstalled",
age=18,
bio="Uninstalled",
blog="http://uninstalled.com",
days_since_last_login=4,
birthday=now().da... |
465420 | import dataclasses
import enum
import typing
# An account identifier may be a byte array of 33 bytes,
# a hexadecimal string of 66 characters.
AccountID = typing.Union[bytes, str]
# A block identifier may be a byte array of 32 bytes,
# a hexadecimal string of 64 characters or a positive integer.
BlockID = typing.Uni... |
465433 | from app.db.base_class import Base
from sqlalchemy import ForeignKey, Integer, Column, String, Boolean
from app.core.config import settings
class Role(Base):
"""
A world can have multiple roles.
"""
role_id = Column(Integer, primary_key=True, autoincrement=True)
world_id = Column(
Integer... |
465447 | import unittest
import numpy
import pandas as pd
import scipy.sparse
import scipy.sparse.csr
import sklearn.linear_model
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
import willump.evaluation.willump_executor as wexec
with open("tests/test_re... |
465450 | import torch
import torch.nn as nn
from fewshots.models import register_model
from fewshots.models import r2d2, lrd2
from fewshots.utils import norm
def _norm(num_channels, bn_momentum, groupnorm=False):
if groupnorm:
return norm.GroupNorm(num_channels)
else:
return nn.BatchNorm2d(num_channel... |
465467 | from dataclasses import dataclass
from typing import List
from osbenchmark.telemetry import Telemetry
@dataclass
class Node:
"""A representation of a node within a host"""
name: str
port: int
pid: int
root_dir: str
binary_path: str
log_path: str
heap_dump_path: str
data_paths: Li... |
465486 | from AC3utils import PLUGIN_BASE, PLUGIN_VERSION
from Components.ActionMap import NumberActionMap
from Components.Button import Button
from Components.ConfigList import ConfigListScreen
from Components.Label import Label
from Components.config import config, getConfigListEntry
from Screens.Screen import Screen
class A... |
465537 | from lib.mmonit import MmonitBaseAction
class MmonitDismissEvent(MmonitBaseAction):
def run(self, event_id):
self.login()
data = {"id": event_id}
self.session.post("{}/reports/events/dismiss".format(self.url), data=data)
self.logout()
return True
|
465561 | import os
import subprocess
import pptx
from pptx.chart.data import ChartData
from pptx.enum.chart import XL_CHART_TYPE
from pptx.util import Inches
import pdfrw
from pd2ppt import df_to_table
import pandas as pd
def load_excel_files():
df_times = pd.read_excel("input_data/project_hours.xlsx")
df_expense... |
465632 | import os
import math
import numpy as np
root_path = '/home/project/I3D/data/Kinetics/train_256'
num_frames = 16
data_list = []
id_list = []
label_list = []
erro_data = []
label = 0
id = 0
for file_path in sorted(os.listdir(root_path)):
for video_path in sorted(os.listdir(os.path.join(root_path, file_path))):
... |
465646 | r"""Distributed TensorFlow with Monitored Training Session.
This implements the 1a image recognition benchmark task, see https://mlbench.readthedocs.io/en/latest/benchmark-tasks.html#a-image-classification-resnet-cifar-10
for more details
Adapted from official tutorial::
https://www.tensorflow.org/deploy/distrib... |
465674 | import pandas as pd
from pyarc.qcba.data_structures import QuantitativeDataFrame
from pyids.ids_classifier import IDS, mine_IDS_ruleset
from pyids.ids_ruleset import IDSRuleSet
from pyids.rule_mining import RuleMiner
from pyids.model_selection import CoordinateAscentOptimizer, train_test_split_pd
df = pd.read_csv("... |
465718 | import time
from collections import deque
import gym
class RecordEpisodeStatistics(gym.Wrapper):
def __init__(self, env, deque_size=100):
super().__init__(env)
self.t0 = time.perf_counter()
self.episode_return = 0.0
self.episode_horizon = 0
self.return_queue = deque(maxlen... |
465740 | import asyncio
from asyncio.futures import Future
from typing import List
from PIL import Image
from io import BytesIO
from importlib import resources
from datetime import datetime
from collections import defaultdict
from .base_rust_api import BaseRustSocket
from .structures import RustTime, RustInfo, RustMap, RustMar... |
465752 | class Node:
def __init__(self, parent, rank=0, size=1):
self.parent = parent
self.rank = rank
self.size = size
def __repr__(self):
return '(parent=%s, rank=%s, size=%s)' % (self.parent, self.rank, self.size)
class Forest:
def __init__(self, num_nodes):
self.nodes = ... |
465755 | from __future__ import (
absolute_import,
unicode_literals,
)
import functools
def decorated(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
|
465793 | import asyncio
from ..pool import ConnectionPool, ClosedPool, EmptyPool
from .aioconnection import AIOLDAPConnection
MYPY = False
if MYPY:
from ..ldapclient import LDAPClient
class AIOPoolContextManager:
def __init__(self, pool, *args, **kwargs):
self.pool = pool
self.__conn = None
as... |
465805 | import json
import copy
import requests
import datetime
from logUtils import *
# Log file location
_logFilePath = r"D:/Temp/Logging/createViews_[date].log"
# ArcGIS Online
_sourceFLUrl = "[YOUR-FEATURE-LAYER-URL]"
_uniqueValueField = "PROVINCIE"
_username = "[YOUR-USERNAME]"
_password = "[<PASSWORD>]"
# Sript param... |
465840 | from abc import ABC, abstractmethod
from contextlib import contextmanager
from typing import TYPE_CHECKING, Iterator, Optional
if TYPE_CHECKING:
from dvc.fs.ssh import SSHFileSystem
from dvc.types import StrPath
class BaseMachineBackend(ABC):
def __init__(self, tmp_dir: "StrPath", **kwargs):
self... |
465847 | import moderngl
import numpy as np
ctx = moderngl.create_standalone_context()
prog = ctx.program(
vertex_shader='''
#version 330
in vec2 in_vert;
in vec3 in_color;
out vec3 v_color;
void main() {
v_color = in_color;
gl_Position = vec4(in_vert, 0.0... |
465886 | from copy import deepcopy
import json
class Encoding(object):
CHANNELS = ['x', 'y', 'row', 'column', 'color', 'size', 'shape', 'text']
def __init__(self, **condition):
if (len(condition.keys()) != 1):
raise ValueError('only one condition allowed')
self._condition = next(iter(condition.items()))
... |
465905 | import torch
from torch import nn
import torch.nn.functional as F
from tqdm import tqdm, trange
import numpy as np
from math import *
import laplace.util as lutil
from util.evaluation import get_calib
class DiagLaplace(nn.Module):
"""
Taken, with modification, from:
https://github.com/wjmaddox/swa_gaussia... |
465943 | from typing import Union
from django.shortcuts import render
from django.http import HttpResponse
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.response import Response
from rest_framework.... |
465952 | import json
import requests
import urllib.parse as urlparse
def check_web_exception(host_name):
if "http" not in host_name:
host_name = "https://" + host_name
try:
res = requests.get(host_name, timeout=3)
res.raise_for_status()
except Exception:
return 2
try:
r... |
465974 | import pandas as pd
import geopandas as gpd
import re
import textdistance
import numpy as np
import math
def make_ordinal(s):
ordinal = lambda n: "%d%s" % (n,"tsnrhtdd"[(math.floor(n/10)%10!=1)*(n%10<4)*n%10::4])
name_ord = []
for x in s:
x = x.title()
m = re.findall(r'\d+', x)
... |
465977 | from mxnet import gluon
from mxnet import autograd
from mxnet import nd
from mxnet import image
import mxnet as mx
from tqdm import tqdm
def load_data_fashion_mnist(batch_size, resize=None):
"""download the fashion mnist dataest and then load into memory"""
def transform_mnist(data, label):
if resize:
... |
466128 | import numpy as np
import torch
import torch.nn as nn
from .backbone import backbone_fn
from collections import OrderedDict
from utils.utils import non_max_suppression
class yolov3layer(nn.Module):
'''
Detection Decoder followed yolo v3.
'''
def __init__(self, args):
super(yolov3layer, self).... |
466147 | from django.test import TestCase
from django.db import IntegrityError
from django.core.exceptions import ValidationError
from datetime import datetime
from datetime import timedelta
from .models import TestBasicInformation as BasicInformation
from .models import TestExperience as Experience
from .models import TestEdu... |
466166 | import numpy as np
import hypers as hp
from typing import Tuple, List
__all__ = ['decompose', 'vca']
class decompose:
""" Provides instances of decomposition classes """
def __init__(self, X: 'hp.hparray'):
self.vca = vca(X)
class vca:
def __init__(self, X: 'hp.hparray'):
self.X = X
... |
466179 | class temporal:
'''This is an abstract class'''
class MensajeOut:
tipo='normal'
mensaje=''
codigo=''
class MensajeTs:
instruccion=''
identificador=''
tipo=''
referencia=''
dimension=''
class Tabla_run:
def __init__(self, basepadre, nombre, atributos=[]):
self.basepadr... |
466199 | from .custom_driver import client
from .utils import log
from enum import Enum
def close_modal(browser: client) -> None:
el = browser.find("//div[@class='modalContent']")
el = el.find_element_by_xpath(".//a[@class='closeWindow clickable']")
browser.click(el)
def close_welcome_screen(browser: client) -> ... |
466217 | from canvas.tests.tests_helpers import CanvasTestCase, create_user, create_staff, create_group
class TestAuthorization(CanvasTestCase):
def test_user_cannot_moderate_group(self):
normal_user, group = create_user(), create_group()
self.assertFalse(group.can_moderate(normal_user))
de... |
466218 | import lasagne
import lasagne.layers as L
import lasagne.nonlinearities as NL
import lasagne.init as LI
from rllab.core.lasagne_powered import LasagnePowered
from rllab.core.lasagne_layers import batch_norm
from rllab.core.serializable import Serializable
from rllab.misc import ext
from rllab.policies.base import Polic... |
466295 | from django.db.models.signals import post_save
from django.dispatch import receiver
from django.conf import settings
from courses.models import Course
from twython import Twython
from twython.exceptions import TwythonError
from telegram import Bot, ParseMode
@receiver(post_save, sender=Course)
def send_message_tel... |
466343 | from dolfin import *
from dolfin_adjoint import *
import windse
import numpy as np
import copy
import matplotlib
matplotlib.use('TKAgg')
import matplotlib.pyplot as plt
parameters['form_compiler']['quadrature_degree'] = 6
set_log_level(15)
### Create an Instance of the Options ###
windse.initialize("params3D.yaml")... |
466353 | from flask import Flask, render_template, request, redirect, url_for, session
from tinydb import TinyDB, Query
from mastodon import Mastodon
from wordcloud import WordCloud
from datetime import datetime
from numpy.random import *
from xml.sax.saxutils import unescape
import re
import json
import requests
import MeCab
... |
466379 | import threading
def split_processing(ports, num_splits, scan, range_low, range_high):
split_size = (range_high-range_low) // num_splits
threads = []
for i in range(num_splits):
# determine the indices of the list this thread will handle
start = i * split_size
# special case on the... |
466395 | import adafruit_irremote
import board
import digitalio
import neopixel
import pulseio
pixels = neopixel.NeoPixel(board.NEOPIXEL, 10)
red_led = digitalio.DigitalInOut(board.D13)
red_led.direction = digitalio.Direction.OUTPUT
pulsein = pulseio.PulseIn(board.REMOTEIN, maxlen=120, idle_state=True)
decoder = adafruit_irr... |
466445 | from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
import tensorflow as tf
import datetime
import scipy.io as sio
import math
import time
from matplotlib.pyplot import pause
import os
import glob
from tensorflow.keras import layers
from tensorflow.keras import models
i... |
466471 | import tensorflow as tf
import config
import os
from urllib.request import urlretrieve
from zipfile import ZipFile
from dataset.dataset import Dataset
from network.eval import Learning
FLAGS = tf.app.flags.FLAGS
data_dir = config.data_dir
tmp_zip_adr = config.tmp_zip_adr
dataset_urls = config.dataset_urls
def downlo... |
466500 | import logging
import os
import shutil
import subprocess
import tempfile
import uuid
import panda3d.core as pc
from direct.directtools.DirectGrid import DirectGrid
from direct.showbase import ShowBaseGlobal
from panda3d.core import ConfigVariableBool
from pubsub import pub
import p3d
from p3d.displayShading import Di... |
466530 | from curtsies.input import *
def paste():
with Input() as input_generator:
print("If more than %d chars read in same read a paste event is generated" % input_generator.paste_threshold)
for e in input_generator:
print(repr(e))
time.sleep(1)
if __name__ == '__main__':
pas... |
466598 | import unittest
from unittest.mock import patch
from requests.exceptions import HTTPError
from my_user import get_users, requests
class TestUsers(unittest.TestCase):
@patch.object(requests, 'get', side_effect=HTTPError)
def test_get_users(self, mock_requests):
with self.assertRaises(HTTPError):
... |
466605 | from abc import abstractmethod
from typing import Dict, Any
from anoncreds.protocol.exceptions import SchemaNotFoundError
from anoncreds.protocol.types import ID, PublicKey, RevocationPublicKey, \
Schema, Tails, Accumulator, \
AccumulatorPublicKey, TimestampType, SchemaKey
class PublicRepo:
# GET
@a... |
466629 | print "Using testing configuration."
SECRET_KEY = '<KEY>'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '/tmp/wwwhisper_test_db',
}
}
|
466633 | import sys
sys.path.append(r'../shared')
from decl_grid import *
from numpy import *
from geo import *
from statistics import *
# x = 14
# y = 3
# d_x = 10
# d_y = 10
def optimal_dx_dy(array1, array2, array3, d_x, d_y, min_max, x):
w_m = []
dx_ar = []
dy_ar = []
for dx in range(1, d_x):
for d... |
466665 | import sys
import os
launcher={ 'shared' : 'env ' + sys.argv[4],
'MPI' : 'mpirun -genv ' + sys.argv[4] + ' -genv DIST_CNC=MPI -n 4',
'SOCKETS': 'env ' + sys.argv[4] + ' DIST_CNC=SOCKETS CNC_SOCKET_HOST=$CNCROOT/share/icnc/misc/distributed/socket/start_batch.sh',
'SHMEM' : 'env ' + s... |
466670 | from django.test import TestCase
from abidria.exceptions import EntityDoesNotExistException
from experiences.entities import Experience
from experiences.models import ORMExperience, ORMSave
from experiences.repositories import ExperienceRepo
from people.models import ORMPerson
class ExperienceRepoTestCase(TestCase):... |
466687 | import numpy as np
import cv2
def norm_rot_angle(rot):
norm_rot = rot
while norm_rot > 180:
norm_rot = norm_rot - 360
while norm_rot <= -180:
norm_rot = norm_rot + 360
return norm_rot
def rotate_2d(pt_2d, rot_rad):
x = pt_2d[0]
y = pt_2d[1]
sn, cs = np.sin(rot_rad), np.co... |
466691 | import numpy as np
from PuzzleLib.Backend import gpuarray, Memory
from PuzzleLib.Modules.Module import ModuleError, Module
class DepthConcat(Module):
def __init__(self, name=None):
super().__init__(name)
self.movesData = True
def updateData(self, data):
self.data = Memory.depthConcat(data)
def updateGra... |
466695 | from .tokenizer import Tokenizer
from .vocabulary import Vocabulary
# dummy import to call from chariot.transformer module
from .formatter.base import BaseFormatter
from .text.base import BasePreprocessor
from .token.base import BasePreprocessor
from .generator.base import BaseGenerator
|
466764 | from functools import partial
from multiprocessing import Pool, cpu_count
from pathlib import Path
from shutil import copyfile
from PIL import Image
def resize_one(path, size=(224, 224), output_dir="resized"):
output_dir = Path(output_dir)
image = Image.open(path)
image = image.resize(size, resample=Imag... |
466768 | import abc
import typing
import numpy as np
import SimpleITK as sitk
import pymia.data.conversion as conv
class Load(abc.ABC):
"""Interface for loading the data during the dataset creation in :meth:`.Traverser.traverse`
.. automethod:: __call__
"""
@abc.abstractmethod
def __call__(self, fi... |
466774 | import pytest
from srp import *
def test_formato_string():
user = Usuario(
nombre='Ramanujan',
edad=25,
direccion='Calle X, #Y Colonia Z'
)
assert 'Nombre: Ramanujan\nEdad: 25\nDireccion: Calle X, #Y Colonia Z' == user.formato_string()
def test_formato_diccionario():
user = U... |
466812 | from time import sleep
from uuid import uuid4
import pyodbc
from .base import *
DB_DRIVER = 'ODBC Driver 17 for SQL Server'
DB_HOST = os.environ['MCR_MICROSOFT_COM_MSSQL_SERVER_HOST']
DB_PORT = os.environ['MCR_MICROSOFT_COM_MSSQL_SERVER_1433_TCP']
DB_USER = 'sa'
DB_PASSWORD = '<PASSWORD>'
sleep(10)
db_connection = p... |
466822 | import skimage.io as io
import skimage.transform as skt
import numpy as np
from PIL import Image
from src.models.class_patcher import patcher
from src.utils.imgproc import *
class patcher(patcher):
def __init__(self, body='./body/body_i-s.png', **options):
super().__init__('I-s', body=body, pantie_positio... |
466831 | import claripy
import nose
def test_fallback_abstraction():
bz = claripy.backends.z3
a = claripy.BVV(5, 32)
b = claripy.BVS('x', 32, explicit_name=True)
c = a+b
d = 5+b
e = b+5
f = b+b
g = a+a
nose.tools.assert_false(a.symbolic)
nose.tools.assert_true(b.symbolic)
nose.tool... |
466835 | import mxnet as mx
def vgg16_pool3(input):
conv1_1 = mx.sym.Convolution(data=input, kernel=(3,3), pad=(100,100),
num_filter=64, name="conv1_1")
relu1_1 = mx.sym.Activation(data=conv1_1, act_type="relu",
name="relu1_1")
conv1_2 = mx.sym.Convol... |
466867 | from .. import util
from .base import TestAdmin
class TestAdminUnits(TestAdmin):
# Uses underlying paging
def test_get_administratrive_units(self):
response = self.client_list.get_administrative_units()
response = response[0]
self.assertEqual(response['method'], 'GET')
(uri, ar... |
466889 | import itertools
from typing import Tuple, Dict, Optional
import torch
from pytorch_toolbelt.inference.ensembling import Ensembler, ApplySigmoidTo, ApplySoftmaxTo
from torch import nn
from . import rgb_dct, rgb, dct, ela, rgb_ela_blur, timm, ycrcb, hpf_net, srnet, res, bit, timm_bits, unet, stacker
from ..dataset im... |
466934 | import datetime
from haystack import indexes
from newsroom.models import Article
class ArticleIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
author = indexes.CharField(model_attr='cached_byline')
published = indexes.DateTimeField(model_attr='publ... |
466943 | import PyTango
dev_info = PyTango.DbDevInfo()
dev_info.server = "Publisher/test"
dev_info._class = "Publish"
dev_info.name = "test/publisher/1"
db = PyTango.Database()
db.add_device(dev_info)
|
466945 | from tfbldr.datasets.audio import fetch_sample_speech_tapestry
from tfbldr.datasets.audio import soundsc
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import tensorflow as tf
import os
import numpy as np
from scipy.io import wavfile
from tfbldr.datasets.audio import linear_to_mel_weight_matrix... |
466961 | from .src import log_gen
from .src import apache_gen
def help():
return 'lunaticlog: to help you generate fake log loads.'
|
466968 | import tensorflow as tf
import tensorflow_datasets as tfds
# See all registered datasets
builders = tfds.list_builders()
print (builders)
# Load a given dataset by name, along with the DatasetInfo
data, info = tfds.load("mnist", with_info=True)
train_data, test_data = data['train'], data['test']
print(info) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.