content string |
|---|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.contrib.sites.models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Site',
fields=[
... |
"""
MySQL database backend for Django.
Requires mysqlclient: https://pypi.python.org/pypi/mysqlclient/
MySQLdb is supported for Python 2 only: http://sourceforge.net/projects/mysql-python
"""
from __future__ import unicode_literals
import datetime
import re
import sys
import warnings
from django.conf import settings... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from units.compat.mock import patch
from ansible.modules.network.onyx import onyx_ospf
from units.modules.utils import set_module_args
from .onyx_module import TestOnyxModule, load_fixture
class TestOnyxOspfModule(TestOnyxModule)... |
import requests
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
OAuth2LoginView,
OAuth2CallbackView)
from .provider import TwitchProvider
class TwitchOAuth2Adapter(OAuth2Adapt... |
"""
Django settings for spameggs project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
i... |
import sys
import logging
import dbus
from sugar3 import dispatch
from jarabe import config
_DBUS_SERVICE = 'org.freedesktop.Notifications'
_DBUS_IFACE = 'org.freedesktop.Notifications'
_DBUS_PATH = '/org/freedesktop/Notifications'
_instance = None
class NotificationService(dbus.service.Object):
def __init... |
"""Build a language detector model
The goal of this exercise is to train a linear classifier on text features
that represent sequences of up to 3 consecutive characters so as to be
recognize natural languages by using the frequencies of short character
sequences as 'fingerprints'.
"""
# License: Simplified BSD
impor... |
class Ref(object):
def __init__(self, repo, name):
super(Ref, self).__init__()
self.repo = repo
self.name = name
def getHead(self):
return self.repo._getCommitByRefName(self.name)
def getNormalizedName(self):
return self.name
def getNewCommits(self, comparedTo, li... |
"""A collection of modules for iterating through different kinds of
tree, generating tokens identical to those produced by the tokenizer
module.
To create a tree walker for a new type of tree, you need to do
implement a tree walker object (called TreeWalker by convention) that
implements a 'serialize' method taking a ... |
def main(request, response):
import simplejson as json
f = file('config.json')
source = f.read()
s = json.JSONDecoder().decode(source)
url1 = "http://" + s['host'] + ":" + str(s['ports']['http'][1])
url2 = "http://" + s['host'] + ":" + str(s['ports']['http'][0])
_CSP = "style-src " + url1
... |
"""
Use tabs for indentation.
This rule check if the each line starts with a space.
In addition, it suppresses the violation when the line contains only spaces and tabs.
== Violation ==
void Hello()
{
[SPACE][SPACE]Hello(); <== Violation. Spaces are used for indentation.
}
== Good ==
void Hello()... |
# -*- coding: utf-8 -*-
import os
import re
import sys
import shlex
import subprocess
import multiprocessing
class NativeLib:
def __init__ (self, apiVersion, abiVersion):
self.apiVersion = apiVersion
self.abiVersion = abiVersion
def getPlatform ():
if sys.platform.startswith('linux'):
return 'linux'
else:
... |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
int_or_none,
float_or_none,
str_to_int,
)
class VidmeIE(InfoExtractor):
_VALID_URL = r'https?://vid\.me/(?:e/)?(?P<id>[\da-zA-Z]+)'
_TEST = {
'url': 'https://vid.me/QNB',
'md... |
from webkitpy.common.config import urls
def bug_comment_from_svn_revision(svn_revision):
return "Committed r%s: <%s>" % (svn_revision, urls.view_revision_url(svn_revision))
def bug_comment_from_commit_text(scm, commit_text):
svn_revision = scm.svn_revision_from_commit_text(commit_text)
return bug_commen... |
from gi.repository import GObject
from gi.repository import Gtk
from sugar3.graphics.icon import Icon
from sugar3.graphics import style
class PaletteMenuBox(Gtk.VBox):
def __init__(self):
Gtk.VBox.__init__(self)
def append_item(self, item_or_widget, horizontal_padding=None,
verti... |
from django.forms import SelectMultiple
from .base import WidgetTest
class SelectMultipleTest(WidgetTest):
widget = SelectMultiple()
numeric_choices = (('0', '0'), ('1', '1'), ('2', '2'), ('3', '3'), ('0', 'extra'))
def test_render_selected(self):
self.check_html(self.widget, 'beatles', ['J'], c... |
#a class for the Kaplan-Meier estimator
from statsmodels.compat.python import range
import numpy as np
from math import sqrt
import matplotlib.pyplot as plt
class KAPLAN_MEIER(object):
def __init__(self, data, timesIn, groupIn, censoringIn):
raise RuntimeError('Newer version of Kaplan-Meier class available... |
import logging
from autotest.client.shared import error
from autotest.client import utils
@error.context_aware
def run(test, params, env):
"""
Timer device tscwrite test:
1) Check for an appropriate clocksource on host.
2) Boot the guest.
3) Download and compile the newest msr-tools.
4) Execu... |
from twisted.python import log
from twisted.internet import defer
from twisted.application import service
from buildbot import pbutil
class UsersBase(service.MultiService):
"""
Base class for services that manage users manually. This takes care
of the service.MultiService work needed by all the services th... |
from gi.repository import Gtk
from zim.newfs import LocalFile
from zim.newfs.helpers import TrashHelper, TrashNotSupportedError
from zim.config import XDG_DATA_HOME, data_file
from zim.templates import list_template_categories, list_templates
from zim.gui.widgets import Dialog, BrowserTreeView, ScrolledWindow
from zim... |
"""
Test cases for dirdbm module.
"""
import os, shutil, glob
from twisted.trial import unittest
from twisted.persisted import dirdbm
class DirDbmTestCase(unittest.TestCase):
def setUp(self):
self.path = self.mktemp()
self.dbm = dirdbm.open(self.path)
self.items = (('abc', 'foo'), ('/l... |
# -*- coding: utf-8 -*-
import logging
import urlparse
import time
import lxml.html
import openerp
import re
_logger = logging.getLogger(__name__)
class Crawler(openerp.tests.HttpCase):
""" Test suite crawling an openerp CMS instance and checking that all
internal links lead to a 200 response.
If a use... |
#!/usr/bin/env python3
# https://github.com/drduh/config/blob/master/lighttpd/upload.py
# Simple file uploader
# Put into /var/www/cgi-bin/, make executable and enable CGI
import cgi
import os
CHUNK_SIZE = 100000
UPLOAD = "/var/www/upload/"
HEADER = """
<html><head><title>%s</title>
<style type="text/css">
body {
... |
"""
Invenio implementation of the connector to CKEditor for file upload.
This is heavily borrowed from FCKeditor 'upload.py' sample connector.
"""
import os
import re
from invenio.legacy.bibdocfile.api import decompose_file, propose_next_docname
allowed_extensions = {}
allowed_extensions['File'] = ['7z','aiff','asf',... |
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.translation import ugettext_lazy as _
from taggit.managers import TaggableManager
from ideasbox.models import TimeStampedModel
from ideasbox.search.models import SearchableQuerySet, SearchMixin... |
"""
Testing attribute/function access in a query.
"""
import unittest
class TesetAttrs(unittest.TestCase):
def __init__(self, methodName='runTest'):
unittest.TestCase.__init__(self, methodName)
`Foo(int i, Avg avg) groupby(1).
Bar(int i).`
def setUp(self):
`clear Foo.
... |
from astroplan import FixedTarget
from astropy.coordinates import SkyCoord
from pocs import PanBase
class Field(FixedTarget, PanBase):
def __init__(self, name, position, equinox='J2000', **kwargs):
""" An object representing an area to be observed
A `Field` corresponds to an `~astroplan.Observi... |
import time
import getpass
from optparse import OptionParser
from tests.util.thrift_util import create_transport
# Imports required for HiveServer2 Client
from cli_service import LegacyTCLIService
from thrift.transport import TTransport, TSocket
from thrift.protocol import TBinaryProtocol
parser = OptionParser()
pars... |
print(int(False))
print(int(True))
print(int(0))
print(int(1))
print(int(+1))
print(int(-1))
print(int('0'))
print(int('+0'))
print(int('-0'))
print(int('1'))
print(int('+1'))
print(int('-1'))
print(int('01'))
print(int('9'))
print(int('10'))
print(int('+10'))
print(int('-10'))
print(int('12'))
print(int('-12'))
prin... |
"""Support for monitoring the state of Vultr Subscriptions."""
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import CONF_MONITORED_CONDITIONS, CONF_NAME, DATA_GIGABYTES
import homeassistant.helpers.config_validation as cv
fr... |
# coding=utf-8
"""
The SoftInterruptCollector collects metrics on software interrupts from
/proc/stat
#### Dependencies
* /proc/stat
"""
import platform
import os
import diamond.collector
# Detect the architecture of the system
# and set the counters for MAX_VALUES
# appropriately. Otherwise, rolling over
# coun... |
"""Nadam for TensorFlow."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import state_ops
... |
"""Support for HLK-SW16 switches."""
from homeassistant.components.switch import ToggleEntity
from . import DATA_DEVICE_REGISTER, SW16Device
from .const import DOMAIN
PARALLEL_UPDATES = 0
def devices_from_entities(hass, entry):
"""Parse configuration and add HLK-SW16 switch devices."""
device_client = hass.... |
from __future__ import unicode_literals
import argparse
import logging
import re
logger = logging.getLogger(__name__)
def main(log_path):
for log_line in yield_train_log_line(log_path):
print log_line
break
class TrainLogLine(object):
__slots__ = ('iteration', 'elapsed', 'test_loss', 'tra... |
from Numeric import *
import LinearAlgebra as la
import sys
n = 15
m = zeros(((n + 1) * 4, (n + 1) * 4), Float)
for i in range(n):
m[4 * i + 2][4 * i + 0] = .5
m[4 * i + 2][4 * i + 1] = -1./12
m[4 * i + 2][4 * i + 2] = 1./48
m[4 * i + 2][4 * i + 3] = -1./480
m[4 * i + 2][4 * i + 4] = .5
m[4 * i... |
from django.core.exceptions import ImproperlyConfigured
# -*- coding: utf-8 -*-
import functools
try:
import urlparse
except ImportError:
from urllib import parse as urlparse # python3 support
from django.core.exceptions import SuspiciousOperation
def default_redirect(request, fallback_url, **kwargs):
"""
E... |
import socket
import struct
import OpenSSL
from requests import adapters
try:
from requests.packages.urllib3 import connectionpool
from requests.packages.urllib3 import poolmanager
except ImportError:
from urllib3 import connectionpool
from urllib3 import poolmanager
import six
import ssl
from glance... |
#!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2019 Fortinet, Inc.
#
# 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 Lic... |
__author__ = '<EMAIL> (Takashi MATSUO)'
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import urllib
impor... |
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import pandas as pd
import sklearn.linear_model as lm
from sklearn.model_selection import learning_curve
from sklearn.metrics import accuracy_score
from sklearn.metrics import make_scorer
from sklearn.model_selection import Grid... |
"""ProximalGradientDescent for TensorFlow."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import ops
# pylint: disable=unused-import
from tensorflow.python.ops import math_ops
# pylint: enable=unused-import
from tensorflo... |
from __future__ import absolute_import
import codecs
from uuid import uuid4
from io import BytesIO
from .packages import six
from .packages.six import b
from .fields import RequestField
writer = codecs.lookup('utf-8')[3]
def choose_boundary():
"""
Our embarrassingly-simple replacement for mimetools.choose_... |
"""
Support for ANEL PwrCtrl switches.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.pwrctrl/
"""
import logging
import socket
from datetime import timedelta
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from hom... |
import sphinx
org_StandaloneHTMLBuilder_index_page = None
def StandaloneHTMLBuilder_index_page(self, pagename, doctree, title):
if pagename not in self.env.files_to_rebuild:
if pagename != self.env.config.master_doc and 'orphan' not in self.env.metadata[pagename]:
print("Excluding %s from fu... |
import sys
try:
import pygments
from pygments.lexers import CppLexer
from pygments.formatters import HtmlFormatter
PYGMENTS_IMPORTED = True
except ImportError:
print('It appears that Pygments is not installed. '
'Can be installed using easy_install Pygments or from http://pygments.org.')
PYGMENTS_IMPORT... |
"""SCons.Tool.BitKeeper.py
Tool-specific initialization for the BitKeeper source code control
system.
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.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 200... |
from telemetry.page import page as page_module
from telemetry import story
class MseCasesPage(page_module.Page):
def __init__(self, url, page_set):
super(MseCasesPage, self).__init__(url=url, page_set=page_set)
def RunNavigateSteps(self, action_runner):
super(MseCasesPage, self).RunNavigateSteps(action_... |
# -*- coding: utf-8 -*-
"""
Copyright [2009-2018] EMBL-European Bioinformatics Institute
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... |
"Commonly-used date structures"
from django.utils.translation import ugettext_lazy as _, pgettext_lazy
WEEKDAYS = {
0: _('Monday'), 1: _('Tuesday'), 2: _('Wednesday'), 3: _('Thursday'), 4: _('Friday'),
5: _('Saturday'), 6: _('Sunday')
}
WEEKDAYS_ABBR = {
0: _('Mon'), 1: _('Tue'), 2: _('Wed'), 3: _('Thu'),... |
"""Converting code to AST.
Adapted from Tangent.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import textwrap
import gast
from tensorflow.python.util import tf_inspect
def parse_object(obj):
"""Return the AST of given object."""
return parse... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from distutils.spawn import find_executable
from subprocess import call, Popen, PIPE
from ansible.errors import AnsibleError, AnsibleConnectionFailure, AnsibleFileNotFound
from ansible.module_utils._text import to_bytes,... |
"""Views, menus and traversal related to PersonProducts."""
__metaclass__ = type
__all__ = [
'PersonProductBreadcrumb',
'PersonProductFacets',
'PersonProductNavigation',
]
from zope.component import queryAdapter
from zope.traversing.interfaces import IPathAdapter
from lp.app.errors import NotFoundEr... |
import random
import time
class PowerInfo:
def __init__(self):
self._lastEnergy = 0
self._prevPower = 0
# Use time.perf_counter() instead of time.clock() when using python 3
self._lastTimeStamp = time.perf_counter()
@property
def current(self):
return random.gauss(14, 0.5)
@property
def voltage(self)... |
# Module 'ntpath' -- common operations on WinNT/Win95 pathnames
"""Common pathname manipulations, WindowsNT/95 version.
Instead of importing this module directly, import os and refer to this
module as os.path.
"""
import os
import sys
import stat
import genericpath
import warnings
from genericpath import *
__all__ ... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.compat.tests.mock import patch
from ansible.modules.network.onyx import onyx_lldp_interface
from units.modules.utils import set_module_args
from .onyx_module import TestOnyxModule, load_fixture
class TestOnyxLldpInte... |
"""Tests the --help flag of Google C++ Testing Framework.
SYNOPSIS
gtest_help_test.py --build_dir=BUILD/DIR
# where BUILD/DIR contains the built gtest_help_test_ file.
gtest_help_test.py
"""
__author__ = '<EMAIL> (Zhanyong Wan)'
import os
import re
import gtest_test_utils
IS_LINUX = os.name ... |
import sqlalchemy as sql
def upgrade(migrate_engine):
meta = sql.MetaData()
meta.bind = migrate_engine
failed_auth_count = sql.Column('failed_auth_count', sql.Integer,
nullable=True)
failed_auth_at = sql.Column('failed_auth_at', sql.DateTime(),
... |
from scipy import stats
import matplotlib.pyplot as plt
nsample = 100
np.random.seed(7654321)
# A t distribution with small degrees of freedom:
ax1 = plt.subplot(221)
x = stats.t.rvs(3, size=nsample)
res = stats.probplot(x, plot=plt)
# A t distribution with larger degrees of freedom:
ax2 = plt.subplot(222)
x = stat... |
from boto.regioninfo import RegionInfo, get_regions
def regions():
"""
Get all available regions for the AWS Elastic Beanstalk service.
:rtype: list
:return: A list of :class:`boto.regioninfo.RegionInfo`
"""
import boto.beanstalk.layer1
return get_regions(
'elasticbeanstalk',
... |
"""
This file is part of ntv2generator.
ntv2generator 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.
ntv2generato... |
from django.conf import settings
from django.db import models
from meetup.api import MeetupClient
import datetime
STATUSES = [(s, s) for s in ('past','pending','upcoming')]
API_KEY = getattr(settings, 'MEETUP_KEY', None)
class Account(models.Model):
key = models.CharField(max_length=128)
description = models.... |
'''Path selection function select a face or faces, two edges, etc to get a dictionary with what was selected in order '''
import FreeCAD,FreeCADGui
import Part
from FreeCAD import Vector
def equals(p1,p2):
'''returns True if vertexes have same coordinates within precision amount of digits '''
precision = 12 #... |
#!/usr/bin/env python
# -*- coding: ascii -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
#
"""Simple test suite using unittest.
By clach04 (Chris Clark).
Calling:
python test/testsuite.py
or
cd test
./testsuite.py
Could use any unitest compatible test runner (nose, etc.)
Aims to test for regres... |
"""Zenodo application factories."""
from __future__ import absolute_import
import os
import sys
from invenio_base.app import create_app_factory
from invenio_base.wsgi import create_wsgi_factory, wsgi_proxyfix
from invenio_config import create_conf_loader
from invenio_files_rest.app import Flask
from statsd import St... |
#!/router/bin/python
import sys
import site
import string
import random
import os
try:
import pwd
except ImportError:
import getpass
pwd = None
using_python_3 = True if sys.version_info.major == 3 else False
def user_input():
if using_python_3:
return input()
else:
# using pytho... |
from nupic.frameworks.opf.expdescriptionhelpers import importBaseDescription
# the sub-experiment configuration
config ={
'modelParams' : {'sensorParams': {'encoders': {u'c0_timeOfDay': None, u'c0_dayOfWeek': None, u'c1': {'name': 'c1', 'clipInput': True, 'n': 275, 'fieldname': 'c1', 'w': 21, 'type': 'AdaptiveScalar... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
module: vcenter_license
short_description: Manage VMware vCenter license... |
from iaasgw.exception.iaasException import IaasException
from iaasgw.log.log import IaasLogger
from iaasgw.utils.propertyUtil import getImage, getScriptProperty, getDnsProperty, getPuppetProperty, getVpnProperty
from iaasgw.utils.stringUtils import isEmpty, isNotEmpty, startsWithIgnoreCase
class CloudStackInstanceContr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" @todo add docstring """
# ### imports ###
from __future__ import (
absolute_import,
division,
print_function # ,
# unicode_literals
)
import fnmatch
import io
import json
import re
import os
# import pprint
import subprocess
import sys
OSIS = [
... |
from openerp.osv import fields, osv
class mrp_price(osv.osv_memory):
_name = 'mrp.product_price'
_description = 'Product Price'
_columns = {
'number': fields.integer('Quantity', required=True, help="Specify quantity of products to produce or buy. Report of Cost structure will be displayed base on t... |
import constants
class BucketFull(Exception):
""" Raised when the bucket is full """
class KBucket(object):
""" Description - later
"""
def __init__(self, rangeMin, rangeMax):
"""
@param rangeMin: The lower boundary for the range in the 160-bit ID
space covere... |
import BaseHTTPServer
import imp
import logging
import multiprocessing
import optparse
import os
import SimpleHTTPServer # pylint: disable=W0611
import socket
import sys
import time
import urlparse
if sys.version_info < (2, 6, 0):
sys.stderr.write("python 2.6 or later is required run this script\n")
sys.exit(1)
... |
import os
from telemetry.core import util
# TODO(dtu): Move these functions from core.util to here.
GetBaseDir = util.GetBaseDir
GetTelemetryDir = util.GetTelemetryDir
GetUnittestDataDir = util.GetUnittestDataDir
GetChromiumSrcDir = util.GetChromiumSrcDir
AddDirToPythonPath = util.AddDirToPythonPath
GetBuildDirector... |
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... |
from mrjob.job import MRJob
from mrjob.step import MRStep
import string
import sys
class MRGrados(MRJob):
SORT_VALUES = True
def mapper(self, _, line):
line_stripped = line.translate(string.maketrans("",""), '"')
line_split = line_stripped.split(',') #split by the comma
sorted... |
#!/Library/Frameworks/Python.framework/Versions/2.7/bin/python
# USAGE:
# PREAMBLE:
import numpy as np
import MDAnalysis
import sys
import os
import matplotlib.pyplot as plt
traj_file ='%s' %(sys.argv[1])
# ----------------------------------------
# VARIABLE DECLARATION
base1 = 1
nbases = 15
#nbases = 3
#Nsteps ... |
import argparse
import json
import os
import sys
import common
def main(argv):
parser = argparse.ArgumentParser()
parser.add_argument('--output', required=True)
parser.add_argument('args', nargs=argparse.REMAINDER)
args = parser.parse_args(argv)
passthrough_args = args.args
if passthrough_args[0] == '-... |
#!/usr/bin/env python
import numpy
import random
import logging
import itertools
import collections
from friendloc.base import gob
from friendloc.base.models import Edges, User, Tweets
from friendloc.base import gisgraphy, twitter, utils
NEBR_KEYS = ['rfriends','just_followers','just_friends','just_mentioned']
@go... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Performs a clustering run with a number of clusters and a given mask,
and creates graphs of the corresponding DBI, pSF, SSR/SST, and RMSD
values.
These faciliate the choice of cluster numbers and improve the clustering
process by allowing to pick the number of cluste... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.openstack im... |
# -*- coding: utf-8 -*-
from neural_networks.boltzmann_machines.generative_rbm import GenRBM
from neural_networks.perceptrons.mlp import MLP
from utilities.data_utils import make_batches
class DBN():
''' Deep belief network aka stacked boltzmann machines'''
def __init__(self, layer_definitions):
se... |
import threading
class PlanningData:
def __init__(self, planning_pb=None):
self.path_lock = threading.Lock()
self.path_param_lock = threading.Lock()
self.planning_pb = planning_pb
self.path_x = []
self.path_y = []
self.relative_time = []
self.speed = []
... |
"""
Form Widget classes specific to the Django admin site.
"""
import django.utils.copycompat as copy
from django import forms
from django.forms.widgets import RadioFieldRenderer
from django.forms.util import flatatt
from django.utils.html import escape
from django.utils.text import truncate_words
from django.utils.t... |
#!/usr/bin/python
# coding:utf-8
from bs4 import BeautifulSoup
import re
import os
import sys
import urllib
import time
import random
import time
#################### 配置开始#################
# 版面配置
# 支持爬多个版面,取消下面的注释即可
# 二手房
# board = 'OurHouse'
# 二手市场主版
# board = 'SecondMarket'
# 租房
boards = ['OurEstate', 'PolicyEst... |
# -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
PROVINCE_CHOICES = (
('01', _('Araba')),
('02', _('Albacete')),
('03', _('Alacant')),
('04', _('Almeria')),
('05', _('Avila')),
('06', _('Badajoz')),
('07', _('Illes Balears')),
('08', _('Barcelona')),
(... |
"""
Copyright (c) 2003-2007 Gustavo Niemeyer <<EMAIL>>
This module offers extensions to the standard python 2.3+
datetime module.
"""
__author__ = "Gustavo Niemeyer <<EMAIL>>"
__license__ = "PSF License"
import datetime
__all__ = ["easter", "EASTER_JULIAN", "EASTER_ORTHODOX", "EASTER_WESTERN"]
EASTER_JULIAN = 1
... |
import time
import datetime
from django import forms
from django.forms.util import ErrorDict
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.utils.crypto import salted_hmac, constant_time_compare
from django.utils.encoding import force_unicode
from django.utils.t... |
import unittest
import numpy as np
import nest
nest.set_verbosity('M_WARNING')
HAVE_OPENMP = nest.ll_api.sli_func("is_threaded")
class TestConnectArrays(unittest.TestCase):
non_unique = np.array([1, 1, 3, 5, 4, 5, 9, 7, 2, 8], dtype=np.uint64)
def setUp(self):
nest.ResetKernel()
def test_con... |
# -*- coding: utf-8 -*-
import os
from lutris import settings
from lutris.runners.runner import Runner
class o2em(Runner):
"""Magnavox Oyssey² Emulator"""
human_name = "O2EM"
package = "o2em"
executable = "o2em"
platform = "Magnavox Odyssey 2, Phillips Videopac+"
tarballs = {
'i386': ... |
import six
from syn.five import xrange
from nose.tools import assert_raises
from syn.type.a import (Type, ValuesType, MultiType, TypeType, AnyType,
TypeExtension, Set, Schema)
from syn.base_utils import is_hashable, feq
from syn.base_utils import ngzwarn, on_error, elog
from syn.globals import ... |
from oslo_config import cfg
from oslo_log import log as logging
import stevedore.driver
import stevedore.extension
from nova.i18n import _LE
CONF = cfg.CONF
LOG = logging.getLogger(__name__)
def load_transfer_modules():
module_dictionary = {}
ex = stevedore.extension.ExtensionManager('nova.image.download.... |
import mock
from mock import MagicMock
from nose.tools import set_trace
from library import cl_license
from asserts import assert_equals
from datetime import date, datetime
def mod_args_generator(values, *args):
def mod_args(args):
return values[args]
return mod_args
@mock.patch('library.cl_license.A... |
from Components.VariableText import VariableText
from Components.Sensors import sensors
from Tools.HardwareInfo import HardwareInfo
from enigma import eLabel
from Renderer import Renderer
from os import popen
class DMCHDMaxTemp(Renderer, VariableText):
def __init__(self):
Renderer.__init__(self)
VariableText.__in... |
"""
This module defines standalone schema constraint classes.
"""
from sqlalchemy import schema
from migrate.exceptions import *
class ConstraintChangeset(object):
"""Base class for Constraint classes."""
def _normalize_columns(self, cols, table_name=False):
"""Given: column objects or names; retu... |
"""Export utilities."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.framework import deprecated
from tensorflow.contrib.framework.python.ops import variables as contrib_variables
from tensorflow.contrib.session_bundle import expo... |
"""Generic add-on view factories"""
# -*- coding: utf-8 -*-
import httplib as http
from flask import request
from framework.exceptions import HTTPError, PermissionsError
from framework.auth.decorators import must_be_logged_in
from osf.models import ExternalAccount
from osf.utils import permissions
from website.proj... |
from __future__ import unicode_literals
import base64
import logging
import string
from datetime import datetime, timedelta
from django.conf import settings
from django.contrib.sessions.exceptions import SuspiciousSession
from django.core.exceptions import SuspiciousOperation
from django.utils import timezone
from dj... |
"""
Parser and utilities for the smart 'if' tag
"""
import warnings
from django.utils.deprecation import RemovedInDjango110Warning
# Using a simple top down parser, as described here:
# http://effbot.org/zone/simple-top-down-parsing.htm.
# 'led' = left denotation
# 'nud' = null denotation
# 'bp' = binding power (... |
import time
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
class Timer(object):
def __init__(self, name='elapsed time', logger=None, print_result=False):
self.verbose =... |
# coding: utf-8
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'hgh.views.home', name='home'),
# url(r'^hgh/', include('hgh.foo.u... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.