id
stringlengths
3
8
content
stringlengths
100
981k
3280486
import pytest from autofit.database import query as q @pytest.fixture( name="less_than" ) def make_less_than(): return q.V( "<", 1 ) @pytest.fixture( name="greater_than" ) def make_greater_than(): return q.V( ">", 0 ) @pytest.fixture( name="simple_and" ) def make_simpl...
3280502
from GenericRequest import GenericRequest from kol.manager import PatternManager class LoadClanAdminRequest(GenericRequest): "Load's the clan administration page." def __init__(self, session): super(LoadClanAdminRequest, self).__init__(session) self.url = session.serverURL + "clan_admin.php" ...
3280549
import importlib def import_config(config_name, prefix='configs'): m = importlib.import_module(name='{}.{}'.format(prefix, config_name)) return m.config
3280584
import sys import signal import crontab_jobs default_app_config = 'dataloaderinterface.apps.DataloaderinterfaceConfig' def on_dataloaderinterface_shutdown(*args): from django.conf import settings crontab_jobs.stop_jobs() sys.exit(0) signal.signal(signal.SIGINT, on_dataloaderinterface_shutdown) signal.s...
3280604
import torch.nn as nn import torch.nn.functional as F class MLPModel(nn.Module): def __init__(self, input_shape, output_dim, n_layers=2, n_channels=64, bn=False): super().__init__() layers = [] bn_layers = [] cur_hidden_ch = input_shape[0] for i in range(n_layers): ...
3280612
import numpy as np class VaspData(np.lib.mixins.NDArrayOperatorsMixin): """Wraps the data produced by the VASP calculation. Instead of exposing the underlying file structure directly, the data is wrapped in this container. This allows changing the way the data is internally represented without affect...
3280627
RuleIntro = { "enc_type_valid_1": "Verify the consistency of data field and type 'quantitative'.", "enc_type_valid_2": "Verify the consistency of data field and type 'temporal'.", "bin_q_o": "Only use bin on quantitative or ordinal data. ", "log_q": "Only use log scale with quantitative data.", "zer...
3280638
import unittest from beancount_bot import transaction from beancount_bot.dispatcher import Dispatcher class TestDispatcher(unittest.TestCase): def test_process(self): dispatcher = Dispatcher() tx = dispatcher.process('') ret = transaction.stringfy(tx) self.assertEqual(ret, ...
3280650
from cloud_inquisitor.constants import ROLE_USER, HTTP from cloud_inquisitor.plugins import BaseView from cloud_inquisitor.plugins.types.resources import EBSVolume from cloud_inquisitor.utils import MenuItem from cloud_inquisitor.wrappers import check_auth, rollback class EBSVolumeList(BaseView): URLS = ['/api/v1...
3280678
import torch from torch import nn from torch import distributed from ops import * import copy class SuperMobileConvBlock(nn.Module): def __init__(self, in_channels, out_channels, expand_ratio_list, kernel_size_list, stride): super().__init__() hidden_channels_list = [in_channels * expand_ratio ...
3280693
from datetime import datetime, date from marqeta.response_models.address_request_model import AddressRequestModel from marqeta.response_models import datetime_object import json import re class BusinessIncorporationRequestModel(object): def __init__(self, json_response): self.json_response = json_response...
3280750
from streamlink.plugins.googledrive import GoogleDocs from tests.plugins import PluginCanHandleUrl class TestPluginCanHandleUrlGoogleDocs(PluginCanHandleUrl): __plugin__ = GoogleDocs should_match = [ 'https://drive.google.com/file/d/123123/preview?start=1', ]
3280755
from flask import Flask, jsonify, render_template, request app = Flask(__name__) # ---------------------------------------------------------------------------------------------------------------------- @app.route('/') def index(): return render_template('base.html') # --------------------------------------------...
3280771
import os import os.path as osp import numpy as np import cv2 import shutil import random # 为保证每次运行该脚本时划分的样本一致,故固定随机种子 random.seed(0) import paddlex as pdx # 定义训练集切分时的滑动窗口大小和步长,格式为(W, H) train_tile_size = (1024, 1024) train_stride = (512, 512) # 定义验证集切分时的滑动窗口大小和步长,格式(W, H) val_tile_size = (769, 769) val_stride = (769...
3280794
import numpy as np def hermite_matrices(x_given, x_eval): """ Return matrices for a Hermite polynomial at the given nodes. This includes interpolation matrices (A_i and B_i) and differentiation matrices (A_d and B_d). Parameters ---------- x_given : ndarray[:] Vector of given nodes i...
3280795
import pandas as pd import sys, os from collections import OrderedDict from viola.core.bedpe import Bedpe from viola.core.vcf import Vcf from typing import ( List, Optional, ) class MultiBedpe(Bedpe): """ A database-like object that contains information of multiple BEDPE files. In this class, main ...
3280883
from seamless.highlevel import Context, Cell ctx = Context() ctx.add = lambda a,b: a + b ctx.a = 10 ctx.b = 20 ctx.add.a = ctx.a ctx.add.b = ctx.b ctx.result = ctx.add ctx.compute() print(ctx.result.value) print() subctx = ctx ctx = Context() ctx.sub1 = subctx ctx.compute() print(ctx.sub1.result.value) ctx.sub2 = sub...
3280907
config = { 'embedding_hidden_size': 512, 'initializer_range': 0.02, 'embedding_dropout_prob': 0.1, 'n_speakers': 1, 'n_conv_encoder': 5, 'encoder_conv_filters': 512, 'encoder_conv_kernel_sizes': 5, 'encoder_conv_activation': 'relu', 'encoder_conv_dropout_rate': 0.5, 'encoder_lstm...
3280929
import argparse import logging from pathlib import Path import numpy as np from tqdm import tqdm from collections import defaultdict from .utils.read_write_model import read_model def main(model, output, num_matched): logging.info('Reading the COLMAP model...') cameras, images, points3D = read_model(model) ...
3280940
from typing import Optional from src.data.mongo.secret import get_random_key def get_access_token(access_token: Optional[str] = None) -> str: if access_token is not None: return access_token return get_random_key()
3280943
import pytest import pytorch_testing_utils as ptu import torch from torch import nn import pystiche from pystiche import enc, ops from tests.asserts import assert_named_modules_identical from tests.utils import suppress_deprecation_warning class TestOperatorContainer: class Operator(ops.Operator): def ...
3280950
import functools import pyproj import shapely.ops from rtree.index import Index, Property def project(shape, source, target): '''Projects a geometry from one coordinate system into another. Args: shape: the geometry to project. source: the source EPSG spatial reference system identifier. ...
3281009
import unittest import numpy as np from parameterized import parameterized_class from unittest import mock from numpy.testing import assert_array_equal from small_text.data.datasets import SklearnDataset, DatasetView from small_text.data.datasets import split_data from small_text.data.exceptions import UnsupportedO...
3281067
from django.urls import reverse, resolve from tethys_sdk.testing import TethysTestCase class TestUrls(TethysTestCase): def set_up(self): pass def tear_down(self): pass def test_urls(self): # This executes the code at the module level url = reverse('app_library') ...
3281115
from pytest import raises import numpy as np from numpy.testing import assert_equal, assert_allclose from menpo.math import dot_inplace_left, dot_inplace_right, as_matrix, from_matrix from menpo.image import MaskedImage n_big = 9182 k = 100 n_small = 99 n_images = 5 image_shape = (10, 10) mask = np.zeros(image_shape...
3281116
from collections import defaultdict import pdb from PIL import Image import numpy as np import cv2 class BboxEval: def __init__(self): self.per_verb_occ_bboxes = defaultdict(float) self.per_verb_all_correct_bboxes = defaultdict(float) self.per_verb_roles_bboxes = defaultdict(float) ...
3281135
import torch import torch.nn.functional as F from torch.nn import Linear from torch_geometric.nn import GCNConv, global_mean_pool from torch_scatter import scatter_mean, scatter_max from asap_pool import ASAP_Pooling import pdb def readout(x, batch): x_mean = scatter_mean(x, batch, dim=0) x_max, _ = scatter_ma...
3281144
from unittest import TestCase from hkws.base_adapter import BaseAdapter class TestHKAdapter(TestCase): def test_add_lib(self): a = BaseAdapter() a.add_lib("/Users/zhubin/python/pyhikvsion/hkws/lib/linux", ".so") print(a.so_list)
3281153
from sdk import * addr_list = addresses() _pid_pass = "<PASSWORD>" _pid_fail = "id_30011" _proposer = addr_list[0] _initial_funding = (int("2") * 10 ** 9) _each_funding = (int("5") * 10 ** 9) _funding_goal_general = (int("10") * 10 ** 9) def test_pass_proposal_cli(): _prop = Proposal(_pid_pass, "general", "propo...
3281161
import logging import unicodedata INVALID_CHARS = " !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~\n\r" MIN_WORD_LENGTH = 3 def filter_characters(string, invalid_chars=INVALID_CHARS): """ Removes invalid characters from a string :param string: String to be sanitized :param invalid_chars: a string containing all...
3281202
from collections import OrderedDict from flask_restx import fields from mindsdb.api.http.namespaces.configs.datasources import ns_conf get_datasource_rows_params = OrderedDict([ ('page[size]', { 'description': 'page size', 'type': 'integer', 'in': 'path', 'required': False, ...
3281260
from pathlib import Path import pytest import staticjinja @pytest.fixture def reloader(site): return staticjinja.Reloader(site) def test_should_handle(reloader, root_path, template_path): exists = template_path / "template1.html" DNE = template_path / "DNE.html" assert reloader.should_handle("crea...
3281304
from django.shortcuts import render # Create your views here. def index(request): context_dict={'text':'hello_world','number':100} return render(request,'basic_app/index.html',context_dict) def other(request): return render(request,'basic_app/other.html') def relative(request): return render(request,...
3281306
from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib import colors from reportlab.lib.units import mm from copy import deepcopy from reportlab.lib.enums import TA_JUSTIFY import directory.models as directory from directions.models import ParaclinicResult from results.prepare_data import text_to_bold ...
3281307
from rest_framework import status, viewsets from rest_framework.response import Response from rest_framework import mixins from rest_framework.decorators import api_view, permission_classes, authentication_classes from rest_framework.authtoken.models import Token from modelchimp.serializers.project_key import ProjectK...
3281361
import torch import torch.nn as nn import torch.nn.functional as F import torchvision.models as models from collections import OrderedDict from .hourglass import Hourglass class DRNet(nn.Module): def __init__(self, phrase_encoder, feature_dim, num_layers=3, backbone="resnet18"): super(DRNet, self).__init_...
3281381
from __future__ import print_function from __future__ import division import time from utils import * def dncnn(input, is_training=True, output_channels=3): with tf.variable_scope('block1'): output = tf.layers.conv2d(input, 64, 3, padding='same', activation=tf.nn.relu) for layers in xrange(2, 19 + 1)...
3281432
from .cartesian_coordinates import CartesianCoordinateHandler from .coordinate_handler import _get_coord_fields class SpectralCubeCoordinateHandler(CartesianCoordinateHandler): name = "spectral_cube" def __init__(self, ds, ordering=("x", "y", "z")): ordering = tuple( "xyz"[axis] for axis ...
3281442
from armulator.armv6.opcodes.abstract_opcodes.stm_user_registers import StmUserRegisters from armulator.armv6.opcodes.opcode import Opcode class StmUserRegistersA1(StmUserRegisters, Opcode): def __init__(self, instruction, increment, word_higher, registers, n): Opcode.__init__(self, instruction) S...
3281443
import tensorflow as tf import config import os from data_input.data_input import DataInput from rfl_net.rfl_net import RFLNet from rfl_net.utils import print_and_log class EvalNet(): def __init__(self): config_proto = tf.ConfigProto() config_proto.gpu_options.allow_growth = True with tf.Gr...
3281456
from typing import Dict from pydantic import BaseModel class AlbRequestContextData(BaseModel): targetGroupArn: str class AlbRequestContext(BaseModel): elb: AlbRequestContextData class AlbModel(BaseModel): httpMethod: str path: str body: str isBase64Encoded: bool headers: Dict[str, str...
3281460
from pathlib import Path def change_path_suffix(path_str, suffix_str): path = Path(path_str) dir_path = path.parent file_base = path.stem return str(dir_path / (file_base + suffix_str))
3281471
from evaluator.music_demixing import MusicDemixingPredictor import numpy as np print("Calculating scores for local run...") submission = MusicDemixingPredictor(model_name='tdf+demucs0.5') scores = submission.scoring() scores = np.array([list(score.values()) for score in scores.values()]) print(np.mean(scores, 0), np....
3281475
import json import logging import typing from copy import copy from dataclasses import dataclass, field, replace from pathlib import Path from typing import Any, Dict, List, Optional @dataclass(frozen=True) class SelectedStrategy: name: str args: List[str] = field(default_factory=list) def with_args(self...
3281476
import tensorflow as tf def mae(pred, target, name='mae'): return tf.reduce_mean(tf.abs(pred - target), name=name) def mse(pred, target, name='mse'): return tf.reduce_mean(tf.square(pred - target), name=name) def rmse(pred, target, name='rmse'): return tf.sqrt(tf.reduce_mean(tf.square(pred - target...
3281518
from .test import BaseTest, ValidatorError class Test_Id_Error_Escapedslash(BaseTest): label = 'Forward slash gives 404' level = 1 # should this also be true for level0? Glen category = 1 versions = [u'1.0', u'1.1', u'2.0',u'3.0'] validationInfo = None def run(self, result): try: ...
3281575
def is_even(n): return n % 2 == 0 def test_product_of_even_numbers_is_even(): "Natural numbers truths" evens = [(18, 8), (14, 12), (0, 4), (6, 2), (16, 10)] for e1, e2 in evens: check_even.description = "for even numbers %d and %d their product is even as well" % (e1, e2) yield check_e...
3281585
import logging from hetdesrun.component.load import base_module_path from hetdesrun.runtime.exceptions import ( RuntimeExecutionError, DAGProcessingError, UncaughtComponentException, MissingOutputDataError, ComponentDataValidationError, WorkflowOutputValidationError, WorkflowInputDataValida...
3281586
import numpy as np import argparse import os def merge(source_metadata, target_metadata, out_dir=''): concatinated_metas = [] with open(source_metadata, 'r', encoding='utf-8') as file: source_metas = file.readlines() with open(target_metadata, 'r', encoding='utf-8') as file: target_metas = ...
3281633
from torch import nn import transformers class BertForMLM(nn.Module): """ BertForMLM Simplified huggingface model """ def __init__( self, model_name: str = "bert-base-uncased", output_logits: bool = True, output_hidden_states: bool = True, ): """ ...
3281665
import asyncio import numpy as np import ucp.utils async def worker(rank, eps, args): futures = [] # Send my rank to all others for ep in eps.values(): futures.append(ep.send(np.array([rank], dtype="u4"))) # Recv from all others recv_list = [] for ep in eps.values(): recv_lis...
3281669
import argparse def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('mode', type=str) parser.add_argument('--start', type=int, default=0) parser.add_argument('--end', type=int, default=-1) parser.add_argument('--save-failures', type=str, default='./bad_videos.txt') return ...
3281675
from typing import Type from .base import _LOGGED_VALUE__PROPERTY_NAME, _LOGGED_MODEL__PROPERTY_ATTR_PREFIX, _ValueType from .data import TimeRangedData class LoggedValue: """ Overview: LoggedValue can be used as property in LoggedModel, for it has __get__ and __set__ method. This class's ins...
3281710
import torch import torch.nn as nn import torch.nn.init as init def init_weights(m, a=1e-2): if isinstance(m, nn.Conv1d): init.normal_(m.weight.data) if m.bias is not None: init.normal_(m.bias.data) elif isinstance(m, nn.Conv2d): init.kaiming_normal_(m.weight.data, a=a) ...
3281711
from typing import Any, Callable, List, Optional from ignite.engine import Engine, Events class EpochOutputStore: """EpochOutputStore handler to save output prediction and target history after every epoch, could be useful for e.g., visualization purposes. Note: This can potentially lead to a mem...
3281763
import os def pytest_addoption(parser): parser.addoption('--cpu', action='store_true') def pytest_configure(config): if not config.option.cpu: return os.environ['PATH'] = ':'.join(p for p in os.environ['PATH'].split(':') if 'cuda' not in p) os.environ['CUDA_VERSION'] = '' os.environ['CUD...
3281795
import unittest import numpy as np from dirichletcal.calib.fixeddirichlet import FixedDiagonalDirichletCalibrator from . import get_simple_binary_example from . import get_simple_ternary_example class TestFixedDiagonalDirichlet(unittest.TestCase): def setUp(self): self.cal = FixedDiagonalDirichletCalibrat...
3281830
from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from torch.utils.data import Dataset, DataLoader from torch.utils.data.sampler import SubsetRandomSampler import numpy as np ...
3281887
import json, os import argparse from tqdm import tqdm def parse_args(): parser = argparse.ArgumentParser(description="Train FGVC Network") parser.add_argument( "--input_path", help="input train/test splitting files", required=True, type=str, ) parser.add_ar...
3281894
def remove_unnecessary_attributes(tag): keys = list(tag.attrs.keys()) for attr in keys: if attr not in ['src', 'href']: del tag.attrs[attr] def has_only_one_anchor(tag): return len(list(tag.children)) == 1 and tag.next and tag.next.name == 'a'
3281907
import pandas as pd import panel as pn import plotly.express as px from dataviz_in_python import config config.configure("plotly", url="lib_plotly", title="Plotly") TEXT = """ # Plotly: High Quality, Interactive Plots in Python [Plotly](https://plotly.com/python/)'s Python graphing library makes interactive, publi...
3281922
from argparse import RawDescriptionHelpFormatter from argopt import argopt try: from StringIO import StringIO except ImportError: from io import StringIO def test_basic(): doc = ''' Example programme description. You should be able to do args = argopt(__doc__).parse_args() instead of args = doco...
3282010
from soap.semantics.functions.arithmetic import arith_eval, error_eval from soap.semantics.functions.boolean import bool_eval from soap.semantics.functions.fixpoint import ( fixpoint_eval, unroll_fix_expr, fix_expr_eval ) from soap.semantics.functions.label import label, luts, resource_eval from soap.semantics.func...
3282023
from .name2idx import C, V class DifferentialEquation(object): """Kinetic equations""" def __init__(self, perturbation): super(DifferentialEquation, self).__init__() self.perturbation = perturbation def diffeq(self, t, y, *x): dydt = [0] * V.NUM dydt[V.MP] = ( ...
3282104
import gym from gym.spaces import Box, Discrete, Tuple import numpy as np import unittest import ray from ray.rllib.models import ModelCatalog, MODEL_DEFAULTS, ActionDistribution from ray.rllib.models.tf.tf_modelv2 import TFModelV2 from ray.rllib.models.tf.tf_action_dist import TFActionDistribution from ray.rllib.mode...
3282117
import clr import time from System.Reflection import Assembly dynamoCore = Assembly.Load("DynamoCore") dynVersion = dynamoCore.GetName().Version.ToString() dynVersionInt = int(dynVersion[0])*10+int(dynVersion[2]) class WorksharingLog: def __init__(self, version, sessions): self.Version = version self.Sessions = ...
3282119
from .iou3d_utils import boxes_iou_bev, nms_gpu, nms_normal_gpu __all__ = ['boxes_iou_bev', 'nms_gpu', 'nms_normal_gpu']
3282260
import sys import os import inspect import re from setuptools import setup as setuptools_setup ENTRY_POINT_TEMPLATE = """ #!/usr/bin/env python2.7 # -*- coding: utf-8 -*- import re import sys from {} import {} if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.ex...
3282288
import numpy as np from jrieke.utils import resize_image from tqdm import tqdm_notebook import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable # ---------------------------- Interpretation methods -------------------------------- def sensitivity_analysis(model, image_...
3282289
import atexit import datetime import faulthandler import os import re import tempfile import unittest import numpy faulthandler.enable() # to debug seg faults and timeouts import cfdm n_tmpfiles = 1 tmpfiles = [ tempfile.mkstemp("_test_Field.nc", dir=os.getcwd())[1] for i in range(n_tmpfiles) ] (tmpfile,) ...
3282368
from django.urls import path from .views import ( UserDashboard, DeletePostbyAuthor, user_dashboard_filter_category_posts_view, user_dashboard_filter_tag_posts_view, ) urlpatterns = [ path("", UserDashboard.as_view(), name="user_dashboard"), path("posts/<int:pk>/delete/confirm", Delet...
3282396
from datetime import datetime, date, timedelta import unittest from businesstime import BusinessTime from businesstime.holidays.usa import USFederalHolidays class BusinessTimeTest(unittest.TestCase): def setUp(self): """ Tests mostly based around January 2014, where two holidays, New Years Day ...
3282405
import sys import logging import argparse import shutil from collections import OrderedDict import git import yaml import torch import torch.optim as optim from baselines.common.atari_wrappers import EpisodicLifeEnv, FireResetEnv OPTS = OrderedDict({None: None, 'adam': optim.Adam, ...
3282419
import json from typing import Dict from typing import List from typing import Optional import schema tag_schema = {str: schema.Or(None, {str: str,})} image_definition_schema = schema.Schema( { str: [ schema.Or( schema.And( { "type":...
3282429
from baseline.tf.seq2seq.model import * from baseline.tf.seq2seq.train import * from baseline.tf.seq2seq.encoders import * from baseline.tf.seq2seq.decoders import *
3282455
from __future__ import absolute_import, division, print_function import sys import logging import logging.handlers # Hide messages if we log before setting up handler logging.root.manager.emittedNoHandlerWarning = True logging.getLogger("paramiko").setLevel(logging.WARNING) def getLogger(): return logging.getL...
3282527
def extractNovelSaga(item): """ 'Novel Saga' """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): return None if 'Dragon Martial Emperor' in item['tags']: return buildReleaseMessageWithType(item, 'Dragon Martial Emperor', vol,...
3282544
import boto3 import sure # noqa # pylint: disable=unused-import import json from moto import mock_cloudformation, mock_ec2 from tests import EXAMPLE_AMI_ID from string import Template from uuid import uuid4 SEC_GROUP_INGRESS = Template( """{ "AWSTemplateFormatVersion": "2010-09-09", "Description": "AWS C...
3282558
from pathlib import Path from typing import Union def get_files(path: Union[str, Path], extension='.wav'): if isinstance(path, str): path = Path(path).expanduser().resolve() return list(path.rglob(f'*{extension}'))
3282647
import os import click import yaml import numpy as np from state_construction import StateConstructor import torch ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) # base folder on the running machine or VM OUTPUT_DIR = ROOT_DIR @click.command() @click.option('--options', '-o', multiple=True, nargs=2, type=cl...
3282768
import warnings class EasyPySpinWarning(Warning): pass def warn( message: str, category: Warning = EasyPySpinWarning, stacklevel: int = 2 ) -> None: """Default EasyPySpin warn""" warnings.warn(message, category, stacklevel + 1)
3282780
import time import hiro # type: ignore from starlette.applications import Starlette from starlette.requests import Request from starlette.responses import PlainTextResponse from starlette.routing import Route from starlette.testclient import TestClient from slowapi.util import get_ipaddr, get_remote_address from tes...
3282844
from __future__ import annotations from typing import TYPE_CHECKING, List from pochta.utils import HTTPMethod if TYPE_CHECKING: from pochta import Delivery class Settings: """ Методы API Настроек. Используется через объект :class:`Delivery <pochta.delivery.Delivery>` или вручную. """ def...
3282864
a = 0 while a < 10: print(a) a = a + 1 else: print("while else output!") print("Just printed out 10 numbers in a while loop")
3282866
from tinydb.middlewares import Middleware from tinydb.storages import MemoryStorage from tinydb import TinyDB import weakref class WeakRefMiddleware(Middleware): def __init__(self, storage_cls=TinyDB.DEFAULT_STORAGE): # Any middleware *has* to call the super constructor # with storage_cls ...
3282874
import logging from typing import Dict, List, Any import numpy as np import pandas as pd import torch from transfer_nlp.common.tokenizers import CustomTokenizer from transfer_nlp.embeddings.embeddings import Embedding from transfer_nlp.loaders.loaders import DatasetSplits, DataFrameDataset from transfer_nlp.loaders.v...
3282912
import pytest def test_custom_conf_does_not_apply_to_unknown_vhost(docker_compose, nginxproxy): r = nginxproxy.get("http://nginx-proxy/") assert r.status_code == 503 assert "X-test" not in r.headers def test_custom_conf_applies_to_web1(docker_compose, nginxproxy): r = nginxproxy.get("http://web1.nginx...
3282960
from __future__ import unicode_literals import psycopg2.extensions import sqlalchemy import sqlalchemy.types as types from sqlalchemy.dialects.postgresql.base import ischema_names __version__ = '1.8.0' class CIText(types.Concatenable, types.UserDefinedType): # This is copied from the `literal_processor` of sql...
3283025
from rest_framework.serializers import ModelSerializer from models.models import Model, ModelLog, Metadata, ObjectType from projects.models import Project, S3, Flavor, Environment, MLFlow, ReleaseName, ProjectTemplate from apps.models import AppInstance, Apps, AppCategories, AppStatus from django.contrib.auth.models i...
3283035
from .abstract_condition import AbstractCondition from .condition_type import ConditionType class Condition(AbstractCondition): def __init__(self, attribute, operator, value): super().__init__(type_=ConditionType.CONDITION.value) self.attribute = attribute self.operator = operator ...
3283118
def Convolution(data, name, num_filter, kernel, stride=[1,1], pad=[0,0]): bottom = data top = name print 'layer {' print ' bottom: "%s"' % bottom print ' top: "%s"' % top print ' name: "%s"' % name print ' type: "Convolution"' print ' convolution_param {' print ' num_output: %i' % num_filter ...
3283142
import base64 from django.utils import simplejson import urllib from google.appengine.api import urlfetch def track(event, properties=None): """ A simple function for asynchronously logging to the mixpanel.com API on App Engine (Python) using RPC URL Fetch object. @param event: The overal...
3283148
from pathlib import Path from examples.anbncn import anbncn from examples.evaluate import evaluate_deepstochlog_task, create_default_parser eval_root = Path(__file__).parent def main(max_length: int = 12, epochs: int = 1, runs: int = 5, only_time: bool = False): print( "Running {} runs of {} epochs eac...
3283169
import zmq import comm import time from multiprocessing import Process # This is a message forwarder, a basic proxy service so publishers and subscribers can be dynamic without a well # known address. Note that the normal rules for pub/sub port assigned listed above are reversed # for the proxey service def forwarde...
3283171
from math import log def check_enough_values(num_values, value_bits, state_bits, modulus=None): if modulus: return log(modulus, 2) * num_values >= state_bits else: return num_values * value_bits >= state_bits
3283181
import glob import logging import os import signal import sys import time from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop, PeriodicCallback from tornado.process import task_id from tornado.options import define, parse_command_line, options from tornado.web import Application, url from sick...
3283218
from __init__ import * def test_across_services(arr, country): # Update here too for item in arr: json_value = check_services(item, country) if not json_value: return False def test_netflix_search(arr): for item in arr: json_value = get_netflix_details(item) if n...
3283256
from datetime import datetime, time from flask import Blueprint, Response, g, request, current_app from flask_restful import Api from flasgger import swag_from from app.docs.v2.student.apply.goingout import * from app.models.account import StudentModel from app.models.apply import GoingoutApplyModel from app.views.v2...
3283272
from typing import Any from pyppeteer.page import Page from PuppeteerLibrary.custom_elements.base_page import BasePage from PuppeteerLibrary.locators.SelectorAbstraction import SelectorAbstraction class PuppeteerPage(BasePage): def __init__(self, page: Page): self.page = page self.selected_iframe...
3283338
from .customer_saved_search import CustomerSavedSearch class CustomerGroup(CustomerSavedSearch): pass