id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3314470 | import logging
log = logging.getLogger(__name__)
_type_map = {}
class TypeMeta(type):
def __new__(mcs, name, bases, attrs):
cls = type.__new__(mcs, name, bases, attrs)
if '__metaclass__' not in attrs:
_type_map[name.lower()] = cls
from TelegramBotAPI.types.field import Fie... |
3314493 | from collections import namedtuple
from typing import Any, Dict
import os
import boto3
import numpy as np
import torchvision.transforms as transforms
from torch import nn
from sklearn.metrics import average_precision_score
from determined.pytorch import (
DataLoader,
LRScheduler,
PyTorchTrial,
PyTorc... |
3314538 | import os
import cv2
import math
import numpy as np
from torch.utils.data import Dataset
from pycocotools.coco import COCO
from pycocotools import mask as maskUtils
COCO_CLASSES = [
'person',
'bicycle',
'car',
'motorcycle',
'airplane',
'bus',
'train',
'truck',
'boat',
'traffic ... |
3314570 | from ztk.api.base import RestApi
class ZtkItemIdConvertRequest(RestApi):
'''__init__(self, content, type=1, tlj=0, hjs=1, domain='api.zhetaoke.com', port=10001)
解析商品编号API(返回商品ID和券ID)
content 淘口令文案或者二合一链接或者长链接或者短链接或者喵口令。
type 是否返回优惠券详细信息,type=1表示返回商品ID和优惠券详细信息,注意,优惠券信息可能为空
tlj 是否解析淘礼金淘口令,tlj=1表示解析,tlj=... |
3314603 | from typing import List, Optional
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
LINE_WIDTH = 1.5
def palette_gen(n_colors):
palette = plt.get_cmap("tab10")
curr_idx = 0
while curr_idx < 10:
yield palette.colors[curr_idx]
curr_idx += 1
def plot_losses(
... |
3314636 | import persistent
class Object(persistent.Persistent):
def __init__(self, **kw):
self.__dict__.update(kw)
|
3314650 | import json
from unittest import mock
import requests
from rest_framework.test import APITestCase
from rest_framework import status
from rest_framework.reverse import reverse
from shipchain_common.test_utils import mocked_rpc_response
from apps.shipments.rpc import Load110RPCClient
from apps.eth.rpc import EventRPCCl... |
3314661 | import rainbowhat
import time
TIMEOUT = 4 # Timeout in MS
rgb = [100,0,0]
#c = 261
d = 294
e = 329
f = 349
g = 392
a = 440
b = 493
c = 523
states = [
[10,0,0, "Reed", a],
[0,10,0, "Gren", b],
[0,0,10, "Blue", c]
]
counts = [0,0,0]
#for note in [a,a,g,g,a,a,g,None,f,f,e,e,d,d,c,None,g,g,f,f,e,e,d,None,... |
3314731 | import numpy as np
import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras.models import *
from tensorflow.keras.layers import *
from tensorflow.keras.optimizers import *
from tensorflow.keras.callbacks import *
from tensorflow.keras import backend
from tensorflow.keras.activations impo... |
3314750 | from ptypes import *
v = 0 # FIXME: this file format is busted
class seq_parameter_set_rbsp(pbinary.struct):
class __pic_order_type_1(pbinary.struct):
_fields_ = [
(1, 'delta_pic_order_always_zero_flag'),
(v, 'offset_for_non_ref_pic'),
(v, 'offset_for_top_to_botto... |
3314807 | from tests.utils import W3CTestCase
class TestGridPositionedItemsGapsRtl(W3CTestCase):
vars().update(W3CTestCase.find_tests(__file__, 'grid-positioned-items-gaps-rtl-'))
|
3314858 | from abc import ABC, abstractmethod
from rxbp.multicast.mixins.multicastmixin import MultiCastMixin
class LiftIndexMultiCastMixin(MultiCastMixin, ABC):
@property
@abstractmethod
def lift_index(self) -> int:
...
|
3314939 | import random
from http import HTTPStatus
from typing import Any, Dict, List
import pytest
import requests
from rotkehlchen.constants import ZERO
from rotkehlchen.constants.assets import A_CRV, A_USD
from rotkehlchen.fval import FVal
from rotkehlchen.tests.utils.api import (
api_url_for,
assert_error_response... |
3314944 | from torchvision.datasets import CIFAR10
from torchvision.datasets import CIFAR100
import os
root = '/database/cifar100/'
from PIL import Image
dataset_train = CIFAR100(root)
for k, (img, label) in enumerate(dataset_train):
print('processsing' + str(k))
if not os.path.exists(root + 'CIFAR100_image/'... |
3314947 | import numpy as np
import timeit
from datetime import timedelta
import imp
from MLMCPy.input import Input
from MLMCPy.model import Model
class MLMCSimulator:
"""
Computes an estimate based on the Multi-Level Monte Carlo algorithm.
"""
def __init__(self, data, models):
"""
Requires a d... |
3314952 | import numpy as np
import dircache
from sets import Set
import time
import tables as pt
import sys
import time
import os
from optparse import OptionParser
class TimestampsModel (pt.IsDescription):
timestamp = pt.Time64Col()
#class TimestampsModel ends
class StrategyDataModel(pt.IsDescription):
... |
3314955 | import random
import re
import numpy as np
from utils import get_segments, get_ids, create_padding_mask
def preprocess(file, BATCH_SIZE, max_length, tokenizer):
train_dataset = []
input_vocab_size = len(tokenizer.vocab)
f = open(file, 'r')
words = f.read()
words = words.replace('\n\n', '.')
words... |
3314957 | import numpy as np
import os
from numpy import *
from scipy.misc import imresize
from PIL import Image
# read a floder's total RGB pictures
def rgb_import(filedir, dims, numfrm,startfrm):
R , G ,B = [],[],[]
for i in range(numfrm):
target = str(i + startfrm).zfill(3)+".png"
toturl = os.path.joi... |
3314972 | from pyutilib.component.core import *
class IPackage2Util(Interface):
"""Interface for Package2 utilities"""
class Package2Util(Plugin):
implements(IPackage1Util)
|
3314980 | import inspect, importlib, importlib.util
import json, types, traceback, os, sys
from proxy import Executor, Proxy
from weakref import WeakValueDictionary
def python(method):
return importlib.import_module(method, package=None)
def fileImport(moduleName, absolutePath, folderPath):
if folderPath not in sys.p... |
3314989 | from selene import tools
from selene.support import by
from selene.support.conditions import be
from selene.support.conditions import have
from selene.tools import wait_to, s, ss
_elements = ss('#todo-list li')
def visit():
tools.visit('https://todomvc4tasj.herokuapp.com')
wait_to(have.js_returned_true("ret... |
3314995 | from pyzeebe.grpc_internals.zeebe_job_adapter import ZeebeJobAdapter
from pyzeebe.grpc_internals.zeebe_message_adapter import ZeebeMessageAdapter
from pyzeebe.grpc_internals.zeebe_process_adapter import ZeebeProcessAdapter
# Mixin class
class ZeebeAdapter(ZeebeProcessAdapter, ZeebeJobAdapter, ZeebeMessageAdapter):
... |
3314997 | class ConnectionError(Exception):
"""
Wraps errors related with
requests to backend
"""
def __init__(self, response=None, message=None):
"""
Initializes the exception with the response
received from the backend
Params:
`response`: The response received f... |
3315036 | from .create_group_parser import CreateGroupParser
from .create_project_parser import CreateProjectParser
from .create_users_parser import CreateUserParser
from .delete_group_parser import DeleteGroupParser
from .delete_project_parser import DeleteProjectParser
from .login_parser import LoginParser
from .global_options... |
3315039 | from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework import status
from django.utils.translation import ugettext_lazy as _
@api_view()
def api_root(request, format=None):
return Response({
'fruit': rever... |
3315055 | import json
import base58
from dotenv import load_dotenv
import os
import requests
import time
from src.queries import getCurrentEpoch, getStartBlockEpoch, getActiveAllocations
# Indexer ID
ANYBLOCK_ANALYTICS_ID = os.getenv('ANYBLOCK_ANALYTICS_ID')
def getPoiQuery(indexerId, subgraphId, blockNumber, blockHash):
... |
3315074 | import json
import requests
octopus_server_uri = 'https://your.octopus.app/api'
octopus_api_key = 'API-YOURAPIKEY'
headers = {'X-Octopus-ApiKey': octopus_api_key}
def get_octopus_resource(uri):
response = requests.get(uri, headers=headers)
response.raise_for_status()
return json.loads(response.content.de... |
3315076 | import zmq
from zproc import util, serializer
class _TaskResultBase:
def __init__(self, server_address: str, task_id: bytes):
#: Passed on from the constructor
self.task_id = task_id
self._zmq_ctx = util.create_zmq_ctx()
self._server_meta = util.get_server_meta(self._zmq_ctx, ser... |
3315140 | import os
import time
import argparse
import torch
import torch.nn as nn
import torch.optim as optim
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
from torch.utils.data import DataLoader
from model.EDVR_arch import EDVR, CharbonnierLoss
from youku import YoukuDataset
from utils.util import c... |
3315189 | from django import template
from django.db.models import get_model
from oscar_support import utils
Message = get_model('oscar_support', 'Message')
TicketStatus = get_model('oscar_support', 'TicketStatus')
register = template.Library()
@register.assignment_tag(takes_context=True)
def get_messages(context, ticket, n... |
3315289 | from numba.core.descriptors import TargetDescriptor
from numba.core.options import TargetOptions
from .target import HSATargetContext, HSATypingContext
class HSATargetOptions(TargetOptions):
pass
class HSATargetDesc(TargetDescriptor):
options = HSATargetOptions
typingctx = HSATypingContext()
targetc... |
3315333 | import os
class AbstractGame():
""" Basic wrapper for every game used."""
def __init__(self):
self.process = None
self.model = None
self.score = None
self.score_extended = None
def run(self, advanced_results=False):
"""
Runs a whole game and returns result... |
3315342 | import psycopg2 as db
class PGStore:
def __init__(self, db_ip="localhost", db_port="5432", db_name=None, db_user=None, db_passwd=None):
self.db_ip = db_ip
self.db_port = db_port
self.db_name = db_name
self.db_user = db_user
self.db_passwd = <PASSWORD>
self.con = se... |
3315387 | if __name__ == '__main__':
x = 0 # before loop line
for i in range(10): # for line
print(i) # print line
print('TEST SUCEEDED!')
|
3315406 | from __future__ import print_function
import os
import torch
import torch.backends.cudnn as cudnn
import numpy as np
import argparse
from torch.nn.parallel import DataParallel, DistributedDataParallel
from data import AnnotationTransform, VOCDetection, COCODetection, detection_collate, VOCroot, COCOroot, \
VOC_300,... |
3315449 | class Solution:
def sumOddLengthSubarrays(self, arr: List[int]) -> int:
s1=0
l=len(arr)
for i in range(l):
for j in range(i,l,2):
for k in range(i,j+1):
s1+=arr[k]
return s1
|
3315452 | parameterized_module = """
module DFFRAM_RTL_{size}
(
CLK,
WE,
EN,
Di,
Do,
A
);
localparam A_WIDTH = {addr_width};
input wire CLK;
input wire [3:0] WE;
input wire EN;
input wire [31:0] Di;
output reg [31:0] Do;
in... |
3315468 | from .azblobclient import AzureBlobClient
from .azblobpath import AzureBlobPath
__all__ = [
"AzureBlobClient",
"AzureBlobPath",
]
|
3315470 | import math
def add_vec(u, v):
return (u[0]+v[0], u[1]+v[1])
def norm_vec(v):
return math.sqrt(v[0]*v[0] + v[1]*v[1])
def sub_vec(u, v):
return (u[0]-v[0], u[1]-v[1])
def rot90_vec(v):
return (v[1], -v[0])
def scal_vec(alpha, v):
return (alpha*v[0], alpha*v[1])
def unit_vec(v):
L = norm_ve... |
3315505 | from typing import Dict, TypeVar
K = TypeVar('K')
V = TypeVar('V')
def get_inverted_dict(d: Dict[K, V]) -> Dict[V, K]:
return {v: k for k, v in d.items()}
|
3315560 | import kubernetes
import requests
import os
import json
import datetime
import logging
from django.conf import settings
from substrapp.utils import timeit
from substrapp.exceptions import PodErrorException, PodTimeoutException
import time
logger = logging.getLogger(__name__)
MEDIA_ROOT = os.getenv('MEDIA_ROOT')
REGI... |
3315621 | from nibbler import Nibbler
from nibbler.extension.map_source import EXTENSION as map_source
CODE = """def foo():
a = 10
b = 20
c = 30
print("bar")
"""
nibbler = Nibbler(globals(), config=[map_source])
nibbler._constant_variables["print"] = print
@nibbler.nibble
def foo():
a = 10 # noqa: F841
... |
3315669 | import torch
import torch.nn as nn
from torch.nn import init
import functools
def weightsInit(layer):
classname = layer.__class__.__name__
if classname.find('Conv') != -1:
init.xavier_normal(layer.weight.data, gain=1)
elif classname.find('Linear') != -1:
init.xavier_normal(layer.weight.data... |
3315699 | from magma import *
from mantle.util.edge import falling
from loam import Part
from loam.peripherals.debounce import debounce
class VGA(Part):
IO = ["I", Bits(8), "HSYNC", In(Bit), "VSYNC", In(Bit)]
def __init__(self, board):
Part.__init__(self, board, 'VGA')
def on(self):
for i in range(... |
3315721 | from os import path
from .jstl_path_resolver import JstlPathResolver
from .generic_path_resolver import GenericPathResolver
class HyperClickPathResolver:
def __init__(self, view, str_path, roots, settings):
current_file = view.file_name()
current_dir = path.dirname(path.realpath(current_file))
... |
3315793 | import ray
from copy import deepcopy
from leaderboard.leaderboard_evaluator import LeaderboardEvaluator
from leaderboard.utils.statistics_manager import StatisticsManager
class ChallengeRunner():
def __init__(self, args, scenario, route, port=1000, tm_port=1002, debug=False):
args = deepcopy(args)
... |
3315823 | import ctypes
from vivsys.common import *
class ServiceControlManager:
def __init__(self):
self.hScm = None
def __enter__(self):
self.hScm = advapi32.OpenSCManagerW(None, None, SC_MANAGER_CREATE_SERVICE)
if not self.hScm:
raise ctypes.WinError()
return self
d... |
3315843 | from django.conf.urls import include, url
from .views import slack_message_callback
urlpatterns = [
url(r'^messages', slack_message_callback, name="slack-message-callback"),
]
|
3315910 | from gi.repository import Gtk
from gaphas.tool.scroll import on_scroll, scroll_tool
def test_scroll_tool_returns_a_controller(view):
tool = scroll_tool(view)
assert isinstance(tool, Gtk.EventController)
def test_offset_changes(view, scrolled_window):
tool = scroll_tool(view)
view.add_controller(to... |
3315928 | import random
from datetime import (
datetime,
timedelta,
)
from cachecow.decorators import cached_function
from django.contrib.auth.models import User
from django.core.cache import cache
from django.db import models
from django.db.models import (
Avg,
Count,
Max,
Min,
Sum,
)
from manabi.a... |
3315947 | from clang.cindex import Cursor, CursorKind
from ast.node import Node
from utility.code_generation import string_to_char_pack
class Enum(Node):
def __init__(self, **kwargs):
Node.__init__(self, **kwargs)
self.constants = [cursor.spelling for cursor in self.cursor.get_children() if cursor.kind == ... |
3315966 | import re
from os.path import join
from django.test import override_settings
from mock import patch
from testil import assert_raises, tempdir
import corehq.blobs as mod
from corehq.util.test_utils import generate_cases
from settingshelper import SharedDriveConfiguration
@generate_cases([
dict(root=None, msg=r"i... |
3315982 | from colicoords.data_models import Data
from colicoords.config import cfg
from colicoords.fileIO import load_thunderstorm
import tifffile
import numpy as np
import os
def listdir_fullpath(d):
return [os.path.join(d, f) for f in os.listdir(d)]
def load_data(dataset):
dclasses = ['binary', 'brigh... |
3316000 | from kaldo.observables.secondorder import SecondOrder
from kaldo.observables.thirdorder import ThirdOrder
from ase.calculators.lammpslib import LAMMPSlib
from kaldo.forceconstants import ForceConstants
from kaldo.conductivity import Conductivity
from kaldo.phonons import Phonons
from ase.io import read
import numpy as ... |
3316005 | import math
from collections import OrderedDict
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
import sys
from pathlib import Path
root_dir = (Path(__file__).parent / '..' / '..' ).resolve()
if str(root_dir) not in sys.path:
sys.path.insert(0, str(root_dir))
__all__ = [
'm... |
3316012 | import os
from models import WarpGenerator256 as Generator
from torch.backends import cudnn
from torchvision import transforms as T
from PIL import Image
import torch
import argparse
import yaml
import numpy as np
def get_config(config):
with open(config, 'r') as stream:
return yaml.load(stream)
def denor... |
3316056 | import pytest
from pygears import Intf, gear
from pygears.lib import decouple
from pygears.lib import group
from pygears.lib.delay import delay_rng
from pygears.lib.verif import directed, drv
from pygears.sim import sim
from pygears.typing import Queue, Uint
from pygears.util.test_utils import formal_check, synth_chec... |
3316069 | from skygear.settings import SettingsParser, add_parser
from .conversation_handlers import (register_conversation_hooks,
register_conversation_lambdas)
from .decorators import (after_conversation_created,
after_conversation_deleted,
... |
3316072 | from datetime import datetime
from typing import Optional
from pydantic import BaseModel, Field
class DateTimeModelMixin(BaseModel):
created_at: Optional[datetime] = Field(default_factory=datetime.now)
updated_at: Optional[datetime] = Field(default_factory=datetime.now)
|
3316105 | snippets = {
"a": "a[href]",
"a:blank": "a[href='http://${0}' target='_blank' rel='noopener noreferrer']",
"a:link": "a[href='http://${0}']",
"a:mail": "a[href='mailto:${0}']",
"a:tel": "a[href='tel:+${0}']",
"abbr": "abbr[title]",
"acr|acronym": "acronym[title]",
"base": "base[href]/",
"basefont": "basefont/"... |
3316120 | import scipy.stats as ss
from ..core.utilities import *
import numpy as np
class NormalTerciles:
def __init__(self, normal_width=0.34):
self.low_thresh, self.high_thresh = ss.norm(0, 1).interval(normal_width)
def fit(self, X, x_lat_dim=None, x_lon_dim=None, x_sample_dim=None, x_feature_dim=None):
x_lat_dim, x_l... |
3316141 | from setuptools import setup, find_packages
def get_version_and_cmdclass(package_path):
"""Load version.py module without importing the whole package.
Template code from miniver
"""
import os
from importlib.util import module_from_spec, spec_from_file_location
spec = spec_from_file_location(... |
3316148 | from .common import * # NOQA
import pytest
import requests
import semver
namespace = {'client': None,
'cluster': None,
'rancher_catalog': None,
'project': None}
m_chart_name = 'rancher-monitoring'
m_version = os.environ.get('RANCHER_MONITORING_V2_VERSION', None)
m_app = 'cattle-... |
3316178 | import os
import os.path as op
import json
# import logging
import base64
import yaml
import errno
import io
import math
from PIL import Image, ImageDraw
from maskrcnn_benchmark.structures.bounding_box import BoxList
from .box_label_loader import LabelLoader
def load_linelist_file(linelist_file):
... |
3316188 | class Solution:
def minSideJumps(self, obs: List[int]) -> int:
dp = [10000000, 1, 0, 1]
for i in obs:
dp[i] = 10000000
for j in range(1, 4):
if i != j:
dp[j] = min(dp[1] + (1 if j != 1 else 0),
dp[2] + (1 if j... |
3316229 | import argparse
import os
import json
import logging
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams
from utils import bd
from glob import glob
rcParams['axes.labelsize'] = 20
rcParams['xtick.labelsize'] = 20
rcParams['ytick.labelsize'] = 20
rcParams['legend.fonts... |
3316297 | import json
import logging
import os
import re
from decimal import Decimal
from django.core.cache import cache
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db.models.aggregates import Count
from django.db.models.expressions import Subquery, Value
from django.db.models.functions.co... |
3316327 | import numpy as np
import os
path_protein_benchmark = "/home/cyppsp/project_bayesian/zdock/2c/"
protein_list = np.loadtxt("temp", dtype='str')
def c_normal_mode_analysis(protein, rpath, lpath, output):
os.system("cp "+rpath+" /home/cyppsp/cNMA/Example/Example1/Input/"+protein+'_r_u.pdb')
os.system("cp "+lpath+" /... |
3316365 | import os
# For reading, visualizing, and preprocessing data
import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.model_selection import GroupKFold
from sklearn.preprocessing import StandardScaler
from xgboost import XGBClassifier
from alaska2.dataset import METHOD_TO_INDEX
from a... |
3316397 | import numpy as np
import torch
import torch.nn as nn
def cutmix(batch, alpha):
data, targets = batch
indices = torch.randperm(data.size(0))
shuffled_data = data[indices]
shuffled_targets = targets[indices]
lam = np.random.beta(alpha, alpha)
image_h, image_w = data.shape[2:]
cx = np.ran... |
3316421 | from itertools import chain
import hashlib
from django.db import models
from django.contrib.postgres.fields import JSONField, ArrayField
from django.core.serializers.json import DjangoJSONEncoder
from django.urls import reverse
from django.utils.translation import gettext as _, get_language
from dateutil.parser impo... |
3316441 | import json
import os
from pathlib import Path
class CocoFilter():
""" Filters the COCO dataset
"""
def _process_info(self):
self.info = self.coco['info']
def _process_licenses(self):
self.licenses = self.coco['licenses']
def _process_categories(self):
self... |
3316450 | import numpy as np
import scipy
from scipy import constants as C
def split_line():
print('--------------------')
print('scipy version', scipy.__version__)
print('常数和特殊函数')
print('真空中的光速', C.c)
print('普朗克常数', C.h)
print('1 英里等于多少米', C.mile)
print('1 英寸等于多少米', C.inch)
print('1 克等于多少千克', C.gram)
print('1 磅等于多少千克',... |
3316463 | import numpy as np
from numpy.random import rand
from cmath import sqrt
from scipy.linalg import eig, inv
import matplotlib
matplotlib.rcParams = matplotlib.rc_params_from_file('../../matplotlibrc')
from matplotlib import pyplot as plt
from solutions import arnoldi
def arnoldi_convergence_plot(A, b, k, view_vals, file... |
3316532 | import unittest
from esridump import esri2geojson
class TestEsriJsonToGeoJson(unittest.TestCase):
def setUp(self):
self.maxDiff = None
def assertEsriJsonBecomesGeoJson(self, esrijson, geojson):
out_json = esri2geojson(esrijson)
self.assertDictEqual(out_json, geojson)
class TestGeoJs... |
3316547 | from enum import Enum, IntEnum
from subprocess import CalledProcessError
from colored import fg, stylize
from .environment import EnvironmentVariable
class Color(Enum):
ERROR = fg("red")
NOTICE = fg("yellow")
class MessageLevel(IntEnum):
LOUD = 2
NORMAL = 1
QUIET = 0
def _level() -> MessageL... |
3316560 | import numpy as np
import scipy.sparse as sparse
import scipy.sparse.linalg as linalg
class Element(object):
def __init__(self, node_a, node_b):
self.node_a = node_a
self.node_b = node_b
def get_dof(self):
return (self.node_a.dof_a, self.node_a.dof_b,
... |
3316581 | from localstack.services.cloudformation.deployment_utils import generate_default_name
from localstack.services.cloudformation.service_models import GenericBaseModel
from localstack.utils.aws import aws_stack
class CloudFormationStack(GenericBaseModel):
@staticmethod
def cloudformation_type():
return "... |
3316596 | from .request import Request
from .response import Response
from .primitives import UString, Int
class DeleteRequest(Request):
"""
"""
opcode = 2
writes_data = True
parts = (
("path", UString),
("version", Int),
)
class DeleteResponse(Response):
"""
"""
opcode =... |
3316615 | import torch
import torchvision.transforms as transforms
from torchvision.datasets import ImageFolder
from torch.autograd import Variable
from model import Generator, Discriminator
# Hyperparameters
lr = 0.0002
batch_size = 32
image_size = 64
z_dim = 100
epochs = 80
# Image Preprocessing
transform = transforms.Compos... |
3316646 | from setuptools import setup, find_packages
setup(
name = "entrypointtest",
version = "0.1",
packages = find_packages(),
entry_points={
'entry.point.test': [
'entry_point_1=test_entry_point.module_one',
'entry_point_2=test_entry_point.module_two'
]
}
)
|
3316683 | import numpy as np
import cv2
from ...models.keypoint_detectors import SIFT_detect
def sample_homography(
shape, perspective=True, scaling=True, rotation=True, translation=True,
n_scales=5, n_angles=25, scaling_amplitude=0.1, perspective_amplitude_x=0.1,
perspective_amplitude_y=0.1, patch_rat... |
3316695 | import builtins
import sys
import inspect
import unittest
from crosshair.fnutil import (
fn_globals,
load_function_at_line,
resolve_signature,
set_first_arg_type,
)
from crosshair.util import set_debug
def with_invalid_type_annotation(x: "TypeThatIsNotDefined"): # type: ignore # noqa: F821
pass... |
3316715 | import requests
import csv
import json
import sys
def getInfo(ip):
url = "http://api.ipstack.com/" + ip + "?access_key=5abb1d1c4e614029ec30c94dee269d19"
response = requests.request("GET", url, params={"format":"json"})
return json.loads(response.text)
filename = sys.argv[1]
inputFile = open(filename, newline='... |
3316734 | from .csv_rule import CSVRule
from flask import Flask
app = Flask(__name__)
class limitAcuityRule(CSVRule):
# def __init__(self, name_in_csv, node_id):
# super().__init__(name_in_csv, node_id)
def __init__(self, name_in_csv, allowed_acuity, node_id):
super().__init__(name_in_csv, node_id)
... |
3316740 | from math import log
import torch
from torch import nn
import torch.nn.functional as F
import segmentation_models_pytorch as smp
from .functional import create_fixed_cupy_sparse_matrices, GraphQuadraticSolver
from losses import l1_loss_func, mse_loss_func
INPUT_DIM = 4
FEATURE_DIM = 64
def get_neighbor_affinity_no... |
3316775 | from typing import Any, Dict
from starlette.middleware import Middleware
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from xpresso import App, Path, Request, Response, Router
from xpresso.routing.mount import Mount
from xpresso.testclient import TestClient
def test_router_middle... |
3316783 | from attacker_model import *
from attacker import Attacker
import shutil
import pandas as pd
import os
import imgaug as ia
from imgaug import augmenters as iaa
import numpy as np
args['save_root']='./changed_images_1/'
args['cuda']="1"
args['ssim_thr']=SSIM_THR
args['max_iter']=60
#
# if os.path.exists(args['save_... |
3316789 | import multiprocessing
from pyomyo import Myo, emg_mode
# ------------ Myo Setup ---------------
q = multiprocessing.Queue()
def worker(q):
m = Myo(mode=emg_mode.FILTERED)
m.connect()
def add_to_queue(emg, movement):
q.put(emg)
m.add_emg_handler(add_to_queue)
def print_battery(bat):
print("Battery level... |
3316797 | import os
import gc
import sys
sys.path.insert(0, "/home/phan.huy.hoang/phh_workspace/") # noqa
import time
import copy
import argparse
import cv2
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from models import DBTextModel
from utils import (read_img, test_preprocess, visuali... |
3316817 | class Solution:
def isPalindrome(self, s: str) -> bool:
start = 0
end = len(s) - 1
while start < end:
while start < end and not s[start].isalnum():
start += 1
while start < end and not s[end].isalnum():
end -= 1
... |
3316819 | import json
def convertActions(inp, world):
action_list = []
for high_level_action in inp['actions']:
args = high_level_action['args']
# print("Action", high_level_action['name'], args)
if high_level_action['name'] == 'pickNplaceAonB':
action_list.extend([
[... |
3316897 | def get_character_weight(char: str, options: dict) -> int:
"""
Return an integer weight corresponding to `char`.
The weight is determined by the Unicode code point of `char` and ranges specified by `options`.
>>> char = '日'
>>> options = {
... 'default_weight': 200,
... 'ranges': [
... |
3316945 | class Solution:
def groupStrings(self, strings: List[str]) -> List[List[str]]:
def getHashKey(s):
if len(s) == 0:
return ('ZERO')
elif len(s) == 1:
return ('ONE')
else:
return tuple([(ord(s[i + 1]) - ord(s[i])) % 26 for i in... |
3317011 | import unittest
import mock
from chainer import testing
from chainer.training import extensions
from chainer.training import util
@testing.parameterize(
{'base_lr': 1, 'warmup_start_lr': 0.1,
'warmup_iter': 100, 'expect': [0.1, 0.991, 1, 1]},
{'base_lr': 0.1, 'warmup_start_lr': 1,
'warmup_iter': 1... |
3317013 | import numpy as py
print("Input: ",end="")
arr = py.array(input().split()).astype(int)
def count(arr, low, high):
if high >= low:
mid = low + (high - low)//2
if ((mid == high or arr[mid+1]==0) and (arr[mid]==1)):
return mid+1
if arr[mid]==1:
... |
3317029 | from ParadoxTrading.Fetch.ChineseFutures import FetchDominantIndex
from ParadoxTrading.Indicator import EFF
from ParadoxTrading.Chart import Wizard
fetcher = FetchDominantIndex()
rb = fetcher.fetchDayData('20100101', '20170101', 'rb')
eff = EFF(20).addMany(rb).getAllData()
wizard = Wizard()
main_view = wizard.addVi... |
3317036 | import paper
import database
import numpy as np
from collections import defaultdict
"""
Notes
- This needs to be a separate thing from database? Not part of the main package
- Maybe same thing for the .csv and .gml writing and so on? idk
- How to integrate this into my graph objects?
Functions needed:
- Clear any Pap... |
3317050 | import numpy as np
import time
def calc_sim():
a = np.random.random((512))
b = np.random.random((512))
c = np.mean(np.multiply(a,b))
return c
times = 100000
cs = []
t1 = time.time()
for i in range(times):
c = calc_sim()
cs.append(c.tolist())
t2 = time.time()
print(t2-t1)
cs = np.sort(cs)[... |
3317058 | a, b, c = map(int, input().split())
i, j, k = map(int, input().split())
uses = min(a / i, b / j, c / k)
print(a - i * uses, b - j * uses, c - k * uses)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.