content string |
|---|
from optparse import OptionParser
from optparse import OptionValueError
import traceback
import nvcamera
import time
import os
def main():
try:
# parse arguments
usage = "Usage: %prog <options>\nThe script captures image/video with AE, AWB and AF set to Auto by default."
parser = OptionPars... |
#!/usr/bin/env python3
# written 2020-11-24 by mza
# last updated 2020-12-18 by mza
# from https://learn.adafruit.com/adafruit-pct2075-temperature-sensor/python-circuitpython
import time
import sys
import board
import busio
import adafruit_pct2075 # sudo pip3 install adafruit-circuitpython-pct2075/
from DebugInfoWar... |
from flup.server.fcgi import WSGIServer
from flaskext.xmlrpc import XMLRPCHandler, Fault
from xmlrpcdispatcher import XMLRPCDispatcher
class FlaskXMLRPC(object):
"""
Encapsulates an XML-RPC receiver within a flask server.
It also exports the service xmlrpc, which has the service contract outlined below.
... |
#!/usr/bin/env python3
from .common import *
def test_mget_mset(kv=default_kv):
r = getconn()
def insert_by_pipeline():
pipe = r.pipeline(transaction=False)
for k, v in list(kv.items()):
pipe.set(k, v)
pipe.execute()
def insert_by_mset():
ret = r.mset(**kv)
... |
"""Geometrical Points.
Contains
========
Point3D
"""
from __future__ import print_function, division
from sympy.core import S, sympify
from sympy.core.compatibility import iterable, range
from sympy.core.containers import Tuple
from sympy.simplify import simplify, nsimplify
from sympy.geometry.point import Point
fr... |
"""Put all the LQG mathematics here so that it can be tested separately to the servo
loop"""
from __future__ import division, print_function
import numpy as np
import scipy.linalg as la
#Time interval of servo loop. As logging happens this often, we make it a moderately
#large time, but much smaller than the ~250s sm... |
#!/usr/bin/env python3
# https://www.hackerrank.com/challenges/bigger-is-greater
import unittest
def bigger_is_greater(w):
array = list(w)
length = len(array)
for i in range(length - 1, 0, -1):
if array[i - 1] < array[i]:
array[i:] = sorted(array[i:])
for j in range(i, len... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Institution.city'
db.add_column(u'admin_institution', 'city',
self.gf(... |
"""
WSGI config for myfeeder project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION``... |
import os
from http import client
from urllib.parse import urljoin, urlunparse
from urllib.request import urlretrieve
from src.client.urllib_ex.parse_image import ImageParser
FOLDER_NAME = "DOWNLOAD_TEMP"
def download_image(src_url, data):
if not os.path.exists(FOLDER_NAME):
os.makedirs(FOLDER_NAME)
... |
from sympy.core import S, C, sympify
from sympy.core.function import Function, ArgumentIndexError
from sympy.ntheory import sieve
from math import sqrt as _sqrt
from sympy.core.compatibility import reduce, as_int
from sympy.core.cache import cacheit
class CombinatorialFunction(Function):
"""Base class for combi... |
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.cross_validation import train_test_split
class MarketValue(object):
def __init__(self, df):
print('Graphing Market Analysis...')
# Create ML m... |
"""
Package gaphor.UML.states implements diagram items for UML state machines.
Pseudostates
============
There are some similarities between activities and state machines, for example
- initial node and initial psuedostate
- final node and final state
Of course, they differ in many aspects, but the similaritie... |
"""A sum tree data structure.
Used for prioritized experience replay. See prioritized_replay_buffer.py
and Schaul et al. (2015).
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import random
import numpy as np
class SumTree(object):
"""... |
"""U-MOOC web application entry point."""
__author__ = 'Pavel Simakov (<EMAIL>)'
import os
import webapp2
# The following import is needed in order to add third-party libraries.
import appengine_config # pylint: disable-msg=unused-import
from common import tags
from controllers import sites
from models import cust... |
import io
import os
import setuptools
# Package metadata.
name = "google-cloud-trace"
description = "Cloud Trace API client library"
version = "1.2.0"
# Should be one of:
# 'Development Status :: 3 - Alpha'
# 'Development Status :: 4 - Beta'
# 'Development Status :: 5 - Production/Stable'
release_status = "Developm... |
# Below is the interface for Iterator, which is already defined for you.
#
# class Iterator(object):
# def __init__(self, nums):
# """
# Initializes an iterator object to the beginning of a list.
# :type nums: List[int]
# """
#
# def hasNext(self):
# """
# Returns... |
import json
import httplib2
import re
import inspect
class GithubAPI(object):
'''
Author: Emre Berge Ergenekon
Contains functions for making some of the Github v3 API requests.
'''
_base_url = ''
def __init__(self, user_name, repo_name):
self._base_url = 'https://api.github.c... |
from .platform import PY2
if PY2:
from StringIO import StringIO
from .robottypes2 import (is_bytes, is_dict_like, is_integer, is_list_like,
is_number, is_string, is_unicode, type_name)
long = long
unicode = unicode
else:
from io import StringIO
from .robottypes3 ... |
import datetime
from cloudbot import hook
from cloudbot.util import http, timesince
@hook.command("scene")
@hook.command()
def pre(inp):
"""pre <query> -- searches scene releases using orlydb.com"""
try:
h = http.get_html("http://orlydb.com/", q=inp)
except http.HTTPError as e:
return 'U... |
import sys
import time
from mns.mns_account import Account
from mns.mns_queue import *
from mns.mns_topic import *
from mns.mns_subscription import *
try:
import configparser as ConfigParser
except ImportError:
import ConfigParser as ConfigParser
cfgFN = "sample.cfg"
required_ops = [("Base", "AccessKeyId"), ("... |
# -*- coding: utf-8; mode: python; indent-tabs-mode: t; tab-width:4 -*-
import time,sys
class ADS1248:
MUX0 = 0x00
VBIAS = 0x01
MUX1 = 0x02
SYS0 = 0x03
OFC0 = 0x04
OFC1 = 0x05
OFC2 = 0x06
FSC0 = 0x07
FSC1 = 0x08
FSC2 = 0x09
IDAC0 = 0x0A
IDAC1 = 0x0B
GPIOCFG = 0x0C
GPIODIR = 0x0D
GPIODAT = 0x0E
RDATAC... |
#!/usr/bin/env python
import pandas as pd
import numpy as np
import argparse
import sys
import matplotlib.pyplot as plt
import seaborn as sns
def restricted_int(val):
try:
val = int(val)
except ValueError:
raise argparse.ArgumentTypeError("%r not an integer literal" % (val,))
if v... |
from astrodata.adutils.future import pyDisplay
import astrodata
from astrodata.AstroData import AstroData
from astrodata import Descriptors
from astrodata import IDFactory
from pyraf import iraf
def supported():
return pyDisplay.supported()
class DisplayServiceException:
""" This is the general exception the ... |
import logging
import pytest
from pip._internal.commands.search import (
SearchCommand, highest_version, print_results, transform_hits,
)
from pip._internal.status_codes import NO_MATCHES_FOUND, SUCCESS
from tests.lib import pyversion
if pyversion >= '3':
VERBOSE_FALSE = False
else:
VERBOSE_FALSE = 0
d... |
from PyQt5 import QtCore, QtGui, QtWidgets, Qt
from codebook_ui.settings_ui import *
"""Contains the UI for the main Codebooks window"""
class CodebooksMainUi(QtWidgets.QMainWindow):
"""Class containing the UI for the main Codebooks window"""
def __init__(self, parent = None):
super().__init__(paren... |
from collections import Counter
from typing import List, Optional
import numpy as np
from eli5.base import TargetExplanation, WeightedSpans, DocWeightedSpans
from eli5.base_utils import attrs
from eli5.utils import max_or_0
def get_char_weights(doc_weighted_spans, preserve_density=None):
# type: (DocWeightedSpa... |
import datetime
import operator
import threading
import traceback
from search import pickBestResult
import sickbeard
from sickbeard import db
from sickbeard import exceptions
from sickbeard.exceptions import ex
from sickbeard import helpers, logger
from sickbeard import search
from sickbeard import history
from sick... |
from nose.tools import assert_equal, assert_true, assert_false, assert_raises
import networkx as nx
# Tests for node and edge cutsets
def _generate_no_biconnected(max_attempts=50):
attempts = 0
while True:
G = nx.fast_gnp_random_graph(100,0.0575)
if nx.is_connected(G) and not nx.is_biconnected(... |
import csv
import sys
from sys import argv
import math
import statistics
filename = 'LBMA-GOLD_final_1.csv'
raw_file = open(filename)
file_reader = csv.DictReader(raw_file, delimiter=',')
def inputs():
while True:
try:
x = int(input("Please enter year number in 4 digits:"))
break
except ValueError:
... |
#!/usr/bin/env python
import json
import sys
import urllib2
from setuptools import find_packages
from setuptools import setup
from setuptools.command.develop import develop
from setuptools.command.install import install
from subprocess import call
def with_post_install(command):
'''Runs the code in `modified_ru... |
import sys
import os
from PyQt4 import QtCore
import picard
from picard.util import thread
def _stderr_receiver(prefix, time, msg):
sys.stderr.write("%s %s %s %s%s" % (prefix, str(QtCore.QThread.currentThreadId()), time, msg, os.linesep))
class Log(object):
def __init__(self):
self.entries = []
... |
import socket
import sys
import errno
#behold! global variables crossing!
host = "www.scan.me"
remote_ip = ""
def create_socket():
try:
return socket.socket()
except socket.error, e:
print "Failed to create socket. Error code: %s, Error message : %s" (str(e[0]), str(e[1]))
sys.exit(1)
def resolve_host(host)... |
import exception
import hashlib
class User:
file_name = 'user_info'
def __init__(self, username, password, superuser=False):
if type(username) is not str:
raise exception.IncorrectTypeError('Username must be a string.')
if type(password) is not str:
raise exception.Inc... |
"""Server Version Class."""
import logging
class ServerVersion(object): # Can't import APIClassTemplate due to dependency loop.
"""
Get the FMC's version information.
Set instance variables for each version info returned as well as return the whole response text.
:return: requests' response.text
... |
""" Generation of sine-Gaussian bursty type things
"""
import pycbc.types
import numpy
def fd_sine_gaussian(amp, quality, central_frequency, fmin, fmax, delta_f):
""" Generate a Fourier domain sine-Gaussian
Parameters
----------
amp: float
Amplitude of the sine-Gaussian
quality: float
... |
import numpy as np
# import FitsUtils
import FittingUtilities
import HelperFunctions
import matplotlib.pyplot as plt
import sys
import os
from astropy import units
from astropy.io import fits, ascii
import DataStructures
from scipy.interpolate import InterpolatedUnivariateSpline as interp
import MakeModel
import Helper... |
from _plugin import ClipboardPlugin, TestPlugin
def create_plugin():
return ColsToCommas()
class ColsToCommas(ClipboardPlugin):
def __init__(self):
ClipboardPlugin.__init__(self)
self.max_col_width = 30
self.indent = ''
def name(self):
return 'Columns to Comma Separated'
def description(self... |
import base64
import unittest
import time
import thread
import sys
from sherpa_samp.utils import DictionaryClass
from sherpa_samp import mtypes
import sampy as samp
import numpy
import logging
_max = numpy.finfo(numpy.float32).max
_tiny = numpy.finfo(numpy.float32).tiny
_eps = numpy.finfo(numpy.float32).eps
logging.... |
"""
rejson-py is a package that allows storing, updating and querying objects as
JSON documents in a [Redis](https://redis.io) database that is extended with the
[ReJSON module](https://github.com/redislabsmodules/rejson). The package extends
[redis-py](https://github.com/andymccurdy/redis-py)'s interface with ReJSON's... |
import subprocess
from testtools.matchers import (
Contains,
Equals,
Not,
)
from tests import integration
class BuildTestCase(integration.TestCase):
def _build_invalid_part(self, debug):
exception = self.assertRaises(
subprocess.CalledProcessError,
self.run_snapcraft... |
from io import StringIO
from sslyze.cli.console_output import ConsoleOutputGenerator
from sslyze.plugins.compression_plugin import CompressionScanResult
from sslyze import ScanCommandError, ScanCommandErrorReasonEnum, ScanCommand
from sslyze.scanner.server_scan_request import ScanCommandsResults
from sslyze.server_con... |
'''
Module containing class `SerialPort`
Note that this module depends on the PySerial serial communications Python extension.
'''
from __future__ import print_function
from serial import Serial, SerialException, SerialTimeoutException
import serial
# On Mac OS X, a typical USB to serial converter device name is ... |
#!/usr/bin/env python
import argparse
import geoip2
import ipaddress
import json
import logging
import os
import socket
import sys
import config
from datetime import datetime
from scapy.all import IP, PcapReader
from lib.ops_logger import initialize_log
from lib.geoip_address import GEOIPAddress
logger = initialize_l... |
from __future__ import absolute_import
import imp
import io
import os
import shutil
import sys
from imp import reload
from retriever import datasets
from retriever import download
from retriever import install_csv
from retriever import install_json
from retriever import install_mysql
from retriever import install_pos... |
from pecan import rest
import wsmeext.pecan as wsme_pecan
from rally.api import types
class Version(types.Version):
@classmethod
def convert(cls):
v = super(Version, cls).convert('v1', 'CURRENT',
updated_at='2014-01-07T00:00:00Z')
return v
class Contr... |
from .base import Action
from .. import arguments as Args
from ..error import exit_with_error
from ..formatting import format_table
from ..formatting import print_health_check
from ...objects.environment import Environment
class HealthCheckAction(Action):
"""Run health check on environment
"""
action_name... |
from plot_visual import PlotVisual
import numpy as np
__all__ = ['BarVisual']
def get_histogram_points(hist):
"""Tesselates histograms.
Arguments:
* hist: a N x Nsamples array, where each line contains an histogram.
Returns:
* X, Y: two N x (5 * Nsamples + 1) arrays wit... |
"""Unit tests of MQProducer interface in the DIRAC.Resources.MessageQueue.MProducerQ
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import unittest
from DIRAC import S_OK
from DIRAC.Resources.MessageQueue.MQProducer import MQProducer
from DIRAC.Resource... |
"""
Test that two targets with the same name generates an error.
"""
import os
import sys
import TestGyp
import TestCmd
# TODO(sbc): Remove the use of match_re below, done because scons
# error messages were not consistent with other generators.
# Also remove input.py:generator_wants_absolute_build_file_... |
#!/usr/bin/env python
'''
app.py
HABS Data Portal Application
'''
from flask import Flask
from flask_environments import Environments
import os
app = Flask(__name__)
env = Environments(app, default_env='COMMON')
env.from_yaml('config.yml')
if app.config['LOGGING'] == True:
import logging
logger = logging.... |
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import range
import os
import subprocess
import sys
import time
import urllib.request, urllib.parse, urllib.error
import testtools
testtools.try_import('selenium')
testtools.try_import('django')
import sst
f... |
import numpy as np
import pytest
from inverse_covariance import (
QuicGraphicalLassoEBIC,
AdaptiveGraphicalLasso,
QuicGraphicalLassoCV,
)
from inverse_covariance.profiling import ClusterGraph
class TestAdaptiveGraphicalLasso(object):
@pytest.mark.parametrize(
"params_in",
[
... |
#!/usr/bin/env python
from gnuradio import gr
from gnuradio import gr, blocks, analog, filter
from gnuradio import channels
# import ofdm
import numpy
# from fbmc_transmitter_hier_bc import fbmc_transmitter_hier_bc
# from fbmc_receiver_hier_cb import fbmc_receiver_hier_cb
# from fbmc_channel_hier_cc import fbmc_channe... |
#!/usr/bin/env python
# Contact: <EMAIL>
"""
Python bindings for MPI
"""
import sys
import os
import re
try:
import setuptools
except ImportError:
setuptools = None
pyver = sys.version_info[:2]
if pyver < (2, 6) or (3, 0) <= pyver < (3, 2):
raise RuntimeError("Python version 2.6, 2.7 or >= 3.2 required"... |
from ..app import db
from ..forms import Form
from wtforms import StringField, validators, SelectField
from healthtools_ec.app import db
from sqlalchemy import func
class Surgeon(db.Model):
__tablename__ = 'surgeons'
id = db.Column(db.Integer, autoincrement=True, primary_key=True)
name = db.Column(db.Str... |
import random
from pandaharvester.harvestercore.work_spec import WorkSpec
from pandaharvester.harvestercore.job_spec import JobSpec
from pandaharvester.harvestercore import core_utils
from pandaharvester.harvestermisc.info_utils import PandaQueuesDict
from pandaharvester.harvestercore.resource_type_mapper import Resou... |
from gameTypes import *
import pyglet
from util import *
from pygletUtil import *
from level import Level
class Map:
blocksAnims = {} # Анимация блоков для получения спрайтов
# @@ Имена блоков по типам. (вынести куда-то?)
blockImgNames = {BlockType.ruby : ('block1anim/ruby', 7),
BlockT... |
from . import PresenterBase
# import releases
# from entities import InvalidEntity
import wiki
import logging
class RoadmapPresenter(PresenterBase):
def __init__(self, dw, roadmap, release):
PresenterBase.__init__(self)
self.dw = dw
self.roadmap = roadmap
self.release = release
self.texts = {
# 'what':... |
import unittest
from lib.util import format_satoshis, parse_URI
class TestUtil(unittest.TestCase):
def test_format_satoshis(self):
result = format_satoshis(1234)
expected = "0.00001234"
self.assertEqual(expected, result)
def test_format_satoshis_diff_positive(self):
result = f... |
import sys
import spack.cmd
import spack.cmd.common.arguments as arguments
import spack.environment as ev
import spack.util.environment
import spack.user_environment as uenv
import spack.store
description = "add package to the user environment"
section = "user environment"
level = "short"
def setup_parser(subparser... |
"""Helpers for validation and checking of SBML and libsbml operations."""
import logging
import time
from typing import Iterable, List, Optional
import libsbml
from sbmlutils.utils import bcolors
logger = logging.getLogger(__name__)
def check(value: int, message: str) -> bool:
"""Check the libsbml return valu... |
from envi.archs.arm.const import *
import envi.registers as e_reg
'''
Strategy:
* Use only distinct register for Register Context (unique in each bank)
* Store a lookup table for the different banks of registers, based on the
register data in proc_modes (see const.py)
* Emulator does translation fr... |
"""
Copyright (C) 2004-2015 Pivotal Software, Inc. All rights reserved.
This program and the accompanying materials are made available under
the terms of the 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
... |
import os
import tempfile
from os.path import abspath, dirname, join, normcase, sep
from django.core.exceptions import SuspiciousFileOperation
from django.utils.encoding import force_text
# For backwards-compatibility in Django 2.0
abspathu = abspath
def upath(path):
"""Always return a unicode path (did somethi... |
from core.himesis import Himesis
import uuid
class HCityCompany2Association(Himesis):
def __init__(self):
"""
Creates the himesis graph representing the DSLTrans rule CityCompany2Association.
"""
# Flag this instance as compiled now
self.is_compiled = True
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
import jsonfield.fields
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
... |
#coding: utf-8
import pygame
class Screen(object):
def __init__(self, memory):
self.memory = memory
self.window = pygame.display.set_mode((160, 144))
pygame.display.set_caption('PyGB')
self.screen_buffer = [[(0,0,0)]*256 for x in xrange(256)] #256x256 RGB pixels
self.clock ... |
# -*- coding: utf-8 -*-
"""
"""
# Copyright (C) 2015 ZetaOps Inc.
#
# This file is licensed under the GNU General Public License v3
# (GPLv3). See LICENSE.txt for details.
import random
from zengine.forms import JsonForm
from zengine.forms import fields
from zengine.views.base import SimpleView, BaseView
from zengin... |
#!/usr/bin/env python3
import re
import subprocess as sp
import sys
import json
import urllib.request as req
import jsonschema
re_full = re.compile(r'(?P<name>^.*?$)(?P<desc>.*?)(^Argument.*?$(?P<args>.*?))?(^Result[^\n,]*?:\s*$(?P<resl>.*?))?(^Exampl.*?$(?P<exmp>.*))?', re.DOTALL | re.MULTILINE)
re_argline = re.com... |
"""
Functions to create initializers for parameter variables
"""
from numbers import Number
import numpy as np
from .utils import floatX
class Initializer(object):
def __call__(self, shape):
return self.sample(shape)
def sample(self, shape):
raise NotImplementedError()
class Normal(Initi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Console Hangman by christosvas
import random, os, sys
class FileHelper:
def wordslists_files(self, folder):
files = os.listdir( './' + folder)
if len(files) < 1:
print 'No words files in folder: ', folder
sys.exit()
return files
def open_file(se... |
from django.conf import settings
from lino.api import dd, rt
from lino.utils import Cycler
def objects():
polls = rt.models.polls
five = polls.ChoiceSet.objects.get(name="1...5")
ten = polls.ChoiceSet.objects.get(name="1...10")
USERS = Cycler(settings.SITE.user_model.objects.all())
def poll(ch... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
.. py:currentmodule:: leepstools.file.__init__
.. moduleauthor:: Hendrix Demers <<EMAIL>>
Package for read and write LEEPS input / output files.
"""
###############################################################################
# Copyright 2017 Hendrix Demers
#
# L... |
import unittest
from unittest import mock
import tethys_cli.link_commands as link_commands
class TestLinkCommands(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
@mock.patch('tethys_cli.link_commands.exit')
@mock.patch('tethys_cli.link_commands.link_service_to_app_... |
import os
from fabric.api import *
from fabric.colors import red, green
import pear
@task
def loc():
"""
Run phploc on the project
"""
if (pear.pear_detect('phploc')):
local('phploc --exclude app/cache,app/logs/vendor')
else:
print(red('The PEAR package phploc is not installed.', Tr... |
from enum import Enum, EnumMeta
from six import with_metaclass
class _CaseInsensitiveEnumMeta(EnumMeta):
def __getitem__(self, name):
return super().__getitem__(name.upper())
def __getattr__(cls, name):
"""Return the enum member matching `name`
We use __getattr__ instead of descriptors... |
"""
Provides XML support.
@since: 0.6
"""
#: list of supported third party packages that support the C{etree}
#: interface. At least enough for our needs anyway.
ETREE_MODULES = [
'lxml.etree',
'xml.etree.cElementTree',
'cElementTree',
'xml.etree.ElementTree',
'elementtree.ElementTree'
]
#: A tup... |
from .base import Source
class FilterBase(Source):
def predicate(self, obj):
pass
def reset(self):
super().reset()
def __next__(self):
next_elem = next(self.parent)
while not self.predicate(next_elem):
next_elem = next(self.parent)
return next_elem
c... |
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
# read data
#
reader ... |
# coding: utf-8
from django.conf import settings
from django.db import connection
from django.utils.translation import ugettext as _
from modoboa.lib.exceptions import InternalError
def db_table_exists(table, cursor=None):
"""Check if table exists
Taken from here:
https://gist.github.com/527113/307c2de... |
""" run with
nosetests -v
nosetests -v --nocapture
TODO:: rest cloud commands
"""
from cloudmesh_base.util import HEADING
from cloudmesh_base.logger import LOGGER
import os
import unittest
log = LOGGER(__file__)
class Test(unittest.TestCase):
def setUp(self):
self.cloudname = "india"
... |
from __future__ import division
import numpy as np
from scipy import interpolate
# parameter matrix types
Z = IMPEDANCE = TYPE_Z = 'Z'
Y = ADMITTANCE = TYPE_Y = 'Y'
S = SCATTERING = TYPE_S = 'S'
T = SCATTERING_TRANSFER = TYPE_T = 'T'
H = HYBRID = TYPE_H = 'H'
G = INVERSE_HYBRID = TYPE_G = 'G'
ABCD = TRANSMISSION = T... |
from SimPEG import Mesh, Regularization, Maps, Utils, EM
from SimPEG.EM.Static import DC
import numpy as np
import matplotlib.pyplot as plt
#%matplotlib inline
import copy
#import pandas as pd
#from scipy.sparse import csr_matrix, spdiags, dia_matrix,diags
#from scipy.sparse.linalg import spsolve
from scipy.stats imp... |
from geoscript.feature import Feature
from geoscript.layer import Layer, Raster
from geoscript.render import Map
from geoscript.style import Stroke
from geoscript.workspace import Memory
def draw(obj, style=None, bounds=None, size=None, format=None, **options):
"""
Draws an object onto a canvas.
*obj* can be a ... |
#!/bin/env python
# encoding:utf-8
#
#
#
__Author__ = "CORDEA"
__date__ = "2014-11-25"
import sys
with open(sys.argv[1]) as f:
lines = f.readlines()
conDict = {
"YRI": "AFR",
"CHB": "ASN",
"TSI": "EUR",
"LWK": "AFR",
"CHS": "ASN",
"GBR": "EUR",
"IBS": ... |
#!/usr/bin/env python
import os
import os.path
import shutil
import subprocess
in_path = "/Users/eric/Library/Application Support/Google/Chrome/Default/File System/030/p/"
out_path = "/Users/WebstormProjects/gl-water2d/lol2_frames/"
in_file_num = 0
out_frame_num = 0
# create output directory if necessary.
if not os... |
#!/usr/bin/env python
################
# see notes at bottom for requirements
from __future__ import absolute_import, print_function
import glob
import os
import sys
from sys import platform
from distutils.core import setup
from pkg_resources import parse_version
# import versioneer
import psychopy
version = psychopy._... |
from __future__ import unicode_literals
import xml.etree.ElementTree as ElementTree
class MathNode(object):
"""Backs ont an ElementTree node. Provides an easier interface, info on where to go for zooming, and node-specific template strings set by the rule functions."""
def __init__(self, tag, associated_xml, templ... |
"""
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distri... |
import webob
import webob.exc
import deform
import colander
from wiseguy.loader import AppLoader
@colander.deferred
def deferred_component_validator(node, kw):
loader = kw['loader']
components = loader.ep_parser.get_components()
def validate(node, val):
for component_name, component in components:
... |
"""Test the bumpfee RPC.
Verifies that the bumpfee RPC creates replacement transactions successfully when
its preconditions are met, and returns appropriate errors in other cases.
This module consists of around a dozen individual test cases implemented in the
top-level functions named as test_<test_case_description>.... |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import (
compat_etree_fromstring,
compat_str,
compat_urlparse,
)
from ..utils import (
ExtractorError,
int_or_none,
sanitized_Request,
parse_iso8601,
)
class VevoBaseIE(InfoExtractor):
d... |
"""
Copyright 2011-13 Attila Zseder
Email: <EMAIL>
This file is part of hunmisc project
url: https://github.com/zseder/hunmisc
hunmisc is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of... |
from testfixtures import LogCapture
from twisted.internet import defer
from scrapy.exceptions import StopDownload
from tests.test_engine import (
AttrsItemsSpider,
DataClassItemsSpider,
DictItemsSpider,
TestSpider,
CrawlerRun,
EngineTest,
)
class BytesReceivedCrawlerRun(CrawlerRun):
def ... |
"""Single use seals
Similar to those serialized zip-ties and tamper-evident bags used to verify the
authenticity of physical items, single use seals are special cryptographic
constructs that have a unique hash and can be applied to seal another hash
exactly once, producing a seal witness.
"""
import proofmarshal.pro... |
from direct.showbase.ShowBase import ShowBase
base = ShowBase()
from direct.gui.DirectGui import *
from panda3d.core import TextNode
import sys
from panda3d.core import PointLight
from panda3d.core import LVector3
from panda3d.core import AmbientLight
#soundtrack = base.loader.loadSfx("sound\secunda.mp3")
#soundtrac... |
from django.db import models
from django.template.defaultfilters import slugify
from game.gamelog import game_log
from names import get_full_name
# Note that all handle functions slugify to allow either name or slug input
def GetCityHandle(targetName):
return City.objects.get(slug=slugify(targetName))
def GetUnit... |
"""
Narrative authentication tools.
This uses the KBase auth2 API to get and manage auth tokens.
"""
import requests
import json
from biokbase.narrative.common.url_config import URLS
from biokbase.narrative.common.util import kbase_env
tokenenv = 'KB_AUTH_TOKEN'
token_api_url = URLS.auth + "/api/V2"
endpt_token = "/t... |
"""
Test cases for the L{twisted.python.reflect} module.
"""
import weakref
from collections import deque
try:
from ihooks import ModuleImporter
except ImportError:
ModuleImporter = None
from twisted.trial import unittest
from twisted.python import reflect
from twisted.python.versions import Version
from twi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.