id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
127766 | import falcon
import pytest
from falcon import testing
from poseidon_api.api import api
@pytest.fixture
def client():
return testing.TestClient(api)
def test_v1(client):
response = client.simulate_get('/v1')
assert response.status == falcon.HTTP_OK
def test_network(client):
response = client.simul... |
127793 | import pyredner
import torch
pyredner.set_use_gpu(torch.cuda.is_available())
position = torch.tensor([1.0, 0.0, -3.0])
look_at = torch.tensor([1.0, 0.0, 0.0])
up = torch.tensor([0.0, 1.0, 0.0])
fov = torch.tensor([45.0])
clip_near = 1e-2
# randomly generate distortion parameters
torch.manual_seed(1234)
target_distor... |
127802 | from pathlib import Path
import pytest
from ics import Calendar, Event
from pythoncz.models.events import (preprocess_ical, find_first_url,
set_url_from_description)
def test_preprocess_ical():
path = Path(__file__).parent / 'invalid_ical.ics'
lines = preprocess_ical(path... |
127807 | import logging
from typing import Optional
log: logging.Logger = logging.getLogger(__name__)
class Object:
"""
Represents a generic Call of Duty object.
Parameters
----------
client : callofduty.Client
Client which manages communication with the Call of Duty API.
"""
_type: Opti... |
127810 | import sys
import unittest
import pendulum
from src import (
Crypto,
CryptoCommandService,
)
from minos.networks import (
InMemoryRequest,
Response,
)
from tests.utils import (
build_dependency_injector,
)
class TestCryptoCommandService(unittest.IsolatedAsyncioTestCase):
def setUp(self) -> N... |
127833 | import argparse
import xarray as xr
import numpy as np
import xesmf as xe
from glob import glob
import os
import shutil
def add_2d(
ds,
):
"""
Regrid horizontally.
:param ds: Input xarray dataset
"""
ds['lat2d'] = ds.lat.expand_dims({'lon': ds.lon}).transpose()
ds['lon2d'] = ds.lon.expa... |
127862 | from setuptools import find_packages, setup
from beacon_api import __license__, __version__, __author__, __description__
setup(
name="beacon_api",
version=__version__,
url="https://beacon-python.rtfd.io/",
project_urls={
"Source": "https://github.com/CSCfi/beacon-python",
},
license=__... |
127886 | import zengl
class Context:
context = None
main_uniform_buffer = None
main_uniform_buffer_data = bytearray(b'\x00' * 64)
@classmethod
def initialize(cls):
ctx = zengl.context()
cls.context = ctx
cls.main_uniform_buffer = ctx.buffer(size=64)
ctx.includes['main_unifo... |
127920 | import re
from collections import defaultdict, Counter
from numbers import Number
from typing import Optional, List, Dict
import numpy as np
import torch
from allennlp.common import FromParams, Registrable
from dataclasses import dataclass, replace
from pycocoevalcap.bleu.bleu import Bleu
from pycocoevalcap.cider.cid... |
127933 | import unittest
import numpy as np
from pax import core, plugin
from pax.datastructure import Event, Peak
class TestPosRecMaxPMT(unittest.TestCase):
def setUp(self):
self.pax = core.Processor(config_names='XENON100', just_testing=True, config_dict={'pax': {
'plugin_group_names': ['test'],
... |
127988 | from __future__ import annotations
import pytest
from _pytest.config import Config
from docutils import __version__ as docutils_version
from sphinx import __display_version__ as sphinx_version
from sphinx.testing.path import path
pytest_plugins = "sphinx.testing.fixtures"
collect_ignore = ["roots"]
def pytest_repor... |
128189 | import strawberry
from pythonit_toolkit.api.extensions import SentryExtension
from users.admin_api.mutation import Mutation
from users.admin_api.query import Query
schema = strawberry.federation.Schema(
query=Query, mutation=Mutation, extensions=[SentryExtension]
)
|
128207 | import glob, os
import sys
import urllib
from pathlib import Path
if __name__ == "__main__":
os.chdir(os.path.dirname(sys.argv[0]))
lecture_toc_md = []
lecture_root = "../lectures"
weeks = [week for week in os.listdir(lecture_root) if week.lower().startswith('week') and not week.lower().endswith('.md'... |
128209 | import os
import pytest
from deduplication.commands.search import search
from deduplication.tests.conftest import delete_output, mkdir_output, PROJECT_DIR, POTATOES_BASE_PATH, checkEqual
@pytest.mark.parametrize(
'tree_type, distance_metric, nearest_neighbors, leaf_size, parallel, batch_size, threshold, '
'... |
128282 | from xdoctest import checker
from xdoctest import directive
# from xdoctest import utils
def test_visible_lines():
"""
pytest testing/test_checker.py
"""
got = 'this is invisible\ronly this is visible'
print(got)
want = 'only this is visible'
assert checker.check_output(got, want)
def te... |
128283 | from django.db import DEFAULT_DB_ALIAS
from django.core.management import call_command
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
'--database', default=DEFAULT_DB_ALIAS,
help='Name of databas... |
128304 | import pytest
from algosec.errors import EmptyFlowSearch
from library import algosec_add_single_application_flow
from tests.conftest import AnsibleExitJson, ALGOSEC_SERVER, ALGOSEC_USER, ALGOSEC_PASSWORD, ALGOSEC_CERTIFY_SSL, my_vcr
PROPER_ARGS = dict(
ip_address=ALGOSEC_SERVER,
user=ALGOSEC_USER,
passwor... |
128325 | import numpy
from matplotlib import pyplot
def forward_difference(f, x0, h):
return (f(x0+h) - f(x0)) / h
def backward_difference(f, x0, h):
return (f(x0) - f(x0-h)) / h
def central_difference(f, x0, h):
return (f(x0+h) - f(x0-h)) / (2*h)
def euler(f, x_end, y0, N):
x, dx = numpy.linspace(0, x_end, N+... |
128334 | import numpy as np
import time, re
from .. import ROOT
from .. import larcv
from iomanager import IOManager
from imagefactory import ImageFactory
# data manger helps get the producers from the ROOT file
# as well as manage factory creation of images as the user
# hits replot, next/prev event
class DataManager(objec... |
128395 | from selenium.webdriver import Firefox
url = 'http://selenium.dunossauro.live/aula_05_c.html'
firefox = Firefox()
firefox.get(url)
def melhor_filme(browser, filme, email, telefone):
"""Preenche o formulário do melhor filme de 2020."""
browser.find_element_by_name('filme').send_keys(filme)
browser.find... |
128405 | import os
import logging
from pathlib import Path
from collections import UserDict
import yaml
import tree_hugger.setup_logging
from tree_hugger.exceptions import QueryFileNotFoundError
class Query(UserDict):
data = {}
def __init__(self, query_file_path: str, query_file_content: str):
self.query_f... |
128431 | from .episode_iterator import EpisodeIterator # NOQA
from .minibatch_iterator import MinibatchIterator # NOQA
from .semisupervised_episode_iterator import SemiSupervisedEpisodeIterator # NOQA
from .sim_episode_iterator import SimEpisodeIterator # NOQA
|
128433 | import unittest
from swmm_mpc.rpt_ele import rpt_ele
class test_rpt_ele(unittest.TestCase):
test_rpt_file = "example.rpt"
rpt = rpt_ele(test_rpt_file)
def test_total_flood(self):
true_flood_vol = 0.320
self.assertEqual(true_flood_vol, self.rpt.total_flooding)
def test_get_start_line(... |
128493 | from random import randint
from retrying import retry
import apysc as ap
from apysc._display.y_interface import YInterface
from apysc._type.variable_name_interface import VariableNameInterface
from tests.testing_helper import assert_attrs
class TestAnimationY:
@retry(stop_max_attempt_number=15, wai... |
128509 | import numpy as np
from ..rdkit import smiles_list_to_fingerprints, precursors_from_templates
def tanimoto(fp1, fp2):
a = fp1.sum()
b = fp2.sum()
c = float((fp1&fp2).sum())
return c/(a+b-c)
def pairwise_tanimoto(arr1, arr2, metric=tanimoto):
if arr1.size == 0:
return np.array([[]])
ret... |
128518 | import numpy as np
from Utils.Data.DatasetUtils import is_test_or_val_set, get_train_set_id_from_test_or_val_set, \
get_test_or_val_set_id_from_train
from Utils.Data.Features.Generated.TweetFeature.IsEngagementType import *
from Utils.Data.Features.MappedFeatures import MappedFeatureEngagerId, MappedFeatureCreator... |
128553 | from moto import mock_lambda, mock_logs
from newrelic_lambda_cli.cli import cli, register_groups
@mock_lambda
@mock_logs
def test_subscriptions_install(aws_credentials, cli_runner):
"""
Assert that 'newrelic-lambda subscriptions install' attempts to install the
New Relic log subscription on a function.
... |
128600 | import setuptools
setuptools.setup(
name="devrecargar",
version="0.1.4",
url="https://github.com/scottwoodall/django-devrecargar",
author="<NAME>",
author_email="<EMAIL>",
description="""
A Django app that automatically reloads your browser when a file
(py, html, js, css) chang... |
128606 | from typing import Any
import strawberry
from strawberry.types import Info
from src.api.context import Context
@strawberry.federation.type(extend=True)
class Query:
@strawberry.field
async def association_service(self, info: Info[Context, Any]) -> bool:
return True
|
128611 | from __future__ import unicode_literals, division, print_function, absolute_import
from .simec import SimilarityEncoder, masked_mse, masked_binary_crossentropy, LastLayerReg
from .utils import center_K
|
128627 | import logging
import requests
from .. import VERSION_STR
from ..exceptions import ConnectionError, ApiCallError
LOG = logging.getLogger(__name__)
class OpenRefsResponse:
"""Обёртка над ответом requests."""
def __init__(self, response: requests.Response):
"""
:param response:
"""
... |
128667 | import unittest
from mock import Mock
from records_mover.records.schema.field.numpy import details_from_numpy_dtype
import numpy as np
class TestNumpy(unittest.TestCase):
def test_details_from_numpy_dtype(self):
tests = {
np.dtype(str): 'string',
np.dtype(int): 'integer',
... |
128676 | import time
import os
# for organization, encode parameters in dir name
def setOutDir(params):
timestamp = str(int(time.time()))
try:
jobid = os.environ['SLURM_JOBID']
except:
jobid = 'NOID'
if params['root'] is None:
root = os.path.join(os.environ['HOME'], "STM", "experiments"... |
128691 | import time
import torch
from labml import monit, logger
from labml.logger import Text
N = 10_000
def no_section():
arr = torch.zeros((1000, 1000))
for i in range(N):
for t in range(10):
arr += 1
def section():
arr = torch.zeros((1000, 1000))
for i in range(N):
with ... |
128705 | from .libc import printf, scanf, localtime, asctime
from ctypes import c_int, create_string_buffer, byref, Structure
def input_pair():
key = c_int()
value = create_string_buffer(16)
printf(b"[Input a pair as int:string] ")
scanf(b"%i:%s", byref(key), byref(value))
return key, value.value
def print... |
128726 | from django.urls import path
from .apps import AZIranianBankGatewaysConfig
from .views import callback_view, go_to_bank_gateway
app_name = AZIranianBankGatewaysConfig.name
_urlpatterns = [
path('callback/', callback_view, name='callback'),
path('go-to-bank-gateway/', go_to_bank_gateway, name='go-to-bank-gatew... |
128742 | import codecs
import yaml
from yaml.composer import Composer
from ansiblereview import Result, Error
def hunt_repeated_yaml_keys(data):
"""Parses yaml and returns a list of repeated variables and
the line on which they occur
"""
loader = yaml.Loader(data)
def compose_node(parent, index):
... |
128747 | from mobula.utils import get_git_hash
def test_get_git_hash():
git_hash = get_git_hash()
assert type(git_hash) == str, (git_hash, type(git_hash))
assert len(git_hash) == 7 or git_hash == 'custom', git_hash
def test_edict():
from mobula.internal.edict import edict
data = edict(a=3, b=4)
asser... |
128829 | from sympy import acos
N = ReferenceFrame('N')
v1 = a * N.x + b * N.y + a * N.z
v2 = b * N.x + a * N.y + b * N.z
acos(v1.dot(v2) / (v1.magnitude() * v2.magnitude()))
|
128838 | import sys
import logging
import argparse
from conda_docker.conda import (
build_docker_environment,
find_user_conda,
conda_info,
find_precs,
fetch_precs,
)
from conda_docker.logging import init_logging
def cli(args):
parser = argparse.ArgumentParser(description="Docker Environments")
sub... |
128850 | import fileinput
import io
from html import escape
from html.entities import name2codepoint
from html.parser import HTMLParser
class MyHTMLParser(HTMLParser):
script = False
in_a_g = False
record_next_y = False
g_buffer = None
y_limit = None
g_current_y = None
g_dict = dict()
def _pri... |
128864 | from typing import Type, Any, Optional, overload
from .core import resource as res
from .core.internal_models import meta_v1, autoscaling_v1
__all__ = ['create_global_resource', 'create_namespaced_resource']
_created_resources = {}
def get_generic_resource(version, kind):
global _created_resources
model = ... |
128865 | from http import cookiejar
from urllib import request, error
from urllib.parse import urlparse
class HtmlDownLoader(object):
def download(self, url, retry_count=3, headers=None, proxy=None, data=None):
if url is None:
return None
try:
req = request.Request(url, headers=head... |
128957 | import time
from datetime import timedelta
from django.db import transaction
from dpq.queue import AtLeastOnceQueue
from dpq.decorators import repeat
def foo(queue, job):
transaction.on_commit(lambda: 1/0)
print('foo {}'.format(job.args))
def timer(queue, job):
print(time.time() - job.args['time'])
d... |
128967 | from setuptools import find_packages, setup
with open("README.md", "r") as f:
long_description = f.read()
setup(
name="riot",
description="A simple Python test runner runner.",
url="https://github.com/DataDog/riot",
author="<NAME>.",
author_email="<EMAIL>",
classifiers=[
"Programm... |
128985 | class C:
def f(self, x):
pass
def g(self):
def f(x): #gets ignored by pytype but fixer sees it, generates warning (FIXME?)
return 1
return f
|
129010 | import unittest
import os
import json
pymongo_missing = False
try:
import pymongo
except:
pymongo_missing = True
import logging
from reporter_config.Config import Config, Parser
class RCMultipleActionsTest(unittest.TestCase):
def setUp(self):
"""
Example message created by a conv functi... |
129023 | from flask import Flask
from . import api, web
app = Flask(
__name__,
static_url_path='/assets',
static_folder='static',
template_folder='templates')
app.config['SECRET_KEY'] = 'secret' # this is fine if running locally
app.register_blueprint(api.bp)
app.register_blueprint(web.bp)
|
129029 | import codecs
import os
import tempfile
from xml.dom import minidom
from six import PY2
from junit_xml import to_xml_report_file, to_xml_report_string
def serialize_and_read(test_suites, to_file=False, prettyprint=False, encoding=None):
"""writes the test suite to an XML string and then re-reads it using minido... |
129030 | from __future__ import absolute_import
import itertools
__all__ = ["Registry"]
class Registry(object):
"""The registry of access control list."""
def __init__(self):
self._roles = {}
self._resources = {}
self._allowed = {}
self._denied = {}
# to allow additional sh... |
129061 | import random
import torch
import torch.optim as optim
from parlai.agents.dialog_evaluator.auto_evaluator import (
TorchGeneratorWithDialogEvalAgent,
CorpusSavedDictionaryAgent
)
from parlai.core.metrics import AverageMetric
from parlai.core.torch_agent import History
from parlai.core.torch_generator_agent im... |
129088 | import sys, asyncio, os
from catalog import searchDomains, findOpenPorts, kafkaProducer, festin, filterRepeated, S3Store, S3Write
from aux import consumer, producer
async def dispatcher(p, kafkaQ, S3Q):
if p["port"] == "80":
await kafkaQ.put(p)
else:
await S3Q.put(p)
async def main():
task... |
129131 | import unittest
import numpy as np
import time
import uuid
from arch.api import session
from federatedml.param.intersect_param import IntersectParam
class TestRsaIntersectGuest(unittest.TestCase):
def setUp(self):
self.jobid = str(uuid.uuid1())
session.init(self.jobid)
from feder... |
129178 | from typing import List, Callable, Optional, Union, Dict, Awaitable, Any
from aiogram.types import InlineKeyboardButton, CallbackQuery
from aiogram_dialog.dialog import Dialog
from aiogram_dialog.manager.manager import DialogManager
from aiogram_dialog.widgets.text import Text
from aiogram_dialog.widgets.widget_event... |
129195 | import socket
from p2p.connection_manager import ConnectionManager
STATE_INIT = 0
STATE_STANDBY = 1
STATE_CONNECTED_TO_NETWORK = 2
STATE_SHUTTING_DOWN = 3
class ServerCore:
def __init__(self, my_port=50082, core_node_host=None, core_node_port=None):
self.server_state = STATE_INIT
print('Initial... |
129199 | from google.cloud import storage
import tempfile
import h5py
import os
class GCSH5Writer(object):
def __init__(self, fn):
self.fn = fn
if fn.startswith('gs://'):
self.gclient = storage.Client()
self.storage_dir = tempfile.TemporaryDirectory()
self.writer = h5py.F... |
129207 | from .core.warnings import high
high("DEPRECATED! Please use my.hackernews.materialistic instead.")
from .hackernews.materialistic import *
|
129248 | from typing import Dict, Generator, Tuple, Optional, Union
import pandas as pd
import torch
import torchtext
from .torch_data import toTensor, TorchDataSet, TorchDataSetProvider
class TorchtextDataSetFromDataFrame(torchtext.data.Dataset):
"""
A specialisation of torchtext.data.Dataset, where the ... |
129261 | from django import template
from django.utils.http import urlquote
from endpoint_monitor.models import EndpointTest
from linda_app.lists import CATEGORIES
from linda_app.models import Vocabulary, VocabularyClass, VocabularyProperty, get_configuration, \
datasource_from_endpoint
register = template.Library()
# Loa... |
129265 | import numpy as np
import sys
from lstm import LstmParam, LstmNetwork
class ToyLossLayer:
"""
Computes square loss with first element of hidden layer array.
"""
@classmethod
def loss(self, pred, label):
return (pred[0] - label) ** 2
@classmethod
def bottom_diff(self, pred, label):... |
129284 | from ckan.logic.schema import validator_args
@validator_args
def create_user_to_organization_schema(not_empty, unicode_safe,
email_validator, business_id_validator):
return {
"fullname": [not_empty, unicode_safe],
"email": [not_empty, unicode_safe, email_vali... |
129314 | from __future__ import print_function
import argparse
from elasticsearch import Elasticsearch
import elasticsearch.helpers
from solr_to_es.solrSource import SlowSolrDocs
import pysolr
DEFAULT_ES_MAX_RETRIES = 15
DEFAULT_ES_INITIAL_BACKOFF = 3
class SolrEsWrapperIter:
def __init__(self, solr_itr, es_index, es_typ... |
129337 | from boa3.exception import CompilerError, CompilerWarning
from boa3.neo.vm.opcode.Opcode import Opcode
from boa3.neo.vm.type.Integer import Integer
from boa3.neo.vm.type.String import String
from boa3_test.tests.boa_test import BoaTest
from boa3_test.tests.test_classes.testengine import TestEngine
class TestTyping(Bo... |
129355 | class MTransformationMatrix(object):
"""
Manipulate the individual components of a transformation.
"""
def __eq__(*args, **kwargs):
"""
x.__eq__(y) <==> x==y
"""
pass
def __ge__(*args, **kwargs):
"""
x.__ge__(y) <==> x>=y
... |
129359 | import sys
from collections import OrderedDict
from functools import partial
import torch.nn as nn
from modules import IdentityResidualBlock, GlobalAvgPool2d
from .util import try_index
class ResNeXt(nn.Module):
def __init__(self,
structure,
groups=64,
norm_act... |
129390 | from .resource import FieldsResource
"""
contentful.asset
~~~~~~~~~~~~~~~~
This module implements the Asset class.
API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/assets
:copyright: (c) 2016 by Contentful GmbH.
:license: MIT, see LICENSE for more details.
"""
... |
129401 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
import future.utils
from functools import reduce
import fractions
import operator
import os
import re
import sys
import tempfile
from html.parser import... |
129416 | from fabric import task
from patchwork.transfers import rsync
import os
import os.path as osp
from pathlib import Path
import json
## START EDIT: Edit these values to your profiles
# name of the bimhaw profile used in the bootstrapping process
PHASE1_PROFILE = "scooter"
# name of the bimhaw profile that is the end ... |
129497 | d=[int(i) for i in input().split()]
s=sum(d)
result=0
if s%len(d)==0:
for i in range(len(d)):
if d[i]<(s//len(d)):
result=result+((s//len(d))-d[i])
print(result,end='')
else:
print('-1',end='') |
129502 | import os
from typing import List
from app.common.build_artifact import BuildArtifact
from app.master.atom import AtomState
from app.util.conf.configuration import Configuration
from app.util.log import get_logger
from app.util.pagination import get_paginated_indices
class Subjob(object):
def __init__(self, buil... |
129514 | import tensorflow as tf
from nn_basic_layers import *
from filterbank_shape import FilterbankShape
from ops import *
class Naive_Fusion_Net(object):
def __init__(self, config):
# Placeholders for input, output and dropout
self.config = config
self.input_x1 = tf.placeholder(tf.float32,shape... |
129542 | from numpy.testing import (assert_allclose, assert_almost_equal,
assert_array_equal, assert_array_almost_equal_nulp)
import numpy as np
import pytest
import matplotlib.mlab as mlab
from matplotlib.cbook.deprecation import MatplotlibDeprecationWarning
def _stride_repeat(*args, **kw... |
129547 | from opera.parser.yaml.node import Node
from .constraint_clause import ConstraintClause
from .property_definition import PropertyDefinition
from ..entity import TypeEntity
from ..list import List
from ..map import Map
from ..reference import DataTypeReference
class DataType(TypeEntity):
REFERENCE = DataTypeRefere... |
129573 | import pytest
from napkin import sd
from napkin import sd_action
class TestParams:
def test_empty(self):
assert "" == str(sd.Params(tuple(), dict()))
def test_args(self):
assert "abc, def" == str(sd.Params(('abc', 'def'), dict()))
def test_args_kargs(self):
assert "abc, foo=1" =... |
129622 | import datetime
from enum import Enum
from typing import Dict, List
from dataclasses import field
# we use pydantic for dataclasses so that we can
# easily load and validate JSON reports.
#
# pydantic checks all the JSON fields look as they should
# while using the nice and familiar dataclass syntax.
#
# really, you s... |
129623 | import ast
import sqlite3
import sys
import traceback
import unittest
from io import StringIO
from time import sleep
from unittest import mock
from littleutils import SimpleNamespace, only
import sorcery as spells
from sorcery import unpack_keys, unpack_attrs, print_args, magic_kwargs, maybe, args_with_source, spell
... |
129627 | from django.db import models
from taggit.managers import TaggableManager
class BaseModel(models.Model):
name = models.CharField(max_length=50, unique=True)
tags = TaggableManager()
def __unicode__(self):
return self.name
class Meta(object):
abstract = True
class AlphaModel(... |
129656 | from axelrod import Player
class Grumpy(Player):
"""A player that defects after a ceratin level of grumpiness. Grumpiness increases when the opponent defects and decreases when the opponent co-operates."""
name = 'Grumpy'
def __init__(self, starting_state = 'Nice', grumpy_threshold = 10, nice_threshold =... |
129670 | import EmailParser.pst_parser
"""
if __name__ == "__main__":
pass
else:
from EmailBoxClass import EmailBox
EmailBox.main = EmailParser.pst_parser.main
"""
|
129685 | from arekit.common.news.objects_parser import SentenceObjectsParserPipelineItem
from arekit.contrib.source.rusentrel.sentence import RuSentRelSentence
class RuSentRelTextEntitiesParser(SentenceObjectsParserPipelineItem):
def __init__(self):
super(RuSentRelTextEntitiesParser, self).__init__(
i... |
129691 | import os
import unittest
from nose.plugins import Plugin
from nose.plugins.plugintest import PluginTester
from nose.plugins.manager import ZeroNinePlugin
here = os.path.abspath(os.path.dirname(__file__))
support = os.path.join(os.path.dirname(os.path.dirname(here)), 'support')
class EmptyPlugin(Plugin):
pass
... |
129746 | from __future__ import (
absolute_import,
unicode_literals,
)
import re
from typing import (
Any as AnyType,
Iterable,
List as ListType,
)
import warnings
import six
from conformity.fields.basic import (
Introspection,
UnicodeString,
)
from conformity.fields.utils import strip_none
from c... |
129759 | import sublime
import sublime_lib.flags as flags
from sublime_lib.vendor.python.enum import IntFlag
from functools import reduce
from unittest import TestCase
class TestFlags(TestCase):
def _test_enum(self, enum, prefix=''):
for item in enum:
self.assertEqual(item, getattr(sublime, prefix +... |
129877 | from django.db import migrations
try:
from django.contrib.postgres.fields import CIEmailField
except ImportError:
CIEmailField = None
else:
from django.contrib.postgres.operations import CITextExtension
def _operations():
if CIEmailField:
yield CITextExtension()
yield migrations.Alter... |
129908 | from slims.output import file_value
from slims.slims import Slims
from slims.step import Step, file_output
def execute():
# Make sure the path to the file exists
return file_value('C:/Users/User/Downloads/file.txt')
slims = Slims("slims", url="http://127.0.0.1:9999/", token="<PASSWORD>", local_host="0.0.0.0... |
129949 | import dash
dash.register_page(
__name__,
title="Forward Outlook",
description="This is the forward outlook", # should accept callable too
path="/forward-outlook",
image="birds.jpeg",
)
def layout():
return "Forward outlook"
|
129994 | from __future__ import print_function, division
import sys,os
qspin_path = os.path.join(os.getcwd(),"../")
sys.path.insert(0,qspin_path)
from quspin.basis import spinless_fermion_basis_1d
from quspin.basis import spinless_fermion_basis_general
import numpy as np
from itertools import product
def check_ME(b1,b2,opstr... |
130010 | import boto3
import json
import os
def parse_rule_violations(rule_violations):
rule_violations_text = ''
for rule in rule_violations:
bot_message = rule.get('Bot message')
del rule['Bot message']
rule_violations_text = ''.join([rule_violations_text,json.dumps(rule).replace('"', '').rep... |
130065 | from flextensor.scheduler import schedule
from flextensor.task import register_task
from flextensor.utils import RpcInfo
# from flextensor.ppa_model import measure_latency
from flextensor.intrinsic import register_intrin
def gen_micro_schedule(task, target, model_func=None):
register_task(task, override=True)
... |
130073 | import pytest
from pytest import approx
from barril import units
@pytest.fixture
def db():
db = units.UnitDatabase.GetSingleton()
yield db
def testTransmissibility(db):
converted = db.Convert("transmissibility", "cp.m3/day/bar", "cp.bbl/day/psi", 1.0)
assert approx(converted) == 0.433667315
def t... |
130088 | import pytest
@pytest.fixture(autouse=True)
def _autouse_resp_mocker(resp_mocker, version_api):
pass
|
130290 | from linode_api4.errors import UnexpectedResponseError
from linode_api4.objects import Base, Property
class AuthorizedApp(Base):
api_endpoint = "/profile/apps/{id}"
properties = {
"id": Property(identifier=True),
"scopes": Property(),
"label": Property(),
"created": Property(i... |
130329 | import gaphas
import pytest
from gaphor.core.modeling import Diagram, Presentation, StyleSheet
class Example(gaphas.Element, Presentation):
def __init__(self, diagram, id):
super().__init__(connections=diagram.connections, diagram=diagram, id=id)
def unlink(self):
self.test_unlinked = True
... |
130411 | from django.conf.urls import url
from .views import (
LocationSearchView,
)
urlpatterns = [
url(r'^create-location/$', LocationSearchView.as_view(), name='location_create'),
]
|
130418 | import pylab
import numpy
class GeneralRandom:
"""This class enables us to generate random numbers with an arbitrary
distribution."""
def __init__(self, x = pylab.arange(-1.0, 1.0, .01), p = None, Nrl = 1000):
"""Initialize the lookup table (with default values if necessary)
Inputs:
x = random nu... |
130453 | from typing import List
import numpy as np
class BenchmarkResult:
def __init__(self, loop_names: List[str], n_repeats: int, metric_names: List[str]):
"""
:param loop_names: List of loop names
:param n_repeats: Number of random restarts in benchmarking
:param metric_names: List of... |
130531 | from disco.core import result_iterator
from disco.error import DataError
from disco.test import TestCase, TestJob, FailedReply
class RedundantJob(TestJob):
@staticmethod
def map(e, params):
yield int(e), ''
@staticmethod
def reduce(iter, params):
yield sum(k for k, v in iter), ''
clas... |
130603 | from guizero import App, TextBox, PushButton, Text
def show():
output.value = textbox.value
app = App()
textbox = TextBox(app, multiline=True, height=10, width=50, scrollbar=True)
textbox.value = "hello\ngoodbye\nno way\nthis is a very long stream of text, very long indeed, the best long line of text, its super b... |
130610 | import logging
import random
import time
from ..candidate_generation import candidates_per_query, syntactically_relevant_indexes
from ..selection_algorithm import DEFAULT_PARAMETER_VALUES, SelectionAlgorithm
from ..utils import get_utilized_indexes, mb_to_b
# budget_MB: The algorithm can utilize the specified storage... |
130641 | from __future__ import print_function
from sys import stdout, stderr
from pepper.framework.abstract import AbstractComponent
from pepper.framework.util import Scheduler
from pepper.framework.component import SpeechRecognitionComponent
from pepper import config
import threading
import urllib
from time import time
cl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.