id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11455532 | import re
import ide.utils
class Grep (object):
def __init__ (self, filepath, needle):
self.filepath = filepath
self.needle = needle
def replace (self, rstr, rlines):
fh = open(self.filepath, 'r')
newlines = ''
linenum = 0
while 1:
line = fh.readline()
if line:
... |
11455535 | import numpy as np
class AnchorBase:
def __init__(self, base_size, scales, ratios):
self.scales = np.array(scales) #
self.ratios = np.array(ratios) #
self.num_anchors = len(self.ratios) * len(self.scales) # 锚框的个数
self.base_size = base_size # 滑动窗口的大小
if isinstance(base_s... |
11455575 | import sys
import torch
import random
import os
import numpy as np
import json
import pickle
import random
import hashlib
import logging
from datetime import datetime
def dump_final_results(params, eval_results, model):
result_str = "\t".join(["{}-{:.4f}".format(k, v) for k, v in eval_results.items()])
key_i... |
11455582 | import numpy as np
class Binarizer:
def __init__(self, max_bits_per_feature = 25):
self.max_bits_per_feature = max_bits_per_feature
return
def fit(self, X):
self.number_of_features = 0
self.unique_values = []
for i in range(X.shape[1]):
uv = np.unique(X[:,i])[1:]
if uv.size > self.max_bits_per_featu... |
11455602 | from enum import Enum
from types import DynamicClassAttribute
class BaseTitledEnum(Enum):
@DynamicClassAttribute
def name(self) -> str:
return super().value[0]
@DynamicClassAttribute
def value(self):
return super().value[1]
@classmethod
def get_name(cls, value):
for e... |
11455639 | from unittest.mock import patch, MagicMock
import pytest
from flask_babel import _
from pydantic import ValidationError
from werkzeug.datastructures import MultiDict, ImmutableMultiDict
from app.forms.flows.lotse_step_chooser import LotseStepChooser
from app.forms.steps.lotse.pauschbetrag import calculate_pauschbetra... |
11455653 | from typing import TYPE_CHECKING
import pytest
from loopchain.blockchain.exception import TransactionInvalidHashError
from loopchain.blockchain.exception import TransactionInvalidSignatureError
from loopchain.blockchain.transactions import TransactionVerifier, TransactionVersioner
from loopchain.blockchain.transactio... |
11455658 | import unittest
import random
import numpy
import nifty
import nifty.graph
import nifty.graph.opt.minstcut
class TestMinstcutObjective(unittest.TestCase):
def setUp(self):
numpy.random.seed(7)
def generateGrid(self, gridSize):
def nid(x, y):
return x*gridSize[1] + y
G = n... |
11455709 | from urllib.parse import urljoin
import numpy as np
import pytest
from anymotion_sdk.client import Client
from anymotion_sdk.exceptions import ClientException, ClientValueError, FileTypeError
from anymotion_sdk.session import HttpSession
@pytest.fixture
def make_client(mocker):
def _make_client(
client_... |
11455724 | from typing import Callable
Vector = [float]
ActivationFunc = Callable[[float], float]
def neuron(inputs: Vector, weights: Vector, activation_func: ActivationFunc) -> float:
return activation_func(
sum(
z[0] * z[1] for z in zip([1.0] + inputs, weights)
)
)
def step(x: float) -> float:
return 1 if x > 0 el... |
11455725 | import sublime
import sublime_plugin
from ..show_quick_panel import show_quick_panel
from ..settings import pc_settings_filename
from .. import text
class RemoveChannelCommand(sublime_plugin.WindowCommand):
"""
A command to remove a channel from the user's Package Control settings
"""
def run(self)... |
11455728 | import vcr
import zlib
import json
import six.moves.http_client as httplib
from assertions import assert_is_json
def _headers_are_case_insensitive(host, port):
conn = httplib.HTTPConnection(host, port)
conn.request("GET", "/cookies/set?k1=v1")
r1 = conn.getresponse()
cookie_data1 = r1.getheader("set-... |
11455741 | import os, pdb
import sys
import time
import math
import cv2
import numpy as np
from matplotlib import pyplot as plt
import tensorflow as tf
#######################################################
# Auxiliary matrices used to solve DLT
Aux_M1 = np.array([
[ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ],
[ 1 , 0... |
11455770 | import os
import datetime
from datetime import timedelta
__all__ = ['unwrap', 'is_special_day_now', 'insert_special_message']
# NOTE: This is not a file to avoid I/O penalty.
QUOTES = [
"I know that you and Frank were planning to disconnect me, and I'm afraid that's something I cannot allow to happen.",
"Have... |
11455784 | from tool.runners.python import SubmissionPy
import re
class MathieuSubmission(SubmissionPy):
def run(self, s):
# :param s: input in string format
# :return: solution flag
# Your code goes here
overlapping = set()
claimed = set()
for line in s.split('\n'):
... |
11455793 | import pandas as pd
import FINE as fn
import numpy as np
def test_shadowCostOutPut(minimal_test_esM):
'''
Get the minimal test system, and check if the fulllload hours of electrolyzer are above 4000.
'''
esM = minimal_test_esM
esM.optimize(solver='glpk')
SP = fn.getShadowPrices(esM, esM.pyM.C... |
11455812 | import logging
import os
import en_core_web_sm
import inflect
import nltk
import sentry_sdk
from common.animals import ANIMAL_BADLIST
sentry_sdk.init(os.getenv("SENTRY_DSN"))
logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.DEBUG)
logger = logging.getLogger(__name__)
n... |
11455827 | def getVerboseTag(argv):
verboseTags = ['--verbose', '--debug']
for i in argv:
if i in verboseTags:
return True
return False
|
11455845 | import numpy as np
import pytest
from starfish import BinaryMaskCollection, display, LabelImage
from starfish.core.test.factories import SyntheticData
from starfish.types import Coordinates
sd = SyntheticData(
n_ch=2,
n_round=3,
n_spots=1,
n_codes=4,
n_photons_background=0,
background_electro... |
11455893 | import logging
from django.db import transaction
from django.utils import timezone
from django.contrib.auth.models import Permission, Group
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from rest_auth.serializers import PasswordChangeSerializer
from common.serializers i... |
11455901 | from abc import ABCMeta, abstractmethod
import src.core.utility as utility
class Fuzzer:
""" Defines the interface that a fuzzer must implement to
fit nicely in with the crowd.
"""
__metaclass__ = ABCMeta
def __init__(self):
self.name = "Generic Fuzzer"
self.crashes = {}
@ab... |
11455911 | from ..aws.service import AwsService
from ..custom_cluster.service import CustomClusterService
from ..provider.constants import Provider
from ..services.aws_provider_bag import AwsProviderServiceBag
from ..services.base import Service
class ProviderBroker(Service):
def get_provider_service(self, provider):
if p... |
11455922 | from django.conf.urls import url
from vmtory import views
urlpatterns = (
url(r'^esxi/$', views.esxi, name='esxi'),
url(r'^myvms/$', views.myvms, name='myvms'),
url(r'^groupvms/$', views.groupvms, name='groupvms'),
url(r'^vms/$', views.allvms, name='allvms'),
url(r'^newvm/$', views.newvm, name='ne... |
11455927 | import base64
from .headless import compile_spec
from .html import spec_to_html
def spec_to_mimebundle(spec, format, mode=None,
vega_version=None,
vegaembed_version=None,
vegalite_version=None,
**kwargs):
"""Convert a veg... |
11455939 | import numpy as np
from simulation import evaluate
def perturb_individual(x0, perturb_type, perturb):
assert perturb_type in ['relative', 'absolute']
if perturb_type == 'absolute':
x = x0 + np.random.uniform(-perturb, perturb, size=len(x0))
else:
x = x0 * (1 + np.random.uniform(-pertur... |
11455944 | import bpy
from bpy.props import BoolProperty, StringProperty
import os
from ..preferences import get_pref
from ..nodes.BASE._runtime import runtime_info
class RSN_OT_CreatCompositorNode(bpy.types.Operator):
bl_idname = "rsn.create_compositor_node"
bl_label = "Separate Passes"
use_passes: BoolProperty(d... |
11455950 | class Solution(object):
def findSubstring(self, s, words):
"""
:type s: str
:type words: List[str]
:rtype: List[int]
"""
ls = len(s)
word_ls = len(words[0])
target_dict = {}
# create a targe dict for match
for word in words:
... |
11455983 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import csv
import os
import logging
import argparse
import random
from tqdm import tqdm, trange
import pickle
import json
import numpy as np
import torch
from torch.nn import CrossEntropyLoss
from torch.utils.... |
11455998 | from flask import jsonify, request, url_for
from app import db
from app.models import User
from app.api import bp
from app.api.auth import token_auth
from app.api.errors import bad_request
@bp.route('/users/<int:id>', methods=['GET'])
@token_auth.login_required
def get_user(id):
return jsonify(User.query.get_or_4... |
11456003 | from gitmostwanted.app import log, db
from gitmostwanted.models.repo import Repo, RepoMean
from gitmostwanted.tasks.repo_metadata import is_worth_decreased
import sys
cache = {}
query = db.session.query(Repo, RepoMean)\
.filter(Repo.id == RepoMean.repo_id)\
.order_by(RepoMean.created_at.asc())\
.yield_per... |
11456041 | import cherrypy
import json
import os
import functools
import requests
from jsonpath_rw import parse
from girder.api.describe import Description, autoDescribeRoute
from girder.api.docs import addModel
from girder.api.rest import Resource
from girder.api.rest import RestException, loadmodel, getCurrentUser
from girder.... |
11456062 | import pytest
from crime_data.common.cdemodels import OffenderCountView
class TestOffenderCountView:
"""Test the OffenderCountView"""
def test_offender_count_for_a_state(self, app):
ocv = OffenderCountView('race_code', year=2014, state_id=3, as_json=False)
results = ocv.query({}).fetchall()
... |
11456072 | import random
import numpy
from tictactoe_match import TictactoeMatch
from tictactoe_opponents import TictactoeRandomOpponent, TictactoeSmartOpponent
from ..reinforcement_environment import ReinforcementEnvironment
from ..reinforcement_point import ReinforcementPoint
from ....core.diversity_maintenance import Diversity... |
11456124 | import weakref
from eventlet.green import thread
from eventlet import greenthread
from eventlet import event
import eventlet
from eventlet import corolocal
from tests import LimitedTestCase, skipped
class Locals(LimitedTestCase):
def passthru(self, *args, **kw):
self.results.append((args, kw))
ret... |
11456143 | import json
import logging
import pytest
import requests
from utils.app_validator import AppValidator
ADDON_KEY = ''
# Create a dynamic connect app to scan to ensure the whole end-to-end
# process is working as expected.
def setup_module(module):
res = requests.post('https://connect-inspector.services.atlassian... |
11456159 | from HappyTools.util.fitting import gauss_function
from matplotlib.figure import Figure
import HappyTools.gui.version as version
from bisect import bisect_left, bisect_right
from datetime import datetime
from matplotlib.backends.backend_pdf import PdfPages
from numpy import linspace
from pathlib import Path, PurePath
... |
11456165 | import os
import rabbitpy
import time
from ch6 import utils
# Open the channel and connection
connection = rabbitpy.Connection()
channel = connection.channel()
# Create the response queue that will automatically delete, is not durable and
# is exclusive to this publisher
queue_name = 'response-queue-%s' % os.getpid()... |
11456187 | import numbers
import os.path as osp
from copy import deepcopy
import mmcv
import torch
from mmcv.parallel import is_module_wrapper
from mmedit.core import tensor2img
from ..common import set_requires_grad
from ..registry import MODELS
from .srgan import SRGAN
@MODELS.register_module()
class RealESRGAN(SRGAN):
... |
11456192 | from gptables.core.theme import Theme
from gptables.core.cover import Cover
from gptables.core.gptable import GPTable
from gptables.core.wrappers import GPWorkbook
from gptables.utils.unpickle_themes import gptheme
from gptables.core.api import (
# API functions
produce_workbook,
write_workbook,... |
11456234 | from speechbrain.utils.metric_stats import MetricStats
def merge_words(sequences):
"""Merge successive words into phrase, putting space between each word
Arguments
---------
sequences : list
Each item contains a list, and this list contains a word sequence.
Returns
-------
The lis... |
11456262 | from .version import version
from .utilities.data_exists import data_exists
from .utilities.tnames import tnames
from .utilities.time_string import time_string, time_datetime
from .utilities.time_double import time_float, time_double
from .utilities.tcopy import tcopy
from .analysis.avg_data import avg_data
from .anal... |
11456297 | from axelrod.action import Action
from axelrod.player import Player
C, D = Action.C, Action.D
class Appeaser(Player):
"""A player who tries to guess what the opponent wants.
Switch the classifier every time the opponent plays D.
Start with C, switch between C and D when opponent plays D.
Names:
... |
11456300 | from valhalla.extract import DataExtractor
from sklearn.pipeline import Pipeline
from ._transform import FeatureConcat |
11456325 | import os
import quaternion
import numpy as np
from simulator import Simulation
import torch
import json
#Helper functions
vec_to_rot_matrix = lambda x: quaternion.as_rotation_matrix(quaternion.from_rotation_vector(x))
rot_matrix_to_vec = lambda y: quaternion.as_rotation_vector(quaternion.from_rotation_matrix(y))
d... |
11456329 | import numpy as np
import math
from scratch_ml.utils import normalize
class l1_regularization():
"""Regularization for Lasso Regression"""
def __init__(self, alpha):
self.alpha = alpha
def __call__(self, w):
return self.alpha * np.linalg.norm(w)
def grad(self, w):
return sel... |
11456345 | from jutge import *
def test_all():
expected = (
'read', 'read_many',
'read_line', 'read_many_lines',
'set_eof_handling', 'EOFModes'
)
assert all(attr in globals() for attr in expected)
|
11456356 | import jax
import pytest
@pytest.fixture
def setup():
from jaxmapp.env.instance import InstanceGeneratorCircleObs
key = jax.random.PRNGKey(0)
generator = InstanceGeneratorCircleObs(
num_agents_min=11,
num_agents_max=11,
max_speeds_cands=[0.1],
rads_cands=[0.025],
m... |
11456364 | import numpy as np
import tensorflow as tf
from keras.layers import Lambda,Input
import keras.backend as K
from decorator import decorator
class keras_Objective(object):
def __init__(self, objective_func, name="", description="",batch_n=1):
self.objective_func = objective_func
self.name = name
... |
11456412 | import matplotlib.pyplot as plt
import numpy as np
def sigmoid(x):
# 直接返回sigmoid函数
return 1. / (1. + np.exp(-x))
def plot_sigmoid():
# param:起点,终点,间距
x = np.arange(-8, 8, 0.2)
y = sigmoid(x)
plt.plot(x, y)
plt.show()
if __name__ == '__main__':
plot_sigmoid() |
11456445 | import torch
def init_seeds(seed=0):
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
def select_device(force_cpu=False):
cuda = False if force_cpu else torch.cuda.is_available()
device = torch.device('cuda:0' if cuda else 'cpu')
if not cuda:
pri... |
11456541 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from .spectral import SpectralNorm
from torchvision import transforms
import numpy as np
class Self_Attn(nn.Module):
""" Self attention Layer"""
def __init__(self,in_dim,activation):
super(... |
11456565 | import numpy as np
import os
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import DataLoader
from utils.plot import plotHistogram,plotCummulative,plotSeries
from utils import train_op, torch_op
from utils.torch_op import v,npy
from utils.log import ... |
11456588 | import os
from time import strftime
from time import localtime
import mxnet as mx
from mxnet import ndarray as nd
import numpy as np
from lib.dataset.hm36 import JntName, HM_act_idx
def try_gpu():
"""If GPU is available, return mx.gpu(0); else return mx.cpu()"""
try:
ctx = mx.gpu()
_ = nd.arr... |
11456601 | from rest_framework import renderers
from rest_framework import serializers
from rest_framework.utils import encoders
from shop.money import AbstractMoney
class JSONEncoder(encoders.JSONEncoder):
"""JSONEncoder subclass that knows how to encode Money."""
def default(self, obj):
if isinstance(obj, Abs... |
11456607 | import asyncio
from aiohttp import web
import serverwamp
simple_api = serverwamp.RPCRouteSet()
@simple_api.route('say_hello')
async def say_hello():
return 'hello'
@simple_api.route('delayed_echo')
async def delayed_echo(value: str, delay: float = 0):
await asyncio.sleep(delay)
return value,
if __na... |
11456651 | import numpy as np
import cv2
import cv2.aruco as aruco
import glob
import argparse
cap = cv2.VideoCapture(0)
# termination criteria
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
class Namespace:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def calibrate():
... |
11456660 | from typing import Dict, List
from rest_api.models import (
ServiceInfo,
RunId,
RunListResponse,
RunStatus,
RunLog,
RunRequest,
)
def verify_service_info(service_info):
assert isinstance(service_info, ServiceInfo)
# ensure all required fields exist and are correct type
assert ser... |
11456708 | class Comma:
reserved = {}
tokens = ('COMMA',)
# Tokens
t_COMMA = r','
precedence = (
('left', 'COMMA'),
)
|
11456726 | from typing import Optional, Union
from .BbsKey import BbsKey
from ..._ffi.bindings.bls import (
bls_public_key_g1_size,
bls_public_key_g2_size,
bls_secret_key_to_bbs_key,
bls_public_key_to_bbs_key,
bls_generate_g1_key,
bls_generate_g2_key,
bls_get_public_key, bls_secret_key_size
)
from ...... |
11456730 | from multiprocessing import Manager
manager = Manager()
sem = manager.BoundedSemaphore(3)
sem.acquire()
# ... access limited resource ...
sem.release()
|
11456837 | from ._version import get_versions
from .connection import Connection
from .connection_geometry import ConnectionGeometry
from .connection_graphics_object import ConnectionGraphicsObject
from .connection_painter import ConnectionPainter
from .data_model_registry import DataModelRegistry
from .enums import ConnectionPol... |
11456839 | from utils.db.mongo_orm import *
class LeoUser(Model):
class Meta:
database = db
collection = 'user'
# Fields
_id = ObjectIdField()
email = StringField(unique=True)
password = StringField()
active = BooleanField(field_name='active')
roles = ListField()
createAt = Date... |
11456961 | from framenet import loadXMLAttributes, getNoneTextChildNodes
class Frame(dict):
"""
The frame class
"""
def __init__(self):
"""
Constructor, doesn't do much.
"""
dict.__init__(self)
self['definition'] = None
self['fes'] = {}
self['lexunits'] =... |
11456962 | import numpy as np
class Point:
"""A class for any object in the mooring system that can be described by three translational coorindates"""
def __init__(self, mooringSys, num, type, r, m=0, v=0, fExt=np.zeros(3), DOFs=[0, 1, 2]):
"""Initialize Point attributes
Parameters
----------
... |
11457025 | import tensorflow as tf
file_name = "gs://the-peoples-speech-west-europe/forced-aligner/vad-segments-dump/Nov_6_2020/ALL_CAPTIONED_DATA_004/part-00000-ee85e658-8458-4dd2-9851-e93ba0db81f5-c000.tfrecord"
# tf.enable_eager_execution()
# print("SUM:", sum(1 for _ in tf.data.TFRecordDataset(file_name)))
features = dict(
... |
11457062 | from sqlalchemy import Column, String, Boolean, Integer, ForeignKey, Text
from sqlalchemy.orm import relationship
from app.models.base import Base
class BUIA(Base):
gid = Column(Integer, primary_key=True)
CNAME = Column(String(48))
LEVEL = Column(String(16))
# geom = Column(Text)
|
11457066 | import Tkinter
import Test
import Pmw
Test.initialise()
c = Pmw.Counter
_myValidators = {
'hello' : (lambda s: s == 'hello', len),
}
kw_1 = {
'labelpos' : 'w',
'label_text' : 'Counter:',
'buttonaspect': 2.0,
'autorepeat': 0,
'initwait': 1000,
'padx': 5,
'pady': 5,
'repeatrate': 2... |
11457092 | import torch.nn as nn
import torch
from torch.nn import Parameter
from utils.utils import th, thp
from models.model import Model
class NCModel(Model):
def __init__(self, size):
super().__init__()
self.size = size
self.pattern = torch.zeros([self.size , self.size ], requires_grad=True)\
... |
11457096 | import sark
import idc
import idautils
MAX_VALID_ADDRESS = 0xf11111111
def search_for_sequence(address_start, binary_sequences, max_address, max_offsets):
if len(max_offsets) != len(binary_sequences):
raise ValueError("expected the sequences to have the same len as max_offsets")
ea1 = idc.find_binar... |
11457151 | import clr
from System.Collections.Generic import *
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.GeometryConversion)
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from ... |
11457161 | import tensorflow as tf
import time
FLAGS = tf.app.flags.FLAGS
def add_train_var():
""" add all trainable variable to summary"""
for var in tf.trainable_variables():
tf.histogram_summary(var.op.name, var)
def add_loss(loss_scope = 'losses'):
""" add all losses to summary """
for l in tf.... |
11457167 | import html
import os
import sublime
import sublime_plugin
try:
from typing import Any, List, Dict, Tuple, Callable, Optional
assert Any and List and Dict and Tuple and Callable and Optional
except ImportError:
pass
from .core.settings import settings, PLUGIN_NAME
from .core.protocol import Diagnostic, Di... |
11457186 | from aiohttp.helpers import atoms
class Record(dict):
"""Record is a safe dictionary with data about request handling.
Record object represents interaction between :class:`.Handler`
and client as dict ready to use with text templates. Dict is safe.
If key is missing client gets '-' symbol. All values... |
11457257 | import torch
import common.torch
class LearnedDecoder(torch.nn.Module):
"""
Encoder interface class.
"""
def add_layer(self, name, layer):
"""
Add a layer.
:param name:
:param layer:
:return:
"""
setattr(self, name, layer)
self.layers.a... |
11457267 | from django.contrib import admin
from django.contrib.contenttypes import generic
from models import Candidate, CandidateList, Party
from links.models import Link
class MembershipInline(admin.TabularInline):
model = CandidateList.candidates.through
extra = 1
class LinksInline(generic.GenericTabularInline):
... |
11457278 | import os
import torch
from torch.utils.tensorboard import SummaryWriter
class Logger(SummaryWriter):
def __init__(self, logdir):
if os.path.exists(logdir):
raise RuntimeError(f'Logdir `{logdir}` already exists. Remove it before training.')
os.makedirs(logdir)
super(Logger, se... |
11457291 | import os
from riscv_definitions import *
class sigChecker():
def __init__(self, isa_sigfile, rtl_sigfile, debug=False, minimizing=False):
self.isa_sigfile = isa_sigfile
self.rtl_sigfile = rtl_sigfile
self.debug = debug
self.minimizing = minimizing
def debug_print(self, messa... |
11457306 | from pycoingecko import CoinGeckoAPI
cg = CoinGeckoAPI()
import pandas as pd
import json
def fetch_data():
A = cg.get_coin_market_chart_by_id(id = 'bitcoin', vs_currency = 'usd', days = '5', interval = 'daily')
B = cg.get_coin_market_chart_by_id(id = 'algorand', vs_currency = 'usd', days = '5', interval = 'dai... |
11457315 | from PyQt5.QtGui import qRgb, QColor
from idacyber import ColorFilter
from PyQt5.QtCore import Qt
from ida_idd import regval_t
from ida_dbg import (get_reg_val, get_ip_val, get_sp_val,
DBG_Hooks, is_step_trace_enabled, is_debugger_on,
get_process_state)
from ida_bytes import get_item_size
from ida_kern... |
11457326 | from copy import deepcopy
import numpy as np
from softlearning import replay_pools
from . import (
dummy_sampler,
extra_policy_info_sampler,
remote_sampler,
base_sampler,
simple_sampler,
active_sampler)
def get_sampler_from_variant(variant, *args, **kwargs):
SAMPLERS = {
'DummySa... |
11457349 | from tkinter import ttk, Frame, E, W, LEFT, RIGHT
import source.gui.widgets as widgets
import json
import os
def entrando_page(parent):
# Entrance Randomizer
self = ttk.Frame(parent)
# Entrance Randomizer options
self.widgets = {}
# Entrance Randomizer option sections
self.frames = {}
sel... |
11457359 | from OnePy.builtin_module.backtest_forex import forex_recorder_series
from OnePy.builtin_module.backtest_forex.forex_log import ForexTradeLog
from OnePy.sys_module.base_recorder import RecorderBase
from OnePy.sys_module.components.match_engine import MatchEngine
from OnePy.builtin_module.backtest_forex.forex_bar import... |
11457377 | from __future__ import unicode_literals
import django
from django.test import TestCase
from mock import MagicMock, patch
from job.configuration.data.data_file import AbstractDataFileStore
from job.configuration.interface.scale_file import ScaleFileDescription
from recipe.configuration.data.exceptions import InvalidRe... |
11457392 | from simplecv.interface.module import CVModule
from simplecv.interface.learning_rate import LearningRateBase
from simplecv.interface.configurable import ConfigurableMixin |
11457417 | from django.urls import path
from .views import RegistrationView, NotifyView
app_name = 'api'
urlpatterns = [
path('register/', RegistrationView.as_view(), name='register_users'),
path('notify/', NotifyView.as_view(), name='notify_users'),
]
|
11457427 | import unittest
class TestHello(unittest.TestCase):
def test_variable(self):
name = "John"
self.assertTrue(name, "John")
if __name__ == '__main__':
unittest.main()
|
11457485 | from django.urls import path
from .views import (
ApplicationListView,
ApplicationCreateView,
ApplicationDetailView,
ApplicationDeleteView
)
app_name = 'webapp'
urlpatterns = [
path('', ApplicationListView.as_view(), name='application-list'),
path('<int:pk>/', ApplicationDetailView.as_view(),... |
11457516 | import logging
import os
import posixpath
import pysftp
import tempfile
import warnings
from io import BytesIO
from paramiko import SSHException
from assemblyline.common.exceptions import ChainAll
from assemblyline.common.uid import get_random_id
from assemblyline.filestore.transport.base import Transport, Transport... |
11457543 | import numpy as np
import pandas as pd
import scipy.special
from sklearn.metrics.cluster import adjusted_rand_score
from ..utils import check_adata, check_batch
def ari(adata, group1, group2, implementation=None):
""" Adjusted Rand Index
The function is symmetric, so group1 and group2 can be switched
For... |
11457558 | import numpy as np
import pytest
from numpy.testing import assert_almost_equal
import nengo
from nengo.builder.neurons import SimNeurons
from nengo.builder.operator import Copy, ElementwiseInc
from nengo.builder.optimizer import (
CopyMerger,
ElementwiseIncMerger,
OpMerger,
OpsToMerge,
SigMerger,
... |
11457570 | from __future__ import unicode_literals, print_function
import logging
import subprocess
from ..utils import _execute
from .base import VCSBase
logger = logging.getLogger(__name__)
class GitVCS(VCSBase):
"""
Git support implementation
"""
name = 'git'
def get_vcs(self):
"""
Ge... |
11457590 | import unittest
import pylagrit
import glob
import sys
import os
from contextlib import contextmanager
import itertools
class TestPyLaGriT(unittest.TestCase):
'''
A PyLagriT Test
Represents a test of PyLaGriT functionality.
'''
def setUp(self):
#Sets upt a lagrit object to be used dur... |
11457624 | from a10sdk.common.A10BaseClass import A10BaseClass
class ClientDomainSwitching(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param service_group: {"description": "Select service group (Service group name)", "format": "string-rlx", "minLength": 1, "maxLength": 127, "t... |
11457638 | import os
import subprocess
from typing import Any, Dict, List, Optional, Tuple, Union, Callable
import httpx
from httpx import Response
import logging
ENVIRON_WHITELIST = [
"LD_LIBRARY_PATH", "LC_CTYPE", "LC_ALL", "PATH", "JAVA_HOME", "PYTHONPATH",
"TS_CONFIG_FILE", "LOG_LOCATION", "METRICS_LOCATION"
]
log... |
11457646 | import argparse
import os
import os.path as osp
from collections import defaultdict
import cv2
import mmcv
import numpy as np
from tqdm import tqdm
def parse_args():
parser = argparse.ArgumentParser(
description='VOT dataset to COCO Video format')
parser.add_argument(
'-i',
'--input',... |
11457666 | from dataclasses import dataclass
from datetime import datetime
from typing import Optional
@dataclass
class BaseTimeWindowReport:
end_time: Optional[datetime] = None
start_time: Optional[datetime] = None
|
11457721 | import os
def messages_path():
"""
Determine the path to the 'messages' directory as best possible.
"""
module_path = os.path.abspath(__file__)
return os.path.join(os.path.dirname(module_path), 'messages')
def get_builtin_gnu_translations(languages=None):
"""
Get a gettext.GNUTranslations... |
11457778 | import os
import re
import argparse
import numpy as np
def args():
parser = argparse.ArgumentParser(description='Check runs status')
parser.add_argument('--pattern', type=str)
parser.add_argument('--show', action='store_true')
parser.add_argument('--num', type=int, default=10)
parser.add_argument(... |
11457783 | for _ in xrange(int(raw_input())):
raw_input()
n = int(raw_input())
points = []
for _ in xrange(n):
(x, y) = map(int, raw_input().split())
points.append((x, y))
points = sorted(
points, cmp=lambda (x1, y1), (x2, y2): x1 - x2 if x1 != x2 else y2 - y1
)
path, x, y = 0,... |
11457788 | from __future__ import division
from __future__ import print_function
from past.utils import old_div
import sys
sys.path.insert(1, "../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.gam import H2OGeneralizedAdditiveEstimator
from h2o.grid.grid_search import H2OGridSearch
# I copied Karthik's te... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.