content stringlengths 4 20k |
|---|
import unittest
import os
import tempfile
import numpy as np
from numpy import ma
from numpy.testing import assert_array_almost_equal
from netCDF4 import Dataset
# Test automatic conversion of masked arrays (set_always_mask())
class SetAlwaysMaskTestBase(unittest.TestCase):
"""Base object for tests checking the... |
from __future__ import unicode_literals
from __future__ import division
from __future__ import print_function
import os
import sys
import utils_tests
import trappy
sys.path.append(os.path.join(utils_tests.TESTS_DIRECTORY, "..", "trappy"))
class TestFilesystem(utils_tests.SetupDirectory):
def __init__(self, *arg... |
from pymongo import MongoClient
import gridfs
import datetime
today = datetime.datetime.today()
client = MongoClient("mongodb://localhost:27017/nodefilestore")
db = client.nodefilestore
fs = gridfs.GridFS(db)
expiredUploadIDs = []
expiredFileIDs = []
usedFileIDs = []
totalFilesDeleted = 0
# collect expired uploads
... |
"""Tests for loader."""
import os
from absl.testing import absltest
from dm_control.locomotion.mocap import loader
from dm_control.locomotion.mocap import mocap_pb2
from dm_control.locomotion.mocap import trajectory
from google.protobuf import descriptor
from google.protobuf import text_format
from dm_control.utils ... |
import sys
import six
import datetime
from twisted.python import log
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks
from twisted.internet.endpoints import serverFromString
from autobahn.wamp import types
from autobahn.twisted.util import sleep
from autobahn.twisted import wamp... |
# example showing how one might assembled an ordered list of atoms
# from mouse clicked through use of a PyMOL Wizard.
from pymol.wizard import Wizard
from pymol import cmd, util
import pymol
import traceback
click_sele = "_clicked"
disp_sele = "_displayed"
# Wizard class definition
def quote_blanks(st):
st = ... |
import utils
import parseinstallargs
import subprocess
import sys
import os
import shutil
import multiprocessing
DEFAULT_GIT_VER='2.5.0-rc1'
DEFAULT_VER='2.4.91'
APP='qemu-system-arm'
URL='git://git.qemu.org/qemu.git'
class Installer:
'''Installer'''
def __init__(self, defaultVer=DEFAULT_VER, defaultGitVer=... |
# -*- coding: utf-8 -*-
from django import forms
from django.forms.util import ErrorList
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import Us... |
from __future__ import absolute_import, division, print_function
import numpy as np
from numba.npyufunc.deviceufunc import (UFuncMechanism, GenerializedUFunc,
GUFuncCallSteps)
from numba.roc.hsadrv.driver import dgpu_present
import numba.roc.hsadrv.devicearray as devicearray
im... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
ZetCode PyQt5 tutorial
This example shows how to use
a QComboBox widget.
author: Jan Bodnar
website: zetcode.com
last edited: January 2015
"""
import sys
from PyQt5.QtWidgets import (QWidget, QLabel,
QComboBox, QApplication)
class Example(QWidget):
... |
import cmath
import itertools
import math
import numpy as np
import tensor
def realify_complex_matrix (M):
retval = np.ndarray((2*M.shape[0],2*M.shape[1]), dtype=float)
for r,row in enumerate(M):
R = 2*r
for c,component in enumerate(row):
C = 2*c
retval[R,C] = compo... |
#!/usr/bin/python
# -*- coding:utf8 -*-
from flask import render_template, Blueprint
from flask_login import login_required
from models import *
blueprint = Blueprint('order', __name__, static_folder='../static/order')
@blueprint.route('/searchbox1/<int:page>')
@login_required
def searchbox1(page):
"""
用户自定义... |
from __future__ import absolute_import, division, print_function
from cryptography import utils
from cryptography.x509 import certificate_transparency
from cryptography.x509.base import (
Certificate, CertificateBuilder, CertificateRevocationList,
CertificateRevocationListBuilder,
CertificateSigningRequest... |
"""
pglookout - test configuration
Copyright (c) 2016 Ohmu Ltd
See LICENSE for details
"""
from pglookout import logutil, pgutil
from pglookout.pglookout import PgLookout
from py import path as py_path # pylint: disable=no-name-in-module
from unittest.mock import Mock
import os
import pytest
import signal
import subp... |
# -*- coding: utf-8 -*-
__doc__ = """
WebSocket within CherryPy is a tricky bit since CherryPy is
a threaded server which would choke quickly if each thread
of the server were kept attached to a long living connection
that WebSocket expects.
In order to work around this constraint, we take some advantage
of some inter... |
from violation import violations
from cuisine import cuisine_codes
from pygeocoder import Geocoder
class Restaurant(object):
def __init__(self, data):
boro = {1: 'manhattan', 2: 'the bronx', 3: 'brooklyn', 4: 'queens', 5: 'staten island'}
self.inspection_date = data[0]['INSPECTIONDATE']
sel... |
from xdrlib import Packer, Unpacker
import socket
slope_str2int = {'zero':0,
'positive':1,
'negative':2,
'both':3,
'unspecified':4}
# could be autogenerated from previous but whatever
slope_int2str = {0: 'zero',
1: 'positive',
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# python import
import os, json
# django import
from django.http import HttpResponse
try:
from django.views.decorators.csrf import csrf_exempt
except ImportError:
# monkey patch this with a dummy decorator which just returns the same function
# (for compatabi... |
import random
import unittest
import sys,os
sys.path.append("../src/")
from silpa.modules import dictionary
class TestDictionary(unittest.TestCase):
def setUp(self):
self.dictionary=dictionary.getInstance()
def testEnglishHindi(self):
self.dictionary.get_response()
self.assertEqual(sel... |
import sys
import numpy as np
from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
#---------------------------------------------
def main(argv):
"""
Main entry point of this utility application.
This is simply a function called by the checking of namespace __main__, at
the e... |
# birdcallbot dl
# download and store info from macalauy library from online and excel sheet
# find corresponding audio and photo to make a :35 sec video
import xl
import shutil
import os
import random
from lxml import html
from urllib.parse import urlencode
from pydub import AudioSegment
from requests import get #... |
import six
from openstack import exceptions as sdkexc
from oslo_serialization import jsonutils
from requests import exceptions as reqexc
from senlinclient.common.i18n import _
verbose = False
class BaseException(Exception):
'''An error occurred.'''
def __init__(self, message=None):
self.message = m... |
from django.shortcuts import render
from django.views.generic import TemplateView
from rest_framework import viewsets, filters
from rest_framework.decorators import detail_route, list_route
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from books.models import B... |
"""This module contains a series of generally useful and reusable
components for use when building extensions to the optparse module
which parses command lines."""
import collections
import re
import logging
import optparse
_logger = logging.getLogger("util.%s" % __name__)
#
# used with the usercolonpassword type
#
... |
from casadi import *
T = 10. # Time horizon
N = 20 # number of control intervals
# Declare model variables
x1 = MX.sym('x1')
x2 = MX.sym('x2')
x = vertcat(x1, x2)
u = MX.sym('u')
# Model equations
xdot = vertcat((1-x2**2)*x1 - x2 + u, x1)
# Objective term
L = x1**2 + x2**2 + u**2
# Formulate discrete time dynamics... |
import re
from datetime import datetime
from functools import lru_cache, reduce
from itertools import chain
from typing import Dict
from dateutil.parser import ParserError, parse
from django.db.models import Q
from django.utils import timezone
from django.utils.translation import gettext as _
from jellyfish import dam... |
import unittest
from crm_solver.beamlet import Beamlet
class CrmAcceptanceTest(unittest.TestCase):
RELATIVE_PRECISION = 0.001
lithium_testcase = 'beamlet/acceptancetest/scenario-standard_plasma-H_energy-100_beam-Li_profile.xml'
sodium_testcase = 'beamlet/acceptancetest/scenario-standard_plasma-H_energy-1... |
from abstract import BCFerriesAbstractObject
from decorators import cacheable, fuzzy, lazy_cache
import re, dateutil.parser, datetime
from route import BCFerriesRoute
class BCFerriesTerminal(BCFerriesAbstractObject):
def __init__(self, name, url, api):
super(BCFerriesTerminal, self).__init__(self)
self.name... |
"""
Automated tests for checking transformation algorithms (the models package).
"""
import logging
import unittest
import os
import os.path
import tempfile
import six
import numpy
import scipy.linalg
from gensim.corpora import mmcorpus, Dictionary
from gensim.models import ldamodel, ldamulticore
from gensim import... |
import os
from time import sleep
import unittest
import argparse
import json
import re
from appium import webdriver
PATH = lambda p: os.path.abspath(
os.path.join(os.path.dirname(__file__), p)
)
class CordovaAppTests(unittest.TestCase):
def appiumHost(self, caps):
url=""
if re.match("http:/... |
#!/usr/bin/env python3
import sys
import asyncio
from electrum_grs.network import filter_protocol, Network
from electrum_grs.util import create_and_start_event_loop, log_exceptions
try:
txid = sys.argv[1]
except:
print("usage: txradar txid")
sys.exit(1)
loop, stopping_fut, loop_thread = create_and_star... |
from src.gyms.cartpole import CartPole
from src.agents import Agent
from src.utils import uniform
env = CartPole()
observe = env.appearance()
# Q function is appproximated by depth-2 MLP
action_space = [[-1.0], [1.0]]
inp_dim = len(observe) + len(action_space[0])
MLP_dims = (inp_dim, 4, 1)
cart = Agent(MLP_dims, acti... |
"""
Usage example
1. Join switches (use your favorite method):
$ sudo mn --controller remote --topo tree,depth=3
2. Run this application:
$ PYTHONPATH=. ./bin/ryu run \
--observe-links ryu/app/gui_topology/gui_topology.py
3. Access http://<ip address of ryu host>:8080 with your web browser.
"""
import os
from ... |
import os
import subprocess
import fixtures
import testscenarios
from testtools.matchers import FileExists, Not
from tests import fixture_setup, integration
class ParserTestCase(integration.TestCase):
"""Test bin/snapcraft-parser"""
def setUp(self):
super().setUp()
if os.getenv("SNAPCRAFT_P... |
"""Copy Command."""
from __future__ import print_function
import time
import datetime
import logging
import copy
from biggraphite.cli import command
from biggraphite.cli.command_list import list_metrics
from biggraphite.drivers.cassandra import TooManyMetrics
from biggraphite import accessor as bg_accessor
log = l... |
import random
import numpy as np
from OpenGL.GL import *
from PyEngine3D.Common import logger
from PyEngine3D.App import CoreManager
from PyEngine3D.Utilities import Attributes
from PyEngine3D.OpenGLContext import CreateTexture, Texture3D
class VectorFieldTexture3D:
def __init__(self, **data):
self.name... |
from __future__ import absolute_import, print_function
import os
import sys
import subprocess
import textwrap
import fabric
import fabric.api as fab
from testmill import (login, cache, keypair, manifest, application,
error, util, console, inflect)
usage = textwrap.dedent("""\
usage: r... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
from babel import dates
from babel.dates import get_timezone
from babel.util import UTC
TEST_DT = datetime.datetime(2016, 1, 8, 11, 46, 15)
TEST_TIME = TEST_DT.time()
TEST_DATE = TEST_DT.date()
def test_format_interval_same_instant_1()... |
# -*- coding: utf-8 -*-
# Librerias externas.
import os
import sqlite3
import hashlib
# El uso de locks es para los threads que sirven las paginas de Flask.
import threading
from functools import wraps
from math import ceil
from twisted.internet import reactor
from twisted.web.wsgi import WSGIResource
from twiste... |
#!/usr/bin/env python
'''Test Manage Function'''
import unittest
import configparser
import os
import sqlite3 as lite
from /xfero/.db import manage_function as db_function
from /xfero/.db import create_XFERO_DB as db
class Test(unittest.TestCase):
'''
**Purpose:**
Unit Test class for th... |
if "bpy" in locals():
import importlib
importlib.reload(settings)
importlib.reload(utils_i18n)
else:
import bpy
from bpy.props import (BoolProperty,
CollectionProperty,
EnumProperty,
FloatProperty,
... |
import logging
from grab.item.field import Field, ItemListField
from grab.selector import XpathSelector
from grab.selector import JsonSelector
from grab.error import GrabMisuseError
from grab.document import Document
logger = logging.getLogger('grab.item.item')
class ItemBuilder(type):
def __new__(cls, name, bas... |
import os
import shutil
from gi.repository import Gdk, Gtk
import gpodder
from gpodder import util
from gpodder.gtkui.base import GtkBuilderWidget
_ = gpodder.gettext
class BuilderWidget(GtkBuilderWidget):
def __init__(self, parent, **kwargs):
self._window_iconified = False
GtkBuilderWidget.__... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
... |
from msrest.serialization import Model
class NodeHealthStateFilter(Model):
"""Defines matching criteria to determine whether a node should be included
in the returned cluster health chunk.
One filter can match zero, one or multiple nodes, depending on its
properties.
Can be specified in the cluste... |
from PyQt4 import QtGui
from .uic_generated.PayupManualDialog import Ui_PayupManualDialog
import re
from decimal import Decimal
class PayupManualDialog(QtGui.QDialog, Ui_PayupManualDialog):
def __init__(self, parent, amount_total):
QtGui.QDialog.__init__(self, parent)
self.setupUi(self)
s... |
import pytest
import hubcheck
from hubcheck.testcase import TestCase2
from hubcheck.shell import ContainerManager
pytestmark = [ pytest.mark.website,
pytest.mark.tool_session,
pytest.mark.weekly,
pytest.mark.upgrade,
pytest.mark.prod_safe_upgrade,
... |
# coding: utf8
import requests
from json import loads
import pickle
import os.path
import gtk
import terminatorlib.plugin as plugin
from terminatorlib.config import Config
from terminatorlib.util import get_config_dir
#########
TOKEN = 'TOKEN'
#############
AVAILABLE = ['Online_Servers']
class Online_Servers(plugin.... |
import os, json, re, uuid, hashlib, functools
import flask
from flask import request, session
class g:
user_db = None
login_manager = None
class LoginManager:
# Validate credentials and save a new user.
def new_user(self):
username, email, password = (
request.form['username'], ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# MC64BOT - A telegram Bot to interact with a Minecraft Server
from telegram.ext import Updater, CommandHandler
import logging
import os.path
import subprocess
from subprocess import call
from mcstatus import MinecraftServer
server = MinecraftServer.lookup("127.0.0.1:255... |
"""TensorFlow Probability math functions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow_probability.python.internal import all_util
from tensorflow_probability.python.math import ode
from tensorflow_probability.python.math import psd_ke... |
from functions.str import w_str
from functions.types import get_type
from wtypes.control import WRaisedException
from wtypes.exception import WException
from wtypes.list import WList
from wtypes.number import WNumber
from wtypes.string import WString
def add(*operands):
# TODO: thorough consideration of all opera... |
from flask import flash, redirect, request, session
from werkzeug.exceptions import Forbidden, NotFound
from indico.modules.events import Event
from indico.modules.events.registration.util import get_event_regforms_registrations
from indico.modules.events.views import WPAccessKey
from indico.util.i18n import _
from in... |
from modularodm.exceptions import ValidationError
from modularodm import Q
from rest_framework import exceptions
from rest_framework import serializers as ser
from api.base.exceptions import Conflict
from api.base.serializers import (
JSONAPISerializer, IDField,
LinksField, RelationshipField, DateByVersion,
)
... |
"""Handler for Kubeflow."""
import functools
import os
import sys
import time
from typing import Any, Dict, Optional
import click
import kfp
from tfx.orchestration.kubeflow import kubeflow_dag_runner
from tfx.tools.cli import labels
from tfx.tools.cli.container_builder import builder
from tfx.tools.cli.handler impo... |
from django.contrib.auth.models import User
from django.db import models
from project.models import Project
class Message(models.Model):
is_active = models.BooleanField(default=True)
created = models.DateField(auto_now_add=True)
author = models.ForeignKey(User)
project = models.ForeignKey(Project)
... |
"""empty message
Revision ID: 564f5a5061f
Revises: 5824a5f06dd
Create Date: 2015-04-19 07:49:24.416817
"""
# revision identifiers, used by Alembic.
revision = '564f5a5061f'
down_revision = '5824a5f06dd'
from alembic import op
import sqlalchemy as sa
from woodwind.models import JsonType
def upgrade():
### comm... |
from shinken.webui.bottle import redirect
### Will be populated by the UI with it's own value
app = None
# Our page. If the user call /dummy/TOTO arg1 will be TOTO.
# if it's /dummy/, it will be 'nothing'
def get_page():
# First we look for the user sid
# so we bail out if it's a false one
user = app.get... |
from setuptools import setup
version = '2.2.dev0'
long_description = '\n\n'.join([
open('README.rst').read(),
open('TODO.rst').read(),
open('CREDITS.rst').read(),
open('CHANGES.rst').read(),
])
install_requires = [
'Django >= 1.6',
'django-extensions',
'lizard-ui >= 5.0',
'lizard-... |
import os
import re
from invoke import task, collection
from textwrap import dedent
import sys
if sys.platform == 'win32':
WINDOWS = True
else:
WINDOWS = False
def run(ctx, *args, **kwargs):
if 'pty' not in kwargs:
kwargs['pty'] = True
if WINDOWS:
kwargs['pty'] = False
if 'echo' ... |
#!/usr/bin/python
import sys
import os
if len(sys.argv) <= 1:
print 'Usage: %s training_file [testing_file]' % sys.argv[0]
raise SystemExit
train_pathname = sys.argv[1]
file_name = os.path.split(train_pathname)[1]
scaled_file = file_name + ".scale"
model_file = file_name + ".model"
range_file = file_name + ".range... |
"""User fixtures."""
from fixture import DataSet
from flask import current_app
class UserData(DataSet):
"""User data."""
class admin:
email = current_app.config.get('CFG_SITE_ADMIN_EMAIL')
password = ''
note = '1'
nickname = 'admin' |
"""
This module implements the APIs for IP Blocking and IP Filtering
"""
import logging
from imcsdk.mometa.ip.IpBlocking import IpBlocking
from imcsdk.mometa.ip.IpFiltering import IpFiltering, IpFilteringConsts
from imcsdk.apis.utils import _get_mo, _is_valid_arg, _is_invalid_value
from imcsdk.imccoreutils import get_s... |
from lib.common import helpers
import re
class Stager:
def __init__(self, mainMenu, params=[]):
self.info = {
'Name': 'AppleScript',
'Author': ['@harmj0y'],
'Description': ('An OSX office macro.'),
'Comments': [
"http://stackoverflow.com/... |
"""Test functions for the sparse.linalg.interface module
"""
from __future__ import division, print_function, absolute_import
from functools import partial
from itertools import product
import operator
import pytest
from numpy.testing import assert_, assert_equal, \
assert_raises
import numpy as np
import s... |
import argparse
try:
from time import perf_counter
except:
from time import time
perf_counter = time
import dataset
import numpy
from numpy.testing import assert_almost_equal
import random
import datetime
import os
import logging
from algo.learnspn import LearnSPN
from spn import NEG_INF
from spn.u... |
import os
import subprocess
import sys
from distutils.spawn import find_executable
from glob import glob
from pkg_resources import parse_version
from setuptools import Extension, setup
PROJ_MIN_VERSION = parse_version("7.1.0")
CURRENT_FILE_PATH = os.path.dirname(os.path.abspath(__file__))
BASE_INTERNAL_PROJ_DIR = "pr... |
import sys
import requests
from flask import Flask, Blueprint, request, jsonify
from flask_cors import CORS
from articles import Articles
app = Flask(__name__)
bp = Blueprint('articles', __name__, url_prefix='/articles')
articles = Articles()
@bp.route("/", methods=["GET"])
def list():
arts = articles.list()
... |
"""
Template file used by the OPF Experiment Generator to generate the actual
description.py file by replacing $XXXXXXXX tokens with desired values.
This description.py file was generated by:
'~/nupic/eng/lib/python2.6/site-packages/nupic/frameworks/opf/expGenerator/ExpGenerator.py'
"""
from nupic.frameworks.opf.expd... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import OrderedDict
import fnmatch
import obspy
import os
import re
import shelve
import warnings
import uuid
import event_query as search
class EventShelveException(Exception):
"""
Exception raised by this module.
"""
pass
class EventSh... |
"""\
Implement Hartree-Fock Greens Function for band energy corrections.
From Szabo/Ostland Chapter 7.
Correcting orbital 5, HF Eorb = -0.620213
-> Eorb = -0.527220 -0.538650
Correcting orbital 6, HF Eorb = -0.571950
-> Eorb = -0.603409 -0.600940
Correcting orbital 7, HF Eorb = -0.571950
-> Eorb = -0.603409 -0.600939
C... |
# A lot of failures in these tests on Mac OS X.
# Byte order related?
import unittest
from ctypes import *
from ctypes.test import need_symbol
import _ctypes_test
from test.test_support import impl_detail
class CFunctions(unittest.TestCase):
_dll = CDLL(_ctypes_test.__file__)
def S(self):
return c_l... |
authors = ("Dario Giovannetti <<EMAIL>>", )
version = "1.3"
description = "Adds the backend for managing alarm events."
website = "https://kynikos.github.io/outspline/"
affects_database = True
provides_tables = ("AlarmsProperties", "Alarms", "CopyAlarms", "AlarmsOffLog")
dependencies = (("core", 4), ("extensions.organi... |
# -*- coding: utf-8 -*-
"""Test the entry class."""
import bibpy
import bibpy.entry
import pytest
@pytest.fixture
def test_entry():
return bibpy.entry.Entry('article', 'key')
def test_formatting(test_entry):
assert test_entry.format() == '@article{key,\n}'
def test_properties(test_entry):
assert tes... |
import unittest
from pants.build_graph.address import Address
from pants.engine.objects import ValidationError
from pants.engine.struct import Struct
class StructTest(unittest.TestCase):
def test_attribute_error_raised_in_property(self) -> None:
"""This tests that Struct#__getattr__ doesn't prevent corre... |
import warnings
import os
from matplotlib.testing.compare import compare_images
from hicexplorer import hicCompartmentalization
from tempfile import NamedTemporaryFile
warnings.simplefilter(action="ignore", category=RuntimeWarning)
warnings.simplefilter(action="ignore", category=PendingDeprecationWarning)
tolerance = ... |
# -*- coding: utf-8 -*-
'''
Module for the HeaderBar class
'''
from gi import require_version
require_version('Gtk', '3.0')
from gi.repository import Gtk, GLib, Gio
from .dialogs import AddDialog
class HeaderBar(Gtk.HeaderBar):
'''
HeaderBar class
'''
def __init__(self, app):
super()._... |
"""
Object-layer module containing classes modelling sentences
"""
from __future__ import print_function, absolute_import
from amcat.tools.model import AmcatModel
from django.db import models
class Sentence(AmcatModel):
"""Model for sentences.
A sentence is a natural sentence in an article
created by s... |
from msrest.serialization import Model
class ComputeVmProperties(Model):
"""Properties of a virtual machine returned by the Microsoft.Compute API.
:param statuses: Gets the statuses of the virtual machine.
:type statuses: list of :class:`ComputeVmInstanceViewStatus
<azure.mgmt.devtestlabs.models.Com... |
from requests import RequestException, Response
from typing import List, Union
REQUEST_ERROR_STATUS_CODE = 503
REQUEST_ERROR_MESSAGE = "Request failed"
TOKEN_ERROR_GUIDANCE = "See our requirements for JSON Web Tokens at https://docs.notifications.service.gov.uk/rest-api.html#authorisation-header" # noqa
TOKEN_ERROR_... |
#!/usr/bin/env python
"""
--------------------------------------------------------------------------------
Created: Jackson Lee 8/27/12
Read in phyloxml file or a tog newick tree file and a fasta file and match top 10
characters of header with xml. Then add in the appropriate genome name
input file:
fasta file... |
#Written for the 135-102DAG-J01 Thermistor
import Adafruit_BBIO.ADC as ADC
import time
import datetime
import math as mt
ADC.setup()
#See June 4 comment on http://ealmberg.blogspot.com/2015/06/4-june-15.html
Bvalue = 3348 #Beta
Ro = 1000 #Resistance at 25 C
To = 298.15 #Room temperature in Kelvin
# ... |
"""
Copyright (c) 2012 Anant Bhardwaj
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, publish,
distribute,... |
from unittest import mock
from airflow.providers.apache.hdfs.sensors.web_hdfs import WebHdfsSensor
from tests.providers.apache.hive import TestHiveEnvironment
TEST_HDFS_CONN = 'webhdfs_default'
TEST_HDFS_PATH = 'hdfs://user/hive/warehouse/airflow.db/static_babynames'
class TestWebHdfsSensor(TestHiveEnvironment):
... |
# -*- coding: utf-8 -*-
import json
import urllib
import uuid
import os
import time
from itertools import chain
from uuid import uuid4
import application.models as Models
from flask import Blueprint, request, jsonify, current_app, redirect, render_template
from flask_login import current_user, login_user, logout_user, ... |
import datetime
import json
import logging
import re
from dateutil.parser import parse
from redash.query_runner import *
from redash.utils import JSONEncoder, parse_human_time
logger = logging.getLogger(__name__)
try:
import pymongo
from bson.objectid import ObjectId
from bson.timestamp import Timestamp... |
"""Ce fichier contient la classe MessageTmp, définie plus bas."""
class MessageTmp:
"""Cette classe représente un message de log stocké par la fil
d'attente du Logger.
"""
def __init__(self, niveau, message, formate):
"""Un message de log contient :
- un niveau d'erreur (int... |
import sys
import pytest
if sys.version_info >= (3, 3):
from unittest.mock import Mock
ABI = [{}]
ADDRESS = '0xd3CdA913deB6f67967B99D67aCDFa1712C293601'
NON_CHECKSUM_ADDRESS = '0xd3cda913deb6f67967b99d67acdfa1712c293601'
INVALID_CHECKSUM_ADDRESS = '0xd3CDA913deB6f67967B99D67aCDFa1712C293601'
@pytest.mark.para... |
"""learn_main tests."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import os
import tensorflow as tf
from tensorflow.contrib.learn.python.learn import learn_runner
from tensorflow.contrib.learn.python.learn import run_config
patch = tf.te... |
"""SCons.exitfuncs
Register functions which are executed when SCons exits for any reason.
"""
#
# Copyright (c) 2001 - 2014 The SCons Foundation
#
# 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 So... |
import numpy as np
from ..algo.multicorr_funcs import *
def multicorr(g1, g2, method='cross', upsample_factor=1, verbose=False):
"""Align a reference to an image by cross correlation. The template
and the image must have the same size.
The function takes in FFTs so that any FFT algorithm can be used to
... |
# -*- coding: utf-8 -*-
'''
Manage Windows features via the ServerManager powershell module
'''
from __future__ import absolute_import
import logging
import json
# Import python libs
try:
from shlex import quote as _cmd_quote # pylint: disable=E0611
except ImportError:
from pipes import quote as _cmd_quote
#... |
import urllib
from oslo_config import cfg
from nova.tests.functional.api_sample_tests import api_sample_base
CONF = cfg.CONF
CONF.import_opt('osapi_compute_extension',
'nova.api.openstack.compute.legacy_v2.extensions')
class InstanceUsageAuditLogJsonTest(api_sample_base.ApiSampleTestBaseV3):
AD... |
#!/usr/bin/env python
import argparse
import glob
import os
import re
import shutil
import subprocess
import sys
import stat
if sys.platform == "win32":
import _winreg
from lib.config import BASE_URL, PLATFORM, enable_verbose_mode, \
get_target_arch, get_zip_name, build_env
from lib.util impo... |
#parse-pag-statements.py
# Code to be used in transforming ESTC pagination statements in Open Refine. (Use Jython.)
import re
roman = re.compile('[xvi]')
plates = re.compile('\d+\splates')
range = re.compile('-')
ie = re.compile('\d+\\[i\\.?e\\.?\d+')
pt = re.compile('\d+pt')
vol = re.compile('v\.\d+')
# This code f... |
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
import gtk
import gobject
from forms import FormFor
import widgets
from settings import Settings
import datetime
class LiabilitiesTab(gtk.VBox):
def __init__(self, user, done = False):
gtk.VBox.__init__(self)
self.user = user
self.info_vbox =gtk.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Feature extraction
==================
Spectral features
-----------------
.. autosummary::
:toctree: generated/
chroma_stft
chroma_cqt
chroma_cens
melspectrogram
mfcc
rms
spectral_centroid
spectral_bandwidth
spectral_contrast
... |
"""Sample app to list and delete DLP jobs using the Data Loss Prevent API. """
from __future__ import print_function
import argparse
# [START dlp_list_jobs]
def list_dlp_jobs(project, filter_string=None, job_type=None):
"""Uses the Data Loss Prevention API to lists DLP jobs that match the
specified filt... |
from django.contrib import admin
from django.shortcuts import redirect
from django.utils.translation import ugettext_lazy as _
from reversion import VersionAdmin
from base.admin import (PrettyFilterMixin, MediaRemovalAdminMixin,
DownloadMediaFilesMixin,
RestrictedCompet... |
import requests
import datetime
import time
import jwt
class BotFramework:
def __init__(self, ms_app_id, ms_app_password):
self.ms_app_id = ms_app_id
self.ms_app_password = ms_app_password
self.token_url = "https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token"
sel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.