id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1726652 | import unittest
import numpy as np
from welib.tools.colors import TestColors
if __name__ == '__main__':
unittest.main()
|
1726657 | from django.test.testcases import TestCase
from django.core.management import call_command
from mock import patch
from robber import expect
class CacheDataTestCase(TestCase):
@patch('data.cache_managers.cache_all')
def test_cache(self, cache_all_mock):
call_command('cache_data')
expect(cache_... |
1726722 | from __future__ import unicode_literals
from __future__ import absolute_import
import django
from django.test import TestCase
from job.error.error import JobError
class TestJobError(TestCase):
"""Tests functions in the job error module."""
def setUp(self):
django.setup()
def test_creat... |
1726814 | SEND_UPLOADED_FILE_TO_SENDBOX_ANALYSIS_HTTP_RESPONSE = {
"errors": [],
"meta": {
"powered_by": "falconx-api",
"query_time": 0.163158146,
"quota": {
"in_progress": 3,
"total": 100,
"used": 36
},
"trace_id": "trace_id"
},
"resourc... |
1726824 | import mock
from celery.exceptions import SoftTimeLimitExceeded
from scoring_engine.engine.job import Job
from scoring_engine.engine.execute_command import execute_command
class TestWorker(object):
def test_basic_run(self):
job = Job(environment_id="12345", command="echo 'HELLO'")
task = execut... |
1726839 | from datetime import datetime
from . import db
class OAuth(db.Model):
__tablename__ = "oauth"
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey("user.id"))
provider_id = db.Column(db.String(255))
provider_user_id = db.Column(db.Integer)
access_token =... |
1726972 | from __future__ import division, print_function
import sys
import time
import logging
sys.path.insert(0, '../health_monitor')
from data_model import AtrFibAlarms, VenTacAlarms, APCAlarms
from data_model import Data, RespAlarms, SleepAlarms
from sqlalchemy import create_engine, func
from sqlalchemy.orm import sessionmak... |
1726978 | from HTMLTableToList import HTMLTableToList
from pprint import pprint
html_table_string = """<table class="table table-condensed">
<tr>
<th>RGB</th>
<td>53</td><td>72</td><td>35</td>
</tr>
<t... |
1726986 | from django.test.utils import override_settings
from django.test import tag
from django.contrib.gis.geos import Point
from django.core import mail
from django_elasticsearch_dsl.test import ESTestCase
from bluebottle.test.factory_models.accounts import BlueBottleUserFactory
from bluebottle.test.utils import Bluebottl... |
1727057 | from keras.models import Model
from keras.layers import Input, Dense
# A vanilla autoencoder
def autoencoder(sparse_dim, embedding_dim):
input_record = Input(shape=(sparse_dim,))
encoded = Dense(embedding_dim,
activation='relu',
name='encoder')(input_record)
decoded ... |
1727060 | from sebs.cache import Cache
from sebs.faas.config import Config, Credentials, Resources
from sebs.utils import LoggingHandlers
class LocalCredentials(Credentials):
def serialize(self) -> dict:
return {}
@staticmethod
def deserialize(config: dict, cache: Cache, handlers: LoggingHandlers) -> Crede... |
1727160 | from __future__ import print_function, division
import flopy
import gsflow
import os
import numpy as np
# from flopy.discretization import StructuredGrid
def start_tag(f, tag, indent_level, indent_char=" "):
s = indent_level * indent_char + tag
indent_level += 1
f.write(s + "\n")
return indent_level... |
1727162 | import logging
from unittest import TestCase
from tests.utils.hvac_integration_test_case import HvacIntegrationTestCase
class TestInit(HvacIntegrationTestCase, TestCase):
def test_read_init_status(self):
read_response = self.client.sys.read_init_status()
logging.debug("read_response: %s" % read_r... |
1727208 | import requests
import pandas as pd
from datetime import datetime
import ccxt
import sqlite3
import config
import settings
now = datetime.utcnow()
def get_fx(currency_f):
fx = requests.get(
'https://apilayer.net/api/live?access_key=a1d6d82a3df7cf7882c9dd2b35146d6e&source=USD&format=1').json()
return ... |
1727232 | from client import exceptions as ex
from client.sources.common import core
import mock
import unittest
###############
# Field Tests #
###############
class MockField(core.Field):
VALID_INT = 42
OK_INT = 3
INVALID_INT = 2
def is_valid(self, value):
return value == self.VALID_INT
def to_j... |
1727245 | from hoverpy import HoverPy
import unittest
import os
class TestCase(unittest.TestCase):
"""
TestCase, which can be used like unittest.TestCase
"""
def setUp(self):
"""
Set up each test case by initializing HoverPy
"""
enabled = os.environ.get(
"HOVERPY_E... |
1727266 | import numpy as np
import datetime
import pandas as pd
from operator import itemgetter
from copy import deepcopy
class BotTester(object):
"""The BotTester object is used to evaluate how close a collection of bot's picks match human picks.
This can be used in the following manner:
tester = BotTeste... |
1727296 | import argparse
from graphviz import Graph
from sequence.kernel.timeline import Timeline
from sequence.topology.node import BSMNode
from sequence.topology.topology import Topology
if __name__ == "__main__":
'''
Program for drawing network from json file
input: relative path to json file
Graphviz libra... |
1727298 | import tensorflow as tf
import numpy as np
import poisson_problem
import neural_networks
import matplotlib.pyplot as plt
from matplotlib import rc
import matplotlib.ticker as ticker
rc('font', **{'size':12, 'family':'serif', 'serif':['Computer Modern Roman']})
rc('text', usetex=True)
def draw_magnitude_int_loss(x_r... |
1727302 | from opentera.db.Base import db, BaseModel
class TeraServiceProject(db.Model, BaseModel):
__tablename__ = 't_services_projects'
id_service_project = db.Column(db.Integer, db.Sequence('id_service_project_sequence'), primary_key=True,
autoincrement=True)
id_service = db.Co... |
1727304 | from collections import defaultdict
class Solution(object):
def findJudge(self, N, trust):
"""
:type N: int
:type trust: List[List[int]]
:rtype: int
"""
graph = defaultdict(list)
for i in range(1, N + 1):
graph[i] = []
for trustPair in ... |
1727310 | from __future__ import absolute_import
from six.moves.urllib.parse import urlparse
from ..errors import SolveError
def validate_api_host_url(url):
"""
Validate SolveBio API host url.
Valid urls must not be empty and
must contain either HTTP or HTTPS scheme.
"""
if not url:
raise Sol... |
1727328 | import torch
from torch.utils.data import Dataset
from .collaters import *
import json
import pickle
import os
import glob
import sys
from musa.ops import *
from .utils import *
import timeit
import struct
import numpy as np
import multiprocessing as mp
from sklearn.cluster import KMeans
import copy
def read_aco_file... |
1727346 | from common.rule import Rule
from tree_decomposition import tree_decomposition
class TdRule(Rule):
"""
A hyperedge replacement grammar rule. In addition to storing the necessary
indexing information and graph fragment, computes various useful structures
(like the tree decomposition) which are independe... |
1727372 | import pytest
from telegram_bot import app
@pytest.fixture
def client():
# app.app.config['TESTING'] = True
client = app.app.test_client()
yield client
def test_route(client):
response = client.get('/')
assert response.status_code == 200
|
1727388 | from django.conf import settings
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.http import Http404
from django.shortcuts import render
from django.utils.translation import ugettext_lazy as _
from wagtail.contrib.routable_page.models import RoutablePageMixin, route
from wagtail.cor... |
1727400 | import json
import sys
def is_ssa(bril):
"""Check whether a Bril program is in SSA form.
Every function in the program may assign to each variable once.
"""
for func in bril['functions']:
assigned = set()
for instr in func['instrs']:
if 'dest' in instr:
if ... |
1727402 | import json
from torch.utils import data
from munch import Munch
from nltk.stem import WordNetLemmatizer
from exp import ex
from .task_loaders import load_tasks
from .tokenizer import build_tokenizer
class Dataset(data.Dataset):
def __init__(self, data_path):
super(Dataset, self).__init__()
sel... |
1727407 | from typing import Literal
from urllib.parse import urlencode
import json
import time
class Agent:
def __init__(self):
self._epoch_offset = 0
def get_screen_properties(self) -> dict:
"""Returns dict representing `window.screen`."""
return {}
def get_navigator_properties(self) ... |
1727409 | from autobahn.twisted.websocket import WebSocketServerProtocol
from autobahn.twisted.websocket import WebSocketServerFactory
from paradrop.base.output import out
class AirsharkSpectrumProtocol(WebSocketServerProtocol):
def __init__(self, factory):
WebSocketServerProtocol.__init__(self)
self.factor... |
1727414 | from http import HTTPStatus
from fastapi.param_functions import Depends
from fastapi.templating import Jinja2Templates
from starlette.exceptions import HTTPException
from starlette.requests import Request
from starlette.responses import HTMLResponse
from lnbits.core.models import User
from lnbits.decorators import ch... |
1727418 | from qsr_rcc2 import QSR_RCC2
from qsr_rcc3_rectangle_bounding_boxes_2d import QSR_RCC3_Rectangle_Bounding_Boxes_2D
from qsr_rcc4 import QSR_RCC4
from qsr_rcc5 import QSR_RCC5
from qsr_rcc8 import QSR_RCC8
from qsr_cardinal_direction import QSR_Cardinal_Direction
from qsr_qtc_b_simplified import QSR_QTC_B_Simplified
fr... |
1727452 | import wx
import gui.proxydialog as proxydialog
from logging import getLogger; log = getLogger('pg_proxy')
def panel(p, sizer, addgroup, exithooks):
pp = proxydialog.ProxyPanel(p)
sizer.Add(pp, 0, wx.EXPAND | wx.ALL)
p.on_close = pp.OnOK
return p
|
1727453 | from __future__ import absolute_import
from __future__ import print_function
import veriloggen
import generate_instance
expected_verilog = """
module blinkled #
(
parameter WIDTH = 8
)
(
input CLK,
input RST,
output [WIDTH-1:0] LED
);
genvar i;
generate for(i=0; i<WIDTH; i=i+1) begin: gen_for
submo... |
1727458 | import unittest
import os
from yacg.builder.jsonBuilder import getModelFromJson
from yacg.model.config import BlackWhiteListEntry, BlackWhiteListEntryTypeEnum
import yacg.generators.randomDataGenerator as randomDataGenerator
from yacg.model.config import RandomDataTask, RandomDataTaskOutputTypeEnum, RandomDataTaskSpe... |
1727465 | from ztag.annotation import *
class SynologyDiskStationHTTPTitle(Annotation):
protocol = protocols.HTTP
subprotocol = protocols.HTTP.GET
port = None
def process(self, obj, meta):
t = obj["title"].strip()
if t.startswith("Synology DiskStation") or t.startswith("DiskStation2"):
... |
1727478 | from setuptools import setup, find_packages
from react import VERSION
setup(
name='PyReact',
version=VERSION,
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/reactjs/react-python/',
license='Apache-2.0',
description='Python bridge to JSX & the React JavaScript library.',
... |
1727491 | import logging
from django.core.management import call_command
from math import ceil
from multiprocessing import Pool, Event, Value
from time import perf_counter
from typing import Generator, List, Tuple
from usaspending_api.broker.helpers.last_load_date import get_earliest_load_date, update_last_load_date
from usasp... |
1727521 | from collections import defaultdict
import torch
def tensors_sum(tensors):
result = 0
for tensor in tensors:
result += tensor
return result
def magnitude_squared(x):
return x.pow(2).sum(-1)
def nhwc_to_nchw(x):
return x.permute(0, 3, 1, 2)
def nchw_to_nhwc(x):
return x.permute(0... |
1727523 | import numpy as np
import os
import glob
from qtim_tools.qtim_utilities.format_util import convert_input_2_numpy
from qtim_tools.qtim_utilities.nifti_util import save_numpy_2_nifti, create_4d_nifti_from_3d
from qtim_tools.qtim_utilities.file_util import grab_files_recursive
from qtim_tools.qtim_dce.dce_util import par... |
1727556 | import numpy as np
import pandas as pd
def get_key_int_maps(keys):
key_to_int = {name: i for i, name in enumerate(keys)}
int_to_key = {i: name for i, name in enumerate(keys)}
return key_to_int, int_to_key
def onehot_encode_class(class_to_idx, classname):
n_classes = len(class_to_idx.keys())
oneho... |
1727595 | import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job
import pyspark.sql.functions as F
from pyspark import SparkContext
# from operator import add
from pyspark.sql.types impor... |
1727597 | from mmdet.datasets.builder import PIPELINES
import os
import cv2
import random
import numpy as np
def visual_table_resized_bbox(results):
bboxes = results['img_info']['bbox']
img = results['img']
for bbox in bboxes:
img = cv2.rectangle(img, (int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3]... |
1727608 | from itertools import chain
from itertools import combinations
from nose.tools import assert_equal, assert_in
import networkx as nx
from networkx.algorithms.community import asyn_lpa_communities
class TestAsynLpaCommunities(object):
def _check_communities(self, G, expected):
"""Checks that the communit... |
1727621 | from pytest import File, Item
from pytest_translations.config import MARKER_NAME
from pytest_translations.po_spelling import PoSpellCheckingItem
from pytest_translations.utils import TranslationException, open_po_file, msgfmt
class PoFile(File):
def __init__(self, fspath, parent):
super().__init__(fspath... |
1727656 | from typing import Optional
import problog
from problog.engine import GenericEngine, DefaultEngine, ClauseDB
from problog.logic import Term, Var
from problog.program import LogicProgram, SimpleProgram, PrologString
from refactor.tilde_essentials.evaluation import TestEvaluator
from refactor.tilde_essentials.example i... |
1727666 | from tests.package.test_lua import TestLuaBase
class TestLuaLuaossl(TestLuaBase):
config = TestLuaBase.config + \
"""
BR2_PACKAGE_LUA=y
BR2_PACKAGE_LUAOSSL=y
"""
def test_run(self):
self.login()
self.module_test("openssl")
self.module_test("_openssl")
... |
1727668 | from typing import Any, Dict, List
import torch.nn as nn
from ._utils import INTERNAL_ERROR_MESSAGE
from .nn import CatEmbeddings, CLSEmbedding, LinearEmbeddings
def default_no_weight_decay_condition(
module_name: str,
module: nn.Module,
parameter_name: str,
parameter: nn.Parameter,
) -> bool:
d... |
1727688 | from typing import List, Optional, Union, Iterable
import aiotfm
from aiotfm.enums import Game
from aiotfm.errors import CantFriendPlayerError, CommunityPlatformError, FriendLimitError, InvalidAccountError
from aiotfm.packet import Packet
from aiotfm.player import Player
from aiotfm.utils import Date
class FriendLis... |
1727696 | from .plots import Plot,PlotError,PlotState
from .. import context
from .. import items
from .. import maps
from .. import waypoints
from .. import monsters
from .. import dialogue
from .. import services
from .. import teams
from .. import characters
import random
from .. import randmaps
# **************************... |
1727697 | import pytest
from orion.packages.utils.nlp_utils import clean_name
from orion.packages.utils.nlp_utils import identity_tokenizer
def test_clean_name_from_double_initials():
name = "A. B. FooBar"
result = clean_name(name)
expected_result = None
assert result == expected_result
def test_clean_name... |
1727704 | import unittest
from mock import Mock, patch
from contextio.lib.resources.message import Message
from contextio.lib.resources.thread import Thread
class TestMessage(unittest.TestCase):
def setUp(self):
self.message = Message(Mock(spec=[]), {"message_id": "fake_message_id"})
def test_constructor_crea... |
1727733 | from pyspark.sql.types import StructType, StructField, \
IntegerType, TimestampType, StringType, DoubleType
citibike_schema = StructType(
[
StructField('tripduration', IntegerType(), True),
StructField('starttime', TimestampType(), True),
StructField('stoptime', TimestampType(), True),
... |
1727759 | from tkinter import Tk, Text, Menu, filedialog, Label, Button, END, W, E, FALSE
from tkinter.scrolledtext import ScrolledText
from prologpy.solver import Solver
def is_file_path_selected(file_path):
return file_path is not None and file_path != ""
def get_file_contents(file_path):
"""Return a string contain... |
1727762 | from django.core.management.base import BaseCommand
from common.utils import progress_bar
from intrinsic.models import IntrinsicImagesDecomposition
from intrinsic.tasks import upload_intrinsic_file
class Command(BaseCommand):
args = ''
help = 'Upload images to EC2'
def handle(self, *args, **options):
... |
1727797 | import sys
sys.path.append('../gen-py')
import random
from social_network import PostStorageService
from social_network.ttypes import Media
from social_network.ttypes import PostType
from social_network.ttypes import Creator
from social_network.ttypes import Url
from social_network.ttypes import UserMention
from socia... |
1727861 | import datamol as dm
def test_match_substructure():
mol1 = dm.to_mol("CC(=O)OC1=CC=CC=C1C(=O)O")
mol2 = dm.to_mol("CCN(CC)CC(=O)CC(C)NC1=C2C=CC(=CC2=NC=C1)Cl")
query1 = dm.from_smarts("[C;H0](=O)")
query2 = dm.to_mol("CN(C)")
# Test multiple scenarios
dm.viz.match_substructure(
mols... |
1727874 | import hmac
import base64
import hashlib
from nonebot.utils import logger_wrapper
log = logger_wrapper("DING")
def calc_hmac_base64(timestamp: str, secret: str):
secret_enc = secret.encode('utf-8')
string_to_sign = '{}\n{}'.format(timestamp, secret)
string_to_sign_enc = string_to_sign.encode('utf-8')
... |
1727919 | from datetime import datetime
from unittest.mock import patch
import pytest
from tatoebatools.version import Version
class TestVersion:
@patch("tatoebatools.version.json.load")
@patch("builtins.open")
def test_init_with_file(self, m_open, m_load):
m_load.return_value = {"foo": "2020-05-22 11:51:0... |
1727947 | import re
from unidecode import unidecode
class TextProcessor():
def __init__(self, v3=False):
if v3:
vocab = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;!?-\'\"()[] \t\n'
not_vocab = re.compile('[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+')
else:
... |
1727958 | from soundrts.world import World
from soundrts.worldclient import DummyClient
from soundrts.worldplayercomputer import Computer
from soundrts.worldresource import Deposit
from soundrts.worldroom import Square
class Deposit(Deposit): # type: ignore
def __init__(self, type_):
self.resource_type = type_
c... |
1727965 | from tkinter import ttk
from ozopython.colorLanguageTranslator import ColorLanguageTranslator
from .ozopython import *
from tkinter import *
def run(filename):
code = ozopython.compile(filename)
colorcode = ColorLanguageTranslator.translate(code)
def load(prog, prog_bar):
colormap = {
... |
1727973 | from dagster import OutputDefinition, composite_solid, pipeline, solid
from dagster.core.definitions.input import InputDefinition
@solid
def do_something():
pass
@solid
def one():
return 1
@solid(
input_defs=[InputDefinition("arg1", int)],
output_defs=[OutputDefinition(int)],
)
def do_something_el... |
1727980 | import taichi as ti
import taichi_glsl as ts
from mgpcg import MGPCGPoissonSolver
import time
import utils
from utils import *
@ti.data_oriented
class SurfaceTensionStrategy:
def __init__(self, simulator, surface_tension):
self.dim = simulator.dim
self.res = simulator.res
self.dt = simula... |
1728025 | from flask import Flask, request
import telebot
import proxy_bot
import config
app = Flask(__name__)
class WebhookProxyBot(proxy_bot.ProxyBot):
def __init__(self, token, master_id, server, baseurl, cert=None):
path = 'proxybot/' + token
super().__init__(token, master_id)
@server.route('... |
1728060 | from abc import ABC, abstractmethod
import time
from typing import List, Tuple, Iterator, Type
_sleep_for: float = 0.2
class TestCase(ABC):
"""Abstract test case interface."""
@abstractmethod
def run(self) -> None:
pass
class TestCaseOne(TestCase):
"""Concrete test case one."""
def __... |
1728094 | import os
import numpy as np
import json
import logging
from pipeline_model import TensorFlowServingModel
from pipeline_monitor import prometheus_monitor as monitor
from pipeline_logger import log
import tensorflow as tf
_logger = logging.getLogger('pipeline-logger')
_logger.setLevel(logging.INFO)
_logger_stream_hand... |
1728110 | import argparse
# Custom argparse Action.
# Allows setting one 'dest' from multiple arguments
class SetDestOnce(argparse.Action):
def __init__(self, *args, **kwargs):
super(SetDestOnce, self).__init__(*args, **kwargs)
def __call__(self, parser, namespace, values, option_string=None):
found = ... |
1728115 | from __future__ import absolute_import, division, unicode_literals
from html5lib.filters.whitespace import Filter
from html5lib.constants import spaceCharacters
spaceCharacters = "".join(spaceCharacters)
def runTest(input, expected):
output = list(Filter(input))
errorMsg = "\n".join(["\n\nInput:", str(input)... |
1728128 | from expression import *
from threading import Thread
def song():
changeDegree([3,5,9], [70,60,90])
changeDegree([7], [30])
os.system('aplay /home/pi/Robot-Blueberry/audio-files/national-song.wav')
takePosition()
def move():
time.sleep(1)
if __name__ == '__main__':
t1 = Thread(target=song)
... |
1728156 | import unittest
from modules.DatabaseModule.DBManager import DBManager
from opentera.db.models.TeraDevice import TeraDevice
import os
from opentera.config.ConfigManager import ConfigManager
from tests.opentera.db.models.BaseModelsTest import BaseModelsTest
class TeraDeviceTest(BaseModelsTest):
filename = os.path... |
1728159 | from flask import Blueprint, render_template, request, redirect, url_for, flash
import logging
import utils
log = logging.getLogger("Nurevam.site")
limit = 25 #original was 10.
blueprint = Blueprint('customcmd', __name__, template_folder='../templates/custom commands')
name = "custom commands"
description = "Allow... |
1728164 | from __future__ import print_function
import os
import numpy as np
import sys
import random
import glob
data_dir=sys.argv[1] #data directory contains all mol2 files
output_script_dir = 'out_scripts' #generated scripts to execute, for different docking modules
output_data_dir = 'out_data' #generated pdb files... |
1728178 | from keras.layers import Input, Dense, LSTM, Embedding, Dropout
from keras.layers.merge import add
from keras.models import Model
from keras.utils import plot_model
from nltk.translate.bleu_score import corpus_bleu
from DataUtils import generate_desc
# define the captioning model
def define_model(vocab_size, max_len... |
1728181 | import math
import torch
from torch import nn
from collections.abc import Iterable
from pixelflow.distributions import Distribution, StandardUniform
from pixelflow.transforms.subset import AutoregressiveSubsetTransform2d
from pixelflow.utils import sum_except_batch
class AutoregressiveSubsetFlow2d(Distribution):
... |
1728199 | import os
import glob
from .reader import reader as sql_reader
from mygrations.formats.mysql.definitions.database import database as database_definition
class database(database_definition):
def __init__(self, strings):
""" Constructor. Accepts a string or list of strings with different possible contents
... |
1728203 | from PySide2.QtWidgets import QApplication
import numpy as np
import visoptslider
if __name__ == "__main__":
app = QApplication()
# Define the target function and bound
num_dimensions = 3
def target_function(x):
# Rosenbrock function
value = 0.0
for i in range(x.shape[0] - 1):... |
1728228 | import jieba.analyse
import jieba
import pandas as pd
import re
from segmentation import filter
# tf_idf analysis
def tf_idf(texts):
jieba.load_userdict("./model/dict.txt")
jieba.analyse.set_idf_path("./model/idf.txt")
jieba.analyse.set_stop_words("./model/chinese_stopwords.txt")
jieba.enable_parallel(8... |
1728248 | import json
import numpy as np
import os
import tensorflow as tf
def read_tensor_from_byte_array(byteArray,
input_height=224,
input_width=224,
input_mean=127.5,
input_std=127.5):
input_name... |
1728250 | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'name': 'affirm',
'url': 'https://github.com/gooli/affirm',
'author': '<NAME>',
'author_email': '<EMAIL>',
'version': '0.9.2',
'py_modules': ['affirm'],
'description': 'Improved error m... |
1728267 | import asyncio
import logging
from time import time
from aiohttp import ClientSession, ClientTimeout, ClientResponse
class Requester:
"""
Wrapper around ClientSession to retry requests in case of timeouts and
log them
"""
def __init__(self, session: ClientSession,
timeout: int =... |
1728285 | import os
import subprocess
import time
from datetime import datetime
import math
import getpass
username = getpass.getuser()
file_names = []
file_content_locator = []
file_sizes = []
file_system_name = 'FIUNAMFS'
file_system_version = '0.7'
volume_tag = 'FIUNAMFS.img'
cluster_length = '512'
num_of_clusters_dir = '4'... |
1728312 | from __future__ import unicode_literals
from django.db import models
from django.db.models import ForeignKey, CASCADE
from nested_admin.tests.compat import python_2_unicode_compatible
@python_2_unicode_compatible
class Parent(models.Model):
name = models.CharField(max_length=128)
def __str__(self):
... |
1728341 | from floem import *
class DisplayPacket(Element):
def configure(self):
self.inp = Input(SizeT, "void *", "void *")
self.out = Output("void *", "void *")
def impl(self):
self.run_c(r'''
(size_t len, void *pkt, void *buf) = inp();
if (pkt != NULL) {
printf("Go... |
1728344 | import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
# Set random seed for reproducibility
np.random.seed(1000)
nb_iterations = 100000
x = 1.0
samples = []
def prior(x):
return 0.1 * np.exp(-0.1 * x)
def likelihood(x):
if x >= 0:
return 0.5 * np.exp(-np.abs(... |
1728347 | import asyncio
import pathlib
import semver
import tarfile
import tempfile
from tensorflow import keras
from tensorflow.keras import callbacks
from tensorcraft import asynclib
from tensorcraft import client
class _RemoteCallback(callbacks.Callback):
"""Callback with default session for communication with remote... |
1728351 | from django.template import Library
from dojango.util import json_encode
register = Library()
@register.filter
def json(input):
return json_encode(input)
|
1728353 | import urllib.parse
from flask import request, abort, render_template
from flask_login import current_user
from wikked.views import add_auth_data, add_navigation_data
from wikked.web import app, get_wiki
from wikked.webimpl import url_from_viewarg
from wikked.webimpl.decorators import requires_permission
from wikked.we... |
1728364 | from tool.runners.python import SubmissionPy
import heapq
class YouyounSubmission(SubmissionPy):
def run(self, s):
"""
:param s: input in string format
:return: solution flag
"""
seats = s.strip().replace('F', '0').replace('B', '1').replace('R', '1').replace('L', '0').split... |
1728373 | import re
from loguru import logger
def get_clean_source_packets(packets_log_file):
packets_log_content = packets_log_file.read()
source_packets = [bytes(l[2:-1], 'utf-8').decode('unicode-escape')
for l in packets_log_content.split('\n') if l]
# logger.debug(source_packets)
return source_... |
1728376 | import collections
import itertools
import numpy as np
__all__ = ['chow_liu']
def chow_liu(X, root=None):
"""Return a Chow-Liu tree.
A Chow-Liu tree takes three steps to build:
1. Compute the mutual information between each pair of variables. The values are organised in
a fully connected grap... |
1728409 | from __future__ import division
import numpy as np
import fidimag.extensions.common_clib as clib
# Change int he future to common clib:
import fidimag.extensions.clib as atom_clib
import sys
from .minimiser_base import MinimiserBase
class SteepestDescent(MinimiserBase):
"""
This class is the driver to minimi... |
1728421 | import numpy as np
import matplotlib.pyplot as plt
import time
import random
class filter():
def __init__(self, mean0, var0, meanSensor, varSensor, meanMove, varMove, positions, distances):
self.mean0 = mean0
self.var0 = var0
self.meanSensor = meanSensor
self.varSensor = varSensor
self.positions = positions... |
1728428 | from .bif_forgetter import bifForgetter
class sgmcmcForgetter(bifForgetter):
''' bifForgetter for SGMCMC
Args:
optimizer (torch.optim): sgmcmc optimizer that used to
sample (update) model parameter (i.e., params) for
estimating the expectation terms in I(target... |
1728486 | from .collate_fn import CommonDurationModelCollate, TTSCollate
from .taco2_data import TextMelLoader, TextMelCollate
|
1728488 | import numpy as np
import cv2
class CoordGenerator(object):
def __init__(self, intrin, img_w, img_h):
super(CoordGenerator, self).__init__()
self.intrinsics = intrin
self.image_width = img_w
self.image_height = img_h
def pixel2local(self, depth): # depth: float32,... |
1728532 | from enum import Enum
from collections import namedtuple
import tvm
import tvm.te as te
import tvm.tg as tg
import tvm.tir as tir
import numpy as np
def pprint_dict(d):
import json
print(json.dumps(d, indent=2, sort_keys=False))
def get_vector_add(n):
"""TVM expression for vector add"""
A = te.placeholder... |
1728540 | class Solution(object):
def isAlienSorted(self, words, order):
"""
:type words: List[str]
:type order: str
:rtype: bool
"""
sequences = []
left = 0
while left < len(words) - 1:
firstWord = words[left]
secondWord = words[left + 1... |
1728545 | from chemex import helper as ch
_SCHEMA_METHODS_PARAM = {
"type": "object",
"additionalProperties": {
"type": "object",
"properties": {
"include": {
"oneOf": [
{
"type": "array",
"items": {"anyOf": [... |
1728548 | import numpy as np
import gym
from dezero import Model
from dezero import optimizers
import dezero.functions as F
import dezero.layers as L
from common.utils import plot_total_reward
class PolicyNet(Model):
def __init__(self, action_size=2):
super().__init__()
self.l1 = L.Linear(256)
self.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.