id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1719726 | import numpy as np
import torch
def getIndeices(shape,height,width,stride,dialation, offset):
H, W = shape
outHeight = (H - dialation*(height-1)-1) // stride +1
outWidth = (W - dialation*(width-1)-1) // stride +1
i0 = np.repeat(np.arange(height)*dialation, width)
i1 = stride * np.repeat(np.arange(... |
1719752 | import random
import threading
import functools
from collections import Counter
from src.gamemodes import game_mode, GameMode
from src.messages import messages
from src.containers import UserList, UserDict
from src.decorators import command, handle_error
from src.functions import get_players, change_role
from src.statu... |
1719753 | from django.utils import translation
import lxml.html
def text_content(e):
return e.text_content().strip()
def texts_for(e, selector):
return list(text_content(m) for m in e.cssselect(selector))
def text_for_tags(e, tags):
return list(
text_content(c)
for c in e.getchildren()
i... |
1719755 | import os
from PIL import Image
from torch.utils.data import DataLoader, Dataset
import torchvision.transforms as transforms
from config import *
class Edges2Handbags(Dataset):
"""Edges2Handbags Dataset"""
def __init__(self, image_path, purpose):
self.path = os.path.join(image_path, pu... |
1719758 | import h5py
import numpy as np
import xarray as xr
from pathlib import Path
import brainio_collection
from brainio_base.assemblies import NeuronRecordingAssembly
from brainio_contrib.packaging import package_data_assembly
from mkgu_packaging.dicarlo.kar2018 import filter_neuroids
def load_responses(response_file, ad... |
1719781 | import bpy
from . import _common
class ahs_maincurve_select(bpy.types.Operator):
bl_idname = 'object.ahs_maincurve_select'
bl_label = "選択"
bl_description = "メインカーブをすべて選択する"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
try:
for ob in context.visibl... |
1719806 | import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat
from isab_pytorch import ISAB
# helpers
def exists(val):
return val is not None
def batched_index_select(values, indices):
last_dim = values.shape[-1]
return values.gather(1, indices[:, :, None... |
1719844 | import sure # noqa # pylint: disable=unused-import
import xmltodict
import moto.server as server
def test_cloudfront_list():
backend = server.create_backend_app("cloudfront")
test_client = backend.test_client()
res = test_client.get("/2020-05-31/distribution")
data = xmltodict.parse(res.data, dict_... |
1719877 | import zipfile
from surprise import SVD, Dataset, Reader, evaluate
# Unzip ml-100k.zip
zipfile = zipfile.ZipFile('ml-100k.zip', 'r')
zipfile.extractall()
zipfile.close()
# Read data into an array of strings
with open('./ml-100k/u.data') as f:
all_lines = f.readlines()
# Prepare the data to be used in Surprise
r... |
1719893 | import torch
import os
import pandas as pd
from datetime import datetime
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
def load_dataset(root, s_label):
# following the preprocessing on
# https://github.com/propublica/compas-analysis/blob/master/Compas... |
1719931 | from contextlib import contextmanager
from sqlalchemy import create_engine, Boolean, Column, DateTime, Integer, String, LargeBinary
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from . import DB_PATH
eng = None
session_factor... |
1719939 | import numpy as np
from keras.layers.core import Lambda, Merge
from keras.layers.convolutional import Convolution2D
from keras import backend as K
from keras.regularizers import l1l2, Regularizer
from keras.engine import Layer
def crosschannelnormalization(alpha = 1e-4, k=2, beta=0.75, n=5,**kwargs):
"""
... |
1720011 | import argparse
import numpy as np
import tensorflow as tf
import os
import sys
import scipy.io as sio
baseDir = os.path.dirname(os.path.abspath(__file__))
rootDir = os.path.dirname(baseDir)
sys.path.append(baseDir)
sys.path.append(os.path.join(rootDir, 'models'))
sys.path.append(os.path.join(rootDir, 'utils'))
parse... |
1720028 | from types import MethodType
from typing import * # noqa: F401 F403 (because of the argspec factory)
from typing import Any, Dict, Union, Callable, Iterable, Optional
from inspect import Parameter, unwrap, isabstract
import inspect
import wrapt
import typing_extensions # noqa: F401
import pandas as pd
from omnipat... |
1720077 | from django.conf.urls import url, include
urlpatterns = (
url(r'', include('takeyourmeds.recordings.recordings_create.urls',
namespace='create')),
)
|
1720094 | from .tokenizers import ABtokenizer
from .model import AbLang, AbRep, AbHead
from .pretrained import pretrained |
1720101 | import struct
import socket
def ip2int(addr):
"""
Convert an IP in string format to decimal format
"""
return struct.unpack("!I", socket.inet_aton(addr))[0]
def check_ip(ip, network_range):
"""
Test if the IP is in range
Range is expected to be in CIDR notation format. If no MASK is
... |
1720109 | import shutil
import os
import re
work = os.getcwd()
found = []
regex = re.compile(r'pydarkstar\.(.*)\.rst')
for root, dirs, files in os.walk(work):
for f in files:
m = regex.match(f)
if m:
found.append((root, f))
for root, f in found:
path = os.path.join(root, f)
with open(pat... |
1720130 | from typing import Any, Callable, Optional
class Monostate:
def __init__(
self,
on_progress: Optional[Callable[[Any, bytes, int], None]],
on_complete: Optional[Callable[[Any, Optional[str]], None]],
title: Optional[str] = None,
duration: Optional[int] = None,
):
... |
1720159 | from django.shortcuts import HttpResponseRedirect, reverse
from rest_framework import viewsets, filters, mixins
from rest_framework.response import Response
import django_filters
from maintainer.models import Maintainer
from maintainer.forms import MaintainerAutocompleteForm
from maintainer.serializers import Maintain... |
1720287 | import cv2
img = cv2.imread("../image/squirrel.jpg")
rectangledImg = cv2.rectangle(img,(120,100),(370,380),(0,0,255), 2)
writeText = cv2.putText(rectangledImg,"This is Squirrel", (118,95), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255,0,0), 2)
cv2.imwrite("putText.jpg",writeText)
cv2.imshow("TextedImg",writeText)
|
1720300 | import os
import sys
from typing import Any, Optional
import _tkinter as tk
from ._base import TkWidget
from ._layouts import BaseLayoutManager
from ._utils import from_tcl, to_tcl
from ._window_mixin import WindowMixin
from .exceptions import TclError
tcl_interp = None
class App(WindowMixin, TkWidget):
wm_pat... |
1720302 | import os
from pages.topic_collection_page.fixtures.helpers.create_fixture import create_fixture
import pages.topic_collection_page.fixtures.helpers.components as components
from snippets.theme.fixtures.test_cases import kitchen_sink as kitchen_sink_theme
# A "kitchen sink" topic collection page
def kitchen_sink():
... |
1720311 | import sqlalchemy as sa
from alembic import op
"""add email verification fields
Revision ID: <KEY>
Revises: <PASSWORD>
Create Date: 2019-02-25 18:46:34.490192
"""
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '<PASSWORD>'
def upgrade():
op.add_column('app_user', sa.Column(
... |
1720387 | import json
import fastai
from fastai.torch_core import Any, Tensor, MetricsList, ifnone
from fastai.basic_train import LearnerCallback, Learner
import time
from firebasedata import SendDataToFirebase
SendData = SendDataToFirebase()
class Fastdash(LearnerCallback):
"""
Uses callbacks to in torchdash to sen... |
1720421 | import unittest
import codegen
import ast
import sys
PY3 = sys.version_info >= (3, 0)
class TestCodegen(unittest.TestCase):
def assertPreserved(self, code):
result = codegen.to_source(ast.parse(code))
self.assertEqual(result.rstrip(), code.rstrip())
def test_BoolOp(self):
self.assert... |
1720425 | import torch
import numpy as np
from FClip.nms import non_maximum_suppression, structure_nms
class PointParsing():
@staticmethod
def jheatmap_torch(jmap, joff, delta=0.8, K=1000, kernel=3, joff_type="raw", resolution=128):
h, w = jmap.shape
lcmap = non_maximum_suppression(jmap[None, ...], de... |
1720446 | import asyncio
import logging
from typing import Optional
from async_timeout import timeout
from asyncpg import PostgresError
from buildpg.asyncpg import BuildPgConnection, connect_b
from ..settings import BaseSettings
__all__ = 'AsyncPgContext', 'lenient_conn'
logger = logging.getLogger('foxglove.db')
class Asyn... |
1720453 | from unittest import TestCase
from Ity.Taggers.DocuscopeTagger import DocuscopeTagger
__author__ = 'zthomae'
class TestDocuscopeTagger(TestCase):
def test__get_ds_words_for_token(self):
self.fail()
def test__get_ds_words_for_token_index(self):
self.fail()
def test__get_long_rule_tag(sel... |
1720459 | import math
from typing import Any, Dict, Iterable
from fugue import FugueWorkflow
from tune import optimize_by_continuous_asha
from tune.constants import TUNE_REPORT_METRIC
from tune.concepts.dataset import TuneDatasetBuilder
from tune.iterative.asha import ASHAJudge, RungHeap
from tune.iterative.objective import Ite... |
1720526 | import torch
import torch.nn.functional as F
from .concat_softmax import ConcatSoftmax
from .utils import split_half
class SymNetsCategoryLoss(torch.nn.Module):
def __init__(self):
super().__init__()
self.softmax_fn = ConcatSoftmax()
# x and y are the first and second halves of "p^st"
de... |
1720527 | from .agent import A3CAgent
from .episode import Episode
from .shared_optim import SharedAdam, SharedRMSprop
|
1720555 | from carla_utils import carla
cc = carla.ColorConverter
import re
import numpy as np
import collections
import pygame
def find_weather_presets():
rgx = re.compile('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)')
name = lambda x: ' '.join(m.group(0) for m in rgx.finditer(x))
presets = [x for x in ... |
1720578 | import os
import subprocess
import tempfile
import pytest
import nbformat
dir = os.path.dirname(__file__)
path_list = os.path.split(dir)
extension_path = path_list[0]
notebook_path = os.path.join(extension_path, 'lenstronomy_extensions/Notebooks')
def _notebook_run(path):
"""Execute a notebook via nbconvert and ... |
1720615 | import os
import sys
import math
import random
import numpy as np
from datetime import datetime
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import data_utils
def _stoke_decoding(stoke):
lift_pen_padding = 2.0
lines = []
points = []
x_prev = 0
y_prev = 0
was_dr... |
1720638 | from botfunc import search_connpass_online
import pytest
import json
from pathlib import Path
@pytest.fixture()
def mocking_connpass_json(monkeypatch):
"""
connpassAPIのレスポンスになるjsonをjsonファイルに固定するmonkeypatch
"""
def test_connpass_json(ym):
"""
テスト用のconnpass api レスポンス結果をjsonファイルからloadする... |
1720687 | import datetime
import pandas as pd
from searchtweets import ResultStream, gen_rule_payload, load_credentials
from twilio_connect_demo import twilio_connect, send_message
premium_search_args = load_credentials(
filename="secret_demo.yaml", yaml_key="search_tweets_api", env_overwrite=False
)
today = datetime.date... |
1720723 | import re
import numpy as np
__all__ = ['get_color', 'get_next_color']
HEX = '0123456789abcdef'
HEX2 = dict((a+b, (HEX.index(a)*16 + HEX.index(b)) / 255.) \
for a in HEX for b in HEX)
def rgb(triplet):
triplet = triplet.lower()
if triplet[0] == '#':
triplet = triplet[1:]
if len(tripl... |
1720724 | import cv2
import numpy as np
path = '/Users/mitchellkrieger/opt/anaconda3/envs/learn-env/share/opencv4/haarcascades/'
#get facial classifiers
face_cascade = cv2.CascadeClassifier(path +'haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(path +'haarcascade_eye.xml')
#read images
witch = cv2.i... |
1720736 | import math
import numpy as np
import logging
logger = logging.getLogger('cwl')
class CWLMetric(object):
def __init__(self):
self.expected_utility = 0.0
self.expected_cost = 0.0
self.expected_total_utility = 0.0
self.expected_total_cost = 0.0
self.expected_ite... |
1720738 | import numpy as np
from graph_tiger.graphs import karate
from graph_tiger.cascading import Cascading
from graph_tiger.diffusion import Diffusion
def test_sis_model():
params = {
'model': 'SIS',
'b': 0.00208,
'd': 0.01,
'c': 1,
'runs': 10,
'steps': 5000,
'd... |
1720763 | def export_module_as():
from jumpscale.core.base import StoredFactory
from .liquid import LiquidClient
return StoredFactory(LiquidClient)
|
1720766 | from ckan.plugins.interfaces import Interface
class IDataValidation(Interface):
def can_validate(self, context, data_dict):
'''
When implemented, this call can be used to control whether the
data validation should take place or not on a specific resource.
Implementations will rec... |
1720776 | import re
import string
PUNCTUATION_TRANS = str.maketrans(string.punctuation, ' ' * len(string.punctuation))
WHITESPACE_TRANS = str.maketrans(string.whitespace, ' ' * len(string.whitespace))
def preprocess_text(text):
"""Method for pre-processing the given response text.
It:
* replaces all punctuations w... |
1720783 | import mpl_toolkits.axes_grid1.axes_grid as axes_grid_orig
from .axislines import Axes
class CbarAxes(axes_grid_orig.CbarAxesBase, Axes):
pass
class Grid(axes_grid_orig.Grid):
_defaultAxesClass = Axes
class ImageGrid(axes_grid_orig.ImageGrid):
_defaultAxesClass = Axes
_defaultCbarAxesClass = CbarA... |
1720793 | import json
import os
import pytest
from vdb.lib.gha import GitHubSource
from vdb.lib.nvd import NvdSource
@pytest.fixture
def test_cve_json():
test_cve_data = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "data", "cve_data.json"
)
with open(test_cve_data, "r") as fp:
return... |
1720828 | import time
import torch
import os
import sys
sys.path.insert(0, '.')
import vedanet as vn
__all__ = ['speed']
def speed():
print('Creating network')
batch = 1
gpus = '7'
network_size = (544, 544)
max_iters = 200
use_cuda = True if gpus is not None else False
if gpus is not None:
... |
1720842 | import shutil
import tempfile
from multiprocessing import Process, Value
from pathlib import Path
from color import Color
from image import Image
from point import Point
from ray import Ray
class RenderEngine:
"""Renders 3D objects into 2D objects using ray tracing"""
MAX_DEPTH = 5
MIN_DISPLACE = 0.0001... |
1720905 | import tvm
def test_for():
dev_type = tvm.var("dev_type")
def device_context(dev_id):
ctx = tvm.call_extern("handle", "device_context", dev_type, dev_id)
return tvm.make.Call(
"handle", "tvm_thread_context", [ctx], tvm.expr.Call.Intrinsic, None, 0)
ib = tvm.ir_builder.create()
... |
1720909 | import Augmentor
test = "True"
test2 = "True"
test3 = "True"
imgaug = "True"
if imgaug == "True":
p = Augmentor.Pipeline("images/", output_directory="")
if test == "True":
print("Rotate kismindayim")
p.rotate(probability=0.7, max_left_rotation=10, max_right_rotation=10)
if test2 == "... |
1720910 | def get_context(context):
context.volunteers = [
dict(
name='<NAME>',
title='Conference Manager',
contact='<EMAIL>'
),
dict(
name='<NAME>',
title='Tickets and Registration',
contact='<EMAIL>'
),
dict(
name='<NAME>',
title='Guest Relations',
contact='<EMAIL>'
)
]
|
1720923 | from io import BytesIO
from awscrt.auth import (
AwsCredentialsProvider,
AwsSigningAlgorithm,
AwsSignatureType,
)
from awscrt.http import HttpRequest, HttpHeaders
import pytest
from amazon_transcribe.auth import StaticCredentialResolver
from amazon_transcribe.request import Request
from amazon_transcribe... |
1720955 | import numpy as np
from gym import spaces
import vrep
from envs.VrepEnv import catch_errors, VrepEnv
class SawyerEnv(VrepEnv):
"""
Abstract parent class encapsulating behaviour common to environments with a Sawyer arm.
"""
num_joints = 7
action_space = spaces.Box(np.array([-0.3] * num_joints), np... |
1720997 | from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.contrib.auth.decorators import login_required
from django.urls import path
from tcgen import views as tvi... |
1720999 | from nlp_id.tokenizer import Tokenizer, PhraseTokenizer
def test_tokenizer():
"""
test for Tokenizer
"""
tokenizer = Tokenizer()
text = "<NAME> pergi ke pasar di area Jakarta Pusat."
text2 = "Pada akhirnya, kucobalah apakah benar masakanmu enaknya seperti yang kukira."
text3 = "semuanya pe... |
1721068 | import hashlib
import importlib
from collections import namedtuple
from datetime import datetime
import pytest
import pytz
import requests
from asn1crypto import tsp, algos, core, cms, ocsp
from freezegun import freeze_time
from oscrypto import asymmetric, symmetric
from pyhanko_certvalidator import ValidationContext,... |
1721077 | class Closure:
def __init__(self, proto, py_func, n):
self.proto = proto
self.py_func = py_func
self.upvals = []
if proto and len(proto.upvalues) > 0:
self.upvals = [None] * len(proto.upvalues)
elif py_func and n > 0:
self.upvals = [None] * n
|
1721078 | import pygame
from util import loadImage
from monster_dropping import MonsterDropping
from random import randint
class Monster(pygame.sprite.Sprite):
def __init__(self, screen_rect, drawing_group):
pygame.sprite.Sprite.__init__(self)
self.screen_rect = screen_rect
self.drawing_group = draw... |
1721084 | import pytest
from slim.base._view.base_view import BaseView
from slim.base._view.err_catch_context import ErrorCatchContext
from slim.exception import FinishQuitException, SyntaxException, SQLOperatorInvalid, ColumnIsNotForeignKey, \
InvalidParams, InvalidPostData, InvalidHeaders, TableNotFound, ColumnNotFound, R... |
1721091 | import mxnet as mx
from mxnet import gluon
from mxnet.gluon import HybridBlock
from ceecnet.utils.get_norm import *
class Conv2DNormed(HybridBlock):
"""
Convenience wrapper layer for 2D convolution followed by a normalization layer
All other keywords are the same as gluon.nn.Conv2D
"""
... |
1721102 | from koala.sequence_id import SequenceId
_request_id = SequenceId()
_reentrant_id = SequenceId()
def set_request_id_seed(seed: int):
_request_id.set_seed(seed)
def new_request_id() -> int:
return _request_id.new_id()
def set_reentrant_id_seed(seed: int):
_reentrant_id.set_seed(seed)
def new_reentra... |
1721119 | from dataclasses import dataclass, field
from typing import List, Union
from relogic.structures.structure import Structure
@dataclass
class Pointwise(Structure):
text_a: str = None
text_b: str = None |
1721135 | import databricks.koalas as ks
import numpy as np
# These function can return a Column Expression or a list of columns expression
# Must return None if the data type can not be handle
import pandas as pd
from pyspark.sql import functions as F
from optimus.engines.base.commons.functions import word_tokenize
from optimu... |
1721136 | from .containers import LiteralInt, LiteralDec, Temporary, DelegatedWrite
from .cbl_type import CBLType, CBLTypeInstance
from .native_type import NativeType, as_var
from .operator_mixins import LogOperatorMixin, IntegerOperators, \
NumericalOperators, IntrinsicOperatorType
import cmd_ir.instructions as i
class V... |
1721188 | import torch
from torch import nn
def create_fc_stack(fc_channel, act=nn.ReLU, **act_kwargs):
fc = nn.Sequential()
for i in range(len(fc_channel) - 1):
in_c = fc_channel[i]
out_c = fc_channel[i + 1]
fc_name = 'fc_%d_%d' % (in_c, out_c)
fc.add_module(fc_name, nn.Linear(in_c, out_... |
1721206 | import os
from cdp.cdp_viewer import OutputViewer
from .default_viewer import create_metadata
from .utils import add_header, h1_to_h3
def create_viewer(root_dir, parameters):
"""
Given a set of parameters for a certain set of diagnostics,
create a single page.
Return the title and url for this page... |
1721252 | try:
from PyQt5.QtWidgets import QComboBox
from PyQt5.QtCore import Qt
except ImportError:
from PySide2.QtWidgets import QComboBox
from PySide2.QtCore import Qt
class ComboBox(QComboBox):
def findData(self, any_obj, role=Qt.UserRole, *args, **kwargs):
if args or kwargs:
return ... |
1721285 | cmp_str = {
'ORTH' : lambda x : x.str,
'TEXT' : lambda x : x.str,
'LOWER' : lambda x : x.str.lower(),
'LEMMA' : lambda x : x.lemma,
'POS' : lambda x : x.pos,
'DEP' : lambda x : x.dep,
'ENT_TYPE' : lambda x : x.ner.get('type', [''])[0],
'CATEGORY_SUPER' : lambda x : ... |
1721308 | import yahoo_finance
def get_stock_info_and_historical_data(symbol):
"""Retrieve stock info and historical data for `symbol`
Leverages yahoo-finance for Python
https://github.com/lukaszbanasiak/yahoo-finance
"""
share = yahoo_finance.Share(symbol)
info = share.get_info()
start_date = info... |
1721339 | import keras.backend as K
import numpy as np
import pandas as pd
from datetime import time, datetime
import tensorflow as tf
from argparse import ArgumentParser
def get_flops(model):
run_meta = tf.RunMetadata()
opts = tf.profiler.ProfileOptionBuilder.float_operation()
# We use the Keras session graph in ... |
1721347 | import numpy as np
import tqdm
from losses.dsm import dsm_score_estimation
import torch.nn.functional as F
import logging
import torch
import os
import shutil
import tensorboardX
import torch.optim as optim
from torchvision.datasets import MNIST, CIFAR10, FashionMNIST
import torchvision.transforms as transforms
from to... |
1721351 | from qtpy.QtWidgets import QWidget, QSizePolicy
class FormBaseWidget(QWidget):
def __init__(self):
super().__init__()
self.setMaximumWidth(400)
self.setMinimumWidth(400)
sp = self.sizePolicy()
sp.setVerticalPolicy(QSizePolicy.Minimum)
self.setSizePolicy(sp)
|
1721356 | from django.db import connection, ProgrammingError
from serveradmin.serverdb.models import Attribute, ServerAttribute, Server
from django.core.exceptions import ObjectDoesNotExist
def attribute_startswith(search_string, limit=20):
"""Query attributes starting search_string
:param search_string: e.g. al to m... |
1721395 | from pathlib import Path
from pipup.req_files import ReqFile
def test_find_package_requirements():
""" Find the requirements file in this package """
r = ReqFile(auto_read=False)
assert r.exists
# Our valid path
p = Path(__file__).parent / "../requirements.txt"
p = p.resolve()
assert r.... |
1721401 | from django.contrib import admin
from .models import Speaker, Talk, Slot, Workshop
class SlotAdmin(admin.ModelAdmin):
list_display = ['date', 'get_description', 'room']
list_filter = ['room']
date_hierarchy = 'date'
def get_queryset(self, request):
return super().get_queryset(request).prefetc... |
1721455 | from setuptools import setup, find_packages
import sys, os
PROJECT_NAME = 'HanziSRS'
mainscript = '{}/__main__.py'.format(PROJECT_NAME)
setup_requires = ['PyQt5', 'google_speech', 'bs4', 'jieba', 'requests', 'flask', 'PyYAML']
if sys.platform == 'darwin':
setup_requires.append('py2app')
extra_options = dict(
... |
1721466 | from __future__ import absolute_import
from builtins import object
from mock import Mock
from .fixtures.mock_cmdl import cmdl
from .fixtures.mock_utils import MockUtils
from relaax.server.rlx_server.rlx_config import options
from relaax.common.rlx_netstring import NetStringClosed
from relaax.server.rlx_server.\
rl... |
1721506 | import unittest
from dffml.util.config.numpy import numpy_docstring_args
from .double_ret import double_ret as numpy_double_ret
class TestMakeConfig(unittest.TestCase):
def test_numpy_docstring_args(self):
args = numpy_docstring_args(numpy_double_ret)
self.assertIn("super_cool_arg", args)
... |
1721570 | from __future__ import absolute_import, unicode_literals
import unittest
from fluent_compiler.bundle import FluentBundle
from fluent_compiler.errors import FluentReferenceError
from ..utils import dedent_ftl
class TestSelectExpressionWithStrings(unittest.TestCase):
def test_with_a_matching_selector(self):
... |
1721573 | import itertools
import asynctest
import pytest
from aioredis import RedisError
from jsondaora import dataclasses
@pytest.mark.asyncio
async def test_should_get_one(
fake_service, serialized_fake_entity, fake_entity
):
await fake_service.repository.memory_data_source.hmset(
'fake:other_fake:fake',
... |
1721583 | from heliotrope.argparser import parse_args
from heliotrope.config import HeliotropeConfig
def test_parse_args():
config = HeliotropeConfig()
args = parse_args(
[
"--host",
"127.0.0.1",
"--port",
"8000",
"--workers",
"1",
... |
1721598 | load("@npm//@angular/bazel:index.bzl", _ng_module = "ng_module")
load("@io_bazel_rules_sass//sass:sass.bzl", _sass_binary = "sass_binary", _sass_library = "sass_library")
def ng_module(
# name used for this rule
name,
# typescript sources
srcs,
# dependencies for the typescript ... |
1721617 | import base64
import json
import boto3
import web3
from eth_account.messages import defunct_hash_message
from common.blockchain_util import BlockChainUtil
from common.boto_utils import BotoUtils
from common.logger import get_logger
from signer.config import GET_SERVICE_DETAILS_FOR_GIVEN_ORG_ID_AND_SERVICE_ID_REGISTRY... |
1721623 | import abc
from algotrader.model.market_data_pb2 import *
from algotrader.model.model_factory import ModelFactory
from algotrader.model.trade_data_pb2 import *
from algotrader.trading.event import MarketDataEventHandler
from algotrader.utils.market_data import get_quote_mid
from algotrader.utils.model import add_to_li... |
1721648 | from flake8_multiline_containers import MultilineContainers
import pytest
@pytest.fixture
def linter():
m = MultilineContainers()
m.errors = []
return m
@pytest.fixture
def dummy_file_path():
return 'tests/dummy'
|
1721652 | from skidl import SKIDL, TEMPLATE, Part, Pin, SchLib
SKIDL_lib_version = '0.0.1'
pspice = SchLib(tool=SKIDL).add_parts(*[
Part(name='0',dest=TEMPLATE,tool=SKIDL,do_erc=True),
Part(name='CAP',dest=TEMPLATE,tool=SKIDL,do_erc=True,aliases=['C']),
Part(name='DIODE',dest=TEMPLATE,tool=SKIDL,do_erc=... |
1721711 | import time
from concurrent.futures import ThreadPoolExecutor
####### SINGLE THREAD
def ask_user():
start = time.time()
user_input = input('Enter your name: ')
greet = f'Hello, {user_input}'
print(greet)
print('ask_user: ', time.time() - start)
def complex_calculation():
print('Started calculating...')
start ... |
1721748 | from discord.ext import commands
class HelpCommand(commands.DefaultHelpCommand):
def get_ending_note(self):
ending_note = super().get_ending_note()
invite = self.context.bot.config.server_invite
if self.get_destination() == self.context.author:
return f"Join the server: {invit... |
1721757 | from __future__ import nested_scopes, generators, division, absolute_import, with_statement, \
print_function, unicode_literals
from .utilities.compatibility import backport
backport()
import serial.abc
from copy import deepcopy
import serial
from .utilities import qualified_name
from .abc.model import Model
tr... |
1721767 | from MyDD import MyDeltaDebuggingReducer, MyGrammarReducer
import os
import subprocess
class TryDeltaDebugging:
def __init__(self,program,input,timeout=None):
self.program=program
inputfile=open(input,mode="rb")
self.input=inputfile.read()
inputfile.close()
self.timeout=time... |
1721786 | import torch
import torch.nn as nn
import torch.nn.functional as F
from dconv_native import DeformConv3d
from network.layers import DConv3d, MDConv3d, SpatialDConv3d, SpatialMDConv3d
from network.layers import ASPPModule
from utils.registry import register
@register("module")
class GC3d(nn.Module):
def __init__(s... |
1721794 | from mixt.contrib.css import css_vars
from .generic import MenuCollector
class MainMenuCollector(MenuCollector):
# noinspection PyUnresolvedReferences
@css_vars(globals())
@classmethod
def render_css_global(cls, context):
colors = context.styles.colors
tagged = tuple(
f'... |
1721825 | def has_magnet(self):
"""Return if the Hole has magnets
Parameters
----------
self : HoleM51
A HoleM51 object
Returns
-------
has_magnet : bool
True if the magnets are not None
"""
return (
self.magnet_0 is not None
or self.magnet_1 is not None
... |
1721830 | import os
import pytest
@pytest.fixture
def patch_project_dir(monkeypatch):
monkeypatch.setattr('uwsgiconf.contrib.django.uwsgify.toolbox.find_project_dir', lambda: 'dummy')
@pytest.fixture
def patch_base_command(monkeypatch, patch_project_dir, tmpdir):
fifofile = tmpdir.join('some.fifo')
fifofile.wri... |
1721831 | from flamejam import db
from datetime import datetime
class Comment(db.Model):
id = db.Column(db.Integer, primary_key=True)
text = db.Column(db.Text)
posted = db.Column(db.DateTime)
game_id = db.Column(db.Integer, db.ForeignKey('game.id'))
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
... |
1721973 | import logging
import shlex
from unittest import TestCase
from pydantic_cli import to_runner_sp
from pydantic_cli.examples.subparser import to_subparser_example
log = logging.getLogger(__name__)
class TestExamples(TestCase):
def _run_with_args(self, args: str):
f = to_runner_sp(to_subparser_example())
... |
1721999 | del_items(0x801373D8)
SetType(0x801373D8, "unsigned char map_buf[102400]")
del_items(0x801503D8)
SetType(0x801503D8, "unsigned short *imgbuf[21]")
del_items(0x8015042C)
SetType(0x8015042C, "struct POLY_FT4 br[10][2][2]")
del_items(0x80150A6C)
SetType(0x80150A6C, "struct POLY_FT4 tmdc_pol[10][2][2]")
del_items(0x801510A... |
1722018 | import os
import sqlite3
from datetime import timedelta, datetime
from threading import Timer, Lock
from plugin import *
class ignore(plugin):
def __init__(self, bot):
super().__init__(bot)
self.time_delta_regex = re.compile(r'([0-9]+[Hh])?\W*([0-9]+[Mm])?(.*)')
self.ignore_timers = []
... |
1722058 | from unittest.mock import Mock
from ombpdf import document
def test_textline_repr_works(m_16_19_doc):
assert repr(m_16_19_doc.pages[0][4]) == \
'<OMBTextLine with text "August 1, 2016 ">'
def test_textline_is_blank_works(m_16_19_doc):
assert m_16_19_doc.pages[0][0].is_blank()
assert not m_16_19... |
1722095 | from small_text.query_strategies.exceptions import (EmptyPoolException, # noqa:F401
QueryException,
PoolExhaustedException)
from small_text.query_strategies.coresets import (greedy_coreset, # noqa:F401
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.