id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1730857 | import torch
from torch import nn
class LayerNorm(nn.Module):
"""Construct a layer normalization module.
https://arxiv.org/abs/1607.06450
It normalizes the outputs of neurons for a given layer:
out = (gamma * (x - x.mean(-1)) / (x.std(-1) + eps)) + beta
Args:
hidden_size (int): number of... |
1730882 | import random
import unittest
import os
import pprint
import requests
from serpapi import GoogleSearch
class TestSearchApi(unittest.TestCase):
def setUp(self):
GoogleSearch.SERP_API_KEY = os.getenv("API_KEY", "demo")
@unittest.skipIf((os.getenv("API_KEY") == None), "no api_key provided")
def test_paginate(... |
1730897 | from typing import List, Optional
import torch
class AddFeatsByKeys(object):
"""This transform takes a list of attributes names and if allowed, add them to x
Example:
Before calling "AddFeatsByKeys", if data.x was empty
- transform: AddFeatsByKeys
params:
list_add_to_x:... |
1730899 | import os
from pathlib import Path
import pandas as pd
from autogluon.tabular import TabularPredictor
from pytorch_widedeep.utils import LabelEncoder
from sklearn.model_selection import train_test_split
SEED = 42
if __name__ == '__main__':
ROOTDIR = Path('/home/wenqi-ao/userdata/workdirs/automl_benchmark')
P... |
1730937 | import os
import yaml
import arxiv
import smtplib, ssl
from pathlib import Path
from datetime import date
today = date.today()
def build_query(domains, keyword):
query = '('
for i, domain in enumerate(domains):
query += f'cat:{domain}'
if i != len(domains) - 1:
query += ' OR '
... |
1730942 | class RadixSort:
def __init__(self,a):
self.a = a
def result(self):
maxElement = max(self.a)
exp = 1
while int(maxElement/exp) > 0:
self.countingsort(exp)
exp *= 10
return self.a
def countingsort(self,exp):
position = [0]*(10)
... |
1730983 | class Pilha(object):
def __init__(self):
self.dados = []
def empilha(self, elemento):
self.dados.append(elemento)
def desempilha(self):
if not self.vazia():
return self.dados.pop(-1)
def vazia(self):
return len(self.dados) == 0
p = Pilha()
word = raw_... |
1730989 | import torch
from torch import nn
from core.modules import LayerNorm
from typing import Optional
import torch.nn.functional as F
class UtteranceEncoder(nn.Module):
def __init__(self, idim: int,
n_layers: int = 2,
n_chans: int = 256,
kernel_size: int = 5,
... |
1730990 | from __future__ import annotations
import collections
import functools
import pickle
import sys
from abc import ABC, abstractmethod
from concurrent.futures.thread import ThreadPoolExecutor
from typing import Callable, Dict, Union, Any, List, Sequence, Optional
import json
import logging
import re
import threading
fro... |
1730999 | from django.conf import settings
from django.utils.module_loading import import_string
try:
name = settings.WAGTAILNEWS_PAGINATOR
except AttributeError:
from django.core.paginator import Paginator, EmptyPage
def paginate(request, items):
paginator = Paginator(items, 20)
try:
p... |
1731019 | import os
from slam.NFiSAM import NFiSAM_empirial_study
if __name__ == '__main__':
# knots = [5,7,9,11,13]
# hidden_dims = [4,6,8,10,12]
knots = [9]
hidden_dims = [8]
iters = [2000]
training_samples = [2000]
learning_rates = [.02]
run_file_dir = os.path.dirname(__file__)
seed_dir =... |
1731024 | import os
from instascrape.utils import to_datetime
from instascrape.commands import COOKIES_DIR, error_print, dump_cookie, load_cookie, load_obj
from colorama import Fore, Style
def cookies_handler(**args):
action = args.get("action")
insta = load_obj()
cookies = [f for f in os.listdir(COOKIES_DIR) if ... |
1731041 | from pathlib import Path
import mimetypes
import torchaudio
AUDIO_EXTENSIONS = tuple(str.lower(k) for k, v in mimetypes.types_map.items()
if v.startswith('audio/'))
class AudioData:
'''Holds basic information from audio signal'''
def __init__(self, sig, sr=48000):
self.sig =... |
1731052 | from typing import Iterable, Optional, TypeVar
from stock_indicators._cslib import CsIndicator
from stock_indicators._cstypes import List as CsList
from stock_indicators.indicators.common.results import IndicatorResults, ResultBase
from stock_indicators.indicators.common.quote import Quote
def get_prs(base_history: ... |
1731060 | import os.path as osp
import PIL
from PIL import Image
import torchvision.transforms.functional as TF
import torch
from torch.utils.data import Dataset
from torchvision import transforms
import numpy as np
THIS_PATH = osp.dirname(__file__)
ROOT_PATH = osp.abspath(osp.join(THIS_PATH, '..', '..'))
IMAGE_PATH = osp.joi... |
1731084 | from Crypto.PublicKey import RSA
from ast import literal_eval
import jose.jwk as jwk
import jose.jwt as jwt
import time
import uuid
import os
class JWT():
"""
This class creates a JWT from the Okta Client configuration.
"""
OAUTH_ENDPOINT = "/oauth2/v1/token"
HASH_ALGORITHM = "RS256"
PEM_FORM... |
1731093 | import sys
sys.path.append('../utils')
from ops import dense_sum_list, get_shape
from np_op import convert2list
import tensorflow as tf
import numpy as np
import os
def test1(id_=0):
''' dense_sum_list test
Results :
=================Round1===================
const : [4, 2]
[[ 1. ... |
1731094 | from dataclasses import dataclass
from datetime import date, datetime
import mock
from pdfminer.layout import LTChar, LTCurve, LTFigure, LTImage, LTTextBoxHorizontal, LTTextLineHorizontal
from typing import List
from rdr_service.services.consent import files
from tests.helpers.unittest_base import BaseTestCase
class... |
1731138 | import sys
class Solution(object):
def minCostII(self, costs):
"""
:type costs: List[List[int]]
:rtype: int
"""
if not costs:
return 0
self.costs = costs
self.memo = {}
self.k = len(costs[0])
mincost = sys.maxint
for i in... |
1731151 | from netunnel.client import NETunnelClient
import asyncio
async def main():
async with NETunnelClient('http://localhost:4040') as client:
# Open a client-to-server tunnel from localhost:12345 to localhost:22
tunnel = await client.open_tunnel_to_server(local_address='127.0.0.1',
... |
1731176 | import sys
import os
SECRET_KEY = '<KEY>'
#SECRET_KEY = os.getenv('DJANGO_SECRET_KEY')
DEBUG = False
STATIC_ROOT = '/var/cache/activity_assistant/static/'
STATICFILES_DIRS = ['/opt/activity_assistant/web/frontend/static']
ZERO_CONF_MAIN_PATH = "/opt/activity_assistant/zero_conf_server.py"
UPDATER_SERVICE_PATH = "/o... |
1731177 | from __future__ import unicode_literals
import datetime
import os
import sqlite3
import unittest
import numpy
from six import string_types
import pandas
from gtfspy.gtfs import GTFS
from gtfspy.util import wgs84_distance
from gtfspy.route_types import BUS, TRAM, ALL_ROUTE_TYPES
class TestGTFS(unittest.TestCase):
... |
1731288 | from _dependencies.analyze import _make_dependency_spec
from _dependencies.exceptions import DependencyError
class _Graph:
def __init__(self):
self.specs = {}
def get(self, name):
return self.specs.get(name)
def assign(self, name, dependency):
_check_dunder_name(name)
sel... |
1731302 | import os
import numpy as np
import pandas as pd
import hashlib
import time
import shutil
from scipy.sparse import coo_matrix
import multiprocessing as mp
import MNMAPI
class DODE(object):
def __init__(self, nb, config):
self.config = config
self.nb = nb
self.num_assign_interval = nb.config.config_dict... |
1731341 | import tensorflow as tf
def _append_homog(tensor):
rank = len(tensor.shape.as_list())
shape = tf.concat([tf.shape(tensor)[:-1], [1]], axis=0)
ones = tf.ones(shape, dtype=tensor.dtype)
return tf.concat([tensor, ones], axis=rank - 1)
def dense(inputs, weights, batch_norm, is_training, particles=1):
... |
1731376 | import json
import traceback
import subprocess
from threading import Timer
from json.decoder import JSONDecodeError
from concurrent.futures import ProcessPoolExecutor
import requests
from stem.control import Controller
from stem import Signal
from onioningestor.operators import Operator
class Plugin(Operator):
... |
1731411 | import marshmallow as ma
from .. import models
from ..serializers.base import BaseSchema
from .dataset_version import DatasetVersionSchema
from .storage_provider import StorageProviderSchema
class DatasetSchema(BaseSchema):
MODEL = models.Dataset
id = ma.fields.Str()
name = ma.fields.Str()
descripti... |
1731472 | from database.repo import Repo
from database.models.Events import Events
class DatabaseEvents(Repo):
def listEvents(self, reqArgs):
return self.all(Events, reqArgs )
def getEvent(self, id):
return self.get(Events)
def postEvent(self, **entityFields):
return self.post(Events, *... |
1731477 | import time
import json
from brownie import *
from rich.console import Console
from assistant.rewards.rewards_utils import calculate_sett_balances
from assistant.subgraph.client import fetch_wallet_balances
from config.badger_config import badger_config
from rich.console import Console
from scripts.systems.badger_syste... |
1731491 | from django.conf import settings
if settings.USE_I18N:
from trans_real import *
else:
from trans_null import *
del settings
|
1731494 | from unittest.mock import patch
import unittest
import json
from stix_shifter_modules.sentinelone.entry_point import EntryPoint
from stix_shifter.stix_transmission import stix_transmission
from requests.exceptions import ConnectionError
class PingResponse:
""" class for capturing response"""
def __init__(self,... |
1731500 | import argparse
import datetime
import os
import sys
sys.path.append(os.path.join(os.getcwd(), '../common'))
from runner_helper2 import *
from logtable_def import *
MOCK = False
RERUN_TESTS = False
NUM_EPOCH = 3
TIMESTAMP = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
HERE = os.path.abspath(os.path.dirname(... |
1731509 | import unittest
from satella.os import whereis
class TestWhereis(unittest.TestCase):
def test_whereis_python(self):
"""
Note that it will fail on Windows unless you have PYTHON.EXE in your path
"""
execs = list(whereis('python'))
self.assertGreaterEqual(len(execs), 1)
|
1731516 | from pathlib import Path
from dataclasses import dataclass
from typing import Union
import toml
from semver import VersionInfo
from typeguard import typechecked
from wheel_inspect import inspect_wheel
from balsa import get_logger
from pyship import __application_name__ as pyship_application_name
from pyship import py... |
1731543 | from __future__ import print_function
from __future__ import absolute_import
import sys
sys.path.append('C:\\projects\\qgate_sandbox')
from tests.test_base import *
from qgate.script import *
class TestBigCircuitsBase(SimulatorTestBase) :
@classmethod
def setUpClass(cls):
if cls is TestBigCircuitsBa... |
1731550 | from .simple_cnn import SimpleCNN
from .simple_mlp import SimpleMLP
from .mlp_tiny_imagenet import SimpleMLP_TinyImageNet
from .mobilenetv1 import MobilenetV1
|
1731553 | import Init
import Modeling
import System
import Time
class Subsystem:
"""This class represents the the agents that are assigned to the subsystems.
The agents can predict the behavior of their subsystems and store the
current costs, coupling variables and states.
Parameters
----------
sys_id ... |
1731562 | from faceai.Detection import *
from .dan_models import *
def dan(modelpath =None,
**kwargs):
"""
'dan()' function attempt to build DAN model with some initialization parameter.
:param modelpath: the path of the model's weights
:return: DAN model
"""
execution_path... |
1731616 | from setuptools import setup, find_packages
from pip.req import parse_requirements
from debpackager.main import __version__
install_reqs = parse_requirements('requirements.txt', session=False)
reqs = [str(ir.req) for ir in install_reqs]
setup(
name='debpackager',
version=__version__,
packages=find_package... |
1731628 | import logging
from datetime import datetime
from .switch import Switch
LOG = logging.getLogger(__name__)
class Insight(Switch):
def __init__(self, *args, **kwargs):
Switch.__init__(self, *args, **kwargs)
self.insight_params = {}
def __repr__(self):
return '<WeMo Insight "{name}">'.f... |
1731689 | from .dcgan_128 import *
from .dcgan_32 import *
from .dcgan_48 import *
from .dcgan_64 import *
from .dcgan_base import *
from .dcgan_cifar import *
|
1731846 | from layers.resnet import ShallowConnectedResNet, ShallowResNet
__all__ = ["ShallowResNet", "ShallowConnectedResNet"]
|
1731864 | import os
import torch
from net.qa_extract import QaExtract
import config.args as args
def save_model(model, output_dir):
model_to_save = model.module if hasattr(model, 'module') else model # Only save the model it-self
output_model_file = os.path.join(output_dir, "pytorch_model.bin")
torch.save(model_to... |
1731865 | import os
import sipconfig
from PyQt4 import pyqtconfig
from distutils import sysconfig
vcs_so = '%s/vcs/_vcs.so' % sysconfig.get_python_lib()
vcs_inc = '%s/vcs/Include' % sysconfig.get_python_lib()
## vcs_so = '/Users/hvo/src/uvcdat/cdatBuild/lib/python2.7/site-packages/vcs/_vcs.so'
## vcs_inc = '/Users/hvo/src/uv... |
1731867 | import os
import sys
sys.path.append(os.getcwd())
import src.data.data as data
import torch
from jobman import DD
vocab_paths = {
"emotion": "data/vocabs/emotion.vocab",
"motivation": "data/vocabs/motivation.vocab",
"sentence": "data/vocabs/tokens.vocab",
"plutchik": "data/vocabs/plutchik8.vocab",
... |
1731876 | import torch
import torch.nn.functional as F
from torch.autograd import Variable
#LINF_SGD_LR = 0.01 #0.0078 # 0.04
# performs Linf-constraint PGD attack w/o noise
# @epsilon: radius of Linf-norm ball
def attack_Linf_PGD_labeled_free(netD, input_v, delta,y_b,y_c, metric, epsilon,lr,b_metric,c_metric,c_alph,n_gpu,num... |
1731879 | from skipchunk import skipchunk
import jsonpickle
def pretty(obj):
print(jsonpickle.encode(obj,indent=2))
def test():
skipchunk_config = {
"host":"http://localhost:9200/",
"name":"example-sentences",
"path":"./skipchunk_data",
"engine_name":"elasticsearch"
}
#text = '... |
1731895 | import os
import re
import HTMLParser
__all__ = ['replace_newlines', 'preserve_quotes',
'remove_meta', 'unescape', 'sanitize']
parser = HTMLParser.HTMLParser()
nlbr_pattern = re.compile(r'\<br( \/)?\>')
quot_pattern = re.compile(r'\<span class=\"quote\"\>(.+?)\<\/span\>')
code_pattern = re.compile(r'\<pr... |
1731934 | from google.cloud.firestore_v1.base_query import BaseQuery
from google.cloud.firestore_bundle.types import BundledQuery
def limit_type_of_query(query: BaseQuery) -> int:
"""BundledQuery.LimitType equivalent of this query.
"""
return (
BundledQuery.LimitType.LAST
if query._limit_to_last
... |
1731937 | import unittest
from unittest.mock import MagicMock
from unittest.mock import patch
from keydra.exceptions import DistributionException
from keydra.providers import aws_appsync
SECRET = {
'description': 'Secret for appsync used by treasury integrations',
'key': 'treasury-integrations',
'config': {
'api-i... |
1732022 | import unittest
from kiss_headers import (
AltSvc,
CacheControl,
ContentEncoding,
ContentLength,
ContentType,
Date,
Expires,
Header,
Server,
SetCookie,
StrictTransportSecurity,
XFrameOptions,
XXssProtection,
explain,
)
class MyExplainTestCase(unittest.TestCase)... |
1732034 | import os
import re
import yaml
import cerberus
import logging
from watsor.config.schema import schema
_LOGGER = logging.getLogger(__name__)
_ENV_pattern = re.compile('.*?\${(\w+)}.*?')
SECRETS_YAML = "secrets.yaml"
__SECRET_CACHE = {}
def _load_yaml(filename: str, loader: yaml.Loader = yaml.SafeLoader):
_LOG... |
1732077 | import re
from collections import OrderedDict
from rest_framework import renderers
from xml.sax.saxutils import escape
class KeyStringBaseRenderer(renderers.BaseRenderer):
def process_key(self, key):
raise NotImplementedError('process_key() must be implemented.')
def process_value(self, value):
... |
1732110 | import re
import string
import json
import pickle
from feature_extract import FeatureFinder
class Classifier:
def __init__(self):
self.features = {}
#end
def extract_features(self, featureVector):
#tweet_words = set(tweet)
featureList = pickle.load(open('data/featureList.pickle','... |
1732122 | import torch
import torch.nn as nn
import torch.nn.functional as F
class DnCNN(nn.Module):
def __init__(self, channels, num_of_layers=17, **kwargs):
super(DnCNN, self).__init__()
kernel_size = 3
padding = 1
features = 64
layers = []
layers.append(nn.Conv2d(in_channe... |
1732162 | from datetime import timedelta
import pytest
from django.utils import timezone
from jcasts.podcasts import scheduler
from jcasts.podcasts.factories import PodcastFactory, SubscriptionFactory
from jcasts.podcasts.models import Podcast
class TestEmptyQueue:
def test_empty_queue(self, db, mock_feed_queue):
... |
1732163 | import asyncio
import struct
from ipaddress import IPv4Address
from urllib.parse import quote
import aiohttp
from yarl import URL
from . import settings
from .bencode import bdecode
async def retrieve_peers_http_tracker(task_registry, tracker, infohash):
url = f"{tracker}?info_hash={quote(infohash)}&peer_id={qu... |
1732165 | import tensorflow as tf
import os
import sys
import time
import numpy as np
from model.trainer import Trainer
from dataset.data_loader import KaldiMultiDataRandomQueue, KaldiMultiDataSeqQueue, DataOutOfRange
from model.common import l2_scaling
from model.loss import softmax
from model.loss import asoftmax, additive_mar... |
1732187 | import torch
import torch.nn.functional as F
import time
import os
import cv2
import numpy as np
from sklearn.neighbors import KDTree
from random import sample
from lib.utils import save_session, AverageMeter
from lib.ransac_voting_gpu_layer.ransac_voting_gpu import ransac_voting_layer_v3
from lib.ransac_voting_gpu_lay... |
1732204 | import logging
from typing import List
from opyoid.bindings import Binding, BindingToProviderAdapter, ClassBindingToProviderAdapter, \
InstanceBindingToProviderAdapter, MultiBindingToProviderAdapter, ProviderBindingToProviderAdapter, \
SelfBindingToProviderAdapter
from opyoid.bindings.registered_binding import... |
1732251 | from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.schema import Column, ForeignKey, PrimaryKeyConstraint
from sqlalchemy.types import Integer, String, BigInteger
Base = declarative_base()
class Channel(Base):
__tablename__ = 'channels'
id = Colum... |
1732261 | import KratosMultiphysics as KM
import KratosMultiphysics.ShallowWaterApplication as SW
def Factory(settings, Model):
if not isinstance(settings, KM.Parameters):
raise Exception("expected input shall be a Parameters object, encapsulating a json string")
return ComputeFroudeProcess(Model, settings["Para... |
1732267 | import torch
from torch.distributions import Normal as TorchNormal
from dpp.utils import clamp_preserve_gradients
class Normal(TorchNormal):
def log_cdf(self, x):
# No numerically stable implementation of log CDF is available for normal distribution.
cdf = clamp_preserve_gradients(self.cdf(x), 1... |
1732275 | from pathlib import Path
from tqdm import tqdm
def read_lines_from_input(input_files):
for fname in tqdm(input_files):
with open(fname) as infile:
yield [i.strip() for i in infile]
def split(input_files, file_path_prefix,
file_name_suffix='',
append_trailing_newlines=True... |
1732294 | import matplotlib.pyplot as plt
import seaborn as sns
import argparse
import json
def load_from_json(file_name):
with open(file_name, 'r') as out_file:
return json.load(out_file)
def plot_curves(json_logs, exp_ids, mode, factor):
""" Plots perplexity/ BLEU curves of multiple experiments for compariso... |
1732320 | try:
from django.conf.urls import url, include
except ImportError:
from django.urls import url, include
urlpatterns = [
url(r'^', include('notify.urls', namespace='notifications')),
]
|
1732368 | from base64 import b64encode
from tornado_http_auth import DigestAuthMixin, BasicAuthMixin, auth_required
from tornado.testing import AsyncHTTPTestCase
from tornado.web import Application, RequestHandler
credentials = {
'user1': '<PASSWORD>',
'user2': '<PASSWORD>',
}
class BasicAuthHandler(BasicAuthMixin, ... |
1732394 | import numpy as np
from . import tools
class IntervalTestData(object):
functions = [tools.f]
first_derivs = [tools.fd]
domains = [(1,2),(0,2),(-1,0),(-.2*np.pi,.2*np.e),(-1,1)]
integrals = [
[ 0.032346217980525, 0.030893429600387, -0.014887469493652,
-0.033389463703032, -0.016340257... |
1732397 | import torch
def collate_fn(batch):
data = {}
imgs = []
frame_ids = []
img_paths = []
sequences = []
cam_ks = []
T_velo_2_cams = []
scale_3ds = batch[0]["scale_3ds"]
for scale_3d in scale_3ds:
data["projected_pix_{}".format(scale_3d)] = []
data["fov_mask_{}".forma... |
1732416 | import os
import numpy as np
import pandas as pd
from mlblocks.discovery import load_pipeline
from orion.core import Orion
class TestOrion:
@classmethod
def setup_class(cls):
cls.clean = pd.DataFrame({
'timestamp': list(range(100)),
'value': [1] * 100,
})
cls... |
1732491 | import sys
import struct
import time
import socket
import cPickle
import select
class Client:
def __init__(self, host, port):
self.__host = host
self.__port = port
self.__dbg_flag = False
self.__server_sock = None
self.__retry = 0
... |
1732502 | from kubernetes import config
from openshift import client, watch
import os
def process_image(obj):
metadata = obj.metadata
name = metadata.name
namespace = metadata.namespace
for tag in obj.spec.tags:
if tag.name == 'latest':
continue
else:
print("Deleting %s:%... |
1732511 | import numpy as np
import pandas as pd
from ..data import cat
ifm_opr_ids = [
'CAR1013',
'CAR1217',
'ACR210',
'ACR288',
'CAR973',
'ACR423',
'ACR281',
'ACR211',
'VCSOPR10',
'CAR1041',
'ACR273',
'ACR425',
'CAR1046',
'ACR280',
'ACR274',
'CAR1070',
'CAR1... |
1732546 | import argparse
from collections import defaultdict
import json
from nlp2go.cli import Cli
from nlp2go.model import Model
from nlp2go.server import Server
import os
os.environ["PYTHONIOENCODING"] = "utf-8"
def parse_args(args):
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(... |
1732548 | from xendit.models._base_model import BaseModel
from .balance_account_type import BalanceAccountType
from xendit.xendit_error import XenditError
from xendit._api_requestor import _APIRequestor
from xendit._extract_params import _extract_params
class Balance(BaseModel):
"""Balance class (API Reference: Balance)
... |
1732577 | from datetime import date
from unittest import TestCase
from regparser.grammar import delays
class GrammarDelaysTests(TestCase):
def test_date_parser(self):
result = delays.date_parser.parseString("February 7, 2012")
self.assertEqual(date(2012, 2, 7), result[0])
result = delays.date_pars... |
1732601 | import FWCore.ParameterSet.Config as cms
# iso deposits and isolation values, defined by the Muon POG
from RecoMuon.MuonIsolation.muonPFIsolation_cff import *
# computing the isolation for the muons produced by PF2PAT, and not for reco muons
sourceMuons = 'pfSelectedMuons'
muPFIsoDepositCharged.src = sourceMuons
m... |
1732605 | import torch
import torch.nn as nn
import torch.nn.functional as F
from functools import reduce
from base.base_model import BaseModel
from .backbones import mobilenetv2
from .backbones import resnet
class DecoderBlock(nn.Module):
def __init__(self, in_channels, out_channels, block_unit):
super(DecoderBlock, self).... |
1732622 | import pytest
from todolist.core.accounts.entities.user import User
from todolist.core.accounts.protocols import UserRepo
from todolist.core.accounts.services import hash_service, user_service
from todolist.core.accounts.services.exceptions import (
EmailNotUniqueError,
UserNotFoundError,
)
@pytest.fixture()... |
1732650 | from jmessage import *
from jmessage import url
import json
class Group(object):
def __init__(self,jmessage):
self.jmessage=jmessage;
def build_group(self, owner_username=None, name=None, members_username=None, desc=None):
group = {}
if owner_username is not None:
group["own... |
1732736 | import json
from typing import Tuple
import librosa
import torch
from pororo.models.tts.hifigan.checkpoint import load_checkpoint
from pororo.models.tts.hifigan.model import Generator
from pororo.models.tts.synthesis import synthesize
from pororo.models.tts.tacotron.params import Params as tacotron_hp
from pororo.mod... |
1732744 | from pyradioconfig.parts.common.calculators.calc_white import CALC_Whitening
class Calc_Whitening_Bobcat(CALC_Whitening):
pass |
1732756 | from django.shortcuts import render
from django.views.generic import View
from django.views.generic.base import RedirectView
from django.views.generic.edit import FormMixin
from django.views.generic.list import ListView
from django.shortcuts import get_object_or_404
from billing.models import Transaction
from digital... |
1732779 | import argparse
import json
import os
from common.dataset.reader import JSONLineReader
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--submission', help='/path/to/submission/file', required=True)
parser.add_argument('--data', help='/path/to/data/file', required=True)
... |
1732795 | import re
import json
import numpy as np
from tqdm import tqdm
import pdb
import os
import pickle
import cPickle
import string
import sys
def unpickle(p):
return cPickle.load(open(p,'r'))
def load_json(p):
return json.load(open(p,'r'))
def clean_words(data):
dict = {}
freq = {}
# start with 1
idx = 1
sentence... |
1732819 | import os
import glob
from PIL import Image
import numpy as np
import random
image_dir = "[DIRECTORY OF SCRAPED IMAGES]"
out_dir = "./out_pruned_images"
os.makedirs(out_dir, exist_ok=True)
filelist = glob.glob(os.path.join(image_dir, "*.png"))
random.shuffle(filelist)
uninteresting_count = 0
uninteresting_sat_stdevs ... |
1732848 | import threading
class StoppableThread(threading.Thread):
def __init__(self, loop_func, setup_func):
threading.Thread.__init__(self)
self._stop_event = threading.Event()
self.daemon = True
self.loop_func = loop_func
self.setup_func = setup_func
# function using _... |
1732861 | import pyclesperanto_prototype as cle
import numpy as np
def test_exclude_labels_2d():
gpu_input = cle.push(np.asarray([
[0, 0, 2, 0, 0, 0, 0],
[0, 1, 2, 0, 7, 0, 0],
[0, 1, 0, 0, 7, 5, 5],
[8, 8, 8, 0, 0, 0, 0],
[0, 4, 4, 0, 3, 0, 0],
[... |
1732886 | import copy
import random
class Key:
"""
A key that the Cascade protocol reconciles.
"""
_random = random.Random()
ERROR_METHOD_BERNOULLI = "bernoulli"
ERROR_METHOD_EXACT = "exact"
ERROR_METHODS = [ERROR_METHOD_BERNOULLI, ERROR_METHOD_EXACT]
def __init__(self):
"""
Cre... |
1732895 | from PIL import Image
def dpix(p):
return (p << 4) | p
TRANSPARENT_IDX = 0x0
LIGHT_GREEN_IDX = 0x1
LIGHT_RED_IDX = 0x2
LIGHT_BLUE_IDX = 0x3
LIGHT_BROWN_IDX = 0x4
LIGHT_STEEL_IDX = 0x5
GREEN_IDX = 0x6
RED_IDX = 0x7
BLUE_IDX = 0x8
BROWN_IDX = 0x9
STEEL_IDX = 0xA
DARK_GREEN_IDX = 0xB
DARK_RED_IDX = 0xC
DARK_BLUE_I... |
1732917 | import logging.config
import os
import sys
from os.path import expanduser
import requests
import superannotate.lib.core as constances
from packaging.version import parse
from superannotate.lib.app.analytics.class_analytics import class_distribution
from superannotate.lib.app.exceptions import AppException
from superan... |
1732941 | import requests
# Vuln Base Info
def info():
return {
"author": "cckuailong",
"name": '''AxxonSoft Axxon Next Directory Traversal''',
"description": '''AxxonSoft Axxon Next suffers from a directory traversal vulnerability.''',
"severity": "high",
"references": [
... |
1732992 | BASE_PATH = '/home/diam/Desktop/WBC_Test_Images/'
def get_filename_for_index(index):
PREFIX = 'Original_Images/BloodImage_'
num_zeros = 5 - len(index)
path = '0' * num_zeros + index
return PREFIX + path + '.jpg'
reader = csv.reader(open(BASE_PATH + 'labels.csv'))
# skip the header
next(reader)
X = [... |
1732999 | import io
import csv
import requests
class HttpException(Exception):
pass
class GoogleSheetCSVReader(csv.DictReader):
def __init__(self, sheet_id, gid=0, *args, **kwds):
self._sheet_id = sheet_id
self._gid = gid
url = self._get_sheet_url(self._sheet_id, self._gid)
response_bo... |
1733019 | import argparse
from fit_rdf_gnn import *
parser = argparse.ArgumentParser()
parser.add_argument("-logdir", type=str)
parser.add_argument("-data", type=str, nargs='+')
parser.add_argument("-val", type=str, nargs='+')
parser.add_argument("-name", type=str)
parser.add_argument("-device", type=int, default=0)
parser.add... |
1733055 | from rest_framework import serializers
from core.models.insurer import Insurer
class InsurerSerializer(serializers.ModelSerializer):
class Meta:
model = Insurer
fields = ('id', 'name', 'is_active')
|
1733112 | from toolz import curry
@curry
def group_with(predicate, xs):
"""Takes a list and returns a list of lists where each sublist's elements are
all satisfied pairwise comparison according to the provided function.
Only adjacent elements are passed to the comparison function"""
out = []
is_str = isinst... |
1733152 | from Grove_Fingerprint import Fingerprint
import sys
import wiringpi2
fp = Fingerprint()
if fp.verifyPassword():
print 'Found device.'
else:
print 'Device not found'
sys.exit(0)
def getFingerprintIDez():
p = fp.getImage()
if p != fp.FINGERPRINT_OK:
return -1
p = fp.image2Tz()
... |
1733162 | class User():
"""DocString"""
def __init__(self, first_name, last_name, location, field):
"""初始化一个用户的属性"""
self.first_name = first_name
self.last_name = last_name
self.location = location
self.field = field
self.login_attempts = 0
def describe_user(self)... |
1733186 | import os
import logging
import json
from typing import List, Dict
import torch
from .discrete_tuning import preprocess
from ..config import Config
from ..util import load_language_model
from ..trainer import BaseTrainer
os.environ["TOKENIZERS_PARALLELISM"] = "false" # to turn off warning message
__all__ = 'Continuo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.