content
stringlengths
4
20k
import operator from ..sql import operators class UnevaluatableError(Exception): pass _straight_ops = set(getattr(operators, op) for op in ('add', 'mul', 'sub', 'div', 'mod', 'truediv', 'lt', 'le', 'n...
#======================================================================= # # Python Lexical Analyser # # Regular Expressions # #======================================================================= import array import string import types from sys import maxint import Errors # # Constants # BOL = 'bol' EOL = 'e...
#!/usr/bin/env python # coding=utf8 __app_version__ = '0.1.1' __material_version__ = '0.96.1' import re from flask import Blueprint, current_app, url_for try: from wtforms.fields import HiddenField except ImportError: def is_hidden_field_filter(field): raise RuntimeError('WTForms is not installed.')...
""" ===================================== Multi-class AdaBoosted Decision Trees ===================================== This example reproduces Figure 1 of Zhu et al [1] and shows how boosting can improve prediction accuracy on a multi-class problem. The classification dataset is constructed by taking a ten-dimensional ...
"""SCons.Tool.rpm Tool-specific initialization for rpm. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. The rpm tool calls the rpmbuild command. The first and only argument should a tar.gz consisting of the sourc...
#!/usr/bin/env python """Wrapper script with bsub functionality.""" from __future__ import print_function import sys import os import shlex import argparse from submitjob import submitjob from utility import color def esub(args, bsubargs, jobscript): """Wrapper script with bsub functionality.""" data = {"c...
import os import sys import re import hashlib import json from cStringIO import StringIO import pandas as pd import logging from HTMLParser import HTMLParser import datetime import os.path from google.cloud import storage from lxml import etree from collections import Counter #-------------------------------------- #...
""" Copyright 2006 ThoughtWorks, Inc. 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, soft...
import mxnet as mx import proposal import proposal_target from rcnn.config import config eps = 2e-5 use_global_stats = True workspace = 512 res_deps = {'50': (3, 4, 6, 3), '101': (3, 4, 23, 3), '152': (3, 8, 36, 3), '200': (3, 24, 36, 3)} units = res_deps['101'] filter_list = [256, 512, 1024, 2048] def residual_unit...
import re import warnings from xml.dom.minidom import parseString, Node from django.conf import settings, UserSettingsHolder from django.core import mail from django.http import request from django.template import Template, loader, TemplateDoesNotExist from django.template.loaders import cached from django.test.signal...
""" 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 distributed under the Li...
import BaseHTTPServer import errno import os import re import socket from SocketServer import ThreadingMixIn import ssl import sys import threading import time import traceback import types import urlparse import routes as default_routes from logger import get_logger from request import Server, Request from response i...
from django.contrib.gis.gdal import OGRGeomType from django.db.backends.sqlite3.introspection import ( DatabaseIntrospection, FlexibleFieldLookupDict, ) from django.utils import six class GeoFlexibleFieldLookupDict(FlexibleFieldLookupDict): """ Sublcass that includes updates the `base_data_types_reverse` ...
#!/usr/bin/python import subprocess import string import urllib.request import urllib.parse import xml.etree.ElementTree as ET from histelement import * from histelementcontainer import * from utils import * import pygame class SmsReader: def __init__(self,historycontainer): self.token = -1 self.smses = -1 ...
"""Ed25519 public key encryption handler""" from .packet import String, SSHPacket from .public_key import SSHKey, SSHCertificateV01, KeyExportError from .public_key import register_public_key_alg, register_certificate_alg # Short variable names are used here, matching names in the spec # pylint: disable=invalid-name ...
from openerp import models, fields, api import openerp.addons.decimal_precision as dp class PriceRule(models.Model): _name = "delivery.price.rule" _description = "Delivery Price Rules" _order = 'sequence, list_price' @api.depends('variable', 'operator', 'max_value', 'list_base_price', 'list_price', '...
# coding=utf-8 r""" This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ from twilio.base import deserialize from twilio.base import values from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base...
import copy import datetime import pickle import unittest from django.test import override_settings from django.utils import timezone try: import pytz except ImportError: pytz = None requires_pytz = unittest.skipIf(pytz is None, "this test requires pytz") if pytz is not None: CET = pytz.timezone("Europe...
from __future__ import unicode_literals from ..utils import ( int_or_none, str_to_int, unified_strdate, ) from .keezmovies import KeezMoviesIE class MofosexIE(KeezMoviesIE): _VALID_URL = r'https?://(?:www\.)?mofosex\.com/videos/(?P<id>\d+)/(?P<display_id>[^/?#&.]+)\.html' _TESTS = [{ 'url...
from rest_framework import generics from rest_framework import permissions as drf_permissions from rest_framework import exceptions from rest_framework import status from rest_framework.response import Response from modularodm import Q from framework.auth.oauth_scopes import CoreScopes from website.models import Nod...
"""SCons.Tool.dmd Tool-specific initialization for the Digital Mars D compiler. (http://digitalmars.com/d) Coded by Andy Friesen (<EMAIL>) 15 November 2003 There are a number of problems with this script at this point in time. The one that irritates me the most is the Windows linker setup. The D linker doesn't have...
import sqlite3 def get_full_sql(user): conn = sqlite3.connect("tasks.db") c = conn.cursor() temp = [] for row in c.execute('SELECT * FROM tasks where email = "' + user + '";'): temp.append(row) conn.close() return temp def get_tasks(user): temp = get_full_sql(user) ...
r"""Find the full path to commands. which(command, path=None, verbose=0, exts=None) Return the full path to the first match of the given command on the path. whichall(command, path=None, verbose=0, exts=None) Return a list of full paths to all matches of the given command on the path. whichgen(comman...
from .mbcharsetprober import MultiByteCharSetProber from .codingstatemachine import CodingStateMachine from .chardistribution import SJISDistributionAnalysis from .jpcntx import SJISContextAnalysis from .mbcssm import SJIS_SM_MODEL from .enums import ProbingState, MachineState class SJISProber(MultiByteCharSetProber)...
"""Wrapper for Python TPU tests. The py_tpu_test macro will actually use this file as its main, building and executing the user-provided test file as a py_binary instead. This lets us do important work behind the scenes, without complicating the tests themselves. The main responsibilities of this file are: - Define...
''' Recorder module =============== .. versionadded:: 1.1.0 Create an instance of :class:`~kivy.input.recorder.Recorder`, attach to the class, and bind some keys to record / play sequences: - F6: play the last record in a loop - F7: read the latest recording - F8: record input events Configuration -----...
""" mediatum - a multimedia content repository Copyright (C) 2010 Arne Seifert <<EMAIL>> 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) a...
# -*- coding: utf-8 -*- """ flask ~~~~~ A microframework based on Werkzeug. It's extensively documented and follows best practice patterns. :copyright: (c) 2011 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ __version__ = '0.10.1' # utilities we import from Werkzeug and...
from django.conf.urls import patterns from django.conf.urls import url from openstack_dashboard.dashboards.admin.routers import views ROUTER_URL = r'^(?P<router_id>[^/]+)/%s' urlpatterns = patterns( 'horizon.dashboards.admin.routers.views', url(r'^$', views.IndexView.as_view(), name='index'), url(ROUTE...
{ 'name': 'Repairs Management', 'version': '1.0', 'category': 'Manufacturing', 'description': """ The aim is to have a complete module to manage all products repairs. ==================================================================== The following topics should be covered by this module: ------------...
# -*- coding: utf-8 -*- """ requests.auth ~~~~~~~~~~~~~ This module contains the authentication handlers for Requests. """ import os import re import time import hashlib from base64 import b64encode from .compat import urlparse, str from .cookies import extract_cookies_to_jar from .utils import parse_dict_header, ...
#!/usr/bin/env python # # test_multibytecodec_support.py # Common Unittest Routines for CJK codecs # import sys, codecs import unittest, re from test import test_support from StringIO import StringIO class TestBase: encoding = '' # codec name codec = None # codec tuple (with 4 elements) ...
ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} try: import pyodbc except ImportError: pyodbc_found = False else: pyodbc_found = True from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.pycompat24 ...
"""Creates a copy of specified directories\files.""" import logging import os import re from gcimagebundlelib import manifest from gcimagebundlelib import utils class FsCopyError(Exception): """Error occured in fs copy operation.""" class InvalidFsCopyError(Exception): """Error when verification fails befor...
from evoflow.utils import slices2array from evoflow.engine import OP from evoflow import backend as B class DualCrossover(OP): O_AUTOGRAPH = True O_XLA = False def __init__(self, population_fraction, max_crossover_probability, **kwargs): """Perform Dual crossovers on a given pop...
"""Test node handling.""" from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * import urllib.parse class NodeHandlingTest (BitcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 4 self.setup_clean_chain = False def ...
""" common cache-manager operations """ from afs.util.Executor import exec_wrapper import ParseCacheManagerUtil as PM from BaseUtil import BaseUtil class CacheManagerUtil(BaseUtil) : @exec_wrapper def flush_all(self, _cfg=None): """ Force the AFS Cache Manager to discard all data ...
""" Django REST Framework serializers for the User API application """ from django.contrib.auth.models import User from django.utils.timezone import now from rest_framework import serializers from lms.djangoapps.verify_student.models import SoftwareSecurePhotoVerification, SSOVerification, ManualVerification from .mo...
import sys, os import getopt from socket import * try: from kodi.xbmcclient import * except: sys.path.append(os.path.join(os.path.realpath(os.path.dirname(__file__)), '../../lib/python')) from xbmcclient import * def usage(): print "kodi-send [OPTION] --action=ACTION" print 'Example' print '\tk...
import os, sys; sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..")) from pattern.search import search, taxonomy, Classifier from pattern.en import parsetree # The search module includes a Taxonomy class # that can be used to define semantic word types. # For example, consider that you want to...
from __future__ import division, absolute_import, print_function import collections import numpy as np from numpy import matrix, asmatrix, bmat from numpy.testing import ( TestCase, run_module_suite, assert_, assert_equal, assert_almost_equal, assert_array_equal, assert_array_almost_equal, assert_raises ) fro...
""" Support for functionality to interact with FireTV devices. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.firetv/ """ import logging import requests from blumate.components.media_player import ( SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, S...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible import constants as C from ansible.errors import AnsibleError, AnsibleParserError from ansible.playbook.attribute import Attribute, FieldAttribute try: from __main__ import display except ImportError: from ans...
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse_lazy from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon import forms from horizon import messages from horizon import tabs from horizon.utils import memoized from horizon import wo...
class ModuleDocFragment(object): # Standard files documentation fragment DOCUMENTATION = """ options: host: description: - Specifies the DNS host name or address for connecting to the remote device over the specified transport. The value of host is used as the destination address f...
# -*- coding: utf-8 -*- """ Unit tests for handling email sending errors """ import json from itertools import cycle from smtplib import SMTPConnectError, SMTPDataError, SMTPServerDisconnected import ddt from celery.states import RETRY, SUCCESS from django.conf import settings from django.core.management import call_c...
""" Unit tests for the container page. """ import re import datetime from pytz import UTC from mock import patch, Mock from django.http import Http404 from django.test.client import RequestFactory from django.utils import http import contentstore.views.component as views from contentstore.views.tests.utils import Stu...
#!/usr/bin/env python import sys from collections import namedtuple import rpmfluff RPM = namedtuple('RPM', ['name', 'version', 'release', 'epoch', 'recommends']) SPECS = [ RPM('foo', '1.0', '1', None, None), RPM('foo', '1.0', '2', '1', None), RPM('foo', '1.1', '1', '1', None), RPM('foo-bar', '1.0...
import copy import rope.base.exceptions from rope.base import pyobjects, taskhandle, evaluate, worder, codeanalyze, utils from rope.base.change import ChangeContents, ChangeSet from rope.refactor import occurrences, functionutils class ChangeSignature(object): def __init__(self, project, resource, offset): ...
import tensorflow as tf import time import numpy as np import mdl_data import sys GPUNUM = sys.argv[1] FILEPATH = sys.argv[2] # Network Parameters learning_rate = 0.001 training_epochs = 20 batch_size = 32 display_step = 1 n_input_img = 4096 # YLI_MED image data input (data shape: 4096, fc7 layer output) n_hidden_1...
ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} def find_launch_configs(client, module): name_regex = module.params.get('name_regex') sort_order = module.params.get('sort_order') limit = module.params.get('limit') ...
import unittest from ..arcgis_txt import ArcGISTextIO from ...FileIO import FileIO as psopen from .... import examples as pysal_examples import tempfile import os import warnings class test_ArcGISTextIO(unittest.TestCase): def setUp(self): self.test_file = test_file = pysal_examples.get_path('arcgis_txt.t...
import mock import unittest from boto.ec2.blockdevicemapping import BlockDeviceType, BlockDeviceMapping class BlockDeviceTypeTests(unittest.TestCase): def setUp(self): self.block_device_type = BlockDeviceType() def check_that_attribute_has_been_set(self, name, value, attribute): self.block_de...
from __future__ import absolute_import, division, print_function __metaclass__ = type import json import shlex import shutil import os import subprocess import sys import traceback import signal import time import syslog import multiprocessing from ansible.module_utils._text import to_text PY3 = sys.version_info[0]...
import os from django import template from django.template.base import Template from django.conf import settings from ..utils import read_theme_info register = template.Library() @register.inclusion_tag('themes/list.html') def list_themes(): themes = [] for theme in os.listdir('{}/themes/'.format(settings...
""" Support for decoding image formats using SDL2_Image. """ import sdl2 import sdl2.ext import sdl2.sdlimage as sdl2image import rave.log import rave.events import rave.rendering import rave.resources from .common import fs_to_rwops ## Constants. FORMAT_NAMES = { sdl2image.IMG_INIT_JPG: 'JPEG', sdl2image...
import argparse import fnmatch import json import os import re import urllib2 # Strips C and C++ comments from the given string. # # Copied from http://stackoverflow.com/a/241506/627587. def strip_comments(text): def replacer(match): s = match.group(0) if s.startswith('/'): return " " ...
from django.template.defaultfilters import join from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class JoinTests(SimpleTestCase): @setup({'join01': '{{ a|join:", " }}'}) def test_join01(self): output = self.engine.render_to_string('join01...
from __future__ import unicode_literals, division, absolute_import from builtins import * # noqa pylint: disable=unused-import, redefined-builtin from future.moves.urllib.parse import urlparse import json import logging from collections import MutableSet import requests from requests import RequestException from fl...
""" Copyright 2013 Steven Diamond This file is part of CVXPY. CVXPY 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. CVXPY is distributed i...
"""Tests to ensure that the html5lib tree builder generates good trees.""" import warnings try: from bs4.builder import HTML5TreeBuilder HTML5LIB_PRESENT = True except ImportError, e: HTML5LIB_PRESENT = False from bs4.element import SoupStrainer from bs4.testing import ( HTML5TreeBuilderSmokeTest, ...
"""Universal report objects and some formatting drivers. A way to create simple reports using python objects, primarily designed to be formatted as text and html. """ __docformat__ = "restructuredtext en" import sys from logilab.common.compat import StringIO from logilab.common.textutils import linesep def get_nod...
from scout.constants import CASEDATA_HEADER, CLINVAR_HEADER def set_submission_objects(form_fields): """Creates a list of submission objects (variant and case-data) from the clinvar submission form in blueprints/variants/clinvar.html. Args: form_fields(dict): it's the submission form dictionary. Key...
import sys, unittest, re, os.path sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..', 'src')) import Exscript.util.ipv4 class ipv4Test(unittest.TestCase): CORRELATE = Exscript.util.ipv4 def testIsIp(self): from Exscript.util.ipv4 import is_ip self.assert_(is_ip('0.0.0...
#!/usr/bin/env python from datetime import datetime, timedelta from tests.compat import mock, unittest import os from boto import provider from boto.compat import expanduser INSTANCE_CONFIG = { 'allowall': { u'AccessKeyId': u'iam_access_key', u'Code': u'Success', u'Expiration': u'2012-09...
from __future__ import absolute_import, division, print_function, \ with_statement import socket import struct import logging import hashlib import hmac ONETIMEAUTH_BYTES = 10 ONETIMEAUTH_CHUNK_BYTES = 12 ONETIMEAUTH_CHUNK_DATA_LEN = 2 # Index consts for transfer statistics U = 0 D = 1 def sha1_hmac(secret, ...
from django import forms from django_inlines import registry from django_inlines.forms import InlineField from test_app.inlines import BasicInline from .test_common import InlinesTestCase __all__ = ('InlineFormTestCase',) class InlineForm(forms.Form): content = InlineField() class InlineFormTestCase(Inlines...
import os import glob from gppylib.test.behave_utils.utils import execute_sql_singleton master_data_dir = os.environ.get('MASTER_DATA_DIRECTORY') if master_data_dir is None: raise Exception('Please set MASTER_DATA_DIRECTORY in environment') def gp_fts_log_in_master_log_count(mdd): return gp_in_master_log_cou...
#!/usr/bin/env python3 import pytest from pysisyphus.calculators import Gaussian16 from pysisyphus.calculators.PySCF import PySCF from pysisyphus.helpers import geom_loader from pysisyphus.intcoords.augment_bonds import augment_bonds from pysisyphus.testing import using from pysisyphus.tsoptimizers.RSIRFOptimizer imp...
from .application_gateways_operations import ApplicationGatewaysOperations from .application_security_groups_operations import ApplicationSecurityGroupsOperations from .available_endpoint_services_operations import AvailableEndpointServicesOperations from .express_route_circuit_authorizations_operations import ExpressR...
import os import shlex import shutil import unittest from copyright import App, diffdir DATA_DIR = 'test/data' INPUT_DIR = os.path.join(DATA_DIR, 'input') TMP_DIR = os.path.join(DATA_DIR, 'tmp') TRUTH_DIR = os.path.join(DATA_DIR, 'truth') def datadir(suffix): return os.path.join(DATA_DIR, suffix) def inputdir(s...
import numpy as np from numpy.matrixlib.defmatrix import matrix, asmatrix # need * as we're copying the numpy namespace from numpy import * __version__ = np.__version__ __all__ = np.__all__[:] # copy numpy namespace __all__ += ['rand', 'randn', 'repmat'] def empty(shape, dtype=None, order='C'): """ Return a ...
''' gpgenfsmap.py Generates a mapping of Servers, Filesystems, GPDB Filespaces and Storage Pools Options: -h, -?, --help Print this usage. -p --port Port to use to connect to DB. Defaults to $PGPORT -u --username Username to connect to DB. Defaaults to $PGUSER -n --host Hostnam...
import github.GithubObject import github.AuthorizationApplication class Authorization(github.GithubObject.CompletableGithubObject): """ This class represents Authorizations as returned for example by http://developer.github.com/v3/todo """ @property def app(self): """ :type: :cla...
#!/usr/bin/python ''' Extract _("...") strings for translation and convert to Qt4 stringdefs so that they can be picked up by Qt linguist. ''' from subprocess import Popen, PIPE import glob import operator import os import sys OUT_CPP="qt/crownstrings.cpp" EMPTY=['""'] def parse_po(text): """ Parse 'po' forma...
from sqlalchemy.testing import fixtures from ..orm._fixtures import FixtureTest from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import relationship, interfaces, configure_mappers from sqlalchemy.ext.automap import generate_relationship from sqlalchemy.testing.mock import Mock from sqlalchemy import ...
"""Tests for handling the device registry.""" from homeassistant.components.media_player.const import DOMAIN as MP_DOMAIN from homeassistant.components.plex.const import DOMAIN async def test_cleanup_orphaned_devices(hass, entry, setup_plex_server): """Test cleaning up orphaned devices on startup.""" test_de...
import os from flask import Flask, render_template, request from flask import redirect, url_for, flash from models import * app = Flask(__name__) app.config.from_object(__name__) app.config.update(dict( SECRET_KEY='development key', # USER='development', # PASSWORD='devpassword', # DATABASE='devdataba...
from __future__ import unicode_literals from . import CountryReverseConverter, CaseInsensitiveDict from ..country import COUNTRY_MATRIX from ..exceptions import CountryConvertError, CountryReverseError class CountryNameConverter(CountryReverseConverter): def __init__(self): self.codes = set() self...
from scipy.constants import mu_0 from SimPEG import * from SimPEG.Utils import kron3, speye, sdiag import matplotlib.pyplot as plt def spheremodel(mesh, x0, y0, z0, r): """ Generate model indicies for sphere - (x0, y0, z0 ): is the center location of sphere - r: is the radius of the sphere...
""" Define allowed quantities for FRB galaxies Uncertainty is valid for any quantity with '_err' add-on, eg. W1_err Am also likely to add _flg for each as well """ ############################################################## # Redshift valid_z = [ 'z', # Preferred redshift, may derived from one of sev...
import os import moksha.common.utils import logging import pkg_resources import warnings import types from collections import defaultdict from paste.deploy.converters import asbool from inspect import isclass from sqlalchemy import create_engine from moksha.common.exc import MokshaException from moksha.common.lib.hel...
#!/usr/bin/env python import fnmatch import os import sys from lib.util import execute IGNORE_FILES = [ os.path.join('atom', 'browser', 'mac', 'atom_application.h'), os.path.join('atom', 'browser', 'mac', 'atom_application_delegate.h'), os.path.join('atom', 'browser', 'resources', 'win', 'resource.h'), os.pa...
from copy import deepcopy from unittest import mock import tensorflow as tf def test_safe(func): """ Isolate tests """ def func_wrapper(*args): with tf.Graph().as_default(): result = func(*args) print('Tests Passed') return result return func_wrapper def _ass...
from django.conf import settings from django.db import models class TypeCategory(models.Model): id = models.BigIntegerField('Type Category ID', primary_key=True) name = models.CharField('Type Category Name', max_length=200) class Meta: app_label = 'poscore' def __unicode__(self): ...
# # Unit Tests for the Callbacks class # # Rajul Srivastava (<EMAIL>) # import unittest import logging import numpy as np import ginga.misc.Callback as Callback class TestError(Exception): pass class TestCallbacks(unittest.TestCase): def setUp(self): pass def test_init(self): test_ca...
import numpy as np from pyms.GCMS.Class import GCMS_data, Scan, IonChromatogram class AstonPyMS(GCMS_data): """ Adapter to allow pyms routines to run on aston files. Note: initialization uses AstonFrame, not scan lists as in pyms. """ def __init__(self, data): self.data = data d...
from __future__ import print_function import os import sys from genmsg import EXT_MSG, EXT_SRV, MsgContext from genmsg.gentools import compute_full_type_name from genmsg.msg_loader import load_msg_from_file, load_srv_from_file from genmsg.msgs import bare_msg_type, is_builtin, resolve_type pkg_name = sys.argv[1] msg...
"""Sphinx "napoleon" extension.""" import sys from setuptools import setup, find_packages reqs = open('requirements.txt', 'r').read().strip().splitlines() reqs_test = open('requirements_test.txt', 'r').read().strip().splitlines() extra = {} if sys.version_info[0] >= 3: extra['use_2to3'] = True extra['use_2to...
from ansible.compat.tests import unittest from ansible.playbook.attribute import Attribute class TestAttribute(unittest.TestCase): def setUp(self): self.one = Attribute(priority=100) self.two = Attribute(priority=0) def test_eq(self): self.assertTrue(self.one == self.one) sel...
# ----------------------------------------------------------------------------- # calc.py # # A simple calculator with variables. This is from O'Reilly's # "Lex and Yacc", p. 63. # # This example uses unicode strings for tokens, docstrings, and input. # ----------------------------------------------------------------...
from oslo_config import cfg from nova.tests.functional.v3 import api_sample_base CONF = cfg.CONF CONF.import_opt('osapi_compute_extension', 'nova.api.openstack.compute.extensions') class FlavorExtraSpecsSampleJsonTests(api_sample_base.ApiSampleTestBaseV3): ADMIN_API = True extension_name = '...
import ns.plc import ns.core import ns.spectrum import ns.network def sendPacket(mac, p, dst): mac.Send(p,dst) def receivedACK(): print '*** ACK received ***' def main(dummy_argv): ## Enable logging ns.core.LogComponentEnableAll(ns.core.LOG_PREFIX_TIME) ns.core.LogComponentEnable('PLC_Mac', ns...
__all__ = ['Serializer', 'SerializerError'] from .error import YAMLError from .events import * from .nodes import * class SerializerError(YAMLError): pass class Serializer: ANCHOR_TEMPLATE = 'id%03d' def __init__(self, encoding=None, explicit_start=None, explicit_end=None, version=None, tag...
import tacticenv from pyasm.common import Container, jsonloads, Environment, Xml from pyasm.security import Batch from pyasm.search import Search, SearchType from pyasm.unittest import UnittestEnvironment import unittest import urllib2 class RestTest(unittest.TestCase): def test_all(my): test_env = ...
from __future__ import absolute_import, print_function, division import time import copy import os import six from mitmproxy import stateobject from netlib import certutils from netlib import tcp class ClientConnection(tcp.BaseHandler, stateobject.StateObject): """ A client connection ...
#!/usr/bin/env python """Sample script of recurrent neural network language model. This code is ported from following implementation written in Torch. https://github.com/tomsercu/lstm """ import argparse import math import sys import time import numpy as np from chainer import cuda, Variable, FunctionSet, optimizers ...
""" This module contains functions to compute confirmation on a pair of words or word subsets. The advantage of indirect confirmation measure is that it computes similarity of words in W' and W* with respect to direct confirmations to all words. Eg. Suppose x and z are both competing brands of cars, which semantically ...
"""Export the Python grammar and symbols.""" # Python imports import os # Local imports from .pgen2 import token from .pgen2 import driver from . import pytree # The grammar file _GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), "Grammar.txt") _PATTERN_GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), ...
'''OpenGL extension ATI.element_array This module customises the behaviour of the OpenGL.raw.GL.ATI.element_array to provide a more Python-friendly API Overview (from the spec) This extension provides a mechanism for an application to create an array of index data for use in specifying geometric primitives. ...