id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1602675 | from Redy.Opt import *
from dis import dis
@feature(goto)
def loop1():
task1: label
task2: label
end: label
with task1:
print('task1')
x = input('where do you want to goto?[1, 2, end]')
if x == 'end':
print('jump to end')
end.jump()
elif x == '... |
1602738 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.card import card
def test_card():
"""Test module card.py by downloading
card.csv and testing shape of
extracted data has 3010 rows and 34 ... |
1602782 | import numpy as np
import matplotlib.pyplot as plt
# Generate data
n = 500
t = np.linspace(0,20.0*np.pi,n)
X = np.sin(t) # X is already between -1 and 1, scaling normally needed |
1602783 | import os
import shutil
from django.core.files import File
from django.conf import settings
from service_catalog.maintenance_jobs import cleanup_ghost_docs_images
from service_catalog.models import Doc
from tests.test_service_catalog.base import BaseTest
class TestMaintenanceJob(BaseTest):
def setUp(self):
... |
1602792 | from learntools.core import *
class WorseHeuristic(ThoughtExperiment):
_hint = ("The first heuristic assigns a score of 0 to column 2, and a score of -99 to "
"column 3. What scores do you get with the second heuristic?")
_solution = ("The first heuristic is guaranteed to select column 2 to block... |
1602873 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
#data = np.loadtxt("data.txt").reshape((2048,2048))
data = np.memmap("DenseOffset.off", dtype=np.float32, mode='r', shape=(100,100,2))
data1=data[:,:,0]
print(data1)
plt.imshow(data1, cmap=cm.coolwarm) ... |
1602883 | import os
def parseargs(p):
"""
Add arguments and `func` to `p`.
:param p: ArgumentParser
:return: ArgumentParser
"""
p.set_defaults(func=func)
p.description = "print name of current/working directory"
p.add_argument(
"-L",
"--logical",
action="store_true",
... |
1602908 | import numpy as np
class MotionFeatureExtractor:
""" Functor for extracting motion features from a detection.
"""
def __init__(self, stats):
""" Constructor.
"""
## Dict containing mean and std of motion features.
self.stats = stats
def __call__(self, det, last=None... |
1602953 | import unittest
import time
from mu.integration_tests import int_test
from mu.sims.bms_carrier import BmsCarrier
from mu.sims.sub_sims.mcp23008 import NUM_MCP23008_PINS, MCP23008_KEY
class TestMcp23008(int_test.IntTest):
def setUp(self):
super().setUp()
self.board = self.manager.start(BmsCarrier,... |
1602961 | import importlib
from mu.protogen import stores_pb2
MODULE_NAME_FORMAT = 'mu.protogen.{}_pb2'
STORE_TYPE_NAME_FORMAT = 'Mu{}Store'
def store_from_name(type_name):
type_name = type_name.lower()
# get class from module via introspection
type_module = importlib.import_module(MODULE_NAME_FORMAT.format(type_... |
1602985 | import numpy as np
from py.forest import Node
class Cube():
def __init__(self, node):
assert isinstance(node, Node)
self.start = node.start
self.end = node.end
self.dim = node.dim
self.id_string = node.id_string
self.split_axis = node.split_axis
self.split_v... |
1602994 | import unittest
from securityheaders.checkers.other import XWebKitCSPDeprecatedChecker
class XWebKitCSPDeprecatedCheckerTest(unittest.TestCase):
def setUp(self):
self.x = XWebKitCSPDeprecatedChecker()
def test_checkNoHeader(self):
nox = dict()
nox['test'] = 'value'
self.assertEqua... |
1603003 | import multiprocessing as mp
from pathlib import Path
import subprocess
from unittest.mock import MagicMock
from libmuscle.mcp.tcp_server import TcpServer
from libmuscle.mcp.message import Message
from ymmsl import Reference, Settings
from .conftest import skip_if_python_only
def tcp_server_process(control_pipe):
... |
1603026 | import unittest2 as unittest
import pymongo
import time
import random
import threading
from oplogreplay import OplogReplayer
SOURCE_HOST = '127.0.0.1:27017'
DEST_HOST = '127.0.0.1:27018'
TESTDB = 'testdb'
# Inherit from OplogReplayer to count number of processed_op methodcalls.
class CountingOplogReplayer(OplogRepl... |
1603028 | from appJar import gui
def show(btn): app.showSubWindow("sub")
def hide(btn): app.hideSubWindow("sub")
app=gui()
app.addLabel("l1", "Sub Window Demo")
app.addButton("PRESS", show)
app.startSubWindow("sub")
app.addLabel("s1", "sub")
app.addButton("Stop", hide)
app.stopSubWindow()
app.setSubWindowLocation("sub", 400,4... |
1603058 | from django.db.models import Value, F, TextField
from django.db.models.functions import Concat
from sphinxql import indexes, fields
from .models import Document
class DocumentIndex(indexes.Index):
name = fields.Text(Concat(F('type__name'), Value(' '), F('number'),
output_field=TextF... |
1603200 | import torch
import torch.nn.functional as F
from layers import Linear, LayerNorm
from .multi_head_attention import MultiHeadAttention, AttentionMask
from typing import Optional, Callable, Dict
from dataclasses import dataclass
# This file is based on PyTorch's internal implementation
ActivationFunction = Callable[[to... |
1603209 | import tensorflow as tf
import time
def activation_function(act,act_input):
act_func = None
if act == "sigmoid":
act_func = tf.nn.sigmoid(act_input)
elif act == "tanh":
act_func = tf.nn.tanh(act_input)
elif act == "relu":
act_func = tf.nn.... |
1603219 | import itertools
import logging
from typing import Any, Dict, List, Optional
import torch
from torch.utils.data import DataLoader
from probnmn.config import Config
from probnmn.data.datasets import JointTrainingDataset
from probnmn.data.samplers import SupervisionWeightedRandomSampler
from probnmn.models import (
... |
1603226 | from unittest.mock import (
Mock,
patch,
)
import pytest
from auctions.application.use_cases import PlacingBidUseCase
from auctions.application.use_cases.placing_bid import PlacingBidInputDto, PlacingBidOutputDto
from auctions.domain.entities import (
Auction,
Bid,
)
from auctions.domain.factories imp... |
1603238 | from unittest import mock
from django.contrib.auth.models import User
from django.urls import reverse
import pytest
from .. import settings
from ..forms import KeyRegistrationForm
from ..models import WebAuthnKey
def test_list_webauthn_keys(admin_client):
response = admin_client.get(reverse("kagi:webauthn-keys... |
1603281 | import ipaddress
from collections import OrderedDict
import tldextract
import validators
def valid_domain(item):
if validators.domain(item) is not True:
return False
x = tldextract.extract(item)
return x.subdomain is ''
def valid_fqdn(item):
if validators.domain(item) is not True:
... |
1603288 | from PIL import Image, ImageDraw, ImageFont
from .conf import COLOR
from .util import getTemplatePath, comma, getrgb, get_scale
class COORDINATES():
MIN_BAR_SIZE = 3
MIN_AXIS_LABEL_WIDTH = 180
GAP_LABEL_AND_BAR = 1
def __init__(self, chrom, spos, epos, xscale, w, h, debug=False):
self.chrom =... |
1603302 | import logging
import os
from dart.client.python.dart_client import Dart
from dart.config.config import configuration
from dart.engine.emr.metadata import EmrActionTypes
from dart.model.action import Action, ActionData, ActionState
from dart.model.graph import SubGraphDefinition, EntityType, Relationship, Ref, SubGraph... |
1603333 | from typing import List, Callable
from .clip import Clip
from .follow import Follow
from .game import Game
from .model import Model
from .stream import Stream
from .user import User
from .video import Video
__all__: List[Callable] = [
Clip,
Follow,
Game,
Model,
Stream,
User,
Video,
]
|
1603380 | from __future__ import division
import os
import sys
import cv2
import argparse
import glob
import math
import numpy as np
import matplotlib.pyplot as plt
from skimage import draw, transform
from scipy.optimize import minimize
from PIL import Image
import objs
import utils
#fp is in cam-ceil normal, h... |
1603428 | from ipwhois import IPWhois
from metadata import MetadataPlugin
class WhoIsPlugin(MetadataPlugin):
def __init__(self):
MetadataPlugin.__init__(self)
self.name = "WhoIs"
def run(self):
try:
ip_whois = IPWhois(self._dst_ip)
raw_res = ip_whois.lookup()
... |
1603471 | import unittest
from prestans import exception
from prestans.parser import AttributeFilter
from prestans import types
class ModelUnitTest(unittest.TestCase):
def test_required(self):
class MyModel(types.Model):
pass
required_default = MyModel()
self.assertTrue(required_defau... |
1603562 | import os
import torch
import logging
from model import DeepSpeech
class Observer(object):
'''
Train Observer base class.
'''
def __init__(self, logger):
self.logger = logger
def on_epoch_start(self, model, epoch): pass
def on_epoch_end(self, model, optimizer, epoch, loss_results, ... |
1603585 | from plugin.models.m_sync.result import SyncResult, SyncResultError, SyncResultException
from plugin.models.m_sync.status import SyncStatus
|
1603602 | from backend.common.sitevars.sitevar import Sitevar
class NotificationsEnable(Sitevar[bool]):
@staticmethod
def key() -> str:
return "notifications.enable"
@staticmethod
def description() -> str:
return "For enabling/disabling all notifications"
@staticmethod
def default_valu... |
1603618 | from tortoise import Tortoise
from app.core import settings
async def init_db() -> None:
await Tortoise.init(
db_url=str(settings.DATABASE_URL), modules={"models": settings.APP_MODELS}
)
await Tortoise.generate_schemas()
|
1603620 | import numpy as np
import tensorflow as tf
from util import xavier_init
class SparseAutoencoder(object):
def __init__(self, num_input, num_hidden, transfer_function=tf.nn.softplus, optimizer=tf.train.AdamOptimizer(),
scale=0.1):
self.num_input = num_input
self.num_hidden = num_hidd... |
1603634 | from os.path import join, isdir
import glob
from subprocess import call
import numpy as np
from rastervision.common.utils import _makedirs
from rastervision.common.settings import VALIDATION
from rastervision.semseg.tasks.utils import (
make_prediction_img, plot_prediction, predict_x)
from rastervision.semseg.mo... |
1603635 | from PIL import Image
import pytest
from yoga.image.encoders import png
class Test_big_endian_unint32_bytes_to_python_int(object):
def test_uint32_value(self):
assert (
png.big_endian_uint32_bytes_to_python_int(b"\xAA\xBB\xCC\xDD")
== 0xAABBCCDD
)
class Test_python_int_t... |
1603660 | from collections import OrderedDict
from .utility import Utility
from .base import OperatorLayerBase
class Dropout(OperatorLayerBase):
def __init__(self, d):
marker = eval(d.argMarker[0])
mod = marker['mod']
op = marker['op']
args = marker['args']
self.marker = marker
self.mod_ = mod
self.op_ = op
s... |
1603694 | from django.test import Client, TestCase
from slurpee.models import ExternalData
from slurpee.constants import P_OVERLAY
from systems.tests.utils import create_fake_host
import simplejson as json
class ExternalDataTests(TestCase):
def setUp(self):
serial = 'asdf'
self.external_serial = serial +... |
1603736 | import os
from backend.settings import logging, logger, static_path
ACL_MODEL = 'standard'
logger = logging.getLogger('.'.join([logger.name, 'acl']))
controller_static_path = os.path.join(static_path, "controller")
interfaces_path = os.path.join(controller_static_path, "interfaces")
acl_path = os.path.join(controll... |
1603773 | from collections import deque
d = deque()
N = int(input())
for _ in range(N):
cmd, *args = input().split()
getattr(d, cmd)(*args)
print (*[item for item in d], sep = " ")
|
1603789 | import numpy as np
# pythran export calculate_z(int, complex[], complex[], int[])
def calculate_z(maxiter, zs, cs, output):
"""Calculate output list using Julia update rule"""
# omp parallel for schedule(guided)
for i in range(len(zs)):
n = 0
z = zs[i]
c = cs[i]
# while n ... |
1603807 | def extractYurikatransWordpressCom(item):
'''
Parser for 'yurikatrans.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
titlemap = [
('Arms Otome Ch', 'Arms Otome', ... |
1603808 | import numpy as np
def softmax_func(x):
"""
Numerically stable softmax function. For more details
about numerically calculations please refer:
http://www.deeplearningbook.org/slides/04_numerical.pdf
:param x:
:return:
"""
stable_values = x - np.max(x, axis=1, keepdims=True)
return ... |
1603828 | import logging
from rich.logging import RichHandler
from telethon import TelegramClient
from tgpy.api import API
from tgpy.app_config import Config
from tgpy.console import console
from tgpy.context import Context
__version__ = "0.4.1"
logging.basicConfig(
level=logging.INFO, format='%(message)s', datefmt="[%X]... |
1603861 | def get_provider_info():
return {
"package-name": "airflow-provider-fivetran",
"name": "Fivetran Provider",
"description": "A Fivetran provider for Apache Airflow.",
"hook-class-names": ["fivetran_provider.hooks.fivetran.FivetranHook"],
"extra-links":["fivetran_provider.operators.fivetra... |
1603869 | from ctypes import *
libupper = CDLL("/Users/below/lib/libup.dylib")
libupper.mytoupper.argtypes = [c_char_p, c_char_p]
libupper.mytoupper.restype = c_int
inStr = create_string_buffer(b"This is a test!")
outStr = create_string_buffer(250)
len = libupper.mytoupper(inStr, outStr)
print(inStr.value)
print(outStr.valu... |
1603886 | import os
import json
import time
import jsonpatch
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from basicauth import encode
from retrying import retry
from dart.model.action import Action, ActionState
from dart.model.dataset import Dataset
from dart.model.datastore import D... |
1603889 | import ee
from ee_plugin import Map
# Computed area filter.
# Find US counties smaller than 3k square kilometers in area.
# Load counties from TIGER boundaries table
counties = ee.FeatureCollection('TIGER/2016/Counties')
# Map a function over the counties to set the area of each.
def func_blc(f):
# Compute area... |
1603899 | from django.urls import reverse
from django.test import TestCase
from ..models import Badge
from .mixins import BadgeFixturesMixin
class BadgeDetailViewTestCase(TestCase):
"""
BadgeDetail view test case.
"""
def setUp(self):
self.badge = Badge.objects.create(
name='Djangonaut',
... |
1603932 | class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
if n == 0: return True
i, l1, l2 = 0, len(flowerbed), len(flowerbed) - 1
while n > 0 and i < l1:
if flowerbed[i] == 1:
i += 2
else:
if i == l2 or flowerbed... |
1603933 | import warnings
from itertools import tee, starmap
from operator import gt
from copy import copy
import numpy as np
import pandas as pd
import bioframe
def assign_view_paired(
features,
view_df,
cols_paired=["chrom1", "start1", "end1", "chrom2", "start2", "end2"],
cols_view=["chrom", "start", "end"]... |
1603937 | class Solution:
def sumEvenAfterQueries(self, A: List[int], queries: List[List[int]]) -> List[int]:
evenSum = sum(num for num in A if num % 2 == 0)
result = []
for val, index in queries:
if A[index] % 2 == 0:
evenSum -= A[index]
A[index] += val
... |
1603975 | from honeygrove.config import Config
from honeygrove.core.ServiceController import ServiceController
from honeygrove.services.ListenService import ListenService
import twisted.internet.reactor
import unittest
class ListenServiceTest(unittest.TestCase):
listen = None
Controller = None
@classmethod
d... |
1603976 | import arcade
import imgui
import imgui.core
from imdemo.page import Page
class WindowMenu(Page):
def draw(self):
flags = imgui.WINDOW_MENU_BAR
imgui.begin("Child Window - File Browser", flags=flags)
if imgui.begin_menu_bar():
if imgui.begin_menu('File'):
img... |
1604022 | import random
class QA:
def __init__(self, question, correctAnswer, otherAnswers):
self.question = question
self.corrAnsw = correctAnswer
self.otherAnsw = otherAnswers
qaList = [QA("Where is New Delhi?", "in India", ["in Pakistan", "in China"]),
QA("What is the capital of Angola?", "Luanda", ["Sydney", ... |
1604027 | import os
from ....utils.common import redirected_stdio
from bloom.generators.debian.generator import em
from bloom.generators.debian.generator import get_changelogs
from bloom.generators.debian.generator import format_description
from catkin_pkg.packages import find_packages
test_data_dir = os.path.join(os.path.di... |
1604036 | from django.core.management.base import NoArgsCommand
class Command(NoArgsCommand):
help = "Returns a list of the SQL statements required to return all tables in the database to the state they were in just after they were installed."
output_transaction = True
def handle_noargs(self, **options):
f... |
1604074 | def abs(x):
if x > 0:
return x
else:
return -x
def sqrt(x):
eps = 1e-10
x = float(x)
r = x/2
residual = r**2 - x
while abs(residual) > eps:
r_d = -residual/(2*r)
r += r_d
residual = r**2 - x
return r
def p(x):
prec = 11
l = list(iter(str(... |
1604078 | import pytest
from homework.models import Answer
pytestmark = [
pytest.mark.django_db,
pytest.mark.usefixtures('purchase'),
]
@pytest.fixture
def _no_purchase(purchase):
purchase.setattr_and_save('paid', None)
def get_answer():
return Answer.objects.last()
def test_creation(api, question, anothe... |
1604114 | import logging
from nltk.tokenize import sent_tokenize
from pynsett.auxiliary.names_modifier import SentenceNamesModifier, assign_proper_index_to_nodes_names, \
DiscourseNamesModifier
from pynsett.discourse.anaphora import AllenCoreferenceVisitorsFactory
from pynsett.discourse.global_graph_visitors import GraphJo... |
1604174 | from setuptools import setup
setup(
name='rpp',
version='0.4',
install_requires=[
'ply',
'attrs',
],
)
|
1604198 | def minimise(on_set, off_set, used_columns=set()):
"""Minimise a set of keys and masks.
Parameters
----------
on_set : {(key, mask), ...}
Set of keys and masks to minimise.
off_set : {(key, mask), ...}
Set of keys and masks which should *not* be covered by the minimised
vers... |
1604219 | from .base_fetcher import BaseFetcher
from integrations.models import Artist, Release
from spotipy.oauth2 import SpotifyOAuth
import datetime
import os
from dateutil.parser import parse
class SpotifyFetcher(BaseFetcher):
def integration_identifier(self):
return('spotify')
def activate_integration(sel... |
1604248 | from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we need to invoke the executable file which will then invoke actual browser
#driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
#driver=webdriver.Firefox(executable_path="C:\\geckodriver.exe")
driver = webdriver.Ie(... |
1604302 | import logging
from flask import request
from flask_restplus import Resource
from biolink.datamodel.serializers import compact_association_set, association_results
from ontobio.golr.golr_associations import search_associations, GolrFields
from biolink.api.restplus import api
from biolink import USER_AGENT
MAX_ROWS=1... |
1604374 | import os
import copy
import scipy
import numpy as np
import matplotlib.pyplot as plt
from astropy import wcs
from astropy.io import fits
from astropy.table import Table, Column
import astropy.units as u
from astropy.coordinates import SkyCoord
from .display import display_single, SEG_CMAP
from .utils import img_cuto... |
1604403 | import logging
import sys
format_str = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
formatter = logging.Formatter(format_str)
def get_verbose_logger(module_name):
"""Gets a logger that writes to the console using a StreamHandler
Args:
**module_name (str)**: Name of the module requesting th... |
1604411 | import os
import matplotlib.pyplot as plt
def create_dir(path):
if not os.path.exists(path):
os.makedirs(path)
def make_image2(xy,img_folder,prefix):
if not os.path.exists(img_folder):
os.makedirs(img_folder);
fig_num=len(xy);
mydpi=100;
for i in range(fig_num):
#fig = plt.figure(figsize=(32... |
1604444 | from functools import lru_cache
from typing import Optional
import pydantic
SETTINGS_ENV_FILE = "~/.planetarycomputer/settings.env"
SETTINGS_ENV_PREFIX = "PC_SDK_"
DEFAULT_SAS_TOKEN_ENDPOINT = "https://planetarycomputer.microsoft.com/api/sas/v1/token"
class Settings(pydantic.BaseSettings):
"""PC SDK configurati... |
1604447 | import logging
import random
import pandas as pd
from atpy.portfolio.portfolio_manager import PortfolioManager, MarketOrder, Type
from pyevents.events import EventFilter
class RandomStrategy:
"""Random buy/sell on each step"""
def __init__(self, listeners, bar_event_stream, portfolio_manager: PortfolioMana... |
1604457 | from qpylib import qpylib
def test_submodules_imported():
assert qpylib.app_qpylib is not None
assert qpylib.asset_qpylib is not None
assert qpylib.json_qpylib is not None
assert qpylib.log_qpylib is not None
assert qpylib.offense_qpylib is not None
assert qpylib.rest_qpylib is not None
ass... |
1604491 | import hashlib, json, os, gzip, sys, re
from unidecode import unidecode
def tab_file(fname, cols):
for line in file(fname).readlines():
vals = line.strip().split("\t")
yield dict(zip(cols, vals))
def _id(uri):
return hashlib.md5(uri).hexdigest()[:16]
has_unicode = re.compile(r'[^\0x00-0x7f]')... |
1604517 | from aspen import log
from gratipay.application import Application
log('Instantiating Application from gunicorn_entrypoint')
website = Application().website
|
1604519 | import math
from textblob import TextBlob
from nlp_profiler.constants import NOT_APPLICABLE, NaN
### Sentiment analysis
def sentiment_polarity_summarised(polarity: str) -> str:
if (not polarity) or (polarity == NOT_APPLICABLE):
return NOT_APPLICABLE
if 'negative' in polarity.lower():
return... |
1604584 | from torch2trt.torch2trt import *
from torch2trt.module_test import add_module_test
@tensorrt_converter('torch.nn.functional.linear')
def convert_Linear(ctx):
input = ctx.method_args[0]
weight = get_arg(ctx, 'weight', 1, None)
bias = get_arg(ctx, 'bias', 2, None)
input_trt = add_missing_trt_tensors(ct... |
1604601 | from typing import Union
class TensorAdapter:
def zeros(self, size: int, dtype: str):
raise NotImplemented()
def argmax(self, arr):
raise NotImplemented()
def get(self, tensor, pos):
raise NotImplemented()
try:
import numpy as np
class NumpyAdapter(TensorAdapter):
... |
1604635 | import torch
from torch import nn
import torch.nn.functional as F
from backbones.unet import Encoder as unet_encoder, Decoder as unet_decoder
from backbones.resnet import resnet50 as resnet_encoder, Decoder as resnet_decoder
from utils.topology import get_circle
import neural_renderer as nr
__all__ = ['CircleNet']
... |
1604664 | import numpy as np
from scipy.fftpack import ss_diff
import torch
from torch import optim
class SPSA(object):
def __init__(self, model,norm, device, eps, learning_rate, delta, spsa_samples, sample_per_draw,
nb_iter, data_name, early_stop_loss_threshold=None, IsTargeted=None):
sel... |
1604679 | import update_index
def test_iter_plugins(mocker):
client = mocker.MagicMock()
client.list_packages.return_value = ["pytest-plugin-a", "pytest-plugin-b"]
client.package_releases.return_value = ["1.0"]
client.browse.return_value = [("pytest-plugin-c", "2.0")]
client.release_data = lambda name, vers... |
1604681 | from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import hashlib
from typing import Dict, Tuple, Optional
class MypyFileCache(object):
def __init__(self):
# type: () -> None
self._cache = {} # type: Dict[str, Tuple[str, str]]
def ... |
1604697 | import tensorflow as tf
import tensorflow.contrib.slim as slim
from tensorflow.contrib.slim.nets import resnet_v1
import numpy as np
class MultiModal(object):
def __init__(self, mode, learning_rate=0.0001):
self.mode = mode
self.learning_rate = learning_rate
self.hidden_repr_size = 128
... |
1604771 | import pytest
@pytest.mark.parametrize(
"file, result, expected",
(
("src/dafny/utils/MathHelpers.dfy", "passed", "passed"),
("src/dafny/utils/Helpers.dfy", "failed", "failed"),
),
)
def test_proof_result(file, result, expected):
assert file.endswith(".dfy")
assert result == expec... |
1604778 | from ml_tutor.model import BaseModelRegression
import time
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error
class LinearRegression(BaseModelRegression):
def __init__(self, learning_rate=0.0001, num_iter=100000, tol=0.00001, visual_training=True):
"""
Creates the... |
1604793 | import numpy as np
import matplotlib.pyplot as plt
from multilayer_perceptron import MLP
from gradient_boosting_decision_tree import GBDT
from xgboost import XGBoost
from random_forest import RandomForest
from adaboost import AdaBoost
from factorization_machines import FactorizationMachines
from support_vector_machine ... |
1604823 | from subprocess import CompletedProcess
from unittest import TestCase
from unittest.mock import patch, call
from data_acquisition_framework.services.youtube.youtube_dl_api import YoutubeDL
class TestYoutubeDL(TestCase):
def setUp(self):
self.youtube_dl_service = YoutubeDL()
def test_init(self):
... |
1604842 | import logging
import re
from django.conf import settings
from twilio.base.exceptions import TwilioRestException
from twilio.rest import Client
from helium.common.utils.commonutils import HeliumError
__author__ = "<NAME>"
__copyright__ = "Copyright 2021, Helium Edu"
__version__ = "1.4.46"
logger = logging.getLogger... |
1604892 | import os
import json
import time
import threading
import rospy
from std_msgs.msg import String
from lg_msg_defs.msg import WindowGeometry
from appctl_support import ProcController
from lg_msg_defs.msg import ApplicationState
from lg_msg_defs.srv import MediaAppsInfoResponse
from lg_common.helpers import get_app_insta... |
1604894 | from airflow import DAG
from airflow_kubernetes_job_operator.kubernetes_legacy_job_operator import (
KubernetesLegacyJobOperator,
)
# from airflow.operators.bash_operator import BashOperator
from airflow.utils.dates import days_ago
# These args will get passed on to each operator
# You can override them on a per-... |
1604932 | import FWCore.ParameterSet.Config as cms
#
# module to combine the persistent genParticles
# from the top decay and top mothers
#
genEvtSingleTop = cms.EDProducer("StGenEventReco",
src = cms.InputTag("decaySubset"),
init = cms.InputTag("initSubset")
)
|
1604935 | from office365.entity_collection import EntityCollection
from office365.teams.channels.channel import Channel
class ChannelCollection(EntityCollection):
"""Team's collection"""
def __init__(self, context, resource_path=None):
super(ChannelCollection, self).__init__(context, Channel, resource_path)
... |
1604962 | from deepaffects.realtime.deepaffects_realtime_pb2 import SegmentChunk
def segment_chunk(content, encoding="wav", languageCode="en-US", sampleRate=8000, segmentOffset=0, duration=0):
"""segment_chunk.
Args:
encoding : Audio Encoding,
languageCode: language code ,
sampleRate: sample r... |
1604963 | from __future__ import print_function, unicode_literals, with_statement, division
from django.core.management.base import BaseCommand
from django.utils.crypto import get_random_string
from django.utils.translation import ugettext as _
import string
class Command(BaseCommand):
help = _('This command generates SE... |
1604964 | from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
determine_ext,
str_to_int,
)
class ZippCastIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?zippcast\.com/(?:video/|videoview\.php\?.*\bvplay=)(?P<id>[0-9a-zA-Z]+)'
_TESTS = [{
# m3u... |
1604968 | from gym.envs.registration import register
from . import env_v1
register(
id='ObstacleAvoidance-v0',
entry_point='environments.carla_enviroments.env_v1_ObstacleAvoidance.env_v1:ObstacleAvoidanceScenario',
trials = 10,
reward_threshold = 100.,
)
register(
id='ObstacleAvoidance-v1',
entry_point='... |
1605054 | import torch
import torch.nn as nn
def Conv1x1ReLU(in_channels,out_channels):
return nn.Sequential(
nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=1),
nn.ReLU6(inplace=True)
)
def Conv3x3ReLU(in_channels,out_channels,stride,padding):
return ... |
1605098 | from __future__ import absolute_import, unicode_literals, print_function
import logging
import pprint
from builtins import str, object
from future.utils import python_2_unicode_compatible, iteritems
from .compat import PY2, PY2_STR
log = logging.getLogger(__name__)
__all__ = ('compile',
'TypeMatch',
... |
1605113 | import sys
from pyiron_atomistics import Project, __version__
pr = Project("tests/static/backwards/")
for job in pr.iter_jobs(recursive=True, convert_to_object=False):
if job.name == "sphinx":
job = job.to_object()
job.run()
print("job {} loaded from {}".format(job.id, sys.argv[0]))
|
1605135 | from ... import UP, DOWN, LEFT, RIGHT, UP_2, DOWN_2, LEFT_2, RIGHT_2
class Movable:
move_up = UP
move_up_alt = UP_2
move_down = DOWN
move_down_alt = DOWN_2
move_left = LEFT
move_left_alt = LEFT_2
move_right = RIGHT
move_right_alt = RIGHT_2
lr_step = 1
ud_step = 1
wrap_hei... |
1605203 | import FWCore.ParameterSet.Config as cms
from DQM.L1TMonitorClient.L1TOccupancyClient_cfi import *
|
1605276 | import torch
import torch.nn.functional as F
from torch import nn
from torch.optim import Adam
from einops import rearrange, repeat
import sidechainnet as scn
from en_transformer.en_transformer import EnTransformer
torch.set_default_dtype(torch.float64)
BATCH_SIZE = 1
GRADIENT_ACCUMULATE_EVERY = 16
def cycle(loader... |
1605291 | import numpy as np
import matplotlib.pyplot as plt
plt.figure(1)
plt.clf()
plt.axis([-10, 10, -10, 10])
# Define properties of the "bouncing balls"
n = 10
pos = (20 * np.random.sample(n*2) - 10).reshape(n, 2)
vel = (0.3 * np.random.normal(size=n*2)).reshape(n, 2)
sizes = 100 * np.random.sample(n) + 100
# Colors wher... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.