content stringlengths 4 20k |
|---|
import discord
from sigma.core.utilities.role_processing import matching_role
async def addselfrole(cmd, message, args):
if message.author.permissions_in(message.channel).manage_roles:
if args:
lookup = ' '.join(args)
target_role = matching_role(message.guild, lookup)
... |
"""
Django settings for apply project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
impo... |
{
'name': 'Purchase Management',
'version': '1.1',
'category': 'Purchase Management',
'sequence': 19,
'summary': 'Purchase Orders, Receipts, Supplier Invoices',
'description': """
Manage goods requirement by Purchase Orders easily
==================================================
Purchase mana... |
import sys
from os.path import dirname, join, abspath
# Figure out where we're installed
ROOT_DIR = dirname(dirname(abspath(__file__)))
# Make sure that carbon's 'lib' dir is in the $PYTHONPATH if we're running from source.
LIB_DIR = join(ROOT_DIR, 'graphite', 'lib')
sys.path.insert(0, LIB_DIR)
from carbon.aggregato... |
from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
import logging
from datetime import datetime, timedelta
from flexget import db_schema, plugin
from flexget.event import event
from flexget.manager import Session
from flex... |
"""
Apple/NeXT Binary Property List (BPLIST) parser.
Also includes a .createXML() function which produces an XML representation of the object.
Note that it will discard unknown objects, nulls and fill values, but should work for most files.
Documents:
- CFBinaryPList.c
http://src.gnu-darwin.org/DarwinSourceArchive/... |
from django.db.models import Q
from .models import UserProfile
class TestUserBackend(object):
"""Authentication backend to easily log in a user while testing."""
def authenticate(self, request=None, username=None, email=None,
password=None):
# This needs to explicitly throw when... |
import functools
from .. import errors
from . import utils
def check_resource(f):
@functools.wraps(f)
def wrapped(self, resource_id=None, *args, **kwargs):
if resource_id is None:
if kwargs.get('container'):
resource_id = kwargs.pop('container')
elif kwargs.get... |
"""
askbot askbot url configuraion file
"""
import os.path
from django.conf import settings
from django.conf.urls.defaults import url, patterns, include
from django.conf.urls.defaults import handler500, handler404
from django.contrib import admin
from askbot import views
from askbot.feed import RssLastestQuestionsFeed,... |
"""Token Manager classes.
There should be a 1-to-1 mapping between an instance of a subclass of
:class:`.BaseTokenManager` and a :class:`.Reddit` instance.
A few proof of concept token manager classes are provided here, but it is expected that
PRAW users will create their own token manager classes suitable for their ... |
'''
Script to generate list of seed nodes for chainparams.cpp.
This script expects two text files in the directory that is passed as an
argument:
nodes_main.txt
nodes_test.txt
These files must consist of lines in the format
<ip>
<ip>:<port>
[<ipv6>]
[<ipv6>]:<port>
<onion>.onion
0xDD... |
from django.core import urlresolvers
from django.contrib.sitemaps import Sitemap
class GeoRSSSitemap(Sitemap):
"""
A minimal hook to produce sitemaps for GeoRSS feeds.
"""
def __init__(self, feed_dict, slug_dict=None):
"""
This sitemap object initializes on a feed dictionary (as would b... |
#
# Python documentation build configuration file
#
# This file is execfile()d with the current directory set to its containing dir.
#
# The contents of this file are pickled, so don't put values in the namespace
# that aren't pickleable (module imports are okay, they're removed automatically).
import sys, os, time
sy... |
""" Python character mapping codec test
This uses the test codec in testcodec.py and thus also tests the
encodings package lookup scheme.
Written by Marc-Andre Lemburg (<EMAIL>).
(c) Copyright 2000 Guido van Rossum.
"""#"
import test.support, unittest
import codecs
# Register a search function which knows about ... |
from sos.plugins import Plugin, RedHatPlugin
class Tuned(Plugin, RedHatPlugin):
"""Tuned system tuning daemon
"""
packages = ('tuned',)
profiles = ('system', 'performance')
plugin_name = 'tuned'
def setup(self):
self.add_cmd_output([
"tuned-adm list",
"tuned-ad... |
"""
### Tutorial Documentation
Documentation that goes along with the Airflow tutorial located
[here](https://airflow.apache.org/tutorial.html)
"""
# [START tutorial]
# [START import_module]
from datetime import timedelta
from textwrap import dedent
# The DAG object; we'll need this to instantiate a DAG
from airflow i... |
from openerp.osv import osv
class AbstractReport(osv.AbstractModel):
"""Model used to embed old style reports"""
_name = 'report.abstract_report'
_template = None
_wrapped_report_class = None
def render_html(self, cr, uid, ids, data=None, context=None):
context = dict(context or {})
... |
# -*- coding: utf-8 -*-
"""Tests for the XQueue certificates interface. """
from contextlib import contextmanager
import ddt
import json
from mock import patch, Mock
from nose.plugins.attrib import attr
from django.test import TestCase
from django.test.utils import override_settings
from opaque_keys.edx.locator impor... |
from panda3d.core import *
from direct.gui.DirectGui import *
from direct.task.Task import Task
from direct.interval.IntervalGlobal import *
import DistributedCloset
import ClosetGlobals
import TrunkGUI
from toontown.toon import ToonDNA
from toontown.toonbase import TTLocalizer
from toontown.toonbase import ToontownGlo... |
import datetime as dt
from io import StringIO
from .testutils import (unittest, ConnectingTestCase,
skip_before_postgres, skip_before_python, skip_copy_if_green)
import psycopg2
from psycopg2 import sql
class SqlFormatTests(ConnectingTestCase):
@skip_before_python(2, 7)
def test_pos(self):
s = sq... |
"""
Test cases for the dircache module
Nick Mathewson
"""
import unittest
from test.test_support import is_jython, run_unittest, TESTFN
import dircache, os, time, sys, tempfile
class DircacheTests(unittest.TestCase):
def setUp(self):
self.tempdir = tempfile.mkdtemp()
def tearDown(self):
... |
import abc
import json
import logging
import time
import luigi
from luigi import postgres
from luigi.contrib import rdbms
from luigi.s3 import S3PathTask, S3Target
logger = logging.getLogger('luigi-interface')
try:
import psycopg2
import psycopg2.errorcodes
except ImportError:
logger.warning("Loading po... |
"""
.. module:: identitydb.
Here is a simple1 database for identities cache. Also keep track of
changing identities sources and maintain a several "index" dictionaries
to speed up processes.
"""
#------------------------------------------------------------------------------
from __future__ import absolute_import
imp... |
"""Tests for utilities working with user input."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.data.util import convert
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensor... |
#!/usr/bin/env python3
import glob
import os
import platform
import shutil
import sys
import argparse
import mapnik
from nose.tools import eq_, raises
# mapnik.logger.set_severity(mapnik.severity_type.None)
# mapnik.logger.set_severity(mapnik.severity_type.Debug)
try:
import json
except ImportError:
import ... |
# encoding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
class RTL2IE(InfoExtractor):
_VALID_URL = r'http?://(?:www\.)?rtl2\.de/[^?#]*?/(?P<id>[^?#/]*?)(?:$|/(?:$|[?#]))'
_TESTS = [{
'url': 'http://www.rtl2.de/sendung/grip-das-motormagazin/folge/folge-203-... |
#
#
# FOOTNOTES
#
# * (Yes, "in the common case" is deliberate weasel wording, as is
# "significantly impede". For example, the hooks may prompt
# occasionally, e.g. when pushing between your own private
# repositories.)
#
# ** See utils/fixtabs for a cleap-up utility if you feel like fixing
# a whole file rat... |
from django.core.cache import cache
# wger
from wger.core.models import DaysOfWeek
from wger.core.tests.base_testcase import WgerTestCase
from wger.exercises.models import (
Exercise,
Muscle,
)
from wger.manager.models import (
Day,
Set,
Setting,
Workout,
)
from wger.utils.cache import cache_ma... |
import time
from openerp.osv import osv
from openerp.report import report_sxw
class pos_user_product(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(pos_user_product, self).__init__(cr, uid, name, context)
self.localcontext.update({
'time': time,
'... |
'''
This module provides a basic "weak method" implementation. It is necessary
because the weakref module does not support weak methods (in the sense that,
counter-intuitively, a user who creates a weakref.ref(obj.method), a reasonable
action, get a weak ref that is None.
:copyright: Copyright since 2006 by Oliver Sc... |
import sys
import cx_Oracle
from django.db.backends.oracle.introspection import DatabaseIntrospection
from django.utils import six
class OracleIntrospection(DatabaseIntrospection):
# Associating any OBJECTVAR instances with GeometryField. Of course,
# this won't work right on Oracle objects that aren't MDS... |
from __future__ import absolute_import, unicode_literals
import warnings
from django.conf import settings
from django.utils import six
# Always import this module as follows:
# from debug_toolbar import settings [as dt_settings]
# Don't import directly CONFIG or PANELs, or you will miss changes performed
# with ov... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
dinfdistdown.py
---------------------
Date : October 2012
Copyright : (C) 2012 by Alexander Bruy
Email : alexander dot bruy at gmail dot com
************... |
# -*- coding: utf-8 -*-
"""
Google App Engine OpenID Providers
----------------------------------
|openid|_ provider implementations based on the |gae_users_api|_.
.. note::
When using the :class:`GAEOpenID` provider, the :class:`.User` object
will always have only the
:attr:`.User.user_id`,
:attr:`.... |
'''
Support for ADS-B data
Samuel Dudley
Dec 2015
'''
import time
from math import *
from MAVProxy.modules.lib import mp_module
from MAVProxy.modules.mavproxy_map import mp_slipmap
from MAVProxy.modules.lib import mp_settings
from MAVProxy.modules.lib.mp_menu import * # popup menus
from pymavlink import mavutil
cl... |
from __future__ import absolute_import, division, unicode_literals
from jx_base.expressions import FALSE, FalseOp, NULL, NullOp, TrueOp, extend
from jx_base.language import Language
from jx_sqlite.utils import quote_column
from jx_sqlite.sqlite import sql_call
from mo_dots import wrap, FlatList, is_data
from mo_future... |
#!/usr/bin/env python
#
#
'''
The TDDFT calculations by default use the same XC functional, grids, _numint
schemes as the ground state DFT calculations. Different XC, grids, _numint
can be set in TDDFT.
'''
import copy
from pyscf import gto, dft, tddft
mol = gto.M(atom='N 0 0 0; N 0 0 1', basis='6-31g*')
mf = dft.... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from units.compat.mock import patch
from ansible.modules.network.onyx import onyx_buffer_pool
from units.modules.utils import set_module_args
from .onyx_module import TestOnyxModule, load_fixture
class TestOnyxBufferPoolModule(Te... |
from random import random
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.graphics import Color
from kivy.graphics import Ellipse
from kivy.graphics import Line
class PaintWidget(Widget):
de... |
# -*- coding: utf-8 -*-
import uuid
from .model import Node, PrivateLink
from framework.forms.utils import sanitize
from framework.mongo.utils import from_mongo
from modularodm import Q
from website.exceptions import NodeStateError
def show_diff(seqm):
"""Unify operations between two compared strings
seqm is a di... |
from __future__ import division, print_function, absolute_import
import numpy as np
from scipy.lib.six.moves import xrange
from scipy.linalg import get_blas_funcs
from .utils import make_system
__all__ = ['lgmres']
def norm2(q):
q = np.asarray(q)
nrm2 = get_blas_funcs('nrm2', dtype=q.dtype)
return nrm2(... |
from django import forms
from django.core.validators import EMPTY_VALUES
from django.forms.models import ModelChoiceIterator
from pootle.i18n.gettext import ugettext_lazy as _
class GroupedModelChoiceIterator(ModelChoiceIterator):
def __init__(self, field):
self.field = field
self.choice_groups =... |
import json
from xlr_xldeploy.XLDeployClientUtil import XLDeployClientUtil
xld_client = XLDeployClientUtil.create_xldeploy_client(xldeployServer, username, password)
response = xld_client.check_ci_exist(xldCI, True)
my_ci = json.loads( xld_client.get_ci(xldCI, 'json') )
print xldNewTags
xld_client.update_ci_property(... |
import datetime
import pytest
from mock import patch
from treeherder.seta.models import JobPriority
from treeherder.seta.runnable_jobs import RunnableJobsClient
from treeherder.seta.update_job_priority import (_initialize_values,
_sanitize_data,
... |
from io import BytesIO
import os
import ssl
import sys
import warnings
import base64
from six.moves import urllib
from six.moves import http_client
from .TTransport import TTransportBase
import six
class THttpClient(TTransportBase):
"""Http implementation of TTransport base."""
def __init__(self, uri_or_ho... |
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class FinalizeOAuth(Choreography):
def __init__(self, temboo_session):
"""
Create a... |
import os
import shutil
from mutagen._compat import cBytesIO
from mutagen.ogg import OggPage
from mutagen.oggspeex import OggSpeex, OggSpeexInfo, delete
from tests import TestCase
from tests.test_ogg import TOggFileTypeMixin
from tempfile import mkstemp
class TOggSpeex(TestCase, TOggFileTypeMixin):
Kind = OggSpe... |
import os
import os.path
import time
import errno
import rb
from gi.repository import RB
SECS_PER_DAY = 86400
class URLCache(object):
def __init__(self, name, path, refresh=-1, discard=-1, lifetime=-1):
"""
Creates a new cache. 'name' is a symbolic name for the cache.
'path' is either an... |
from __future__ import division, print_function, absolute_import
import numpy as np
from numpy.linalg import norm
from numpy.testing import (assert_, assert_allclose, assert_equal,
run_module_suite)
from scipy.linalg import polar, eigh
diag2 = np.array([[2, 0], [0, 3]])
a13 = np.array([[1, 2, 2]])
precomputed_c... |
"""The :mod:`~deap.base` module provides basic structures to build
evolutionary algorithms. It contains the :class:`~deap.base.Toolbox`, useful
to store evolutionary operators, and a virtual :class:`~deap.base.Fitness`
class used as base class, for the fitness member of any individual. """
import sys
from collections... |
'''login -- PythonWin user ID and password dialog box
(Adapted from originally distributed with Mark Hammond's PythonWin -
this now replaces it!)
login.GetLogin() displays a modal "OK/Cancel" dialog box with input
fields for a user ID and password. The password field input is masked
with *'s. GetLogin takes two opti... |
import unittest
import numpy as np
from op_test import OpTest
class TestRefByTrainerIdOp(OpTest):
def setUp(self):
self.op_type = "ref_by_trainer_id"
param_baks = [("x%d" % x, np.random.random((10, 10)).astype("float32"))
for x in range(10)]
self.inputs = {
... |
#!/usr/bin/env python3
import sys
import os
import argparse
def write_pymol_arrows(base, structs, scale, color, radius, hradius, hlength, threshold):
pymol_file = base + '_arrows.pymol'
lines = []
arrow_objs = set()
t2 = threshold**2
s2 = scale**2
for i, struct in enumerate(structs):
... |
from __future__ import unicode_literals
from .common import InfoExtractor
class AlJazeeraIE(InfoExtractor):
_VALID_URL = r'http://www\.aljazeera\.com/programmes/.*?/(?P<id>[^/]+)\.html'
_TEST = {
'url': 'http://www.aljazeera.com/programmes/the-slum/2014/08/deliverance-201482883754237240.html',
... |
"""Native adapter for serving CherryPy via mod_python
Basic usage:
##########################################
# Application in a module called myapp.py
##########################################
import cherrypy
class Root:
@cherrypy.expose
def index(self):
return 'Hi there, Ho there, Hey there'
# ... |
from openerp.osv import fields, osv
class purchase_order(osv.osv):
_inherit = "purchase.order"
def _prepare_order_line_move(self, cr, uid, order, order_line, picking_id, group_id, context=None):
res = super(purchase_order, self)._prepare_order_line_move(
cr, uid, order, order_line, picki... |
#!/usr/bin/env python
import sys
import sh
import json
import requests
import re
import os
from datetime import datetime
source_dir = '%s/source' % os.environ['GITHUB_WORKSPACE']
client_dir = '%s/client/source' % os.environ['GITHUB_WORKSPACE']
script_dir = os.path.dirname(os.path.realpath(__file__))
def check_for_ch... |
import shm_wrapper as shm
from vegas_hpc.GBTStatus import GBTStatus
import time, pyfits
import vegas_hpc.possem as possem
import numpy as n
#import psr_utils as psr
import vegas_hpc.astro_utils as astro
#import slalib as s
from pyslalib import slalib as s
DEGTORAD = 0.017453292519943295769236907684
RADTODEG = 57.29577... |
# This test module covers support in various parts of the standard library
# for working with modules located inside zipfiles
# The tests are centralised in this fashion to make it easy to drop them
# if a platform doesn't support zipimport
import test.support
import os
import os.path
import sys
import textwrap
import ... |
import base64
import json
from django import forms
from django.contrib import admin
from drip.models import Drip, SentDrip, QuerySetRule
from drip.drips import configured_message_classes, message_class_for
from drip.utils import get_user_model
class QuerySetRuleInline(admin.TabularInline):
model = QuerySetRule
... |
from datetime import time
from django.template.defaultfilters import time as time_filter
from django.test import SimpleTestCase, override_settings
from django.utils import timezone, translation
from ..utils import setup
from .timezone_utils import TimezoneTestCase
class TimeTests(TimezoneTestCase):
"""
#206... |
import time
import unittest
import node
LEADER = 1
ROUTER = 2
SED1 = 3
ED1 = 4
MTDS = [SED1, ED1]
class Cert_7_1_1_BorderRouterAsLeader(unittest.TestCase):
def setUp(self):
self.nodes = {}
for i in range(1,5):
self.nodes[i] = node.Node(i, (i in MTDS))
self.nodes[LEADER].set_... |
import pandas as pd
import numpy as np
class Aggregate():
""" Aggregation Algorithm
Parameters
----------
learning_rate : float
Learning rate for the Aggregation algorithm
loss_type : string
'absolute' or 'squared'
match_window : int
(default: 10) how many of the obse... |
import sys
import time
import os
import json
from common import cmd_output, run_cmd, err
def run():
""" start trafodion instance """
dbcfgs = json.loads(dbcfgs_json)
print 'Starting trafodion'
traf_home = os.environ['TRAF_HOME']
if os.path.exists('%s/sql/scripts/trafstart' % traf_home):
ru... |
from __future__ import print_function
import mxnet as mx
import numpy as np
import rl_data
import sym
import argparse
import logging
import os
import gym
from datetime import datetime
import time
parser = argparse.ArgumentParser(description='Traing A3C with OpenAI Gym')
parser.add_argument('--test', action='store_true... |
from dtypes.quick_sort import quisort
from random import shuffle
import pytest
def test_rand_quicksort():
tlist = range(500)
shuffle(tlist)
assert tlist != range(500)
quisort(tlist)
assert tlist == range(500)
def test_backward_quicksort():
tlist = range(500)
tlist.reverse()
quisort(t... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import gym
from ray.rllib.utils.annotations import DeveloperAPI
# By convention, metrics from optimizing the loss can be reported in the
# `grad_info` dict returned by learn_on_batch() / co... |
import logging
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon import messages
from openstack_dashboard import api
LOG = logging.getLogger(__name__)
class AddInterface(forms.SelfHandlingForm):... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'community'}
import json
import traceback
try:
import botocore
except ImportError:
pass ... |
#!/usr/bin/env python
'''
SelectROI.py
Written by Jeff Berry 18 Feb 2011
Modified by Gus Hahn-Powell 21 Feb 2014
purpose:
This script is designed to help the user select a region of interest
to use with the set of images selected by the user. The boundaries
can be set either by clicking and dragging, or with the t... |
class StateSampler(object):
def __init__(self, *args, **kwargs):
pass
def scoped_state(self, step_name, state_name=None, io_target=None):
return _FakeScopedState()
def start(self):
pass
def stop(self):
pass
def stop_if_still_running(self):
self.stop()
def commit_counters(self):
... |
# coding: utf-8
from __future__ import unicode_literals
import os.path
import re
from .common import InfoExtractor
class SaveFromIE(InfoExtractor):
IE_NAME = 'savefrom.net'
_VALID_URL = r'https?://[^.]+\.savefrom\.net/\#url=(?P<url>.*)$'
_TEST = {
'url': 'http://en.savefrom.net/#url=http://yout... |
from django.conf import settings
from django.core.management.base import NoArgsCommand
from django.shortcuts import render
from django.test import RequestFactory
from django.utils.translation import ugettext
from html5lib import constants as html5lib_constants
from kuma.wiki.content import parse
class Command(NoArgs... |
__author__ = 'e.bidelman (Eric Bidelman)'
import cgi
import os
import gdata.auth
import gdata.docs
import gdata.docs.service
import gdata.alt.appengine
from appengine_utilities.sessions import Session
from django.utils import simplejson
from google.appengine.api import users
from google.appengine.ext impo... |
import numpy as np
import pandas as pd
from scipy import stats
from matplotlib import pyplot as plt
from statsmodels.tsa.stattools import grangercausalitytests
from GetHistory import CrpytoCompare
def granger_test(base='BTC', quote='USD', exchange1='Bitfinex', exchange2='BitTrex'):
df_ex1 = CrpytoCompare.crypto_c... |
from django.core.urlresolvers import reverse
from nose.plugins.attrib import attr
from courseware.tests.tests import LoginEnrollmentTestCase
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
from mock import patch
@attr('shard_1')
cl... |
from __future__ import unicode_literals
import frappe
from frappe import throw, _
import frappe.defaults
from frappe.utils import flt, get_fullname, fmt_money, cstr
from erpnext.utilities.doctype.address.address import get_address_display
from frappe.utils.nestedset import get_root_of
class WebsitePriceListMissingErro... |
import Sofa
# utility python module to dynamically create objects in Sofa
def createDragon(parentNode,name,x,y,z,color):
node = parentNode.createChild(name)
# <EulerImplicit name="cg_odesolver" printLog="false" />
node.createObject('EulerImplicit',name='cg_odesolver')
# <CGLinearSolver iterations="25" name="li... |
""" Generic support code for:
error handling code found in every weave module
local/global dictionary access code for inline() modules
swig pointer (old style) conversion support
"""
from __future__ import absolute_import, print_function
from . import base_info
module_support_code = \
"""
//... |
#!/usr/bin/env python
import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
# import thread
import cv
import cv2
import numpy as np
import tf
from math import sin, cos
import math
from slaw_msgs.msg import PoseStampedLabeled, PoseStampedLabeledArray
from j48 import j48_holes
imp... |
"""Testing framework for the software construction toolkit.
A TestFramework environment object is created via the usual invocation:
import TestFramework
test = TestFramework.TestFramework()
TestFramework is a subclass of TestCommon, which is in turn is a subclass
of TestCmd.
"""
import base64
import os
import r... |
import numpy as np
from mdtraj import compute_dihedrals, compute_phi
from mdtraj.testing import eq
from msmbuilder.example_datasets import fetch_alanine_dipeptide
from msmbuilder.featurizer import get_atompair_indices, FunctionFeaturizer, \
DihedralFeaturizer, AtomPairsFeaturizer, SuperposeFeaturizer, \
RMSDFe... |
# -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from unittest import TestCase
from django.core.exceptions import ValidationError
from django.db import models
class ValidationMessagesTest(TestCase):
def _test_validation_messages(self, field, value, expected):
with self.assertRaises(Val... |
from django.db import IntegrityError
from rest_framework import serializers as ser
from rest_framework import exceptions
from website.files import exceptions as file_exceptions
from api.base.serializers import IDField
class DestinationSerializer(ser.Serializer):
parent = ser.CharField(write_only=True)
targe... |
"""TLS Lite + smtplib."""
from smtplib import SMTP
from tlslite.tlsconnection import TLSConnection
from tlslite.integration.clienthelper import ClientHelper
class SMTP_TLS(SMTP):
"""This class extends L{smtplib.SMTP} with TLS support."""
def starttls(self,
username=None, password=None,
... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 30 16:22:29 2014
Author: Josef Perktold
License: BSD-3
"""
from statsmodels.compat.python import StringIO
import numpy as np
from numpy.testing import assert_allclose, assert_equal, assert_
from nose import SkipTest
import pandas as pd
import patsy
from statsmodels.d... |
"""
Provide an SQLALchemy connector for the eGenix mxODBC commercial
Python adapter for ODBC. This is not a free product, but eGenix
provides SQLAlchemy with a license for use in continuous integration
testing.
This has been tested for use with mxODBC 3.1.2 on SQL Server 2005
and 2008, using the SQL Server Nati... |
"""Unit test for Google Test test filters.
A user can specify which test(s) in a Google Test program to run via either
the GTEST_FILTER environment variable or the --gtest_filter flag.
This script tests such functionality by invoking
gtest_filter_unittest_ (a program written with Google Test) with different
environmen... |
r"""JSON (JavaScript Object Notation) <http://json.org> is a subset of
JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data
interchange format.
:mod:`json` exposes an API familiar to users of the standard library
:mod:`marshal` and :mod:`pickle` modules. It is the externally maintained
version of the :m... |
#!/usr/bin/python
import re
import sys
import getopt
from subprocess import Popen, PIPE
from pprint import pprint as ppr
import os
def Usage(s):
print 'Usage: {} -t <cstest_path> [-f <file_name.cs>] [-d <directory>]'.format(s)
sys.exit(-1)
def get_report_file(toolpath, filepath, getDetails, cmt_out):
cmd = [tool... |
"""Spectral biclustering algorithms.
Authors : Kemal Eren
License: BSD 3 clause
"""
from abc import ABCMeta, abstractmethod
import numpy as np
from scipy.sparse import dia_matrix
from scipy.sparse import issparse
from . import KMeans, MiniBatchKMeans
from ..base import BaseEstimator, BiclusterMixin
from ..external... |
import os
from twisted.python import log
from twisted.python.procutils import which
from twisted.python import runtime
def getCommand(name):
possibles = which(name)
if not possibles:
raise RuntimeError("Couldn't find executable for '%s'" % name)
#
# Under windows, if there is more than one exe... |
from __future__ import absolute_import, unicode_literals
from draftjs_exporter.constants import BLOCK_TYPES, ENTITY_TYPES, INLINE_STYLES
from draftjs_exporter.defaults import BLOCK_MAP
TERMS_BLOCK_ID = 'TERMS_AND_CONDITIONS_TEXT'
DRAFT_BLOCK_TYPE_H3 = {'label': 'H3', 'type': BLOCK_TYPES.HEADER_THREE}
DRAFT_BLOCK_TYP... |
from datetime import datetime, timedelta
class AutoResetFilter(object):
"""Initial implementation of auto-reset is fairly simple. You just give it a
time interval. Like aggregation, we the first time period start with the
time of the first record (t0) and signal a reset at the first record on or after
t0 + i... |
from __future__ import unicode_literals
import logging
import os.path
import sys
from os import listdir
from mopidy_bigbeet import Extension
from mopidy_bigbeet.schema import beet_schema, genre_schema
from peewee import *
from playhouse.apsw_ext import APSWDatabase, DateTimeField
user_version = 1
# database = Sqlite... |
from lib.common import helpers
class Module:
def __init__(self, mainMenu, params=[]):
self.info = {
'Name': 'Spawn',
'Author': ['@harmj0y'],
'Description': ('Spawns a new agent in a new powershell.exe process.'),
'Background' : False,
'Outpu... |
import urllib2
from webkitpy.common.net.networktransaction import NetworkTransaction
class Web(object):
def get_binary(self, url, convert_404_to_None=False):
return NetworkTransaction(convert_404_to_None=convert_404_to_None).run(lambda: urllib2.urlopen(url).read()) |
from __future__ import (absolute_import, division)
__metaclass__ = type
import copy
import json
import sys
from ansible.compat.tests import unittest
from units.mock.procenv import swap_stdin_and_argv, swap_stdout
from ansible.module_utils import basic
empty_invocation = {u'module_args': {}}
class TestAnsibleModul... |
"""
The main hook file is called by Juju.
"""
import contextlib
import os
import socket
import subprocess
import sys
from charmhelpers.core import hookenv, host
from charmhelpers.contrib import ssl
from kubernetes_installer import KubernetesInstaller
from path import Path
hooks = hookenv.Hooks()
@contextlib.contextm... |
import os.path
import urllib
import duplicity.backend
from duplicity import globals
from duplicity import log
from duplicity import tempdir
class FTPBackend(duplicity.backend.Backend):
"""Connect to remote store using File Transfer Protocol"""
def __init__(self, parsed_url):
duplicity.backend.Backend.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.