content
stringlengths
5
1.05M
# pylint: disable=missing-docstring,invalid-name from multiprocessing import cpu_count from conans import ConanFile class BotanConan(ConanFile): """ The conan.io package of the Botan C++ TLS library """ name = 'Botan' version = '2.1.0' description = ( 'Botan seeks to be a broadly appli...
# -*- coding: utf-8 -*- from web import db, lm from werkzeug.security import generate_password_hash, check_password_hash from flask_login import UserMixin _TABLE_BOOKS = "books" _TABLE_AUTHORS = "authors" _TABLE_REL = "books_authors" _TABLE_USERS = "users" ROLE_ADMIN = 1 ROLE_USER = 0 class Book(db.Mode...
import click import logging import sys from tabulate import tabulate import rbs_oracle_common @click.command() @click.option('--source_host_db', '-s', type=str, required=False, help='The source <host or RAC cluster>:<database>') @click.option('--debug_level', '-d', type=str, default='WARNING', help='Logging level: D...
import numpy as np class Loss(object): def loss(self,y_true,y_pred): return NotImplementedError() def gradient(self,y,y_pred): return NotImplementedError() def acc(selfself,y,y_pred): return 0 class L2(Loss): def __init(self): pass def loss(self,y_true,y_pred): r...
from datetime import datetime, timezone from typing import Any, Dict, Optional from .channels import PartialChannel __all__ = ('Invite',) class Invite: """Representation of a Discord invite.""" code: str channel: PartialChannel inviter: Optional[Dict[str, Any]] expires_at: Optional[datetime] ...
"""Tests for overall io sub-package.""" from dipy import io def test_imports(): # Make sure io has not pulled in setup_module from dpy assert not hasattr(io, 'setup_module')
from app import app from app import presenter from app.celery_config import celery @celery.task def update_last_practiced_before_today(): presenter.update_last_practiced_before_today()
# -*- coding: utf-8 -*- """ Created on Thu Oct 29 17:51:41 2020 @author: cuixingxing """ import sys sys.path.append('..') import numpy as np import torch import torchvision.datasets from torch.utils.data import Dataset, ConcatDataset, DataLoader from verifacation import get_best_threshold from net.model import Backb...
from unittest.mock import call, patch import pandas as pd import pytest import taskframe from taskframe.client import API_URL from taskframe.dataset import CustomIdsLengthMismatch, MissingLabelsMismatch from .test_utils import custom_mock_open, mock_client, mock_open_func class TestClass: @classmethod def s...
from unittest_reinvent.scoring_tests.console_invoked.test_icolos import Test_structural_Icolos
from basinmaker.func.qgis import * from basinmaker.func.pdtable import * from basinmaker.func.rarray import * from basinmaker.utilities.utilities import * import pandas as pd import numpy as np import tempfile from joblib import Parallel, delayed def combine_catchments_covered_by_the_same_lake_qgis( # OutputFolde...
from sympy.stats import Poisson, Beta, Exponential, P from sympy.stats.rv import pspace, ProductPSpace, density from sympy.stats.drv_types import PoissonDistribution from sympy import Symbol, Eq, Ne def test_density(): x = Symbol('x') l = Symbol('l', positive=True) rate = Beta(l, 2, 3) X = Poisson(x, r...
from django.conf.urls import include, url from django.contrib import admin from rest_framework import routers from jmbo.views import ObjectDetail, ObjectList from jmbo import api as jmbo_api from jmbo import urls as jmbo_urls from jmbo.tests import api as tests_api admin.autodiscover() router = routers.SimpleRouter...
# ------------------------------------------------------------------------ # Tools for stain normalisation # ------------------------------------------------------------------------ import numpy as np import cv2 as cv from PIL import Image from staintools.preprocessing.input_validation import is_uint8_image from stain...
import math import matplotlib.pyplot as plt import pyart import numpy as np import cartopy.crs as ccrs import cartopy from .. import retrieval from matplotlib.axes import Axes from cartopy.mpl.geoaxes import GeoAxes GeoAxes._pcolormesh_patched = Axes.pcolormesh def plot_horiz_xsection_quiver(Grids, ax=None, ...
################################################################################ # Copyright (C) 2002-2012 Travis Shirk <travis@pobox.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; ...
from ur_driver import URDriver
# -*- coding: utf-8 -*- """ Unit tests for ThreadSide. """ from __future__ import unicode_literals from __future__ import print_function import logging import os import shutil import tempfile from queue import Queue from unittest import TestCase, SkipTest from unittest.mock import MagicMock from qgis_plutil.thread_su...
from cell import Cell class Action: def __init__(self, jumper, jumpee, hole): self.jumper = jumper self.jumpee = jumpee self.hole = hole def stringify(self): return self.jumper.cell_id, self.jumpee.cell_id
""" Copyright 2019 IBM Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software...
import os import sys import subprocess import ConfigParser from datetime import datetime config = ConfigParser.RawConfigParser() config.read('config.py') DB_USER = config.get('PostgreSQL', 'DB_USER') DB_NAME = config.get('PostgreSQL', 'DB_NAME') BACKUP_PATH = config.get('Backup', 'BACKUP_PATH') + DB_NAME FILENAME_PRE...
class QueryFileHandler: @staticmethod def load_queries(file_name: str): file = open(file_name, 'r') query = file.read() file.close() query_list = [s and s.strip() for s in query.split(';')] return list(filter(None, query_list))
# coding=utf-8 # Copyright 2021 T5 Authors and HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
# A constant to define how much folds should be used N_FOLDS = 5 # A constant to define an epsilon value for avoiding division by zero EPSILON = 1e-10
import datetime from time import strftime """ Convert timestamp in GeoJSON to readable string date. """ def timestamp_to_string(timestamp) -> str: return str(datetime.datetime.fromtimestamp(timestamp/1000)) """ Convert timestamp in GeoJSON to readable string time. """ def timestamp_to_time(timestamp)...
#!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt import sys import cPickle f = open("temp", "r") mydict = cPickle.load(f) print "finish loading" job_id = 10000664882 if "dispatch_job(new)" in mydict[job_id]: last_timestamp = mydict[job_id]["dispatch_job(new)"] else: last_timestamp = my...
# # Copyright (C) 2021 The Delta Lake Project Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
import numpy as np import nltk nltk.download('punkt') from nltk.stem.porter import PorterStemmer stemmer=PorterStemmer() def tokeniser(sentence): return nltk.word_tokenize(sentence) def stem(word): return stemmer.stem(word.lower()) def bag_words(tokenized_sentence, words): sentence_words=[stem(w...
#!/usr/bin/env python """ Refresh README.rst file from long description Should be run from abagen root (containing setup.py) Authored by: @effigies and @matthew-brett for `nibabel`, licensed under MIT (https://github.com/nipy/nibabel/blob/master/COPYING) """ import os import re import runpy readme_lines = [] with o...
import info from Package.CMakePackageBase import * class subinfo(info.infoclass): def setTargets(self): self.description = "a library to manipulate TIFF image files" self.webpage = "http://www.simplesystems.org/libtiff/" self.defaultTarget = '4.0.10' self.targets[self.defaultTarge...
"""Library that contains shared authentication/authorization for Lambda function""" from cloudx_sls_authorization import token_validation from cloudx_sls_authorization import group_membership def authorize_lambda_request(event: dict, tenant_id: str, app_id: [], allowed_roles: [], ldap_ser...
# using h2o Auto ML import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import h2o print(h2o.__version__) from h2o.automl import H2OAutoML h2o.init(max_mem_size='16G') INPUT_DIR = '../../data/processed/' TRAIN = 'train.csv' TEST = 'test.csv' OUTPUT_DIR = '../../models/' print ("importing train ...
"""Zwraca kody państw""" from pygal.maps.world import COUNTRIES def get_country_code(country_name): """Zwraca stosowany przez Pygal dwuznakowy kod państwa przypisany danemu państwu.""" for code, name in COUNTRIES.items(): if name == country_name: return code # Jeżeli państwo nie zosta...
from plenum.common.constants import CURRENT_PROTOCOL_VERSION from plenum.common.messages.node_messages import LedgerStatus, MessageRep from plenum.common.types import f from stp_zmq.zstack import ZStack def test_that_service_fields_not_being_serialized(): """ Checks that service fields of validators, like 't...
from flask import request from flask_jwt_extended import get_jwt_identity, jwt_required from flask_restful import Resource from ...models import WebhookSubscription, User, Client from ...schemas import WebhookSubscriptionSchema from .responses import respond class WebhookSubscriptionListResource(Resource): @jwt...
import pkgutil from django.db import connection from django.db import migrations def add_gcp_views(apps, schema_editor): """Create the GCP Materialized views from files.""" for view in ("", "_by_account", "_by_service", "_by_region", "_by_project"): view_sql = pkgutil.get_data("reporting.provider.gc...
import unittest from aiogram import types from dasbot.interface import Interface class TestInterface(unittest.TestCase): def test_quiz_kb(self): keyboard = Interface.quiz_kb() self.assertIsInstance(keyboard, types.reply_keyboard.ReplyKeyboardMarkup) # TODO: check buttons if __name__ ==...
from django.contrib import admin from . import models admin.site.register(models.Usuario) admin.site.register(models.Grupo)
""" * Assignment: Loop For Counter * Required: yes * Complexity: easy * Lines of code: 5 lines * Time: 5 min English: 1. Iterate over `DATA` 2. Count occurrences of each number 3. Create empty `result: dict[int, int]`: a. key - digit b. value - number of occurrences 4. Iterating over nu...
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distrib...
import ctypes import os import pyperclip import sys import time import urllib.request from InquirerPy.utils import color_print from PIL import Image from pystray import Icon as icon, Menu as menu, MenuItem as item from .config.modify_config import Config_Editor from .filepath import Filepath from ..presence.presence_...
import re from dbgr.meta import __version__ def test_version_format(): assert re.match(r'^[1-9]\.(0|([1-9]\d*))\.(0|([1-9]\d*))$', __version__)
# -*- coding: utf-8 -*- # python imports from __future__ import unicode_literals # lib imports from django.contrib import admin from import_export.admin import ImportExportModelAdmin # project imports from portfolio.models import ( Project, Testimonial, Skill, Role, Timeline ) @admin.register(Project) class Pro...
celsius=float(input("Informe a temperatura em °C: ")) fah=((9*celsius)/5)+32 print("A temperatura de {}°C corresponde a {}F".format(celsius,fah))
# coding: UTF-8 import numpy as np import matplotlib.pyplot as plt #入力波形を表示させる用 import os from sklearn.externals import joblib #モデルを保存・呼び出し ##音声入力関連## import pyaudio # 音声入力 import wave #波形保存 from datetime import datetime #時刻を取得 from time import sleep #delaytime ###### 採 取 す る サ ン プ ル 数 ##### number_of_sample = 10 ...
from django.db import models from django.contrib.auth.models import AbstractUser from django.template.defaultfilters import slugify from django.urls import reverse class TwitterUser(AbstractUser): username = models.CharField(max_length=50, unique=True) display_name = models.CharField(max_length=50) follow...
""" Based on unittests in https://github.com/wndhydrnt/python-oauth2/tree/master/oauth2/test. """ import unittest import mock from pymongo.collection import Collection from weaver.datatype import Service from weaver.store.mongodb import MongodbServiceStore class MongodbServiceStoreTestCase(unittest.TestCase): ...
from datetime import datetime, timedelta from sys import stdout import simplejson import requests from grid.models import Grid from package.models import Package, Commit, Version from searchv2.models import SearchV2 from searchv2.utils import remove_prefix, clean_title def build_1(print_out=True): now = dat...
from acapture.acapture import *
from core.constructs.workspace import ( Workspace, initialize_workspace, load_workspace, ) from ..constructs.environment import Environment, environment_info class local_environment(Environment): """ A logically isolated instance of a project. """ def __init__(self, info: environment_inf...
from .android_project_generator import AndroidProjectGenerator from .android_entity_generator import AndroidEntityGenerator from .android_resource_generator import AndroidResourceGenerator from .android_authentication_generator import AndroidAuthenticationGenerator from .android_component_generator import AndroidCompon...
import concurrent.futures import os import sys import json from reademptionlib.bammerger import BamMerger from reademptionlib.coveragecalculator import CoverageCalculator from reademptionlib.crossalignfilter import CrossAlignFilter from reademptionlib.deseq import DESeqRunner from reademptionlib.fasta import FastaParse...
""" Morph from source to destination face Usage: morpher.py (--src=<src_path> --dest=<dest_path>) [--fps=<frames_per_second>] Options: -h, --help Show this screen. --src=<src_imgpath> Filepath to source image (.jpg, .jpeg, .png) --dest=<dest_imgpath> Filepath to destination image...
# SPDX-License-Identifier: Apache-2.0 """ The following code compares the speed of tensorflow against onnxruntime with a model downloaded from Tensorflow Hub. """ import time import numpy from tqdm import tqdm import tensorflow_hub as hub import onnxruntime as ort def generate_random_images(shape=(100, 100), n=10): ...
# -*- coding: utf-8 -*- import numpy as np def mean_reciprocal_rank(retrievals, labels): rr = [] for (retrieval, label) in zip(retrievals, labels): rank = 0 if label in retrieval: rank = retrieval.index(label) + 1 rr.append(rank / len(retrieval)) return np.mean(rr) de...
phrase = "Don't panic!" plist = list(phrase) print(phrase) print(plist) plist.pop(0) # on't panic! plist.pop(2) # ont panic! plist.pop(6) # ont paic! plist.pop(6) # ont pac! plist.pop(6) # ont pa! plist.pop(6) # ont pa plist.insert(2, plist.pop(3)) # on tpa plist.insert(4, plist.pop(5)) # on tap new_phrase = ...
import torch from torchvision.transforms import * import albumentations as albu import torchvision.transforms as transform def get_training_augmentation(): train_transform = [ albu.HorizontalFlip(p=0.5), albu.VerticalFlip(p=0.5), albu.ShiftScaleRotate(shift_limit=0.0, scale_limit=0.2, rot...
import re import os import glob import numpy as np import random import random import pandas as pd import json from torch.utils.data import Dataset import logging from tqdm import tqdm LOGGER = logging.getLogger(__name__) class QueryDataset_COMETA(Dataset): def __init__(self, data_dir, load_full...
from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import state_ops from tensorflow.python.framework import ops from tensorflow.python.training import optimizer import tensorflow as tf class Grad(optimizer.Optimizer): def __init__(self, learnin...
def cut(arr): for i in range(len(arr)): if "*" not in arr[0]: arr.remove(arr[0]) else: break return arr[::-1] def flip(arr): for i in arr: i = i[::-1] return list(map(list, zip(*arr)))[::-1] def add(arr): if len(arr[0]) % 2 != 0 and (arr[0][0] == ...
import abc from typing import Any, Dict, List, Union import numpy as np from determined import callback from determined.tensorboard.metric_writers import util class MetricWriter(abc.ABC): @abc.abstractmethod def add_scalar(self, name: str, value: Union[int, float, np.number], step: int) -> None: pas...
import pandas as pd import numpy as np import sys import root_numpy import root_pandas df = root_pandas.read_root("../data/raw/cosmic.0008.03420_03427_v4.root",columns=["Channel", "ADC", "Board", "Nhit", "Asic"]) df.to_csv('../data/raw/cosmic.csv.gz', index=False) del df dfm = root_pandas.read_root("../data/raw/mcm...
import logging import json from flask import render_template,request from flask_wtf import FlaskForm from wtforms import fields from wtforms.validators import Required from . import app, estimator, target_names logger = logging.getLogger('app') # DiseaseChoices = [('1', 'Weight Loss Programs'),(1,'High Blood Press...
import ramen.core.node
import pandas as pd import numpy as np from web_constants import * from signatures import Signatures, get_signatures_by_mut_type from project_data import ProjectData, get_selected_project_data from compute_exposures import compute_exposures def scale_exposures(chosen_sigs, projects, mut_type, single_sample_id=None, ...
#!/usr/bin/python # -*- coding: UTF-8 -*- # # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2...
import trio import time from threading import Thread from kivy.app import App from kivy.lang import Builder from kivy.clock import Clock from kivy.properties import NumericProperty, StringProperty, BooleanProperty from kivy_trio.to_kivy import async_run_in_kivy, EventLoopStoppedError, \ AsyncKivyBind from kivy_tr...
#This example uses Python 2.7 and the python-request library. from requests import Request, Session from requests.exceptions import ConnectionError, Timeout, TooManyRedirects import json import os, sys, re, time import urllib, urllib2 from BeautifulSoup import BeautifulSoup import gzip from StringIO import StringIO im...
import os import json import time import schedule from libs import * logger = Logger("/logs/logs.log") data_service_api = DataServiceAPI( os.environ.get("REST_API_BASE_URL"), os.environ.get("REST_API_USER"), os.environ.get("REST_API_PASSWORD"), logger ) db = MongoDB( os.environ.get("MONG...
from __future__ import annotations ## DO NOT REMOVE import yaml import glob from typing import Dict, Union, Tuple, List def find_cfg_file_path() -> Union[str, None]: """Automatically find config file.""" yaml_files = glob.glob('*/*.yml', recursive=True) + glob.glob('*/*.yaml', recursive=True) if len(yam...
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="gabriel10-turbobert", version="0.0.2", author="Robert Degen", author_email="os@turbobert.de", description="Very Simple PDF TypeWriter", long_description=long_description, long_desc...
import logging import pathlib from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext from tikfake.animation_pipeline import AnimationPipeline from tikfake.utils import downloader_video_with_audio, downloader_video_from_link class Bot: _logger = logging.getLogger(__name__) ...
def orient(tile, degrees): out_tile = '' for i in range(len(tile)): for j in range(len(tile[i])): if degrees == 0: out_tile += tile[i][j] elif degrees == 90: out_tile += tile[-(j+1)][i] elif degrees == 180: out_tile += tile[-(i+1)][-(j+1)] elif degrees == 270: out_tile += tile...
""" *B♭ Minor* The key of B♭ minor. """ from ..._mode import MinorKey from ....scale import Diatonic from ._key import BfKey __all__ = ["BfMinor"] class BfMinor( BfKey, MinorKey, Diatonic, ): pass
import logging from adventofcode2021.utils.abstract import FileReaderSolution logger = logging.getLogger(__name__) class Day07: ... class Day07PartA(Day07, FileReaderSolution): def solve(self, input_data: str) -> int: positions = sorted([int(x) for x in input_data.split(",")]) # We need to...
from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Agent, Lead from .forms import LeadForm, LeadModelForm def lead_list(request): leads = Lead.objects.all() context = { "leads": leads } return render(request, "leads/lead_list.html", context) def lead_d...
# external imports import unittest # local imports from tests.util.mock import Mock class TestUtil(unittest.TestCase): def setUp(self): # create a mock self.mock = Mock() def test_must_be_called_more_than_once(self): try: # check that the mock has been called s...
# from __future__ import print_function, absolute_import, division import logging import multiprocessing import shutil import types from distutils.dir_util import copy_tree from pathlib import Path import traceback import batman import foldedleastsquares import lightkurve import numpy as np import matplotlib import ma...
#!/GPFS/zhangli_lab_permanent/zhuqingjie/env/py3_tf2/bin/python ''' @Time : 20/11/05 下午 01:56 @Author : zhuqingjie @User : zhu @FileName: setup.py @Software: PyCharm ''' import setuptools import cv2_ext ''' pip install -i https://pypi.org/simple/ opencv-utf-8 ''' with open("README.md", "r", encoding='utf-8')...
#!/usr/bin/env python # # Public Domain 2014-present MongoDB, Inc. # Public Domain 2008-2014 WiredTiger, Inc. # # This is free and unencumbered software released into the public domain. # # Anyone is free to copy, modify, publish, use, compile, sell, or # distribute this software, either in source code form or as a com...
import tensorflow as tf from nmt.decoders.abstract_decoder import EmbeddingDecoder class BasicRNNDecoder(EmbeddingDecoder): def decode(self, outputs, states, labels, src_sequence_len, mode, params): default_params = self.default_config() if params: default_params.update(**params) ...
# TODO: Refactor this program to improve its readability. LEGAL_DRINKING_AGE = 18 class Person: def __init__(self, my_age): self.age = my_age def enter_night_club(individual): print("Allowed to enter.") if individual.age >= LEGAL_DRINKING_AGE else print( "Enterance of minors is denited.") ...
import boto3 def get_region(): """Return the configured AWS region, or "us-east-1" if undefined.""" return boto3.session.Session().region_name or 'us-east-1' def get_account_id(): """Get the AWS account id for our current credentials.""" return boto3.resource('iam').CurrentUser().arn.split(':')[4] ...
import json import os from database_config import ( DatabaseConfigurationFactory, SapHanaDatabaseConfiguration, ) # IMPORTANT: to run this test successfully you need to set PYTHONPATH before # running nosetest. # export PYTHONPATH=<buildpack-root>/lib class TestCaseSapHanaDryRun: sap_hana_vcap_example ...
# Generated by Django 2.2.1 on 2020-04-28 09:32 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('webapi', '0025_auto_2020...
import numpy as np from time import time from sklearn import manifold def fit_transform(X_highdimensional, n_neighbors=5): ''' Performs LTSA on the given highdimensional dataset. The data needs to be a numpy array of the form (n_samples, n_features). X_highdimensional: (n_samples, n_features) mat...
from radix_sort import radix_sort def test_list_ten_values_random_order( list_ten_values_random_order, list_ten_values_in_order): """Test list of ten values which are in a randomized order.""" assert radix_sort(list_ten_values_random_order) == list_ten_values_in_order def test_list_eleven_values_ran...
"""Unit-tests for the _utils module.""" from pathlib import Path from unittest.mock import Mock from click import ClickException import pytest from pytest_mock import MockFixture from playlist_along._utils import _detect_file_encoding @pytest.fixture def mock__detect_file_encoding(mocker: MockFixture) -> Mock: ...
from kimmo import *
print " *** Interest calculator **** " print x0 = input("Enter the begin value of savings (or debt):") perc = input("Enter yearly interest rate in percent:") years = input("Enter number of years:") x1 = x0*((1.0 + perc/100.0)**years) print print " End amount after",years,"years is",int(x1*100)/100. print
a = "" for c,i in enumerate(input()): if c == 0: a = i else: print(i+a)
if __name__ =='__main__': students = [] check = set() output = [] for i in range(int(input("Enter number of student "))): name = input("Enter Students name ") score = float(input("Enter Students score ")) students.append([name,score]) check.add(score) second_last = ...
""" This module contains a class representing a Type 1 font. This version reads pfa and pfb files and splits them for embedding in pdf files. It also supports SlantFont and ExtendFont transformations, similarly to pdfTeX and friends. There is no support yet for subsetting. Usage:: >>> font = Type1Font(filename) ...
import re from pathlib import Path import dash_core_components as dcc import dash_html_components as html import markdown from .api_doc import ApiDoc from .helpers import ( ExampleContainer, HighlightedSource, load_source_with_environment, ) from .metadata import get_component_metadata HERE = Path(__file...
from django.conf.urls import url, include from django.contrib import admin from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^polls/', include("test_project.polls.urls", namespace="polls")), url(r'^admin/', admin.site.urls), url(r'^accounts/login/$', auth_views.LoginView.as_view(),...
from server.simpleWebServer import runserver if __name__ == "__main__": runserver()
import json import time import elasticsearch from assemblyline.datastore.exceptions import ILMException MAX_RETRY_BACKOFF = 10 def ilm_policy_exists(es, name): conn = es.transport.get_connection() pol_req = conn.session.get(f"{conn.base_url}/_ilm/policy/{name}") if pol_req.status_code in [400, 401, 403...
""" Unit tests for landlab.components.dimensionless.discharge """ import numpy as np from numpy.testing import assert_array_almost_equal from landlab import RasterModelGrid from landlab.components.dimensionless_discharge import DimensionlessDischarge def init_grid(): """initialize grid for testing""" waters...
#!/usr/bin/env python import os from pathlib import Path from dotenv import load_dotenv # 导入环境变量 print('CELERY: load env') env_path = Path('.') / '.flaskenv' if env_path.is_file(): load_dotenv(dotenv_path=env_path, verbose=True) env_path = Path('.') / '.env' if env_path.is_file(): load_dotenv(dotenv_path=env_...
from flask import Flask from flask_bcrypt import Bcrypt app = Flask(__name__) bcrypt = Bcrypt(app) from flask_sqlalchemy import SQLAlchemy import os if os.environ.get("HEROKU"): app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("DATABASE_URL") else: app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///feat...