content stringlengths 5 1.05M |
|---|
import Rhino.Geometry as rg
# import ghpythonlib.components as gh
import math
from generalFunctions import *
from simpleStartStop import *
from copy import deepcopy as dc
# import Rhino.DocObjects as rd
class Brick(object):
def __init__(self, shell = None, pins = None, patterns = None, l_type = None, p_type = Non... |
from UdonPie import UnityEngine
from UdonPie.Undefined import *
class CharacterValidation:
def __new__(cls, arg1=None):
'''
:returns: CharacterValidation
:rtype: UnityEngine.CharacterValidation
'''
pass
|
from neatrader.trading.engine import TradingEngine
from neatrader.trading.stocksplit import StockSplitHandler
from neatrader.trading.simulator import Simulator
|
import os
import json
import pytest
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
metricbeat_modules = ['cpu',
'load',
'diskio',
'files... |
#
#
# Test of convergence diagnostics
#
#
from __future__ import with_statement
from numpy.testing import assert_equal, assert_array_equal
from numpy.testing import assert_approx_equal, TestCase
import unittest
import nose
import numpy as np
import pymc
import pymc.examples.weibull_fit as model
import os
import warnin... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from compas.geometry import bounding_box
from compas.geometry import bounding_box_xy
__all__ = [
'mesh_bounding_box',
'mesh_bounding_box_xy',
]
def mesh_bounding_box(mesh):
"""Compute the (axis... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="metabu",
version="0.0.1",
author="Herilalaina Rakotoarison, Louisot Milijaona, Andry Rasoanaivon, Michele Sebag, and Marc Schoenauer",
author_email="herilalaina.rakotoarison@inria.fr, milijao... |
from challenges.data_structure.graph.graph import *
import pytest
# Node can be successfully added to the graph
def test_add_vertex():
g = Graph()
zero = Vertex(0)
actual = g.add_vertex(zero)
expected =[]
assert actual == expected
# An edge can be successfully added to the graph
def test_add_ed... |
# -*- coding: utf-8 -*-
from datetime import datetime
from MOEXBondScrinner import BondsMOEXDataRetriever, BondsMOEXFilter, BondsCustomCalculationAndFilter, BondsCSVWriter
# Set personal parameters
filter_description_dict = {'max_bond_value': 100000,
'max_expiration_date': datetime(2030, 1, ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 26 09:00:01 2021
@author: mike
"""
import os
import xarray as xr
# import cdsapi
######################################
### Parameters
save_path = '/media/sdb1/Data/ecmwf/era5-land'
parameter = '2m_temperature'
dem = 'geo_1279l4_0.1x0.1.grib2_v4_... |
from ants_impl import WorkerAnt, SoldierAnt, NurseAnt
from core.ant_queen import AntQueen
if __name__ == '__main__':
ants = [WorkerAnt(), SoldierAnt(), NurseAnt()]
ant_queen = AntQueen(ants)
ant_queen.do_morning_routine() |
from dataset.data_model import HandDataModel
def unpack_data(results, is_eval = False):
joint_out = results['joint']
heatmap = None
heatmap_true = None
if not is_eval:
heatmap = results['heatmap']
heatmap_true = results['heatmap_true']
heatmap_reprojected = results['heatmap_repr... |
# Standard library
import warnings
# Third-party
import astropy.units as u
from astropy.coordinates import (Galactic, CartesianRepresentation,
SphericalRepresentation, CartesianDifferential,
SphericalDifferential,
Spheri... |
class QueueException(Exception): pass
class QueueWriteException(QueueException): pass
class QueueReadException(QueueException): pass
class QueueRemoveException(QueueException): pass
class DataStoreGetException(QueueException): pass
class DataStorePutException(QueueException): pass
class DataStoreTimeout(QueueExceptio... |
from datetime import datetime, timedelta
from enum import Enum
from ..bits import Bits
# https://www.navcen.uscg.gov/?pageName=AISMessagesA
class NavigationStatus(Enum):
USING_ENGINE = 0
AT_ANCHOR = 1
NOT_UNDER_COMMAND = 2
RESTRICTED_MANOEUVERABILITY = 3
... |
import pandas as pd
import logging
from pathlib import Path
from quarantine.model.qobject import *
from quarantine.model.qlocation import *
class QMapFactory():
def __init__(self):
pass
@staticmethod
def load(file_name: str):
# Create path for the file that we are going to load
... |
# + polarisation
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from IPython.display import clear_output
from matplotlib import animation
import scipy as sp
import mpl_toolkits.mplot3d.axes3d as p3
figure = plt.figure(figsize=(9,9))
axis = p3.Axes3D(figure)
plot = list()
d... |
# py_vsk/py_vsk.py
# exec(open('py_vsk/py_vsk.py').read())
# 0.0.5
from scipy.stats import norm, chisquare, ks_2samp, multivariate_normal
from scipy.optimize import minimize, minimize_scalar
from statsmodels.distributions import empirical_distribution
from py_mob import qcut
import numpy
########## 01. vsk_mle() ###... |
import youtube_dl
from pathlib import Path
import os
def run():
video_url = input("please enter youtube video url:")
# make download directory directory
Path.cwd().joinpath("download").mkdir(parents=True, exist_ok=True)
video_info = youtube_dl.YoutubeDL().extract_info(
url=video_url, download=... |
# MIT License
#
# Copyright (C) IBM Corporation 2018
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge... |
from .url import url,index_url
import urllib,json
def query_url(obj_type,query):
search_url = '_search'
return index_url.add_path(obj_type).add_path(search_url).add_query(query)
def query(url):
return json.loads(urllib.request.urlopen(url.to_url()).read().decode("utf8"))
if __name__ == '__main__':
... |
import numpy as np
import pandas as pd
import unittest
import io
import sys
from context import grama as gr
from context import data
## Test the built-in datasets
##################################################
class TestData(unittest.TestCase):
def setUp(self):
pass
def test_make(self):
... |
import unittest
from app.models import Articles
class ArticlesTest(unittest.TestCase):
'''
Test Class to test the behaviour of the Movie class
'''
def setUp(self):
'''
Set up method that will run before every Test
'''
self.new_article = Articles('CNN','Peter Polle','The... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="slidingwindow_generator", # Replace with your own username
version="1.0.6",
author="Jaeyeon Kim",
author_email="anencore94@gmail.com",
description="Generate Sliding Window from Time Serie... |
from functools import reduce
from itertools import filterfalse
def calculate_max_until_now(endpoint_map, logline):
try:
if logline[9].strip('-\n') != '':
endpoint_map[logline[6]]['count'] += 1.0
endpoint_map[logline[6]]['average'] = float(
(endpoint_map[logline[6]][... |
from items import Item
import random
class Consumable(Item):
def __init__(self, name, description, value, health):
self.health = health
super().__init__(name, description, value, health)
def __str__(self):
return "{}\n=====\n{}\nValue: {}\nDamage: {}\nDamage: {}".format(self.name, self... |
from rest_framework import permissions
SAFE_METHODS = ('GET', 'HEAD', 'OPTIONS')
class ReadOnly(permissions.BasePermission):
"""
The endpoint is read-only request.
"""
def has_permission(self, request, view):
return (
request.method in SAFE_METHODS
)
|
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import sys
import Swing
import uuid
import pickle
import pandas as pd
from Swing.util.Analyzer import Analyzer
from datetime import datetime
"""
This pipeline scans a range of window sizes for a given inference method and generates roller objects ... |
"""
Implements the maximum marginal relevance (MMR) algorithm and related
functionality
"""
import numpy as np
from utils.logger import get_logger
from .diversity import load_similarity_func, gaussian_similarity
# Global variable for logging
logger = get_logger()
DEFAULT_SIMILARITY = gaussian_similarity()
# Note f... |
import os
import sys
from hashlib import sha256
import json
import time
import logging
from src.bot import Bot
from scraper.scraper_config import hashtags, handles
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter("[%(asctime)s]: [%(levelname)s]: %(name)s: %(message)s ",... |
# Generated by Django 2.0.5 on 2018-10-25 18:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('INT', '0023_auto_20181014_1909'),
]
operations = [
migrations.AddField(
model_name='notification',
name='hide_conten... |
from quantsim import Qubit, H, CNOT, D
if __name__ == '__main__':
q1, q2 = Qubit(), Qubit()
q1 - H
q1@q2 - CNOT(1, 2) - D
|
import subprocess
from functools import partial
from discord.ext import commands
class Debug(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.newline = "\n" # f-strings dont allow backslaches, screw that
def clean(self, code): # Strip codeblock formatting from the message
i... |
# Copyright 2017-present Open Networking 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 ag... |
from io import BytesIO
import mock
from twisted.internet import defer
from twisted.test import proto_helpers
from twisted.trial import unittest
from lbrynet.core import Peer
from lbrynet.core.server import BlobRequestHandler
from lbrynet.core.PaymentRateManager import NegotiatedPaymentRateManager, BasePaymentRateMana... |
from pyblake2 import blake2b # type: ignore
from typing import (
List
)
from pytezos.crypto.encoding import base58_encode, base58_decode
def _hash_tuple(left: bytes = b'', right: bytes = b'') -> bytes:
return blake2b(left + right, digest_size=32).digest()
def _reduce_operation_hashes(hashes: List[bytes]) ... |
# encoding: utf-8
from __future__ import division, print_function, unicode_literals
###########################################################################################################
#
#
# Reporter Plugin
#
# Read the docs:
# https://github.com/schriftgestalt/GlyphsSDK/tree/master/Python%20Templates/Reporter
... |
"""Bitcoin Object Python Serializations.
Copyright (c) 2010 ArtForz -- public domain half-a-node
Copyright (c) 2012 Jeff Garzik
Copyright (c) 2010-2016 The Bitcoin Core developers
Distributed under the MIT software license, see the accompanying
file COPYING or http://www.opensource.org/licenses/mit-license.php.
Modi... |
import pytest
from cornflake.exceptions import ValidationError
from cornflake.validators import max_
def test_valid():
value = max_(10)(5)
assert value == 5
def test_less_than():
max_(10)(9)
def test_equal():
max_(10)(10)
def test_greater_than():
with pytest.raises(ValidationError):
... |
from django.apps import AppConfig
class ExerciseConfig(AppConfig):
name = 'exercise'
|
import os, subprocess, tempfile, re
from aiohttp import web
from homeassistant.components.http import HomeAssistantView
from .const import DOMAIN, URL
from .shaonianzhentan import delete_file, move_file, github_url, download, mkdir, load_content, save_content, fetch_text
class HAView(HomeAssistantView):
url = URL... |
"""
Administrative interface for personal app
"""
from django.contrib import admin
from .models import (
Skill,
Image,
Event,
Technology,
Testimonial,
Job,
Project,
Link,
OpenSourceContribution,
)
class LinkAdmin(admin.ModelAdmin):
"""
Administrative interface for Link mo... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 06 10:48:52 2018
@author: B
"""
import cv2
import numpy as np
import os
def zeroone(img):
img[img<128]=0
img[img>=128]=1
return img
def labels(img):
ret, thresh = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
conn... |
"""
OWLS data-file handling function
"""
from __future__ import print_function
#-----------------------------------------------------------------------------
# Copyright (c) 2014, yt Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, dist... |
# coding: utf-8
"""
This modules holds methods for generating predictions from a model.
"""
import os
import sys
from typing import List, Optional
from logging import Logger
import numpy as np
import torch
from torchtext.data import Dataset, Field
from joeynmt.helpers import bpe_postprocess, load_config, make_logger,... |
# Copyright (C) 2019 Intel Corporation. All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
#
import re
import sys
import common
import collections
BOARD_NAME = ''
BIOS_INFO = ['BIOS Information', 'Vendor:', 'Version:', 'Release Date:', 'BIOS Revision:']
BASE_BOARD = ['Base Board Information', 'Manufacture... |
from ply import lex
import ast
keywords = (
'AND', 'OR', 'XOR', 'NOT',
'END', 'PRINT', 'MAIN',
'IF', 'THEN', 'ELSE', 'ELSEIF',
'WHILE', 'DO',
'FOR', 'TO', 'DOWNTO',
'FOREACH'
)
tokens = keywords + (
'LPAREN', 'RPAREN', 'LBRACE', 'RBRACE', 'LBRACKET', 'RBRACKET',
'PLUS', 'MINUS', 'TIMES', 'DIV', 'MOD', 'PO... |
from __future__ import absolute_import
import os
import re
from ast import parse
from pathlib import Path
from inspect import getsource
from importlib import import_module
from pkg_resources import resource_filename
from inflect import engine
from grpc_tools import protoc
from django.apps import apps
from django.con... |
# -*- coding: utf-8 -*-
import traceback
import logging
import time
from confluent_kafka import avro, KafkaException
from confluent_kafka.avro import AvroProducer, SerializerError
from queue import SimpleQueue
class Producer:
def __init__(self, *topics, broker, schema_registry, schema, logging_enabled = False):
... |
"""
Map muncher - Convert property-annotated maps to runnable output.
* If the input file is given as .blend, run blend2bam on it.
* Pretag
* Find all nodes with `linked_collection` tag
* If such a node also has a `linked_file` tag, the given file is the
authoritative source for the model to use, and the value o... |
# -*- coding: utf-8 -*-
#
# rtk.dao.RTKIncidentDetail.py is part of The RTK Project
#
# All rights reserved.
# Copyright 2007 - 2017 Andrew Rowland andrew.rowland <AT> reliaqual <DOT> com
"""
===============================================================================
The RTKIncidentDetail Table
==============... |
def hows_the_parrot():
print("He's pining for the fjords!")
hows_the_parrot()
def lumberjack(name, pronoun):
print("{}'s a lumberjack and {} OK!".format(name, pronoun))
lumberjack("Kenneth", "he's")
lumberjack("Lacey", "she's")
lumberjack("Sam", "they're")
def average(num1, num2):
return (num1+num2)... |
from pickle import dump, load
import pandas as pd
import numpy as np
from models import Poly
from solver import exact_cover, solve
def exact_cover_matrix(board):
shapes = board.usable_shapes
names = board.usable_names
Y = {}
X = board.placeable_area | shapes
for name in names:
... |
# Copyright 2021 Alibaba Group Holding Limited. 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.0
#
# Unless required by ... |
import pytest
import vaex
import vaex.webserver
import numpy as np
import contextlib
import sys
test_port = 29110 + sys.version_info[0] * 10 + sys.version_info[1]
scheme = 'ws'
@contextlib.contextmanager
def small_buffer(ds, size=3):
if ds.is_local():
previous = ds.executor.buffer_size
ds.executor... |
print("Hi!")
name = input("What's your name? ")
print("It's nice to meet you,", name)
answer = input("Are you enjoying the course? ")
if answer == "Yes":
print("That's good to hear!")
else:
print("Oh no! That makes me sad!") |
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.gbm import H2OGradientBoostingEstimator
def test_staged_predict_proba():
prostate = h2o.import_file(path=pyunit_utils.locate("smalldata/prostate/prostate.csv"))
prostate["CAPSULE"] = prostate["CAPSULE"].asfa... |
# -*- coding:utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the ... |
# we write a function that computes x factorial iteratively
def simpleFactorial(x):
# we check that x is positive
if x < 0:
raise Exception("factorials of non-negative numbers only")
# we initialize y to 1
y = 1
# we loop through all integers from 1 to x and multiply them onto y
for k in range(1, x+1):
y ... |
import warnings
from typing import Iterable, Set, List, Iterator, Union, Tuple, Dict
import pyhpo
from pyhpo import Ontology
from pyhpo.matrix import Matrix
class HPOSet(set):
def __init__(self, items: Iterable['pyhpo.HPOTerm']) -> None:
set.__init__(self, items)
self._list: List['pyhpo.HPOTerm']... |
import socket # noqa E902
from _thread import *
from board import Board
import pickle
import time
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server = "localhost"
port = 5555
server_ip = socket.gethostbyname(server)
try:
s.bind((server, port))
except socket.error as e:
print(str(e))
s.listen()
p... |
from qiskit import QuantumCircuit
from qc_grader.grade import grade_circuit, grade_number, submit_circuit, submit_number
criteria: dict = {
'max_qubits': 28,
'min_cost': 30
}
def grade_ex1a(circuit: QuantumCircuit) -> None:
if grade_circuit(circuit, 'week1', 'exA', **criteria):
print('Feel free... |
# import necessary libraries
import os
from flask import (
Flask,
render_template,
jsonify,
request,
redirect)
#################################################
# Flask Setup
#################################################
app = Flask(__name__)
#################################################
#... |
from django.shortcuts import render
from django.urls import include, path
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.decorators import renderer_classes, api_view
from rest_framework import authentication, permissions, status
from ajax.views import que... |
"""Forms for working with Sync and SyncLogEntry models."""
from django import forms
from nautobot.utilities.forms import add_blank_choice, BootstrapMixin, BOOLEAN_WITH_BLANK_CHOICES
from .choices import SyncLogEntryActionChoices, SyncLogEntryStatusChoices
from .models import Sync, SyncLogEntry
class SyncFilterForm... |
"""
A custom matcher plugin example.
"""
from hamcrest.core.base_matcher import BaseMatcher
from hamcrest.core.description import Description
from preacher.compilation.verification import MatcherFactoryCompiler
from preacher.plugin import hookimpl
class IsEven(BaseMatcher[int]):
"""
A custom matcher example... |
import torch
import numpy as np
import logging
log = logging.getLogger()
def apply_box_deltas(boxes, deltas):
"""Applies the given deltas to the given boxes.
boxes: [N, 4] where each row is y1, x1, y2, x2
deltas: [N, 4] where each row is [dy, dx, log(dh), log(dw)]
"""
# Convert to y, x, h, w
he... |
import streamlit as st
import amplitude
import utils
def main(session_state):
user_analytics = amplitude.gen_user(utils.get_server_session())
opening_response = user_analytics.safe_log_event(
"opened saude_em_ordem_description", session_state, is_new_page=True
)
st.subheader("O que é?")
... |
from flask import jsonify
from werkzeug.exceptions import default_exceptions
from werkzeug.exceptions import HTTPException
class JsonExceptionHandler(object):
"""
This class Handles Http errors
:returns: json object
"""
def __init__(self, app):
"""
Initialize the app to handle inc... |
from abc import abstractmethod
import numpy as np
from .types_misc import CheckType
from ..interface import Contract, ContractNotRespected, RValue, eval_in_context
from ..syntax import W, Keyword, add_contract, add_keyword
class ArrayElementsTest(Contract):
@abstractmethod
def test_elements(self, context, ... |
# coding: utf-8
""" Given a config file, create a master inference.hdf5 file. """
from __future__ import division, print_function
__author__ = "adrn <adrn@astro.columbia.edu>"
# Standard library
import os, sys
import logging
import glob
# Third-party
import acor
import h5py
import numpy as np
import astropy.units ... |
#
# @lc app=leetcode id=1248 lang=python3
#
# [1248] Count Number of Nice Subarrays
#
# @lc code=start
class Solution:
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
def Most(k):
res = 0
l = 0
for r in range(len(nums)):
k -= nums[r] % 2
... |
# -*- coding: utf-8 -*-
# Copyright 2018 New Vector Ltd
#
# 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 la... |
from app import db
class CasesStatus(db.Model):
__tablename__ = "casesstatus"
id = db.Column(db.Integer, primary_key=True)
reported_date = db.Column(db.DateTime, index=True)
confirmed_negative = db.Column(db.Integer)
presumptive_negative = db.Column(db.Integer)
presumptive_positive = ... |
import numpy as np
from collections import Counter
from nar_module.nar.nar_model import get_list_id
class RecentlyPopularRecommender():
def __init__(self):
pass
def get_recent_popular_item_ids(self):
# get item recent buffer from google service
# recent_items_buffer = self.clicked_it... |
"""
Implements classical histogram equalization / matching.
These function support images as either numpy or cupy arrays. The histeq_trans() function does
accept the histogram arguments as cupy arrays but immediately converts to numpy arrays and always
returns a numpy array.
"""
from .util import check_image_mask_sin... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
""" This file is a part of the VeRyPy classical vehicle routing problem
heuristic library and provides an implementation of the Gillet & Miller (1974)
Sweep heuristic.
The script is callable an... |
from pprint import pprint
import networkx as nx
import matplotlib.pyplot as plt
a, b, c, d, e, f, g, h = range(8)
N = {
a: [b, c, d, e, f],
b: [c, e],
c: [d],
d: [e],
e: [f],
f: [c, g, h],
g: [f, h],
h: [f, g]
}
G = nx.from_dict_of_lists(N)
nx.draw(G)
plt.show()
print(type... |
from __future__ import print_function
import sys
from proton.handlers import MessagingHandler
from proton.reactor import Container
class ReceiveHandler(MessagingHandler):
def __init__(self, conn_url, address, desired):
super(ReceiveHandler, self).__init__()
self.conn_url = conn_url
self.... |
from urllib import request, error
from socket import timeout
from datetime import datetime
import json
from . import aws_utility
from . import logger
from . import config
graphql_api_key = aws_utility.get_graphql_api_key()
graphql_api_url = aws_utility.get_graphql_api_url()
def _request_headers() -> dict:
retur... |
description = 'Setup for the ANDOR CCD camera at BOA using the CCDWWW server'
motprefix = 'SQ:BOA:mcu1:DCCDATZ'
counterprefix = 'SQ:BOA:counter'
excludes = ['embl', 'andor']
devices = dict(
dccdatz = device('nicos_ess.devices.epics.motor.EpicsMotor',
epicstimeout = 3.0,
description = 'Andor focus... |
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
c = 0
out = []
for i, j in zip(s, s[1:]):
if i != j :
out.append(i)
out.append(j)
print(i,j)
return len(out)
if __name__ == "__main__":
sln =... |
from enum import Enum
from subprocess import call
import logging
import time
class CameraFactory(object):
"""description of class"""
log = logging.getLogger('SemBrain')
def __init__(self):
CameraFactory.log.info('CameraFactory.init')
def ExecuteCommand(self, filename):
CameraFactory.l... |
from .covid19 import bp as co_bp
from .statistics import bp as st_bp |
"""Generate different pathways of the book, as determined by profiles.yml."""
import sys
from argparse import ArgumentParser
from pathlib import Path
from shutil import copytree
from subprocess import run
from sys import exit as sys_exit
from yaml import Loader, load
from pathways import landing_page
from pathways.ba... |
from .base import GnuRecipe
class FriBidiRecipe(GnuRecipe):
def __init__(self, *args, **kwargs):
super(FriBidiRecipe, self).__init__(*args, **kwargs)
self.sha256 = '94bdfe553e004d8bd095b109e1826823' \
'11dd511740d5083326d1582f1df237be'
self.name = 'fr... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 19 15:10:33 2019
@author: LaurencT
"""
import re
import numpy as np
def create_target_population(cov_pop_burden_df, param_df, index):
"""Adds a new column to cov_pop_burden_df which is the target population
Inputs:
cov_pop_burden_df - a df which mu... |
# -*- coding: utf-8 -*-
import argparse
import inspect
import math
import numpy as np
import os
from PIL import Image
from pprint import pprint
import sys
# add parent directory to sys path to import relative modules
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os... |
# -*- coding: utf-8 -*-
import os
import sys
import six
import json
import tccli.options_define as OptionsDefine
import tccli.format_output as FormatOutput
from tccli import __version__
from tccli.utils import Utils
from tccli.exceptions import ConfigurationError, ClientError, ParamError
from tencentcloud.common import... |
import pygame
SWITCH_SCENE = pygame.USEREVENT + 1
CONSOLE_PRINT = pygame.USEREVENT + 2
COMMAND = pygame.USEREVENT + 3
|
import pyvista
import vtk
import numpy as np
#
# Create an empty grid
#
grid = pyvista.RectilinearGrid()
#
# Initialize from a vtk.vtkRectilinearGrid object
#
vtkgrid = vtk.vtkRectilinearGrid()
grid = pyvista.RectilinearGrid(vtkgrid)
#
# Create from NumPy arrays
#
xrng = np.arange(-10, 10, 2)
yrng = np.arange(-10, 10, ... |
# -*- coding: utf-8 -*-
import time
from odoo import api, models, _
from odoo.exceptions import UserError
class ReportAgedPartnerBalance(models.AbstractModel):
_inherit = 'report.accounting_pdf_reports.report_agedpartnerbalance'
@api.model
def _get_report_values(self, docids, data=None):
if not ... |
#!/usr/bin/env python
"""
The Resource Expert Droid State container.
RedState holds all test-related state that's useful for analysis; ephemeral
objects (e.g., the HTTP client machinery) are kept elsewhere.
"""
__author__ = "Mark Nottingham <mnot@mnot.net>"
__copyright__ = """\
Copyright (c) 2008-2011 Mark Nottingha... |
import multiprocessing
import os
import time
import traceback
from typing import List, Any
from ipx import Arrow, SharedMemoryArrow
def new_arrow() -> SharedMemoryArrow:
return SharedMemoryArrow.new(size=96, name='0x00ABCDEF')
# return SharedMemoryArrow.new(size=64, name=None)
def del_arrow(arrow: SharedM... |
P1_CHAR = "1"
P2_CHAR = "2"
class ChessPiece(object):
"""
This class is used entirely for inheretence for other chess piece classes.
"""
def __init__(self, row, col, player):
assert 0 <= row < 8
assert 0 <= col < 8
assert player in (P1_CHAR, P2_CHAR), "player: {} error".format(... |
import matplotlib.pyplot as plt
import numpy as np
import umap
from scipy import integrate
from pacmap import PaCMAP
from data_prepare import data_prep
cmap_fig = plt.cm.get_cmap("Spectral")
cmap = plt.cm.get_cmap("RdYlGn_r")
cmap_ = plt.cm.get_cmap("gist_yarg")
# If you would like discrete ladders, use ladder_map
... |
import asyncio
import aiohttp
import socket
import json
from typing import Dict, List, Callable
from asyncio_throttle import Throttler
#enable nested async calls for use in Jupyter notebooks
try:
import nest_asyncio
nest_asyncio.apply(loop=asyncio.get_event_loop())
except:
pass
class AsyncHttpMixin:
h... |
# Copyright 2018 PerfKitBenchmarker Authors. 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.0
#
# Unless required by appli... |
#
# Metrix++, Copyright 2009-2019, Metrix++ Project
# Link: https://github.com/metrixplusplus/metrixplusplus
#
# This file is a part of Metrix++ Tool.
#
from metrixpp.mpp import api
# load common utils for post processing tools
from metrixpp.mpp import utils
class Plugin(api.Plugin, api.IR... |
import numpy as np
from scipy import signal
import streamlit as st
import control
import matplotlib.pyplot as plt
st.title('PID Controller')
'''Process Parameters'''
# Transfer function - Process
K = float(st.text_input("Process gain","3"))
T = float(st.text_input("Time constant","4"))
num_p = np.array([K])
den_p ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.