content stringlengths 4 20k |
|---|
from djblets.auth.util import login_required
from djblets.siteconfig.models import SiteConfiguration
from djblets.util.decorators import simple_decorator
from reviewboard.accounts.models import Profile
@simple_decorator
def check_login_required(view_func):
"""
A decorator that checks whether login is require... |
# useful methods to work with cairo in TamTam
from gi.repository import Gdk
def gdk_color_to_cairo(color):
return (color.red / 65536.0, color.green / 65536.0, color.blue / 65536.0)
def get_gdk_color(str_color):
result, color = Gdk.Color.parse(str_color)
return color
def draw_round_rect(ctx, x, y, width, ... |
import functools, logging
from .optransform import op_normalize, op_apply, op_compose, op_invert, op_transform_x
logger = logging.getLogger('Sublime Collaboration')
class CollabDoc():
def __init__(self, connection, name, snapshot=None):
self.connection = connection
self.name = name
self.ve... |
import os
import unittest
import pysal
import numpy as np
class Testuser(unittest.TestCase):
def setUp(self):
self.wq = pysal.queen_from_shapefile(
pysal.examples.get_path("columbus.shp"))
self.wr = pysal.rook_from_shapefile(
pysal.examples.get_path("columbus.shp"))
de... |
from django.db import models
from django.contrib.contenttypes.models import ContentType
from lino.api import dd
from lino.core.gfks import GenericForeignKey
class Member(dd.Model):
name = models.CharField(max_length=200)
email = models.EmailField(max_length=200, blank=True)
def __str__(self):
re... |
from wtforms import BooleanField
from wtforms import SelectField
from wtforms import StringField
from wtforms import SubmitField
from wtforms import TextAreaField
from wtforms.validators import DataRequired
from wtforms.validators import Length
from wtforms.validators import Optional
from wtforms.validators import Rege... |
"""Web interface to L{twisted.words}.
I provide the user interface for L{words Participant
<twisted.words.service.Participant>} account creation.
"""
import time
#Twisted imports
from twisted.web import html, server, error, widgets
from twisted.cred import identity
from twisted.persisted import styles
#Sibling impo... |
from ircbot.persist import Persistent
from time import time
from datetime import datetime
import re
from .helpers import private_api, ApiError
from ircbot.plugin import BotPlugin
import aiohttp
# Thank you http://stackoverflow.com/users/1622925/bruno-de-lima for the Regex
# http://stackoverflow.com/a/31711517 and http... |
"""
This module houses the ctypes initialization procedures, as well
as the notice and error handler function callbacks (get called
when an error occurs in GEOS).
This module also houses GEOS Pointer utilities, including
get_pointer_arr(), and GEOM_PTR.
"""
import logging
import os
import re
from ctypes import CD... |
import unittest
from test import test_support
from contextlib import closing
import gc
import pickle
import select
import signal
import subprocess
import traceback
import sys, os, time, errno
if sys.platform in ('os2', 'riscos'):
raise unittest.SkipTest("Can't test signal on %s" % sys.platform)
cl... |
# -*- encoding: utf-8 -*-
"""
stonemason.formatbundle
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Bundles map/tile format definition and conversion.
"""
__author__ = 'kotaimen'
__date__ = '2/17/15'
from .maptype import MapType
from .tileformat import TileFormat
from .mapwriter import find_writer, MapWriter
clas... |
import unittest
import os
# internal modules:
from . import cli
class TestCLISearch(unittest.TestCase):
def test_bothModule(self):
stdout = self.runCheckCommand(['search', 'polyfill'])
self.assertTrue(stdout.find('compiler-polyfill') != -1)
def test_bothTarget(self):
stdout = self.run... |
# -*- coding: utf-8 -*-
import random
import uuid
from sqlalchemy import text
from sqlalchemy.exc import NoSuchColumnError
from db import db
from journalist_app import create_app
from .helpers import random_bool, random_chars, random_datetime, bool_or_none
random.seed('ᕕ( ᐛ )ᕗ')
class UpgradeTester():
'''Thi... |
"""
Scheduler Service
"""
import eventlet
from oslo_config import cfg
from oslo_log import log as logging
import oslo_messaging as messaging
from oslo_utils import excutils
from oslo_utils import importutils
from cinder import context
from cinder import db
from cinder import exception
from cinder import flow_utils
fr... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
for run in orm['job_runner.Run'].objects.all():
if run.return_log:
orm['job_runner.RunLog'].o... |
import base64
import configparser
import json
import os
import urllib
import future
import asyncio
import pandas as pd
import requests
import datetime
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from QUANTAXIS.QAEngine.QAEvent im... |
"""
Quantum base exception handling.
"""
from quantum.openstack.common.exception import Error
from quantum.openstack.common.exception import OpenstackException
class QuantumException(OpenstackException):
"""Base Quantum Exception
To correctly use this class, inherit from it and define
a 'message' proper... |
from oslo_config import cfg
from neutron.api import extensions
from neutron.api.v2 import base
from neutron import manager
from neutron.plugins.common import constants
from neutron import quota
def build_plural_mappings(special_mappings, resource_map):
"""Create plural to singular mapping for all resources.
... |
import shutil
import re
from os import path, listdir
from time import sleep
from datetime import datetime
from django.test import TestCase
from django.core import mail
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from expecter import expect
from django_outbox.outbox import Out... |
"""Module containing some of the logic for our VCS installation logic."""
from flake8 import exceptions as exc
from flake8.main import git
from flake8.main import mercurial
# NOTE(sigmavirus24): In the future, we may allow for VCS hooks to be defined
# as plugins, e.g., adding a flake8.vcs entry-point. In that case, ... |
from boto.s3.connection import S3Connection
from boto.s3.key import Key
import time, os
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from formdata.utils.dump_utils import dump_all_sked
from summary_data.utils.update_utils import set_update
AWS_ACCESS_KEY_ID = g... |
from glue import custom_viewer
from matplotlib.colors import LogNorm
from matplotlib.patches import Circle, Rectangle, Arc
from matplotlib.lines import Line2D
bball = custom_viewer('Shot Plot',
x='att(x)',
y='att(y)')
@bball.plot_data
def show_hexbin(axes, x, y):
axes... |
{
'name': 'Maniland PO Report',
'version': '1.0',
'category': 'Purchase',
'author': 'OpenERP SA',
'website': 'http://www.openerp.com',
'depends': ['purchase'],
'data': [
'maniland_report.xml',
'mainland_po_view.xml',
],
'demo': [],
'test': [],
... |
""" Represents document model in htl.
"""
import json
from json import JSONEncoder
import zlib
__all__ = ['HTLDoc', 'HTLPage', 'HTLArea', 'HTLPar', 'HTLLine', 'HTLWord',
'HTLStub', 'dump', 'dumps']
class HTLDoc(object):
def __init__(self, doc_name, pages, lang=None, dc_data=None):
self._doc_n... |
"""
Parser for the environment markers micro-language defined in PEP 508.
"""
# Note: In PEP 345, the micro-language was Python compatible, so the ast
# module could be used to parse it. However, PEP 508 introduced operators such
# as ~= and === which aren't in Python, necessitating a different approach.
impo... |
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.translation import ugettext
from django.utils.translation import ugettext_lazy as _
import logging
import re
from readthedocs.projects.models import Project
from .managers import RedirectManager... |
import config
from functions import is_registered
def join(socket, components): # !join <#channel>+
'''Returns a string for joining the given channel(s)
Joins a list of channels, only if the sender is an owner
'''
response = ''
join_command = components['arguments'].split('!join ') # notice the s... |
try:
from pysqlite2 import dbapi2 as sqlite3
except ImportError:
import sqlite3
class DBWrapper(object):
"""Database connection wrapper."""
def __init__(self, db):
self.conn = sqlite3.connect(db, check_same_thread=False)
self.conn.execute(""" pragma case_sensitive_like = on """)
... |
# Py.test
import pytest
# pytestmark = pytest.mark.nondestructive
def test_invalid_creds(public_api_v2_class):
with pytest.raises(TypeError):
public_api_v2_class(False)
with pytest.raises(ValueError):
public_api_v2_class(dict())
def test_auth_with_company_id_and_psk(public_api_v2):
resu... |
SCHEMA = {
"type": "object",
"properties": {
"resources": {"$ref": "#/resources"},
"key_name": {"type": "string"},
# everything is optionnal
"image": {"type": "string"},
"user": {"type": "string"},
"allocation_pool": {"$ref": "#/os_allocation_pool"},
"conf... |
#!/usr/bin/env python
"""
Copyright (c) 2006-2016 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
from lib.core.enums import DBMS
from lib.core.settings import FIREBIRD_SYSTEM_DBS
from lib.core.unescaper import unescaper
from plugins.dbms.firebird.enumeration import Enumer... |
from oslo.config import cfg
from nova.openstack.common import log as logging
from nova.scheduler import filters
LOG = logging.getLogger(__name__)
max_instances_per_host_opt = cfg.IntOpt("max_instances_per_host",
default=50,
help="Ignore hosts that have too many instances")
CONF = cfg.CONF
CONF.regis... |
import argparse
import socket
import random
import capnp
import brain_capnp
import time
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, LSTM, Dropout, Convolution1D, MaxPooling1D, GlobalMaxPooling1D, Embedding, Flatten
from keras.optimizers import SGD, Nadam, Adam, Adadelta
imp... |
import gdb
from tailq import TailQueue
from thread import Thread
import utils
class SleepQueue(object):
__metaclass__ = utils.GdbStructMeta
__ctype__ = 'struct sleepq'
def __init__(self, addr):
self._obj = gdb.parse_and_eval("sleepq_lookup((void *)%d)" % addr)
def __str__(self):
if s... |
import mimetypes
import os.path
from django.conf import settings
from django.core import mail
from django.core.files.storage import default_storage as storage
from django.core.mail import EmailMessage
from django.template import Context as TemplateContext
from django.utils import translation
import mock
from olympia... |
import os
from app import (
app,
ServiceUnavailable,
SecurityError
)
from flask import (
redirect,
flash,
url_for,
request,
session,
render_template,
jsonify,
send_from_directory
)
from app.models import (
Download,
Parsers
)
from app.forms import (
DownloadForm,
LocationForm
)
from datetime import ... |
#!/usr/bin/python
# This is a crazy hack to convert Weka's arff into caffe's leveldb
import leveldb
import caffe_pb2
import struct
def read(filename):
fl = open(filename)
label_index = 0
label_found = False
line = fl.readline()
while line:
if line.startswith("@data"):
break
... |
from tempest.test_discover import plugins
from tempest.tests import base
from tempest.tests import fake_tempest_plugin as fake_plugin
class TestPluginDiscovery(base.TestCase):
def test_load_tests_with_one_plugin(self):
# we can't mock stevedore since it's a singleton and already executed
# during ... |
#!/usr/bin/python3
from troposphere import Ref, Join, cloudwatch
from troposphere.sns import Topic, Subscription
class SNS(object):
def __init__(self, template):
"""
AWS: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sns-topic.html
Troposphere: https://githu... |
# -*- coding: utf-8 -*-
"""
docker_registry.drivers.s3
~~~~~~~~~~~~~~~~~~~~~~~~~~
This is a s3 based driver.
"""
import gevent.monkey
gevent.monkey.patch_all()
import docker_registry.core.boto as coreboto
# from docker_registry.core import exceptions
from docker_registry.core import compat
from docker_registry.core... |
"""
A collections of builtin avro functions
"""
from pyspark import since, SparkContext
from pyspark.rdd import ignore_unicode_prefix
from pyspark.sql.column import Column, _to_java_column
from pyspark.util import _print_missing_jar
@ignore_unicode_prefix
@since(3.0)
def from_avro(data, jsonFormatSchema, options={}... |
#!/usr/bin/env python
"""
Reorder the atoms in the Angles section of a data file to make sure that
atoms have a "canonical order" (for example the first atom has a lower
id than the last atom, for angle and dihedral interactions.
(This helps us detect potential problems like dupicate Angle interactions.)
... |
"""
Course discovery page.
"""
from . import BASE_URL
from bok_choy.page_object import PageObject
class CourseDiscoveryPage(PageObject):
"""
Find courses page (main page of the LMS).
"""
url = BASE_URL + "/courses"
form = "#discovery-form"
def is_browser_on_page(self):
return "Cours... |
#!/usr/bin/env python
"""
Create generic LPU and simple pulse input signal.
"""
from itertools import product
import sys
import numpy as np
import h5py
import networkx as nx
def create_lpu(file_name, lpu_name, N_sensory, N_local, N_proj):
"""
Create a generic LPU.
Creates a GEXF file containing the neu... |
# -*- coding: utf-8 -*-
import time
from django.db import connection, transaction
from sklcc.views import set_randhex
class MonitorMiddleware(object):
def process_view(self,request,view_func,view_args,view_kwargs):
ip = request.META.get('REMOTE_ADDR','unknown')
content_length = request.META.get('CO... |
from PIL import Image, ImageFile, _binary
__version__ = "0.1"
#
# read MSP files
i16 = _binary.i16le
def _accept(prefix):
return prefix[:4] in [b"DanM", b"LinS"]
##
# Image plugin for Windows MSP images. This plugin supports both
# uncompressed (Windows 1.0).
class MspImageFile(ImageFile.ImageFile):
... |
from toontown.suit import DistributedFactorySuit
from toontown.suit.Suit import *
from direct.directnotify import DirectNotifyGlobal
from direct.actor import Actor
from otp.avatar import Avatar
import SuitDNA
from toontown.toonbase import ToontownGlobals
from panda3d.core import *
from panda3d.direct import *
from toon... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This file is part of XBMC Mega Pack Addon.
Copyright (C) 2014 Wolverine (<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, eith... |
import AlGDock.BindingPMF_plots
import os, shutil, glob
self = AlGDock.BindingPMF_plots.BPMF_plots(\
dir_dock='dock', dir_cool='cool',\
ligand_tarball='prmtopcrd/ligand.tar.gz', \
ligand_database='ligand.db', \
forcefield='prmtopcrd/gaff.dat', \
ligand_prmtop='ligand.prmtop', \
ligand_inpcrd='ligand.trans.... |
import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from java.util import Vector
def addTemplate(core):
mobileTemplate = MobileTemplate()
mobi... |
import os
import re
from pypers.core.step import CmdLineStep
class AlignMem(CmdLineStep):
spec = {
"version": "0.7.6a",
"descr": [
"Aligns 70bp-1Mbp query sequences with the BWA-MEM algorithm."
],
"args":
{
"inputs": [
{
... |
from openmc.arithmetic import *
from openmc.cell import *
from openmc.checkvalue import *
from openmc.mesh import *
from openmc.element import *
from openmc.geometry import *
from openmc.nuclide import *
from openmc.macroscopic import *
from openmc.material import *
from openmc.plots import *
from openmc.region import ... |
from urllib import robotparser
import requests
def download(url, num_tries=3, user_agent=None, proxies=None):
"""
下载给定的URL并返回页面内容
:param url: {str}
:param num_tries=3: {int}
:param user_agent=None: {str}
:param proxies=None: {dict}
"""
print(f'Download: {url} ...')
... |
# -*- coding: UTF-8 -*-
"""
Kodi urlresolver plugin
Copyright (C) 2017 zlootec
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 op... |
{
"name" : "El Nogal - Product Samples Management",
"version" : "1.0",
"author" : "Pexego",
"website" : "http://www.pexego.es",
"category" : "Enterprise Specific Modules",
"description": """Product Samples Management in Openerp""",
"depends" : [
'product',
'sale',
'st... |
from PyQt4.QtGui import *
from electrum_rby.plugins import BasePlugin, hook
from electrum_rby.i18n import _
import random
class Plugin(BasePlugin):
@hook
def init_qt(self, gui):
self.gui = gui
self.vkb = None
self.vkb_index = 0
@hook
def password_dialog(self, pw, grid, pos):
... |
"""Tests for samba.kcc.graph"""
import samba
import samba.tests
from samba.kcc.graph import *
import itertools
def ntdsconn_schedule(times):
if times is None:
return None
from samba.dcerpc import drsblobs
schedule = drsblobs.schedule()
schedule.size = 188
schedule.bandwidth = 0
sched... |
import _plotly_utils.basevalidators
class FontValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(
self, plotly_name="font", parent_name="bar.legendgrouptitle", **kwargs
):
super(FontValidator, self).__init__(
plotly_name=plotly_name,
parent_name=par... |
#/u/GoldenSights
import praw # simple interface to the reddit API, also handles rate limiting of requests
import time
import sqlite3
'''USER CONFIGURATION'''
USERNAME = ""
#This is the bot's Username. In order to send mail, he must have some amount of Karma.
PASSWORD = ""
#This is the bot's Password.
USERAGENT = "... |
from __future__ import unicode_literals
from difflib import SequenceMatcher
from reviewboard.diffviewer.differ import Differ
class SMDiffer(Differ):
"""
Wrapper around SequenceMatcher that works around bugs in how it does
its matching.
"""
def __init__(self, *args, **kwargs):
super(SMDif... |
from setuptools import setup
from setuptools import Command
class TestCommand(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
from django.conf import settings
settings.configure(
DATABASES={
... |
"""Built-in metrics.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import six
from tensorflow.python.keras._impl.keras import backend as K
from tensorflow.python.keras._impl.keras.losses import binary_crossentropy
from tensorflow.python.keras._impl.ke... |
#!/usr/bin/env python
# -*- coding: utf 8 -*-
"""
Helper functions for the striplog package.
"""
from . import defaults
def hex_to_name(hexx):
"""
Convert hex to a color name, using matplotlib's colour names.
Args:
hexx (str): A hexadecimal colour, starting with '#'.
Returns:
str: ... |
# -*- encoding: UTF-8 -*-
import sys
import almath
from naoqi import ALProxy
import rospy
import time
class NaoNode:
def __init__(self):
robotIP = '192.168.0.100'
port = 9559
try:
self.motionProxy = ALProxy("ALMotion", robotIP, port)
self.audioProxy = ALProxy("AL... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'GCWiiManager.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(... |
import datetime
import unittest
class DocumentSchemaTestCase(unittest.TestCase):
def test_datetime_fields_missing(self):
cstruct = {
'title': 'required title',
}
from ..schemata import document_schema
appstruct = document_schema.bind().deserialize(cstruct)
... |
# -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from opensearchsdk.service import BaseService
from opensearchsdk import set_stream_logger
from opensearchsdk.config import Config
__author__ = 'barycenter'
class ReferenceMgr(BaseService):
"""
API document seems not completed
"""
BA... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''Deprecation utilities'''
import inspect
import warnings
import six
from decorator import decorator
import numpy as np
from .exceptions import PescadorError
class Deprecated(object):
'''A dummy class to catch usage of deprecated variable names'''
def __rep... |
from __future__ import print_function, division
import os,unittest,numpy as np
from pyscf.nao import gw as gw_c
class KnowValues(unittest.TestCase):
def test_rescf(self):
""" Hartree-Fock than G0W0 N2 example is marked with level-ordering change """
dname = os.path.dirname(os.path.abspath(__file__))
... |
"""
Basic questions for Freebase.
"""
from refo import Question, Plus
from dsl import DefinitionOf, NameOf, LocationOf
from quepy.dsl import HasKeyword
from quepy.parsing import QuestionTemplate, Particle, Lemma, Pos, Lemmas
class Thing(Particle):
regex = Plus(Question(Pos("JJ")) + (Pos("NN") | Pos("NNP") | Pos(... |
#!/usr/bin/env python
from mpi4py import MPI
from subprocess import call
import sys
"""
This script will create 'nprocs' parallel instances of
CalcDisc-vs-Exposure.py and calculate the significance
for a different exposure on each instance.
For a given mass and ensemble, there are 32 exposures to
calculate for, so t... |
from time import ctime
from PyQt4.QtCore import Qt, QAbstractTableModel, QModelIndex, QVariant
from profit.lib import Signals
class MessagesTableModel(QAbstractTableModel):
""" Data model for session messages.
"""
columnTitles = ['Index', 'Time', 'Type', 'Fields']
sync = True
def __init__(self, ... |
import builtins
import linecache
import re
import os
from artiq import __artiq_dir__ as artiq_dir
from artiq.coredevice.runtime import source_loader
ZeroDivisionError = builtins.ZeroDivisionError
ValueError = builtins.ValueError
IndexError = builtins.IndexError
class CoreException:
"""Information about an exce... |
from pathlib import Path
from keras.applications import VGG16
from keras.models import Model
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import AxesGrid
from tools.datasets.urban_tribes import load_images
def plot_filter(image_path, layer_name, output_dir):
base_model = VGG16(weights='imagenet'... |
"""Provide a widget to record user satisfaction with course content."""
__author__ = 'John Orr (<EMAIL>)'
import os
import urlparse
import jinja2
import appengine_config
from common import schema_fields
from common import tags
from controllers import lessons
from controllers import utils
from models import courses
... |
from copy import deepcopy as copy
from button import ButtonTemplate
ButtonTemplate.get_buttons = lambda self: self.template['attachment']['payload']['buttons']
TITLE_CHARACTER_LIMIT = 80
SUBTITLE_CHARACTER_LIMIT = 80
BUTTON_TITLE_CHARACTER_LIMIT = 20
BUTTON_LIMIT = 3
ELEMENTS_LIMIT = 10
template = {
'template_t... |
"""SMTP email backend class."""
import smtplib
import socket
import ssl
import threading
from django.conf import settings
from django.core.mail.backends.base import BaseEmailBackend
from django.core.mail.message import sanitize_address
from django.core.mail.utils import DNS_NAME
class EmailBackend(BaseEmailBackend):... |
"""
Debug Toolbar middleware
"""
from __future__ import absolute_import, unicode_literals
import re
import threading
from django.conf import settings
from django.utils import six
from django.utils.encoding import force_text
from django.utils.functional import cached_property
from django.utils.module_loading import i... |
from operator import itemgetter
import gtk
from sqlalchemy import select, Column, Unicode, String, Integer, ForeignKey
from sqlalchemy.orm import object_session, relation, backref
import bauble.db as db
def get_species_in_geography(geo):
"""
Return all the Species that have distribution in geo
"""
... |
"""Look up type information for typedefs of same name at different lexical scope and check for correct display."""
from __future__ import print_function
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TypedefTestCase(TestBase):
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import ray
test_values = [1, 1.0, "test", b"test", (0, 1), [0, 1], {0: 1}]
def test_basic_task_api(ray_start_regular):
# Test a simple function.
@ray.remote
def f_simple():
return 1
... |
# encoding: UTF-8
'''
本文件中包含了CTA模块中用到的一些基础设置、类和常量等。
'''
from __future__ import division
# 把vn.trader根目录添加到python环境变量中
import sys
sys.path.append('..')
# 常量定义
# CTA引擎中涉及到的交易方向类型
CTAORDER_BUY = u'买开'
CTAORDER_SELL = u'卖平'
CTAORDER_SHORT = u'卖开'
CTAORDER_COVER = u'买平'
# 本地停止单状态
STOPORDER_WAITING = u'等待中'
STOPORDER_... |
#! /usr/bin/env python
# -*- python -*-
from Tkinter import *
import ttk
from tkFileDialog import askopenfilename, askdirectory
from tkMessageBox import *
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.compat import range
from openpyxl.cell import coordinate_from_string, \
column_... |
import unittest
from hamcrest.core import assert_that
from hamcrest.core.core.is_ import is_
from web import uri
class URITest(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_scheme(self):
google = uri("http://www.google.com")
self.assertEqu... |
import sys
import os
import logging
from tornado import web
from tornado import httpserver
from tornado import ioloop
from tornado import gen
from memsql_framework.util.super_thread import SuperThread
from memsql_framework.ui.web_handler import single_file_handler
from memsql_framework.ui.api_handler import ApiHandle... |
"""Classes supporting configuration property editor and REST operations."""
__author__ = 'Pavel Simakov (<EMAIL>)'
import cgi
import json
import urllib
from controllers.utils import BaseRESTHandler
from controllers.utils import XsrfTokenManager
from models import config
from models import models
from models import ro... |
"""
Sensor from an SQL Query.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.sql/
"""
import decimal
import datetime
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const imp... |
from oslo_config import cfg
from neutron._i18n import _
security_group_opts = [
cfg.StrOpt(
'firewall_driver',
help=_('Driver for security groups firewall in the L2 agent')),
cfg.BoolOpt(
'enable_security_group',
default=True,
help=_(
'Controls whether the ... |
import numpy as np
import matplotlib.pyplot as plt
from stimuli import events2neural
from harmonic import *
from cond_path import *
from list_cond import *
from convolve import *
import numpy.linalg as npl
from matrix_image import *
from path_bold import *
import nibabel as nib
# Load the sub001 task001_run001 dat... |
import account_reversal
import wizard |
import re
import subprocess
gitLogOneLine = re.compile(r'^(?P<message>.*)$')
titleWithEndingPunct = re.compile(r'^(.*)[\.!?]$')
pastTenseWords = [
'closed',
'corrected',
'changed',
'enhanced',
'fixed',
'installed',
'implemented',
'improved',
'moved',
'merged',
'refactored',
... |
from __future__ import division, absolute_import
# System Imports
import sys
from twisted.trial import unittest
try:
import cPickle as pickle
except ImportError:
import pickle
import io
try:
from cStringIO import StringIO as _oldStyleCStringIO
except ImportError:
skipStringIO = "No cStringIO availa... |
"""This is the Bokeh charts interface. It gives you a high level API
to build complex plot is a simple way.
This is the Area builder which lets you build your Area charts
just passing the arguments to the Chart class and calling the proper
functions.
"""
#---------------------------------------------------------------... |
"""
Defines the BridgeDevice class.
Copyright 2017 Red Hat, Inc.
Licensed under the GNU General Public License, version 2 as
published by the Free Software Foundation; see COPYING for details.
"""
__author__ = """
<EMAIL> (Ondrej Lichtner)
"""
from lnst.Common.ExecCmd import exec_cmd
from lnst.Devices.MasterDevice i... |
# encoding: utf-8
"""
http.py
Created by Thomas Mangin on 2011-12-02.
Copyright (c) 2011-2013 Exa Networks. All rights reserved.
"""
# destination = re.compile("(GET|POST|PUT|HEAD|DELETE|OPTIONS|TRACE|CONNECT)\s+(http://[^/]*|)(/?[^ \r]*)\s+(HTTP/.*\r?\nHost\s*:\s*)([^\r]*)(|\r?\n)", re.IGNORECASE)
# x_forwarded_for... |
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... |
"""abydos.fingerprint.
The fingerprint package implements string fingerprints such as:
- Basic fingerprinters originating in `OpenRefine <http://openrefine.org>`:
- String (:py:class:`.String`)
- Phonetic, which applies a phonetic algorithm and returns the string
fingerprint of the resu... |
from sos.plugins import Plugin, RedHatPlugin
import re
from glob import glob
class Cluster(Plugin, RedHatPlugin):
"""cluster suite and GFS related information
"""
plugin_name = 'cluster'
option_list = [("gfslockdump",
'gather output of gfs lockdumps', 'slow', False),
... |
import oslo_config.cfg
from oslo_utils import importutils
_network_opts = [
oslo_config.cfg.StrOpt('network_api_class',
default='nova.network.api.API',
help='The full class name of the '
'network API class to use'),
]
oslo_confi... |
from ete2 import Tree
# Loads a tree. Note that we use format 1 to read internal node names
t = Tree('((((H,K)D,(F,I)G)B,E)A,((L,(N,Q)O)J,(P,S)M)C);', format=1)
print "original tree looks like this:"
# This is an alternative way of using "print t". Thus we have a bit
# more of control on how tree is printed. Here i pri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.