id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9973176 | def print_msg_box(msg, indent=1, width=None, title=None):
"""Print message-box with optional title."""
lines = msg.split('\n')
space = " " * indent
if not width:
width = max(map(len, lines))
box = f'╔{"═" * (width + indent * 2)}╗\n' # upper_border
if title:
box += f'║{space}{tit... |
9973200 | import tensorflow as tf
from tensorpack import (BatchData)
from tqdm import tqdm
from config import config as FLAGS
from data import PNGDataFlow, save_images
from networks import network
class Attacker:
def __init__(self, sess):
self.sess = sess
self.step_size = FLAGS.step_size / 255.0
se... |
9973229 | import platform
import matplotlib as mpl
mpl.use('Agg')
collect_ignore = []
# Ignore sporco.cupy tests if importlib.util or cupy not available
try:
import importlib.util
except ImportError:
collect_ignore.append('cupy')
else:
try:
import cupy
except ImportError:
collect_ignore.append(... |
9973266 | import os
import sys
import time
import versioneer
VERSION = versioneer.get_version()
RELEASE_NOTES = 'docs/release_notes.rst'
BUILD_DATE = time.strftime("%a, %d %b %Y %H:%M:%S + 0000", time.gmtime())
TAG_MODES = ['major', 'minor', 'patch']
def cmd(command, dry_run=False):
print('About to execute "%s"...' % com... |
9973281 | import re
import pandas as pd
import numpy as np
from math import ceil
from .XlsxOperationException import XlsxOperationException
from .WeatherWindowCSVReader import read_weather_window, extend_weather_window
from ..model import DefaultMasterInputDict
from .GridSearchTree import GridSearchTree
class XlsxReader:
... |
9973295 | import unittest
from pyquery.pyquery import PyQuery
from .browser_base import TextExtractionMixin
class TestInnerText(unittest.TestCase, TextExtractionMixin):
def _prepare_dom(self, html):
super(TestInnerText, self)._prepare_dom(html)
self.pq = PyQuery(self.last_html)
def _simple_test(self, ... |
9973329 | import graphene
from graphene_django.types import DjangoObjectType
from wagtail.core.models import Collection
from ..registry import registry
from ..utils import resolve_queryset
from .structures import QuerySetList
class CollectionObjectType(DjangoObjectType):
"""
Collection type
"""
class Meta:
... |
9973351 | from decimal import Decimal
import factory
from .project.models import Restaurant, Chef, Menu, PriceBracket, MenuItem, \
MenuItemOption, MenuItemOptionChoice
class RestaurantFactory(factory.DjangoModelFactory):
title = "<NAME>"
class Meta:
model = Restaurant
class ChefFactory(factory.DjangoMo... |
9973364 | import torch
import torch.nn as nn
import torchvision.models as models
VGG_BN = {
11: models.vgg11_bn,
13: models.vgg13_bn,
16: models.vgg16_bn,
19: models.vgg19_bn
}
class VggEncoder(nn.Module):
"""A ResNet that handles multiple input images and outputs skip connections"""
def __init__(self... |
9973386 | import unittest
import sys
from curtsies.window import BaseWindow, FullscreenWindow, CursorAwareWindow
from io import StringIO
from unittest import skipIf
fds_closed = not sys.stdin.isatty() or not sys.stdout.isatty()
class FakeFullscreenWindow(FullscreenWindow):
width = property(lambda self: 10)
height = ... |
9973399 | import operator
from typing import Dict, Union
Resolvable = Union["AstNode", int, float, str]
QueryConfig = Union["Query", dict, Resolvable]
class Query:
def __init__(self, expr: Union[Resolvable, dict]):
self.query = AstNode.build(expr)
def __call__(self, context):
return self.query(context... |
9973437 | from appenlight_client.utils import import_module, deco_func_or_method
from appenlight_client.timing import time_trace
ignore_set = frozenset()
def add_timing(min_duration=0.1):
module = import_module('pysolr')
if not module:
return
def general_factory(slow_call_name):
def gather_args(so... |
9973464 | import gzip
import os
import hashlib
from datetime import datetime
import rasterio
import requests
from tqdm import tqdm
def bounds_from_transform(transform, width, height):
"""Calculate raster bounds from transform, width & height."""
xres, yres = transform.a, transform.e
left, top = transform.c, transf... |
9973469 | from dataclasses import dataclass
import numpy as np
from paralleldomain.model.annotation.common import Annotation
@dataclass
class SurfaceNormals3D(Annotation):
"""Represents a mask of surface normals for a point cloud.
Args:
normals: :attr:`~.SurfaceNormals3D.vectors`
Attributes:
nor... |
9973489 | import mxnet as mx
import numpy as np
import time
def vgg16_symbol():
data = mx.sym.Variable('data')
# conv1
conv1_1 = mx.sym.Convolution(data=data, kernel=(3, 3), pad=(1, 1), num_filter=64, name="conv1_1")
relu1_1 = mx.sym.Activation(data=conv1_1, act_type="relu", name="relu1_1")
conv1_2 = mx.sy... |
9973503 | import ckan.logic as logic
import ckan.plugins.toolkit as tk
import ckanext.hdx_pages.model as pages_model
# from ckanext.hdx_users.helpers.permissions import Permissions
import ckanext.hdx_pages.helpers.helper as h
NotFound = tk.ObjectNotFound
_ = tk._
def page_create(context, data_dict):
'''
Only sysadmi... |
9973528 | import typing
from funboost.publishers.base_publisher import AbstractPublisher
from funboost.consumers.base_consumer import AbstractConsumer
from funboost.factories import publisher_factotry
from funboost.factories import consumer_factory
"""
这个有两个用途
1 是给用户提供一种方式新增消息队列中间件种类,(框架支持了所有知名类型消息队列中间件或模拟中间件,这个用途的可能性比较少)
2 可以... |
9973553 | from __future__ import print_function, division, absolute_import
import torch as th
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
from .custom_layers import GaussianNoiseVariant
try:
from preprocessing.preprocess import getNChannels
except ImportError:
from ..prepr... |
9973561 | from .common import InfoExtractor
from ..utils import (
float_or_none,
int_or_none,
)
class DotsubIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?dotsub\.com/view/(?P<id>[^/]+)'
_TESTS = [{
'url': 'https://dotsub.com/view/9c63db2a-fa95-4838-8e6e-13deafe47f09',
'md5': '21c7ff600f54... |
9973684 | import argparse
import sys
from pathlib import Path
from ps1_argonaut.DIR_DAT import DIR_DAT
from ps1_argonaut.configuration import Configuration, PARSABLE_GAMES, SLICEABLE_GAMES, SUPPORTED_GAMES
from ps1_argonaut.files.DATFile import DATFile
from ps1_argonaut.files.IMGFile import IMGFile
from ps1_argonaut.files.WADFi... |
9973738 | from collections import namedtuple
import os
import pytest
from leapp import reporting
from leapp.exceptions import StopActorExecutionError
from leapp.libraries.common import repofileutils, rhsm
from leapp.libraries.common.testutils import (
create_report_mocked,
CurrentActorMocked,
logger_mocked
)
from l... |
9973748 | DEFINITIONS = {
'error': 'because value not valid',
# app
'BILIBILI': 'com.typcn.Bilibili',
# replacement
'可以是中文': ('比如', 'hello', 'Xee³'),
# device
'CHERRY_3494': ['0x046a', '0x0011'],
'UIElementRole::自定义UI组件': '用作 filter',
# modifierdef
'Modifier::KEYLOCK': '',
}
MAPS = [
... |
9973752 | from fractions import Fraction
from functools import reduce
def product(fracs):
t =reduce(lambda numerator,denominator:numerator*denominator,fracs)
# complete this line with a reduce statement
return t.numerator, t.denominator
if __name__ == '__main__':
fracs = []
for _ in range(int(in... |
9973757 | import protocol
from member import Component
class Commander(Component):
def __init__(self, member, leader, ballot_num, slot, proposal, commander_id, peers):
super(Commander, self).__init__(member)
self.leader = leader
self.ballot_num = ballot_num
self.slot = slot
self.pro... |
9973804 | import unittest
from keras_transformer.backend import keras
from keras_transformer import get_encoders, get_decoders
class TestGetDecoderComponent(unittest.TestCase):
def test_sample(self):
encoder_input_layer = keras.layers.Input(shape=(512, 768), name='Encoder-Input')
decoder_input_layer = kera... |
9973828 | import argparse
import cmd
from typing import Any
from ..connection import get_connection
class SQL(cmd.Cmd):
intro = 'SQL shell powered by DuckDB. Type help or ? to list commands.\n'
prompt = '(sql) '
def __init__(self, **kwargs: Any) -> None:
self.arguments = self.get_arguments(kwargs)
... |
9973851 | from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorCollection, AsyncIOMotorDatabase
from models.settings import get_settings
class MongoDatabase:
mongo_client: AsyncIOMotorClient
def connect():
settings = get_settings()
MongoDatabase.mongo_client = AsyncIOMotorClient(
settings.mongo... |
9973900 | import lasagne
import cascadenet.network.layers as l
from collections import OrderedDict
def cascade_resnet(pr, net, input_layer, n=5, nf=64, b=lasagne.init.Constant, **kwargs):
shape = lasagne.layers.get_output_shape(input_layer)
n_channel = shape[1]
net[pr+'conv1'] = l.Conv(input_layer, nf, 3, b=b(), na... |
9973929 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from tensorboardX import SummaryWriter
import os
import unittest
# try:
import numpy as np
import caffe2.python.brew as brew
import caffe2.python.cnn as cnn
import caffe... |
9973971 | from collections import Counter
import pdb
class BubbleChain:
"""
BubbleChain object which is a set of bubble objects
"""
__slots__ = ['bubbles', 'sorted', 'ends', 'key', 'id', 'parent_chain', 'parent_sb']
def __init__(self):
"""
initialize the BubbleChain as a set of bubble
... |
9973985 | from __future__ import division, print_function, absolute_import
import numpy as np
def lngmie(ghs, g1, g2, be, be2):
# be = beta * eps
lng = np.log(ghs) + (be*g1+be2*g2)/ghs
return lng
def dlngmie_dxhi00(ghs, g1, g2, be, be2):
# be = beta * eps
ghs, dghs = ghs
g1, dg1 = g1
g2, dg2 = g2... |
9973988 | from typing import NamedTuple
from kfp.components import create_component_from_func, InputPath, OutputPath
def keras_train_classifier_from_csv(
training_features_path: InputPath('CSV'),
training_labels_path: InputPath('CSV'),
network_json_path: InputPath('KerasModelJson'),
model_path: OutputPath('Keras... |
9974019 | from flask_wtf import FlaskForm
import wtforms as f
from wtforms.validators import DataRequired
class LoginForm(FlaskForm):
email = f.StringField('email', validators=[DataRequired()])
password = f.PasswordField('password', validators=[DataRequired()])
display = ['email', 'password']
class UserForm(Flask... |
9974029 | import sys
sys.path.append('../..')
import eureka.S5_lightcurve_fitting.s5_fit as s5
eventlabel = 'template'
s5_meta, lc_model = s5.fitJWST(eventlabel)
|
9974062 | from collections import deque
import cv2
import numpy
import torch
from cv2 import VideoWriter, VideoWriter_fourcc
import agnes
cv2.ocl.setUseOpenCL(False)
class VisualizeAttention:
def __init__(self, env, runner, prerun=0, seconds=20, layer_num=0):
self.nnet = runner.trainer.get_nn_instance()
... |
9974073 | import warnings
import pandas as pd
from transformers import (AutoModelForMaskedLM,
AutoTokenizer, LineByLineTextDataset,
DataCollatorForLanguageModeling,
Trainer, TrainingArguments)
warnings.filterwarnings('ignore')
def get_task_data(data_... |
9974076 | import csv
import io
from typing import Callable, Generator, List
from girder.api import access
from girder.api.describe import Description, autoDescribeRoute
from girder.api.rest import Resource, setContentDisposition
from girder.constants import AccessType, SortDir, TokenScope
from girder.models.folder import Folder... |
9974102 | from ._co2tab import co2tab
from ._export import export
from ._extract import extract
from ._merge import merge
from ._save2incon import save2incon
__all__ = [
"co2tab",
"export",
"extract",
"merge",
"save2incon",
]
|
9974154 | from typing import Any
from typing import get_type_hints
from typing import List
from typing import Tuple
from typing import Type
from typing import TypeVar
import pynamodb.constants
from pynamodb.attributes import Attribute
T = TypeVar("T", bound=Tuple[Any, ...])
_DEFAULT_FIELD_DELIMITER = "::"
class UnicodeDelimi... |
9974174 | from autoflow.workflow.components.data_process_base import AutoFlowDataProcessAlgorithm
__all__ = ["RepeatedEditedNearestNeighbours"]
class RepeatedEditedNearestNeighbours(AutoFlowDataProcessAlgorithm):
class__ = "RepeatedEditedNearestNeighbours"
module__ = "imblearn.under_sampling"
|
9974215 | import argparse
import numpy as np
import shapefile
from netCDF4 import Dataset
from pyproj import Proj
from skimage.draw import polygon
from hagelslag.util.make_proj_grids import read_arps_map_file, read_ncar_map_file, make_proj_grids
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-s",... |
9974243 | import numpy as np
import copy
import logging
import random
from gunpowder.coordinate import Coordinate
from gunpowder.provider_spec import ProviderSpec
from gunpowder.array import ArrayKey
from gunpowder.array_spec import ArraySpec
from gunpowder.graph import GraphKey
from gunpowder.graph_spec import GraphSpec
logg... |
9974272 | from __future__ import absolute_import, division, print_function
from six.moves import range
from dials.array_family import flex
from xfel.merging.application.worker import worker
class error_modifier_ha14(worker):
def __init__(self, params, mpi_helper=None, mpi_logger=None):
super(error_modifier_ha14, self).__... |
9974285 | from __future__ import print_function
__author__ = '<NAME>, <EMAIL>'
from pybrain.optimization.distributionbased.distributionbased import DistributionBasedOptimizer
from scipy import dot, exp, log, sqrt, floor, ones, randn
from pybrain.tools.rankingfunctions import HansenRanking
class SNES(DistributionBasedOptimize... |
9974287 | from rflint.common import SuiteRule, ResourceRule, ERROR
class ResourceFileInUse(SuiteRule):
severity = ERROR
def apply(self, suite):
has_resources = False
for setting in suite.settings:
if setting[0].lower() == "resource":
has_resources = True
if not has_re... |
9974302 | from pathsetup import run_path_setup
run_path_setup()
import time
import pickle
import tensorflow as tf
import numpy as np
import utils
import gl
import os
from tqdm import tqdm
from nltk.tokenize import word_tokenize
from tensorflow.python.layers.core import Dense
from snli.decoder import basic_decoder
from scipy.sta... |
9974303 | import pyb
import micropython
red_led = pyb.LED(1)
green_led = pyb.LED(2)
blue_led = pyb.LED(3)
orange_len = pyb.LED(4)
pulse_detected_led = red_led
class Tachometer(object):
NUM_SAMPLES = 16
def __init__(self, timer_num, channel_num, pin_name, pulses_per_rev=2):
self.timestamp = [0] * T... |
9974317 | import brain
import judgement
import logging
def get_stance_towards(life, target_id):
_know = brain.knows_alife_by_id(life, target_id)
if _know:
if judgement.can_trust(life, target_id):
return 'friendly'
elif judgement.is_target_dangerous(life, target_id):
return 'hostile'
else:
return 'neutral'
... |
9974331 | import os
# loss function related
from lib.utils.box_ops import giou_loss
from torch.nn.functional import l1_loss
from torch.nn import BCEWithLogitsLoss
# train pipeline related
from lib.train.trainers import LTRTrainer
# distributed training related
from torch.nn.parallel import DistributedDataParallel as DDP
# some m... |
9974333 | import FWCore.ParameterSet.Config as cms
HLTPath = "HLT_Ele*"
HLTProcessName = "HLT"
### cut on electron tag
#ELECTRON_ET_CUT_MIN = 10.0
ELECTRON_ET_CUT_MIN_TIGHT = 20.0
ELECTRON_ET_CUT_MIN_LOOSE = 10.0
ELECTRON_COLL = "gedGsfElectrons"
ELECTRON_CUTS = "(abs(superCluster.eta)<2.5) && (ecalEnergy*sin(superClusterPos... |
9974346 | import unittest
import pykka
import pytest
from mopidy import core
from mopidy.models import Ref
from mopidy_mpd.dispatcher import MpdContext, MpdDispatcher
from mopidy_mpd.exceptions import MpdAckError
from mopidy_mpd.uri_mapper import MpdUriMapper
from tests import dummy_backend
class MpdDispatcherTest(unittest.... |
9974396 | from pomagma.compiler.util import eval_float44, eval_float53
def test_eval_float44():
values = map(eval_float44, range(256))
print ' '.join(['{}:{}'.format(k, v) for k, v in enumerate(values)])
for i, j in zip(values[:-1], values[1:]):
assert i < j
assert j - i - 1 < 0.08 * j # less than ... |
9974401 | import click
from pcbnewTransition import pcbnew, isV6
import csv
import os
import re
import sys
import shutil
from pathlib import Path
from kikit.fab.common import *
from kikit.common import *
from kikit.export import gerberImpl, exportSettingsPcbway
def collectSolderTypes(board):
result = {}
for footprint in... |
9974411 | import musicBoxMaker
prefix = ""
suffix = ""
#load the prefix and suffix gcode (for initialization and finish).
#Generate one gcode from your favorite software and copy paste the sections before and after the print of the object itself
#Make sure to adjust the parameter start_extrusion_val for the generateGCODE funct... |
9974425 | from adminsortable.admin import SortableAdmin
from django.contrib import admin
from manabi.apps.featured_decks.models import FeaturedDeck
from manabi.apps.flashcards.models import Deck
@admin.register(FeaturedDeck)
class FeaturedDeckAdmin(SortableAdmin):
model = FeaturedDeck
list_display = ['deck_collection... |
9974451 | from __future__ import absolute_import, print_function
from datetime import timedelta
from django.core.urlresolvers import reverse
from django.utils import timezone
from sentry.api.serializers import Serializer, register, serialize
from sentry.app import tsdb
from sentry.constants import LOG_LEVELS
from sentry.models... |
9974464 | from setuptools import setup
with open('README.rst') as f:
long_description = f.read()
setup(
name='shed_sh',
version='1.0.0',
description=('Don\'t run "curl | sh" again. '
'Use "curl | shed" to verify scripts before running.'),
long_description=long_description,
url='https://... |
9974483 | from typing import Tuple
import dash
from dash.dependencies import Input, Output, State
def init_basic_env_accordion(app: dash.Dash) -> None:
"""
Initiates TAB: Environment Section: 1 accordion callbacks.
---
Args:
app (dash.Dash): Dash application to which the callback is registered to.
... |
9974599 | import functools
import gevent.server
from gevent import socket
import json
import struct
KEYSTORE_PORT = 5577
KEYSTORE_GET = "get"
KEYSTORE_SET = "set"
KEYSTORE_DELETE = "delete"
PUBSUB_PORT = 5578
PUBSUB_SUBSCRIBE = "subscribe"
PUBSUB_UNSUBSCRIBE = "unsubsribe"
PUBSUB_PUBLISH = "publish"
def pack_data(data):
... |
9974606 | import weakref
import logging
import networkx
from PySide2.QtWidgets import QFrame, QHBoxLayout
from PySide2.QtCore import QSize
from .qsymexec_graph import QSymExecGraph
from .qstate_block import QStateBlock
l = logging.getLogger('ui.widgets.qpathtree')
class QPathTree(QFrame):
def __init__(self, simgr, stat... |
9974627 | from pyoms.core.base import Base
from pyoms.core.show import Show
class SideBar(Base):
"""Левое меню"""
def click(self, tag):
# Свернуть\развернуть
Show(tag).toggle("blind") |
9974650 | from typing import Optional, List
from schematics import Model
from slim.utils.jsdict import JsDict
class TempStorage(JsDict):
validated_query: Optional[Model]
validated_post: Optional[Model]
validated_write_values: Optional[List[Model]]
|
9974668 | from typing import List
import dataclasses
import pydantic
from api import can_api_v2_definition
from openapi_schema_pydantic import OpenAPI
from openapi_schema_pydantic.util import PydanticSchema
from openapi_schema_pydantic.util import construct_open_api_with_schema_class
COUNTY_TAG = "County Data"
STATE_TAG = "S... |
9974687 | from collections import OrderedDict
import voluptuous as vol
from .fplapi import FplApi
from homeassistant import config_entries
from homeassistant.helpers.aiohttp_client import async_create_clientsession
from .const import DOMAIN, CONF_USERNAME, CONF_PASSWORD, CONF_NAME
from .fplapi import (
LOGIN_RESULT_OK,
... |
9974688 | import argparse
import copy
import logging
import os
import time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from preactresnet import PreActResNet18
from wideresnet import WideResNet
from utils_plus import (upper_limit, lower_limit, std, clamp, get_loaders,
attack_pgd, ev... |
9974732 | import os
import numpy as np
all_ranks = []
user_time = 0.0
for results_dir in os.listdir('results/'):
full_dir = os.path.join('results/', results_dir)
results_file = os.path.join(full_dir, 'results.txt')
if os.path.exists(results_file):
results_line = open(results_file).readlines()
fields ... |
9974733 | import unittest
from programy.storage.stores.nosql.mongo.dao.usergroups import UserGroups
class UserGroupsTests(unittest.TestCase):
def test_init_no_id(self):
usergroups = UserGroups(usergroups={})
self.assertIsNotNone(usergroups)
self.assertIsNone(usergroups.id)
self.assertEqua... |
9974873 | from unittest import TestCase
from source.preprocessing.psg.psg_file_type import PSGFileType
class TestPSGFileType(TestCase):
def test_file_types_exists(self):
self.assertEqual(PSGFileType.Vitaport.value, 0)
self.assertEqual(PSGFileType.Compumedics.value, 1)
|
9974901 | import json
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.template.loader import render_to_string
from formly.forms.run import PageForm, TargetForm
from formly... |
9974933 | from functools import partial, lru_cache
from collections import namedtuple
import jax
import numpy as onp
import jax.numpy as np
import utils
from spectral_tools import build_t_op, transfer_eigs_power
from parallel_ops import parallel_contract
TI_MPS = namedtuple('TI_MPS', 'core_tensor, bound_obj, state')
TI_MPS.__... |
9975104 | import pickle
import pytest
@pytest.fixture(scope="module", params=range(pickle.HIGHEST_PROTOCOL + 1))
def protocol(request):
"""Returns all available pickle protocols.
This avoids needing to parametrize all test functions manually."""
yield request.param
|
9975105 | from . import animation
from . import controls
from . import element_table
from . import failure_criteria
from . import listing
from . import load_case
from . import magnetics_calc
from . import path_operations
from . import results
from . import setup
from . import special
from . import status
from . import surface_op... |
9975140 | import pytest
from pygears import gear
from pygears.typing import Uint, Bool, Tuple
from pygears.lib.delay import delay_rng
from pygears.sim import sim, cosim
from pygears.lib import directed, drv
@pytest.mark.parametrize('din_delay', [0, 1])
@pytest.mark.parametrize('dout_delay', [0, 1])
def test_bare(lang, din_dela... |
9975238 | import discord
from discord.ext import commands
import compuglobal
from cogs.events import Events
class TVShowCog(commands.Cog):
def __init__(self, bot, api):
self.bot = bot
self.api = api
# Format error to not embed links on page status error
@staticmethod
def format_error(error):
... |
9975283 | from ..vocab import Vocab
class SentenceEncoder:
"""This is a simple encoder that takes a text, tokenizes
it and then uses the vocabulary to convert each token to an
integer ID.
IMPORTANT: This encoder does not support excluding tokens.
"""
def __init__(self, tokenizer, vocab=None):
... |
9975293 | from abc import ABC
from abc import abstractmethod
from easydict import EasyDict as edict
from tensorflow.python import keras
class Model(ABC):
def __init__(
self,
model_parameters: edict = None,
):
self._model_parameters = model_parameters
self._model = self.define_m... |
9975296 | r"""
=====================================
Multi-class AdaBoosted Decision Trees
=====================================
This example reproduces Figure 1 of Zhu et al [1]_ and shows how boosting can
improve prediction accuracy on a multi-class problem. The classification
dataset is constructed by taking a ten-dimensiona... |
9975305 | import sys
try:
import unittest2 as unittest
except ImportError:
import unittest
try:
# Python 2
from StringIO import StringIO
except ImportError:
# Python 3
from io import StringIO
try:
from unittest import mock
except ImportError:
import mock
if sys.version_info.major == 2:
# P... |
9975308 | from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from phonenumber_field.phonenumber import to_python
def validate_international_phonenumber(value):
phone_number = to_python(value)
if phone_number and not phone_number.is_valid():
raise Validatio... |
9975309 | from lintreview.review import Problems
from lintreview.tools.black import Black
from unittest import TestCase
from tests import root_dir, read_file, read_and_restore_file, requires_image
class TestBlack(TestCase):
fixtures = [
'tests/fixtures/black/no_errors.py',
'tests/fixtures/black/has_errors.... |
9975310 | try:
import cPickle as pickle # NOQA
except ImportError:
import pickle # NOQA
import errno
import socket
import time
from django.core.cache.backends.memcached import MemcachedCache
from memcachepool.pool import ClientPool
DEFAULT_ITEM_SIZE = 1000 * 1000
# XXX not sure if keeping t... |
9975322 | from director_frob import *
foo = Bravo()
s = foo.abs_method()
if s != "Bravo::abs_method()":
raise RuntimeError, s
|
9975380 | import pandas as pd
import requests
API_URL="http://api.censusreporter.org/1.0/data/show/{release}?table_ids={table_ids}&geo_ids={geoids}"
def get_data(tables=None, geoids=None, release='latest'):
if geoids is None:
geoids = ['040|01000US']
elif isinstance(geoids,basestring):
geoids = [geoids]
... |
9975385 | class GalleryAlbum(object):
# See documentation at https://api.imgur.com/ for available fields
def __init__(self, *initial_data, **kwargs):
for dictionary in initial_data:
for key in dictionary:
setattr(self, key, dictionary[key])
for key in kwargs:
setat... |
9975397 | import os
import numpy as np
import matplotlib.pyplot as plt
def compute_uncertainty_bounds(est: np.array, std: np.array):
return np.maximum(0, est - 2 * std), est + 2 * std
def plot_market_estimates(data: dict, est: np.array, std: np.array):
"""
It makes a market estimation plot with prices, trends, unce... |
9975401 | import logging
import uuid
import sys
import os
import re
from functools import wraps
from blessings import Terminal
term = Terminal()
logger = logging.getLogger()
class UnsupportedPlatform(Exception): pass
def platform():
if 'linux' in sys.platform:
return 'linux'
elif 'darwin' in sys.platform:
... |
9975403 | from ryu.base import app_manager
from ryu.controller import mac_to_port
from ryu.controller import ofp_event
from ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ofproto_v1_3
from ryu.lib.mac import haddr_to_bin
from ryu.lib.packet i... |
9975436 | from configs import LunarLanderConfig as dense_config
from model import ActorLunarlander
import gym
import numpy as np
from Lunarlander.train_lunarlander import preprocess_state
def accumulate_experience_lunarlander(teacher: ActorLunarlander,
exp_replay, config=dense_config):
e... |
9975473 | from __future__ import print_function
import FWCore.ParameterSet.Config as cms
def customise(process):
FLAVOR = process.generator.hscpFlavor.value()
PROCESS_FILE = process.generator.processFile.value()
PARTICLE_FILE = process.generator.particleFile.value()
USE_REGGE = process.generator.useregge.value(... |
9975498 | from setuptools import setup, find_packages
setup(
name="videostream",
version="0.2",
url="http://github.com/andrewebdev/django-video",
description="A simple video streaming application for django",
author="<NAME>",
author_email="<EMAIL>",
package_dir={'': 'src'},
packages=find_packages... |
9975506 | from desktop_local_tests.dns_during_disruption import DNSDuringDisruptionTestCase
from desktop_local_tests.windows.windows_wifi_power_disrupter import WindowsWifiPowerDisrupter
class TestWindowsDNSDisruptWifiPower(DNSDuringDisruptionTestCase):
'''Summary:
Test whether DNS leaks when the Wi-Fi power is disabl... |
9975542 | import json
from django.http import HttpResponse
from django.template import loader
from hs_core.views.utils import authorize, ACTION_TO_AUTHORIZE
from hs_access_control.models import PrivilegeCodes
from hs_core.tasks import resource_debug
from django.shortcuts import redirect
from celery.result import AsyncResult
d... |
9975546 | import os
import shutil
import time
import pprint
import torch
def set_gpu(x):
os.environ['CUDA_VISIBLE_DEVICES'] = x
print('using gpu:', x)
def ensure_path(path):
if os.path.exists(path):
if input('{} exists, remove? ([y]/n)'.format(path)) != 'n':
shutil.rmtree(path)
os... |
9975602 | import FWCore.ParameterSet.Config as cms
file = open('tpDead.txt')
wiresToDebug = cms.untracked.vstring()
for line in file:
corrWire = line.split()[:6]
#switch station/sector
corrWire[1:3] = corrWire[2:0:-1]
wire = ' '.join(corrWire)
#print wire
wiresToDebug.append(wire)
file.close()
from Cali... |
9975606 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
"""
File name: investor_server
Date created: 17/07/2019
Feature: #Enter feature description here
"""
__author__ = "<NAME>"
__copyright__ = "Copyright 2018, <NAME>"
__license__ = "MIT"
__email__ = "<EMAIL>"
"""... |
9975610 | import os
import json
# The top argument for walk
topdir = '.'
# The extension to search for
exten = '.json'
data = []
for dirpath, dirnames, files in os.walk(topdir):
for name in files:
if name.lower().endswith(exten):
if 'site' not in dirpath and 'github' not in dirpath:
da... |
9975642 | import ssl
from Crypto.Util.asn1 import DerSequence
from Crypto.PublicKey import RSA
from binascii import a2b_base64
def get_pubkey(pem):
""" Extracts public key from x08 pem. """
der = ssl.PEM_cert_to_DER_cert(pem)
# Extract subjectPublicKeyInfo field from X.509 certificate (see RFC3280)
cert = Der... |
9975644 | import argparse
import logging
import mxnet as mx
import os
# Polyaxon
from polyaxon import tracking
logger = logging.getLogger('mnist')
def model(context,
train_iter,
val_iter,
conv1_kernel,
conv1_filters,
conv1_activation,
conv2_kernel,
conv2_f... |
9975679 | from __future__ import absolute_import, division, print_function, unicode_literals
import math
from pi3d.util import Utility
from pi3d.Shape import Shape
import logging
LOGGER = logging.getLogger(__name__)
class Torus(Shape):
""" 3d model inherits from Shape"""
def __init__(self, camera=None, light=None, radius... |
9975699 | import datetime
import math
import os
import time
import torch
import lib
class Trainer(object):
def __init__(self, model, train_data, eval_data, metrics, dicts,
optim, opt):
self.model = model
self.train_data = train_data
self.eval_data = eval_data
self.evaluator = lib.E... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.