content stringlengths 5 1.05M |
|---|
"""
Bacteria Bomb Model
Created by Cameron Leighton
"""
#import the operators
import csv
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot
import matplotlib.animation
import agentframework
import tkinter
import time
#creates the figure and the axes
fig = matplotlib.pyplot.figure(figsize=(7, 7))
ax ... |
# Load the website on local with Python WEBSERVER
from http import server, HTTPStatus
import sys
if __name__ == "__main__":
if(len(sys.argv) < 2):
print("Error: Missing argument...\nUsage: python webserver.py [PORT NUMBER]\n")
else:
handler = server.SimpleHTTPRequestHandler
adresse = 'l... |
import mock
import unittest
import datetime
from . import mock_boto3
import timewarp.ec2
class TestEc2Adapter(unittest.TestCase):
def setUp(self):
self.boto3 = mock_boto3.Boto3Mock()
self.invalidInstanceId = "abcdef"
def tearDown(self):
self.boto3.teardown()
def test_invalidIns... |
"""5-7. Favorite Fruit: Make a list of your favorite fruits, and then write a series of
independent if statements that check for certain fruits in your list.
• Make a list of your three favorite fruits and call it favorite_fruits.
• Write five if statements. Each should check whether a certain kind of fruit
is in your ... |
from classier.utils.PersistentDict import PersistentDict
import concurrent.futures
import threading
import subprocess
import os
TEST_FILE = "test_file.json"
if os.path.exists(TEST_FILE):
subprocess.call(["rm", TEST_FILE])
def write_to_test(val):
print(f"{threading.get_ident()} is writing {val}")
Persist... |
# -*- coding: utf-8 -*-
# pragma pylint: disable=unused-argument, no-self-use
# (c) Copyright IBM Corp. 2010, 2021. All Rights Reserved.
# headers for comments
FROM_SENTINEL_COMMENT_HDR = "From Sentinel"
FROM_SOAR_COMMENT_HDR = "From IBM SOAR"
SENT_TO_SENTINEL_HDR = "Sent to Sentinel"
SENTINEL_INCIDENT_NUMBER = "sen... |
import os
os.environ["JSII_DEBUG"] = "1"
|
# coding=utf-8
# Copyright 2018 The TF-Agents 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... |
#!/usr/bin/env python
'''
Sharan Multani
[email protected]
Script to list all devices in your org, that have checked in after a specified time.
'''
import sys, datetime as dt
from cbapi.example_helpers import build_cli_parser, get_cb_defense_object
from cbapi.psc.defense import Device
def main():
parser... |
# Generated by Django 2.1.5 on 2019-01-18 13:19
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0056_auto_20190114_0857'),
]
operations = [
migrations.RemoveField(
model_name='channel',
name='user',
),
... |
# Generated by Django 2.2.6 on 2019-12-17 13:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cms', '0044_alter_field_hist_freq_verbose_name_on_recordentry'),
]
operations = [
migrations.AddField(
model_name='eventtag',
... |
# -*- coding: utf-8 -*-
#
# Copyright 2020 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
import requests
from flask import current_app
from app import config
class DigitalOcean(object):
base = 'https://api.digitalocean.com/v2/'
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + config.DO_TOKEN
}
def make_req(self, method, endpoint, data=None):
... |
from twisted.conch import recvline
from twisted.conch.insults import insults
from twisted.conch.telnet import TelnetTransport, TelnetBootstrapProtocol
from twisted.conch.manhole_ssh import ConchFactory, TerminalRealm
from twisted.internet import protocol
from twisted.application import internet, service
from twisted.c... |
#!/usr/bin/env python
import os,sys,damask
import os,sys,string
from optparse import OptionParser
import numpy as np
import math
scriptID = string.replace('$Id: out_size.py 153 2015-11-06 14:32:50Z chakra34 $','\n','\\n')
scriptName = os.path.splitext(scriptID.split()[1])[0]
parser = OptionParser(option_class=dama... |
# Generated by Django 3.1.5 on 2021-02-01 22:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('PRODUCTOS', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='productos',
name='pro_precio',
... |
from django.contrib.auth.models import Permission
from django.db import models
from django.utils.translation import gettext_lazy as _
from .settings import MODEL_TREE, TREE_ITEMS_ALIASES
class CharFieldNullable(models.CharField):
"""We use custom char field to put nulls in SiteTreeItem 'alias' field.
That al... |
#!/usr/bin/env python3
#
# Cross Platform and Multi Architecture Advanced Binary Emulation Framework
#
import sys,unittest
sys.path.append("..")
from qiling import *
from qiling.exception import *
from test_elf import *
from test_posix import *
from test_qltool import *
if __name__ == "__main__":
unittest.main(... |
'''
XSSCon - 2019/2020
This project was created by menkrep1337 with 407Aex team.
Copyright under the MIT license
'''
import requests, json
##### Warna #######
N = '\033[0m'
W = '\033[1;37m'
B = '\033[1;34m'
M = '\033[1;35m'
R = '\033[1;31m'
G = '\033[1;32m'
Y = '\033[1;33m'
C = '\033[1;36m'
##### Styling #####... |
"""
This script evaluates the size of the LWW linkable ring signatures
implemented in koppercoin.crypto.lww_signature
"""
from koppercoin.crypto.lww_signature import *
import time
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')
import jsonpickle
from pympler import asizeof... |
class Cocinero():
def prepararPlatillo(self):
self.cuchillo = Cuchillo()
self.cuchillo.cortarVegetales()
self.estufa = Estufa()
self.estufa.boilVegetables()
self.freidora = Freidora()
self.freidora.freirVegetales()
class Cuchillo():
def cortarVegetales(self):
... |
from __future__ import absolute_import, unicode_literals
import os
from .base import *
SECRET_KEY = os.environ['SECRET_KEY']
DEBUG = False
import dj_database_url
DATABASES['default'] = dj_database_url.config()
ALLOWED_HOSTS = [
os.environ['HOST_URL'],
os.environ['ACCESS_URL']
]
# Redirect to https in produ... |
import numpy as np
from sklearn.metrics import roc_auc_score, average_precision_score
def compute_scores_thresholding(gt, exp, threshold):
ret = np.max(exp) * threshold
binary_exp_array = exp > ret
TP = (binary_exp_array * gt).sum()
predict_pos = binary_exp_array.sum()
actual_pos = gt.sum()
... |
from __future__ import print_function
import os
import sys
import json
import unittest
from what import What
from kuyruk import Kuyruk, Config
config = Config()
config.from_pyfile('/tmp/kuyruk_config.py')
class LoaderTestCase(unittest.TestCase):
def test_load_single_file(self):
self._test_function_nam... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
test_cell
"""
from __future__ import print_function
import pytest
import numpy as np
from tunacell.base.cell import Cell, filiate_from_bpointer
from tunacell.base.colony import Colony, build_recursively_from_cells
## Fixture for cell
@pytest.fixture
def cells():
... |
import time
from django.views.generic import TemplateView
from django.utils.decorators import method_decorator
from django.shortcuts import render
from django.views.decorators.cache import never_cache
from cache_helpers.decorators import cache_page_forever, cache_result
from cache_helpers.views import CachePageMixin
... |
import datetime as dt
import numpy as np
import pandas as pd
import os
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import Flask, jsonify
# Database Setup
engine = create_engine("sqlite:///hawaii.sqlite")
#... |
from django.db.models.query import QuerySet
from django.contrib import admin
from .models import Image
# https://docs.djangoproject.com/en/2.2/ref/contrib/admin/actions/#writing-action-functions
def delete_everywhere(modeladmin, request, queryset: QuerySet):
"""
Delete object both in Django and in MinIO too.... |
from argparse import ArgumentParser
from pathlib import Path
import sys
from typing import Callable
import os
os.environ["MKL_THREADING_LAYER"] = "GNU"
import torch
import math
from tqdm import tqdm
# Setup path
new_path = Path().absolute()
sys.path.append(str(new_path))
import src.util.CudaUtil as CU
from src.co... |
from time import time
from functools import partial
from qcodes import VisaInstrument, InstrumentChannel, ChannelList
from qcodes.utils import validators as vals
class DACException(Exception):
pass
class DacReader(object):
@staticmethod
def _dac_parse(resp):
"""
Parses responses from the... |
# coding=utf-8
# Copyright 2020 The TF-Agents 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
class HelloView(APIView):
permission_classes = (IsAuthenticated,)
def get(self, request):
content = {'message': 'Hello, World!'}
return Response(content... |
from pathlib import Path
import torch
import torch.nn as nn
import torch.utils.data as data
from PIL import Image
from torchvision import transforms
import torchvision.models.resnet as resnet
import argparse
from tqdm import tqdm
from torch.utils.tensorboard import SummaryWriter
class TrainDataset(data.Dataset):
... |
#!/usr/bin/env python3
from argparse import ArgumentParser
from glob import glob
from itertools import product
from os.path import normpath, realpath
from pathlib import Path
from subprocess import PIPE, STDOUT, run
from sys import argv
from vang.pio.shell import run_commands
def get_work_dirs(find, root):
retur... |
#! /usr/bin/env python3
import sys
import mysql.connector
from mysql.connector import errorcode
class EventDB(object):
db_targets = {}
def Connect(self, conf):
db_dsn = {
'user': conf['db_user'],
'password': conf['db_pass'],
'host': conf['db_host'],
... |
import os
import lib.snip as snip
import lib.translate as translate
from pynput import keyboard
def pull_and_process():
try:
area = snip.GetArea()
image = area.snip()
translated_string = translate.translate(image, language[choice])
print(translated_string)
except SystemError:
... |
NUMBER_OF_ROWS = 8
NUMBER_OF_COLUMNS = 8
DIMENSION_OF_EACH_SQUARE = 64
BOARD_COLOR_1 = "#DDB88C"
BOARD_COLOR_2 = "#A66D4F"
X_AXIS_LABELS = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H')
Y_AXIS_LABELS = (1, 2, 3, 4, 5, 6, 7, 8)
SHORT_NAME = {
'R':'Rook', 'N':'Knight', 'B':'Bishop',
'Q':'Queen', 'K':'King', 'P':'Paw... |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
import torch
import numpy as np
import unittest
import fastNLP.modules.utils as utils
class TestUtils(unittest.TestCase):
def test_case_1(self):
a = torch.tensor([
[1, 2, 3, 4, 5], [2, 3, 4, 5, 6]
])
utils.orthogonal(a)
def test_case_2(self):
a = np.random.rand(10... |
from gaiasdk import sdk
import logging
def MyAwesomeJob(args):
logging.info("This output will be streamed back to gaia and will be displayed in the pipeline logs.")
# Just raise an exception to tell Gaia if a job failed.
# raise Exception("Oh no, this job failed!")
def main():
logging.basicConfig(leve... |
"""
Exports an experiment to a directory.
"""
import os
import mlflow
import shutil
import tempfile
import click
from mlflow_export_import.common import filesystem as _filesystem
from mlflow_export_import.common import mlflow_utils
from mlflow_export_import.common.search_runs_iterator import SearchRunsIterator
from ... |
import pytest
def test_something(random_number_generator):
a = random_number_generator()
b = 10
assert a + b >= 10
|
import re
from collections import defaultdict
d = open("input.txt").read().splitlines()
rules = defaultdict(list)
i = 0
while len(d[i]) > 0:
for x in re.findall(r'\d+-\d+', d[i]):
a, b = [int(x) for x in x.split('-')]
rules[d[i].split(':')[0]].append(range(a, b+1))
i += 1
yt = [int(x) for x in ... |
from csdl import Model
import csdl
import numpy as np
class ExampleSimple(Model):
"""
:param var: vec1
:param var: vec2
:param var: VecVecCross
"""
def define(self):
x = self.declare_variable('x')
y = self.declare_variable('y')
a = x + y
b = x + y
c = 2... |
#!/usr/bin/env python
import subprocess
import os
import sys
if len(sys.argv) ==1:
print '\nUsage: awskill [instance ID or cluster name]\n'
print '\nSpecify instance ID or cluster name that will be terminated, which can be found using "awsls" or "awsls -c"\n'
sys.exit()
instanceID=sys.argv[1]
#==================... |
#!/usr/bin/env python
# ------------------------------------------------------------------------------------------------------%
# Created by "Thieu Nguyen" at 16:19, 16/03/2020 %
# ... |
# Copyright 2014 Google Inc. All Rights Reserved.
"""The super-group for the compute CLI."""
import argparse
from googlecloudsdk.calliope import base
from googlecloudsdk.compute.lib import constants
from googlecloudsdk.compute.lib import utils
from googlecloudsdk.core import cli
from googlecloudsdk.core import excepti... |
import os
import time
class Teste:
# INICIACAO DA VARIAVEL
def __init__(self):
self.pid = os.getpid()
# FUNCAO PARA ESCREVER O PID DO PYTHON QUE ESTÁ SENDO EXECUTADO(ESSE SOFTWARE).
def escrita(self):
e = open('pid.txt', 'w')
e.writelines('{0}'.format(self.pi... |
# /usr/bin/env python3
# -*- coding: utf-8 -*-
'''
跨平台全局进程锁,防止定时任务多次启动
'''
import os
if os.name == 'nt':
import win32con, win32file, pywintypes
elif os.name == 'posix':
import fcntl
class AutoLock:
def __init__( self, mutexname ):
self.filepath = mutexname + '.lock'
self... |
x = 0
while 1:
print x
x = x + 1
if x > 16000:
x = 0
|
from .misc import SpaceFuncsException
class baseGeometryObject:
_AttributesDict = {'spaceDimension': '_spaceDimension'}
def __init__(self, *args, **kw):
self.__dict__.update(kw)
#__call__ = lambda self, *args, **kwargs: ChangeName(self, args[0]) #if len(args) == 1 and type(args[0]) == str else... |
import re
import json
import urllib
import requests
site = 'https://blog.mhuig.top'
sitemaps = ['/post-sitemap.xml','/page-sitemap.xml']
result = []
bingUrllist = []
bingData = {}
i=0
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'}
for sitemap in sitemaps:
s... |
#!/usr/bin/env python
from copy import deepcopy
from glob import glob
import os
import shutil
import yaml
base_path = os.path.join(os.path.dirname(__file__), "..")
generated_path = os.path.join(base_path, "generated")
# Helper method to allow for `literal` YAML syntax
def str_presenter(dumper, data):
if len(dat... |
import hashlib
import hmac
import re
import time
import urllib
import requests
import six
from broker.exceptions import BrokerApiException, BrokerRequestException
from broker import user_agent
class Request(object):
API_VERSION = 'v1'
QUOTE_API_VERSION = 'v1'
def __init__(self, api_key='', secret='', ... |
# Generated by Django 2.2.14 on 2020-07-24 20:35
import datetime
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),
('auth0lo... |
# high-dimensional reacher
import numpy as np
import matplotlib.pyplot as plt
def smooth(y, radius=2, mode='two_sided'):
if len(y) < 2*radius+1:
return np.ones_like(y) * y.mean()
elif mode == 'two_sided':
convkernel = np.ones(2 * radius+1)
return np.convolve(y, convkernel, mode='same') ... |
#!/usr/bin/env python3
import numpy as np
import scipy.special
from functools import reduce
def peirce_dev(N: int, n: int = 1, m: int = 1) -> float:
"""Peirce's criterion
Returns the squared threshold error deviation for outlier identification
using Peirce's criterion based on Gould's methodology.
... |
import random
chars1='abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ'
chars2 = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
def start():
print('Welcome to the Random Password Generator. Version 1.00')
print("------------------------------------")
length = int(input('H... |
import pytest
from eth_utils import (
decode_hex,
encode_hex,
)
from eth_keys import keys
from p2p import ecies
# (pvikey_hex, pubkey_hex, expected_ecdh) tuples with known-good values, to ensure our
# ECC backends are compatible with other clients'.
# Copied from
# https://github.com/ethereum/cpp-ethereum/... |
import time
import pytest
import tapystry as tap
def test_simple():
def fn():
yield tap.Broadcast('key')
return 5
assert tap.run(fn) == 5
def test_receive():
def broadcaster(value):
yield tap.Broadcast('key', value)
def receiver():
value = yield tap.Receive('key')
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-06-04 09:53
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('problem', '0001_initial'),
]
operations = [
migrations.AlterField(
... |
import pandas as pd
def test_roundtrip_substrait(duckdb_cursor):
res = duckdb_cursor.get_substrait("select * from integers limit 5")
proto_bytes = res.fetchone()[0]
query_result = duckdb_cursor.from_substrait(proto_bytes)
expected = pd.Series(range(5), name="i", dtype="int32")
pd.testing.assert... |
import datetime
from flask import request
import db
import validators
def split_ip(ip):
"""Split a IP address given as string into a 4-tuple of integers."""
return tuple(int(part) for part in ip.split('.'))
def read_all_devices():
device_list = []
all_devices = db.find_all_devices()
if all_dev... |
#
# Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
#
"""
This file contains implementation of data model for physical router
configuration manager
"""
from device_conf import DeviceConf
from ansible_base import AnsibleBase
from dm_utils import PushConfigState
from dm_utils import DMUtils
from dm_utils ... |
'''
repositories
============
The following methods allow for interaction with the Tenable.sc
:sc-api:`Repository <Repository.html>` API. These items are typically seen
under the **Repositories** section of Tenable.sc.
Methods available on ``sc.repositories``:
.. rst-class:: hide-signature
.. autoclass:: Repository... |
n=0
with open("G.txt", "wt") as out_file:
while n != 10:
out_file.write("test\n")
|
# -*- coding: utf-8 -*-
import uuid
from io import StringIO
from PySide2 import QtGui
from PySide2.QtUiTools import QUiLoader
from PySide2.QtCore import QMetaObject
class UiLoader(QUiLoader):
def __init__(self, base_instance):
QUiLoader.__init__(self, base_instance)
self.base_instance = base_inst... |
import os
from relevanceai.constants.config import Config
from relevanceai.constants.links import *
CONFIG_PATH = os.path.dirname(os.path.abspath(__file__)) + "/config.ini"
CONFIG = Config(CONFIG_PATH)
MAX_CACHESIZE = (
int(CONFIG["cache.max_size"]) if CONFIG["cache.max_size"] != "None" else None
)
TRANSIT_ENV_... |
from genetics.fitnessTest import FitnessTest
from genetics.generator import getNewScheduleFromList
from genetics.genepool import GenePool
from product import Product
from schedule import Task
from vessels import Vessels
genepool = GenePool()
running = True
iterationCount = 0
def addSchedule(schedule):
genepool.addS... |
import numpy as np
import torch
from torch import nn, optim # , distributed
from torch.optim import lr_scheduler
from torch.backends import cudnn
from torch.utils import data
from torch.nn.utils import clip_grad_norm_
from torch.utils.tensorboard import SummaryWriter
# from torch.utils.data.distributed import Distribu... |
###############################################################################
''''''
###############################################################################
import pandas as pd
import aliases
import analysis
from thesiscode.utilities import hard_cache, hard_cache_df, hard_cache_df_multi
reader = analysis.u... |
import random
numStr = random.randint(1,100)
num = int(numStr)
timesGuessed = int(0)
correct = False
while ( correct == False ):
requestStr = input("What is your number guess? ")
requestInt = int(requestStr)
if ( requestInt == num ):
print("Your number is correct! You guessed the numb... |
from .verbosemanager import *
from .decorator import *
from .simple import *
from .counter import *
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 9 12:48:26 2020
@author: jacob
"""
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
def hm(plat, data_path):
plate_name = plat.get_plate_name()
params = plat.get_all_params()
# List for making heat... |
# -*- coding: utf-8 -*-
from common.helpers.loadConfig import LoadJsonFiles
from common.helpers.operationResults import OperationResults
from server.icity_server import CONFIGURE_FILE, CONFIGURE_HASH
SUPPORTED_DRIVERS = ['mysql', 'mongodb', 'sqlite', 'postgresql']
DRIVER_MAP = {
"mysql" : "MYSQL_DATABASE_CONNE... |
from django.contrib import admin
from django.contrib.admin.options import ModelAdmin
from django.contrib.auth import logout as auth_logout
from django.contrib.messages import info
from django.db.models import get_model
from django import http
from django.shortcuts import redirect
from django.template import RequestCon... |
from flask import Flask
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
from config import db_path
import os
app = Flask(__name__)
app.config.from_object("config")
db = SQLAlchemy(app)
Session(app)
# set up date base if it doesn't exist
if not os.path.exists(db_path):
from app.models i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from ctypes import *
import time
import cv2
import numpy as np
import Queue
import platform
import time
import os
try:
if platform.system() == 'Darwin':
libuvc = cdll.LoadLibrary("libuvc.dylib")
elif platform.system() == 'Linux':
libuvc = cdll.Load... |
__title__ = 'Simple-Reverse-Proxy'
__description__ = 'A simple reverse proxy implementation using python simplicity.'
__url__ = 'https://github.com/MarcosVs98/sreverse-proxy'
__version__ = '1.0.0'
__build__ = 0x022300
__author__ = 'Marcos Silveira'
__author_email__ = '[email protected]'
__license__ = 'MIT License... |
__author__ = 'satish'
import pickle
import csv
def save_obj(obj, name ):
with open( name + '.pkl', 'wb') as f:
pickle.dump(obj, f, protocol=2)
def load_obj(name ):
with open( name + '.pkl', 'rb') as f:
return pickle.load(f)
DM = load_obj("DesignMatrix")
ftest = open('comedy_comparisons.te... |
import logging
from wellspring.rest.wellspring_rest_base import *
from wellspring.services import device_service
LOGGER = logging.getLogger(__name__)
def register_device(request):
return handle_rest_request(request, device_post_handler, ["POST"])
def device_post_handler(request, response, device_uuid, pathParams... |
from operator import itemgetter
n, m = map(int, input().split())
city_num = [0 for _ in range(n)]
l = []
for i in range(m):
p, y = map(int, input().split())
l.append([i, p, y])
l.sort(key=itemgetter(2))
for i in range(m):
j, p, y = l[i]
city_num[p-1] += 1
idz = str(str(p).zfill(6)... |
'''Example to illustrate Quantile Regression
Author: Josef Perktold
'''
import numpy as np
import statsmodels.api as sm
from statsmodels.sandbox.regression.quantile_regression import quantilereg
sige = 5
nobs, k_vars = 500, 5
x = np.random.randn(nobs, k_vars)
#x[:,0] = 1
y = x.sum(1) + sige * (np.random.randn(nobs... |
import numpy as np
from scipy.integrate import trapz
import matplotlib.pyplot as plt
from genessa.timeseries.gaussian import GaussianModel
from matplotlib.collections import LineCollection
# internal python imports
from ..figures.settings import *
class ComparisonMethods:
""" Methods for comparison objects. """
... |
from flask import Flask
from flask_restful import Resource, Api
from classifier import *
app = Flask(__name__)
api = Api(app)
class Classifier(Resource):
def get(self):
return {
'products': ['Ice Cream', 'Chocolate', 'Fruit', 'Eggs']
}
api.add_resource(Classifier, '/')
if __name__... |
from biobb_common.tools import test_fixtures as fx
from biobb_amber.pdb4amber.pdb4amber_run import pdb4amber_run
class TestPdb4amberRun():
def setUp(self):
fx.test_setup(self, 'pdb4amber_run')
def tearDown(self):
fx.test_teardown(self)
pass
def test_pdb4amber_run(self):
pd... |
"""
Model definition for regression based on the BoW model.
"""
import os
import argparse
import numpy as np
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import (
confusion_matrix, classification_report, accuracy_score, f1_score)
from joblib import dump, load
from data_processing import Da... |
#!/usr/bin/env python3
"""Build Skyfield's internal table of constellation boundaries.
See:
https://iopscience.iop.org/article/10.1086/132034/pdf
http://cdsarc.u-strasbg.fr/viz-bin/Cat?VI/42
"""
import argparse
import os
import sys
import numpy as np
from numpy import array, searchsorted
from skyfield import api
UR... |
#!/usr/bin/env python
# coding: utf-8
# <div><img src="attachment:qgssqml2021wordmark.png"></div>
# # Part I: Introduction to Qiskit
# Welcome to Qiskit! Before starting with the exercises, please run the cell below by pressing 'shift' + 'return'.
# In[1]:
import numpy as np
# Importing standard Qiskit libraries
... |
from rest_framework import permissions
from rest_framework import compat
from gaskserv.models import TimeEntry
class IsAuthenticated(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
return request.user and compat.is_authenticated(request.user)
class IsOwnerOrReadOnly(per... |
# coding: utf-8
from os import DirEntry
import socketserver
from os import path
# Copyright 2013 Abram Hindle, Eddie Antonio Santos
#
# 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
#
# ... |
"""InVision - Weighted Moving Average."""
from typing import List
import click
import numpy as np
import pandas as pd
def moving_avg_prediction(data: pd.DataFrame, num_obs: int) -> pd.DataFrame:
"""Computes average of the last n observations.
A future value of the variable depends on the average of its n pr... |
"""
Software License Agreement (Apache 2.0)
Copyright (c) 2020, The MITRE Corporation.
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
https://www.apache.org/licenses/LICENSE-... |
from dataclasses import asdict
import pytest
from dacite import from_dict
from fhir2dataset.data_class import Element, Elements
from fhir2dataset.tools.fhirpath import multiple_search_dict
@pytest.fixture()
def resources():
resources = [
{
"resourceType": "Observation",
"id": "f0... |
"""
This file is part of flatlib - (C) FlatAngle
Author: João Ventura ([email protected])
This subpackage implements a simple Ephemeris using
the Python port of the Swiss Ephemeris (Pyswisseph).
The pyswisseph library must be already installed and
accessible.
"""
import ... |
# Generated by Django 4.0.1 on 2022-03-09 12:08
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('Assets', '0002_alter_assetlist_cname_alter_assetlist_middle_ware_and_more')... |
from flask import Flask, request, jsonify
from sklearn.externals import joblib
import numpy as np
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
clf = joblib.load('./model/logreg.pkl')
def getParameters():
age = request.args.get('age')
sex = request.args.get('sex')
cigsPerDay = request.args.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from pprint import pprint
from os import path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
from wrappers import SpellbookWrapper as SpellbookWrapper
import testconfig
url = testconfig.url
key = testconfig.key
secret = testconfig.secret
... |
""" agent controllers package """
|
import cobra
from cobra.core import Model
from typing import Tuple, List
import pandas as pd
import subprocess
from warnings import warn
from ncmw.utils import (
get_default_configs,
get_default_medium,
get_biomass_reaction,
DATA_PATH,
)
def gapfill_model(
model: Model, eps: flo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.