id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
4854582 | import matplotlib
import matplotlib.pyplot as plt
import numpy as np
__all__ = [
"cartesian",
"barycentric",
"contour",
"contourf",
"scatter",
]
def cartesian(points):
"""Converts array of barycentric coordinates on a 2-simplex to an array of
Cartesian coordinates on a 2D triangle in the ... |
4854602 | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('ggplot')
#### make a funcion that lets you specify a few parameters and calculates the payoff
# S = underlying price
# K = strike price
# Price = premium paid for option
def long_call(S, K, Price):
# Long Call Payoff = max(un... |
4854607 | import struct
#############################
## Static Configurations ##
#############################
GOT_START_MARKER = struct.pack(">L", 0x11222211)
GOT_END_MARKER = struct.pack(">L", 0x33444433)
# Variables (sizes only)
scout_instructions_globals_32_size = 4 + 10 * 16
scout_instructions_globals_64_size = 8 + ... |
4854625 | import win32com.client as win32
# Grab the Active Instance of Excel.
adobe_app = win32.GetActiveObject("Illustrator.Application")
# Define the Document we will be working with.
adobe_file = adobe_app.ActiveDocument
# Let's start with my Layer, that should contain my other objects.
thumbnail_layer = adobe_file.Layers... |
4854631 | import tabulate
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from standup.status.models import StandupUser
class Command(BaseCommand):
help = 'Stats for standup db'
def handle(self, *args, **options):
User = get_user_model()
users = []
... |
4854634 | from abc import ABC, abstractmethod
from typing import Any, Type, Union
from typing_extensions import Final
from embeddings.embedding import flair_embedding as flair_embedding_module
from embeddings.embedding.flair_embedding import (
FlairAggregationEmbedding,
FlairDocumentCNNEmbeddings,
FlairDocumentPool... |
4854682 | from ..datasets.audio import stft
from .plot import get_viridis
import numpy as np
def specgram(arr, fftsize=512, step=16, mean_normalize=True, real=False,
compute_onesided=True, min_value=-100, max_value=np.inf, axis=0):
arr = np.array(arr)
if len(arr.shape) != 1:
raise ValueError("arr m... |
4854716 | from hazel.chromosphere import Hazel_atmosphere
from hazel.photosphere import SIR_atmosphere
from hazel.parametric import Parametric_atmosphere
from hazel.stray import Straylight_atmosphere
from hazel.configuration import Configuration
from hazel.io import Generic_output_file
from collections import OrderedDict
from ha... |
4854721 | from __future__ import absolute_import
from __future__ import print_function
import veriloggen
import dataflow_lut
expected_verilog = """
module test
(
);
reg CLK;
reg RST;
reg [32-1:0] xdata;
reg xvalid;
wire xready;
reg [32-1:0] ydata;
reg yvalid;
wire yready;
wire [32-1:0] zdata;
wire zvalid;... |
4854739 | import boto3
import gzip
import json
import logging
import os
from StringIO import StringIO
firehose = boto3.client('firehose')
def lambda_handler(event, context):
encodedLogsData = str(event['awslogs']['data'])
decodedLogsData = gzip.GzipFile(fileobj = StringIO(encodedLogsData.decode('base64','stric... |
4854780 | import unittest
from test_case import TestCase
import hppfcl
hppfcl.switchToNumpyArray()
import numpy as np
class TestMainAPI(TestCase):
def test_collision(self):
capsule = hppfcl.Capsule(1.,2.)
M1 = hppfcl.Transform3f()
M2 = hppfcl.Transform3f(np.eye(3),np.array([3, 0, 0]))
req=h... |
4854785 | import FWCore.ParameterSet.Config as cms
from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer
ecalPreshowerTimingTask = DQMEDAnalyzer('ESTimingTask',
RecHitLabel = cms.InputTag("ecalPreshowerRecHit","EcalRecHitsES"),
DigiLabel = cms.InputTag("ecalPreshowerDigis"),
prefixME = cms.untracked.string("EcalPreshower"... |
4854805 | import pytest
from brownie.network.account import Account # type: ignore
from brownie.test import strategy # type: ignore
from brownie import accounts, Marketplace, E721, E1155, ZERO_ADDRESS, reverts # type: ignore
# from hypothesis.stateful import precondition
from typing import DefaultDict, Dict, List, Tuple, Opt... |
4854858 | import os
import yaml
import argparse
from src.data.preprocess import preprocess
parser = argparse.ArgumentParser()
parser.add_argument('--miladatadir', type=str, help="Mila dataset directory")
parser.add_argument('--fig1datadir', type=str, help="Figure 1 dataset directory")
parser.add_argument('--rsnadatadir', type=s... |
4854875 | from concurrent.futures import TimeoutError
from google.cloud import pubsub_v1
import argparse
subscriber = pubsub_v1.SubscriberClient()
def sub(project_id, subscription_id):
timeout = 5.0
subscription_path = subscriber.subscription_path(project_id, subscription_id)
def callback(message):
print(f... |
4854877 | import numpy as np
from sklearn.base import BaseEstimator
from sklearn.model_selection import GridSearchCV, KFold, cross_val_score
from sklearn.linear_model import Ridge
from sklearn.neighbors import KNeighborsRegressor
from sklearn.pipeline import make_pipeline
from mlxtend.feature_selection import ColumnSelector
from... |
4854905 | from __future__ import absolute_import
from django.contrib.auth import middleware
class AuthenticationMiddleware(middleware.AuthenticationMiddleware):
pass
|
4854926 | import seamless
from seamless.core import macro_mode_on
from seamless.core import context, cell
with macro_mode_on():
ctx = context(toplevel=True)
ctx.cson = cell("cson")
ctx.cson.mount("/tmp/test.cson", mode="rw")
ctx.json = cell("plain")
ctx.json.mount("/tmp/test.json", mode="w")
ctx.cson.con... |
4854929 | from hatch.structures import File
TEMPLATE = """\
{title}
{header_marker}
{badges}.. contents:: **Table of Contents**
:backlinks: none
Installation
------------
{package_name} is distributed on `PyPI <https://pypi.org>`_ as a universal
wheel and is available on Linux/macOS and Windows and supports
Python {suppor... |
4854940 | import os
import subprocess
import logging
import sys
import re
import math
import random
import pandas as pd
import statistics as st
from Bio import pairwise2
from Bio import SeqIO
from Bio.Seq import Seq
from joblib import Parallel, delayed
from cctyper.minced import CRISPR
class RepeatMatch(object):
def... |
4854953 | from paradrop.base import constants
def test_constants():
assert hasattr(constants, 'DAEMON_FEATURES')
assert hasattr(constants, 'RESERVED_CHUTE_NAME')
|
4854983 | import json
import base64
import typing
import tempfile
import re
from datetime import datetime
from datetime import timezone
import asyncio
import falcon
from mitmproxy import ctx
from mitmproxy import connections
from mitmproxy import version
from mitmproxy.utils import strutils
from mitmproxy.net.http import c... |
4854994 | import numpy as np
def strategy(history, memory):
n = history.shape[1]
if n == 0:
return 1, np.array([0] * 16)
elif n >= 2:
olderMove = 2 * history[0, -2] + history[1, -2]
recentMove = 2 * history[0, -1] + history[1, -1]
memory[4 * olderMove + recentMove] += 1
# measure... |
4854996 | from typing import List
from pytest import mark
from subprocess import run, PIPE
from py2puml.py2puml import py2puml
from tests import __version__, __description__
@mark.parametrize(
'entrypoint', [
['py2puml'],
['python', '-m', 'py2puml']
]
)
def test_cli_consistency_with_the_default_configu... |
4855035 | from setuptools import setup, find_packages
__version__ = '3.0.0'
with open("README.md", "r") as f:
long_description = f.read()
setup(
name='reactome2py',
version=__version__,
description='Python client for Reactome content and analysis service API calls.',
long_description=long_description,
... |
4855070 | from arekit.common.bound import Bound
from arekit.common.pipeline.context import PipelineContext
from arekit.common.pipeline.item import BasePipelineItem
class SentenceObjectsParserPipelineItem(BasePipelineItem):
def __init__(self, iter_objs_func):
assert(callable(iter_objs_func))
self.__iter_obj... |
4855102 | import rotaryio
import board
import digitalio
import usb_hid
from adafruit_hid.consumer_control import ConsumerControl
from adafruit_hid.consumer_control_code import ConsumerControlCode
button = digitalio.DigitalInOut(board.D12)
button.direction = digitalio.Direction.INPUT
button.pull = digitalio.Pull.UP
encoder = ro... |
4855109 | from collections import namedtuple
Vector = namedtuple('Vector', 'x1 y1 x2 y2 origin_x origin_y')
# setting default values for the last two elements only, i.e. origin_x and origin_y.
Vector.__new__.__defaults__ = (0, 0)
v1 = Vector(0, 0, 10, 10, -10, -10)
print(v1)
# Vector(x1=0, y1=0, x2=10, y2=10, origin_x=-10, ori... |
4855144 | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "agtc",
version = read("VERSION"),
author = "<NAME>",
author_email = "<EMAIL>",
description = ("Compiler for AGT programming language"),
... |
4855163 | from enum import Enum
class CellRawStrDatum(Enum):
""" These are the types of data that may appear in a raw str description of a cell from the server. """
x = 0
f = 1
y = 2
g = 3
t = 4
mf = 5
col = 6
mon = 7 |
4855166 | import cv2
import numpy as np
import utils
#src means source while dst means destination
#this function will make dst as the filtered image of src
def strokeEdges(src, dst, blurKsize = 7, edgeKsize = 5):
#bulrKsize can be used to determine whether we should blur
if blurKsize >= 3:
blurredSrc = cv2.media... |
4855182 | import torch
import torch.nn as nn
class QFunction(nn.Module):
"""
The Q Function
:param network: (nn.Module) The network.
:param optimizer: (torch.optim.Optimizer) The optimizer.
"""
def __init__(self, network: nn.Module, optimizer: torch.optim.Optimizer) -> None:
super().__init__()... |
4855184 | from collections import deque
class Solution:
"""
@param: start: a string
@param: end: a string
@param: dict: a set of string
@return: An integer
"""
def ladderLength(self, start, end, dictionary):
# write your code here
if start == end:
return 1
diction... |
4855215 | from django.core import mail
from django.test import override_settings
from django.urls import reverse
from colossus.apps.campaigns.tests.factories import EmailFactory, LinkFactory
from colossus.apps.lists.tests.factories import MailingListFactory
from colossus.apps.subscribers.constants import ActivityTypes, Status
f... |
4855254 | from abc import ABC, abstractmethod
from PuppeteerLibrary.ikeywords.base_async_keywords import BaseAsyncKeywords
class iDropdownAsync(BaseAsyncKeywords, ABC):
@abstractmethod
async def select_from_list_by_value(self, locator, values):
pass
@abstractmethod
async def select_from_list_by_label(... |
4855266 | import json
import os
#pip install git+https://github.com/ericsomdahl/python-bittrex.git
from bittrex.bittrex import Bittrex, API_V2_0, API_V1_1, BUY_ORDERBOOK, TICKINTERVAL_ONEMIN
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
import Config
my_bittrex ... |
4855270 | import pytest
import control
from tests import assertions
@pytest.fixture
def screen(running_app, root_manager):
from screens.activity.activity import ActivityScreen
s = ActivityScreen()
root_manager.add_widget(s)
return s
def test_enter_activity(not_empty_data, root_manager, screen):
control.... |
4855301 | import os, sys
project_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(project_path)
import torch
from baseline.scscore import train, SCNN, loss_marginranking, valid, loss_softmax
from utils.save_load import save_checkpoint
from utils.scheduler import build_lr_sch... |
4855313 | from __future__ import unicode_literals
import pytest
from lomond.compression import CompressionParameterError, Deflate
from lomond.frame import Frame
def test_deflate_repr():
deflate = Deflate(15, 8, False, False)
assert repr(deflate) == 'Deflate(decompress_wbits=15, compress_wbits=8, reset_decompress=Fals... |
4855314 | import numpy as np
from PartSegCore.algorithm_describe_base import ROIExtractionProfile
from PartSegCore.project_info import AdditionalLayerDescription
from PartSegCore.segmentation.algorithm_base import ROIExtractionResult
class TestSegmentationResult:
def test_update_alternative_names(self):
res = ROIE... |
4855362 | from robot.api.deco import keyword, library
from robot.libraries.BuiltIn import BuiltIn
from robot.libraries.Process import Process
@library(scope='SUITE', version='0.1.0', doc_format='reST')
class CloudIntegration:
ROBOT_LISTENER_API_VERSION = 2
def __init__(self):
self._counter = 0
self.ROBOT_LIBRAR... |
4855369 | import dicomsort
import re
import wx
from threading import Thread
from urllib.request import urlopen
from dicomsort.gui import events
meta = dicomsort.Metadata
def version_tuple(version):
parts = list()
for component in version.split('.'):
number_match = re.match('^\\d+', component)
if nu... |
4855391 | from __future__ import division, absolute_import, print_function
import os
import warnings
__all__ = ['importall']
def importall(package):
"""
`importall` is DEPRECATED and will be removed in numpy 1.9.0
Try recursively to import all subpackages under package.
"""
warnings.warn("`importall is d... |
4855418 | STANDARD_REPLIES = "tests/fixtures/standard_replies"
with open("tests/fixtures/reply-quotations-share-block.eml") as f:
REPLY_QUOTATIONS_SHARE_BLOCK = f.read()
with open("tests/fixtures/OLK_SRC_BODY_SECTION.html") as f:
OLK_SRC_BODY_SECTION = f.read()
with open("tests/fixtures/reply-separated-by-hr.html") as... |
4855459 | def any_args(self,*a,**k): return True
def watch_call(method_name,arg_test= any_args):
""" Adds a Conditionnal Breakpoint to the method method_name of the decorated obj
"""
def make_watcher(obj):
class _watch(obj):
def __init__(self,*a,**k):
init= getattr(obj,'__init__'... |
4855473 | import torch
from torchvision import transforms
from PIL import Image
import torch.nn as nn
import torch.nn.functional as F
#from LeNet_angle_camera import LeNet_angle_camera
from Angle1 import Angle1
import numpy as np
import cv2
class Angle1(nn.Module):
def __init__(self):
super(Angle1, sel... |
4855493 | import re
from itertools import permutations
cel = re.compile(r'11[7-9][0-9]{7}')
for tel in permutations(range(1, 10), 10):
_tel = ''.join(str(x) for x in tel)
if cel.search(_tel):
print(_tel)
|
4855514 | from __future__ import annotations
import typing as tp
import configparser
import os
from pathlib import Path
DEFAULT_LOGSTORE_DIR = f"{os.getcwd()}/.logexp"
class Settings:
@classmethod
def _get_default_dict(cls) -> tp.Dict:
default_dict = {
"logexp": {
"module": "",
... |
4855518 | import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from torch.nn import init
from network import utils as utils
class MultiAttn(nn.Module):
def __init__(self, in_dim, head_num=10):
super(MultiAttn, self).__init__()
self.head_dim = in_dim // head_num
self.... |
4855543 | def create_django_choice_tuple_from_list(list_a):
if list_a is None:
return ()
tuples_list = []
for item in list_a:
if isinstance(item, str):
tuple_item_title = item.title()
else:
tuple_item_title = item
tuple_item = (item, tuple_item_title)
... |
4855544 | import abc
from collections import OrderedDict
import numpy as np
from util import util as util
class RobotSystem(abc.ABC):
def __init__(self,
urdf_file,
package_name,
b_fixed_base,
b_print_robot_info=False):
"""
Base RobotSyste... |
4855571 | from flask_wtf import FlaskForm
from wtforms import (
StringField,
SubmitField,
SelectField,
PasswordField,
HiddenField,
BooleanField,
FormField,
)
from wtforms.fields.html5 import IntegerField
from wtforms.validators import DataRequired, URL
from archivy.config import Config
class NewBook... |
4855574 | import logging
import os
import json
from ..exports_store import ExportsTableStore, ExportsTableNames
from ..tenable_helper import TenableStatus
import azure.functions as func
connection_string = os.environ['AzureWebJobsStorage']
vuln_table_name = ExportsTableNames.TenableVulnExportTable.value
def main(... |
4855590 | import tensorflow as tf
import itertools
def bilinear_interaction_layer(input, embedding_dim, type, name):
"""
FiBinet模型中的Bilinear Interaction Layer实现
Args:
input (Tensor): 输入, shape=(batch, F, K)
embedding_dim (int): embedding维度K
type (str): Bilinear interaction类型, "all", "eac... |
4855605 | import torch
def swish(x):
"""
Swish activation function,
from <NAME>, Le 2017. "Searching for Activation Functions"
"""
return x * torch.sigmoid(x) |
4855611 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Dict
from models.gnn_encoder import StarE_PyG_Encoder
from utils.utils_gcn import get_param, weight_init
from utils.nodepiece_tokenizer import NodePiece_Tokenizer
from torch_geometric.data import Data
class StarE_... |
4855629 | from inspect import isfunction
import math
import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat
from ldm.modules.diffusionmodules.util import checkpoint
def exists(val):
return val is not None
def uniq(arr):
return{el: True for el in arr}.keys()
d... |
4855637 | import json
import time
import threading
import http.server
import socketserver
import pickle
from brainslug import slug, run, body
from brainslug.ribosome import root, define
# ----------------------------------------- #
# Start Laguage Freak Zone
# ----------------------------------------- #
python = root('python'... |
4855668 | import struct
import time
import sys
import pytest
from fido2.attestation import Attestation
from fido2.client import Fido2Client, _call_polling
from fido2.ctap import CtapError
from fido2.ctap1 import CTAP1
from fido2.ctap2 import ES256, AttestedCredentialData, PinProtocolV1
from fido2.hid import CtapHidDevice
from f... |
4855681 | import os, sys, argparse, cdms2, MV2, vcs, vcs.testing.regression as regression
p = argparse.ArgumentParser(description="Basic gm testing code for vcs")
p.add_argument("--source", dest="src", help="source image file")
p.add_argument("--gm_type", dest="gm", help="gm to test",choices=["boxfill","meshfill","isofill"])
p.... |
4855737 | import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from layers import *
from .networks import vgg, vgg_base, ConvOffset2d
class RefineSSD(nn.Module):
def __init__(self,size, num_classes=21, phase='train', c7_channel=1024, def_groups=1, bn=True, multihead=False, return_feature=False, devi... |
4855754 | import open_cp.gui.funcs as funcs
def test_string_ellipse():
assert funcs.string_ellipse("ahdsgs", 10) == "ahdsgs"
assert funcs.string_ellipse("sasagdjgha", 7) == "... gha" |
4855762 | from zeus import factories
from zeus.tasks import send_build_notifications
def test_sends_failure(mocker, db_session, default_revision, default_tenant):
mock_send_email_notification = mocker.patch(
"zeus.notifications.email.send_email_notification"
)
build = factories.BuildFactory(revision=defaul... |
4855766 | print('\n' * 100 + '@ TelegramBackup is loading...')
import os.path
from tgback_utils import (
TelegramAccount, TgbackAES, restore,
VERSION, qr_available, image_error, scanqrcode
)
from getpass import getpass
from sys import platform
from traceback import print_exc
from time import ctime, strftime
from reeds... |
4855780 | import unittest
from typing import Dict, List
from sacrerouge.common import FromParams, Params, Registrable
class _Base1(Registrable):
pass
@_Base1.register('subclass1')
class _Subclass1(_Base1):
def __init__(self, a: int, b: str):
self.a = a
self.b = b
@_Base1.register('subclass2')
class... |
4855804 | import torch
import torch.nn as nn
from ...modules import WithRecorder
class Identity(WithRecorder):
"""
Do nothing.
"""
def __init__(self):
super(Identity, self).__init__()
def forward(self, features):
return features |
4855857 | import numpy as np
from numpy.random import default_rng
def FireflyAlgorithm(function, dim, lb, ub, max_evals, pop_size=20, alpha=1.0, betamin=1.0, gamma=0.01, seed=None):
rng = default_rng(seed)
fireflies = rng.uniform(lb, ub, (pop_size, dim))
intensity = np.apply_along_axis(function, 1, fireflies)
b... |
4855865 | import dash_bootstrap_components as dbc
from dash import html
accordion = html.Div(
dbc.Accordion(
[
dbc.AccordionItem(
[
html.P("This is the content of the first section"),
dbc.Button("Click here"),
],
titl... |
4855868 | import pandas as pd
from pandas.testing import assert_frame_equal
from dtspec.core import markdown_to_df
# pylint: disable=redefined-outer-name
def test_convert_table_to_df():
given = """
| id | name |
| - | - |
| 1 | one |
| 2 | two |
| 3 | three |
"... |
4855904 | from sklearn.tree import DecisionTreeClassifier
from mosaic_ml.model_config.util import convert_multioutput_multiclass_to_multilabel
from mosaic_ml.model_config.util import check_none
class AdaboostClassifier:
def __init__(self, n_estimators, learning_rate, algorithm, max_depth,
random_state=N... |
4855908 | PANEL_DASHBOARD = 'project'
PANEL_GROUP = 'network'
PANEL = 'floating_ips'
ADD_PANEL = \
'openstack_dashboard.dashboards.project.floating_ips.panel.FloatingIps'
|
4855922 | import cv2
from gtts import gTTS
from playsound import playsound
def play_audio(path_of_audio):
playsound(path_of_audio)
def convert_to_audio(text):
my_audio=gTTS(text)
my_audio.save("audio.mp3")
play_audio("audio.mp3")
convert_to_audio("Starting Face detection ")
face_cascade=cv2.CascadeClassifier... |
4855931 | from reportlab import rl_config
from reportlab.lib.colors import white, black
from reportlab.lib.units import mm
from reportlab.pdfbase.acroform import AcroForm
from reportlab.platypus import Flowable, Table
class InteractiveTextField(Flowable):
def __init__(self, width=470, fontsize=12, height=18):
Flowa... |
4855941 | import numpy as np
from gym.spaces import Box
from metaworld.envs import reward_utils
from metaworld.envs.asset_path_utils import full_v2_path_for
from metaworld.envs.mujoco.sawyer_xyz.sawyer_xyz_env import SawyerXYZEnv, _assert_task_is_set
class SawyerDoorLockEnvV2(SawyerXYZEnv):
def __init__(self):
h... |
4855943 | import torch
import torch.nn as nn
from torchvision.models import mobilenet
import torch.utils.model_zoo as model_zoo
from .rutils import register
class SepConvBNReLU(nn.Sequential):
def __init__(self, in_planes, out_planes, kernel_size=3, stride=1, expand_ratio=1):
padding = (kernel_size - 1) // 2
... |
4855970 | from transcriptic.jupyter import Run
from transcriptic.util import load_sampledata_json
def load_run_from_attributes(
run_id: str,
attributes: dict,
) -> Run:
"""
Helper function for constructing an object from specified attributes
"""
return Run(
run_id=run_id,
attributes=attr... |
4855997 | import logging
import requests
def scrape(url, extractor):
"""
Function to request and parse a given URL. Returns only the "relevant"
text.
Parameters
----------
url : String.
URL to request and parse.
extractor : Goose class instance.
An instance of Goose th... |
4856005 | from datetime import date
from typing import TYPE_CHECKING
import pytest
if TYPE_CHECKING:
from simple_smartsheet.models.report import Report
from simple_smartsheet import Smartsheet, AsyncSmartsheet
class TestListReports:
@pytest.mark.vcr
def test_list_reports(self, smartsheet: "Smartsheet"):
... |
4856124 | from typing import NamedTuple
FLAKE8_FORMAT = "{path}:{row}:{col} {symbol} {msg}"
PYLINT_FORMAT = "{path}:{line}:{column}: {msg} ({symbol})"
def to_dict(namedtuple: NamedTuple) -> dict:
return dict(zip(namedtuple._fields, list(namedtuple)))
class SmellWarning(NamedTuple):
"""Class to represent a warning me... |
4856135 | from datetime import datetime
from pydantic import BaseModel, Field
class PredictRequestSchema(BaseModel):
text: str = Field(..., min_length=5, max_length=1024 * 5)
is_positive_user_answered: bool
class PredictResponseSchema(PredictRequestSchema):
is_positive_model_answered: bool
mlflow_run_id: str... |
4856150 | import logging
import os, sys, time, socket
import docker
def setupLogging():
log = logging.getLogger('maestro')
if not len(log.handlers):
log.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s %(levelname)-10s %(message)s")
filehandler = logging.FileHandler('maestro.log')
filehand... |
4856160 | from django.views.generic.base import View
from dashboard.forms import DocumentRequestStatusForm
from document.response import JsonResponse, HttpResponseBadRequest
class DocumentRequestStatusView(View):
def post(self, request):
form = DocumentRequestStatusForm(request.POST)
if not form.is_valid():... |
4856164 | import itertools
houses = [1,2,3,4,5]
orderings = list(itertools.permutations(houses))
print orderings |
4856176 | from typing import Any
from fiscalyear import FiscalYear
from rest_framework.request import Request
from rest_framework.response import Response
from usaspending_api.agency.v2.views.agency_base import AgencyBase
from usaspending_api.common.cache_decorator import cache_response
from usaspending_api.common.elasticsearc... |
4856230 | from bluedot.btcomm import BluetoothServer
from time import sleep
from signal import pause
def data_received(data):
print("recv - {}".format(data))
server.send(data)
def client_connected():
print("client connected")
def client_disconnected():
print("client disconnected")
print("init")
server = Bluet... |
4856236 | import os
import moviepy
from moviepy.audio.AudioClip import AudioArrayClip
from moviepy.editor import VideoFileClip
'''
Function: Extract audio files(.wav) from videos.
'''
def get_audio_wav(name, save_pth, audio_name):
video = VideoFileClip(name)
audio = video.audio
audio.write_audiofile(os.path.join(s... |
4856251 | from tuned.utils.plugin_loader import PluginLoader
from . import base
import tuned.logs
import tuned.consts as consts
from tuned.utils.commands import commands
log = tuned.logs.get()
class Repository(PluginLoader):
def __init__(self):
super(Repository, self).__init__()
self._functions = {}
@property
def func... |
4856255 | import random
import numpy as np
from tqdm import tqdm_notebook
from collections import defaultdict
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence, pad_packed_sequence
from torch.utils.data import DataLoader, Dataset
from transformers import *
from create_dataset ... |
4856262 | from __future__ import print_function
import numpy as np
from nltk.corpus import brown
from sklearn.decomposition import LatentDirichletAllocation
from sklearn.feature_extraction.text import CountVectorizer
# For reproducibility
np.random.seed(1000)
if __name__ == '__main__':
# Compose a corpus
... |
4856273 | import sys
import os
import cPickle
import pysal as ps
#Hack to get the KDTree used in GWK to pickle.
# KDTree uses nested classes that the pickler can not find.
from scipy.spatial import kdtree
kdtree.node = kdtree.KDTree.node
kdtree.leafnode = kdtree.KDTree.leafnode
kdtree.innernode = kdtree.KDTree.innernode
def ma... |
4856334 | import pkgutil
import os
def load_theme(theme):
for try_theme in [theme, "ocean"]:
theme_file = f"themes/{try_theme}.theme"
try:
theme_data = pkgutil.get_data(__name__, theme_file)
if theme_data:
return theme_data.decode("utf-8")
except FileNotFoundEr... |
4856372 | from django.dispatch import receiver
from structlog import get_logger
from . import credit_card_deleted, credit_card_registered
from ..actions import accounts
from ..models import Account, CreditCard
logger = get_logger()
@receiver(credit_card_registered)
def credit_card_registered_handler(sender, credit_card: Cred... |
4856389 | import cv2
import random
import numpy as np
from matplotlib import pyplot as plt
# 读取操作
img_ori = cv2.imread('lenna.jpg', 1) # 彩色图片
img_gray = cv2.imread('lenna.jpg', 0) # 黑白图片
print(img_ori.shape)
# 打印操作,默认通道为 BGR
# cv2.imshow("lenna", img_ori)
# key = cv2.waitKey()
# if key == 27:
# cv2.destroyAllWindows()
#... |
4856398 | def my_func(a, b):
'''
Returns the product of a and b
:param a: Must be a interger, is the first parameter
:param b: Must be a string, must be a string
:return: Transforms param b into a int and returns a + b
'''
try:
b = int(b)
result = b + a
except Exception as e:
... |
4856408 | from tkinter import *
from tkinter.ttk import Style
from links import get_links
class Ui:
def __init__(self, master):
self.master = master
# App Title
self.master.title("Link Extractor")
# header_title
self.header_title = Label(master, text="Extract links")
self.h... |
4856433 | import pandas as pd
from tabulate import tabulate
from utils.unique import unique
from collections import defaultdict
HEAD = ["tag", "precision", "recall", "f1-score",
"preds_true", "num_preds", "num_labels"]
groups=[
['person', 'title', 'firstname', 'middle', 'last',
'nickname', 'nicknametitle', 'n... |
4856441 | from __future__ import absolute_import, division, print_function, unicode_literals
from itertools import islice
from six import exec_, iteritems, iterkeys, itervalues, PY2
__all__ = [
'listitems', 'listkeys', 'listvalues', 'mapkeys', 'mapvalues',
'merge_dicts', 'listmap', 'inverse_mapping', 'is_sorted', 'has... |
4856483 | from flask_session.sessions import (
NullSessionInterface,
RedisSessionInterface,
MemcachedSessionInterface,
FileSystemSessionInterface,
MongoDBSessionInterface,
)
from .sqla import SqlAlchemySessionInterface
__all__ = [
'NullSessionInterface',
'RedisSessionInterface',
'MemcachedSessi... |
4856514 | import datetime
import httplib2
# to see in detail what's going on, uncomment
# httplib2.debuglevel = 4
from apiclient.discovery import build
from oauth2client.client import OAuth2Credentials, OAuth2WebServerFlow
if __name__ == "__main__":
flow = OAuth2WebServerFlow(client_id="client_id_from_Console.apps.google... |
4856521 | from django.shortcuts import render
# Create your views here.
def index_view(request):
context = {}
return render(request, "website/index.html", context)
# function for error 400
def error_400(request, exception):
context = {"exeption": exception}
response = render(request, "errors/400.html", conte... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.