code stringlengths 1 199k |
|---|
"""
Amazon EC2, Eucalyptus and Nimbus drivers.
"""
from __future__ import with_statement
import sys
import base64
import os
import copy
from xml.etree import ElementTree as ET
from libcloud.utils.py3 import b
from libcloud.utils.xml import fixxpath, findtext, findattr, findall
from libcloud.common.aws import AWSBaseRes... |
__version__ = "1.12.0"
__version_info__ = ( 1, 12, 0 ) |
"""Backport from python2.7 to python <= 2.6."""
from itertools import repeat as _repeat, chain as _chain, starmap as _starmap
try:
from itertools import izip_longest as _zip_longest
except ImportError:
from itertools import izip
def _zip_longest(*args, **kwds):
# izip_longest('ABCD', 'xy', fillvalue... |
'''
Author: Christopher Duffy
Date: February 2015
Name: nmap_scanner.py
Purpose: To scan a network
Copyright (c) 2015, Christopher Duffy All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met: * Redistributions
o... |
from os.path import join
from time import strftime
from qiita_db.util import get_mountpoint
from qiita_db.sql_connection import SQLConnectionHandler
from qiita_db.metadata_template import SampleTemplate, PrepTemplate
conn_handler = SQLConnectionHandler()
_id, fp_base = get_mountpoint('templates')[0]
for study_id in con... |
from __future__ import print_function
import numpy as np
from bokeh.client import push_session
from bokeh.io import curdoc
from bokeh.models import (ColumnDataSource, DataRange1d, Plot, Circle, WidgetBox,
Row, Button, TapTool)
N = 9
x = np.linspace(-2, 2, N)
y = x**2
source1 = ColumnDataSource... |
"""
BrowserID support
"""
from social.backends.base import BaseAuth
from social.exceptions import AuthFailed, AuthMissingParameter
class PersonaAuth(BaseAuth):
"""BrowserID authentication backend"""
name = 'persona'
def get_user_id(self, details, response):
"""Use BrowserID email as ID"""
re... |
from sqlalchemy import JSON, Boolean, Column, ForeignKey, Index, Integer, String
from sqlalchemy.dialects import postgresql
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import relationship
from sqlalchemy.sql.functions import GenericFunction
from qcfractal.storage_sockets.models.sql_base import... |
import sys
sys.path.extend(['../sympy', 'ext'])
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.mathjax',
'numpydoc', 'sympylive',]
mathjax_path = 'https://c328740.ssl.cf1.rackcdn.com/mathjax/latest/MathJax.js?config=TeX-AMS_HTML-full'
templates_path = ['.templates']
source_suffix =... |
d = {}
for i in range(100000):
d[i] = i
JS_CODE = '''
var d = {};
for (var i = 0; i < 100000; i++) {
d[i] = i;
}
''' |
import os
import sys
import subprocess
from flask.ext.script import Manager, Shell, Server
from flask.ext.migrate import MigrateCommand
from foobar.app import create_app
from foobar.user.models import User
from foobar.settings import DevConfig, ProdConfig
from foobar.database import db
if os.environ.get("FOOBAR_ENV") =... |
import git
from git.exc import InvalidGitRepositoryError
from git.config import GitConfigParser
from io import BytesIO
import weakref
from typing import Any, Sequence, TYPE_CHECKING, Union
from git.types import PathLike
if TYPE_CHECKING:
from .base import Submodule
from weakref import ReferenceType
from git... |
from sympy.core import pi, oo, symbols, Function, Rational, Integer, GoldenRatio, EulerGamma, Catalan, Lambda, Dummy, Eq
from sympy.functions import Piecewise, sin, cos, Abs, exp, ceiling, sqrt, gamma
from sympy.utilities.pytest import raises
from sympy.printing.ccode import CCodePrinter
from sympy.utilities.lambdify i... |
from django.contrib import admin
from django.utils.translation import ugettext, ugettext_lazy as _
from ella.positions.models import Position
from ella.utils import timezone
class PositionOptions(admin.ModelAdmin):
def show_title(self, obj):
if not obj.target:
return '-- %s --' % ugettext('empty... |
from django.contrib import admin
from panoptes.tracking.models import AccountFilter
class AccountFilterAdmin(admin.ModelAdmin):
list_display = ('location', 'include_users', 'exclude_users')
ordering = ('location',)
admin.site.register(AccountFilter, AccountFilterAdmin) |
'''
c++ finally
'''
def myfunc():
b = False
try:
print('trying something that will fail...')
print('some call that fails at runtime')
f = open('/tmp/nosuchfile')
except:
print('got exception')
finally:
print('finally cleanup')
b = True
TestError( b == True )
def main():
myfunc() |
from __future__ import nested_scopes
__revision__ = "$Id$"
import unittest
from Crypto.PublicKey import RSA
from Crypto import Random
from Crypto.SelfTest.st_common import list_test_cases, a2b_hex, b2a_hex
from Crypto.Hash import *
from Crypto.Signature import PKCS1_PSS as PKCS
from Crypto.Util.py3compat import *
def i... |
"""
This is an example that demonstrates how to use an
RGB led with BreakfastSerial. It assumes you have an
RGB led wired up with red on pin 10, green on pin 9,
and blue on pin 8.
"""
from BreakfastSerial import RGBLed, Arduino
from time import sleep
board = Arduino()
led = RGBLed(board, { "red": 10, "green": 9, "blue... |
import os
import inspect
from lib import BaseTest
def changesRemove(_, s):
return s.replace(os.path.join(os.path.dirname(inspect.getsourcefile(BaseTest)), "changes"), "")
class EditRepo1Test(BaseTest):
"""
edit repo: change comment
"""
fixtureCmds = [
"aptly repo create repo1",
]
run... |
import re
import datetime
import dateutil.parser
from django.conf import settings
from django.utils import feedgenerator
from django.utils.html import linebreaks
from apps.social.models import MSocialServices
from apps.reader.models import UserSubscription
from utils import log as logging
from vendor.facebook import Gr... |
import io
import sys
isPython3 = sys.version_info >= (3, 0)
class Scribe:
@staticmethod
def read(path):
with io.open(path, mode="rt", encoding="utf-8") as f:
s = f.read()
# go to beginning
f.seek(0)
return s
@staticmethod
def read_beginning(path, lines... |
"""
This script shows the categories on each page and lets you change them.
For each page in the target wiki:
* If the page contains no categories, you can specify a list of categories to
add to the page.
* If the page already contains one or more categories, you can specify a new
list of categories to replace the ... |
from botocore.utils import is_json_value_header
class ShapeDocumenter(object):
EVENT_NAME = ''
def __init__(self, service_name, operation_name, event_emitter,
context=None):
self._service_name = service_name
self._operation_name = operation_name
self._event_emitter = eve... |
from sys import version_info
if version_info >= (2,6,0):
def swig_import_helper():
from os.path import dirname
import imp
fp = None
try:
fp, pathname, description = imp.find_module('_allog', [dirname(__file__)])
except ImportError:
import _allog
... |
import logging
import codecs
from optparse import OptionParser
from pyjade.utils import process
import os
def convert_file():
support_compilers_list = ['django', 'jinja', 'underscore', 'mako', 'tornado']
available_compilers = {}
for i in support_compilers_list:
try:
compiler_class = __im... |
import os
import unittest
from lxml import etree
from hovercraft.template import (Template, CSS_RESOURCE, JS_RESOURCE,
JS_POSITION_BODY, JS_POSITION_HEADER)
TEST_DATA = os.path.join(os.path.split(__file__)[0], 'test_data')
class TemplateInfoTests(unittest.TestCase):
"""Tests that te... |
import operator
import os
import abc
import functools
import pyparsing as pp
from mitmproxy.utils import strutils
from mitmproxy.utils import human
import typing # noqa
from . import generators
from . import exceptions
class Settings:
def __init__(
self,
is_client=False,
staticdir=None,
... |
"""Test the fundrawtransaction RPC."""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
def get_unspent(listunspent, amount):
for utx in listunspent:
if utx['amount'] == amount:
return utx
raise AssertionError('Could not find unspent with amoun... |
"""
pygments.styles.borland
~~~~~~~~~~~~~~~~~~~~~~~
Style similar to the style used in the Borland IDEs.
:copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.style import Style
from pygments.token import Keyword, Name, Comment, ... |
from django.conf.urls import *
from omeroweb.webstart import views
urlpatterns = patterns('django.views.generic.simple',
url( r'^$', views.index, name="webstart_index" ),
url( r'^jars/insight\.jnlp$', views.insight, name='webstart_insight'),
) |
"""
All the little functions that make life nicer in the Traits package.
.. moduleauthor:: Mihai Andrei <mihai.andrei@codemart.ro>
.. moduleauthor:: Lia Domide <lia.domide@codemart.ro>
.. moduleauthor:: marmaduke <duke@eml.cc>
"""
import numpy
import collections
import inspect
from tvb.basic.profile import TvbProfile
i... |
import os
import time
from . import test_util
def test_add_file():
test_util.mkfile(1, 'a.md', 'add a file')
test_util.verify_result()
def test_add_file_t():
test_util.mkfile(2, 'l/m/n/test.md', 'add l/m/n/test.md')
test_util.verify_result()
def test_add_dir():
test_util.mkdir(1, 'ad')
test_util... |
"""
Import and export of snippets.
"""
import os
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
from PyQt5.QtCore import QSize, Qt
from PyQt5.QtGui import QKeySequence
from PyQt5.QtWidgets import QMessageBox, QTreeWidget, QTreeWidgetItem
import app
import appinfo... |
__doc__="""interfaces.py
Representation of Predictive Threshold components.
$Id: info.py,v 1.2 2010/12/14 20:45:46 jc Exp $"""
__version__ = "$Revision: 1.4 $"[11:-2]
from Products.Zuul.interfaces import IInfo, IFacade
from Products.Zuul.interfaces.template import IThresholdInfo
from Products.Zuul.form import schema
fr... |
def ExOh(str):
temp = list(str)
xcount = 0
ocount = 0
for c in temp:
if c == "x":
xcount += 1
if c == "o":
ocount += 1
if xcount == ocount:
print "true"
elif xcount != ocount:
print "false"
ExOh(raw_input()) |
__author__="hechao"
__date__ ="$2011-12-20 16:36:20$"
import gc
from xml.parsers import expat
from hwclass import *
class Device:
def __init__(self, dev_xml):
self.description = ''
self.product = ''
self.vendor = ''
self.version = ''
self.businfo = ''
self.logicalname... |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('monitoring', '0002_monitoring_update'),
]
operations = [
migrations.RemoveField(
model_name='requestevent',
name='resources',
),
migrations.AddField(
... |
from south.db import db
from south.v2 import SchemaMigration
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Application.content_type'
db.add_column('applications_application', 'content_type', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['contenttypes.Conte... |
import sys, os, glob, re
def getAvgSingle(fileNameGetAvg):
"""calcuates the average cache hits for a file"""
#print "TESTING:: file:", fileNameGetAvg
#this part is from counter_mikey.py
try:
traceFile = open(fileNameGetAvg, 'r')
fileLines = traceFile.readlines()
traceFile.close()
except IOError:
print "War... |
"""Solar analemma."""
from ._skyBase import RadianceSky
from ..material.light import Light
from ..geometry.source import Source
from ladybug.epw import EPW
from ladybug.sunpath import Sunpath
import os
try:
from itertools import izip as zip
writemode = 'wb'
except ImportError:
# python 3
writemode = 'w'... |
"""
Read samples from a UHD device and write to file formatted as binary
outputs single precision complex float values or complex short values
(interleaved 16 bit signed short integers).
"""
from gnuradio import gr, eng_notation
from gnuradio import uhd
from gnuradio.eng_option import eng_option
from optparse import Op... |
from PyQt4.QtCore import Qt
from PyQt4.QtGui import QColor
from volumina.api import LazyflowSource, ColortableLayer, AlphaModulatedLayer
from ilastik.applets.dataExport.dataExportGui import DataExportGui, DataExportLayerViewerGui
from lazyflow.operators import OpMultiArraySlicer2
from ilastik.utility.exportingOperator ... |
"""
sphinx.environment.managers.toctree
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Toctree manager for sphinx.environment.
:copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from six import iteritems
from docutils import nodes
from sphinx import add... |
from django.template.defaultfilters import register
from appointment.constants import EVENT_STATUS, ALARM_STATUS, ALARM_METHOD
@register.filter(name='event_status')
def event_status(value):
"""Event Status Templatetag"""
if not value:
return ''
STATUS = dict(EVENT_STATUS)
try:
return STA... |
from datetime import datetime, date, timedelta
from dateutil.relativedelta import relativedelta
from openerp.osv import fields, osv
from openerp.tools import DEFAULT_SERVER_DATE_FORMAT as OE_DATEFORMAT
class hr_employee(osv.Model):
_inherit = 'hr.employee'
def _get_contracts_list(self, employee):
'''Ret... |
import datetime
import sqlalchemy.orm.exc
from nylas.logging import get_logger
log = get_logger()
from inbox.auth.oauth import OAuthAuthHandler
from inbox.basicauth import OAuthError
from inbox.models import Namespace
from inbox.config import config
from inbox.models.backends.outlook import OutlookAccount
from inbox.mo... |
'''
Copyright (C) 2005 Aaron Spike, aaron@ekips.org
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 2 of the License, or
(at your option) any later version.
This program is distributed ... |
import os
from spack import *
class Vasp(MakefilePackage):
"""
The Vienna Ab initio Simulation Package (VASP)
is a computer program for atomic scale materials modelling,
e.g. electronic structure calculations
and quantum-mechanical molecular dynamics, from first principles.
"""
homepage = "h... |
import sys
from testrunner import run
def testfunc(child):
child.expect("All up, running the shell now")
child.sendline("ifconfig")
child.expect(r"Iface\s+(\d+)\s+HWaddr:")
if __name__ == "__main__":
sys.exit(run(testfunc, timeout=1, echo=False)) |
"""
Unit tests for the class
:class:`iris.fileformats.um._fast_load_structured_fields.FieldCollation`.
"""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
import iris.tests as tests
from iris._lazy_data import as_lazy_data
from netcdftime... |
import unittest
from ctypes import *
import _ctypes_test
lib = CDLL(_ctypes_test.__file__)
class StringPtrTestCase(unittest.TestCase):
def test__POINTER_c_char(self):
class X(Structure):
_fields_ = [("str", POINTER(c_char))]
x = X()
# NULL pointer access
self.assertRaises... |
"""Windows-specific implementation of process utilities.
This file is only meant to be imported by process.py, not by end-users.
"""
from __future__ import print_function
import os
import sys
import ctypes
import msvcrt
from ctypes import c_int, POINTER
from ctypes.wintypes import LPCWSTR, HLOCAL
from subprocess import... |
from oslo.config import cfg
import requests
from neutron.api.v2 import attributes as attr
from neutron.common import exceptions as exc
from neutron.db import portbindings_base
from neutron.db import quota_db # noqa
from neutron.extensions import external_net
from neutron.extensions import portbindings
from neutron.ext... |
"""Tests for tensorflow.ops.tf.gather."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from te... |
import unittest
from enum import Enum
from airflow.utils.weekday import WeekDay
class TestWeekDay(unittest.TestCase):
def test_weekday_enum_length(self):
assert len(WeekDay) == 7
def test_weekday_name_value(self):
weekdays = "MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY SUNDAY"
week... |
from tempest import clients
from tempest.common.utils.data_utils import rand_name
import tempest.test
class BaseIdentityAdminTest(tempest.test.BaseTestCase):
@classmethod
def setUpClass(cls):
super(BaseIdentityAdminTest, cls).setUpClass()
os = clients.AdminManager(interface=cls._interface)
... |
"""Support for NX584 alarm control panels."""
import logging
from nx584 import client
import requests
import voluptuous as vol
import homeassistant.components.alarm_control_panel as alarm
from homeassistant.components.alarm_control_panel import PLATFORM_SCHEMA
from homeassistant.components.alarm_control_panel.const imp... |
import sys
def tokens(nodes):
for i in range(0, nodes):
print (i * (2 ** 127 - 1) / nodes)
tokens(int(sys.argv[1])) |
""" Tests for swift.common.compressing_file_reader """
import unittest
import cStringIO
from slogging.compressing_file_reader import CompressingFileReader
class TestCompressingFileReader(unittest.TestCase):
def test_read(self):
plain = 'obj\ndata'
s = cStringIO.StringIO(plain)
expected = '\x... |
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Common")
AddReference("QuantConnect.Indicators")
from System import *
from QuantConnect import *
from QuantConnect.Indicators import ... |
"""AFF4 object representing client stats."""
from grr.lib import aff4
from grr.lib import rdfvalue
from grr.lib.aff4_objects import standard
class ClientStats(standard.VFSDirectory):
"""A container for all client statistics."""
class SchemaCls(standard.VFSDirectory.SchemaCls):
STATS = aff4.Attribute("aff4:stats... |
"""
WSGI config for mysite project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os, sys
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTIN... |
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks
from autobahn.wamp.types import CallResult
from autobahn.twisted.wamp import ApplicationSession
class Component(ApplicationSession):
"""
Application component that provides procedures which
return complex results.
"""
... |
import collections
import copy
import sys
import uuid
import eventlet
import mock
from oslo_config import cfg
import oslo_messaging
import testtools
from neutron.agent.common import config
from neutron.agent.dhcp import agent as dhcp_agent
from neutron.agent.dhcp import config as dhcp_config
from neutron.agent import d... |
from Experiment import Experiment # Main experiment class
from pUtil import tolog # Logging method that sends text to the pilot log
from pUtil import readpar # Used to read values from the schedconfig DB (queuedata)
from pUtil import isAnalysisJob # Is the current job a user anal... |
'''
Saves relevant data fed back from TwitterStream etc next to its PID and timestamp ready for analysis
Needs to do limited analysis to work out which keywords in the tweet stream correspond to which programme
'''
from datetime import datetime
import os
import string
import time as time2
from time import time
from Axo... |
"""
==========================================================================
Illustration of prior and posterior Gaussian process for different kernels
==========================================================================
This example illustrates the prior and posterior of a
:class:`~sklearn.gaussian_process.Gau... |
test = {
'name': '',
'points': 1,
'suites': [
{
'cases': [
{
'code': r"""
>>> type(imdb_by_year) == tables.Table
True
>>> imdb_by_year.column('Title').take(range(3))
array(['The Kid (1921)', 'The Gold Rush (1925)', 'The General (1926)'],
... |
from __future__ import unicode_literals
from random import randint
from .. import Provider as AddressProvider
class Provider(AddressProvider):
address_formats = ['{{street_address}}, {{city}}, {{postcode}}']
building_number_formats = ['#', '##', '###']
city_formats = ['{{city_prefix}} {{first_name}}']
s... |
from oscar_vat_moss import fields
from oscar.apps.address.abstract_models import AbstractShippingAddress
from oscar.apps.address.abstract_models import AbstractBillingAddress
class ShippingAddress(AbstractShippingAddress):
vatin = fields.vatin()
class BillingAddress(AbstractBillingAddress):
vatin = fields.vatin... |
from __future__ import absolute_import
from digits.utils import subclass, override, constants
from digits.extensions.data.interface import DataIngestionInterface
from .forms import DatasetForm, InferenceForm
import numpy as np
import os
TEMPLATE = "templates/template.html"
INFERENCE_TEMPLATE = "templates/inference_temp... |
import datetime
import sys
import time
from typing import Any, Union
from pyshark.packet.fields import LayerFieldsContainer, LayerField
from pyshark.packet.packet import Packet as RawPacket
from pktverify.addrs import EthAddr, ExtAddr, Ipv6Addr
from pktverify.bytes import Bytes
from pktverify.consts import VALID_LAYER_... |
from __future__ import unicode_literals
import warnings
from django.core.checks import Error, Warning as DjangoWarning
from django.db import models
from django.db.models.fields.related import ForeignObject
from django.test import ignore_warnings
from django.test.testcases import SimpleTestCase, skipIfDBFeature
from dja... |
"""
exec_command
Implements exec_command function that is (almost) equivalent to
commands.getstatusoutput function but on NT, DOS systems the
returned status is actually correct (though, the returned status
values may be different by a factor). In addition, exec_command
takes keyword arguments for (re-)defining environ... |
"""
wakatime.dependencies.haxe
~~~~~~~~~~~~~~~~~~~~~~~~~~
Parse dependencies from Haxe code.
:copyright: (c) 2018 Alan Hamlett.
:license: BSD, see LICENSE for more details.
"""
from . import TokenParser
class HaxeParser(TokenParser):
exclude = [
r'^haxe$',
]
state = None
def ... |
from __future__ import print_function
from __future__ import absolute_import
import contextlib
import logging
import os
import py_utils
from py_utils import binary_manager
from py_utils import cloud_storage
from py_utils import dependency_util
import dependency_manager
from dependency_manager import base_config
from de... |
"""
Oracle database backend for Django.
Requires cx_Oracle: http://cx-oracle.sourceforge.net/
"""
from __future__ import unicode_literals
import decimal
import re
import sys
import warnings
def _setup_environment(environ):
import platform
# Cygwin requires some special voodoo to set the environment variables
... |
"""
lantz.drivers.andor.ccd
~~~~~~~~~~~~~~~~~~~~~~~
Low level driver wrapping library for CCD and Intensified CCD cameras.
Only functions for iXon EMCCD cameras were tested.
Only tested in Windows OS.
The driver was written for the single-camera scenario. If more than one
camera is present, ... |
import datetime
import httplib2
import itertools
import json
from django.conf import settings
from django.db import connection, transaction
from django.db.models import Sum, Max
import commonware.log
from apiclient.discovery import build
from celeryutils import task
from oauth2client.client import OAuth2Credentials
imp... |
import hashlib
import logging
import os
from django.conf import settings
from django.core.files.storage import default_storage as storage
from django.db import transaction
from PIL import Image
from olympia import amo
from olympia.addons.models import (
Addon, attach_tags, attach_translations, AppSupport, CompatOve... |
from __future__ import absolute_import
from sentry.models import Activity
from sentry.testutils import APITestCase
class GroupNoteTest(APITestCase):
def test_simple(self):
group = self.group
activity = Activity.objects.create(
group=group,
project=group.project,
t... |
from __future__ import absolute_import
from celery.utils.dispatch.saferef import safe_ref
from celery.tests.utils import Case
class Class1(object):
def x(self):
pass
def fun(obj):
pass
class Class2(object):
def __call__(self, obj):
pass
class SaferefTests(Case):
def setUp(self):
... |
from twisted.internet.defer import inlineCallbacks, returnValue
from vumi.connectors import (
BaseConnector, ReceiveInboundConnector, ReceiveOutboundConnector,
IgnoreMessage)
from vumi.tests.utils import LogCatcher
from vumi.worker import BaseWorker
from vumi.message import TransportUserMessage
from vumi.middle... |
import binascii
import hashlib
import sys
def computeAuxpow (block, target, ok):
"""
Build an auxpow object (serialised as hex string) that solves
(ok = True) or doesn't solve (ok = False) the block.
"""
# Start by building the merge-mining coinbase. The merkle tree
# consists only of the block hash as roo... |
'''Trains two recurrent neural networks based upon a story and a question.
The resulting merged vector is then queried to answer a range of bAbI tasks.
The results are comparable to those for an LSTM model provided in Weston et al.:
"Towards AI-Complete Question Answering: A Set of Prerequisite Toy Tasks"
http://arxiv.... |
version_info = (1, 9, 'dev0')
__version__ = '.'.join(map(str, version_info)) |
from __future__ import print_function
__title__ = 'pif.utils'
__author__ = 'Artur Barseghyan'
__copyright__ = 'Copyright (c) 2013 Artur Barseghyan'
__license__ = 'GPL 2.0/LGPL 2.1'
__all__ = ('ensure_autodiscover', 'list_checkers', 'get_public_ip')
from pif.base import registry
from pif.discover import autodiscover
def... |
from abc import abstractmethod
import sys, abc
if sys.version_info >= (3, 4):
ABC = abc.ABC
else:
ABC = abc.ABCMeta('ABC', (), {})
import numpy as np
from enum import Enum
class Env(ABC):
class Terminate(Enum):
Null = 0
Fail = 1
Succ = 2
def __init__(self, args, enable_draw):
self.enable_draw = ... |
VERSION = "1.0.0b3" |
def uniquer(seq, idfun=None):
if idfun is None:
def idfun(x): return x
seen = {}
result = []
for item in seq:
marker = idfun(item)
if marker in seen: continue
seen[marker] = 1
result.append(item)
return result |
from gettext import gettext as _
import traceback
from pulp.client.commands.repo.sync_publish import StatusRenderer
from pulp.client.extensions.core import COLOR_FAILURE
from pulp_puppet.common import constants
from pulp_puppet.common.publish_progress import PublishProgressReport
from pulp_puppet.common.sync_progress ... |
import curses
import sys
FROMWHO = "Thomas Gellekum <tg@FreeBSD.org>"
def set_color(win, color):
if curses.has_colors():
n = color + 1
curses.init_pair(n, color, my_bg)
win.attroff(curses.A_COLOR)
win.attron(curses.color_pair(n))
def unset_color(win):
if curses.has_colors():
... |
"""
ReflectionBlock can render and process ReflectionIdevices as XHTML
"""
import logging
from exe.webui.block import Block
from exe.webui import common
from exe.webui.element import TextAreaElement
log = logging.getLogger(__name__)
class ReflectionBlock(Block):
"""
Reflec... |
"""Tests for CMFNotification installation ad uninstallation.
$Id: testInstallation.py 65679 2008-05-25 23:45:26Z dbaty $
"""
from zope.component import getUtility
from zope.component import getMultiAdapter
from AccessControl.PermissionRole import rolesForPermissionOn
from plone.portlets.interfaces import IPortletManage... |
from openstack.tests.unit import base
from openstack.orchestration.v1 import resource
FAKE_ID = '32e39358-2422-4ad0-a1b5-dd60696bf564'
FAKE_NAME = 'test_stack'
FAKE = {
'links': [{
'href': 'http://res_link',
'rel': 'self'
}, {
'href': 'http://stack_link',
'rel': 'stack'
}],
... |
"""
Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com>
This file is part of RockStor.
RockStor 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 2 of the License,
or (at your option) any lat... |
"""
Tests for waffle utils features.
"""
import crum
import ddt
from django.test import TestCase
from django.test.client import RequestFactory
from edx_django_utils.cache import RequestCache
from mock import patch
from opaque_keys.edx.keys import CourseKey
from waffle.testutils import override_flag
from .. import Cours... |
from datetime import datetime
import uuid
from werkzeug.exceptions import Forbidden
import logging
import openerp
from openerp import api, tools
from openerp import SUPERUSER_ID
from openerp.addons.website.models.website import slug
from openerp.exceptions import Warning
from openerp.osv import osv, fields
from openerp... |
from __future__ import absolute_import
from django.core.management import call_command
from teams.models import Team, TeamMember, Workflow
from widget.rpc import Rpc
def refresh_obj(m):
return m.__class__._default_manager.get(pk=m.pk)
def reset_solr():
# cause the default site to load
from haystack import b... |
"""
Created on Tue Sep 22 09:47:41 2015
@author: thomas.douenne
"""
from __future__ import division
import statsmodels.formula.api as smf
from openfisca_france_indirect_taxation.examples.utils_example import simulate_df_calee_by_grosposte
if __name__ == '__main__':
import logging
log = logging.getLogger(__name_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.