code
stringlengths
1
199k
"""Tests for the CSRF helper.""" import unittest import mock import webapp2 import webtest from ctc.helpers import csrf from ctc.testing import testutil MOCKED_TIME = 123 class CsrfTests(testutil.CtcTestCase): # Helpers class TestHandler(csrf.CsrfHandler): """A handler for testing whether or not request...
u'''MCL — Publication Folder''' from ._base import IIngestableFolder, Ingestor, IngestableFolderView from .interfaces import IPublication from five import grok class IPublicationFolder(IIngestableFolder): u'''Folder containing publications.''' class PublicationIngestor(Ingestor): u'''RDF ingestor for publicatio...
import os import tempfile import unittest import logging from pyidf import ValidationLevel import pyidf from pyidf.idf import IDF from pyidf.exterior_equipment import ExteriorFuelEquipment log = logging.getLogger(__name__) class TestExteriorFuelEquipment(unittest.TestCase): def setUp(self): self.fd, self.pa...
from collections import defaultdict import codecs def count(corpus, output_file): debug = False dic = defaultdict(int) other = set() fout = codecs.open(output_file, 'w', 'utf8') for line in open(corpus, 'r'): words = line.split() for word in words: if len(word) % 3 == 0: ...
from __future__ import absolute_import import collections import io import json import time try: import fastavro except ImportError: # pragma: NO COVER fastavro = None import google.api_core.exceptions import google.rpc.error_details_pb2 try: import pandas except ImportError: # pragma: NO COVER pandas...
from capstone import * from .architecture import Architecture from avatar2.installer.config import GDB_X86, OPENOCD class X86(Architecture): get_gdb_executable = Architecture.resolve(GDB_X86) get_oocd_executable = Architecture.resolve(OPENOCD) qemu_name = 'i386' gdb_name = 'i386' registers = {'eax'...
import instantiation_validation_benchmark as base from experimental_framework import common NUM_OF_NEIGHBORS = 'num_of_neighbours' AMOUNT_OF_RAM = 'amount_of_ram' NUMBER_OF_CORES = 'number_of_cores' NETWORK_NAME = 'network' SUBNET_NAME = 'subnet' class InstantiationValidationNoisyNeighborsBenchmark( base.Instan...
"""Sends a text mesage to the user with a suggestion action to dial a phone number. Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#dial_action This code is based on the https://github.com/google-business-communications/python-businessmessages Python B...
from world import world from bigml.api import HTTP_OK def i_get_the_project(step, resource): resource = world.api.get_project(resource) world.status = resource['code'] assert world.status == HTTP_OK world.project = resource['object']
from oslo_config import cfg from oslo_log import log as logging from oslo_utils import uuidutils from sqlalchemy.orm import exc from sqlalchemy.sql import expression as expr from neutron.db import models_v2 from neutron.extensions import l3 from neutron_lib import constants as l3_constants from neutron_lib import excep...
import unittest from unittest import mock import pytest from google.cloud.vision import enums from google.cloud.vision_v1 import ProductSearchClient from google.cloud.vision_v1.proto.image_annotator_pb2 import ( AnnotateImageResponse, EntityAnnotation, SafeSearchAnnotation, ) from google.cloud.vision_v1.pro...
from django.db import models from django.utils.html import format_html from sorl.thumbnail import get_thumbnail from sorl.thumbnail.fields import ImageField from sno.models import Sno class SnoGalleries(models.Model): class Meta: verbose_name = 'Фотография в галереи СНО' verbose_name_plural = 'Фотог...
"""Library for network related helpers.""" import socket def get_ip(): """Get primary IP (the one with a default route) of local machine. This works on both Linux and Windows platforms, and doesn't require working internet connection. """ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: # doesn...
import functools import warnings from collections import Mapping, Sequence from numbers import Number import numpy as np import pandas as pd from . import ops from . import utils from . import common from . import groupby from . import indexing from . import alignment from . import formatting from .. import conventions...
import random import time import threading import multiprocessing import numpy as np from tqdm import tqdm from six.moves import queue from tensorpack import * from tensorpack.utils.concurrency import * from tensorpack.utils.stats import * def play_one_episode(player, func, verbose=False): def f(s): spc = p...
import optparse import pickle parser = optparse.OptionParser() parser.add_option('-i','--input', dest = 'input_file', help = 'input_file') parser.add_option('-o','--output', dest = 'output_file', help = 'output_file') (options, args) = parser.parse_args() if options.input_file is None: options.input_file = raw_input...
import errno import os import pwd import shutil import sys from jinja2 import Environment, FileSystemLoader class TutorialEnv: LOCAL_MACHINE = ("Local Machine Condor Pool", "submit-host") USC_HPCC_CLUSTER = ("USC HPCC Cluster", "usc-hpcc") OSG_FROM_ISI = ("OSG from ISI submit node", "osg") XSEDE_BOSCO =...
""" Django settings for sparta project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) SECRET_KEY = '...
from django.views.generic import ListView, DetailView, CreateView from django.db.models import Q from django.http import JsonResponse, HttpResponseRedirect from django.core.urlresolvers import reverse from django.shortcuts import render from pure_pagination.mixins import PaginationMixin from django.contrib.auth.mixins ...
import itertools import collections def read_table(filename): with open(filename) as fp: header = next(fp).split() rows = [line.split()[1:] for line in fp if line.strip()] columns = zip(*rows) data = dict(zip(header, columns)) return data table = read_table("../../data/colldata.txt")...
from __future__ import with_statement import operator import threading from mapproxy.grid import bbox_intersects, bbox_contains from mapproxy.util.py import cached_property from mapproxy.util.geom import ( require_geom_support, load_polygon_lines, transform_geometry, bbox_polygon, ) from mapproxy.srs im...
class InfortrendNASTestData(object): fake_share_id = ['5a0aa06e-1c57-4996-be46-b81e360e8866', # NFS 'aac4fe64-7a9c-472a-b156-9adbb50b4d29'] # CIFS fake_share_name = [fake_share_id[0].replace('-', ''), fake_share_id[1].replace('-', '')] fake_channel_ip = ['172.27...
from google.cloud import resourcemanager_v3 async def sample_get_tag_key(): # Create a client client = resourcemanager_v3.TagKeysAsyncClient() # Initialize request argument(s) request = resourcemanager_v3.GetTagKeyRequest( name="name_value", ) # Make the request response = await clie...
"""Python utilities required by Keras.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import binascii import codecs import marshal import os import re import sys import time import types as python_types import numpy as np import six from tensorflow.python...
from __future__ import unicode_literals import pytest import allure_commons from allure_pytest.utils import ALLURE_LABEL_PREFIX, ALLURE_LINK_PREFIX class AllureTestHelper(object): def __init__(self, config): self.config = config @allure_commons.hookimpl def decorate_as_label(self, label_type, labels...
from django import forms from django.utils.text import slugify from .models import Farmwork class FarmworkForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(FarmworkForm, self).__init__(*args, **kwargs) class Meta: model = Farmwork fields = [ 'job_role', ...
from django.contrib.auth.models import AnonymousUser from core.models import Identity from api.v2.serializers.post import AccountSerializer from api.v2.views.base import AdminAuthViewSet class AccountViewSet(AdminAuthViewSet): """ API endpoint that allows providers to be viewed or edited. """ lookup_fie...
""" The DT_Utils module provides helper functions for Decision Tree algorithms implementation, model creation and analysis. """ import pickle from matplotlib import pyplot as plt from sklearn.metrics import mean_squared_error from tools.Utils import create_folder_if_not_exists def score_dt(model_name, model, X,...
from artnet import * import SocketServer import time, os, random, datetime, sys import argparse import socket import struct from subprocess import Popen, PIPE, STDOUT import glob DEBUG = False UDP_IP = "2.0.0.61" UDP_PORT = 6454
import sys from drone.actions.emr_launcher import launch_emr_task from drone.actions.ssh_launcher import launch_ssh_task from drone.job_runner.dependency_manager import dependencies_are_met from drone.job_runner.job_progress_checker import check_running_job_progress from drone.metadata.metadata import get_job_info, job...
import scrapy from scrapy import log from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor from rcbi.items import Part import copy import json import re VARIANT_JSON_REGEX = re.compile("product: ({.*}),") class ShendronesSpider(CrawlSpider): name = "shendrones" allowed_domains...
from karld.loadump import dump_dicts_to_json_file from karld.loadump import ensure_dir from karld.loadump import ensure_file_path_dir from karld.loadump import i_get_csv_data from karld.loadump import is_file_csv from karld.loadump import i_get_json_data from karld.loadump import is_file_json from karld.loadump import ...
import uuid from mock import Mock, patch from trove.backup import models as backup_models from trove.common import cfg from trove.common import exception from trove.common.instance import ServiceStatuses from trove.datastore import models as datastore_models from trove.instance import models from trove.instance.models ...
import abc import copy import os import oslo_messaging import six from neutron.agent.linux import ip_lib from neutron.common import rpc as n_rpc from neutron import context from neutron_lib import constants from neutron_lib.plugins import directory from neutron_vpnaas.services.vpn import device_drivers from neutron_vpn...
from django.conf.urls import patterns, include, url from django.contrib import admin from api import views admin.autodiscover() from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'headings', views.HeadingViewSet) router.register(r'users', views.UserViewSet) urlpatterns = patterns...
import functools import logbook import math import numpy as np import numpy.linalg as la from six import iteritems from zipline.finance import trading import pandas as pd from . import risk from . risk import ( alpha, check_entry, information_ratio, sharpe_ratio, sortino_ratio, ) log = logbook.Logge...
from bs4 import BeautifulSoup as Soup import glob import sys import re """ Version xml de cfdi 3.3 """ class CFDI(object): def __init__(self, f): """ Constructor que requiere en el parámetro una cadena con el nombre del cfdi. """ fxml = open(f,'r').read() soup ...
from colorama import Fore, Back class frets: tuning = list() max_string_name_len = 0; frets_count = 0; strings = dict() NOTES = ('E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B', 'C', 'C#', 'D', 'D#') def __init__(self, tuning=('E', 'A', 'D', 'G'), frets_count=24): ...
import os_resource_classes as orc import os_traits import six from nova import context as nova_context from nova import exception from nova import objects from nova.tests.functional.api import client as api_client from nova.tests.functional import integrated_helpers from nova import utils class TestServicesAPI(integrat...
import tarfile class load_data: ''' class to load txt data ''' def __init__(self, filename): self.filename = filename tfile, members = self.get_archive_object_tar() self.read_files(tfile, members) def get_archive_object_tar(self): ''' return tarfile object and...
zhangyu
from .fetch import FetchParser from .json_ld import JsonLdParser from .lom import LomParser from .lrmi import LrmiParser from .nsdl_dc import NsdlDcParser __all__ = [ 'FetchParser', 'JsonLdParser', 'LomParser', 'LrmiParser', 'NsdlDcParser', ]
"""Python front-end supports for functions. NOTE: functions are currently experimental and subject to change! """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import hashlib from tensorflow.core.framework import attr_value_pb2 from tenso...
import sys, os extensions = ['sphinx.ext.intersphinx', 'sphinx.ext.todo'] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = u'Armstrong Platform' copyright = u'2011, Bay Citizen and Texas Tribune' version = '12.03.1' release = '12.03.1' exclude_patterns = [] pygments_style = 'sphinx'...
""" Helper module for ORMBad version information. """ __version_info__ = { 'major': 0, 'minor': 1, 'micro': 0, 'releaselevel': 'final', 'serial': 0, } def get_version(short=False): """ Returns the version from the version info. """ assert __version_info__['releaselevel'] in ('alpha',...
"""This example creates a bidder-level filter set. A bidder-level filter set can be used to retrieve aggregated data for all Authorized Buyers accounts under the given bidder account, including the bidder account itself. """ import argparse from datetime import date from datetime import datetime from datetime import ti...
"""Tests for Keras core layers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python import keras from tensorflow.python.eager import context from tensorflow.python.framework import ops from tensorflow.python.keras impo...
from __future__ import ( unicode_literals, print_function, division, absolute_import, ) str = type('') import ctypes as ct import warnings _lib = ct.CDLL('libbcm_host.so') bcm_host_init = _lib.bcm_host_init bcm_host_init.argtypes = [] bcm_host_init.restype = None bcm_host_deinit = _lib.bcm_host_dein...
import Tkinter as tk from picamera import PiCamera from time import sleep from PIL import Image,ImageFilter,ImageChops,ImageTk imagefile = "image.jpg" w = 320 h = 240 lastfilter = "none" camera = PiCamera() def takephoto(): camera.capture(imagefile) image1 = Image.open(imagefile) return image1 def photoloop(): coun...
"""Support for switches which integrates with other components.""" import logging import voluptuous as vol from homeassistant.components.switch import ( ENTITY_ID_FORMAT, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME, CONF_ENTITY_PICTURE_TE...
"""Federated CIFAR-10 classification library using TFF.""" import functools from typing import Callable, Optional from absl import logging import tensorflow as tf import tensorflow_federated as tff from fedopt_guide import training_loop from utils.datasets import cifar10_dataset from utils.models import resnet_models C...
from django.db import models from django.contrib.auth.models import User class Activity(models.Model): owner = models.ForeignKey(User, null=False) text = models.CharField(max_length=20, unique=True) class Dessert(models.Model): activity = models.ForeignKey(Activity, null=False) description = models.Text...
import time from tsm.common.app import exception import requests import json from requests.packages.urllib3.util.retry import Retry from requests.adapters import HTTPAdapter KANGROUTER_WEBSERVICE_APPLICATION_ROOT="/kangrouter/srv/v1" class KangRouterClient: pathbase = "https://thesolvingmachine.com/kangrouter/srv/v1/...
""" This pretty much just tests creating a user, a universe, a planet, a building type name, a building type, and a building. """ import os import sys import sqlalchemy sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) import legendary_waffle db_engine = sqlalchemy.create_engine("sqlite...
"""heroku_blog URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class...
"""Tests for nova websocketproxy.""" import mock from nova.console import websocketproxy from nova import exception from nova import test class NovaProxyRequestHandlerBaseTestCase(test.TestCase): def setUp(self): super(NovaProxyRequestHandlerBaseTestCase, self).setUp() self.wh = websocketproxy.NovaP...
"""Contains the logic for `aq add rack --bunker`.""" from aquilon.worker.broker import BrokerCommand # pylint: disable=W0611 from aquilon.worker.commands.add_rack import CommandAddRack class CommandAddRackBunker(CommandAddRack): required_parameters = ["bunker", "row", "column"]
import netaddr from rally.common import logging from rally.common.utils import RandomNameGeneratorMixin from rally_ovs.plugins.ovs import ovsclients from rally_ovs.plugins.ovs import utils LOG = logging.getLogger(__name__) class OvnClientMixin(ovsclients.ClientsMixin, RandomNameGeneratorMixin): def _get_ovn_control...
import grpc from google.cloud.spanner_v1.proto import ( result_set_pb2 as google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2, ) from google.cloud.spanner_v1.proto import ( spanner_pb2 as google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2, ) from google.cloud.spanner_v1.proto import ( t...
import allure from selenium.webdriver.common.by import By from .base import BasePage from .elements import SimpleInput, SimpleText from .blocks.nav import NavBlock class BrowseMoviePageLocators(object): """Локаторы страницы просмотра информации о фильме""" TITLE_LOCATOR = (By.CSS_SELECTOR, '#movie h2') COUN...
""" Copyright 2015-2018 IBM 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 distr...
import unittest import pykintone from pykintone.model import kintoneModel import tests.envs as envs class TestAppModelSimple(kintoneModel): def __init__(self): super(TestAppModelSimple, self).__init__() self.my_key = "" self.stringField = "" class TestComment(unittest.TestCase): def test...
''' The Salt Key backend API and interface used by the CLI. The Key class can be used to manage salt keys directly without interfacing with the CLI. ''' from __future__ import absolute_import, print_function import os import copy import json import stat import shutil import fnmatch import hashlib import logging import ...
""" WSGI config for brp project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """ import os from dj_static import Cling from django.core.wsgi import get_wsgi_application os.environ.setde...
""" recursely """ __version__ = "0.1" __description__ = "Recursive importer for Python submodules" __author__ = "Karol Kuczmarski" __license__ = "Simplified BSD" import sys from recursely._compat import IS_PY3 from recursely.importer import RecursiveImporter from recursely.utils import SentinelList __all__ = ['install'...
import sys from setuptools import setup, find_packages NAME = "pollster" VERSION = "2.0.2" REQUIRES = ["urllib3 >= 1.15", "six >= 1.10", "certifi", "python-dateutil", "pandas >= 0.19.1"] setup( name=NAME, version=VERSION, description="Pollster API", author_email="Adam Hooper <adam.hooper@huffingtonpost....
import requests import logging import redis from requests.packages.urllib3.exceptions import ConnectionError from core.serialisers import json from dss import localsettings HEADERS = { 'content-type': 'application/json' } logger = logging.getLogger('spa') def post_notification(session_id, image, message): try: ...
__version__ = '0.6.4-dev'
from django.conf import settings from django.conf.urls import include, patterns, url from django.views.decorators import csrf from django.views.generic import base from django.contrib import admin admin.autodiscover() from devincachu.destaques import views as dviews from devincachu.inscricao import views as iviews from...
import roslib; roslib.load_manifest('face_detection') import rospy import sys import cv from cv_bridge import CvBridge from sensor_msgs.msg import Image from geometry_msgs.msg import Point from geometry_msgs.msg import PointStamped cv_bridge = CvBridge() def callback(publisher, coord_publisher, cascade, imagemsg): ...
from __future__ import print_function import urllib from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * from jp.ac.kyoto_su.aokilab.dragon.mvc.model import OpenGLModel from jp.ac.kyoto_su.aokilab.dragon.mvc.view import * from jp.ac.kyoto_su.aokilab.dragon.opengl.triangle import OpenGLTriangle fro...
from lino.core.roles import UserRole class SimpleContactsUser(UserRole): pass class ContactsUser(SimpleContactsUser): pass class ContactsStaff(ContactsUser): pass
from django.db.models import Transform from django.db.models import DateTimeField, TimeField from django.utils.functional import cached_property class TimeValue(Transform): lookup_name = 'time' function = 'time' def as_sql(self, compiler, connection): lhs, params = compiler.compile(self.lhs) ...
__author__ = 'Adam R. Smith, Michael Meisinger, Dave Foster <dfoster@asascience.com>' import threading import traceback import gevent from gevent import greenlet, Timeout from gevent.event import Event, AsyncResult from gevent.queue import Queue from pyon.core import MSG_HEADER_ACTOR from pyon.core.bootstrap import CFG...
""" Module for listing commands and help. """ from basemodule import BaseModule, BaseCommandContext from alternatives import _ class HelpContext(BaseCommandContext): def cmd_list(self, argument): """List commands""" arg = argument.lower() index = self.bot.help_index public = "public ...
''' Created on Dec 16, 2014 @author: Jaakko Leppakangas ''' import sys from PyQt4 import QtGui from ui.preprocessDialog import PreprocessDialog def main(): app = QtGui.QApplication(sys.argv) window=PreprocessDialog() window.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
""" Pygments HTML formatter tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: Copyright 2006-2009 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import os import re import unittest import StringIO import tempfile from os.path import join, dirname, isfile, abspath from pygme...
import itertools import numba import numpy as np import os import pandas as pd import pyarrow.parquet as pq import random import string import unittest from numba import types import sdc from sdc import hiframes from sdc.str_arr_ext import StringArray from sdc.tests.test_base import TestCase from sdc.tests.test_utils i...
import pytest import urllib.error from urlpathlib import UrlPath def test_scheme(): # does not raise NotImplementedError UrlPath('/dev/null').touch() def test_scheme_not_supported(): with pytest.raises(NotImplementedError): UrlPath('http:///tmp/test').touch() def test_scheme_not_listed(): with p...
from __future__ import unicode_literals from flask import abort, make_response, request from flask_api.decorators import set_renderers from flask_api import exceptions, renderers, status, FlaskAPI import json import unittest app = FlaskAPI(__name__) app.config['TESTING'] = True class JSONVersion1(renderers.JSONRenderer...
from celery.task import Task import requests class StracksFlushTask(Task): def run(self, url, data): requests.post(url + "/", data=data)
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('freebasics', '0006_change_site_url_field_type'), ] operations = [ migrations.AddField( model_name='freebasicscontroller', name='p...
def excise(conn, qrelname, tid): with conn.cursor() as cur: # Assume 'id' column exists and print that for bookkeeping. # # TODO: Instead should find unique constraints and print # those, or try to print all attributes that are not corrupt. sql = 'DELETE FROM {0} WHERE ctid =...
import datetime from django.utils import timezone from django.test import TestCase from django.urls import reverse from .models import Question class QuestionMethodTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() should return False for questi...
"""--- Day 3: Perfectly Spherical Houses in a Vacuum --- Santa is delivering presents to an infinite two-dimensional grid of houses. He begins by delivering a present to the house at his starting location, and then an elf at the North Pole calls him via radio and tells him where to move next. Moves are always exactly o...
import logging from ...sim_type import SimTypeFunction, SimTypeShort, SimTypeInt, SimTypeLong, SimTypeLongLong, SimTypeDouble, SimTypeFloat, SimTypePointer, SimTypeChar, SimStruct, SimTypeFixedSizeArray, SimTypeBottom, SimUnion, SimTypeBool from ...calling_conventions import SimCCStdcall...
""" femagtools.plot ~~~~~~~~~~~~~~~ Creating plots """ import numpy as np import scipy.interpolate as ip import logging try: import matplotlib import matplotlib.pyplot as plt import matplotlib.cm as cm from mpl_toolkits.mplot3d import Axes3D matplotlibversion = matplotlib.__version__ exc...
from __future__ import (absolute_import, division, print_function) from . import _wrap_numbers, Symbol, Number, Matrix def symbols(s): """ mimics sympy.symbols """ tup = tuple(map(Symbol, s.replace(',', ' ').split())) if len(tup) == 1: return tup[0] else: return tup def symarray(prefix, ...
fruit = ["apples", "oranges", "pears", "grapes", "blueberries"] lunch = ["pho", "timmies", "thai", "burgers", "buffet!", "indian", "montanas"] situations = {"fruit":fruit, "lunch":lunch}
""" sim_det_noise.py implements the noise simulation operator, OpSimNoise. """ import numpy as np from ..op import Operator from ..ctoast import sim_noise_sim_noise_timestream as sim_noise_timestream from .. import timing as timing class OpSimNoise(Operator): """ Operator which generates noise timestreams. ...
import zmq import time if __name__ == '__main__': ctx = zmq.Context() worker = ctx.socket(zmq.PULL) worker.connect('tcp://localhost:5555') sinker = ctx.socket(zmq.PUSH) sinker.connect('tcp://localhost:6666') print 'all workers are ready ...' while True: try: msg = worker.recv() print 'begi...
from unittest import TestCase import pkg_resources from mock import patch from click import UsageError from click.testing import CliRunner class TestCli(TestCase): @patch('molo.core.cookiecutter.cookiecutter') def test_scaffold(self, mock_cookiecutter): from molo.core.scripts import cli package ...
import numpy as np from scipy.sparse import csr_matrix class AliasArray(np.ndarray): """An ndarray with a mapping of values to user-friendly names -- see example This ndarray subclass enables comparing sub_id and hop_id arrays directly with their friendly string identifiers. The mapping parameter translates...
import warnings import pytest import numpy as np from numpy.testing.utils import assert_allclose from ... import units as u from ...tests.helper import raises from ...extern.six.moves import zip from ...utils.compat import NUMPY_LT_1_13 class TestUfuncCoverage(object): """Test that we cover all ufunc's""" def t...
""" berenson@eecs.berkeley.edu) of its """ """ This node advertises an action which is used by the main lightning node (see run_lightning.py) to run the Retrieve and Repair portion of LightningROS. This node relies on a planner_stoppable type node to repair the paths, the PathTools library to retrieve paths from the li...
from django.core.management import setup_environ import settings setup_environ(settings) import socket from trivia.models import * irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) irc.connect((settings.IRC_SERVER, settings.IRC_PORT)) def send(msg): irc.send(msg + "\r\n") print "{SENT} " + msg return def...
""" Commands that are available from the connect screen. """ import re import traceback from django.conf import settings from src.players.models import PlayerDB from src.objects.models import ObjectDB from src.server.models import ServerConfig from src.comms.models import Channel from src.utils import create, logger, u...
import json import os import subprocess import sys sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import pynacl.platform python = sys.executable bash = '/bin/bash' echo = 'echo' BOT_ASSIGNMENT = { ###################################################################### # Buildbots. ###########...
from contextlib import contextmanager from _pytest.python import FixtureRequest import mock from mock import Mock import pyramid.testing from webob.multidict import MultiDict import pyramid_swagger import pyramid_swagger.tween import pytest import simplejson from pyramid.config import Configurator from pyramid.interfac...
import ghcnpy ghcnpy.intro() ghcnpy.get_ghcnd_version() print("\nTESTING SEARCH CAPABILITIES") ghcnpy.find_station("Asheville") print("\nTESTING PULL CAPABILITIES") outfile=ghcnpy.get_data_station("USW00003812") print(outfile," has been downloaded")