content stringlengths 4 20k |
|---|
import argparse
import json
import sys
import colorama
from termcolor import colored
from .parser import SchemaParser
from .primitive import Object
from .visitor import ValidationVisitor
from .schema.visitor import AvroSchemaVisitor
def validate(arguments):
with open(arguments.schema) as fp:
schema = jso... |
from .chaos_event import ChaosEvent
class ExecutingFaultsChaosEvent(ChaosEvent):
"""Describes a Chaos event that gets generated when Chaos has decided on the
faults for an iteration. This Chaos event contains the details of the
faults as a list of strings.
:param time_stamp_utc:
:type time_stamp_... |
"""Fixer that changes map(F, ...) into list(map(F, ...)) unless there
exists a 'from future_builtins import map' statement in the top-level
namespace.
As a special case, map(None, X) is changed into list(X). (This is
necessary because the semantics are changed in this case -- the new
map(None, X) is equivalent ... |
from flask_restful import reqparse
from brainminer.base.api import PermissionProtectedResource
from brainminer.storage.dao import RepositoryDao
# ----------------------------------------------------------------------------------------------------------------------
class RepositoriesResource(PermissionProtectedResourc... |
"""
Integration tests for the stem.util.system functions against the tor process
that we're running.
"""
import os
import getpass
import unittest
import stem.util.system
import test.runner
import test.mocking as mocking
def filter_system_call(prefixes):
"""
Provides a functor that passes calls on to the stem.uti... |
r"""Multivariate autoregressive model (vector autoregression).
Implements the following model (num_blocks = max(ar_order, ma_order + 1)):
y(t, 1) = \sum_{i=1}^{ar_order} ar_coefs[i] * y(t - 1, i)
y(t, i) = y(t - 1, i - 1) + ma_coefs[i - 1] * e(t) for 1 < i < num_blocks
y(t, num_blocks) = y(t - 1, num_blocks - 1... |
import inspect
import traceback
import logging
import os
from logging.handlers import TimedRotatingFileHandler
from threading import RLock
from fate_arch.common import file_utils
class LoggerFactory(object):
TYPE = "FILE"
LOG_FORMAT = "[%(levelname)s] [%(asctime)s] [%(process)s:%(thread)s] - %(filename)s[lin... |
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.test.client import Client
from apps.canvas_auth.models import User, AnonymousUser
from canvas.models import EmailUnsubscribe
from canvas.tests.tests_helpers import CanvasTestCase, NotOkay, create_content, create_user, create_... |
#!/usr/bin/env python2
from SettingsWidgets import *
class Module:
name = "general"
comment = _("Miscellaneous Cinnamon preferences")
category = "prefs"
def __init__(self, content_box):
keywords = _("logging, click")
sidePage = SidePage(_("General"), "cs-general", keywords, content_bo... |
import os
import subprocess
import sys
import gettext
_ = lambda m: gettext.dgettext(message=m, domain='ovirt-engine')
import config
from ovirt_engine import configfile
from ovirt_engine import service
from ovirt_engine import java
class Daemon(service.Daemon):
def __init__(self):
super(Daemon, self)... |
from __future__ import unicode_literals
from django.test import TestCase
from rest_framework import status
from rest_framework.authentication import BasicAuthentication
from rest_framework.decorators import (
api_view, authentication_classes, parser_classes, permission_classes,
renderer_classes, throttle_clas... |
from unittest.mock import patch, MagicMock
from taiga.mdrender.extensions import emojify
from taiga.mdrender.service import render, cache_by_sha, get_diff_of_htmls, render_and_extract
from datetime import datetime
dummy_project = MagicMock()
dummy_project.id = 1
dummy_project.slug = "test"
def test_proccessor_vali... |
#!/usr/bin/env python
import os, sys, pygame
from pygame import locals
import time
# Define the colors we will use in RGB format
black = [ 0, 0, 0]
white = [255,255,255]
red = [255, 0, 0]
#os.environ["SDL_VIDEODRIVER"] = "dummy"
pygame.init()
# Set the height and width of the screen
size=[630,300]
screen=pygame.di... |
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table(
'tunnelkeylasts',
sa.Column('last_key', sa.Integer(), nullable=False),
sa.PrimaryKeyConstraint('last_key'))
op.create_table(
'tunnelkeys',
sa.Column('network_id', sa.String(length=36), nulla... |
import os
import glob
import numpy as np
from PIL import Image
import logging
from .dataset import Dataset
from .util import touch
log = logging.getLogger(__name__)
_URLS = {
'liberty': ['http://www.cs.ubc.ca/~mbrown/patchdata/liberty.zip'],
'notredame': ['http://www.cs.ubc.ca/~mbrown/patchdata/notredame.zip... |
"""
List of user commands.
"""
from reduction.reducer import Reducer
class ReductionSingleton(object):
""" Singleton reduction class """
## storage for the instance reference
__instance = None
def __init__(self):
""" Create singleton instance """
# Check whether we already have a... |
import unittest
from autothreadharness.harness_case import HarnessCase
class Router_5_1_7(HarnessCase):
role = HarnessCase.ROLE_ROUTER
case = '5 1 7'
golden_devices_required = 11
def on_dialog(self, dialog, title):
if title.startswith('Enter Router Max Child Count'):
inp = dialog.f... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
try:
import pyrax
HAS_PYRAX = True
except ImportError:
HAS_PYRAX = False
def rax_asp(module, at=None, change=0, cron=None, cooldown=300,
desired_capacity=0, is_per... |
#!/usr/bin/env python
## zip archive frontend for git-fast-import
##
## For example:
##
## mkdir project; cd project; git init
## python import-zips.py *.zip
## git log --stat import-zips
from os import popen, path
from sys import argv, exit, hexversion, stderr
from time import mktime
from zipfile import ZipFile
... |
r"""Support for regular expressions (RE).
This module provides regular expression matching operations similar to
those found in Perl. It supports both 8-bit and Unicode strings; both
the pattern and the strings being processed can contain null bytes and
characters outside the US ASCII range.
Regular expressions can ... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Article'
db.create_table('news_article', (
('id', self.gf('django.db.models.fiel... |
from __future__ import absolute_import
import unittest2
from st2client.utils import strutil
class StrUtilTestCase(unittest2.TestCase):
# See https://mail.python.org/pipermail/python-list/2006-January/411909.html
def test_unescape(self):
in_str = 'Action execution result double escape \\"stuffs\\".\\... |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 11 12:21:00 2016
@author: Joseph R. Cole
"""
#import pdb
import Tkinter as tki
import tkSimpleDialog
import logging
import os
from EmailSamplesDB import *
class WordListSelectGUI(tkSimpleDialog.Dialog) :
def __init__(self, parent, DBobj, title=None) :
self.DBobj = DB... |
""" API v0 views. """
import logging
from edx_rest_api_client import exceptions
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.status import HTT... |
"""OAI harvestor - 'wget' records from an OAI repository.
This 'getter' simply retrieve the records from an OAI repository.
"""
__revision__ = "$Id$"
try:
import sys
import httplib
import urllib
import getpass
import socket
import re
import time
import base64
import tempfile
i... |
import math
from mathutils import Matrix
import appleseed as asr
from ..translator import Translator
from ...logger import get_logger
from ...utils import util
logger = get_logger()
class InteractiveCameraTranslator(Translator):
"""
This translator is responsible for translating the Blender camera into an ... |
# fixture_built_batch.py
import os
import pytest
import shutil
from ..hscbatch import hscBatch
from .setpaths import *
@pytest.fixture
def batch_good():
if os.path.isdir(dir_batch):
shutil.rmtree(dir_batch)
shutil.copytree(dir_verif, dir_batch)
return hscBatch(dir_batch=dir_batch)
@pytest.fixture
def batch_... |
import unittest
from withings import WithingsAuth, WithingsCredentials
from requests_oauthlib import OAuth1Session
try:
from unittest.mock import MagicMock
except ImportError:
from mock import MagicMock
class TestWithingsAuth(unittest.TestCase):
def setUp(self):
self.consumer_key = 'fake_consume... |
class Key(object):
@classmethod
def from_path(cls, *args, **kwds):
raise NotImplementedError("Paths are not currently supported")
def __init__(self, encoded=None, obj=None):
self.name = None
if obj:
self.id = obj.id
self.kind = obj.kind()
else:
... |
# coding=utf-8
"""
oauthlib.oauth2.rfc6749.errors
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error used both by OAuth 2 clients and providers to represent the spec
defined error responses for all four core grant types.
"""
from __future__ import unicode_literals
import json
from oauthlib.common import add_params_to_uri, urlenc... |
from __future__ import print_function
# $example on:init_session$
from pyspark.sql import SparkSession
# $example off:init_session$
# $example on:schema_inferring$
from pyspark.sql import Row
# $example off:schema_inferring$
# $example on:programmatic_schema$
# Import data types
from pyspark.sql.types import *
# $ex... |
from django.db import models
from django.contrib.auth.models import User
from data_services.models import DimRun
from . import cluster_id
cluster_choices = tuple([(cluster, cluster) for cluster in cluster_id.ALL_KNOWN])
class RunProvider(models.Model):
"""
Associates a run to a provider. When runs are submi... |
#!/usr/bin/env python
# pylint: disable=
"""
Pump for the online file format
(the file format formerly known as formerly as JPP)
"""
import numpy as np
import km3io
from thepipe import Module, Blob
from km3pipe.dataclasses import Table
from km3pipe.logger import get_logger
log = get_logger(__name__) # pylint: dis... |
from oslo_db.sqlalchemy import utils
INDEX_COLUMNS = ['instance_uuid']
# using the index name same with mysql
INDEX_NAME = 'instance_uuid'
SYS_META_TABLE_NAME = 'instance_system_metadata'
def upgrade(migrate_engine):
"""Add instance_system_metadata indexes missing on PostgreSQL and other DB.
"""
# This... |
from __future__ import unicode_literals
import datetime
from django.forms.utils import flatatt, pretty_name
from django.forms.widgets import Textarea, TextInput
from django.utils import six
from django.utils.encoding import (
force_text, python_2_unicode_compatible, smart_text,
)
from django.utils.html import con... |
"""GTFlow Model definitions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
from tensorflow.contrib import learn
from tensorflow.contrib.boosted_trees.estimator_batch import estimator_utils
from tensorflow.contrib.boosted_trees.estimator_ba... |
from gnuradio import gr
import numpy
import pmt
class snet_classifier(gr.basic_block):
"""docstring for block snet_classifier"""
def __init__(self):
gr.basic_block.__init__(
self,
name='snet_classifier',
in_sig=[],
out_sig=[])
self.message_port_... |
import argparse
from functools import partial, reduce
import json
import operator
import os
import random
import string
from thclient import (TreeherderClient, TreeherderResultSetCollection,
TreeherderJobCollection)
import time
from runner import format_result_summary
def geometric_mean(iterabl... |
"""
Tests for ProctoredExamTransformer.
"""
import ddt
from milestones.tests.utils import MilestonesTestCaseMixin
from mock import Mock, patch
from nose.plugins.attrib import attr
from gating import api as lms_gating_api
from lms.djangoapps.course_blocks.api import get_course_blocks
from lms.djangoapps.course_blocks.t... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import datetime
import os
import traceback
import textwrap
from ansible.compat.six import iteritems
from ansible import constants as C
from ansible.errors import AnsibleError, AnsibleOptionsError
from ansible.plugins import modul... |
"""Remove silence command"""
import sys
from argparse import ArgumentParser
from lazyasd import lazyobject
from xonsh.tools import print_color
from umdone.sound import Audio
from umdone.commands import audio_io
@lazyobject
def PARSER():
parser = ArgumentParser('remove-silence')
parser.add_argument('path',
... |
import re, datetime
import tests, debug
from common import TestCommon
from results import PassFailResult, RowResults
from itertools import product
@tests.add_test
class MdbBench(TestCommon):
'''mdbbench'''
name = "mdbbench"
#resets = ["random_nat_ram", "propszrand_nat_ram", "szprob_cp_nat_ram"]
resets... |
# -*- coding: utf-8 -*-
import os
from gluon.fileutils import listdir
@auth.requires_membership('admin')
def index():
btn = A('Setup', _href=URL('manage', 'setup'), _class='btn btn-large btn-block')
btn2 = A('Categories', _href=URL('manage', 'select', args='category'), _class='btn btn-large btn-block btn-primary')
... |
from datetime import date
from django.conf import settings
from django.db import connection
import cronjobs
from kitsune.dashboards.models import (
PERIODS, WikiDocumentVisits, WikiMetric, L10N_TOP20_CODE, L10N_TOP100_CODE, L10N_ALL_CODE,
L10N_ACTIVE_CONTRIBUTORS_CODE)
from kitsune.dashboards.readouts import... |
#!/usr/bin/env python2
from __future__ import division, print_function
from astroML.decorators import pickle_results
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import scipy
from os import path
from sys import argv
from classifier import classifier
from fit import power_law
import gw
f... |
import os
import sys
from decimal import Decimal, ROUND_DOWN
import json
import random
import shutil
import subprocess
import time
import re
from authproxy import AuthServiceProxy, JSONRPCException
from util import *
def p2p_port(n):
return 11000 + n + os.getpid()%999
def rpc_port(n):
return 12000 + n + os.g... |
from google.appengine.api import users
from google.appengine.ext import webapp, db
from google.appengine.ext.webapp import template
from handlers.updatebase import UpdateBase
from loggers.recordbotevent import RecordBotEvent
from loggers.recordpatchevent import RecordPatchEvent
from model.attachment import Attachment
... |
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.azure_rm_common import AzureRMModuleBase
try:
from msrestazur... |
#!/usr/bin/python
import urlparse, json
from mod_pywebsocket import common, msgutil, util
from mod_pywebsocket.handshake import hybi
from wptserve import stash
address, authkey = stash.load_env_config()
stash = stash.Stash("/stash_responder", address=address, authkey=authkey)
def web_socket_do_extra_handshake(request... |
import re
import time
from streamlink.cache import Cache
from streamlink.exceptions import PluginError
from streamlink.plugin import Plugin
from streamlink.plugin import PluginArguments, PluginArgument
from streamlink.plugin.api import useragents
from streamlink.stream import HLSStream
from streamlink.utils import upd... |
""" helper_funcs.py.
scavenged from enthought,interpolate
"""
from __future__ import division, print_function, absolute_import
import numpy as np
from . import _interpolate # C extension. Does all the real work.
def atleast_1d_and_contiguous(ary, dtype=np.float64):
return np.atleast_1d(np.ascontiguousarray... |
#!/usr/bin/env python
"""Test :mod:`tools.convertPyX12`.
Each TestCase is reasonably similar to the following.
1. Use the ParserBuilder to read the source and build an :mod:`X12.parse` object.
2. Emit SQL. Use the SQL to build a SQLite database.
3. Emit Python Source. Evaluate the Python source to cr... |
"""
Code to manage the creation and SQL rendering of 'where' constraints.
"""
from django.db.models.sql.datastructures import EmptyResultSet
from django.utils import tree
from django.utils.functional import cached_property
# Connection types
AND = 'AND'
OR = 'OR'
class WhereNode(tree.Node):
"""
Used to repr... |
#!/usr/bin/env python
# encoding: utf-8
import re
import sys
from setuptools import setup, find_packages
if sys.version_info < (2, 6):
print 'MediaDrop requires Python 2.6 or 2.7.'
sys.exit(1)
from mediadrop import __version__ as VERSION
# setuptools' dependency resolution is often too simplistic. If we in... |
import os
import re
import appengine_wrappers
from extensions_paths import SERVER2
from path_util import IsDirectory
from test_util import ReadFile, ChromiumPath
import url_constants
# TODO(kalman): Investigate why logging in this class implies that the server
# isn't properly caching some fetched files; often it fe... |
"""Support for the Awair indoor air quality monitor."""
from datetime import timedelta
import logging
import math
import voluptuous as vol
from homeassistant.const import (
CONF_ACCESS_TOKEN,
CONF_DEVICES,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_TEMPERATURE,
TEMP_CELSIUS,
)
from homeassistant.excepti... |
from oslo_config import cfg
from nova.tests.functional.v3 import test_servers
CONF = cfg.CONF
CONF.import_opt('osapi_compute_extension',
'nova.api.openstack.compute.extensions')
class SuspendServerSamplesJsonTest(test_servers.ServersSampleBase):
extension_name = "os-suspend-server"
ctype = '... |
# Simple test suite for Cookie.py
from test.test_support import run_unittest, run_doctest, check_warnings
import unittest
import Cookie
import pickle
class CookieTests(unittest.TestCase):
# Currently this only tests SimpleCookie
def test_basic(self):
cases = [
{ 'data': 'chips=ahoy; vienn... |
import time
from openerp.report import report_sxw
from common_report_header import common_report_header
#
# Use period and Journal for selection or resources
#
class journal_print(report_sxw.rml_parse, common_report_header):
def __init__(self, cr, uid, name, context=None):
if context is None:
c... |
# Borrowed from Alex Martelli's sort from Python cookbook using inlines
# 2x over fastest Python version -- again, maybe not worth the effort...
# Then again, 2x is 2x...
#
# C:\home\eric\wrk\scipy\weave\examples>python dict_sort.py
# Dict sort of 1000 items for 300 iterations:
# speed in python: 0.2509999275... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import re
from ansible.module_utils.facts.network.base import NetworkCollector
from ansible.module_utils.facts.network.generic_bsd import GenericBsdIfconfigNetwork
class AIXNetwork(GenericBsdIfconfigNetwork):
"""
This is... |
import edxmako
from django.conf import settings
from edxmako.middleware import get_template_request_context
from edxmako.shortcuts import marketing_link
from mako.template import Template as MakoTemplate
DJANGO_VARIABLES = ['output_encoding', 'encoding_errors']
# TODO: We should make this a Django Template subclass ... |
from f5.utils.responses.handlers import Stats
NESTED_DICT = \
{u'https://localhost/mgmt/tm/fakemod/fake/fakeone/~Common~fakeone/stats': {
u'nestedStats': {
u'kind': u'tm:fakemod:fake:fakestats',
u'selfLink': u'https://localhost/mgmt/tm/fakemod/fake/fakeone/'
... |
"""
An RPC service for thrift modules.
@author: Jonathan Stoppani <<EMAIL>>
"""
from thrift.protocol.TBinaryProtocol import TBinaryProtocolFactory
from thrift.transport.TTwisted import ThriftServerFactory
from twisted.application import service, internet
from twisted.internet import defer, reactor, protocol
from sm... |
import unittest
from oslo_log import log as logging
import oslotest.base
import testtools
from designate import exceptions
from designate import objects
LOG = logging.getLogger(__name__)
def create_test_domain():
return objects.Domain(
name='www.example.org.',
email='<EMAIL>',
)
class Dom... |
import pyupm_i2clcd as lcd
# Initialize Jhd1313m1 at 0x3E (LCD_ADDRESS) and 0x62 (RGB_ADDRESS)
myLcd = lcd.Jhd1313m1(0, 0x3E, 0x62)
myLcd.setCursor(0,0)
# RGB Blue
#myLcd.setColor(53, 39, 249)
# RGB Red
myLcd.setColor(255, 0, 0)
while(1):
myLcd.write('Hello World')
myLcd.setCursor(1,2)
myLcd.write('Hell... |
#!/usr/bin/env python3
import unittest
from unittest.mock import patch
import numpy as np
from tmc import points
from tmc.utils import load, get_out
module_name="src.multiplication_table_revisited"
multiplication_table = load(module_name, "multiplication_table")
def patch_name(m, d):
import importlib
parts... |
import itertools
import random
random.seed()
import math
class BeatPattern(object):
def __init__(self, lily, onsets, endings):
self.lily=lily
self.onsets=onsets
self.endings=endings
#self.inverted=0 # TBD: allow for "inverted"
def __iter__(self):
''' Make me look like a ... |
from types import ListType
from grp import getgrnam
__doc__ = '''Netfarm Archiver - release 2.1.0 - Postfix mailbox lookup'''
__version__ = '2.1.0'
__all__ = [ 'mblookup' ]
## Recurse in aliases
def lookup_alias(entry, db, bc):
entries = entry[:-1].strip().split(',')
results = []
for entry in entries:
... |
""" Insert Interval
Given a set of non-verlapping intervals, insert a new interval into the
intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Input: intervals = [[1, 3], [6, 9]], newInterval = [2, 5]
Output: [[1, 5], [6, 9]]
E... |
import actions
import error
import functions
import gui
import logreport
import rpc
import tiny_socket
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
"""Support for Harmony Hub devices."""
import asyncio
import json
import logging
from aioharmony.const import ClientCallbackType
import aioharmony.exceptions as aioexc
from aioharmony.harmonyapi import HarmonyAPI as HarmonyClient, SendCommandDevice
import voluptuous as vol
from homeassistant.components import remote
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import re
import textwrap
import types
from ansible.compat.tests import unittest
from ansible.compat.tests.mock import patch, mock_open, MagicMock
from ansible.plugins.callback import CallbackBase
class TestCallback(unittest.T... |
import types
import warnings
import functools
from gi import PyGIDeprecationWarning
from gi._gi import CallableInfo
from gi._gobject.constants import \
TYPE_NONE, \
TYPE_INVALID
# support overrides in different directories than our gi module
from pkgutil import extend_path
__path__ = extend_path(__path__, __n... |
from typing import Any, TYPE_CHECKING
from azure.core.configuration import Configuration
from azure.core.pipeline import policies
from azure.mgmt.core.policies import ARMHttpLoggingPolicy
from .._version import VERSION
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.creden... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import subprocess
KEEP = 7 # number od days to keep
BACKUP_DIR = '/home/{{ user }}/dbs'
IGNORE_DBS = (
'template0',
'template1',
'template_postgis',
'postgres',
)
def run(command):
"""
Runs a command.
Returns stdout if sucess,... |
import time
import cgi
import oauth2 as oauth
from django.test import Client
from oauth_provider.tests.auth import BaseOAuthTestCase
from oauth_provider.models import Token, Consumer, Scope
from oauth_provider.compat import get_user_model
User = get_user_model()
class ProtocolExample(BaseOAuthTestCa... |
#!/usr/bin/python
# Comflics: Exploring OpenFOAM
# Compute Strouhal Number of Laminar Vortex Shedding
# S. Huq, 13MAY17
#
import numpy as np
import scipy.signal as signal
import matplotlib.pyplot as plt
# # Read Results
data = np.loadtxt('./postProcessing/forceCoeffs/0/forceCoeffs.dat', skiprows=0)
L = 2 ... |
"""Helper functions for enqueuing data from arrays and pandas `DataFrame`s."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import random
import types as tp
import numpy as np
import six
from tensorflow.python.estimator.inputs.queues ... |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 8 13:54:04 2016
@author: Søren
"""
# Python standard modules
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from collections import defaultdict
import seaborn as sns
from itertools import cycle, islice
# Own modules
from dayahead_o... |
__revision__ = "$Id$"
import unittest
from invenio.webcomment import calculate_start_date
from invenio.testutils import make_test_suite, run_test_suite
class TestCalculateStartDate(unittest.TestCase):
"""Test for calculating previous date."""
def test_previous_year(self):
"""webcomment - calculate_s... |
import datetime
import random
import unittest
import uuid
from nose.plugins.attrib import attr
import mock
from opaque_keys.edx.locator import CourseLocator, BlockUsageLocator
from xmodule.modulestore import ModuleStoreEnum
from xmodule.x_module import XModuleMixin
from xmodule.modulestore.inheritance import Inherita... |
from openerp.osv import fields, osv
from openerp import tools
from openerp.addons.crm import crm
class project_issue_report(osv.osv):
_name = "project.issue.report"
_auto = False
_columns = {
'section_id':fields.many2one('crm.case.section', 'Sale Team', readonly=True),
'company_id': fields... |
""" Regroup variables for deprecated features.
To keep the OpenERP server backward compatible with older modules, some
additional code is needed throughout the core library. This module keeps
track of those specific measures by providing variables that can be unset
by the user to check if her code is future proof.
In... |
#! /usr/bin/env python
"""Test script for the anydbm module
based on testdumbdbm.py
"""
import os
import unittest
import anydbm
import glob
from test import test_support
_fname = test_support.TESTFN
def _delete_files():
# we don't know the precise name the underlying database uses
# so we use glob to loca... |
class IntegrationHelper:
def __init__(self,
username=None, password=None, sharedKey=None,
certChain=None, privateKey=None,
cryptoID=None, protocol=None,
x509Fingerprint=None,
x509TrustList=None, x509CommonName=None,
settings = None... |
from __future__ import absolute_import
from datetime import datetime
from django.contrib.gis.tests.utils import no_mysql, no_spatialite
from django.contrib.gis.shortcuts import render_to_kmz
from django.db.models import Count
from django.test import TestCase
from .models import City, PennsylvaniaCity, State, Truth
... |
"""
Serialize data to/from JSON
"""
import datetime
from StringIO import StringIO
from django.core.serializers.python import Serializer as PythonSerializer
from django.core.serializers.python import Deserializer as PythonDeserializer
from django.utils import datetime_safe
from django.utils import simplejson
try:
... |
"""Possible actions on an instance.
Actions should probably match a user intention at the API level. Because they
can be user visible that should help to avoid confusion. For that reason they
tend to maintain the casing sent to the API.
Maintaining a list of actions here should protect against inconsistencies when
... |
from couchpotato.core.downloaders.base import Downloader
from couchpotato.core.helpers.encoding import isInt
from couchpotato.core.helpers.variable import cleanHost
from couchpotato.core.logger import CPLog
import json
import requests
import traceback
log = CPLog(__name__)
class Synology(Downloader):
protocol =... |
import platform
import xbmc
import lib.common
from lib.common import log, dialog_yesno
from lib.common import upgrade_message as _upgrademessage
from lib.common import upgrade_message2 as _upgrademessage2
__addon__ = lib.common.__addon__
__addonversion__ = lib.common.__addonversion__
__addonname__ = lib.comm... |
# pylint: disable=missing-docstring
from urlparse import parse_qs, urlparse
import uuid
from django.http import HttpRequest
from mock import patch
from edx_ace import Message, Recipient
from openedx.core.djangoapps.site_configuration.tests.factories import SiteFactory
from student.tests.factories import UserFactory
... |
"""
Command line handling for Cobbler.
Copyright 2008, Red Hat, Inc
Michael DeHaan <<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; either version 2 of the License, or
(at your option) any ... |
import logging
import mock
import a10_neutron_lbaas.a10_exceptions as a10_ex
from a10_neutron_lbaas.tests.unit.v2 import fake_objs
from a10_neutron_lbaas.tests.unit.v2 import test_base
LOG = logging.getLogger(__name__)
def return_one(*args):
return 1
def return_two(*args):
return 2
class TestMembers(te... |
"""
This module contains the spatial lookup types, and the `get_geo_where_clause`
routine for Oracle Spatial.
Please note that WKT support is broken on the XE version, and thus
this backend will not work on such platforms. Specifically, XE lacks
support for an internal JVM, and Java libraries are required to use... |
from ._cffi import ffi, ptop
has_numpy = True
try:
import numpy as np
except ImportError:
has_numpy = False
from .init import (
open,
close,
open_device,
get_device_list,
free_device_list,
)
from .ctrl import (
enable_module,
set_sample_rate,
get_sampling,
set_sampling... |
import numpy as np
from sklearn.ensemble import GradientBoostingRegressor
from random import sample
class RegressionDriver(object):
"""Class for Regression-based analysis of Driver traces"""
def __init__(self, driver, datadict):
"""Initialize by providing a (positive) driver example and a dictionary ... |
"""
Support for the Yahoo! Weather service.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/weather.yweather/
"""
import logging
from datetime import timedelta
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassist... |
import logging
from telemetry.core import util
def _WaitForLoginFormToLoad(backend, login_form_id, tab):
def IsFormLoadedOrAlreadyLoggedIn():
return (tab.EvaluateJavaScript(
'document.querySelector("#%s")!== null' % login_form_id) or
backend.IsAlreadyLoggedIn(tab))
# Wait until the form ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('contacts', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='address',
name='addr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.