content
stringlengths
4
20k
import tempfile, py, os from testing.test_interpreter import BaseTestInterpreter, hippy_fail class TestFileOps(BaseTestInterpreter): @py.test.mark.skipif("config.option.runappdirect", reason="we have <input> only on hippy") def test___file__(self): output = self.run('echo __FI...
#-*-coding:utf-8-*- #====================================================================== # script used to plot a transfert function etaC/etaR # where : # * etaC is complex nutation amplitudes (MHB) got from # ondes.txt + corrections from amplitudes.dat (fitted parameters) # * etaR is complex nu...
""" ############################################################################## The calculation of Kier and Hall's kappa indices based on its topological structure. You can get 7 molecular kappa descriptors. You can freely use and distribute it. If you hava any problem, you could contact with us timely! Authors...
""" Service requests (parsing, handling, etc). """ import urllib import cgi from mapproxy.util.py import cached_property class NoCaseMultiDict(dict): """ This is a dictionary that allows case insensitive access to values. >>> d = NoCaseMultiDict([('A', 'b'), ('a', 'c'), ('B', 'f'), ('c', 'x'), ('c', 'y'...
from django.core.exceptions import PermissionDenied from metronus_app.model.administrator import Administrator from metronus_app.model.employee import Employee from metronus.settings import DEFAULT_FROM_EMAIL,AUTH_PASSWORD_VALIDATORS from metronus_app.model.projectDepartmentEmployeeRole import ProjectDepartmentEmployee...
from time import localtime, mktime, gmtime from enigma import iServiceInformation, eServiceCenter, eServiceReference, getBestPlayableServiceReference import NavigationInstance from timer import TimerEntry class TimerSanityCheck: def __init__(self, timerlist, newtimer=None): self.localtimediff = 25*3600 - mktime(...
""" Module of TinyCSSRule class. """ from tinycss.css21 import RuleSet from hatemile import helper from hatemile.util.css.stylesheetrule import StyleSheetRule from .tinycssdeclaration import TinyCSSDeclaration class TinyCSSRule(StyleSheetRule): """ The TinyCSSRule class is official implementation of :py:...
""" Swaps contains all swap or atoms position exchange MoveGenerator classes. .. inheritance-diagram:: fullrmc.Generators.Swaps :parts: 1 """ # standard libraries imports from __future__ import print_function import re # external libraries imports import numpy as np # fullrmc imports from ..Globals import INT_T...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Copyright 2017 Andries Bron This file is part of Radenium. Radenium 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,...
import copy import json import os from os_apply_config import config_exception as exc def read_configs(config_files): '''Generator yields data from any existing file in list config_files.''' for input_path in [x for x in config_files if x]: if os.path.exists(input_path): try: ...
import sys from rest_framework import serializers as ser from rest_framework.exceptions import ValidationError, MethodNotAllowed, NotFound from api.base.exceptions import Conflict from addons.wiki.exceptions import ( NameInvalidError, NameMaximumLengthError, PageConflictError, WikiError, ) from api.ba...
import os from astroquery.utils.tap.model import modelutils, taptable from requests.models import Response __all__ = ['DummyHandler'] def data_path(filename): data_dir = os.path.join(os.path.dirname(__file__), 'data') return os.path.join(data_dir, filename) class DummyHandler: def get_file(self, filen...
""" Linked Lists consists of Nodes. Nodes contain data and also may link to other nodes: - Head Node: First node, the address of the head node gives us access of the complete list - Last node: points to null """ from typing import Any class Node: def __init__(self, item: Any, next: Any) ...
import tensorflow as tf import matplotlib import numpy as np import matplotlib.pyplot as plt import random import math np.random.seed(1234) random.seed(1234) plt.switch_backend("TkAgg") def plotScatter(points, color): xs = [x[0] for x in points] ys = [y[1] for y in points] plt.scatter(xs, ys, c=colo...
from .offer_term_info import OfferTermInfo class MonetaryCredit(OfferTermInfo): """Indicates that this is a monetary credit offer. :param effective_date: Indicates the date from which the offer term is effective. :type effective_date: datetime :param name: Constant filled by server. :type na...
from __future__ import print_function, absolute_import from boxbranding import getMachineBuild from Components.ActionMap import ActionMap from Components.ChoiceList import ChoiceList, ChoiceEntryComponent from Components.config import config from Components.Label import Label from Components.Sources.StaticText import ...
import requests import json import frappe class AuthError(Exception): pass class FrappeException(Exception): pass class FrappeClient(object): def __init__(self, url, username, password): self.session = requests.session() self.url = url self.login(username, password) def __enter__(self): return self de...
# -*- coding: utf-8 -*- from south.utils import datetime_utils as 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 'ServiceEvent' db.create_table(u'watch_serviceevent', ( ...
import numpy as np from .objective_function import ObjectiveFunction class Rosenbrock(ObjectiveFunction): """ """ def __init__(self): """ """ super(Rosenbrock, self).__init__( d=2, gaussian_noise=0, f_bias=390.0, max_eval=400, ...
#!/usr/bin/env python3 # daemon.py import os import sys import atexit import signal def daemonize(pidfile, *, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'): if os.path.exists(pidfile): raise RuntimeError('Already running') # First fork...
#!/usr/bin/env python __author__ = 'greg' from cassandra.cluster import Cluster import cassandra import pymongo import uuid import json from cassandra.concurrent import execute_concurrent cluster = Cluster() cassandra_session = cluster.connect('serengeti') # try: # cassandra_session.execute("drop table classifica...
""" Acceptance tests for Studio related to the acid xblock. """ from unittest import skip from nose.plugins.attrib import attr from bok_choy.web_app_test import WebAppTest from ..pages.studio.auto_auth import AutoAuthPage from ..pages.studio.overview import CourseOutlinePage from ..pages.xblock.acid import AcidView fr...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import keystoneclient import keystoneclient.auth.identity.v3 import keystoneclient.session import keystoneclient.v3.client import novaclient.client import local_settings auth = keystoneclient.auth.identity.v3.Password(auth_url=local_settings.auth_url_v3, ...
# -*- coding: utf-8 -*- import urllib2 from BeautifulSoup import BeautifulSoup # Download the HTML request = urllib2.Request('http://www.uci.edu') response = urllib2.urlopen(request) print '\r\n\r\n' # Verify that everything went ok. # Error codes: 200 == good, 404, 500 == bad print 'The error code is:', response.c...
import contextlib from decimal import Decimal import importlib import unittest from dependency_injector.wiring import ( wire, Provide, Provider, Closing, register_loader_containers, unregister_loader_containers, ) from dependency_injector import containers, providers, errors # Runtime import t...
import simplejson as json import unicodehelper from .specs.webapps import WebappSpec def detect_webapp(err, package): """Detect, parse, and validate a webapp manifest.""" # Parse the file. with open(package, mode="r") as f: detect_webapp_string(err, f.read()) def detect_webapp_string(err, data...
import requests import os #import numpy as np import urllib #import matplotlib.pyplot as plt from scipy import ndimage from scipy import misc from skimage import filter import json import time # queue utilities from rq import get_current_job import socket def processImage(image_path): #job = get_current_job() ...
from stp_core.common.log import getlogger from stp_core.loop.looper import Prodable from stp_core.loop.startable import Status logger = getlogger() # TODO: move it to plenum-util repo class Motor(Prodable): """ Base class for Prodable that includes status management. Subclasses are responsible for chang...
''' Copyright (c) 2011-2017, Agora Games, LLC All rights reserved. https://github.com/agoragames/haigha/blob/master/LICENSE.txt ''' from chai import Chai from haigha.frames import content_frame from haigha.frames.content_frame import ContentFrame from haigha.frames.frame import Frame class ContentFrameTest(Chai): ...
__version__='3.3.0' __doc__='''Data structure to hold a collection of attributes, used by styles.''' class ABag: """ 'Attribute Bag' - a trivial BAG class for holding attributes. This predates modern Python. Doing this again, we'd use a subclass of dict. You may initialize with keyword arguments....
"""Base class for RPC testing.""" from collections import deque import logging import optparse import os import shutil import subprocess import sys import tempfile import time from .util import ( PortSeed, MAX_NODES, bitcoind_processes, check_json_precision, connect_nodes_bi, disable_mocktime,...
#!/usr/bin/python3 """ Copyright (c) 2018 Bill Peterson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, pu...
# -*- coding: utf-8 -*- import pytest from marshmallow import fields from marshmallow.marshalling import Marshaller, Unmarshaller, missing from marshmallow.exceptions import ValidationError from tests.base import User def test_missing_is_falsy(): assert bool(missing) is False class TestMarshaller: @pytest...
"""Contains a metaclass and helper functions used to create protocol message classes from Descriptor objects at runtime. Recall that a metaclass is the "type" of a class. (A class is to a metaclass what an instance is to a class.) In this case, we use the GeneratedProtocolMessageType metaclass to inject all the usefu...
import unittest from pyramid.compat import text_ class Test__make_predicates(unittest.TestCase): def _callFUT(self, **kw): from pyramid.config.util import make_predicates return make_predicates(**kw) def test_ordering_xhr_and_request_method_trump_only_containment(self): order1, _, _ = ...
import numpy as np from scipy.sparse import csc_matrix, csr_matrix from vtt import VTT def test_vtt(): """ Test VTT """ N = 20 # number of documents F = 15 # number of features ones = np.ones((int(N*0.5),int(F*0.5)), dtype=np.int) zeros = np.zeros((int(N*0.5),int(F*0.5)), dtype=np.int) NER_counts = np.array(...
from numpy import * import pylab as pl from mpl_toolkits.mplot3d import Axes3D from numpy.linalg import norm,det import matplotlib.pyplot as plt #=============================================================================== # Class: Defines boundary based on a set of closed set of points #==========================...
import time import sys import ConfigParser sys.path.append('../Control_program/') from telescope import * ##### Use current system config file ####### configfile = '/opt/salsa/controller/SALSA.config' ############################# config = ConfigParser.ConfigParser() config.read(configfile) tel = TelescopeController(...
import logging from tornado.options import options import tornado.web import tornado.httpclient import json import os import fnmatch from subprocess import call PERMITTED_IPS = [ "127.0.0.1", "204.232.175.*", "192.30.252.*" ] class GitWebHookHandler(tornado.web.RequestHandler): def get(self, *args, **kwargs...
from tests import PyResTests, Basic, TestProcess from pyres import ResQ from pyres.worker import Worker from pyres.job import Job import os class ResQTests(PyResTests): def test_enqueue(self): self.resq.enqueue(Basic,"test1") self.resq.enqueue(Basic,"test2", "moretest2args") ResQ._enqueue(Ba...
from lablog.interfaces import Interface import humongolus.field as field from lablog.util import aes from lablog import config from lablog import messages from datetime import datetime import json import logging k = list(config.SKEY) k.append(0x00) SKEY = bytearray(k) KEY = buffer(SKEY) class Node(Interface): mea...
from __future__ import unicode_literals # Ensure 'assert_raises' context manager support for Python 2.6 import tests.backport_assert_raises from nose.tools import assert_raises import boto import boto3 from boto.exception import EC2ResponseError import sure # noqa from moto import mock_ec2 from tests.helpers import ...
from ventana import Ventana import utils import pygtk pygtk.require('2.0') import gtk, gtk.glade, time, sqlobject try: import pclases except ImportError: import sys from os.path import join as pathjoin; sys.path.append(pathjoin("..", "framework")) import pclases try: import geninformes except Import...
# -*- coding: utf-8 -*- from .campos import CampoData from .campos import CampoFixo from .campos import CampoRegex from .erros import CampoError from .erros import CampoInexistenteError class Registro(object): """ Classe abstrata para a manipulação dos registros. >>> class RegistroTest(Registro): .....
import logging import re import statsd import webob.dec from oslo_middleware import base LOG = logging.getLogger(__name__) VERSION_REGEX = re.compile(r"/(v[0-9]{1}\.[0-9]{1})") UUID_REGEX = re.compile( r'.*(\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}).*a', re.IGNORECASE) # UUIDs without th...
from typing import Any, Dict from django.utils.module_loading import import_string from django.utils.translation import ugettext as _ from django.views.decorators.csrf import csrf_exempt, csrf_protect from zerver.decorator import authenticated_json_view, authenticated_rest_api_view, \ process_as_post from zerver....
from . import deadline # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
from __future__ import unicode_literals import ConfigParser as configparser import logging import re import time import urlparse from collections import OrderedDict from contextlib import closing import requests try: import cStringIO as StringIO except ImportError: import StringIO as StringIO try: impo...
from stockanalyser.stock import Stock from stockanalyser.analysis.levermann import (Levermann, prev_weekday, closest_weekday, prev_month) from stockanalyser.mymoney import Money import pytest import datetime def test_eval_analyst_rating(): s = Stock("VOW.DE") l = L...
from __future__ import print_function import traceback import newspaper import re import time from Data2File import getDataBasePath, article2file class NPSpyder: # Initialize a source object defining the source website and the regex to filter articles # name: ID to be used to name folders etc. # sourceURL...
''' Load trace files as numpy arrays. ''' import logging log = lambda: logging.getLogger(__name__) import numpy as np from datetime import time, datetime converters = { # Legacy data types 'none': lambda _: None, 'string': lambda x: x, 'hex': lambda x: int(x, 16), 'float': lambda x: float(x), # ...
from django.contrib.auth.models import User from django.db import models from ordered_model.models import OrderedModel from datetime import date, time, datetime, timedelta from django.utils import timezone import re class Page(OrderedModel): url = models.CharField("Url of page to display (relative to root)...
""" Caching instances via ``related_name`` -------------------------------------- ``cache_relation`` adds utility methods to a model to obtain ``related_name`` instances via the cache. Usage ~~~~~ :: from django.db import models from django.contrib.auth.models import User class Foo(models.Model): ...
""" Module for the Cache class for BlockStructure objects. """ # pylint: disable=protected-access from logging import getLogger from openedx.core.lib.cache_utils import zpickle, zunpickle from .block_structure import BlockStructureModulestoreData logger = getLogger(__name__) # pylint: disable=C0103 class BlockSt...
import os import pytest from cafa_do_format_checker import cafa_checker ''' The tests are intended to be run with pytest (pip install pytest) From the project root directory (parent directory of the test directory), run pytest with python's module syntax: python -m pytest or to run a single test (where test_valid_DO_...
# -*- coding: utf-8 -*- """ pygments.lexers.mosel ~~~~~~~~~~~~~~~~~~~~~ Lexers for the mosel language. http://www.fico.com/en/products/fico-xpress-optimization :copyright: Copyright 2006-2019 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.lexer im...
import argparse import copy import io import os import subprocess import sys import warnings import pbr.version import six.moves from stestr import commands from subunit import run as subunit_run from testtools import run as testtools_run from os_testr import regex_builder as rb __version__ = pbr.version.VersionIn...
""" Documentation comment extractor =============================== This module extracts relevant documentation comments, optionally reformatting them in reST syntax. This is the part that uses Clang Python Bindings to extract documentation comments from C source code. This module does not depend on Sphinx. There ar...
# -*- coding: utf-8 -*- from django.db import models from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from mezzanine.conf import settings from mezzanine.core.fields import FileField from mezzanine.core.models import Display...
#!/usr/bin/env python import subprocess import socket import sys import string import random import os import signal def timeout(sig,frm): sys.stderr.write( "End-to-end test timeout." ) sys.exit(1) # Timeout after 10 seconds signal.signal(signal.SIGALRM, timeout) signal.alarm(10) server_sock = socket.socket(soc...
"""A NSUPDATE server class for gevent, emulating apple's mDNSResponder SPS server""" # Copyright (c) 2013 Russell Cloran # Copyright (c) 2014 Joey Korkames import traceback import struct import logging import dns.name import dns.flags import dns.message import dns.reversename import dns.edns import ipaddress import ...
#coding:utf-8 import struct # 支持文件类型 # 用16进制字符串的目的是可以知道文件头是多少字节 # 各种文件头的长度不一样,少半2字符,长则8字符 def typeList(): return { "52617221": "EXT_RAR", "504B0304": "EXT_ZIP", "FFD8FF":"JPEG (jpg)", "89504E47":"PNG (png)", "47494638":"GIF (gif)", "49492A0...
""" Module hosting class representing the connection data to the gogonlinux website """ import json import requests import os import stat WEBSITE_URL = "http://www.gogonlinux.com" AVAILABLE_GAMES = "/available" BETA_GAMES = "/available-beta" def get_data_from_resource(location): """ Return the data from a s...
""" Decorator module, see http://pypi.python.org/pypi/decorator for the documentation. """ __version__ = '3.3.2' __all__ = ["decorator", "FunctionMaker", "partial"] import sys, re, inspect try: from functools import partial except ImportError: # for Python version < 2.5 class partial(object): ...
# -*- coding: utf-8 -*- __author__ = 'study_sun' from spider_base import SBURLManager from convenient import * reload(sys) sys.setdefaultencoding('utf-8') class StockURLManager(SBURLManager): #比较诡异一些,返回的依次是(code, 基础信息url, 介绍页url, 当日行情url) def pop_url(self): code = self.feed_urls.pop() return ...
""" General tests for relational fields. """ from __future__ import unicode_literals from django.db import models from django.test import TestCase from rest_framework import serializers class NullModel(models.Model): pass class FieldTests(TestCase): def test_pk_related_field_with_empty_string(self): ...
#!/opt/local/bin/python # Python program to find first triangle number with 500 factors import sys import math import timeit import time import itertools def my_iter_product(iterable, repeat=1): # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy # product(range(2), repeat=3) --> 000 001 010 011 100 101 110...
# -*- coding: utf-8 -*- """ Created on Mon Jun 23 14:11:22 2014 @author: mstreet """ import unittest import numpy as np import annexCeqns as ISO # import pdb class ISOtestSetUp(unittest.TestCase): def setUp(self): self.cases = np.array(xrange(1,4)) # transmission coefficients self.H_v = n...
import unittest import sys from unittest.mock import Mock, MagicMock, _magics class TestMockingMagicMethods(unittest.TestCase): def test_deleting_magic_methods(self): mock = Mock() self.assertFalse(hasattr(mock, '__getitem__')) mock.__getitem__ = Mock() self.assertTrue(hasattr(m...
version = "Beta-4.0-RC2" config = { 'port':9998, 'version':version, 'agentprefix':'OMERO', 'redirect':'http://trac.openmicroscopy.org.uk/omero/wiki/UpgradeCheck', 'upgrade':'Please upgrade to %s See http://trac.openmicroscopy.org.uk/omero for the latest version' % version } from twisted.applica...
##################################### # # # # # # # Eyüp Can KILINÇDEMİR # # <EMAIL> # # ceksoft.wordpress.com # # # # # #...
from ropperapp.loaders.loader import * from ropperapp.loaders.mach_intern.mach_gen import * from struct import pack as p import importlib class SegmentData(DataContainer): """ struct = SegmentCommand name = string (section name) bytes = c_byte_array (section bytes) """ class LoaderData(DataContain...
import sys import os import ycm_client_support VERSION_FILENAME = 'EXPECTED_CORE_VERSION' def DirectoryOfThisScript(): return os.path.dirname( os.path.abspath( __file__ ) ) def ExpectedCoreVersion(): return int( open( os.path.join( DirectoryOfThisScript(), VERSION_FILENAME ) )....
""" FILE: perl.py AUTHOR: Cody Precord @summary: Lexer configuration module for Perl. """ __author__ = "Cody Precord <<EMAIL>>" __svnid__ = "$Id: _perl.py 66108 2010-11-10 21:04:54Z CJP $" __revision__ = "$Revision: 66108 $" #-----------------------------------------------------------------------------# # Imports im...
from south.db import db from django.db import models from localtv.models import * class Migration: no_dry_run = True def forwards(self, orm): "Write your forwards migration here" for tag in orm.Tag.objects.all(): orm['tagging.Tag'].objects.get_or_create( name=t...
# -*- coding: utf-8 -*- import time import os import logging from logging.handlers import BaseRotatingHandler from gunicorn.glogging import Logger as GLogger from gunicorn import util as gutil try: import codecs except ImportError: codecs = None try: basestring except NameError: basestring = str cla...
from django.contrib.auth import signals from django.contrib.auth.models import User from django.contrib.auth.tests.utils import skipIfCustomUser from django.test import TestCase, override_settings from django.test.client import RequestFactory @skipIfCustomUser @override_settings(USE_TZ=False, PASSWORD_HASHERS=['d...
import sys import readParams_moreoptions as rdp1 import matplotlib.pyplot as plt import matplotlib.ticker as ticker import numpy as np from netCDF4 import MFDataset as mfdset, Dataset as dset import time import pyximport pyximport.install() from getvaratzc import getvaratzc5, getvaratzc, getTatzc, getTatzc2 from pym6 i...
# -*- coding:utf-8 -*- from ..client import Client from .model import Model from ..resources.resource import Resource from ..resources.license import License from ...util import Util import saklient # module saklient.cloud.models.model_license class Model_License(Model): ## ライセンスを検索・作成するための機能を備えたクラス。 ##...
import csv import json from virtualisation.misc.jsonobject import JSONObject as JOb import os from rabbitmq import RabbitMQ __author__ = 'Daniel Puschmann' class ConsumerDummy(object): """ Default listener, to test if messages are sent through the message bus. """ def __init__(self, ex...
import sys, os from shutil import copy2 from os.path import expanduser from bbdd import Bbdd from images import Images class Bookie: ruta = None #Setters def setId(self, id): self.id = id bd = Bbdd() self.name, self.country = bd.select("bookie", None, "id=" + str(self.id), "name, country")[0] bd.clos...
#!/usr/bin/env python import sys import textwrap import matplotlib.pyplot as plt from descartes.patch import PolygonPatch import graph def GenerateOutputFile(grph): array = grph.synthesizeArray() output_str = " AvgPoint2StateLookup : constant array\n (X_Coordinate'Range, Y_Coordinate'Range)\n ...
from django.conf import settings from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon import tabs from openstack_dashboard import api from openstack_dashboard.dashboards.identity.projects.groups \ import tables as groups_tables from openstack_dashboard.dashboards.id...
"""Functional tests for 3d convolutional operations.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import itertools import numpy as np from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow....
from tendenci.apps.contacts.models import Contact from django import forms from captcha.fields import CaptchaField from django.utils.translation import ugettext_lazy as _ from tendenci.apps.base.fields import EmailVerificationField, CountrySelectField class ContactForm(forms.ModelForm): class Meta: model...
# coding=utf-8 from __future__ import print_function from __future__ import division from . import ph import numpy as np import unittest __author__ = 'aleb' # noinspection PyArgumentEqualDefault class GeneralTest(unittest.TestCase): def test_issue24(self): FSAMP = 100 n = np.arange(1000) ...
import invoice import ir_sequence_approval import ir_attachment_facturae
from __future__ import print_function, division, absolute_import import sys from contextlib import contextmanager import pytest s3fs = pytest.importorskip('s3fs') boto3 = pytest.importorskip('boto3') moto = pytest.importorskip('moto') httpretty = pytest.importorskip('httpretty') from toolz import concat, valmap, pa...
"""Serializers for REST framework""" from rest_framework import serializers from geomat.stein.models import CrystalSystem, Handpiece, MineralType, Photograph, QuizQuestion,\ QuizAnswer, Cleavage, GlossaryEntry, TreeNode from drf_yasg.utils import swagger_serializer_method class StdImageField(serializers.ImageFi...
"""The Exponential distribution class.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib.distributions.python.ops import gamma from tensorflow.python.framework import dtypes from tensorflow.python.framework impor...
from bettercache.utils import CachingMixin, strip_wsgi from bettercache.proxy import proxy import logging logger = logging.getLogger(__name__) class BetterView(CachingMixin): """Accepts any path and attempts to serve it from the cache. If it cannot find the response in the cache, it will use ``bettercache.pro...
#!/opt/yinhe/venv1/bin/python # # The Python Imaging Library. # $Id$ # # a utility to identify image files # # this script identifies image files, extracting size and # pixel mode information for known file formats. Note that # you don't need the PIL C extension to use this module. # # History: # 0.0 1995-09-01 fl C...
import unittest from pypat import * class TestExamples(unittest.TestCase): # Matching against literal values def test_literal(self): result = match(42, (234, lambda: False), (True, lambda: False), (42, lambda: True)) self.ass...
"""Management command for enabling an extension.""" from __future__ import unicode_literals from django.core.management.base import CommandError from django.utils.translation import ugettext as _ from djblets.extensions.errors import (EnablingExtensionError, InvalidExtensionErro...
from openerp import api, fields, models, _ from openerp.exceptions import UserError class SaleOrderLine(models.Model): _inherit = "sale.order.line" @api.multi def _compute_analytic(self, domain=None): lines = {} if not domain: domain = [('so_line', 'in', self.ids), ('amount', ...
#!/usr/bin/python """ This module implements the base class upon which all the individual data sets are built. """ from Globals import * from BaseClasses import LampadasCollection class DataSet(LampadasCollection): def __init__(self, dms): super(DataSet, self).__init__() self.dms = dms def ...
" Common settings for all project. " from os import path as op, walk import logging from settings import SOURCE_DIR, PROJECT_DIR, PROJECT_NAME SECRET_KEY = "RedefineME.%s" % PROJECT_NAME # Databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'django_master.sqlite'...
from gensim import corpora from gensim import models import psycopg2 DOC_NUM = 4 DBPATH = "dbname=image_tagging host=localhost user=postgres" con = psycopg2.connect(DBPATH) concur = con.cursor() #concur.execute("select tweet_id, word from preprocess order by tweet_id") concur.execute("delete from exp_rawlda") con...
"""Test the rawtransaction RPCs. Test the following RPCs: - createrawtransaction - signrawtransaction - sendrawtransaction - decoderawtransaction - getrawtransaction """ from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * class multidict(dict): """Dict...
import logging, os from autotest.client.shared import error from autotest.client.virt import virt_test_utils, virt_utils, aexpect def run_nic_hotplug(test, params, env): """ Test hotplug of NIC devices 1) Boot up guest with one nic 2) Add a host network device through monitor cmd and check if it's ad...