id
stringlengths
3
8
content
stringlengths
100
981k
1647691
import argparse from datetime import datetime import time import os from tqdm import trange, tqdm from timeit import default_timer as timer import numpy as np import matplotlib.pyplot as plt from collections import deque from perlin import TileableNoise from math import sin, pi from random import random, seed, unifor...
1647713
from pyjackson import deserialize, serialize from pyjackson.decorators import type_field @type_field('type_alias') class Parent: type_alias = 'parent' # also could be None for abstract parents class Child1(Parent): type_alias = 'child1' def __init__(self, a: int): self.a = a class Child2(Par...
1647727
import random import numpy as np import os.path as osp import pickle as pkl import torch from torch_geometric.data import InMemoryDataset, Data class BA3Motif(InMemoryDataset): splits = ['training', 'evaluation', 'testing'] def __init__(self, root, mode='testing', transform=None, pre_transform=None, pre_fil...
1647748
from fever.scorer import evidence_macro_recall, evidence_macro_precision, fever_score import unittest class MaxEvidenceTestCase(unittest.TestCase): def test_recall_partial_predictions_same_groups_zero_score(self): instance = {"label": "supports", "predicted_label": "supports","evidence":[[[None,None,"pa...
1647845
from python_pachyderm import Client as _Client from .mixin.admin import AdminMixin from .mixin.auth import AuthMixin from .mixin.debug import DebugMixin from .mixin.enterprise import EnterpriseMixin from .mixin.health import HealthMixin from .mixin.identity import IdentityMixin from .mixin.license import LicenseMixin ...
1647864
from .poly import FixedPoly import numpy as np import pymunk as pm from .gravity_obj import MOVING_OBJ_COLLISION_TYPE from .img_tool import ImageTool from .funnel import dist import pygame as pg def bucket_touching_handler(arbiter, space, data): locations = arbiter.shapes[1].locations if arbiter.shapes[0].in_...
1647866
import argparse, json import boto3 from jinja2 import Environment, FileSystemLoader """ A bunch of free functions that we use in all scripts. """ def get_jinja_env(config): """ Get a jinja2 Environment object that we can use to find templates. """ return Environment(loader=FileSystemLoader('.')) def json...
1647945
import os import test_utils EXAMPLES_ROOT = test_utils.EXAMPLES_ROOT def test_1(): root_dir = os.path.join(EXAMPLES_ROOT, 'mnist') output_evaluator = test_utils.TemplateOutputEvaluator( b'''\ Device: @numpy # unit: 10 # Minibatch-size: 100 # epoch: 1 epoch main/loss validation/main/loss ...
1647974
from LucidDynamodb import DynamoDb from LucidDynamodb.exceptions import ( TableNotFound ) import logging logging.basicConfig(level=logging.INFO) if __name__ == "__main__": try: db = DynamoDb() db.delete_table(table_name='dev_jobs') logging.info("Table deleted successfully") tabl...
1647985
from test.base import BaseTestCase class ApiSettingsTest(BaseTestCase): __URL = '/api/settings' def setUp(self): pass def test_get(self): response = self.client.get(self.__URL) self.assertEqual(200, response.status_code) self.assertIsNotNone(response)
1648016
from collections import namedtuple from abc import ABCMeta, abstractmethod ## @brief Interface class to be used by modules who want to recieve a notification whenever the date changes class DateChangeListener: __metaclass__ = ABCMeta @abstractmethod def on_date_change( self, new_date ): pass ## @...
1648025
import logging import os.path from flask import request from flask_restplus import Resource, fields from common import api, main log = logging.getLogger(__name__) # This collects the API operations into named groups under a root URL. example_ns = api.namespace('example', description="Example operations") Example...
1648083
from django.urls import path from rest_framework.routers import DefaultRouter from .views import index_template_view, viettel_user_detail_view from .viewsets import ViettelShakeViewSet, ViettelUserViewSet app_name = 'shake' router = DefaultRouter() router.register(r'shake', ViettelShakeViewSet, basename='shake') rou...
1648133
from typing import ( Any, Awaitable, Callable, Iterable, Optional, TypeVar, overload, Protocol, ) from .task import from_result, zero from .util import IDisposable T = TypeVar("T") T_co = TypeVar("T_co", covariant=True) TD = TypeVar("TD", bound=IDisposable) U = TypeVar("U") class Del...
1648143
import json import boto from boto.s3.key import Key MAX_CACHE_TIME = 30 # Local file settings DATA_DIR = "prices/price_data/" SEPARATOR = "_-_" MAX_PRICES = 129600 # AWS S3 settings BUCKET_NAME = "acacia-prices" def prices_get(exchange, pair, num_prices=None, price_ratio=1, cached=True): filename = get_filenam...
1648171
import keyword from pathlib import Path from django.core.management import CommandError from django.template.loader import get_template from ._base import BaseGenerateCommand from ...utils import pascalcase TEMPLATES = { "_reflex.py": "sockpuppet/scaffolds/reflex.py", "_controller.js": "sockpuppet/scaffolds/...
1648177
import json from pathlib import Path from typing import Any, Dict from tqdm import tqdm from pokeapi_ditto.common import apply_base_url def _is_id(s: str): try: int(s) return True except ValueError: return False def _dump(path: Path, content: Any): if not path.parent.exists(): ...
1648180
import six import os, errno, logging, inspect from sqlalchemy.orm.session import object_session from sqlalchemy.orm.interfaces import MapperProperty from sqlalchemy.orm.attributes import get_history from sqlalchemy.orm.util import class_mapper from sqlalchemy import event from sqlalchemy.util import set_creation_order ...
1648194
import unittest import rem import six from six.moves import cPickle as pickle class T07(unittest.TestCase): """Checking internal REM structures""" def testTagWrapperSerialization(self): import pickle tag = rem.Tag("test") wrapOrig = rem.storages.TagWrapper(tag) wrapDesc = pick...
1648214
from django.conf import settings from django.core.management.base import BaseCommand, CommandError from django.utils import timezone from django.template.loader import get_template from django.template import Context from django.forms import EmailField from django.core.exceptions import ValidationError from django.util...
1648282
from flask import * from functools import wraps def login_required(f): @wraps(f) def wrap(*args, **kwargs): if 'logged_in' in session: return f(*args, **kwargs) else: return redirect(url_for('user.login_route')) return wrap
1648305
import unittest import numpy as np from dacbench import AbstractEnv from dacbench.benchmarks import CMAESBenchmark from dacbench.wrappers import ObservationWrapper class TestObservationTrackingWrapper(unittest.TestCase): def get_test_env(self) -> AbstractEnv: bench = CMAESBenchmark() env = bench....
1648315
from __future__ import print_function import matplotlib matplotlib.use('Agg') import numpy as np import matplotlib.pyplot as plt import sys sys.path.insert(0,'../powderday/agn_models/') from hopkins import agn_spectrum as hopkins_agn from astropy import units as u from astropy import constants as const import h5py fr...
1648322
from django.db.models import Count from django.http import JsonResponse from rest_framework.views import APIView from std_bounties.models import Bounty, Token from std_bounties.serializers import TokenSerializer class Tokens(APIView): @staticmethod def get(self): token_qs = {} result = [] ...
1648332
import numpy as np from PuzzleLib import Config from PuzzleLib.Backend import gpuarray from PuzzleLib.Modules.Module import ModuleError from PuzzleLib.Modules.DeconvND import DeconvND class Deconv1D(DeconvND): def __init__(self, inmaps, outmaps, size, stride=1, pad=0, dilation=1, postpad=0, wscale=1.0, useBias=Tru...
1648345
from termpixels.pixeldata import PixelData from time import perf_counter # Boxes _BOX_T = 0 _BOX_B = 1 _BOX_L = 2 _BOX_R = 3 _BOX_TL = 4 _BOX_TR = 5 _BOX_BL = 6 _BOX_BR = 7 BOX_CHARS_ASCII = "--||++++" BOX_CHARS_LIGHT = "──││┌┐└┘" BOX_CHARS_LIGHT_ARC = "──││╭╮╰╯" BOX_CHARS_HEAVY = "━━┃┃┏┓┗┛" BOX_CHARS_DOUBLE = "══║║╔...
1648352
import FWCore.ParameterSet.Config as cms from DQMOffline.PFTau.PFClient_cfi import pfClient, pfClientJetRes #from DQMOffline.PFTau.PFClient_cfi import * pfJetClient = pfClient.clone( FolderNames = ['PFJetValidation/CompWithGenJet'], HistogramNames = ['delta_et_Over_et_VS_et_'], CreateProfilePlots = True, ...
1648382
from tests import OkTestCase from server.models import db, Assignment, Backup, Message, User from server import utils class TestDownload(OkTestCase): def _add_file(self, filename, contents): self.setup_course() email = '<EMAIL>' self.login(email) self.user = User.lookup(email) ...
1648395
import json from ..Ad.sub.AdFieldObject import AdFieldObject class AdObject: def __init__(self, json_def): if type(json_def) is str: json_def = json.loads(json_def) s = json_def self.ad = None if 'ad' not in s else AdFieldObject(s['ad']) self.adattr = None if 'adattr' no...
1648430
Python 3.4.4 (v3.4.4:737efcadf5a6, Dec 20 2015, 20:20:57) [MSC v.1600 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> >>> import os import glob import time os.system('modprobe w1-gpio') os.system('modprobe w1-therm') base_dir = '/sys/bus/w1/devices/' device_folder = glob...
1648439
import unittest import copy import torch import os import shutil import csv import tempfile import trojai.modelgen.config as tpmc import trojai.modelgen.architecture_factory as tpmaf import trojai.modelgen.data_manager as tpmd import trojai.modelgen.architectures.mnist_architectures as tpma import trojai.modelgen.defa...
1648465
import unittest from unittest.mock import MagicMock from git_gopher.Fzf import Fzf from git_gopher.CommandRunner import CommandRunner from git_gopher.GitDataGetter import GitDataGetter from git_gopher.HistoryCommandRunner import HistoryCommandRunner from git_gopher.StashMessage import StashMessage class TestStashMessa...
1648493
from submission import Submission class SilvestreSubmission(Submission): def run(self, s): """ :param s: input in string format :return: solution in integer format """ result = 0 char_list = list(s) char_list.append(char_list[0]) for i, char in enum...
1648497
import unittest class CameraSimulatorTest(unittest.TestCase): def test_get_camera_info_msg(self): pass
1648558
import glob from os.path import split import os rel = "" if os.getcwd().endswith("scripts") else "./scripts/" HEADER_PATH = rel + 'README_HEADER.md' EXAMPLES_PATH = rel + "../examples" README_DESTINATION = rel + "../README.md" TEST_FILE_PATH = rel + "../pytago/tests/test_core.py" DISABLED_EXAMPLES = { "iterunpac...
1648616
import sys sys.path.append("..") import os import math import torch import torch.nn as nn import torchvision import model.E.E_Blur as BE import model.E.E_PG as BE_PG import model.E.E_BIG as BE_BIG from model.utils.custom_adam import LREQAdam import lpips from metric.grad_cam import GradCAM, GradCamPlusPlus, GuidedBackP...
1648636
import datetime as dt from dateutil.relativedelta import relativedelta import numpy as np import pandas as pds # Orbits period is a pandas.Timedelta kwarg, and the pandas repr # does not include a module name. Import required to run eval # on Orbit representation from pandas import Timedelta # noqa: F401 import pytes...
1648704
import os import json import kfp import fire from datetime import datetime def update_op_project_id_img(op): project_id = os.getenv('PROJECT_ID') if not project_id: raise Exception('Please set an $PROJECT_ID env value.') img = op.component_spec.implementation.container.image img = img.format(P...
1648749
import numpy as np import matplotlib.pyplot as plt import pandas as pd def read_data(input_file, index): # Read the data from the input file input_data = np.loadtxt(input_file, delimiter=',') # Lambda function to convert strings to Pandas date format to_date = lambda x, y: str(int(x)) + '-' + str(int(...
1648796
from typing import List import pandas as pd from ..util import io __all__ = [ "read_acc_file_into_df", "read_bvp_file_into_df", "read_eda_file_into_df", "read_hr_file_into_df", "read_ibi_file_into_df", "read_temp_file_into_df", ] def read_hr_file_into_df(filepath_or_buffer) -> pd.DataFrame:...
1648829
import os import torch import torch.nn as nn import torch.nn.functional as F from .modules import encoder, bts from ..utils import load_weights from utils import log_info class Model(nn.Module): def __init__(self, dataset, max_depth, model_weights_file, seed=None): super(Model, self).__init__() i...
1648839
from __future__ import absolute_import from kafka.protocol.api import Request, Response from kafka.protocol.types import Array, Int8, Int16, Int32, Int64, Schema, String UNKNOWN_OFFSET = -1 class OffsetResetStrategy(object): LATEST = -1 EARLIEST = -2 NONE = 0 class OffsetResponse_v0(Response): API...
1648841
import logging import os import png logger = logging.getLogger('dump-asc-16') font_file_path = 'assets/hzk-fonts/ASC16' outputs_dir = 'outputs/png/asc/16/' asc_glyph_bytes_length = 8 * 16 // 8 def _iter_ascii(font_file, num_start, num_stop): count = 0 for num in range(num_start, num_stop): c = chr(n...
1648849
from rapid_response_kit.utils.clients import twilio, pusher_connect from rapid_response_kit.utils.helpers import ( parse_numbers, echo_twimlet, twilio_numbers, check_is_valid_url ) from clint.textui import colored from twilio.twiml import Response from pusher import Pusher from flask import render_temp...
1648855
import unittest import numpy as np import bayesnet as bn class TestProduct(unittest.TestCase): def test_product(self): arrays = [ 1, np.arange(1, 5), np.arange(1, 7).reshape(2, 3), np.arange(1, 7).reshape(2, 3, 1) ] axes = [ None...
1648864
from neuralogic import get_neuralogic, get_gateway from neuralogic.core.settings import SettingsProxy from typing import List class Sources: @staticmethod def from_settings(settings: SettingsProxy) -> "Sources": neuralogic = get_neuralogic() sources = neuralogic.cz.cvut.fel.ida.setup.Sources(s...
1648867
from KratosMultiphysics import * from KratosMultiphysics.FluidDynamicsApplication import * import KratosMultiphysics.KratosUnittest as KratosUnittest import random class AdjointVMSElement2D(KratosUnittest.TestCase): def setUp(self): self.delta_time = 1.0 # create test model part self.mode...
1648889
from specter import Spec, expect from alchemize import Attr, JsonMappedModel from alchemize.mapping import get_key_paths, get_normalized_map class TestModel(JsonMappedModel): __mapping__ = { 'thing': Attr('thing', str), 'old_style': ['thing', str], } class SampleMapping(JsonMappedModel): ...
1648890
from plugins.base import Base from utils import fmt import gevent class Welcome(Base): def on_member_join(self, guild, member): welcome_message = fmt(guild.storage.get('welcome_message'), server=guild.name, user=member.mention) announcem...
1648895
import logging import click from regparser.diff.tree import changes_between from regparser.index import dependency, entry logger = logging.getLogger(__name__) @click.command() @click.argument('cfr_title', type=int) @click.argument('cfr_part', type=int) def diffs(cfr_title, cfr_part): """Construct diffs between...
1648896
import numpy as np import pickle class CorrelationList: def __init__(self, shape): self._sumx = np.zeros(shape, dtype=float) self._sumy = np.zeros(shape, dtype=float) self._sumxy = np.zeros(shape, dtype=float) self._sumxsq = np.zeros(shape, dtype=float) self._sumysq = np.ze...
1648966
from haystack import indexes from regcore import models class DocumentIndex(indexes.Indexable, indexes.SearchIndex): """Search index used by Haystack""" doc_type = indexes.CharField(model_attr='doc_type') version = indexes.CharField(model_attr='version', null=True) label_string = indexes.CharField(mo...
1648969
from passlib.hash import sha512_crypt s = "penguins" for ip in range(1000,2000): sp = str(ip) p = sp[1:] h = sha512_crypt.using(salt=s, rounds=5000).hash(p) if h[12:16] == "PcSL": print p, h
1649014
from pypika import ( Parameter, PostgreSQLQuery, Table, terms, Dialects, ) from pypika.terms import Node from pypika.utils import format_quotes from .base import Database class DateTrunc(terms.Function): """ Wrapper for the PostgreSQL date_trunc function """ def __init__(self, fi...
1649047
memory = {} """ The N'th Fibonacci number is F(n) = F(n-1) + F(n-2) with F(0) = 1, F(1) = 1 """ def fib(n): global memory if n not in memory: if n >= 2: memory[n] = fib(n-2) + fib(n-1) else: memory[n] = 1 return memory[n]
1649067
from typing import Any from gogettr.api import ApiClient class Capability: """Provides base functionality for the individual capabilities.""" def __init__(self, client: ApiClient): self.client = client def pull(self, *args, **kwargs) -> Any: """Pull the desired data from GETTR.""" ...
1649077
from django.urls import path, include from django.conf import settings from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf.urls.static import static urlpatterns = [ path('api/', include('api.urls')) ] if settings.DEBUG: urlpatterns += staticfiles_urlpatterns() # urlpattern...
1649082
from torch.utils.data import Dataset import torchvision.transforms as transforms import torchvision.transforms.functional as TF from PIL import Image import os import random class TumorDataset(Dataset): """ Returns a TumorDataset class object which represents our tumor dataset. TumorDataset inherits from t...
1649084
import numpy as np import pandas as pd import pytest from activitysim.abm.models.util.trip import get_time_windows @pytest.mark.parametrize("duration, levels, expected", [(24, 3, 2925), (24, 2, 325), (24, 1, 25), (48, 3, 20825), (48, 2, 1225), (48, 1, 49)]) def test...
1649098
from typing import Any, Optional class ImportErrorMixin: """ Mixin class which always raises :class:`ImportError`. Subclasses can modify the message by overriding `__import_error_message__`. Parameters ---------- args Ignored. kwargs Ignored. Raises ------ Im...
1649099
from django.conf.urls import url from jekyllnow.views import ( JekyllNowTheme ) urlpatterns = [ url(r'^jn-init/$', JekyllNowTheme.as_view(), name='jn-init'), ]
1649105
class StreamingAPIError(Exception): def __init__(self, code: int, message: str): self.code = code self.text = message self.message = f"[{code}] {message}" super().__init__(self.message)
1649119
import spacy # ja_core_news_sm モデルを読み込む nlp = spacy.load("ja_core_news_sm") # パイプラインの名前を出力 print(nlp.pipe_names) # (name, component) のタプルからなるパイプライン情報を表示 print(nlp.pipeline)
1649140
from .rman_translator import RmanTranslator from ..rman_sg_nodes.rman_sg_runprogram import RmanSgRunProgram class RmanRunProgramTranslator(RmanTranslator): def __init__(self, rman_scene): super().__init__(rman_scene) self.bl_type = 'PROCEDURAL_RUN_PROGRAM' def export(self, ob, db_name): ...
1649181
import django_filters from django.db.models import Q from django.forms.widgets import CheckboxSelectMultiple from api.models import LauncherConfig, Launch, Location, Pad class LaunchListFilter(django_filters.FilterSet): search = django_filters.CharFilter(field_name='search', label="Search", method='filter_by_all...
1649185
from asyncio import sleep from typing import Callable, Coroutine, Any Handler = Callable[..., Coroutine[Any, Any, Any]] async def delayed_task( seconds: int, handler: Handler, do_break: bool = False, *args, **kwargs ): while True: await sleep(seconds) await handler(*args, **kwargs) i...
1649194
import sys sys.path.append("../../") from appJar import gui with gui() as app: with app.labelFrame("framer"): app.label('hello world') with app.labelFrame("framer"): app.label('hhello world')
1649196
class UdpPacket: def __init__(self, length: int, payload: bytearray): self.length = length self.payload = payload
1649222
import os import re import sys import pwd import time import socket import platform import struct import fcntl try: import urllib2 except ImportError: import urllib.request as urllib2 import subprocess try: import lsb_release except ImportError: lsb_release = None from datetime import datetime from coll...
1649227
import pytest @pytest.fixture def params_parser(dummy_request): from snosearch.parsers import ParamsParser from snovault.elasticsearch import ELASTIC_SEARCH from elasticsearch import Elasticsearch dummy_request.environ['QUERY_STRING'] = ( 'type=Experiment&assay_title=Histone+ChIP-seq&award.pro...
1649279
from __future__ import division # TODO: Add generator that considers lat/long (distance to North and South poles). class Moisture: def generate(self, map_obj): # Calculate moisture. Freshwater sources spread moisture: rivers # and lakes (not oceans). Saltwater sources have moisture but do ...
1649285
from .cbl_type import CBLType, CBLTypeInstance, CBLTypeMeta from .containers import Temporary from .function_type import InstanceFunctionType import cmd_ir.instructions as i class StructTypeInstance(CBLTypeInstance): def __init__(self, compiler, this, var_members, func_members, func_properties): super()....
1649297
import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import ( cross_val_score, train_test_split, ShuffleSplit, ) from sklearn.metrics import accuracy_score from sklearn.metrics import f1_score, recall_score from sklearn.metrics import confusion_matrix import ...
1649309
from sublime_plugin import WindowCommand from ..libraries import serial from ..libraries.tools import get_setting class DeviotCleanConsoleCommand(WindowCommand): monitor = None def run(self): self.monitor.clean_console() def is_enabled(self): port_id = get_setting('port_id', None) ...
1649324
from asgi_webdav.constants import ( DAVPath, ) def test_basic(): path = DAVPath("/a/b/c") assert path.raw == "/a/b/c" assert path.parts == ["a", "b", "c"] assert path.count == 3 assert path.parent == DAVPath("/a/b") assert path.name == "c" assert path.startswith(DAVPath("/a/b")) a...
1649340
import asyncio import logging from time import sleep from sanic import Sanic from sanic.exceptions import ServiceUnavailable from sanic.log import LOGGING_CONFIG_DEFAULTS from sanic.response import text response_timeout_app = Sanic("test_response_timeout") response_timeout_default_app = Sanic("test_response_timeout...
1649361
from bitmovin_api_sdk.encoding.encodings.muxings.fmp4.fmp4_api import Fmp4Api from bitmovin_api_sdk.encoding.encodings.muxings.fmp4.customdata.customdata_api import CustomdataApi from bitmovin_api_sdk.encoding.encodings.muxings.fmp4.information.information_api import InformationApi from bitmovin_api_sdk.encoding.encodi...
1649363
from __future__ import unicode_literals SEQUENCE = [ 'old_tool_model', 'tool_working_directory_required', ]
1649370
from IPython.display import HTML def print_frames(dataframes): if not isinstance(dataframes, tuple): return dataframes border_style = u'\"border: none\"' cells = [u'<td style={}> {} </td>'.format(border_style, df._repr_html_()) for df in dataframes] table = '''<table style={}> <tr style={...
1649431
from .ner import * from .multi_choice import * from .sequence_classification import * from .record_qa import * from .masked_language_model import *
1649435
import doctest import insights.parsers.octavia as octavia_module from insights.parsers.octavia import OctaviaConf, VALID_KEYS from insights.tests import context_wrap CONF_FILE = """ [DEFAULT] # Print debugging output (set logging level to DEBUG instead of default WARNING level). debug = False # Plugin options are hot...
1649630
from core.models import Person from ..models import Enrollment def enrollment_event_box_context(request, event): enrollment = None is_enrollment_admin = False if request.user.is_authenticated: is_enrollment_admin = event.enrollment_event_meta.is_user_admin(request.user) try: ...
1649683
from troposphere import ( Ref, Output ) from stacker.blueprints.base import Blueprint from stacker.util import load_object_from_string class GenericResourceCreator(Blueprint): """ Generic Blueprint for creating a resource Example config - this would create a stack with a single resource in it, an ec...
1649700
from pyparrot.Anafi import Anafi from pyparrot.DroneVisionGUI import DroneVisionGUI from pyparrot.Model import Model import cv2 WRITE_IMAGES = False class UserVision: def __init__(self, vision): self.index = 0 self.vision = vision def save_pictures(self, args): img = self.vision.get...
1649723
class Config(object): """ Model Configuration [use_img_feat] options control how we use image features None not using image features (default) "concat_bf_lstm" concatenate image feature before LSTM "concat_af_lstm" concatenate image feature after LSTM "...
1649770
import codecs, ssl, chardet from urllib.request import urlopen, Request db = 'db.txt' def get(src): with urlopen(Request(src, None, {'User-Agent': ''}), context=ssl._create_unverified_context()) as site: text = site.read() with codecs.open(db, 'w', 'utf-8') as file: print(text.decode(chardet.detect(text)['enc...
1649779
from typing import List from typing import Union import pystac from gcsfs import GCSFileSystem from satextractor.models import ExtractionTask from satextractor.models import Tile from satextractor.scheduler import create_tasks_by_splits def get_scheduler(name, **kwargs): return eval(name) def gcp_schedule( ...
1649789
from __future__ import absolute_import from __future__ import division from __future__ import print_function import ray from collections import namedtuple import numpy as np import random from ray.rllib.agents.trainer import Trainer from ray.rllib.models.catalog import ModelCatalog from ray.rllib.policy.policy impor...
1649866
from django.shortcuts import get_object_or_404 from facebook import GraphAPI, GraphAPIError from raven.contrib.django.raven_compat.models import client from canvas.exceptions import InvalidFacebookAccessToken from canvas.templatetags.jinja_base import render_jinja_to_string from canvas.view_guards import require_staff...
1649881
import numpy as np from itertools import product import depthai as dai from math import gcd from pathlib import Path from FPS import FPS, now import cv2 import os, sys, re SCRIPT_DIR = Path(__file__).resolve().parent DEFAULT_YUNET_MODEL = str(SCRIPT_DIR / "models/face_detection_yunet_180x320_sh4.blob") def find_isp_...
1649899
from gevent.pywsgi import WSGIServer from app import app, db db.create_all() http_server = WSGIServer(('', 9090), app) http_server.serve_forever()
1649905
class Instruccion: '''This is an abstract class''' class Imprimir(Instruccion) : ''' Esta clase representa la instrucción imprimir. La instrucción imprimir únicamente tiene como parámetro una cadena ''' def __init__(self, cad) : self.cad = cad class Mientras(Instruccion) : ...
1649909
import optimizer_plots as plots import cPickle as pickle import copy import json import math import os import shutil import time import warnings import sys import numpy as np import skopt from scipy.optimize import fmin_l_bfgs_b from six.moves import configparser from sklearn import clone from sklearn.externals.joblib...
1649914
import basevcstest class TestVCSLambert(basevcstest.VCSBaseTest): def testLambert(self): s = self.clt("clt") iso = self.x.createisofill() p = self.x.createprojection() p.type = "lambert" iso.projection = p self.x.plot(s(latitude=(20, 60), longitude=(-140, -20)), ...
1649940
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns def assignHost(VCs_query,level): # Host range at the species level gVC_tax={} for vc in VCs_query: gVC_tax[vc]=[] for i in VCs_query: idx=int(i.split('_')[1]) for uv in VCs[idx]: ...
1649953
import six def brackets_check(pattern): """ Check whether the pattern is missing square brackets, in a way which does not require the usual parsing. This is a light hack to provide an improved error message in this particular case. :param pattern: A STIX pattern string :return: True if the p...
1650002
class DBParser(): def __init__(self): print("----------Start DBParser ----------") self.query = None def split_query(self, query): return query.strip().replace("\n", " ").split() def get_index(self, statement): return self.query.index(statement) if statement in self.query else None def parse(self, ...
1650018
class StrictVersion: def __init__(self, version): self.version = version __all__ = ['VERSION'] VERSION = StrictVersion('0.32')
1650029
import unittest import groundstation.objects.object_factory as object_factory from groundstation.objects.base_object_pb2 import BaseObject, \ ROOT as TYPE_ROOT, \ UPDATE as TYPE_UPDATE, \ UNSET as TYPE_UNSET from groundstation.objects.root_object_pb2 import RootObject from groundstation.objects.update_obj...
1650043
from jupyter_server.base.handlers import APIHandler from jupyter_server.utils import url_path_join import tornado from tornado.web import StaticFileHandler from .dictionaries import discover_dictionaries, dictionaries_to_url from ._version import __version__ class LanguageManagerHandler(APIHandler): lang_dicti...