code
stringlengths
1
199k
from satsolver.util import Result, Failure, Success def test_result(): res = Result() assert not res.success assert res.result is None def test_success_defaults(): suc = Success() assert suc.success assert suc.result is None def test_success_with_result(): suc = Success(result=1234) asse...
"""Common utilities for data pipeline tools.""" import contextlib import shutil import tempfile import time from typing import Optional from absl import logging @contextlib.contextmanager def tmpdir_manager(base_dir: Optional[str] = None): """Context manager that deletes a temporary directory on exit.""" tmpdir = t...
import sys import Intermediate_Representation_DSL_Translator.flexAndBison as ITASIR_DSL_Interpreter import Intermediate_Representation_DSL_Translator.Publisher_Subscriber_Pattern as psp if sys.platform == 'win32': PATH_DELIM = "\\" TEMPLATE_PACKS_DIR = "D:\\Projects\\JetBrains\\PyCharm_Workspace\\Diploma\\WebSe...
from __future__ import print_function import os from formation import AtomicTemplate, Template OUTPUT_FILE = os.path.join( os.path.dirname(os.path.dirname(__file__)), "output", "004_vpc_in_template.yaml" ) def main(): template = Template() vpc = AtomicTemplate("VPC", "EC2::VPC") template.merge(v...
from fbads.managers.base import Manager from fbads.resources.account import AccountResource class AccountManager(Manager): resource_class = AccountResource def _get_api_path(self, object_id): return 'act_{0}'.format(self._api.account_id) def list(self, *args, **kwargs): raise NotImplementedE...
import gym import torch.nn as nn import torch import torch.optim as optim import numpy as np import torch.nn.functional as F from torch.autograd import Variable from torch.distributions import Categorical from itertools import count env = gym.make('CartPole-v0') from tensorboard_logger import log_value, configure confi...
from pocket_change.auth import PocketChangeUser from flask import g @PocketChangeUser.authenticator def jira_auth(user): if g.jira.verify_credentials(user.name, user.password): # If the user already exists in the database, # update their password to match what authenticated # in Jira to keep...
"""A natural text boolean expression task of variable difficulty.""" import bigbench.api.task as task import random import math class WebOfLiesTask(task.Task): """A natural text boolean expression task of variable difficulty.""" _names = [ "Crista", "Lorine", "Alejandro", "Millie...
import numpy as np from vessel_scoring.utils import get_cols_by_name import vessel_scoring.base_model COURSE_STD = 0 SPEED_STD = 1 SPEED_AVG = 2 SHORE_DIST = 3 class LegacyHeuristicModel(vessel_scoring.base_model.BaseModel): def __init__(self, window='3600'): """ window - window size to use in featu...
""" Copyright 2015 SmartBear Software 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...
from flask.ext.testing import TestCase as Base from tracker import create_app from tracker.models import User, Expense, Comment from tracker.config import TestConfig from tracker.extensions import db from flask.ext.login import login_user import datetime class TestCase(Base): """Base TestClass for your application....
from kfp.deprecated import dsl, compiler def gcs_download_op(url): return dsl.ContainerOp( name='GCS - Download', image='google/cloud-sdk:279.0.0', command=['sh', '-c'], arguments=['gsutil cat $0 | tee $1', url, '/tmp/results.txt'], file_outputs={ 'data': '/tmp/re...
"""Tests for gate_compilation.py""" import numpy as np import cirq from cirq_google.optimizers.two_qubit_gates.gate_compilation import ( gate_product_tabulation, GateTabulation, ) import cirq_google.optimizers.two_qubit_gates as cgot def test_deprecated_gate_product_tabulation(): with cirq.testing.assert_de...
__title__ = 'backend' __version__ = '1.0' __author__ = 'Andrea Biancini' __copyright__ = 'Copyright 2013 Andrea Biancini' __date__ = "October 2, 2013" from .backend import BackendChooser, BackendError from .mysqlbackend import MySQLBackend from .elasticsearchbackend import ElasticSearchBackend __all__ = [ 'B...
import json import ssl try: import urllib.request as request except ImportError: import urllib2 as request from skydive.auth import Authenticate from skydive.graph import Node, Edge class BadRequest(Exception): pass class RESTClient: def __init__(self, endpoint, scheme="http", username=...
from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Account', fields=[ ('id', models.AutoField(verb...
"""Thompson sampling evaluation of ENN agent on GP regression task.""" import functools from typing import Dict, Optional, Sequence, Tuple from acme.utils import loggers from enn import base as enn_base from enn import utils from enn.experiments.neurips_2021 import agents from enn.experiments.neurips_2021 import base a...
TILESIZE = 10 MAPWIDTH = 160 MAPHEIGHT = 80 PADDING = 0 TEXTURE_PATH = 'art/tiles/' FONT_PATH = 'art/fonts/' HILL = 0 GRASS = 1 WATER = 2 FOREST = 3 COAST = 4 CITY = 5 LOWHILL = 8 MOUNTAIN = 9 PLAYER = 6 ROAD = 7 TERRAIN_NAMES = { 0: 'Hills', 1: 'Grass', 2: 'Water', 3: 'Fo...
"""Functional tests for convolutional operations.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import os import time import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin from tensorflow.contrib import l...
from typing import Set from zerver.models import MutedTopic class StreamTopicTarget: """ This class is designed to help us move to a StreamTopic table or something similar. It isolates places where we are are still using `topic_name` as a key into tables. """ def __init__(self, stream_id: i...
import os import imghdr import mimetypes from webapp.web import BaseHandler class AvatarHandler(BaseHandler): def get(self, name): fullpath = "images/" + name filetype = "jpeg" if os.path.isfile("images/" + name): with open(fullpath, "rb") as f: image = f.read() ...
import errno import socket from _ssl import CERT_NONE from _ssl import CERT_REQUIRED from threading import Thread from ws4py.client.threadedclient import WebSocketClient import sdk.util as util if util.P3: pass else: pass try: from OpenSSL.SSL import Error as pyOpenSSLError except ImportError: class pyO...
"""Test Home Assistant scenes.""" from unittest.mock import patch import pytest import voluptuous as vol from homeassistant.components.homeassistant import scene as ha_scene from homeassistant.setup import async_setup_component from tests.common import async_mock_service async def test_reload_config_service(hass): ...
from .azure_common import BaseTest, arm_template from c7n_azure.utils import ResourceIdParser from jsonschema.exceptions import ValidationError from c7n_azure.session import Session from c7n.utils import local_session class LockActionTest(BaseTest): def setUp(self): super(LockActionTest, self).setUp() ...
import errno import os import click import logbook import pandas as pd from six import text_type from zipline.utils.compat import wraps from zipline.data import bundles as bundles_module from zipline.utils.cli import Date, Timestamp from zipline.utils.run_algo import _run, load_extensions try: __IPYTHON__ except Na...
import os import sys from tornado.util import ObjectDict SERVER_NAME = 'jinja2-support' SERVER_DIR = os.path.dirname(os.path.abspath(__file__)) PROJECT_DIR = os.path.dirname(SERVER_DIR) sys.path.append(PROJECT_DIR) WEB_APPLICATION_SETTING = ObjectDict( static_path=os.path.join(SERVER_DIR, "static"), template_pa...
print("Loading tensorflow...") import tensorflow as tf from libs import utils, gif import numpy as np import matplotlib.pyplot as plt import os plt.style.use('bmh') import datetime plt.ion() plt.figure(figsize=(5, 5)) TID=datetime.date.today().strftime("%Y%m%d")+"_"+datetime.datetime.now().time().strftime("%H%M%S") imp...
import numpy as np from sklearn import datasets from sklearn.decomposition import PCA np.random.seed(0) iris_X, iris_y = datasets.load_iris(return_X_y=True) indices = np.random.permutation(len(iris_X)) iris_X_train = iris_X[indices[:-10]] iris_y_train = iris_y[indices[:-10]] from sklearn.neighbors import KNeighborsClas...
from google.cloud import retail_v2 async def sample_import_completion_data(): # Create a client client = retail_v2.CompletionServiceAsyncClient() # Initialize request argument(s) input_config = retail_v2.CompletionDataInputConfig() input_config.big_query_source.dataset_id = "dataset_id_value" in...
from __future__ import absolute_import, unicode_literals import unittest import gobject gobject.threads_init() import pygst pygst.require('0.10') import gst # noqa: pygst magic is needed to import correct gst import mock from mopidy.models import Track from mopidy.stream import actor from mopidy.utils.path import path...
"""Date or time helper functions.""" import time from clusterfuzz._internal.base import utils from clusterfuzz._internal.system import environment def initialize_timezone_from_environment(): """Initializes timezone for date functions based on environment.""" plt = environment.platform() if plt == 'WINDOWS': r...
""" Send events through Salt's event system during state runs """ import salt.utils.functools def send( name, data=None, preload=None, with_env=False, with_grains=False, with_pillar=False, show_changed=True, **kwargs ): """ Send an event to the Salt Master .. versionadded:: 2...
data = { 'title': 'Marjeska na 4 zvonove', 'song': [ 'x - - - x - - - x - x - x - - - x - - - x - - - x - x - x - - - x - - - x - - - x - x - x - - - x - - - x - - - x - x - x - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ...
__source__ = 'https://leetcode.com/problems/valid-mountain-array/' import unittest class Solution(object): def validMountainArray(self, A): """ :type A: List[int] :rtype: bool """ N = len(A) i = 0 # walk up while i+1 < N and A[i] < A[i+1]: ...
import pytest from hpe_test_utils import OneViewBaseFactsTest from oneview_module_loader import LogicalInterconnectGroupFactsModule ERROR_MSG = 'Fake message error' PARAMS_GET_ALL = dict( config='config.json', name=None ) PARAMS_GET_BY_NAME = dict( config='config.json', name="Test Logical Interconnect G...
""" Handles all requests relating to consistency groups. """ import functools from oslo_config import cfg from oslo_log import log as logging from oslo_utils import excutils from oslo_utils import timeutils from jacket.db import base from jacket.storage import exception from jacket.storage.i18n import _, _LE, _LW from ...
from oslo_serialization import jsonutils import webob from nova.compute import flavors from nova import test from nova.tests.unit.api.openstack import fakes FAKE_FLAVORS = { 'flavor 1': { "flavorid": '1', "name": 'flavor 1', "memory_mb": '256', "root_gb": '10', "swap": 512, ...
from netmiko import ConnectHandler from getpass import getpass from datetime import datetime from net_system.models import NetworkDevice, Credentials import django def main(): django.setup() devices = NetworkDevice.objects.all() starttime = datetime.now() print 'Start time: ', starttime for a_device...
"""Support for Toon sensors.""" from datetime import timedelta import logging from homeassistant.config_entries import ConfigEntry from homeassistant.helpers.typing import HomeAssistantType from . import (ToonEntity, ToonElectricityMeterDeviceEntity, ToonGasMeterDeviceEntity, ToonSolarDeviceEntity, ...
""" Functions that implement prediction of and imaging from visibilities using the nifty gridder. https://gitlab.mpcdf.mpg.de/ift/nifty_gridder This performs all necessary w term corrections, to high precision. """ import logging from typing import Union import numpy from data_models.memory_data_models import Visibilit...
{ "cells": [ { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[3.57889930e-03 1.08136188e-02 1.82038188e-02 2.57528110e-02\n", " 3.34639765e-02 4.13407669e-02 4.93867058e-02 5.76053905e-02\n",...
from importlib import reload import json import os import pytest from google.cloud.aiplatform.training_utils import environment_variables from unittest import mock _TEST_TRAINING_DATA_URI = "gs://training-data-uri" _TEST_VALIDATION_DATA_URI = "gs://test-validation-data-uri" _TEST_TEST_DATA_URI = "gs://test-data-uri" _T...
import pprint as _pprint import sys as _sys import warnings as _warnings _warnings.resetwarnings() _warnings.filterwarnings('error') from tdi import filters as _filters class Collector(object): def __init__(self): self.events = [] self.canary = 'bla' def __getattr__(self, name): if name....
"""Handle MySensors gateways.""" from __future__ import annotations import asyncio from collections import defaultdict from collections.abc import Callable, Coroutine import logging import socket import sys from typing import Any import async_timeout from mysensors import BaseAsyncGateway, Message, Sensor, mysensors im...
import sys from Ziggeo import Ziggeo if(len(sys.argv) < 3): print ("Error\n") print ("Usage: $>python video_delete_all_rejected.py YOUR_API_TOKEN YOUR_PRIVATE_KEY\n") sys.exit() api_token = sys.argv[1] private_key = sys.argv[2] ziggeo = Ziggeo(api_token, private_key) def indexVideos(skip=0): yey = 0 video_list = z...
''' create list and write elements into yaml and json files read those files and print them ''' import json import yaml from pprint import pprint as tisk number_Str = raw_input("Write random number for list:\n") list_Gen = range(int(number_Str)) list_Gen.append({'vendor': 'Check Point', 'model': 'R77', 'IP': '10.1.1.1/...
"""Tests for plaso.output.pstorage.""" import os import unittest from plaso.lib import pfilter from plaso.lib import storage from plaso.output import interface from plaso.output import pstorage from tests import test_lib as shared_test_lib from tests.output import test_lib class PstorageTest(test_lib.OutputModuleTestCa...
import codecs import os import re import sys from os import path from setuptools import find_packages, setup if "sdist" in sys.argv or "develop" in sys.argv: os.chdir("staff_toolbar") try: from django.core import management management.call_command("compilemessages", stdout=sys.stderr, verbosity=...
import logging from flask import Response from flask import request from flask_restplus import Resource, Namespace from son_editor.impl import workspaceimpl from son_editor.util import descriptorutil from son_editor.util.constants import WORKSPACES from son_editor.util.descriptorutil import SCHEMA_ID_VNF from son_edito...
import logging import os from six.moves import xrange from kafka import ( KafkaConsumer, MultiProcessConsumer, SimpleConsumer, create_message ) from kafka.common import ( ProduceRequestPayload, ConsumerFetchSizeTooSmall, OffsetOutOfRangeError, TopicPartition ) from kafka.consumer.base import MAX_FETCH_BUFFE...
""" Copyright 2018 ARC Centre of Excellence for Climate Systems Science author: Aidan Heerdegen <aidan.heerdegen@anu.edu.au> 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/lice...
from __future__ import absolute_import from builtins import str import json import logging import re from django.conf import settings from django.contrib import messages from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_protect from django.core.exceptions import Obj...
"""Tests for up-sampling layers.""" import keras from keras.testing_infra import test_combinations from keras.testing_infra import test_utils import numpy as np import tensorflow.compat.v2 as tf from tensorflow.python.framework import test_util as tf_test_utils # pylint: disable=g-direct-tensorflow-import @tf_test_uti...
import datetime import dateutil from dateutil import parser import boto from boto import iam conn=iam.connect_to_region('ap-southeast-1') users=conn.get_all_users() timeLimit=datetime.datetime.now() - datetime.timedelta(days=90) print "---------------------------------------------" print "Access Keys Date" + "\t\t" + "...
import sys import fileinput import re if len(sys.argv) < 2: sys.exit(1) pattern = re.compile(sys.argv[1]) for line in fileinput.input(sys.argv[2:]): if re.search(pattern, line): print line,
from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os from pants.backend.jvm.targets.exclude import Exclude from pants.backend.jvm.targets.jvm_target import JvmTarget from pants.base.build_environment import get_...
from cloudscheduler.lib.db_config import Config from cloudscheduler.lib.ProcessMonitor import ProcessMonitor, terminate, check_pid from cloudscheduler.lib.poller_functions import \ start_cycle, \ wait_cycle from cloudscheduler.lib.rpc_client import RPC import multiprocessing from subprocess import Popen, PIPE i...
""" Fantastic Add-on This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the ...
import os import glob import errno import shutil import yaml from skybase import config as sky_cfg from skybase.utils import mkdir_path, basic_timestamp from skybase.planet import Planet from skybase.utils import simple_error_format import skybase.actions.skycloud import skybase.exceptions class PlanetStateDb(object): ...
import paddle.v2 as paddle import paddle.v2.framework.layers as layers import paddle.v2.framework.core as core import paddle.v2.framework.optimizer as optimizer from paddle.v2.framework.framework import Program, g_program from paddle.v2.framework.executor import Executor import numpy as np init_program = Program() prog...
import sys from flask import Flask, render_template, request, redirect, url_for import gspread from GoogleAccount import google_user, google_pass app = Flask(__name__) @app.route('/') def poll_list(): worksheets_list = spreadsheet.worksheets() return render_template('home.html', polls=worksheets_list) @app.route('/<p...
import pandas from sklearn.externals import joblib from treeinterpreter import treeinterpreter as ti from optparse import OptionParser import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from featureizer import featureize from flowenhancer import enhance_flow from clearcut_utils import load_brofile ...
import numpy as np import networkx as nx from latlon_to_spatial import latlonstospace from scipy.spatial import KDTree import scipy.sparse as sparse metadatadir = '../../Data/Metadata/' nodeorder = np.load(metadatadir + 'nodeorder.npy') windmask = np.load(metadatadir + 'windmask_ECMWF.npy').astype(bool) solarmask = np....
from collections import OrderedDict from typing import Dict, Type from .base import UserListServiceTransport from .grpc import UserListServiceGrpcTransport _transport_registry = ( OrderedDict() ) # type: Dict[str, Type[UserListServiceTransport]] _transport_registry["grpc"] = UserListServiceGrpcTransport __all__ = ...
""" Run with $ env EDGEDB_TEST_DEBUG_POOL=1 edb test -k test_server_connpool to get interactive HTML reports in the `./tmp` directory. Alternatively, run with $ python tests/test_server_pool.py to get interactive HTML report of all tests aggregated in one HTML file in `./tmp/connpool.html`. """ from __future__ imp...
import logging import base_behaviors class ContainerBehaviors(base_behaviors.BaseBehaviors): def __init__(self): super(ContainerBehaviors, self).__init__() self.LOG = logging.getLogger(type(self).__name__) self.container_hrefs_to_delete = [] def delete_container(self, container_href): ...
""" libvirt specific routines. """ import binascii import os import stat from oslo_concurrency import processutils from oslo_log import log as logging from oslo_utils import units from oslo_utils import uuidutils from nova.i18n import _ import nova.privsep LOG = logging.getLogger(__name__) @nova.privsep.sys_admin_pctxt...
"""@package sample plotting A sample plotting tool for the one-dimensional DG data. The exact solution plotted is for the sinewave initial condition. """ import argparse import os import numpy as np import matplotlib.pyplot as plt import dg1d.solution as solution plt.rc('text', usetex=True) plt.rc('font', family='serif...
from django import http from django.core.urlresolvers import reverse from mox import IsA from novaclient import exceptions as novaclient_exceptions from horizon import api from horizon import test INDEX_VIEW_URL = reverse('horizon:nova:access_and_security:index') class KeyPairViewTests(test.BaseViewTests): def setU...
try: import dvbcss except ImportError: import sys, os parentDir= os.path.dirname(os.path.abspath(__file__))+os.sep+".." sys.path.append(parentDir) if __name__ == "__main__": import sys print >> sys.stderr, """ This is a support file and is designed to be imported, not run on its own. This module...
"""Functions related to a training a GNN using graph_nets.""" from typing import Callable, Tuple import graph_nets import numpy as np import sonnet as snt import tensorflow as tf from graph_attribution import graphnet_models as gnn_models from graph_attribution import graphs as graph_utils from graph_attribution import...
"""Run YCSB benchmark against AWS DynamoDB. This benchmark does not provision VMs for the corresponding DynamboDB database. The only VM group is client group that sends requests to specifiedDB. TODO: add DAX option. TODO: add global table option. """ import os from absl import flags from perfkitbenchmarker import confi...
""" Test the oversampling / downsampling routines used to generate Kernels at regularly spaced subpixel offsets """ import numpy as np import fastimgproto.gridder.conv_funcs as conv_funcs from fastimgproto.gridder.gridder import ( calculate_oversampled_kernel_indices, convolve_to_grid, populate_kernel_cache...
__author__ = 'Douglas' ''' A função cifraCesar(<mensagem>,<ndesloc>) retorna criptografada a mensagem passada como parâmetro de entrada com deslocamento passado como segundo parâmetro. Ex.: 'Aula de matemática: Capítulo nove' Ret.: 'DXOD*GH*PDWHPÄWLFD=*FDSÐWXOR*QRYH' ''' def cifraCesar(mensagem, ndesloc): textoCifra =...
import numpy as np import unittest import random import time from paddle.hapi.progressbar import ProgressBar class TestProgressBar(unittest.TestCase): def prog_bar(self, num, epoch, width, verbose=1): for epoch in range(epoch): progbar = ProgressBar(num, verbose=verbose) values = [ ...
"""Keystone PKI Token Provider.""" import subprocess # nosec : used to catch subprocess exceptions from keystoneclient.common import cms from oslo_log import log from oslo_log import versionutils from oslo_serialization import jsonutils from keystone.common import utils import keystone.conf from keystone import except...
""" PyTorch Lightning implementation of Proximal Policy Optimization (PPO) <https://arxiv.org/abs/1707.06347> Paper authors: John Schulman, Filip Wolski, Prafulla Dhariwal, Alec Radford, Oleg Klimov The example implements PPO compatible to work with any continous or discrete action-space environments via OpenAI Gym. To...
""" Manage the reading and storing of data. """ from collections import OrderedDict from scipy import genfromtxt from scipy import array import configparser from . import name_constants as co def read_std_data_file(path, lower_names=False, **kwargs): ''' Read a standard data file. The file is expected to ha...
from provdbconnector import ProvDb from provdbconnector.db_adapters.in_memory import SimpleInMemoryAdapter import pkg_resources prov_api = ProvDb(adapter=SimpleInMemoryAdapter, auth_info=None) prov_document_buffer = pkg_resources.resource_stream("examples", "file_buffer_example_primer.json") document_id = prov_api.save...
"""Tests for the event source attribute containers.""" from __future__ import unicode_literals import unittest from plaso.containers import event_sources from tests import test_lib as shared_test_lib class EventSourceTest(shared_test_lib.BaseTestCase): """Tests for the event source attribute container.""" def testG...
import urllib import json import re def buildURL(key, location): return "http://api.worldweatheronline.com/free/v2/tz.ashx?key=" + key + "&q=" + location + "&format=JSON" def getJSON(location): url = buildURL("3fc66d9c63d9061a23478337e2538", location) response = urllib.urlopen(url) data = json.load(response) retur...
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 model 'Boletin' db.create_table(u'app_boletin', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key...
"""This module is the server for our Dance LED server.""" from flask import Flask app = Flask(__name__) led_matrix = [[False for x in range(32)] for x in range(16)] @app.route("/") def index(): return "it works" @app.route("/update/<c_x>/<c_y>/<on>") def update(c_x, c_y, on): led_matrix[int(c_x)][int(c_y)] = (o...
import json import os import typing from collections import namedtuple from pathlib import Path from ruamel import yaml template = """\ data_base_dir: path(FATE) cache_directory: examples/cache/ performance_template_directory: examples/benchmark_performance/ flow_test_config_directory: examples/flow_test_template/heter...
from collections import deque from datetime import timedelta, datetime import re import threading from time import sleep import xml.parsers.expat import feedparser import settings from downloaders import HeadDownloader, Downloader from logger import Logger from models import Feed, Entry TIMEOUT = 10 # timeout in second...
import logging import time import os import sys from ConfigParser import ConfigParser from subprocess import Popen, PIPE class JavaConfig: '''Enable access to properities in java siteConfig file''' def __init__(self, fname): self.prop_d = {} for line in open(fname): line = line.strip...
"""The base classes for RDFValue tests.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from past.builtins import long from typing import Text from grr_response_core.lib.rdfvalues import structs as rdf_structs class RDFValueTestMixin(object): """The ba...
from pylab import * from matplotlib.patches import Polygon def func(x): return (x-3)*(x-5)*(x-7)+85 ax = subplot(111) a, b = 2, 9 # integral area x = arange(0, 10, 0.01) y = func(x) plot(x, y, linewidth=1) ix = arange(a, b, 0.01) iy = func(ix) verts = [(a,0)] + list(zip(ix,iy)) + [(b,0)] poly = Polygon(verts, facec...
from collections import OrderedDict import os import re from typing import Dict, Optional, Sequence, Tuple, Type, Union from google.api_core import client_options as client_options_lib from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('surveys', '0001_initial'), ] operations = [ migrations.AddField( model_name='question', name='answer_type', field=mod...
import tensorflow as tf import numpy as np from gpflow.params import Parameter, Parameterized from gpflow.conditionals import conditional from gpflow.features import InducingPoints from gpflow.kullback_leiblers import gauss_kl from gpflow.priors import Gaussian as Gaussian_prior from gpflow import transforms from gpflo...
import sys import optparse import json import collections from testtools import TestCase from mock import Mock from troveclient.compat import common from troveclient import client """ unit tests for common.py """ class CommonTest(TestCase): def setUp(self): super(CommonTest, self).setUp() self.orig...
import json import logging import math import re import sys import time from django import forms from django.contrib import messages from django.contrib.auth.models import User from django.db.models import Q from django.http import HttpResponse, QueryDict from django.shortcuts import redirect from django.utils.html imp...
''' This module create model of Course ''' from openerp import api, fields, models, _ class Course(models.Model): ''' This class create model of Course ''' _name = 'openacademy.course' # Model odoo name name = fields.Char(string='Title', required=True) # Field reserved to id...
"""Plugin-specific global metadata.""" PLUGIN_NAME = "example_basic"
import logging import os import subprocess import sys import threading import time from datetime import datetime, timedelta from apscheduler.schedulers.background import BackgroundScheduler from cqsdk import CQBot, \ RcvdPrivateMessage, RcvdGroupMessage, SendPrivateMessage from utils import CQ_ROOT, reply qqbot = C...
''' Created on Mar 18, 2014 Copyright (c) 2014-2015 Dario Bonino Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or ag...
import os import sys import string import traceback import optparse import getpass a = os.path.join("../") sys.path.append(a) a = os.path.join("../../") sys.path.append(a) a = os.path.join("../../..") sys.path.append(a) from zoni.version import * from zoni.extra.util import * def main(): ''' This file sets up the data...
import unittest from redis import Redis from redis_queue import Queue, ExclusiveQueue class TestRedisQueue(unittest.TestCase): def setUp(self): self.redis_args = dict(host='127.0.0.1', port=6379) self.key = 'test_redis_queue' self.queue = Queue(self.key, **self.redis_args) def tearDown(s...
"""Tests for mention memory model.""" import copy import json import os from absl.testing import absltest from absl.testing import parameterized import jax from language.mentionmemory.encoders import mention_memory_encoder # pylint: disable=unused-import from language.mentionmemory.tasks import mention_memory_task fro...