id
stringlengths
3
8
content
stringlengths
100
981k
1722104
import numpy as np import astropy.units as u import pytest from ...units import hundred_nm from ...photometry import bandpass from ..core import SpectralGradient class TestSpectralGradient(): def test_new(self): S = SpectralGradient(100 / u.um, wave=(525, 575) * u.nm) assert np.isclose(S.wave0.to(...
1722111
pass pass; assert a assert a; assert b assert a, "eee" raise RuntimeError raise RuntimeError from e return return 1 return 1, return *a del a del (a) del a, b, del a[:] del a.b del (a,) del (a, b) del [a, b] del a; global a global a, b nonlocal a nonlocal a, b yield a yield from a for i in a: pass for i, i...
1722173
from datetime import timedelta from typing import Optional from uuid import uuid4 from django.conf import settings from django.db import models, IntegrityError from django.utils import timezone from django.utils.translation import gettext_lazy as _ from etc.models import InheritedModel if False: # pragma: nocover ...
1722195
from .utils import decompress_mesh_data from ..skeleton import Skeleton from ..trimesh_io import Mesh import h5py import os import orjson import pandas as pd import warnings import numpy as np from dataclasses import asdict warnings.simplefilter(action="ignore", category=pd.errors.PerformanceWarning) NULL_VERSION = 1...
1722217
from __future__ import with_statement from pytest import raises from value import Value def fixture(init): class Option(Value): __init__ = init return Option def test_primitive_value(): Option = fixture(lambda self: None) assert repr(Option()) == 'Option()' assert hash(Option()) == has...
1722255
import asyncio from twitchbot import Mod, channels, get_nick, add_task, stop_task class ChannelViewUpdaterMod(Mod): name = 'channelviewerupdater' TASK_NAME = 'channelviewerupdateloop' async def channel_update_loop(self): while True: while not channels: await asyncio.s...
1722299
import os from xbrr.base.reader.base_element import BaseElement from xbrr.edinet.reader.element_value import ElementValue class Element(BaseElement): def __init__(self, name, element, reference, reader): super().__init__(name, element, reference, reader) self.name = name self.element = el...
1722317
import logging def setupLogger(): logger = logging.getLogger(__package__) # Levels are as follows: ''' CRITICAL = 50 FATAL = CRITICAL ERROR = 40 WARNING = 30 WARN = WARNING INFO = 20 DEBUG = 10 NOTSET = 0 ''' LEVEL = logging.DEBU...
1722340
from django.core.validators import validate_email from django.utils.translation import ugettext_lazy as _ from orchestra.contrib.settings import Setting ORCHESTRA_BASE_DOMAIN = Setting('ORCHESTRA_BASE_DOMAIN', 'orchestra.lan', help_text=("Base domain name used for other settings.<br>" "If you'...
1722347
import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_java(host): assert host.exists("java") if (host.system_info.distribution != "opensuse-leap"): assert host.exists("jav...
1722352
import sys f=open(sys.argv[-1], 'rb') b=f.read() f.close() with open(sys.argv[-1] + ".cpp", 'w') as w: c=0 w.write("const unsigned char mjpg_frame[] = {\n") for i in b: w.write("0x%02x," % i) c+=1 if c==12: w.write("\n") c=0 w.write("\n};")
1722355
from PyObjCTools.TestSupport import * from CoreFoundation import * import datetime try: long except NameError: long = int class TestCFCalendarVariadic (TestCase): def testTypes(self): self.assertIsCFType(CFCalendarRef) def testCFCalendarComposeAbsoluteTime(self): calendar = CFCalenda...
1722445
from ocb.aes import AES from ocb import OCB from base64 import b64encode, b64decode from Crypto import Random import md5 import os from pbkdf2 import PBKDF2 as pbkdf2 class Cipher: keySize = 32 blockSize = 16 @staticmethod def get_key(): return b64encode(Random.get_random_bytes(Cipher.keySize...
1722451
import os import inspect import logging import configargparse import torch from utils.logging_utils import init_logger from utils.parse_action import StoreLoggingLevelAction, CheckPathAction class ConfigurationParer(): """This class defines customized configuration parser """ def __init__(self, ...
1722456
import re from typing import Union, Callable, Iterable def str_chain_apply( input_str: str, ordered_transformers: Iterable[Callable[[str], str]] ) -> str: """Apply set of functions in order - pipeline-like""" result = input_str for t in ordered_transformers: result = t(result) return resul...
1722458
import pytest from util import * # For prod releases PROD_VERSION_CORRECT = '1.0' GITHUB_REF_CORRECT = 'refs/tags/1.0' # For dev releases GITHUB_RUN_NUMBER_CORRECT = '2' DEV_VERSION_CORRECT = GITHUB_RUN_NUMBER_CORRECT GITHUB_WORKFLOW_PRE_RELEASE = 'Pre-Release Package' GITHUB_REF_FALSE = 'not_there' @pytest.fixtu...
1722464
from __future__ import absolute_import from changes.api.base import APIView from changes.config import db from changes.constants import Result from changes.models.build import Build from changes.models.job import Job from changes.models.test import TestCase from changes.models.source import Source # This constant mu...
1722476
from types import MethodType import torch import torch.nn as nn import models from .classification import Learner_Classification as Learner_Template from modules.pairwise import PairEnum class Learner_DensePairSimilarity(Learner_Template): @staticmethod def create_model(model_type,model_name,out_dim): ...
1722547
import torch import torch.nn as nn import torch.nn.functional as F from tqdm import tqdm import numpy as np from lib.model.mlp import MLP class DropoutRegressor(nn.Module): def __init__(self, args, tokenizer): super().__init__() self.args = args self.num_tokens = args.vocab_size s...
1722582
from __future__ import unicode_literals from frappe import _ def get_data(): return { 'fieldname': 'agency_country_process', 'transactions': [ { 'items': ['Candidate Country Process'] } ], }
1722587
from sysrsync.helpers import iterators from nose.tools import eq_ def test_list_flatten(): list_input = [1, [2, 3], [4]] expect = [1, 2, 3, 4] result = iterators.flatten(list_input) eq_(expect, result) def test_tuple_flatten(): tuple_input = (1, [2, 3], [4]) expect = [1, 2, 3, 4] result...
1722613
import pennylane as qml import numpy as np def add_dummy_measurements_for_test(func): def inner(*args, **kwargs): func(*args, **kwargs) if test == True: return qml.expval(qml.PauliY(0)) return inner class EncodingCircuitsPennylane: def __init__(self, enc = None, qubit = None): ...
1722619
import scipy import torch def preemphasis_np(x, preemphasis_factor=0.9): return scipy.signal.lfilter([1, -preemphasis_factor], [1], x) def inv_preemphasis_np(x, preemphasis_factor=0.9): return scipy.signal.lfilter([1], [1, -preemphasis_factor], x) def mix_with_snr(a, b, snr=20): """ PyTorch Functi...
1722627
from abc import abstractmethod import numpy as np from intervaltree import IntervalTree from loguru import logger from vimms.Common import ScanParameters ######################################################################################################################## # DEW Exclusions ########################...
1722641
import numpy as np from preprocess.load_data.data_loader import load_production_missing_category production_missc_tb = load_production_missing_category() # 下の行から本書スタート # KNeighborsClassifierをsklearnライブラリから読み込み from sklearn.neighbors import KNeighborsClassifier # replace関数によって、Noneをnanに変換 production_missc_tb.replace('...
1722661
from __future__ import unicode_literals class PaymentProcessor(object): def configure_api_key(self, api_key): """Configure API key for the processor, you need to call this method before you call any other methods :param api_key: the API key to set """ raise NotImplemented...
1722677
from src.app.auth.model import UserModel from src.common.exceptions import ExceptionHandler class PostAuthService(object): """ Amazon Cognito invokes this trigger to initiate the custom authentication flow. """ def __init__(self, event): """ :param self.event: dict :return: dict ...
1722706
from options.taxonomies.raw_attributes import raw_attributes from options.taxonomies.raw_taxonomies import raw_taxonomies from .helper import * class TaxonomyTree: raw_taxonomy_list = [taxonomy_str.strip().split('>') for taxonomy_str in raw_taxonomies.split('\n')] raw_attribute_list = [(attribute[0], attribut...
1722755
import abc from ..driver_base import SQLAlchemyDriverBase class AuthDriverABC(SQLAlchemyDriverBase, metaclass=abc.ABCMeta): """ Auth Driver Abstract Base Class Driver interface for authorization. """ def __init__(self, conn, **config): super().__init__(conn, **config) @abc.abstractm...
1722761
import os import sys from setuptools import setup, find_packages def read(fname): filename = os.path.join(os.path.dirname(__file__), fname) with open(filename, 'r') as f: return f.read() # Ensure we're not accidentally installed on Python2. if sys.version_info.major < 3: raise RuntimeError("Faceda...
1722774
from collections import defaultdict __all__ = ("MultiDict", ) class MultiDict(defaultdict): """A :class:`MultiDict` is a defaultdict subclass customized to deal with multiple values for the same key. """ def __init__(self, *mapping): super().__init__(list) for key, value in mapping ...
1722800
import folium import itertools import math import numpy as np def _degree_to_zoom_level(l1, l2, margin = 0.0): degree = abs(l1 - l2) * (1 + margin) zoom_level_int = 0 if degree != 0: zoom_level_float = math.log(360/degree)/math.log(2) zoom_level_int = int(zoom_level_float) el...
1722804
import unittest from mygrations.formats.mysql.mygrations.operations.row_delete import row_delete from collections import OrderedDict class test_row_delete(unittest.TestCase): def test_simple(self): op = row_delete('a_table', 7) self.assertEquals("DELETE FROM `a_table` WHERE id=7;", str(op)) ...
1722839
import os from external_cmd import TimedExternalCmd from defaults import * from utils import * FORMAT = '%(levelname)s %(asctime)-15s %(name)-20s %(message)s' logFormatter = logging.Formatter(FORMAT) logger = logging.getLogger(__name__) consoleHandler = logging.StreamHandler() consoleHandler.setFormatter(logFormatter)...
1722857
import tensorflow as tf import pickle def load_cached_vector(fname): with open(fname, 'rb') as fp: word_dict = pickle.load(fp) return word_dict def load_fasttext(fname): word_dict = {} with open(fname, 'r') as f: lines = f.readlines() for line in lines[1:]: line =...
1722925
import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class DownloadConfig: """Configuration for our cached path manager. Attributes: cache_dir (:obj:`str` or :obj:`Path`, optional): Specify a cache directory to save the file to (ov...
1722974
from HTV import HanimeTV hentai = HanimeTV(email="EMAIL", password="<PASSWORD>") query = "Imouto Paradise" url = "https://hanime.tv/hentai-videos/imouto-paradise-1-ep-1" # SEARCH search = hentai.search(query) print (search) # GET INFO info = hentai.info(url) print (info) # GET STORYBOARDS storyboards = hentai.story...
1722977
import os from typing import List try: from typing import Literal except ImportError: from typing_extensions import Literal # type: ignore from typing import Optional import numpy as np import pandas as pd import scanpy as sc from anndata import AnnData from rich import print WORKING_DIRECTORY = os.path.di...
1723053
import urllib.error from urllib.request import urlopen from urllib.parse import urlsplit import time import yaml examples = {} with open('problems.yaml') as f: problems = yaml.safe_load(f.read()) for problem in problems: for url in problem['links']: domain = urlsplit(url).netloc ...
1723065
from PyQt5.QtCore import Qt from PyQt5.QtWidgets import (QGridLayout, QSizePolicy, QToolBar, QToolButton, QWidget) from .ribbon import Ribbon class ToolbarRibbon(Ribbon): """A ribbon with helpers for containing toolbars """ def add_toolbar(self, title=None, toolbar=None): ...
1723089
from armulator.armv6.opcodes.abstract_opcode import AbstractOpcode from armulator.armv6.bits_ops import add, sub from bitstring import BitArray from armulator.armv6.arm_exceptions import UndefinedInstructionException from armulator.armv6.enums import InstrSet class LdmExceptionReturn(AbstractOpcode): def __init__...
1723122
import os from files.core import const from files.config import gluecode as config def run(proj_path, target_name, params): return { "project_name": "ezored", "version": "1.0.0", "build_types": ["Debug", "Release"], "archs": [ { "arch": "armv7", ...
1723163
import matplotlib.pyplot as plt import numpy as np import pandas as pd from matplotlib.backends.backend_pdf import PdfPages def four_dim_scatter(data, year, x_name, y_name, c_name, s_name, smin=1, smax=10, figsize = (16, 10), index_name = "Year", color_bar = "Dark2",discrete...
1723178
DEFAULT_MOUNT_SHARE = "True" MAX_SHARES_PER_FPG = 16 def create_metadata(backend, cpg, fpg, share_name, size, readonly=False, nfs_options=None, comment='', fsMode=None, fsOwner=None): return { 'id': None, 'backend': backend, 'cpg': cpg, 'fpg'...
1723198
from sqlalchemy import ARRAY, BigInteger, Boolean, CHAR, Column, Date, DateTime, Float, Integer, \ JSON, LargeBinary, Numeric, SmallInteger, String, Text, Time, text, PrimaryKeyConstraint, Table, UniqueConstraint from sqlalchemy.dialects.postgresql import INTERVAL, JSONB, UUID from sqlalchemy.orm import declarative...
1723217
from collections import namedtuple import pytest AppUrls = namedtuple('AppUrls', ('ui', 'api', 'admin')) @pytest.fixture def selenium(selenium): """Configure selenium""" selenium.implicitly_wait(10) return selenium def pytest_addoption(parser): parser.addoption('--ui-baseurl', default='http://prox...
1723247
from typing import Union from pygls.lsp.methods import ( TEXT_DOCUMENT_DID_CHANGE, TEXT_DOCUMENT_DID_CLOSE, TEXT_DOCUMENT_DID_OPEN, ) from pygls.lsp.types import ( Diagnostic, DidChangeTextDocumentParams, DidCloseTextDocumentParams, DidOpenTextDocumentParams, Position, Range, ) from...
1723248
from manabi.api.serializers import ManabiModelSerializer from manabi.apps.twitter_usages.models import ( ExpressionTweet, ) class TweetSerializer(ManabiModelSerializer): class Meta: model = ExpressionTweet fields = ( 'id', 'tweet', ) read_only_fields = (...
1723343
from .self_multihead_attn import SelfMultiheadAttn from .encdec_multihead_attn import EncdecMultiheadAttn
1723368
import dash from dash.dependencies import Input, Output import dash_core_components as dcc import dash_html_components as html import dash_table_experiments as dt app = dash.Dash() app.config['suppress_callback_exceptions'] = True app.layout = html.Div([ dcc.Dropdown( id='outer-controls', ...
1723390
import os import countershape import countershape.utils as utils import tutils class TestInDir: def test_one(self): with tutils.tmpdir() as t: old = os.getcwd() sub = os.path.join(t, "sub") os.mkdir(sub) with utils.InDir(sub): assert os.getcwd...
1723438
import asyncio def enable(statsd_client: 'statsd.StatsClient', interval: float = 0.25, loop: asyncio.AbstractEventLoop = None) -> None: ''' Start logging event loop lags to StatsD. In ideal circumstances they should be very close to zero. Lags may increase if event loop callbacks block for too long. ''' if loop...
1723477
import asyncio import json from utilities import utilities import os import requests from lxml import html import re def dump_string(x): text = """ Title :{} \n""".format( x["title"] ) links = x["links"] _link = "" f = 0 for link in links: f = f + 1 _link = _li...
1723483
from collections import namedtuple Station = namedtuple('Station', ['number', 'longitude', 'latitude', 'altitude', 'name']) stations = { 8: Station(number=8, longitude=5.528, latitude=52.453, altitude=-4.2, name='LELYSTAD'), 13: Station(number=13, longitude=3.314, latitude=47.975, altitude=999.9, name='WISSEK...
1723513
import logging from qark.issue import Severity from qark.plugins.webview.helpers import webview_default_vulnerable from qark.scanner.plugin import JavaASTPlugin log = logging.getLogger(__name__) SET_ALLOW_FILE_ACCESS_DESCRIPTION = ( "File system access is enabled in this WebView. If untrusted data is used to spe...
1723530
import torch from torch import nn from mmcv.cnn import ConvModule class SequenceConv(nn.ModuleList): """Sequence conv module. Args: in_channels (int): input tensor channel. out_channels (int): output tensor channel. kernel_size (int): convolution kernel size. sequence_num (in...
1723533
import os, sys sys.path.append(os.path.abspath('EGG.egg')) import EGG.function_exception EGG.function_exception.f()
1723534
import os import sys import unittest sys.path.insert(0, os.path.abspath('..')) # hack to allow simple test structure import polymaze as pmz from polymaze import polygrid as _polygrid_module # silly workaround to allow tests to work in py2 or py3 try: _assertCountEqual = unittest.TestCase.assertCountEqual # py3...
1723544
import torch import torch.nn as nn import torch.nn.functional as F def _neg_loss(outputs: torch.Tensor, targets: torch.Tensor): """ Modified focal loss. Exactly the same as CornerNet. Runs faster and costs a little bit more memory Arguments: outputs (torch.Tensor): BATCH x C x H x W ...
1723563
import torch import torch.nn as nn GlobalAvgPool2D = lambda: nn.AdaptiveAvgPool2d(1) class GlobalAvgPool2DBaseline(nn.Module): def __init__(self): super(GlobalAvgPool2DBaseline, self).__init__() def forward(self, x): x_pool = torch.mean(x.view(x.size(0), x.size(1), x.size(2) * x.size(3)), di...
1723566
from bin_classifier import Main as Bin_Main from ner_classifier import Main as Ner_Main from mt_classifier import Main as Mt_Main import utils import json import os import argparse from data import Dataset ''' BAREBONES GRID-SEARCH SCRIPT ''' # Lists vecs = [None] # Check dropouts = [0.0, 0.3, 0.5] use_chars = ...
1723589
DOCKERFILE = """ FROM pytorch/pytorch:1.10.0-cuda11.3-cudnn8-runtime ARG DEBIAN_FRONTEND=noninteractive ARG requirements ENV TZ=Europe/Oslo RUN apt-get update RUN apt-get install -y \ build-essential \ cmake \ curl \ gcc \ git \ wget \ sudo \ && rm -rf /var/lib/apt/lists/* RUN curl -f...
1723648
import enum from enum import Enum from typing import List from pydantic import BaseModel from pydantic.fields import Field Types = enum.Enum( 'Types', { 'pod': 'pod', 'app': 'app' } ) Kinds = enum.Enum( 'Kinds', { 'encoder' : 'encoder', 'indexer' : 'indexer', ...
1723669
import tensorflow as tf def weight_variable(name, shape): """ Create a weight variable with appropriate initialization :param name: weight name :param shape: weight shape :return: initialized weight variable """ initer = tf.contrib.layers.xavier_initializer(uniform=False) return tf.get...
1723690
import dataiku import json def compare_dataset_schemas(client=None, project_key=None, dataset_a=None, dataset_b=None): """Return the common columns (names and types) between two datasets. """ prj = client.get_project(proje...
1723694
import matplotlib.pyplot as plt import numpy as np import subprocess as sp import argparse def run_example(_exec): """ run_example Args: _exec - string, example executable (including relative path) Returns: bytestring, stdout from running provided example """ p ...
1723706
def method1(set, n, sum): if sum == 0: return True if n == 0: return False # If last element is greater than # sum, then ignore it if set[n - 1] > sum: return method1(set, n - 1, sum) # else, check if sum can be obtained # by any of the following # (a) includin...
1723717
from unittest import TestCase, main from unittest.mock import patch from batchkit_examples.speech_sdk.parser import create_parser, parse_cmdline from .test_base import MockDevice class CommandLineTestCase(TestCase): @classmethod def setUpClass(cls): parser = create_parser() cls.parser = parser...
1723746
a = [1, 2, 3] a.insert(1, 42) print(a) a.insert(-1, -1) print(a) a.insert(99, 99) print(a) a.insert(-99, -99) print(a)
1723756
from typing import Dict, List, Optional from overrides import overrides from allennlp.training.metrics.metric import Metric from allennlp_semparse.domain_languages.domain_language import ExecutionError from .nla_language import NlaLanguage @Metric.register("nla_metric") class NlaMetric(Metric): """ Metric f...
1723772
import pytest pytestmark = pytest.mark.django_db @pytest.fixture def generate_dependency_usages(dependency_usage_factory): dependency_usage_factory( id=1, dependency__id=34, dependency__name="graphql", dependency__type="Python Library", major_version=3, minor_versi...
1723777
from backtester.dataSource import * from backtester.executionSystem import * from backtester.features import * from backtester.instruments import * from backtester.instrumentUpdates import * from backtester.metrics import * from backtester.orderPlacer import * from backtester.constants import * from backtester.financia...
1723808
import RPi.GPIO as GPIO from config.config import MODE FAN_TOP_PIN = 17 FAN_BOTTOM_PIN = 27 MAX_SPEED = MODE['fan']['max_speed'] class Fan: def __init__(self, pin, min_speed): GPIO.setup(pin, GPIO.OUT) self.pwm = GPIO.PWM(pin, 1000) self.pwm.start(MAX_SPEED) self.min_speed = min...
1723823
import json from mlflow.entities import FileInfo from mlflow.store.cli import _file_infos_to_json def test_file_info_to_json(): file_infos = [ FileInfo("/my/file", False, 123), FileInfo("/my/dir", True, None), ] info_str = _file_infos_to_json(file_infos) assert json.loads(info_str) ==...
1723830
import redis import configparser import os import json fp = os.path.dirname(__file__) config = configparser.ConfigParser() config.read(os.path.join(fp, "../../conf.ini")) class RedisHandle: def __init__(self, mq_name: str = 'default'): host = config.get('Redis', 'host') port = int(config.get('Re...
1723836
import os import json import jsonschema from ..errors import SpecError schema_filename = 'pipeline-spec.schema.json' schema_filename = os.path.join(os.path.dirname(__file__), schema_filename) schema = json.load(open(schema_filename)) validator = jsonschema.validators.validator_for(sche...
1723846
from django.urls import path from vat.views import (LoadVatCodes, VatCreate, VatDetail, VatList, VatTransactionEnquiry, VatUpdate) app_name = "vat" urlpatterns = [ path("load_vat_codes", LoadVatCodes.as_view(), name="load_vat_codes"), path("vat_detail/<int:pk>", VatDetail.as_view(), nam...
1723855
A_CONSTANT = "constant" ANOTHER_CONSTANT = "another constant" def a_function_definition(n: int=1) -> str: return A_CONSTANT * n
1723880
import logging import os import datakit.utils from .utils import read_json, write_json class CommandHelpers: """ Mixin class containing common helper methods for Datakit plugins. Intended to be sub-classed alongside Cliff Command. :Usage: * Create a plugin command that subclasses both Command...
1723883
from WorkspaceState import WorkspaceState class EditorHistoryCaretaker: def __init__(self): self.states = [] def add(self, state): self.states.append(state) def get(self, index): if len(self.states) < 1: return None if index < len(self.states): return self.states[index] ...
1723886
import logging import os import sys from logging.handlers import RotatingFileHandler from multiprocessing.pool import ThreadPool as Pool DEFAULT_FOLDER = None THEMES = None TEMP_THEMES = None FP_HASHES = None LOG_FILE = None LOG = logging.getLogger('bw_plex') INI_FILE = None DB_PATH = None CONFIG = None PMS = None POO...
1723898
import datetime from django.test import TestCase from django.utils import timezone from model_bakery import baker from channels.models import Category, Channel, Video class VideoManagerTestCase(TestCase): def setUp(self): self.channel = baker.make(Channel) def test_last_24h_videos(self): ju...
1723918
import os import argparse parser = argparse.ArgumentParser() parser.add_argument('--alias', type=str, required=False, default='0202_randinit') parser.add_argument('--gpu', type=int, required=False, default=0) parser.add_argument('--mode', type=str, required=False, default='randinit') parser.add_argument('--ckpt', typ...
1723921
from baseline.version import __version__ from baseline.utils import * from baseline.vectorizers import * from baseline.confusion import * from baseline.data import * from baseline.reader import * from eight_mile.progress import * from baseline.reporting import * from baseline.model import * from baseline.embeddings imp...
1723936
import abc from ..ifuzzable import IFuzzable class BasePrimitive(IFuzzable): """ The primitive base class implements common functionality shared across most primitives. """ @abc.abstractproperty def name(self): pass @property def mutant_index(self): return self._mutant_i...
1723968
from django.contrib import admin from imagekit.admin import AdminThumbnail from common.admin import AutoUserMixin from shapes.models import SubmittedShape, \ MaterialShape, ShapeSubstance, ShapeSubstanceLabel, \ ShapeName, MaterialShapeNameLabel, MaterialShapeQuality from normals.models import ShapeRectifiedN...
1724028
import sys import numpy from OpenGL.GL import * from OpenGL.GLU import * from OpenGL import GLX import pyopencl as cl class raycl(object): def __init__(self, texture, tex_dim, world): self.tex_dim = tex_dim self.world = world self.clinit() self.loadProgram("raytrace.cl") ...
1724081
from isserviceup.models.favorite import Favorite from isserviceup.services import SERVICES def get_favorite_services(user_id): favs = Favorite.objects(user_id=user_id) res = [] for fav in favs: res.append(SERVICES[fav.service_id]) return res def update_favorite_status(user_id, service_id, st...
1724096
from django.shortcuts import render # Create your views here. def index(request): return render(request, 'index.html') def login_page(request): return render(request, 'login.html')
1724098
from dlib import point, points try: import cPickle as pickle # Use cPickle on Python 2.7 except ImportError: import pickle def test_point(): p = point(27, 42) assert repr(p) == "point(27, 42)" assert str(p) == "(27, 42)" assert p.x == 27 assert p.y == 42 ser = pickle.dumps(p, 2) d...
1724138
from enum import Enum class DataType(Enum): ImageryHistoric = "imagery.historic" ImageryAerial = "imagery.aerial" LidarDSM = "lidar.dsm" LidarDEM = "lidar.dem" LidarPointCloud = "lidar.pointcloud"
1724175
import logging from src.channels_manager.apis.twilio_api import TwilioApi from src.channels_manager.channels.channel import Channel from src.utils.data import RequestStatus class TwilioChannel(Channel): def __init__(self, channel_name: str, channel_id: str, logger: logging.Logger, twilio_api: T...
1724219
from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import train_test_split from sklearn.datasets import load_iris from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D # Needed for projection='3d' from sklearn.manifold import TSNE from pylmnn import LargeMarginNeare...
1724271
import socket UDP_IP = '192.168.43.237' UDP_PORT = 8888 UDP_PAYLOAD = 'abcdef' def yes_or_no(question): reply = str(input(question)).lower().strip() if reply[0] == 'y': return 0 elif reply[0] == 'n': return 1 else: return yes_or_no("Please Enter (y/n) ") while...
1724311
from collections import OrderedDict from enum import Enum from .base import Message from ..bot import Bot class AtableMessage(Message): def __init__(self, msgtype: str, atMobiles: list = None, isAtAll: bool = None): super(AtableMessage, self).__init__(msgtype) if atMobiles or isAtAll: ...
1724317
from messagebird.base import Base from messagebird.base_list import BaseList class CustomDetails(Base): def __init__(self): self.custom1 = None self.custom2 = None self.custom3 = None self.custom4 = None class GroupReference(Base): def __init__(self): self.href = No...
1724336
from bc.model.flat import FlatPolicy from bc.model.regression import Regression from bc.model.skills import SkillsPolicy from bc.model.film import FilmPolicy
1724432
import unittest import json from flask import url_for, Response from yapper import create_app, db from yapper.lib.response import json_error, json_success from yapper.blueprints.blog.models import Tag, Category TEST_ACCESS_TOKEN = 'hello' class ModelAPITestCase(unittest.TestCase): def setUp(self): sel...
1724480
from toml import load, dump from . import DefaultConfig, CONFIG_FILE def load_config() -> DefaultConfig: if not CONFIG_FILE.is_file(): return DefaultConfig() with CONFIG_FILE.open('r') as r: data = load(r) return DefaultConfig(data.get('default', {})) def dump_config(config: Default...
1724501
from .residual import IdentityResidualBlock, ResidualBlock from .ppm import PyramidPoolingModule from .classifier import get_classifier, CosineClassifier