id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
62254 | import tornado.gen
from .base import BaseApiHandler
from ..tasks import cel
class TaskHandler(BaseApiHandler):
@tornado.gen.coroutine
def get(self, task_id):
data = yield self.get_task_meta(task_id)
result_data = {'result': data['result'], 'status': data['status']}
self.finish(result... |
62264 | import mysql.connector
conn = mysql.connector.connect(
host="192.168.99.102",
user="root",
passwd="<PASSWORD>",
database="user_db",
port="3308"
)
def find_all():
query = "SELECT * FROM users"
try:
cursor = conn.cursor()
rows = cursor.execute(query)
cursor.close()
ret... |
62270 | import fileinput
from itertools import count
banks = [int(n) for n in fileinput.input()[0].split()]
seen = {}
for i in count(start=1):
m = max(banks)
idx = banks.index(m)
banks[idx] = 0
for j in range(1, m + 1):
banks[(idx + j) % len(banks)] += 1
t = tuple(banks)
if t in seen:
... |
62335 | import sqlite3
import json
import logging
from ryu.app.wsgi import ControllerBase, WSGIApplication, route
from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller.handler import MAIN_DISPATCHER, CONFIG_DISPATCHER, DEAD_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.of... |
62351 | import numpy
from chainer import functions
from chainer import testing
@testing.parameterize(*(testing.product({
'batchsize': [1, 5],
'size': [10, 20],
'dtype': [numpy.float32],
'eps': [1e-5, 1e-1],
})))
@testing.inject_backend_tests(
None,
# CPU tests
[
{},
]
# GPU tests
... |
62419 | from __future__ import with_statement
# ==============================================================================
# GGisy (python v2.7)
#
# Author: <NAME> (<EMAIL>)
# Bugs and errors: https://github.com/Sanrrone/GGisy/issues
#
# Please type "python GGisy.py -h" for usage help
#
# ==========================... |
62461 | from dateutil import tz
from django.http.response import JsonResponse
from 臺灣言語平臺.項目模型 import 平臺項目表
from 臺灣言語資料庫.資料模型 import 來源表
from 臺灣言語平臺.介面.Json失敗回應 import Json失敗回應
from django.core.exceptions import ObjectDoesNotExist
_臺北時間 = tz.gettz('Asia/Taipei')
_時間輸出樣式 = '%Y-%m-%d %H:%M:%S'
def 轉做臺北時間字串(時間... |
62503 | from dataclasses import dataclass
from typing import Dict
from typing import Optional
@dataclass(frozen=True)
class CurrentDestinationStatus:
number_of_pending_messages: Optional[int]
number_of_consumers: int
messages_enqueued: int
messages_dequeued: int
@dataclass(frozen=True)
class ConsumerStatus:... |
62519 | import sklearn.datasets
import sklearn.model_selection
import sklearn.linear_model
import numpy
import compare_auc_delong_xu
import unittest
import scipy.stats
class TestIris(unittest.TestCase):
@classmethod
def setUpClass(cls):
data = sklearn.datasets.load_iris()
x_train, x_test, y_train, ... |
62551 | import torch
import cv2 as cv
import numpy as np
from sklearn.neighbors import NearestNeighbors
from .model_utils import spread_feature
def optimize_image_mask(image_mask, sp_image, nK=4, th=1e-2):
mask_pts = image_mask.reshape(-1)
xyz_pts = sp_image.reshape(-1, 3)
xyz_pts = xyz_pts[mask_pts > 0.5, :]
... |
62561 | from . import builder, config, exceptions, generator, logging
import click
import os
import sys
__all__ = []
LOG = logging.getLogger(__name__)
@click.group()
@click.option('-v', '--verbose', is_flag=True)
def promenade(*, verbose):
if _debug():
verbose = True
logging.setup(verbose=verbose)
@promen... |
62579 | OntCversion = '2.0.0'
from ontology.interop.Ontology.Contract import Migrate
# from ontology.interop.Ontology.Contract import Destroy
from ontology.interop.System.Runtime import Notify
from ontology.interop.System.Storage import Put, GetContext, Get
KEY = "KEY"
NAME = "SecondName"
def Main(operation, args):
# if ... |
62607 | import torch
import ignite.distributed as idist
from tests.ignite.distributed.utils import (
_sanity_check,
_test_distrib__get_max_length,
_test_distrib_all_gather,
_test_distrib_all_reduce,
_test_distrib_barrier,
_test_distrib_broadcast,
_test_sync,
)
def test_no_distrib(capsys):
as... |
62624 | from __future__ import print_function
import argparse
from collections import OrderedDict
import json
import os
import logging
from keras.callbacks import EarlyStopping
from sklearn.preprocessing import normalize
from sklearn.metrics import roc_curve, auc, roc_auc_score, precision_score, recall_score, f1_score, accurac... |
62630 | import os
from os import path
from eiffel_loop.scons.c_library import LIBRARY_INFO
from eiffel_loop.package import TAR_GZ_SOFTWARE_PACKAGE
from eiffel_loop.package import SOFTWARE_PATCH
info = LIBRARY_INFO ('source/id3.getlib')
print 'is_list', isinstance (info.configure [0], list)
print 'url', info.url
print inf... |
62642 | import logging
import struct
from macholib.MachO import MachO
from macholib.mach_o import *
from .base_executable import *
from .section import *
INJECTION_SEGMENT_NAME = 'INJECT'
INJECTION_SECTION_NAME = 'inject'
class MachOExecutable(BaseExecutable):
def __init__(self, file_path):
super(MachOExecutabl... |
62658 | from django.views.generic import ListView
from ..professors.models import Professor
class SearchView(ListView):
queryset = Professor.objects.all().order_by("-first_name", "last_name")
template_name = "search.html"
def get_context_data(self):
context = super(SearchView, self).get_context_data()
... |
62715 | import unittest
from kafka_influxdb.encoder import heapster_json_encoder
class TestHeapsterJsonEncoder(unittest.TestCase):
def setUp(self):
self.encoder = heapster_json_encoder.Encoder()
def testEncoder(self):
msg = b'{ "MetricsName":"memory/major_page_faults","MetricsValue":{"value":56}, "... |
62743 | from enum import Enum
class MenuChoice(Enum):
"""
Menu choices are always a lower or upper case letter
"""
NONE = -1
LOWER_A = 0
LOWER_B = 1
LOWER_C = 2
LOWER_D = 3
LOWER_E = 4
LOWER_F = 5
LOWER_G = 6
LOWER_H = 7
LOWER_I = 8
LOWER_J = 9
LOWER_K = 10
LOWE... |
62753 | import datetime
from bitmovin import Bitmovin, Encoding, S3Output, H264CodecConfiguration, AACCodecConfiguration, H264Profile, \
StreamInput, SelectionMode, Stream, EncodingOutput, ACLEntry, ACLPermission, MuxingStream, \
S3Input, FairPlayDRM, TSMuxing, HlsManifest, AudioMedia, VariantStream
from bitmovin.error... |
62776 | import click
from marinetrafficapi import constants
from marinetrafficapi.bind import bind_request
from marinetrafficapi.vessels_positions.\
PS01_vessel_historical_track.models import VesselHistoricalPosition
from marinetrafficapi.vessels_positions.\
PS01_vessel_historical_track.query_params import PS01QueryP... |
62791 | from django.views.generic import TemplateView
if settings.DEBUG:
# enable local preview of error pages
urlpatterns += patterns('',
(r'^403/$', TemplateView.as_view(template_name="403.html")),
(r'^404/$', TemplateView.as_view(template_name="404.html")),
(r'^500/$', TemplateView.as_view... |
62823 | import pickle
import pytest
import numpy as np
from astropy import units as u
from astropy import modeling
from specutils.utils import QuantityModel
from ..utils.wcs_utils import refraction_index, vac_to_air, air_to_vac
wavelengths = [300, 500, 1000] * u.nm
data_index_refraction = {
'Griesen2006': np.array([3.073... |
62825 | import logging
import os
from datetime import timedelta
# layers
import sys
sys.path.append('/opt')
import cv2
from common.config import LOG_LEVEL, FRAME_RESIZE_WIDTH, FRAME_RESIZE_HEIGHT, STORE_FRAMES, \
DDB_FRAME_TABLE, UTC_TIME_FMT
from common.utils import upload_to_s3, put_item_ddb
logger = logging.getLogger... |
62855 | import pytest
from pymlconf import Root
def test_delattribute():
root = Root('''
app:
name: MyApp
''')
assert hasattr(root.app, 'name')
del root.app.name
assert not hasattr(root.app, 'name')
with pytest.raises(AttributeError):
del root.app.invalidattribute
|
62879 | from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from backend.views import app_urls
from server import settings
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'server.views.home', name='home'),
# url(... |
62916 | import tensorflow as tf
import experiment
class NoTraining(experiment.Training):
"""This is a replacement component that skips the training process"""
def __init__(self, config, config_global, logger):
super(NoTraining, self).__init__(config, config_global, logger)
def start(self, model, data, ... |
62969 | import django.dispatch
file_is_ready = django.dispatch.Signal()
file_upload_failed = django.dispatch.Signal()
file_joining_failed = django.dispatch.Signal() |
62979 | from django.conf import settings
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.files.storage import FileSystemStorage
from django.http import HttpResponseRedirect
from django.urls import reverse_lazy
from django.views.generic import TemplateView, UpdateVi... |
62985 | import aiohttp
import asyncio
import os
import sys
import time
import random
import contextlib
seaweedfs_url = 'http://127.0.0.1:9081'
def random_content():
return os.urandom(random.randint(1, 10) * 1024)
def random_fid(volumes):
volume_id = random.choice(volumes)
file_key = random.randint(0, 1 << 24)... |
63039 | import pytest
from metagraph.tests.util import default_plugin_resolver
from . import RoundTripper
from metagraph.plugins.python.types import PythonNodeSetType
from metagraph.plugins.numpy.types import NumpyNodeSet, NumpyNodeMap
import numpy as np
def test_nodeset_roundtrip(default_plugin_resolver):
rt = RoundTrip... |
63068 | from enum import Enum
from typing import Dict, Any
from jwt.algorithms import get_default_algorithms
from cryptography.hazmat._types import (
_PRIVATE_KEY_TYPES,
_PUBLIC_KEY_TYPES,
)
# custom types
PrivateKey = _PRIVATE_KEY_TYPES
PublicKey = _PUBLIC_KEY_TYPES
JWTClaims = Dict[str, Any]
class EncryptionKeyFo... |
63073 | import board
import busio
import digitalio
import time
import adafruit_requests as requests
from adafruit_wiznet5k.adafruit_wiznet5k import *
import adafruit_wiznet5k.adafruit_wiznet5k_socket as socket
from adafruit_wiznet5k.adafruit_wiznet5k_ntp import NTP
import adafruit_wiznet5k.adafruit_wiznet5k_dns as dns
... |
63087 | import torch
from torch import nn, distributed as dist
from torch.nn import functional as F
class LabelSmoothingLoss(nn.Module):
def __init__(self, ignore_index, eps=0.1, reduction="mean"):
super().__init__()
self.ignore_index = ignore_index
self.eps = eps
self.reduction = reducti... |
63088 | import random
import torch
import time
import os
import numpy as np
from torch.utils.data import Dataset
from functools import partial
from .utils import dataset_to_dataloader, max_io_workers
from pytorch_transformers.tokenization_bert import BertTokenizer
# the following will be shared on other datasets too if not, ... |
63135 | from __future__ import with_statement # this is to work with python2.5
import terapyps
from pyps import workspace
workspace.delete("convol3x3")
with terapyps.workspace("convol3x3.c", name="convol3x3", deleteOnClose=False,recoverInclude=False) as w:
for f in w.fun:
f.terapix_code_generation(debug=True)
# ... |
63144 | from Treap import Treap
from math import log
class IKS:
def __init__(self):
self.treap = None
self.n = [0, 0]
@staticmethod
def KSThresholdForPValue(pvalue, N):
'''Threshold for KS Test given a p-value
Args:
pval (float): p-value.
N (int): the size of the samples.
... |
63156 | import sys
import time
from sdk import *
addr_list = addresses()
_pid = "id_20020"
_proposer = addr_list[0]
_initial_funding = (int("2") * 10 ** 9)
_each_funding = (int("3") * 10 ** 9)
_funding_goal_general = (int("10") * 10 ** 9)
_prop = Proposal(_pid, "general", "proposal for fund", "proposal headline", _proposer,... |
63194 | from torch import nn
def init_weight(weight, init, init_range, init_std):
if init == "uniform":
nn.init.uniform_(weight, -init_range, init_range)
elif init == "normal":
nn.init.normal_(weight, 0.0, init_std)
def init_bias(bias):
nn.init.constant_(bias, 0.0)
def weights_init(m, init, in... |
63229 | from .decorators import endpoint
from ..definitions.types import InstrumentName
from ..endpoints.annotations import LongClientExtensions
from ..endpoints.annotations import LongUnits
from ..endpoints.annotations import ShortClientExtensions
from ..endpoints.annotations import ShortUnits
from ..endpoints.position import... |
63250 | from ...utilities import db, moocdb_utils
from common import *
def GetForums(vars):
output_items = []
resource_type_id = moocdb_utils.GetResourceTypeMap(vars)['forum']
# course_doc = vars['resource_list'][0]
# discussion_topics = course_doc['metadata']['discussion_topics']
# src_forums = [{'id... |
63321 | print '... Importing simuvex/engines/vex/expressions/get.py ...'
from angr.engines.vex.expressions.get import *
|
63335 | import csv
from site_crawler.cleaner.cleaner import Cleaner
class Dataset_Builder:
def __init__(self):
self.cleaner = Cleaner()
self.create_csv_headers()
def create_csv_headers(self):
csv_files = [
'negative_sentiment',
'positive_sentiment',
'dataset... |
63356 | import os
import pytest
import yaml
from gcasc.utils.yaml_include import YamlIncluderConstructor
from .helpers import read_file, read_yaml
YamlIncluderConstructor.add_to_loader_class(
loader_class=yaml.FullLoader,
base_dir=os.path.dirname(os.path.realpath(__file__)) + "/data",
)
@pytest.fixture()
def file... |
63441 | import tensorflow as tf
from dltk.core.activations import leaky_relu
import numpy as np
def test_leaky_relu():
test_alpha = tf.constant(0.1)
test_inp_1 = tf.constant(1.)
test_inp_2 = tf.constant(-1.)
test_relu_1 = leaky_relu(test_inp_1, test_alpha)
test_relu_2 = leaky_relu(test_inp_2, test_alpha)... |
63453 | def test_get_symbols(xtb_client):
symbols = list(xtb_client.get_all_symbols())
assert len(symbols) > 0
def test_get_balance(xtb_client):
balance = xtb_client.get_balance()
assert balance.get('balance') is not None
def test_ping(xtb_client):
response = xtb_client.ping()
assert response
|
63460 | import argparse
import penman
from amrlib.evaluate.smatch_enhanced import compute_smatch
from ensemble.utils import align, get_entries
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Graph Ensemble (Graphene)')
parser.add_argument(
'-g', '--gold', default='./datasets/spring_g... |
63484 | from rest_framework import serializers
from openbook_categories.models import Category
class GetCategoriesCategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = (
'id',
'name',
'title',
'description',
'avat... |
63490 | def iob_ranges(words, tags):
"""
IOB -> Ranges
"""
assert len(words) == len(tags)
ranges = []
def check_if_closing_range():
if i == len(tags) - 1 or tags[i + 1].split('_')[0] == 'O':
ranges.append({
'entity': ''.join(words[begin: i + 1]),
'typ... |
63507 | import bisect
import copy
import hashlib
import itertools
import json
import operator
import time
from collections import ChainMap
import pmdefaults as PM
from pmdefaults import *
from policy import NEATProperty, PropertyArray, PropertyMultiArray, ImmutablePropertyError, term_separator
CIB_EXPIRED = 2
class CIBEntr... |
63536 | from .init import *
from .opt import *
from .checkpoint import *
from .framework import *
from .logger import *
from .metrics import *
from .geometry import *
try:
from .visualization import *
except ImportError:
__KAOLIN_LOADED__ = False
else:
__KAOLIN_LOADED__ = True |
63539 | import os
import cv2
import numpy as np
import torch
import pickle
import argparse
from configs import paths
from utils.cam_utils import perspective_project_torch
from models.smpl_official import SMPL
def rotate_2d(pt_2d, rot_rad):
x = pt_2d[0]
y = pt_2d[1]
sn, cs = np.sin(rot_rad), np.cos(rot_rad)
... |
63570 | from unittest.mock import patch
from django.test import TestCase
import vcr
from data_refinery_common.models import (
Contribution,
Experiment,
ExperimentSampleAssociation,
OntologyTerm,
Sample,
SampleAttribute,
)
from data_refinery_foreman.foreman.management.commands.import_external_sample_a... |
63615 | import torch
import numpy as np
import argparse
import os
from utils import Logger, LogFiles, ValidationAccuracies, cross_entropy_loss, compute_accuracy, MetaLearningState,\
shuffle
from model import FewShotClassifier
from dataset import get_dataset_reader
from tf_dataset_reader import TfDatasetReader
from image_fo... |
63633 | import os
import subprocess
import sys
args = sys.argv[:]
print('hello from %s' % args[0])
print('args: ' + ' '.join(args))
print('current directory: ' + os.getcwd())
p = subprocess.Popen('ls -al', shell=True, bufsize=1, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while True:
line = p.s... |
63660 | from io import StringIO
from django.core.management import call_command
from django.core.management.base import CommandError
from django.test import TestCase
from flags.state import flag_enabled
class EnableFlagTestCase(TestCase):
def test_enable_flag(self):
out = StringIO()
self.assertFalse(fla... |
63720 | from program_synthesis.karel.dataset import executor
from program_synthesis.karel.dataset import parser_for_synthesis
branch_types = {'if', 'ifElse', 'while'}
stmt_types = {'move', 'turnLeft', 'turnRight', 'putMarker', 'pickMarker'}
class CoverageMeasurer(object):
def __init__(self, code):
self.parser = p... |
63742 | import os
import re
import sys
import cffi
from ._compat import PY2
_directive_re = re.compile(r'^\s*#.*?$(?m)')
def make_ffi(module_path, crate_path, cached_header_filename=None):
"""Creates a FFI instance for the given configuration."""
if cached_header_filename is not None and \
os.path.isfile(ca... |
63754 | import luhn
def test_checksum_len1():
assert luhn.checksum('7') == 7
def test_checksum_len2():
assert luhn.checksum('13') == 5
def test_checksum_len3():
assert luhn.checksum('383') == 3
def test_checksum_len4():
assert luhn.checksum('2827') == 3
def test_checksum_len13():
assert luhn.checksum('... |
63759 | from setuptools import setup
def _md(filename):
'''
Load md file and sanitize it for PyPI.
Remove unsupported github tags:
- code-block directive
- all badges
'''
content = open(filename).read()
return content
long_description = '\n'.join((
_md('README.md'),
_md('CHANGELOG.... |
63784 | import re
from PIL import Image, ImageOps
from io import BytesIO
from django.contrib.auth.models import User
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import HttpResponseForbidden
from django.shortcuts import get_object_or_404
from django.core.files.uploadedfile import Si... |
63818 | import sys
# add your project directory to the sys.path
project_home = u'.'
if project_home not in sys.path:
sys.path = [project_home] + sys.path
from DataComets import app as application |
63822 | from ..factory import Type
class updateChatPinnedMessage(Type):
chat_id = None # type: "int53"
pinned_message_id = None # type: "int53"
|
63881 | from .base import BaseModel
from .head import MLPHeadModel
from .pretraining import (
DenoisingPretrainModel,
SAINTPretrainModel,
TabTransformerPretrainModel,
VIMEPretrainModel,
)
|
63897 | import fabric.api
from provy.core import Role
from provy.more.debian.package.aptitude import AptitudeRole
'''
Roles in this namespace are meant to provide `SELinux <http://selinuxproject.org/>`_ management utilities for Debian distributions.
'''
class SELinuxRole(Role):
'''
This role provides `SELinux <http... |
63902 | import os
from unittest import TestCase
from keras_gpt_2 import get_bpe_from_files
class TestBPE(TestCase):
def test_encode_and_decode(self):
current_path = os.path.dirname(os.path.abspath(__file__))
toy_checkpoint_path = os.path.join(current_path, 'toy_checkpoint')
encoder_path = os.path... |
63915 | from .ingredient import Ingredient
from .recipe import Recipe
from .source import Source
__all__ = ["Ingredient", "Recipe", "Source"]
|
63918 | import os
import sys
import torch
import models
import logging
import argparse
import datetime
from amp import AMP
from data_utils import load_data
class Instructor:
def __init__(self, args):
self.args = args
self.logger = logging.getLogger()
self.logger.setLevel(logging.INFO)
sel... |
63941 | import math
import os
import time
import numpy as np
import pybullet as p
import pybullet_utils.bullet_client as bc
from gripper_module import load_gripper
from misc.urdf_editor import UrdfEditor
import utils
from fusion import TSDFVolume
class Gripper(object):
"""
A moving mount and a gripper.
the mou... |
63975 | from time import clock
import sys
sys.path.append('../../../')
print (sys.path)
from tspdb.src.data import generateHarmonics as gH
from tspdb.src.data import generateTrend as gT
import tspdb.src.data.generateARMA as gA
import numpy as np
from tspdb.src.hdf_util import write_data
import matplotlib.pyplot as pl... |
64018 | import re
import bs4
from LimeSoup.lime_soup import Soup, RuleIngredient
from LimeSoup.parser.elsevier_xml import (
resolve_elsevier_entities, extract_ce_text, find_non_empty_children,
node_named, extract_ce_para, extract_ce_section, extract_ce_abstract,
extract_ce_title, remove_consecutive_whitespaces)
... |
64025 | import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
import logging
import configparser
import time
import json
import concurrent.futures
logger = logging.getLogger(__name__)
config = configparser.ConfigParser()
config.read('config.ini')
crxcavator_api = c... |
64031 | from .build_arima import BuildArima
from .build_sarimax import BuildSarimax
from .build_autoarimax import BuildAutoSarimax
from .build_var import BuildVAR
|
64066 | import sqlalchemy.orm
from .authors import Author
from .base import Base
from .books import Book
def setup(engine):
Base.metadata.create_all(engine)
session = sqlalchemy.orm.Session(engine)
author_wodehouse = Author(name="<NAME>")
author_bernières = Author(name="<NAME>")
session.add_all((author... |
64076 | import datetime
import unittest
from flask import Blueprint, request, jsonify
from freezegun import freeze_time
from mock import Mock, patch
import jwt
from requests.exceptions import HTTPError
from shared_helpers import services
from testing import TrottoTestCase, LIVE_APP_HOST
class TestFunctions(unittest.TestCas... |
64088 | from tableschema import Table
# Data from WEB, schema from MEMORY
SOURCE = 'https://raw.githubusercontent.com/frictionlessdata/tableschema-py/master/data/data_infer.csv'
SCHEMA = {'fields': [{'name': 'id', 'type': 'integer'}, {'name': 'age', 'type': 'integer'}, {'name': 'name', 'type': 'string'}] }
# If schema is not... |
64129 | import numpy as np
import sys,os
##################################### INPUT ############################################
realizations = 2000
########################################################################################
root1 = '/simons/scratch/fvillaescusa/pdf_information/Snapshots/latin_hypercube'
root2 ... |
64160 | import re
import lib.core.common
__product__ = "3dcart"
__description__ = (
"The 3dcart Shopping Cart Software is a complete e-commerce solution for anyone."
)
def search(html, **kwargs):
html = str(html)
headers = kwargs.get("headers", None)
plugin_detection_schema = (
re.compile(r"3dcart.... |
64179 | expected_output = {
"tag": {
"test": {
"system_id": {
"R2_xr": {
"type": {
"L1L2": {
"area_address": ["49.0001"],
"circuit_id": "R1_xe.01",
"format": "P... |
64185 | from wasmer import engine, Store, Module, Instance
from wasmer_compiler_cranelift import Compiler as Cranelift
from wasmer_compiler_llvm import Compiler as LLVM
from wasmer_compiler_singlepass import Compiler as Singlepass
TEST_BYTES = open('benchmarks/nbody.wasm', 'rb').read()
def test_benchmark_headless_time_nbody_... |
64240 | import torch
import torch.nn as nn
import physics_aware_training.digital_twin_utils
class SplitInputParameterNet(nn.Module):
def __init__(self,
input_dim,
nparams,
output_dim,
parameterNunits = [100,100,100],
internalNunits =... |
64256 | from random import randint
from cowait.worker.worker_node import WorkerNode
from .html_logger import HTMLLogger
class NotebookNode(WorkerNode):
"""
The Notebook Node is a variant of the standard worker node meant to run in a notebook.
It simulates a running task by connecting upstream and forwarding event... |
64326 | import click
from .schemaless import SchemalessPrompter
from agent import source
class KafkaPrompter(SchemalessPrompter):
timestamp_types = ['datetime', 'string', 'unix', 'unix_ms']
target_types = ['counter', 'gauge', 'running_counter']
def prompt_config(self):
self.data_preview()
self.se... |
64329 | import heapq
import itertools as itt
import operator as op
from collections import OrderedDict, UserDict, defaultdict
from .array import Array
from .optional import Nothing, Some
from .repr import short_repr
from .row import KeyValue, Row
from .stream import Stream
def identity(_): return _
class Map(OrderedDict):... |
64406 | from django.test import TestCase, Client
from django.contrib.auth.models import User
from .models import Feed
class FeedViewsTest(TestCase):
def setUp(self):
self.client = Client()
user = User.objects.create_user(
username='test_user',
email='<EMAIL>',
password... |
64444 | import unittest
from pyparsing import ParseException
from media_management_scripts.support.search_parser import parse_and_execute, parse
class ParseTestCase():
def parse(self, query, expected, context={}):
self.assertEqual(parse_and_execute(query, context), expected)
class SimpleTest(unittest.TestCase,... |
64450 | import random
class Fluctuation:
def __init__(self, percentage, baseline):
self.percentage = percentage
self.baseline = baseline
def __call__(self, value):
return self.apply(value)
def apply(self, value):
return value + self.generate(self.baseline)
def generate(self... |
64481 | def fib(n):
"return nth term of Fibonacci sequence"
a, b = 0, 1
i = 0
while i<n:
a, b = b, a+b
i += 1
return b
def linear_recurrence(n, (a,b)=(2,0), (u0, u1)=(1,1)):
"""return nth term of the sequence defined by the
linear recurrence
u(n+2) = a*u(n+1) + b*u(n)"""
... |
64482 | import os
import sys
import json
import commands
import re
testrange = [300, 500, 800, 1100, 1400]
WIDTH, HEIGHT = 800, 480
FPS = 25
def eventloop(test_file):
os.system('mkdir img')
#os.system('mkdir img/%s' % (test_file))
os.system('mkdir tmp_%s' % (test_file))
os.system('mkdir tmp2_%s' % (test_file... |
64492 | import numpy as np
from public_tool.form_index import form_index
from XGB_HMM.form_B_matrix_by_XGB import form_B_matrix_by_XGB
from XGB_HMM.predict import self_pred
def pred_proba_XGB(A, model, pi, O, allow_flag, lengths):
# 对dataset形成pred_proba,注意这里的dataset是solve_on_raw_data后的结果,即附带allow_flag的数据
# ou... |
64506 | from __future__ import unicode_literals
from django.db import models # noqa
# Create your models here.
|
64507 | import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
import cPickle
from keras.layers import Input, Dense, Lambda, Flatten, Reshape, Layer
from keras.layers import Conv2D, Conv2DTranspose
from keras.models import Model
from keras import backend as K
from keras import metrics
from keras impor... |
64545 | from leavedemo.leave.models import Account
from datetime import timedelta
def update_hr(workitem):
''' automated and simplistic version of hrform.
'''
instance = workitem.instance
leaverequest = workitem.instance.content_object
if leaverequest.reason_denial:
raise Excep... |
64726 | from typing import List
class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
res = list()
nums.sort()
stdList = range(1, len(nums) + 1) # len(nums) = n
repeatedNum = sum(nums) - sum(set(nums))
res.append(repeatedNum)
missingNum = (set(stdList... |
64750 | from concurrent import futures
import logging
import os
import grpc
from PIL import Image, ImageOps
import helloworld_pb2
import helloworld_pb2_grpc
from minio import Minio
minioEnvKey = "MINIO_ADDRESS"
image_name = 'img2.jpeg'
image2_name = 'img3.jpeg'
image_path = '/pulled_' + image_name
image_path2 = '/pulled_' ... |
64772 | import csv
from flask_wtf import FlaskForm as Form
from flask_wtf.file import FileField, FileRequired, FileAllowed
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
from wtforms import ValidationError
# noinspection PyMethodMayBeStatic
class HostForm(Form):
fqdn = StringFiel... |
64839 | import os
import os
test_list = [line. rstrip('\n') for line in open('./food-101/meta/test.txt')]
os.mkdir('./food-101/test')
source_base = './food-101/images/'
target_base = './food-101/test/'
for item in test_list:
c = item.split('/')[0]
if not os.path.exists(os.path.join(base, c)):
os.mkdir(os.path... |
64844 | from typing import Dict
class APIException(Exception):
"""
example:
{
"status": bool,
"system": {
"code": int,
"message": str
},
"data": None,
}
"""
def __init__(self, status: bool, system: Dict[str, int], source: None):
self.stat... |
64870 | import unittest
import numpy as np
from revpy import fare_transformation
class FareTransformationTest(unittest.TestCase):
def setUp(self):
# example data from page 13 of research paper
# "Optimization of Mixed Fare Structures: Theory and Applications"
# by <NAME> al. (2010)
self... |
64918 | from typing import List
import torch
from torch.utils.data.dataset import Dataset
def noise(outlier_classes: List[int], generated_noise: torch.Tensor, norm: torch.Tensor,
nom_class: int, train_set: Dataset, gt: bool = False) -> Dataset:
"""
Creates a dataset based on the nominal classes of a given ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.