content string |
|---|
import tensorflow as tf
import numpy as np
from sys import argv
from tensorflow.contrib import rnn
from util import run_model
def main():
"""
Run this command to generate the pb file
1. mkdir model
2. python rnn.py
"""
tf.set_random_seed(1)
n_steps = 2
n_input = 10
n_hidden = 20
... |
categories = ["call",
"conditional_jump",
"interrupts_and_exceptions",
"jump",
"loop",
"xreturn"]
microcode = ""
for category in categories:
exec "import %s as cat" % category
microcode += cat.microcode |
"""Prepare data for further process.
Read data from "/slope", "/ring", "/wing", "/negative" and save them
in "/data/complete_data" in python dict format.
It will generate a new file with the following structure:
├── data
│ └── complete_data
"""
from __future__ import absolute_import
from __future__ import division... |
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect
from django.core.exceptions import SuspiciousOperation
from django.shortcuts import render_to_response
from django.utils import simplejson
from django.utils.encoding impo... |
from __future__ import division, print_function, absolute_import
import numpy.testing as npt
import numpy as np
from scipy._lib.six import xrange
from scipy import stats
from common_tests import (check_normalization, check_moment, check_mean_expect,
check_var_expect, check_skew_expect,
... |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import *
import re
import sys
import os
import subprocess
import socket
from .parser i... |
"""
The MIT License (MIT)
Copyright (c) 2017 Funky7Monkey
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,... |
'''OpenGL extension APPLE.ycbcr_422
This module customises the behaviour of the
OpenGL.raw.GL.APPLE.ycbcr_422 to provide a more
Python-friendly API
Overview (from the spec)
This extension provides a method for GL to read, store and optionally
process textures that are defined in Y'CbCr 422 video formats. This
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.apps.registry import Apps
from django.db import models
from django.utils import six
from django.utils.encoding import python_2_unicode_compatible
class CustomModelBase(models.base.ModelBase):
pass
class ModelWithCustomBase(six.with_met... |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import flask_admin as admin
from geoalchemy2.types import Geometry
from flask_admin.contrib.geoa import ModelView
# Create application
app = Flask(__name__)
app.config.from_pyfile('config.py')
db = SQLAlchemy(app)
class Point(db.Model):
id = db.Co... |
"""
fs.osfs.watch_win32
===================
Change watcher support for OSFS, using ReadDirectoryChangesW on win32.
"""
import os
import sys
import errno
import threading
import Queue
import stat
import struct
import ctypes
import ctypes.wintypes
import traceback
import weakref
try:
LPVOID = ctypes.wintypes.LPVO... |
# init: Time: O(n), Space: O(n)
# get: Time: O(1), Space: O(1)
# check: Time: O(1), Space: O(1)
# release: Time: O(1), Space: O(1)
class PhoneDirectory(object):
def __init__(self, maxNumbers):
"""
Initialize your data structure here
@param maxNumbers - The maximum numbers that... |
import os
import sys
def main():
path = sys.argv[1]
suffix = sys.argv[2]
for root, _, filenames in os.walk(path):
for filename in filenames:
if filename.endswith(suffix):
os.remove(os.path.join(root, filename))
if __name__ == '__main__':
main() |
from twext.enterprise.dal.syntax import SQLFragment
from twisted.trial.unittest import TestCase
from twistedcaldav import carddavxml
from txdav.carddav.datastore.query.filter import Filter, FilterBase
from txdav.common.datastore.sql_tables import schema
from txdav.carddav.datastore.query.builder import buildExpressi... |
"""
Copyright (c) 2016, Marcelo Leal
Description: Simple Azure Media Services Python library
License: MIT (see LICENSE.txt file for details)
"""
import os
import json
import amspy
import time
import logging
import datetime
###########################################################################################
####... |
import sqlite3
import urllib
import re
from urllib.request import urlopen
from bs4 import BeautifulSoup
from phyllo.phyllo_logger import logger
def getBooks(soup):
siteURL = 'http://www.thelatinlibrary.com'
textsURL = []
# get links to books in the collection
for a in soup.find_all('a', href=True):
... |
"""
Cling Kernel for Jupyter
Talks to Cling via ctypes
"""
from __future__ import print_function
__version__ = '0.0.2'
import ctypes
from contextlib import contextmanager
from fcntl import fcntl, F_GETFL, F_SETFL
import os
import shutil
import select
import struct
import sys
import threading
from traitlets import ... |
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('\... |
import sys
from PySide2.QtWidgets import *
from GridCal.Gui.TowerBuilder.gui import *
from GridCal.Engine.Devices import *
from GridCal.Gui.TowerBuilder.tower_model import *
from GridCal.Gui.GuiFunctions import PandasModel
from GridCal.Gui.GeneralDialogues import LogsDialogue
class TowerBuilderGUI(QtWidgets.QDialog... |
# encoding: utf-8
"""
Management command for updading the documentation of one or more projects.
"""
import json
import optparse
import os
import os.path
import subprocess
from django.core.management import call_command
from django.core.management.base import BaseCommand, CommandError
from sphinxdoc.models import Pr... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import distutils.spawn
import traceback
import os
import shlex
import subprocess
from ansible import errors
from ansible.utils.unicode import to_bytes
from ansible.callbacks import vvv
import ansible.constants as C
BUFSIZE = 65536... |
"""
Verifies that a dependency on a bundle causes the whole bundle to be built.
"""
import TestGyp
import sys
if sys.platform == 'darwin':
print "This test is currently disabled: https://crbug.com/483696."
sys.exit(0)
test = TestGyp.TestGyp(formats=['ninja', 'make', 'xcode'])
test.run_gyp('test.gyp', chdir... |
import atexit
import sys
from .ansitowin32 import AnsiToWin32
orig_stdout = sys.stdout
orig_stderr = sys.stderr
wrapped_stdout = sys.stdout
wrapped_stderr = sys.stderr
atexit_done = False
def reset_all():
AnsiToWin32(orig_stdout).reset_all()
def init(autoreset=False, convert=None, strip=None, wrap=True):
... |
## 1. Recap ##
import pandas as pd
import matplotlib.pyplot as plt
unrate = pd.read_csv('unrate.csv')
unrate['DATE'] = pd.to_datetime(unrate['DATE'])
plt.plot(unrate['DATE'].head(12),unrate['VALUE'].head(12))
plt.xticks(rotation=90)
plt.xlabel('Month')
plt.ylabel('Unemployment Rate')
plt.title('Monthly Unemployment T... |
{
'name': 'Decimal Precision Configuration',
'description': """
Configure the price accuracy you need for different kinds of usage: accounting, sales, purchases.
=================================================================================================
The decimal precision is configured per company.
""... |
"""
Collects metrics from the gunicorn web server.
http://gunicorn.org/
"""
# stdlib
import time
# 3rd party
import psutil
# project
from checks import AgentCheck
class GUnicornCheck(AgentCheck):
# Config
PROC_NAME = 'proc_name'
# Number of seconds to sleep between cpu time checks.
CPU_SLEEP_SECS... |
import sys
import stat
import shutil
import errno
import subprocess
import os
from gi.repository import GLib, Gio
def fatal(msg):
print >>sys.stderr, msg
sys.exit(1)
def log(msg):
"Print to standard output and flush it"
sys.stdout.write(msg)
sys.stdout.write('\n')
sys.stdout.flush()
def run_... |
import numpy as np
from nose.tools import assert_raises
from horton import * # pylint: disable=wildcard-import,unused-wildcard-import
from horton.meanfield.test.common import check_hf_cs_hf, check_lih_os_hf, \
check_water_cs_hfs, check_n2_cs_hfs, check_h3_os_hfs, check_h3_os_pbe, \
check_co_cs_pbe, check_van... |
"""An XML Reader is the SAX 2 name for an XML parser. XML Parsers
should be based on this code. """
from . import handler
from ._exceptions import SAXNotSupportedException, SAXNotRecognizedException
# ===== XMLREADER =====
class XMLReader:
"""Interface for reading an XML document using callbacks.
XMLReade... |
import os
import shutil
import unittest
from django import conf
from django.test import TestCase
from django.utils import six
from django.utils._os import upath
@unittest.skipIf(
six.PY2,
'Python 2 cannot import the project template because '
'django/conf/project_template doesn\'t have an __init__.py fil... |
import pandas as pd
def get_top_topic_words(topics, opinions, t, top=10):
"""Return dataframe containing top topics and opinions.
Parameters
t : str - index of topic number
top : int - the number of words to store in the dataframe
Returns Pandas DataFrame
The DataFrame contains t... |
from .charsetprober import CharSetProber
from .constants import eNotMe
from .compat import wrap_ord
FREQ_CAT_NUM = 4
UDF = 0 # undefined
OTH = 1 # other
ASC = 2 # ascii capital letter
ASS = 3 # ascii small letter
ACV = 4 # accent capital vowel
ACO = 5 # accent capital other
ASV = 6 # accent small vowel
ASO = 7... |
"""
average several results
"""
import sys
import os
import csv
import cPickle as pickle
import numpy as np
import gzip
from numpy import isnan
RESULT_FILE = ["./RUN/avg_res/0.07889.csv",
"./RUN/avg_res/0.07895.csv",
"./RUN/avg_res/0.07911.csv",
"./RUN/avg_res/0.07939.csv... |
import re
def view_source_url(local_path):
return "http://trac.webkit.org/browser/trunk/%s" % local_path
def view_revision_url(revision_number):
return "http://trac.webkit.org/changeset/%s" % revision_number
contribution_guidelines = "http://webkit.org/coding/contributing.html"
bug_server_domain = "webki... |
import mock
import unittest
import tempestmail.bugs as bugs
class TestBugs(unittest.TestCase):
def setUp(self):
self.bz_url = 'https://bugzilla.redhat.com/show_bug.cgi?id=1386421'
self.lp_url = 'https://bugs.launchpad.net/tripleo/+bug/1634824'
self.error_url = 'https://www.google.com'
... |
# List of languages we support, their iso codes and id as understood
# by Windows SDK (LANG_* and SUBLANG_*_*).
# See http://msdn.microsoft.com/en-us/library/dd318693.aspx for the full list.
g_langs = [
('af', 'Afrikaans', '_LANGID(LANG_AFRIKAANS)'),
('am', 'Armenian (Հայերեն)', '_LANGID(LANG_ARMENIAN)'),... |
"""
unittest2
unittest2 is a backport of the new features added to the unittest testing
framework in Python 2.7. It is tested to run on Python 2.4 - 2.6.
To use unittest2 instead of unittest simply replace ``import unittest`` with
``import unittest2``.
Copyright (c) 1999-2003 Steve Purcell
Copyright (c) 2003-2010 P... |
"""
Volsay problem in Google or-tools.
From the OPL model volsay.mod
This model was created by Hakan Kjellerstrand (<EMAIL>)
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
from ortools.linear_solver import pywraplp
def main(unused_argv):
# Create the solver.
... |
# -*- coding: utf-8 -*-
from time import sleep
import logging
from raven import Client
import raven
import os
import uuid
import requests
import time
class BotEvent(object):
def __init__(self, config):
self.config = config
self.logger = logging.getLogger(__name__)
# UniversalAnalytics can ... |
from server import app
import datetime
import psycopg2
import flask
import pytz
import re
TIMEZONE = pytz.timezone("America/Vancouver")
CONN = "postgres:///lrrbot"
def convert_timezone(row):
return (row[0], row[1], TIMEZONE.normalize(row[2].astimezone(TIMEZONE)))
@app.route("/prism/")
def prism():
with psyc... |
"""
Headless client for the Crazyflie.
"""
import logging
import os
import signal
import sys
import cfclient.utils
import cflib.crtp
from cfclient.utils.input import JoystickReader
from cflib.crazyflie import Crazyflie
if os.name == 'posix':
print('Disabling standard output for libraries!')
stdout = os.dup(1)... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
ModelerScene.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
**************************... |
from boto.compat import six
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/
#
# 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 t... |
"""
Spanning tests for all the operations that F() expressions can perform.
"""
from __future__ import absolute_import
import datetime
from django.db import connection
from django.db.models import F
from django.test import TestCase, Approximate, skipUnlessDBFeature
from .models import Number, Experiment
class Expr... |
{
'name': 'Notes',
'version': '1.0',
'category': 'Tools',
'description': """
This module allows users to create their own notes inside OpenERP
=================================================================
Use notes to write meeting minutes, organize ideas, organize personal todo
lists, etc. Each us... |
# -*- coding: utf-8 -*-
import sys, os
import sphinx
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
DIR = os.path.dirname(__file... |
import os
from os.path import normpath
from mitmproxy.tools.console import pathedit
from mitmproxy.test import tutils
from unittest.mock import patch
class TestPathCompleter:
def test_lookup_construction(self):
c = pathedit._PathCompleter()
cd = os.path.normpath(tutils.test_data.path("mitmproxy... |
#!/usr/bin/env python
import pprint
import sys
import simpleparse.dispatchprocessor
declaration = r'''# note use of raw string when embedding in python code...
full := ws,expr,ws
number := [0-9eE+.-]+
expr := number,'+',number/number,'-',number
ws := [ \t\v]*
'''
class MyProcessorClass(... |
# $HeadURL$
__RCSID__ = "$Id$"
import types
from string import Template
class Activity:
dbFields = [ 'activities.unit',
'activities.type',
'activities.description',
'activities.filename',
'activities.bucketLength',
'sources.site',
... |
from django.utils.translation import ugettext_lazy as _
from horizon import tables
class QuotaFilterAction(tables.FilterAction):
def filter(self, table, tenants, filter_string):
q = filter_string.lower()
def comp(tenant):
if q in tenant.name.lower():
return True
... |
from openerp import SUPERUSER_ID
from openerp.osv import osv
class mail_thread(osv.AbstractModel):
""" Update of mail_mail class, to add the signin URL to notifications. """
_inherit = 'mail.thread'
def _get_inbox_action_xml_id(self, cr, uid, context=None):
""" For a given message, return an acti... |
from __future__ import unicode_literals
import re
import json
import itertools
from .common import InfoExtractor
from ..utils import unified_strdate
class VineIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?vine\.co/v/(?P<id>\w+)'
_TEST = {
'url': 'https://vine.co/v/b9KOOWX7HUx',
'md5':... |
from __future__ import absolute_import
# #START_LICENSE###########################################################
#
#
# This file is part of the Environment for Tree Exploration program
# (ETE). http://etetoolkit.org
#
# ETE is free software: you can redistribute it and/or modify it
# under the terms of the GNU Gener... |
"""The rescue mode extension."""
import webob
from webob import exc
from nova.api.openstack import common
from nova.api.openstack import extensions as exts
from nova.api.openstack import wsgi
from nova import compute
from nova import exception
from nova import utils
authorize = exts.extension_authorizer('compute', ... |
#!/usr/bin/env python
"""
Lists all the unique parts and their colors in a .mpd file. This
is sometimes useful for determining the name of a part and/or a
color.
Hazen 04/15
"""
import os
import re
import sys
import opensdraw.lcad_lib.datFileParser as datFileParser
if (len(sys.argv) != 2):
print("usage: <ldraw ... |
#! /usr/bin/env python
from unit_timeside import *
from timeside.decoder import *
from timeside.analyzer import Yaafe
from yaafelib import DataFlow,FeaturePlan
class TestYaafe(unittest.TestCase):
def setUp(self):
self.sample_rate = 16000
def testOnSweepWithFeaturePlan(self):
"runs on sweep a... |
import os
import sys
import time
import shutil
import struct
import zipfile
script_tag = "[Ardublockly pack] "
script_tab = " "
# The project_root_dir depends on this file location, assumed to be two levels
# below project root, so it cannot be moved without updating this variable
project_root_dir ... |
"""Loader for the Labeled Faces in the Wild (LFW) dataset
This dataset is a collection of JPEG pictures of famous people collected
over the internet, all details are available on the official website:
http://vis-www.cs.umass.edu/lfw/
Each picture is centered on a single face. The typical task is called
Face Veri... |
from django import forms
from django.test import TestCase
from django.core.exceptions import NON_FIELD_ERRORS
from modeltests.validation import ValidationTestCase
from modeltests.validation.models import Author, Article, ModelToValidate
# Import other tests for this package.
from modeltests.validation.validators impor... |
from unittest import main
from b3j0f.utils.ut import UTCase
from ..base import Schema
from ..registry import (
SchemaRegistry, registercls, getbydatatype, unregistercls
)
from uuid import uuid4
from numbers import Number
class AAA(object):
pass
class UpdateContentTest(UTCase):
def setUp(self):
... |
from serial.serialutil import *
import threading
import time
import logging
# map log level names to constants. used in fromURL()
LOGGER_LEVELS = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
}
class LoopbackSerial(SerialBase):
"""Serial p... |
"""BaseHTTPServer that implements the Python WSGI protocol (PEP 3333)
This is both an example of how WSGI can be implemented, and a basis for running
simple web applications on a local machine, such as might be done when testing
or debugging an application. It has not been reviewed for security issues,
however, and w... |
from django.contrib.gis.db.backends.base.adapter import WKTAdapter
from django.contrib.gis.db.backends.base.operations import \
BaseSpatialOperations
from django.contrib.gis.db.backends.utils import SpatialOperator
from django.contrib.gis.db.models import aggregates
from django.db.backends.mysql.operations import D... |
'''
Run this script from the root of the repository to update all translations from
transifex.
It will do the following automatically:
- fetch all translations using the tx tool
- post-process them into valid and committable format
- remove invalid control characters
- remove location tags (makes diffs less noisy)... |
"""
Simple solver "core". Contains capabilities for unpacking
a JSON n-tuple, as well as routing this n-tuple based
on the predicate_type (command, query, assertion, etc.).
Other general capabilities can be added. The design
is general enough that the same "unpacking" and "routing"
method can be used, as long as a new ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import re
import httplib
import urllib
from pyquery import PyQuery as pq
parser = argparse.ArgumentParser(
description='Download video resource from tudou.com',
epilog="Parse the url to video address using flvcd.com")
parser.add_argument('-... |
# -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsPalLabeling: base suite of render check tests
Class is meant to be inherited by classes that test different labeling outputs
See <qgis-src-dir>/tests/testdata/labeling/README.rst for description.
.. note:: This program is free software; you can redistribute it and/or... |
""" Module with the fixbv resize function """
import math
from _fixbv import fixbv
from _fixbv import FixedPointFormat
# round :
ROUND_MODES = ( # towards :
'ceil', # +infinity: always round up
'fix', # 0 : always down
'floor', # -infinity: truncate, alway... |
"""Given a GYP/GN filename, sort C-ish source files in that file.
Shows a diff and prompts for confirmation before doing the deed.
Works great with tools/git/for-all-touched-files.py.
Limitations:
1) Comments used as section headers
If a comment (1+ lines starting with #) appears in a source list without a
precedin... |
'''
class Aniaml:
count = 10
def __init__(self,name):
self.name = name
self.num = None
hobbie = 'meat'
@classmethod #类方法,不能访问实例变量
def talk(self):
print('%s is talking ...'%self.hobbie )
@staticmethod #静态方法,不能访问类变量及实例变量
def walk():
print('is walking ...')
... |
from django import http
from django.contrib.auth.models import User
from django.contrib.messages.storage.user_messages import UserMessagesStorage,\
LegacyFallbackStorage
from django.contrib.messages.tests.base import skipUnlessAuthIsInstalled
from django.contrib.messages.tests.cookie import set_cookie_data
from dja... |
"""
Unit tests for the arpcache module
"""
import os
import subprocess
import sys
import unittest
import mock
import moduletests.src.arpcache
try:
# Python 2.x
from cStringIO import StringIO
except ImportError:
# Python 3.x
from io import StringIO
if sys.hexversion >= 0x3040000:
# contextlib.red... |
from gi.repository import Gtk
from GTG import _, ngettext
from GTG.gtk.editor import GnomeConfig
class NotifyCloseUI():
def __init__(self):
# Load window tree
self.builder = Gtk.Builder()
self.builder.add_from_file(GnomeConfig.NOTIFY_UI_FILE)
signals = {"on_confirm_activate": sel... |
"""
specpolsplit
Split O and E beams
"""
import numpy as np
from scipy.interpolate import interp1d
from scipy.ndimage.interpolation import shift
from specpolutils import rssmodelwave
def read_wollaston(hdu, wollaston_file):
""" Correct the O or E beam for distortion due to the beam splitter
Parameters
... |
import tensorflow as tf
import numpy as np
import os
import sys
import random
import subprocess
from redis import Redis
import time
sys.path.append(os.path.realpath(".."))
import helpers.utils as hlp
from models.feed_forward import FFDiscrete
class A3CDiscreteTrainer(FFDiscrete):
def __init__(self, sess, args):... |
"""
Manages information about the guest.
This class encapsulates libvirt domain provides certain
higher level APIs around the raw libvirt API. These APIs are
then used by all the other libvirt related classes
"""
from lxml import etree
from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_u... |
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
import libcloud.security
# Skip this step if you are launching nodes on an official vCloud
# provider. It is intended only for self signed SSL certs in
# vanilla vCloud Director v1.5 test deployments.
# Note: Code like this ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Create... |
"""Functions to construct sparse matrices
"""
from __future__ import division, print_function, absolute_import
__docformat__ = "restructuredtext en"
__all__ = ['spdiags', 'eye', 'identity', 'kron', 'kronsum',
'hstack', 'vstack', 'bmat', 'rand', 'diags', 'block_diag']
from warnings import warn
import nu... |
import logging
import os
import shutil
from datetime import datetime
from lxml import etree
from flask import current_app as app
from superdesk.errors import IngestFileError, ParserError, ProviderError
from superdesk.io.registry import register_feeding_service
from superdesk.io.feed_parsers import XMLFeedParser
from su... |
import copy
import json
import pytest
from mock import MagicMock
from ansible.module_utils import hetzner
class ModuleFailException(Exception):
def __init__(self, msg, **kwargs):
super(ModuleFailException, self).__init__(msg)
self.fail_msg = msg
self.fail_kwargs = kwargs
def get_module_... |
"""
Template file used by ExpGenerator to generate the actual
permutations.py file by replacing $XXXXXXXX tokens with desired values.
This permutations.py file was generated by:
'~/nupic/eng/lib/python2.6/site-packages/nupic/frameworks/opf/expGenerator/ExpGenerator.py'
"""
from nupic.swarming.permutationhelpers impo... |
from testsuite.base_test import BaseTest
from testfixtures import log_capture
from testsuite import config
from core.sessions import SessionURL
from core import modules
from core import messages
import subprocess
import tempfile
import datetime
import logging
import os
class FileDOwnload(BaseTest):
def setUp(self... |
"""BibFormat element - Prints record statistics
"""
__revision__ = "$Id$"
from invenio.dbquery import run_sql
ELASTICSEARCH_ENABLED = False
try:
from elasticsearch import Elasticsearch
from invenio.config import \
CFG_ELASTICSEARCH_LOGGING, \
CFG_ELASTICSEARCH_SEARCH_HOST, \
CFG_ELASTI... |
"""
.. module: security_monkey.openstack.auditors.security_group
:platform: Unix
.. version:: $$VERSION$$
.. moduleauthor:: Michael Stair <<EMAIL>>
"""
from security_monkey.auditors.security_group import SecurityGroupAuditor
from security_monkey.watchers.openstack.network.openstack_security_group import OpenStac... |
#! /usr/bin/env python
"""Test script for popen2.py"""
import warnings
warnings.filterwarnings("ignore", ".*popen2 module is deprecated.*",
DeprecationWarning)
warnings.filterwarnings("ignore", "os\.popen. is deprecated.*",
DeprecationWarning)
import os
import sys
impor... |
import re
from django.utils.cache import patch_vary_headers
from django.utils.text import compress_sequence, compress_string
re_accepts_gzip = re.compile(r'\bgzip\b')
class GZipMiddleware(object):
"""
This middleware compresses content if the browser allows gzip compression.
It sets the Vary header acco... |
from django import forms
from django.contrib.contenttypes.models import ContentType
from forms_builder.forms.forms import FormForForm
from .models import SurveyFieldEntry, SurveyFormEntry
class SurveyFormForForm(FormForForm):
field_entry_model = SurveyFieldEntry
content_type = forms.ModelChoiceField(
... |
from __future__ import unicode_literals
from django.utils import unittest
from django.utils.ipv6 import is_valid_ipv6_address, clean_ipv6_address
class TestUtilsIPv6(unittest.TestCase):
def test_validates_correct_plain_address(self):
self.assertTrue(is_valid_ipv6_address('fe80::223:6cff:fe8a:2e8a'))
... |
import xml.sax.saxutils
from boto.s3.acl import Grant
class BucketLogging(object):
def __init__(self, target=None, prefix=None, grants=None):
self.target = target
self.prefix = prefix
if grants is None:
self.grants = []
else:
self.grants = grants
def __... |
# encoding: utf-8
try:
from collections import OrderedDict
except ImportError:
# support installable ordereddict module in older python versions
from ordereddict import OrderedDict
from time import time
class TimeCache (dict):
__default = object()
def __init__ (self,timeout):
self.timeout = timeout
self.la... |
"""
Settings and configuration for Django.
Values will be read from the module specified by the DJANGO_SETTINGS_MODULE environment
variable, and then from django.conf.global_settings; see the global settings file for
a list of all possible variables.
"""
import logging
import os
import sys
import time # Needed fo... |
USERS = {
"haho0032": {
"sn": "Hoerberg",
"givenName": "Hans",
"eduPersonScopedAffiliation": "<EMAIL>",
"eduPersonPrincipalName": "<EMAIL>",
"uid": "haho",
"eduPersonTargetedID": "one!for!all",
"c": "SE",
"o": "Example Co.",
"ou": "IT",
... |
import hashlib
import logging
import re
from django.conf import settings
from django import http
from django.core.mail import mail_managers
from django.utils.http import urlquote
from django.utils import six
from django.core import urlresolvers
logger = logging.getLogger('django.request')
class CommonMiddleware(ob... |
# -*- coding: utf-8 -*-
"""
requests.structures
~~~~~~~~~~~~~~~~~~~
Data structures that power Requests.
"""
import os
import collections
from itertools import islice
class IteratorProxy(object):
"""docstring for IteratorProxy"""
def __init__(self, i):
self.i = i
# self.i = chain.from_iter... |
"""Configuration-related classes for versionner"""
import codecs
import configparser
import pathlib
import re
import sys
from versionner import defaults
ENV_VERSIONNER_PROJECT_CONFIG_FILE = 'VERSIONNER_PROJECT_CONFIG_FILE'
# pylint: disable=too-many-instance-attributes,too-few-public-methods
class FileConfig:
... |
import mock
import unittest
from swift.common.swob import Request, Response
from swift.common.middleware.acl import format_acl
from swift.proxy import server as proxy_server
from swift.proxy.controllers.base import headers_to_account_info
from swift.common import constraints
from test.unit import fake_http_connect, Fa... |
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'chart_font04.xlsx'
... |
# -*- coding: utf-8 -*-
from .Qt import QtCore, QtGui
from .Vector import Vector
from .Transform3D import Transform3D
from .Vector import Vector
import numpy as np
class SRTTransform3D(Transform3D):
"""4x4 Transform matrix that can always be represented as a combination of 3 matrices: scale * rotate * translate
... |
"""Support for The Things Network's Data storage integration."""
import asyncio
import logging
import aiohttp
from aiohttp.hdrs import ACCEPT, AUTHORIZATION
import async_timeout
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import (
ATT... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.