id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1612214 | from collections import OrderedDict
# Calendar page filter categories
election_types = OrderedDict([
('36', 'All elections'),
])
deadline_types = OrderedDict([
('21', 'Reporting deadlines'),
('25', 'Quarterly reports'),
('26', 'Monthly reports'),
('27', 'Pre- and post-election')
])
reporting_peri... |
1612235 | import base64
import os
import folium
from folium.plugins.heat_map import HeatMap
from folium.utilities import temp_html_filepath
def test_heat_map_with_weights(driver):
"""Verify that HeatMap uses weights in data correctly.
This test will fail in non-headless mode because window size will be different.
... |
1612251 | import attr
from pygments.lexers.jvm import JavaLexer
from typing import List
from ..core.core_settings import app_settings
from ..exporters.common import *
from ..model.app_data import ApiCall
regex = r".*\[([\S\s]*)->([\S\s][^]]*)\](.*)$"
def get_actors_from_title(api_title):
matched_tokens = re.search(regex,... |
1612256 | from gazette.spiders.base.doem import DoemGazetteSpider
class BaAntonioCardosoSpider(DoemGazetteSpider):
TERRITORY_ID = "2901700"
name = "ba_antonio_cardoso"
state_city_url_part = "ba/antoniocardoso"
|
1612289 | import numpy as np
from PIL import Image
from numpy import array
class ImgUtils(object):
@staticmethod
def read_image_bytes(filename):
with open(filename, mode='rb') as file:
return file.read()
@staticmethod
def read_image_numpy(filename, w, h):
img = Image.open(filename)... |
1612301 | import copy
import numpy as np
import torch
from mmpose.core import (aggregate_results, get_group_preds,
get_multi_stage_outputs)
def test_get_multi_stage_outputs():
fake_outputs = [torch.zeros((1, 4, 2, 2))]
fake_flip_outputs = [torch.ones((1, 4, 2, 2))]
# outputs_flip
outp... |
1612313 | from scripts import CommandProcessor
def main():
commands = {
"executing pre-commit hooks": "poetry run pre-commit run --all-files",
}
command_processor = CommandProcessor(commands)
command_processor.run()
if __name__ == "__main__":
main()
|
1612339 | import pandas as pd
class SomeThing:
def __init__(self, x, y):
self.x, self.y = x, y
things = [SomeThing(1,2), SomeThing(3,4), SomeThing(4,5)]
df = pd.DataFrame([t.__dict__ for t in things ])
print(df.iloc[[-1]].to_dict('records')[0])
#print(df.to_html())
print(df.style.render())
|
1612358 | import json
from typing import Set, Tuple
from PyQt5.QtGui import QClipboard
from PyQt5.QtWidgets import QApplication
def copy_text_to_clipboard(text: str) -> None:
cb: QClipboard = QApplication.clipboard()
cb.setText(text)
def get_text_from_clipboard() -> str:
cb: QClipboard = QApplication.clipboard()... |
1612423 | from photons_protocol.errors import BadConversion
from photons_protocol.types import Optional
from delfick_project.norms import sb, dictobj
from bitarray import bitarray
import binascii
import struct
def val_to_bitarray(val, doing):
"""Convert a value into a bitarray"""
if val is sb.NotSpecified:
val... |
1612428 | import logging
import os
import pytest
import unittest
from base import BaseTest
from elasticsearch import RequestError
from idxmgmt import IdxMgmt
INTEGRATION_TESTS = os.environ.get('INTEGRATION_TESTS', False)
class TestCAPinning(BaseTest):
"""
Test beat CA pinning for elasticsearch
"""
@unittest.s... |
1612429 | import os
import unittest
import boto3
from moto import mock_dynamodb2, mock_s3, mock_sqs, mock_sts, mock_secretsmanager
os.environ['DEPLOYMENT_STAGE'] = "test_deployment_stage"
os.environ['AWS_DEFAULT_REGION'] = "us-east-1"
os.environ['AWS_ACCESS_KEY_ID'] = "test_ak"
os.environ['AWS_SECRET_ACCESS_KEY'] = "test_sk"
o... |
1612475 | import ast
import unittest
import hpman
class TestParseSource(unittest.TestCase):
# Note: clear is not required since that parse won't
# affect the hyperparameters instance in memory
def setUp(self):
self.hpm = hpman.HyperParameterManager("_")
def test_parse_name_with_non_literal_name(sel... |
1612507 | import os
import sys
from os.path import join
import pandas as pd
import itertools
import ntpath
from tempfile import mkstemp
from shutil import move, copymode
from os import fdopen, remove
import shutil
import subprocess
def clean(dumpFile):
pathFile = os.path.abspath(os.path.dirname(__file__))
f = open(... |
1612539 | import numpy as np
import pickle
from copy import deepcopy
from det3d.core import box_np_ops
from det3d.datasets.custom import PointCloudDataset
from det3d.datasets.registry import DATASETS
from .eval import get_lyft_eval_result
@DATASETS.register_module
class LyftDataset(PointCloudDataset):
NumPointFeatures =... |
1612555 | import pandas as pd
import syllabels_en
import pickle
from textblob import TextBlob
def _get_n_words(text):
blob = TextBlob(text)
return len(blob.ngrams(n=1))
def _get_n_chars(text):
chars = text.replace(' ', '').replace('.', '').replace('?', '')
chars = chars.replace("'", '').replace('"', "")
ret... |
1612564 | import abc
import re
import shutil
from pathlib2 import Path
import numpy as np
from os import path, walk, makedirs
from utilities import Constants, logger
import io
from utilities.NumpyHelper import NumpyDynamic
class FileIterator(object):
def __init__(self, source, data_path):
self.source = source... |
1612588 | import os
import subprocess
from amaranth.build import *
from amaranth.vendor.lattice_ice40 import *
from .resources import *
__all__ = ["NandlandGoPlatform"]
class NandlandGoPlatform(LatticeICE40Platform):
device = "iCE40HX1K"
package = "VQ100"
default_clk = "clk25"
resources = [
... |
1612594 | class Solution:
# @param A : integer
# @param B : integer
# @param C : list of ints
# @return an int
def paint(self, A, B, C):
MOD = 10000003
if len(C) == 1:
return (C[0] * B) % MOD
if A == 1:
return (sum(C) * B) % MOD # all work done by one worker
low = min(C)
high = sum(C)
ans = float('inf')
... |
1612614 | import glob
import json
import logging
import multiprocessing
import os
import shutil
import struct
import subprocess
from enum import Enum, auto
from dataclasses import dataclass, field
from pathlib import Path
from typing import (
Mapping,
NewType,
Optional,
Sequence,
)
logger = logging.getLogger(_... |
1612617 | import unittest
from calpack import models
class Test_PacketField(unittest.TestCase):
def test_pktfield_encapsulated_pkt(self):
class simple_pkt(models.Packet):
field1 = models.IntField()
class adv_pkt(models.Packet):
field2 = models.PacketField(simple_pkt)
p = ad... |
1612640 | import requests
from channels.auth import AuthMiddlewareStack
import os
from utils.exceptions import IncorrectUserCredentials
os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"
class JWTAuthMiddleware:
def __init__(self, inner):
self.inner = inner
def __call__(self, scope):
token = f"{self.g... |
1612682 | from django import forms
from django.utils.safestring import mark_safe
from markupfield.widgets import MarkupTextarea
from .models import Nomination
class NominationForm(forms.ModelForm):
class Meta:
model = Nomination
fields = (
"name",
"email",
"previous_boa... |
1612700 | import pandas as pd
import numpy as np
data = [
['The', 'Business', 'Centre', '15', 'Stevenson', 'Lane'],
['6', 'Mossvale', 'Road'],
['Studio', '7', 'Tottenham', 'Court', 'Road']
]
def len_strings_in_list(data_list):
return list(map(lambda x: len(x), data_list))
def list_of_list_func_results(list_fun... |
1612719 | from torch import nn
class JointDecoder(nn.Module):
"""Combination of several decoders for several tasks.
Two modes in loss computation :
1. (weigthed) sum of losses
3. Individual loss given a task"""
def __init__(self, decoders, loss_weights=None):
super(JointDecoder, self)._... |
1612748 | import unittest
from programy.context import ClientContext
from programy.dynamic.maps.singular import SingularMap
from programytest.client import TestClient
class TestSingularMaps(unittest.TestCase):
def setUp(self):
self._client_context = ClientContext(TestClient(), "testid")
def test_static_map(s... |
1612816 | import unittest
import json
from code_pipeline.tests_evaluation import RoadTestEvaluator, OOBAnalyzer
from numpy import linspace
import matplotlib.colors as mc
import colorsys
from shapely.geometry import Point, LineString
from matplotlib import pyplot as plt
import matplotlib.patches as patches
from descartes i... |
1612821 | import hashlib
import json
class IDDict(dict):
_id_ignore_keys = set()
def to_id(self, id_keys=None, id_ignore_keys=None):
if id_keys is None:
id_keys = self.keys()
if id_ignore_keys is None:
id_ignore_keys = self._id_ignore_keys
id_keys = set(id_keys) - set(id... |
1612873 | import numpy as np
from bayesnet.array.broadcast import broadcast_to
from bayesnet.math.exp import exp
from bayesnet.math.log import log
from bayesnet.math.sqrt import sqrt
from bayesnet.math.square import square
from bayesnet.random.random import RandomVariable
from bayesnet.tensor.constant import Constant
from bayesn... |
1612907 | import random
import numpy as np
import torch
import torch.nn as nn
from torch.nn.utils import clip_grad_value_
from pytorl.lib import PrioritizedReplay
from pytorl.utils import Setting
from ._base_agent import Agent
class DQN_Agent(Agent):
def __init__(self,
device,
q_net,
target_ne... |
1612935 | import requests
import requests_cache
from .exceptions import BGGValueError
class CacheBackend(object):
pass
class CacheBackendNone(CacheBackend):
def __init__(self):
self.cache = requests.Session()
class CacheBackendMemory(CacheBackend):
""" Cache HTTP requests in memory """
def __init__... |
1612936 | from collections import Counter
import random
# population sample ,once an element has been randomly selected, it cannot be selected again instead of random.choices where the population of the obj becomes infinite.
suits = 'C', 'D', 'H', 'A'
ranks = tuple(range(2,11)) + tuple('JQKA')
deck = [str(rank) + suit
... |
1612949 | import unittest
import wd
class TestValideUnitTestCase(unittest.TestCase):
def setUp(self):
pass
def test_dummy(self):
self.assertTrue(True)
def test_assert_methods(self):
"""
check that these methods exist and work as expected
assertEqual(a, b) a == b
... |
1612959 | i = 1
while (i <= 10):
print("#",end=" ") if i in [2,3,5,7] else print("*",end=" ")
if i in [1,3,6]:
print('\r')
i += 1
|
1613011 | import numpy as np
import rllab.misc.logger as logger
from rllab.misc import special2 as special
class SimpleReplayPool(object):
def __init__(
self,
max_pool_size,
observation_dim,
action_dim,
replacement_policy='stochastic',
replacement_p... |
1613016 | import os
import logging
from raven_python_lambda import RavenLambdaWrapper
class FreshEnvironmentVariables:
def __init__(self, values={}):
self.intended_values = values
def __enter__(self):
self.old_environment_data = os.environ.copy()
os.environ.clear()
os.environ.update(sel... |
1613041 | def swap_case(s):
out = ''
for ind, let in enumerate(s):
if let.isalpha():
if let.islower():
out += s[ind].capitalize()
else:
out += s[ind].lower()
else:
out += let
return out |
1613076 | from pypy.interpreter.error import oefmt
from pypy.interpreter.astcompiler import consts
from rpython.rtyper.lltypesystem import rffi, lltype
from rpython.rlib.objectmodel import we_are_translated
from rpython.rlib.rarithmetic import widen
from pypy.module.cpyext.api import (
cpython_api, CANNOT_FAIL, CONST_STRING,... |
1613105 | import collections
_NotSpecified = object()
class Hash(collections.abc.MutableMapping):
def __init__(self, default_value=None):
self.d = collections.OrderedDict()
self.default_value = default_value
def __len__(self):
return len(self.d)
def __getitem__(self, key):
if key ... |
1613198 | import os
from django.urls import (
include,
path,
)
BASE_DIR = os.path.dirname(__file__)
STATIC_URL = "/static/"
TEST_RUNNER = "djangae.test.AppEngineDiscoverRunner"
# Set the cache during tests to local memory, which is threadsafe
# then our TestCase clears the cache in setUp()
CACHES = {
'default': {... |
1613233 | from __future__ import division, print_function, absolute_import
import os
from time import time, sleep
from tempfile import mkstemp
from nose.tools import raises
import unittest
import json
from rep.estimators._mnkit import MatrixNetClient
from rep.estimators import MatrixNetClassifier, MatrixNetRegressor
from rep.te... |
1613255 | import pytest
from data import model
from buildtrigger.triggerutil import raise_if_skipped_build, SkipRequestException
from endpoints.building import (
start_build,
PreparedBuild,
MaximumBuildsQueuedException,
BuildTriggerDisabledException,
)
from test.fixtures import *
def test_maximum_builds(app):... |
1613257 | import sys,os
import pandas as pd
import numpy as np
from sklearn.metrics import confusion_matrix
from networkx import DiGraph
from networkx import relabel_nodes
from sklearn_hierarchical_classification.constants import ROOT
from tqdm import tqdm
import itertools
import matplotlib
matplotlib.use('Agg')
import matplotli... |
1613264 | from django import forms
from dcim.models import DeviceType, Manufacturer
from extras.forms import CustomFieldModelCSVForm
from utilities.forms import BootstrapMixin
from .choices import PDUUnitChoices
from .models import PDUConfig
BLANK_CHOICE = (("", "---------"),)
class PDUConfigForm(BootstrapMixin, forms.Model... |
1613272 | from setuptools import setup, find_packages
setup(
name='cdvae',
version="0.0.1",
packages=find_packages(include=['cdvae', 'cdvae.*']),
)
|
1613273 | import pytest
from ..connectors.dummy import Dummy as DummyConnector
from ..worker import Worker
from ..brokers.standard import Standard as StandardBroker
from .fixtures import Adder, FakeAdder, AbstractAdder, RetryJob, ExceptionJob
class TestWorker(object):
@property
def connector(self):
return Dum... |
1613302 | import numpy as np
import json
from turorials.perlin_noise.obstacle_generation import flood_grid
class EnvironmentRepresentation:
def __init__(self):
self.obstacle_map = None
self.terrain_map = None
self.start_positions = None
self.nb_free_tiles = 0
self.dim = (8, 8)
... |
1613309 | import os
import unittest
import numpy as np
from PIL import Image
from src.constants.constants import NumericalMetrics
from src.evaluators.habitat_evaluator import HabitatEvaluator
class TestHabitatEvaluatorContinuousCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.evaluator_continuous... |
1613327 | import tensorflow as tf
import numpy as np
from sklearn.metrics import balanced_accuracy_score
import time
import os
def create_graph_placeholders(dataset, use_desc=True, with_tags=True, with_attention=True, use_subgraph=False):
'''
dataset: should be a sequence (list, tuple or array) whose order is [V, A, La... |
1613404 | from leapp.actors import Actor
from leapp.libraries.actor import opensshuseprivilegeseparationcheck
from leapp.models import Report, OpenSshConfig
from leapp.tags import ChecksPhaseTag, IPUWorkflowTag
class OpenSshUsePrivilegeSeparationCheck(Actor):
"""
UsePrivilegeSeparation configuration option was removed.... |
1613436 | import argparse
import json
from hotpot.encoding.iterative_encoding_retrieval import eval_questions
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Evaluate retriever for hotpot')
parser.add_argument('iterative_dataset', help="filename of the iterative dataset")
parser.add_argumen... |
1613446 | from typing import Type, TypeVar
from eth_typing import BLSSignature
from eth_utils import humanize_hash
from ssz.hashable_container import HashableContainer
from ssz.sedes import bytes32, bytes96, uint64
from eth2.beacon.constants import EMPTY_SIGNATURE
from eth2.beacon.typing import (
Root,
Slot,
Valida... |
1613478 | def romanToInt(s):
#Defining the Roman Number Values
a={"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}
#Total value to be returned
val=0
#Counter Variable to track the length of string
i=0
#IDEA:- The Roman number will be in always in Descending Order(Right <Left)
while i... |
1613548 | import ctypes as ct
import numpy as np
import scipy.interpolate as interpolate
import sharpy.utils.controller_interface as controller_interface
import sharpy.utils.settings as settings
import sharpy.utils.control_utils as control_utils
import sharpy.utils.cout_utils as cout
import sharpy.structure.utils.lagrangeconstr... |
1613552 | import base64
import mock
import os
from sigopt.config import Config
fake_context = base64.b64encode(b'{"a": "b"}').decode('utf-8')
class FakeConfigContext(object):
def __init__(self, key):
self.CONFIG_CONTEXT_KEY = key
class TestConfig(object):
def test_load_json_config(self):
with mock.patch.dict(os.e... |
1613560 | def quick_sort(arr):
return quick_sort_help(arr, 0, len(arr)-1)
def quick_sort_help(arr, first, last):
if first < last:
split_point = partition(arr, first, last)
quick_sort_help(arr, first, split_point-1)
quick_sort_help(arr, split_point+1, last)
return arr
def partition(arr,... |
1613564 | import sys
sys.path.append('../../')
from skimage.data import astronaut, camera
from sciwx.canvas import CanvasFrame, CanvasNoteFrame
import wx
def canvas_frame_test():
cf = CanvasFrame(None, autofit=True)
cf.set_imgs([camera(), 255-camera()])
cf.Show()
def canvas_note_test():
cnf = CanvasNoteFrame(N... |
1613582 | from datetime import timedelta
def convert_to_timedelta(time_val):
"""
From: code.activestate.com/recipes/577894-convert-strings-like-5d-and-60s-to-timedelta-objec
Given a *time_val* (string) such as '5d', returns a timedelta object
representing the given value (e.g. timedelta(days=5)). Accepts the
... |
1613588 | from binaryninja import (
BinaryReader, BinaryWriter,
RegisterValueType, enums
)
from .sym_state import State
from .arch.arch_x86 import x86Arch
from .arch.arch_x86_64 import x8664Arch
from .arch.arch_armv7 import ArmV7Arch
from .models.function_models import library_functions
from .utility.expr_wrap_util impor... |
1613617 | import six
import traitlets
class Schema(traitlets.Any):
"""any... but validated by a jsonschema.Validator"""
_validator = None
def __init__(self, validator, *args, **kwargs):
super().__init__(*args, **kwargs)
self._validator = validator
def validate(self, obj, value):
error... |
1613626 | from pathlib import Path
from typing import List
from _pytest.fixtures import fixture
from requests import Session
from keycloak_scanner.scan_base.types import Realm, SecurityConsole, WellKnown, Client
from tests.mock_response import MockResponse, RequestSpec, MockSpec
# httpclient_logging_patch()
@fixture
def b... |
1613655 | import pytest
import responses
from box import Box, BoxList
from tests.conftest import stub_sleep
# Don't need to test the data structure as we just have list and get
# methods available. id will suffice until add/update endpoints are available.
@pytest.fixture(name="cloud_connector_groups")
def fixture_cloud_connec... |
1613669 | import argparse
import tensorflow as tf
from tensorflow.keras.callbacks import Callback
import ray
import ray.train as train
from ray.data import Dataset
from ray.data.dataset_pipeline import DatasetPipeline
from ray.train import Trainer
class TrainReportCallback(Callback):
def on_epoch_end(self, epoch, logs=No... |
1613688 | import sys
class BuffpyException(Exception):
pass
class BuffpyRestException(BuffpyException):
"""
Represents any 4xx or 5xx exceptions from the Buffer API
Reference: https://bufferapp.com/developers/api/errors
Some ideas borrowed from Twilio"s REST exception handling
"""
def __init__(... |
1613715 | import os
import tempfile
import unittest
from tensorflow import keras
import calamari_ocr.scripts.resume_training as resume_training
import calamari_ocr.scripts.train as train
from calamari_ocr.test.test_train_file import uw3_trainer_params
this_dir = os.path.dirname(os.path.realpath(__file__))
class TestTrainFil... |
1613737 | import datetime
import os
import tempfile
from collections import OrderedDict
import boto3
import pandas as pd
import pytest
import yaml
from moto import mock_s3
from numpy.testing import assert_almost_equal
from pandas.testing import assert_frame_equal
from unittest import mock
from triage.component.catwalk.storage ... |
1613758 | import shutil
from fmpy import platform, sharedLibraryExtension
import os
from subprocess import check_call
if os.name == 'nt':
generators = [
('win32', 'Visual Studio 15 2017'),
('win64', 'Visual Studio 15 2017 Win64')
]
else:
generators = [(platform, 'Unix Makefiles')]
for p, generator... |
1613760 | import tensorflow as tf
import numpy as np
from gpflow.likelihoods import ScalarLikelihood
from gpflow.base import Parameter
from gpflow.config import default_float
from gpflow.utilities import positive
class NegativeBinomial(ScalarLikelihood):
def __init__(self, alpha= 1.0,invlink=tf.exp,scale=1.0,nb_scaled=Fals... |
1613764 | import unittest
from mahjong.player import Player
from mahjong.components import Stack, Tile, Suit, Naki, Huro, Jihai
class TestPlayer(unittest.TestCase):
def setUp(self):
self.player = Player('test player', 0)
self.player_2 = Player('test player 2', 1)
def test_att(self):
tile_stac... |
1613774 | from __future__ import absolute_import
import threading
from random import shuffle
class EDRStateFinder(threading.Thread):
def __init__(self, star_system, checker, edr_systems, callback):
self.star_system = star_system
self.checker = checker
self.radius = 50
self.max_trials = 25
... |
1613783 | from dataclasses import dataclass
from typing import Any, Dict, Generator, List, Optional
try:
import boto3 # type:ignore
from botocore.client import ClientError
from botocore.exceptions import ParamValidationError
S3NativeClient = Any
S3NativeBucket = Any
except (ImportError, ModuleNotFoundError... |
1613786 | from collections.abc import Iterable
from functools import partial
from math import sqrt
from numbers import Real
from operator import attrgetter
from warnings import warn
from openmc import (
XPlane, YPlane, Plane, ZCylinder, Cylinder, XCylinder,
YCylinder, Universe, Cell)
from ..checkvalue import (
check... |
1613796 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="cookie-manager",
version="1.2.3",
author="ScholarPack",
author_email="<EMAIL>",
description="Signed cookie manager for communication between multiple trusted services.",
long_descripti... |
1613824 | from setuptools import setup, find_packages
from distutils.extension import Extension
from Cython.Build import cythonize
ext = [
Extension ("t0_test", ['t0_test.pyx', 't0.c', 'tinyber.c'])
]
setup (
name = 'tinyber_test',
version = '0.1',
packages = find_packages(),
... |
1613842 | description = 'setup for the poller'
group = 'special'
sysconfig = dict(
cache = 'pumahw.puma.frm2'
)
devices = dict(
Poller = device('nicos.services.poller.Poller',
autosetup = True,
# setups for which all devices are polled
# poll = ['lakeshore', 'detector', 'befilter'],
# se... |
1613866 | from __future__ import annotations
import ast
import pytest
from flake8_pie import Flake8PieCheck
from flake8_pie.pie809_django_prefer_bulk import err
from flake8_pie.tests.utils import Error, ex, to_errors
EXAMPLES = [
ex(
code="""
[Item.objects.create(item) for item in items]
""",
errors=[err(... |
1613897 | from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
from entity import ApiKey
from .dao import BaseDao
class ApiKeyDao(BaseDao):
T = ApiKey
def get_by_value(self, key: str) -> ApiKey or None:
session = self.Session()
try:
return session.query(ApiKey).filter(ApiKey.k... |
1613916 | import os
import sys
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.sites',
'import_export',
'core',
]
SITE_ID = 1
ROOT_URLCONF = "urls"
DEBUG = True
STATIC_URL ... |
1613936 | import redisai as rai
from ml2rt import load_model
from cli import arguments
model = load_model("../models/spark/linear_regression/linear_regression.onnx")
if arguments.gpu:
device = 'gpu'
else:
device = 'cpu'
con = rai.Client(host=arguments.host, port=arguments.port)
con.modelset("spark_model", 'onnx', dev... |
1614013 | import random
import torch.utils.data
import torchvision.transforms as transforms
#import torchnet as tnt
# pip install future --upgrade
from builtins import object
from pdb import set_trace as st
import torch.utils.data as data_utils
class PairedData(object):
def __init__(self, data_loader_A, data_loader_B, max_da... |
1614045 | from collections import Counter
x = int(input())
shoes = list(map(int, input().split(' ')))
n = int(input())
cnt = Counter()
for i in shoes:
cnt[i]+=1
cost = 0
for i in range(n):
s, c = list(map(int, input().split(' ')))
if cnt[s] > 0:
cost += c
cnt[s]-=1
print(cost) |
1614050 | from .base import BaseJITTest
class TestInstanceVars(BaseJITTest):
def test_initialize(self, topaz, tmpdir):
traces = self.run(topaz, tmpdir, """
class A
def initialize
@a = 1
@b = 2
@c = 3
end
end
i = 0
while i < 1000... |
1614060 | import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.nn.functional as F
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
impo... |
1614070 | from nameko.events import EventHandler as NamekoEventHandler
from nameko_amqp_retry.messaging import Consumer
class EventHandler(NamekoEventHandler, Consumer):
pass
event_handler = EventHandler.decorator
|
1614129 | import json
from urllib.parse import urlparse
from flask import render_template, request
from ... import preprocessors, util
def configure(config, bp, score_processor):
# /spec/
@bp.route("/v1/spec/", methods=["GET"])
@preprocessors.nocache
@preprocessors.minifiable
def v1_spec():
retur... |
1614144 | import setuptools
from distutils.util import convert_path
with open("README.md", "r") as fh:
long_description = fh.read()
main_ns = {}
ver_path = convert_path('btoandav20/version.py')
with open(ver_path) as ver_file:
exec(ver_file.read(), main_ns)
setuptools.setup(
name="btoandav20",
version=main_ns[... |
1614226 | from Components.Converter.Converter import Converter
class HddInfo(Converter):
MODEL = 0
CAPACITY = 1
FREE = 2
def __init__(self, type):
Converter.__init__(self, type)
self.type = {
"Model": self.MODEL,
"Capacity": self.CAPACITY,
"Free": self.FREE,
}[type]
def getText(self):
hdd ... |
1614227 | import sys, getopt
sys.path.append('.')
import RTIMU
import os.path
import time
import math
SETTINGS_FILE = "RTIMULib"
# computeHeight() - the conversion uses the formula:
#
# h = (T0 / L0) * ((p / P0)**(-(R* * L0) / (g0 * M)) - 1)
#
# where:
# h = height above sea level
# T0 = standard temperature at sea leve... |
1614232 | import logging
from aiohttp import web
from eth_typing import BLSSignature
from eth_utils import decode_hex, encode_hex, humanize_hash
from lahja.base import EndpointAPI
from ssz.tools.dump import to_formatted_dict
from ssz.tools.parse import from_formatted_dict
from eth2.beacon.chains.base import BaseBeaconChain
fro... |
1614241 | from collections import defaultdict
import numpy as np
# Grafted from
# https://github.com/maartenbreddels/ipyvolume/blob/d13828dfd8b57739004d5daf7a1d93ad0839ed0f/ipyvolume/serialize.py#L219
def array_to_binary(ar, obj=None, force_contiguous=True):
if ar is None:
return None
if ar.dtype.kind not in [... |
1614246 | import random
import numpy as np
from MAIN.Basics import Processor, Space
from operator import itemgetter
class StateSpace(Processor, Space):
def __init__(self, agent):
self.agent = agent
super().__init__(agent.config['StateSpaceState'])
def process(self):
self.agent.dat... |
1614295 | import json
import requests
import time
from random import uniform
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
try:
import cookielib
except ImportError:
import http.cookiejar as cookielib
DEFAULT_VERSION = 'v1'
class SumoLogic(object):
def __init__(s... |
1614307 | import os
import time
import numpy as np
import tensorflow as tf
from config_api.config_utils import Config as Config
from data_apis.corpus import ConvAI2DialogCorpus
from data_apis.data_utils import ConvAI2DataLoader
from models.model import perCVAE
import argparse
parser = argparse.ArgumentParser()
parser.add_argume... |
1614351 | from spacy.matcher import Matcher
from spacy.tokens import Token, Doc
from spacy.language import Language
from scispacy.hearst_patterns import BASE_PATTERNS, EXTENDED_PATTERNS
@Language.factory("hyponym_detector")
class HyponymDetector:
"""
A spaCy pipe for detecting hyponyms using Hearst patterns.
This ... |
1614372 | from django.core.urlresolvers import reverse
from django.views import generic
from beta.models import BetaSignup
from beta.forms import BetaSignupForm
class Signup(generic.CreateView):
""" View to handle beta signup """
template_name = 'beta/signup.html'
form_class = BetaSignupForm
def get_success_... |
1614389 | from typing import Dict
def dict_equal(dict1: Dict, dict2: Dict) -> bool:
if not len(dict1) == len(dict2):
return False
for (k1, v1), (k2, v2) in zip(dict1.items(), dict2.items()):
if k1 != k2:
return False
if v1 != v2:
return False
return True
|
1614392 | import random
import pytest
import redis
from RLTest import Env
from test_helper_classes import _get_ts_info
def test_ooo(self):
with Env().getClusterConnectionIfNeeded() as r:
quantity = 50001
type_list = ['', 'UNCOMPRESSED']
for chunk_type in type_list:
r.execute_command('ts... |
1614437 | from tensorflow.keras import layers
from tensorflow.keras.activations import swish
from tensorflow.nn import relu6
def relu(x):
return layers.ReLU()(x)
def hard_sigmoid(x):
return layers.ReLU(6.0)(x + 3.0) * (1.0 / 6.0)
def hard_swish(x):
return layers.Multiply()([hard_sigmoid(x), x])
class Convolut... |
1614464 | import ConfigParser
import tensorflow as tf
config = ConfigParser.ConfigParser()
config.read('config.env')
keras_model = config.get('model', 'keras_model')
output_path = config.get('model', 'output_path')
input_model = config.get('model', 'input_model')
tf.keras.backend.set_learning_phase(0)
model = tf.keras.models.... |
1614517 | import pytest
from django.contrib.auth import authenticate, get_user_model
from impostor.backend import AuthBackend
from impostor.forms import BigAuthenticationForm
from impostor.models import ImpostorLog
from impostor.templatetags.impostor_tags import get_impersonated_as
admin_username = "real_test_admin"
admin_pass... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.