text
stringlengths
2
999k
from .about_selia import about_selia from .about_irekua import about_irekua from .contact import about_contact from .about_collections import about_collections
import imaplib2, time, email, os, webbrowser from threading import * detach_dir = '.' # This is the threading object that does all the waiting on # the event class Idler(object): def __init__(self, conn): self.thread = Thread(target=self.idle) self.M = conn self.event = Event() def s...
"""HTML5 Push Messaging notification service.""" import datetime from functools import partial import json import logging import time import uuid from aiohttp.hdrs import AUTHORIZATION import voluptuous as vol from voluptuous.humanize import humanize_error from homeassistant.components import websocket_api from homea...
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) from twitter.common....
from django.core.urlresolvers import reverse from projectroles.constants import get_sodar_constants from projectroles.plugins import ProjectAppPluginPoint from bgjobs.plugins import BackgroundJobsPluginPoint from .models import ( Case, CASE_STATUS_CHOICES, SmallVariantComment, SmallVariantFlags, E...
import threading, requests, random, string class HTTP_DOS: target = "" thread_number = 0 thread_pool = [] proxy_list = [] user_agent_list = [] isStarted = False def __init__(self, target, thread_number, proxy_list = [], user_agent = []): self.target = target ...
""" Parse the wikitext representation of a Wikipedia page into paragraph objects. The goal of this module is to parse wikitext into plaintext in a way that preserves information about link offsets and section information. The default settings are geared towards extracting the offsets for every internal link (i.e. lin...
""" Implementation of a Threaded Modbus Server ------------------------------------------ """ from binascii import b2a_hex import serial import socket import ssl import traceback from pymodbus.constants import Defaults from pymodbus.utilities import hexlify_packets from pymodbus.factory import ServerDecoder from pymo...
from big_muddy_io import BigMuddyIO from flask import render_template from flask import request def big_muddy_clear_all(): big_muddy_io = BigMuddyIO.system() print("clearing console") big_muddy_io.set_all(0) def big_muddy_set_all(): big_muddy_io = BigMuddyIO.system() print("setting console") ...
import logging from enum import Enum, EnumMeta, IntEnum, IntFlag, _decompose from functools import reduce from operator import or_ from typing import Tuple from dis_snek.client.const import logger_name _log = logging.getLogger(logger_name) __all__ = [ "WebSocketOPCodes", "Intents", "UserFlags", "Appl...
from django.db.models import Q from django.test import TestCase from model_mommy import mommy from enemy.models import Enemy from player.models import Player from ..models import Consumable, Weapon class TestModels(TestCase): """ Test Weapon model. """ fixtures = [ 'status/fixtures/fixt...
"""Auto-generated file, do not edit by hand. NC metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_NC = PhoneMetadata(id='NC', country_code=687, international_prefix='00', general_desc=PhoneNumberDesc(national_number_pattern='[2-57-9]\\d{5}', possible_number_pattern...
""" Models for tincture.views.generic tests """ from sqlalchemy import Column, Integer, String from tests.db import Base class Person(Base): __tablename__ = 'people' id = Column(Integer, primary_key=True) name = Column(String(255))
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. """ This module defines the VaspInputSet abstract base class and a concrete implementation for the parameters developed and tested by the core team of pymatgen, including the Materials Virtual Lab, Materials Pr...
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
class Check: def __init__ (self, x, y): self.x = x self.y = y def getX(self): return self.x def getY(self): return self.y def check(): a = Check(1, 2) b = Check(3, 4) a.z = 5 b.z = 6 print(a.x, a.y, a.z) def setup(): PER.setPeriod("Per1", 3)...
def my_function(a, b): """Return a*b """ return a*b
#!/usr/bin/python #! -*- encoding: utf-8 -*- # Python implementation of the bash script written by Romuald Perrot # Created by @vins31 # Modified by YuChen # # this script is for easy use of I23dSFM # # usage : python i23dsfm.py image_dir output_dir # # image_dir is the input directory where images are located # outpu...
class Solution(object): def XXX(self, nums): """ :type nums: List[int] :rtype: int """ x = list(set(nums)) nums[:len(x)] = sorted(x) return len(x)
"""Test the xbox config flow.""" from unittest.mock import patch from openpeerpower import config_entries, data_entry_flow, setup from openpeerpower.components.xbox.const import DOMAIN, OAUTH2_AUTHORIZE, OAUTH2_TOKEN from openpeerpower.helpers import config_entry_oauth2_flow from tests.common import MockConfigEntry ...
from cement import Controller from cement.utils.version import get_version_banner from ..core.version import get_version VERSION_BANNER = """ Add Dependencies and Extensions for Hashicorp Packer %s %s """ % (get_version(), get_version_banner()) class Base(Controller): class Meta: label = 'base' d...
import face_recognition import cv2 IMG_DIR = 'example_01.png' image = face_recognition.load_image_file(IMG_DIR) #加载图像 face_locations = face_recognition.face_locations(image, number_of_times_to_upsample=0, model="cnn") #每一张人脸的位置(top, right, bottom, left) img = cv2.imread(IMG_DIR) for i, bbox in enumerate(face_loca...
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # 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 ...
import asyncio from logging.config import fileConfig from alembic import context from sqlalchemy import engine_from_config, pool from sqlalchemy.ext.asyncio import AsyncEngine from server.config.di import bootstrap, resolve from server.config.settings import Settings from server.infrastructure.database import mapper_...
from django.shortcuts import render from visitantes.models import Visitante def index(request): todos_visitantes = Visitante.objects.all() context = { "nome_pagina": "Início da dashboard", "todos_visitantes": todos_visitantes, } return render(request, "index.html", context)
"""Plotting module for Sympy. A plot is represented by the ``Plot`` class that contains a reference to the backend and a list of the data series to be plotted. The data series are instances of classes meant to simplify getting points and meshes from sympy expressions. ``plot_backends`` is a dictionary with all the bac...
#!/usr/bin/env python import time import os import sys from systemd.daemon import notify, Notification if os.environ.get('SYSTEMD_NOTIFY_ENABLE') == 'true': notify(Notification.STOPPING) notify(Notification.STATUS, "Service stopping...") time.sleep(3) print("Finished prestart") sys.exit(0)
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: task.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import...
import pytest import numpy as np from pathlib import Path from scipy.interpolate import interp1d from scipy.signal import lfilter from scipy.signal import cont2discrete from msdsl.interp.interp import calc_interp_w from msdsl.interp.lds import SplineLDS from msdsl.interp.ctle import calc_ctle_abcd, calc_ctle_num_den fr...
"""BookRecSystem URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class...
import hashlib import logging import os import shutil import sys import tarfile import tempfile import urllib.error import urllib.parse import urllib.request import zipfile from contextlib import closing from urllib.parse import urlparse import boto3 import click import requests import ujson CHUNK_SIZE = 1024 def g...
""" Entrypoint module, in case you use `python -mbittrade`. Why does this file exist, and why __main__? For more info, read: - https://www.python.org/dev/peps/pep-0338/ - https://docs.python.org/2/using/cmdline.html#cmdoption-m - https://docs.python.org/3/using/cmdline.html#cmdoption-m """ from bittrade.cli import m...
# -*- python -*- # Copyright (C) 2009-2016 Free Software Foundation, Inc. # 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 3 of the License, or # (at your option) any later versio...
import sys import getopt import glob import logging from compiler import convert def print_help(): VERSION = 0.1 print( f''' yang2owl version {VERSION}: convert yang modules to owl ontologies usage: yang2owl [-o OUTFILE] [-f FORMAT] [-v LEVEL] [-t TARGET] <-n NAMESPACE> YANG_MODULES \t-n NAMESPACE\...
import datetime import re from decimal import Decimal from django.core.exceptions import FieldError from django.db import connection from django.db.models import ( Avg, Case, Count, DecimalField, DurationField, Exists, F, FloatField, IntegerField, Max, Min, OuterRef, Subquery, Sum, Value, When, ) from django.d...
import os from base64 import b64encode from django.conf import settings from django.utils.encoding import force_str from unittest import mock import pytest from olympia import amo from olympia.amo.tests import addon_factory, root_storage, version_factory from olympia.versions.models import Version, VersionPreview fr...
n = int(input()) count = 0 for i in [10, 5, 1]: if n>=i: q = n//i count += q n = n%i if n==0: print(count) quit()
""" Copyright (c) 2019 Cisco and/or its affiliates. This software is licensed to you under the terms of the Cisco Sample Code License, Version 1.0 (the "License"). You may obtain a copy of the License at https://developer.cisco.com/docs/licenses All use of the material herein must be in accordance wi...
from math import inf from heapq import heappush, heappop import random from collections import defaultdict from .vertices import Vertices from .edges import Edges class Graph: def __init__(self, graph=None, undirected=True, default_v_weight=1.0, default_e_weight=1.0, default_v_absent_weight=inf, default_e_absent_...
# Warning! Servers will not update or merge with the version controlled copy of # this file, so any parameters here, and code that uses them, need to come # without the assumption that they will be present in any given config.py on a # server. Furthermore, on a typical rebuild in a production server, a running # webtil...
import cupy as cp import numpy as np import pytest from cupy.testing import assert_array_almost_equal from numpy.testing import assert_almost_equal from cucim.skimage.filters._gabor import _sigma_prefactor, gabor, gabor_kernel def test_gabor_kernel_size(): sigma_x = 5 sigma_y = 10 # Sizes cut off at +/- ...
import numpy as np import sys sys.path.append("util") sys.path.append("SE") import myparser as myparser import case as case import SE_estimator as SE_estimator import SE_reconstructor as SE_reconstructor import SE_visualizer as SE_visualizer # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~ Parse input and store ...
# Copyright 2011 Nicholas Bray # # 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...
import unittest class MarkovFieldTest(unittest.TestCase): def setUp(self): print('In setUp()') self.fixture = range(1, 10) def tearDown(self): print('In tearDown()') del self.fixture def test(self): self.assertEqual(fun(3), 4) mkf = MarkovField() s...
import logging from . import modifier from .. import get_backend, default_backend, events from ..parameters import unconstrained, ParamViewer log = logging.getLogger(__name__) @modifier(name='shapefactor', op_code='multiplication') class shapefactor: @classmethod def required_parset(cls, sample_data, modifi...
__author__ = "JJ.sven" import json ''' users = { user_account: { pwd: pwd name: name } } ''' users_file_name = 'users.txt' name_key = 'user' pwd_key = 'pwd' users = {} user_file = open(users_file_name, 'r') users = json.load(user_file) user_file.close() def checkAccount(account, pwd): u...
# Copyright (c) 2014 OpenStack Foundation. # # 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 ...
#!/usr/bin/python # -*- coding: utf-8 -*- # ====================================================================== # Copyright 2016 Julien LE CLEACH # # 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 Lic...
# -*- coding: utf-8 -*- # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: # https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code from ccxt.base.exchange import Exchange # ----------------------------------------------------------------------------- try: basestri...
from starlette.applications import Starlette from starlette.middleware import Middleware from starlette.requests import Request from starlette.responses import JSONResponse from starlette.routing import Route from starlette.testclient import TestClient from imia import APIKeyAuthenticator, AuthenticationMiddleware, To...
#!/usr/bin/python3 # # Author: Libor Gabrhel # Program Name: Tweets Collector # Python libraries import tweepy import json import timeit # Loads twitter settings from external file with open('twitter-settings.json', 'r', encoding='utf8') as twitter_settings_content: twitter_settings = json.load(twitter_settings_c...
### # Copyright (c) 2002-2004, Jeremiah Fincher # Copyright (c) 2008-2009, James McCoy # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above ...
from django import forms from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ValidationError from django.utils.translation import gettext as _ from dcim.choices import InterfaceModeChoices from dcim.constants import INTERFACE_MTU_MAX, INTERFACE_MTU_MIN from dcim.forms import I...
import csv import sys import math ## FIXME: zoom levels default_dict = dict( z='', tile_x='', tile_y='', pixel_x='', pixel_y='') def lat_lon_to_tile(lat,lon,z): """convert a Point to tuple (x,y,z) representing a tile in Mercator projection information about converting coordinates ...
import pickle from unittest import mock import numpy as np import pytest import tensorflow as tf from metarl.tf.baselines import GaussianCNNBaseline from metarl.tf.envs import TfEnv from tests.fixtures import TfGraphTestCase from tests.fixtures.envs.dummy import DummyBoxEnv from tests.fixtures.regressors import Simpl...
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # 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 o...
#!/usr/bin/env python3 import os from os.path import isdir, isfile, join, relpath, normpath, dirname, basename from os.path import realpath import sys import zipfile import tempfile import argparse import re OUTPUT_NAME = "libsmp.zip" # default name INCLUDED_DIRS = ["docs"] # directories copied as-is with their tree...
# ---------------------------------------------------------------------- # DefaultObjectItem # ---------------------------------------------------------------------- # Copyright (C) 2007-2021 The NOC Project # See LICENSE for details # ---------------------------------------------------------------------- # Python mod...
"""Auto-generated file, do not edit by hand. GI metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_GI = PhoneMetadata(id='GI', country_code=350, international_prefix='00', general_desc=PhoneNumberDesc(national_number_pattern='[2568]\\d{7}', possible_number_pattern='...
class ComplicateNamespace: @classmethod def init_with_data(cls, **data): instance = cls() for key, value in data.items(): if key in ["id_", "user", "location"]: setattr(instance, key, value) return instance cn = ComplicateNamespace.init_with_data(id...
# Developed by Alexander Bersenev from Hackerdom team, bay@hackerdom.ru """Common functions that make requests to digital ocean api""" import requests import time import json import sys from do_token import TOKEN VERBOSE = True HEADERS = { "Content-Type": "application/json", "Authorization": "Bearer %s" %...
#!/usr/bin/env python # -*- coding:utf-8 -*- """ 写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。 """ def is_odd(obj): new_list = [] for i in range(0, len(obj)): if i % 2 != 0: new_list.append(obj[i]) return new_list li = ['参数0', '参数1', '参数2', '参数3'] opt = is_odd(li) print(opt)
import bisect from collections import deque from algorithms.base_algorithm import BaseAlgorithm class NonPreemptiveSJF(BaseAlgorithm): process_compare_prop = 'remaining_time' def __init__(self, processes): processes = sorted(processes, key=lambda x: (x.arrival_time, x.burst_time)) super().__...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np from numpy.random import RandomState from tensorflow.python.framework import dtypes from tensorflow.python.ops import random_ops import random """ Quarternion layers ...
# type: ignore import logging import colorlog import pytest logger = logging.getLogger(__name__) handler = colorlog.StreamHandler() handler.setFormatter( colorlog.ColoredFormatter( "(%(asctime)s) [%(log_color)s%(levelname)s] | %(name)s | %(message)s [%(threadName)-10s]" ) ) # get root logger logger =...
from unittest import mock from rest_framework.views import APIView from drf_spectacular.validation import validate_schema from tests import generate_schema META = { 'TITLE': 'Spectacular API', 'DESCRIPTION': 'auto-generated spectacular schema for your API', 'TOS': 'https://github.com/tfranzel/drf-spectac...
# -*- coding: utf-8 -*- from setuptools import setup, find_packages with open('requirements.txt') as f: install_requires = f.read().strip().split('\n') # get version from __version__ variable in club/__init__.py from club import __version__ as version setup( name='club', version=version, description='Organize pa...
from sqlalchemy import and_, exists, func from sqlalchemy.orm import Session from src.customer.domain.entities import Customer class SQLACustomerRepository: def __init__(self, sqla_session: Session): self.sqla_session = sqla_session def get_by_id(self, customer_id): return ( self...
import pandas as pd import numpy as np import torch from sklearn.ensemble import RandomForestClassifier from sklearn.impute import SimpleImputer from sklearn.linear_model import LogisticRegression from sklearn.model_selection import cross_val_score from sklearn.preprocessing import MinMaxScaler, KBinsDiscretizer from s...
""" Combine all yaml files listed in _all_.yaml into one file: all.yaml and all.json usage: python _yaml2json.py _all_.yaml Author: Yuhang(Steven) Wang Date: 11-11-2016 """ import json import yaml import sys import copy from plot.tk.fnTK import reduce from plot.tk.dictTK import merge def read_yaml(file): with o...
# Generated by Django 3.0.2 on 2020-05-03 15:45 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('readwith', '0001_initial'), ] operations = [ migrations.CreateModel( ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Aug 23 12:11:15 2020 Modified from the cornstover biorefinery constructed in Cortes-Peña et al., 2020, with modification of fermentation system for 2,3-Butanediol instead of the original ethanol [1] Cortes-Peña et al., BioSTEAM: A Fast and Flexible Pla...
import zmq from threading import Lock, Thread from time import sleep, time import traceback import socket import pickle def get_localhost_ip(): # Get local IP address s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) address = s.getsockname()[0] s.close() return ...
from flask import app from rq import get_current_job from app import db from app.models import Task import sys import time from app.models import User, Post import json from flask import render_template from app.email import send_email def _set_task_progress(progress): job = get_current_job() if job: ...
from dependencies import Injector from dependencies import this class Container(Injector): """A dummy class for tests.""" foo = 1 bar = (this << 1).baz
from sarna.model.enums.base_choice import BaseChoice from sarna.model.enums.language import Language def locale_choice(choice: BaseChoice, lang: Language): translation = getattr(choice, 'translation', None) if translation is None or lang not in translation or not translation[lang]: desc = getattr(choi...
#!python3 # # Copyright (C) 2014-2015 Julius Susanto. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. """ PYPOWER-Dynamics Events Class Sets up and handles events in the simulation """ from pdb import set_trace as bp import numpy as np from pyp...
import datetime import unittest from zoomus import components, util import responses def suite(): """Define all the tests of the module.""" suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(ParticipantsV2TestCase)) return suite class MembersV2TestCase(unittest.TestCase): def setUp(s...
import json import logging import asyncio import aiohttp import base64 import traceback from hailtop.utils import ( time_msecs, sleep_and_backoff, is_transient_error, time_msecs_str, humanize_timedelta_msecs) from hailtop.tls import in_cluster_ssl_client_session from gear import transaction from .globals impo...
import os import pytest FILEPATH = os.path.realpath(__file__) TESTRUNNER_DIR = os.path.dirname(os.path.dirname(FILEPATH)) PYTEST_RC = { 0: "all tests passed successfully", 1: "some of the tests failed", 2: "execution was interrupted by the user", 3: "internal error happened while executing tests", ...
"""Certbot display.""" import logging import os import textwrap import sys import six import zope.interface from certbot import constants from certbot import interfaces from certbot import errors from certbot.display import completer logger = logging.getLogger(__name__) WIDTH = 72 # Display exit codes OK = "ok" ""...
__author__ = "Yaswanth Sai Palaghat" import nltk import sklearn from sklearn.datasets import load_files from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.naive_bayes import MultinomialNB from sklearn.model_selection import trai...
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # Name: duration.py # Purpose: music21 classes for representing durations # # Authors: Michael Scott Cuthbert # Christopher Ariza # # Copyright: Copyright © 2008-2021 Michael Scott...
#ex4: Create a program that asks the user for a number # and then prints out a list of all the divisors of that number. print("Ready for exercise 4?") number = int(input("Give me a number!: ")) x = list(range(2,number + 1)) divisor = [] for i in x: if number % i == 0: divisor.append(i) pr...
# -*- coding: utf-8 -*- # @Time : 2020/10/22 # @Author : Lart Pang # @GitHub : https://github.com/lartpang def cal_mse_loss(seg_logits, seg_gts): assert seg_logits.shape == seg_gts.shape, (seg_logits.shape, seg_gts.shape) seg_probs = seg_logits.sigmoid() loss_map = (seg_probs - seg_gts).pow(2) r...
# coding: utf-8 __author__ = 'cleardusk' import sys import argparse import cv2 import yaml import os import json # from FaceBoxes import FaceBoxes from TDDFA import TDDFA from utils.render import render from utils.render_ctypes import render # faster from utils.depth import depth # from utils.pncc import pncc # from...
from database import app, db, Account from config import pa_username, check_every from flask import render_template import time @app.route('/') def dashboard(): time_file = open('/home/'+pa_username+'/mysite/time.txt', 'r') try: last_updated = int(time_file.read()) except: return('Error ...
from turtle import Turtle class Ball(Turtle): def __init__(self): super().__init__() self.penup() self.shape("circle") self.color("white") self.speed("slowest") self.x_move = 10 self.y_move = 10 def move(self): new_x = self.xcor() + self.x_mo...
from typing import Union import numpy as np import pandas as pd import scipy.stats as st from .exceptions import NotEnoughParticles from .base import Transition from .util import smart_cov def scott_rule_of_thumb(n_samples, dimension): """ Scott's rule of thumb. .. math:: \\left ( \\frac{1}{n} \...
import unittest import forest.db.control import forest.db.database class TestInitialState(unittest.TestCase): def setUp(self): self.database = forest.db.database.Database.connect(":memory:") def tearDown(self): self.database.close() def make_database(self): structure = [ ...
"""Reslowe process model.""" import copy import enum import json import logging import os from django.conf import settings from django.contrib.postgres.fields import ArrayField, JSONField from django.core.exceptions import PermissionDenied, ValidationError from django.core.validators import RegexValidator from django....
import glob import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import tikzplotlib sns.set_style("ticks") plt.rc('font', size=6) plt.rc('text', usetex=False) plt.rc('font', family='serif') def smoother(x, a=0.9, w=10, mode="moving"): if mode == "moving": y = [x[0]]...
# Modules import os import csv # Prompt user for video lookup video = input("What show or movie are you looking for? ") # Set path for file #csvpath = os.path.join("..", "Resources", "netflix_ratings.csv") csvpath = os.path.join("Resources", "netflix_ratings.csv") # Specify the file to write to the movie data. #txtp...
import logging import re from pathlib import Path from typing import Any, Dict, List from hyperstyle.src.python.review.common.subprocess_runner import run_in_subprocess from hyperstyle.src.python.review.inspectors.base_inspector import BaseInspector from hyperstyle.src.python.review.inspectors.common import convert_pe...
# -*- coding: utf-8 -*- """ Created on Fri Jan 10 13:54:18 2020 @author: Mio """ import matplotlib.pyplot as plt import numpy as np from collections import OrderedDict def plot_results(result, nancillas, qubits, p_succes): if result['raw_text'] and len(result['raw_text']) > 1: raise Exception(result['raw_text'])...
""" Django settings for rapid_scene_31457 project. Generated by 'django-admin startproject' using Django 2.2.2. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ im...
""" test parquet compat """ import datetime from distutils.version import LooseVersion from io import BytesIO import os import pathlib from warnings import catch_warnings import numpy as np import pytest from pandas.compat import PY38 import pandas.util._test_decorators as td import pandas as pd import pandas._testi...
dataset_type = "COCODataset" data_root = "data/coco/" img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True ) train_pipeline = [ dict(type="LoadImageFromFile"), dict(type="LoadAnnotations", with_bbox=True), dict(type="RandomFlip", flip_ratio=0.5), dict( ...
import csv import pickle import os import logging from tqdm import tqdm, trange from torch.utils.data import TensorDataset import torch.nn.functional as F import numpy as np import torch from collections import OrderedDict from transformers.utils.dummy_tokenizers_objects import BertTokenizerFast logging.basicConfig(...