code stringlengths 1 199k |
|---|
"""
Course Grading Settings page.
"""
from common.test.acceptance.pages.studio.settings import SettingsPage
from common.test.acceptance.pages.studio.utils import press_the_notification_button
from common.test.acceptance.pages.common.utils import click_css
from selenium.webdriver import ActionChains
from bok_choy.promis... |
from enum import Enum
class InstanceLifecycle(Enum):
ON_DEMAND = "on-demand"
SPOT = "spot"
NA = "N/A" |
import email_extended |
__doc__ = """ Concurrently upload the same large file by two sync clients. It may ne necessary to run mulitple times. In owncloud 5.0.10 this testcase triggers a race condition which is reported in the following way:
2013-11-13 15:54:23,039 - INFO - checker - shared w0d1 af27141daa272ef2285695fe8e709d9f
2013-11-13 15:5... |
import os
import sys
import sphinx
import sphinx.apidoc
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
sys.path.insert(0, os.path.abspath(os.path.join('..', '..')))
import segpy
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.todo',
'sphinx.ext.ifconfig',
'cartouch... |
from . import mrp_production
from . import product |
import argparse
import glob
parser = argparse.ArgumentParser()
parser.add_argument(
'working_dir',
type=str,
metavar='PATH',
help='path to examples working directory',
)
args = parser.parse_args()
files_with_errors = []
for logfile in glob.glob(f"{args.working_dir}/*/output/log/activitysim.log"):
wi... |
"""
Tests for bookmark views.
"""
import ddt
import json
from nose.plugins.attrib import attr
from unittest import skipUnless
import urllib
from django.conf import settings
from django.core.urlresolvers import reverse
from mock import patch
from rest_framework.test import APIClient
from xmodule.modulestore import Modul... |
from django.contrib.auth.decorators import login_required
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from .api import get_backend_class
from .backends.exceptions import NotificationDoesNotExist
from .serializers import NotificationSerial... |
import res_partner |
"""Superdesk Users"""
from superdesk.metadata.item import BYLINE, SIGN_OFF
from superdesk.resource import Resource
class UsersResource(Resource):
def __init__(self, endpoint_name, app, service, endpoint_schema=None):
self.readonly = True if app.config.get('LDAP_SERVER', None) else False
self.additio... |
from spack import *
class Rocthrust(CMakePackage):
"""Thrust is a parallel algorithm library. This library has been ported to
HIP/ROCm platform, which uses the rocPRIM library. The HIP ported
library works on HIP/ROCm platforms"""
homepage = "https://github.com/ROCmSoftwarePlatform/rocThrust"
... |
from spack import *
class Fp16(Package):
"""FP16 is a header-only library for
conversion to/from half-precision floating point formats"""
homepage = "https://github.com/Maratyszcza/FP16/"
url = "https://github.com/Maratyszcza/FP16.git"
version('master', git='https://github.com/Maratyszcza/FP16.... |
import SU2
import os, time, sys, shutil
from optparse import OptionParser
def main():
# Command Line Options
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
help="read config from FILE", metavar="FILE")
parser.add_option("-n", "--partitions", dest="partit... |
from qwt.scale_draw import QwtScaleDraw
from qwt.scale_engine import QwtLinearScaleEngine
from qwt.color_map import QwtLinearColorMap
from qwt.text import QwtText
from qwt.painter import QwtPainter
from qwt.interval import QwtInterval
from qwt.color_map import QwtColorMap
from qwt.qt.QtGui import (QWidget, QSizePolicy,... |
import sys
import os
import re
import io
import traceback
from pybtex.plugin import find_plugin
from pybtex.database import BibliographyData, parse_file
from markdown.preprocessors import Preprocessor
from markdown.util import etree
import logging
log = logging.getLogger(__name__)
class MooseBibtex(Preprocessor):
"""... |
'''
Created on 14 janv. 2015
@author: Remi Cattiau
'''
from nxdrive.engine.workers import EngineWorker, ThreadInterrupt, PairInterrupt
from nxdrive.logging_config import get_logger
from nxdrive.client.common import LOCALLY_EDITED_FOLDER_NAME, UNACCESSIBLE_HASH
from nxdrive.client.common import NotFound
from nxdrive.eng... |
"""Qarbon's main python package."""
from qarbon.release import version as __version__
__all__ = [] |
'''
Created on 2013-04-22 14:54
@summary:
@author: Martin predki
'''
from PySchedGUI.PySchedUI import FileUtils
import os
import readline
import atexit
class PathCompleter(object):
'''
@summary: Implements history path auto completion for all user input
'''
def __init__(self):
history_file = os.... |
""" the slowest set of tests
tests that a schedule set to fire every minute
actually does, without speedup
"""
import time
import logging
from datetime import datetime, timedelta
from rapidsms.tests.scripted import TestScript
import scheduler.app as scheduler_app
from scheduler.models import EventSchedule, ALL
class Te... |
"""HTTP enabled process executor."""
import socket
from mirakuru.compat import HTTPConnection, HTTPException, OK
from mirakuru.compat import urlparse
from mirakuru.tcp import TCPExecutor
class HTTPExecutor(TCPExecutor):
"""Http enabled process executor."""
def __init__(self, command, url, **kwargs):
"""... |
from flask import g, jsonify, request
from functools import wraps
from service import app
from service.errors import (BadRequestError, UnauthorizedError, ForbiddenError,
InternalServerError)
from service.utils import load_auth_client, get_token
def authenticated(fn):
"""Mark a route as r... |
from game import Agent
from game import Actions
from game import Directions
import random
from util import manhattanDistance
import util
class GhostAgent( Agent ):
def __init__( self, index ):
self.index = index
def getAction( self, state ):
dist = self.getDistribution(state)
if len(dist) == 0:
re... |
"""
docs-mail-merge.py (Python 2.x or 3.x)
Google Docs (REST) API mail-merge sample app
"""
from __future__ import print_function
import time
from googleapiclient import discovery
from httplib2 import Http
from oauth2client import client, file, tools
DOCS_FILE_ID = 'YOUR_TMPL_DOC_FILE_ID'
SHEETS_FILE_ID = 'YOUR_SHEET_D... |
"""
OpenFlow1.3 flow table for OFAgent
* requirements
** plain OpenFlow 1.3. no vendor extensions.
* legends
xxx: network id (agent internal use)
yyy: segment id (vlan id, gre key, ...)
a,b,c: tunnel port (tun_ofports, map[net_id].tun_ofports)
i,j,k: vm port (map[net_id].vif_ports[vif_id].ofport)
x,y,z: physic... |
import socket
def check_remote_port_whether_open(remote_addr, remote_port):
""" Check the remote port whether open
:param remote_addr: Remote host's ip address
:param remote_port: Remote host's tcp port
:type remote_addr: string
:type remote_port: int
:return: A boolean value to decide the port ... |
"""
REST API Documentation for the NRS TFRS Credit Trading Application
The Transportation Fuels Reporting System is being designed to streamline compliance reporting for transportation fuel suppliers in accordance with the Renewable & Low Carbon Fuel Requirements Regulation.
OpenAPI spec version: v1
Lic... |
from django.conf.urls import patterns, url
from desktop.lib.django_util import get_username_re_rule, get_groupname_re_rule
username_re = get_username_re_rule()
groupname_re = get_groupname_re_rule()
urlpatterns = patterns('useradmin.views',
url(r'^$', 'list_users'),
url(r'^users/?$', 'list_users'),
url(r'^groups/... |
from distconfig.backends.base import BaseBackend
from distconfig.backends.execution_context import ThreadingExecutionContext
class ConsulBackend(BaseBackend):
"""Consul backend implementation.
:param client: Instance of :class:`consul.Consul`.
:param execution_context: Instance of :class:`distconfig.backend... |
from case import Case
class Case7_3_5(Case):
DESCRIPTION = """Send a close frame with close code and close reason of maximum length (123)"""
EXPECTATION = """Clean close with normal code."""
def init(self):
self.suppressClose = True
def onConnectionLost(self, failedByMe):
Case.onConnectionLost(s... |
import os
from ..constants import FORGE_HOME, RELEASES_URL
FORGE_ROOT = os.environ.get('FORGE_ROOT', FORGE_HOME)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(FORGE_ROOT, 'forge.db'),
}
}
SITE_ID = 1
TIME_ZONE = 'America/Los_Angeles'
MEDIA_ROOT = os.path... |
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 'WishListItem'
db.create_table('market_buy_wishlistitem', (
('id', self.gf('django.db.models.fields.AutoFiel... |
from __future__ import print_function
import argparse
import random
import mxnet as mx
import numpy as np
from mxnet import gluon, init
from mxnet import autograd as ag
from mxnet.gluon import nn
from mxnet.gluon.data.vision import transforms
from gluoncv.model_zoo import get_model
from gluoncv.data import transforms a... |
"""
A module that contains the content-based recommender LDARecommender that uses
LDA.
"""
from lib.content_based import ContentBased
from overrides import overrides
from sklearn.decomposition import LatentDirichletAllocation
class LDARecommender(ContentBased):
"""
LDA Recommender, a content based recommender t... |
from datetime import date
from django.core.management.base import BaseCommand
import logging
from actions.models import Action
from applications.models import Referral
logger = logging.getLogger('statdev')
class Command(BaseCommand):
help = 'Iterates over current referrals to resolve those past their expiry date'
... |
"""
Module holds base stuff regarding JMX format
Copyright 2015 BlazeMeter Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applic... |
"""Tests for Philips Hue config flow."""
import asyncio
from aiohttp import client_exceptions
import aiohue
from aiohue.discovery import URL_NUPNP
import pytest
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.components import ssdp
from homeassistant.components.hue import config_flo... |
from a10sdk.common.A10BaseClass import A10BaseClass
class FilterCfg(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param dport1: {"description": "Forward Destination Port", "format": "number", "maximum": 65535, "minimum": 1, "not": "dport2", "type": "number"}
:param source... |
__author__ = 'Administrator'
import json
from heat.engine.resources.hwcloud.hws_service import HWSService
class EVSService(HWSService):
def __init__(self, ak, sk, region, protocol, host, port):
super(EVSService, self).__init__(ak, sk, 'EVS', region, protocol, host, port)
def list(self, project_id, opts=... |
"""Provide some handy classes for user to implement a simple computation module
in Python easily.
"""
import logging
from .base_module import BaseModule
from ..initializer import Uniform
from .. import ndarray as nd
class PythonModule(BaseModule):
"""A convenient module class that implements many of the module APIs... |
"""
Copyright (c) 2006-2016 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
from lib.core.data import kb
from lib.request.connect import Connect as Request
def getPageTemplate(payload, place):
retVal = (kb.originalPage, kb.errorIsNone)
if payload and place:
i... |
import argparse
import sys
from typing import Any
from django.core import validators
from django.core.exceptions import ValidationError
from django.core.management.base import CommandError
from django.db.utils import IntegrityError
from zerver.lib.actions import do_create_user
from zerver.lib.initial_password import in... |
"""
A driver for XenServer or Xen Cloud Platform.
**Variable Naming Scheme**
- suffix "_ref" for opaque references
- suffix "_uuid" for UUIDs
- suffix "_rec" for record objects
"""
import math
from os_xenapi.client import session
from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_uti... |
from datetime import datetime, timedelta
import json
import logging
import os
from botocore.exceptions import ClientError
import boto3
def bucket_info(c, bucket):
result = {'Bucket': bucket}
response = c.get_metric_statistics(
Namespace='AWS/S3',
MetricName='NumberOfObjects',
Dimensions=[
... |
import unittest
class TestClient(unittest.TestCase):
@staticmethod
def _get_target_class():
from google.cloud.translate import Client
return Client
def _make_one(self, *args, **kw):
return self._get_target_class()(*args, **kw)
def test_constructor(self):
from google.cloud... |
'''
Created on May 29, 2013
@author: vieglais
Copied directly from:
http://asimpleweblog.wordpress.com/2010/06/20/julian-date-calculator/
'''
import math
import datetime
import pytz
MJD0 = 2400000.5 # 1858 November 17, 00:00:00 hours
def base60_to_decimal(xyz,delimiter=None):
"""Decimal value from numbers in sexage... |
import subprocess
import re
import shutil
import os
from os.path import exists, join, split, splitext, normpath, abspath
def ensuredir(path):
if not exists(path):
os.makedirs(path)
def _cmd(*args):
print(' '.join(args))
return subprocess.check_output(args)
def extract_dependent_dylibs(dylib_fpath, f... |
try:
import json
except ImportError:
import simplejson as json
from cm_api.endpoints.types import *
__docformat__ = "epytext"
EXTERNAL_ACCOUNT_PATH = "/externalAccounts/%s"
EXTERNAL_ACCOUNT_FETCH_PATH = "/externalAccounts/%s/%s"
EXTERNAL_ACCOUNT_CONFIG_FETCH_PATH = "/externalAccounts/account/%s"
def get_supported_c... |
from zion.handlers import BaseHandler
from zion.handlers.base import NotFunctionRequest
from swift.common.utils import public
import time
class ComputeHandler(BaseHandler):
def __init__(self, request, conf, app, logger, redis):
super(ComputeHandler, self).__init__(
request, conf, app, logger, re... |
"""Constants for the AVM FRITZ!SmartHome integration."""
from __future__ import annotations
import logging
from typing import Final
ATTR_STATE_BATTERY_LOW: Final = "battery_low"
ATTR_STATE_DEVICE_LOCKED: Final = "device_locked"
ATTR_STATE_HOLIDAY_MODE: Final = "holiday_mode"
ATTR_STATE_LOCKED: Final = "locked"
ATTR_STA... |
from eventlet import greenthread
import mock
from oslo_concurrency import processutils
from six.moves.urllib import error as url_error # pylint: disable=E0611
from six.moves.urllib import request as url_request # pylint: disable=E0611
from manila import exception
from manila.share import configuration as conf
from ma... |
"""Provides methods to bootstrap a home assistant instance."""
import asyncio
import logging
import logging.handlers
import os
import sys
from time import time
from collections import OrderedDict
from typing import Any, Optional, Dict
import voluptuous as vol
import homeassistant.components as core_components
from home... |
from oslo.config import cfg
from nova.compute import power_state
from nova.compute import rpcapi as compute_rpcapi
from nova.compute import utils as compute_utils
from nova import db
from nova import exception
from nova.i18n import _
from nova import image
from nova import objects
from nova.openstack.common import log ... |
import unittest
import random, sys, time, re
sys.path.extend(['.','..','py'])
import h2o, h2o_cmd, h2o_hosts, h2o_browse as h2b, h2o_import as h2i, h2o_glm, h2o_util, h2o_rf, h2o_pca, h2o_jobs as h2j
class Basic(unittest.TestCase):
def tearDown(self):
h2o.check_sandbox_for_errors()
@classmethod
def ... |
from django.conf.urls import patterns, url
urlpatterns = patterns('moocng.externalapps.views',
#url(r'^$', 'externalapps_index', name='externalapps_index'),
url(r'^add/',
'externalapps_add_or_edit',
name='externalapps_add'),
url(r'^(?P<external_app_id>\d+)/edit/$',
'externalapps_add_... |
"""Test the Broadlink config flow."""
import errno
import socket
import broadlink.exceptions as blke
import pytest
from homeassistant import config_entries
from homeassistant.components.broadlink.const import DOMAIN
from . import get_device
from tests.async_mock import call, patch
DEVICE_DISCOVERY = "homeassistant.comp... |
from django.core.urlresolvers import reverse_lazy
from django.http import JsonResponse
from django.shortcuts import redirect, render
from django.views.generic import CreateView, ListView, DetailView, TemplateView
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decora... |
"""Some common utilities for tools to use."""
import codecs
import contextlib
import glob
import logging
import os
import os.path as path
import re
import shutil
import subprocess
import sys
import time
import zipfile
from nototools import notoconfig
@contextlib.contextmanager
def temp_chdir(path):
"""Usage: with t... |
from __future__ import print_function
import logging
import sys
from commands import *
import time
import argparse
from crawler import Crawler
from cleaner import Cleaner
from clients import RBTJIRAClient
from commit import Committer
from post_review import ReviewPoster
from test_patch import PatchTester
possible_optio... |
"""
Scripts to help load the movielens dataset into Python classes
"""
import re
class User:
def __init__(self, id, age, sex, occupation, zip):
self.id = int(id)
self.age = int(age)
self.sex = sex
self.occupation = occupation
self.zip = zip
self.avg_r = 0.0
class Item... |
import logging
import re
from streamlink.exceptions import PluginError
from streamlink.plugin import Plugin
from streamlink.plugin.api import validate
from streamlink.plugin.api.utils import parse_json
from streamlink.stream import HLSStream
log = logging.getLogger(__name__)
class StreamMe(Plugin):
_url_re = re.com... |
import nose
from angr import SimState, SIM_PROCEDURES
FAKE_ADDR = 0x100000
def test_calling_conventions():
#
# SimProcedures
#
from angr.calling_conventions import SimCCCdecl
args = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 1000, 100000, 1000000, 2000000, 14, 15, 16 ]
arches = [
('X86', SimCCCdecl),
... |
import os
import codecs
from django.core.urlresolvers import reverse
from onadata.apps.main.tests.test_base import TestBase
from onadata.apps.logger.models import Attachment
from onadata.apps.logger.models import Instance
from onadata.apps.logger.models import XForm
from onadata.apps.logger.views import submission
clas... |
import numpy as np
import pycuda.gpuarray as gpuarray
import pycuda.driver as drv
import scipy.linalg
import tps
from lfd.tpsopt.culinalg_exts import gemm, get_gpu_ptrs, dot_batch_nocheck
class NoGPUTPSSolver(object):
"""
class to fit a thin plate spline to data using precomputed
matrix products
"""
... |
import os, sys, cPickle
import wx # ensure this import works before starting the application
import matplotlib # ensure this import works before starting the application
if -1 != sys.path[0].find('pyeq2-master'):raise Exception('Please rename git checkout directory from "pyeq2-master" to "pyeq2"')
exampleFileDirectory ... |
"""
This package collects functions useful for studying chemical kinetics problems.
"""
from .rates import MassAction, EyringHS
from .eyring import EyringParam
from .arrhenius import ArrheniusParam |
from __future__ import print_function
import unittest2
from lldbsuite.test.decorators import *
from lldbsuite.test.concurrent_base import ConcurrentEventsBase
from lldbsuite.test.lldbtest import TestBase
@skipIfWindows
class ConcurrentWatchBreakDelay(ConcurrentEventsBase):
mydir = ConcurrentEventsBase.compute_mydir... |
"""Utilities to build feature vectors from text documents"""
import re
import unicodedata
import numpy as np
import scipy.sparse as sp
from ..base import BaseEstimator, TransformerMixin
from ..preprocessing import normalize
from ..utils.fixes import Counter
ENGLISH_STOP_WORDS = set([
"a", "about", "above", "across"... |
__author__ = 'robert'
from pypet.tests.testutils.ioutils import make_temp_dir
import tables as pt
import tables.parameters
import os
import time
def create_children_dfs(hdf5_file, group_node, current_children):
if len(current_children) == 0:
return 1
nchildren = current_children[0]
child_count = 0
... |
"""
ABIDE2BIDS download tool.
"""
import errno
import json
import os
import os.path as op
import shutil
import subprocess as sp
import tempfile
from argparse import ArgumentParser, RawTextHelpFormatter
from multiprocessing import Pool
from typing import Tuple
from xml.etree import ElementTree as et
import numpy as np
f... |
from imageviewer import ImageViewerCell, ImageFileToSpreadsheet
def widgetName():
""" widgetName() -> str
Return the name of this widget plugin
"""
return 'Image Viewer'
def registerWidget(reg, basicModules, basicWidgets):
""" registerWidget(reg: module_registry,
basicModules:... |
import json
import os
import tempfile
from django.conf import settings
from django.core.files.storage import default_storage as storage
from django.utils.encoding import smart_unicode
import mock
from nose import SkipTest
from nose.tools import eq_, ok_
from PIL import Image
from pyquery import PyQuery as pq
from tower... |
import os
def get_package_data():
paths_test = [os.path.join('data', '*.txt')]
return {'astroquery.ogle.tests': paths_test} |
import rospy
import random
import genmsg.msgs
import genpy.dynamic
def get_sub_defs(msg_fqn, msg_txt):
def_dict = {}
defs = msg_txt.split("\n" + "="*80 + "\n")
def_dict[msg_fqn] = defs[0]
for d in defs[1:]:
lines = d.splitlines()
if not lines[0].startswith("MSG: "):
raise Exc... |
from rest_framework import serializers
from commons.serializers import (TimeStampedSerializerMixin, MetaDataSerializer,
IdSerializerMixin, TitleSerializerMixin,
IdTitleSerializerMixin)
from .fields import NoteResourceUriField
from commons.fields import U... |
'''
To run a Bokeh application on a Bokeh server from a single Python script,
pass the script name to ``bokeh serve`` on the command line:
.. code-block:: sh
bokeh serve app_script.py
By default, the Bokeh application will be served by the Bokeh server on a
default port ({DEFAULT_PORT}) at localhost, under the path... |
from django.contrib import admin
from connect.moderation.models import ModerationLogMsg
admin.site.register(ModerationLogMsg) |
"""
from https://gist.github.com/bwhite/3726239
Information Retrieval metrics
Useful Resources:
http://www.cs.utexas.edu/~mooney/ir-course/slides/Evaluation.ppt
http://www.nii.ac.jp/TechReports/05-014E.pdf
http://www.stanford.edu/class/cs276/handouts/EvaluationNew-handout-6-per.pdf
http://hal.archives-ouvertes.fr/docs/... |
import unittest
from mongolite import Connection, Document, OperationFailure, BadIndexError, INDEX_GEO2D, INDEX_ASCENDING, INDEX_DESCENDING
class IndexTestCase(unittest.TestCase):
def setUp(self):
self.connection = Connection(safe=True)
self.col = self.connection['test']['mongolite']
def tearDow... |
from pythran.tests import TestEnv
from pythran.typing import *
class TestCopperhead(TestEnv):
def test_saxpy(self):
self.run_test(
"def saxpy(a, x, y): return list(map(lambda xi, yi: a * xi + yi, x, y))",
1.5, [1,2,3], [0.,2.,4.],
saxpy=[float, List[int], List[float]])
... |
"""
This module adds several functions for interactive source code inspection.
"""
import inspect
from sympy.core.compatibility import callable
def source(object):
"""
Prints the source code of a given object.
"""
print 'In file: %s' % inspect.getsourcefile(object)
print inspect.getsource(object)
de... |
from clone_stmt import CloneStmt
from clone_function import CloneFunction
from dead_code_elim import DCE
from inline import Inliner
from phase import Phase
from simplify import Simplify
from subst import subst_expr, subst_expr_list, subst_expr_tuple, subst_stmt_list
from transform import Transform |
"""Snapshot Build Bisect Tool
This script bisects a snapshot archive using binary search. It starts at
a bad revision (it will try to guess HEAD) and asks for a last known-good
revision. It will then binary search across this revision range by downloading,
unzipping, and opening Chromium for you. After testing the spec... |
import os
import tempfile
import base64
import traceback
from OpenSSL import crypto
import M2Crypto
from M2Crypto import X509
from tempfile import mkstemp
from sfa.util.sfalogging import logger
from sfa.util.namespace import urn_to_hrn
from sfa.util.faults import *
def convert_public_key(key):
keyconvert_path = "/u... |
from unittest import TestCase, expectedFailure
class TuringTests(TestCase):
def setUp(self):
from chatterbot import ChatBot
self.chatbot = ChatBot('Agent Jr.')
@expectedFailure
def test_ask_name(self):
response = self.chatbot.get_response(
'What is your name?'
)
... |
import sys
from SimpleXMLRPCServer import SimpleXMLRPCServer
class EngineRPCServer(SimpleXMLRPCServer):
def __init__(self, addr, interpreter, namespace):
SimpleXMLRPCServer.__init__(self, addr)
self.user_namespace = namespace
self._interpreter = interpreter
self.interpreter = self._i... |
'''
Goal: test functions in utils.py
'''
import os
import time
from app import utils
from .base_test import BaseTestCase
class UtilsTests(BaseTestCase):
def test_create_salt(self):
'''
Verify the remote address reading
https://realpython.com/blog/python/python-web-applications-with-flask-par... |
from django.db import models
from django_dms.models import DocumentBase
class Document(DocumentBase):
""" Basic document entry, with a selected metadata.
"""
title = models.CharField(max_length=150, default="", blank=True)
slug = models.SlugField(unique=True)
summary = models.Tex... |
"""Provide a TestCase base class for PageTest subclasses' unittests."""
import unittest
from telemetry import benchmark
from telemetry.core import exceptions
from telemetry.core import util
from telemetry.page import page as page_module
from telemetry.page import page_set as page_set_module
from telemetry.page import p... |
from PyQt4.QtCore import pyqtSignal, Qt, QTimer
from PyQt4.QtGui import QProgressDialog
from . import job, performer
class Progress(QProgressDialog, performer.ThreadedJobPerformer):
finished = pyqtSignal(['QString'])
def __init__(self, parent):
flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.Wi... |
from collections import defaultdict
from django.test import SimpleTestCase as TestCase
from corehq.apps.app_manager.commcare_settings import parse_condition_string, check_condition, circular_dependencies, SETTINGS, SETTINGS_LOOKUP
from corehq.apps.app_manager.models import Application
class CommCareSettingsTest(TestCas... |
import sys
import re
if sys.argv[1] == "-":
file = sys.stdin
else:
file = open( sys.argv[1], 'r' )
int_re = re.compile("^[0-9]")
var_map = {}
party_mode = 0
could_be_local = {}
local_lines = { 1 : "", 2: "" }
neutral = {}
linenum = 0
for line in file.xreadlines():
args = line.split()
linenum += 1
if... |
from __future__ import unicode_literals, division, absolute_import
import logging
import re
from datetime import datetime, timedelta
from dateutil.parser import parse as parsedate
from flexget.utils.titles.parser import TitleParser, ParseWarning
from flexget.utils import qualities
from flexget.utils.tools import ReList... |
import sys, re, os, time, traceback, subprocess
import pickle
from ..Qt import QtCore, QtGui, QT_LIB
from ..python2_3 import basestring
from .. import exceptionHandling as exceptionHandling
from .. import getConfigOption
if QT_LIB == 'PySide':
from . import template_pyside as template
elif QT_LIB == 'PySide2':
... |
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import render
from bootcamp.activities.models import Notification
from bootcamp.decorators import ajax_required
@login_required
def notifications(request):
user = request.user
notifications = Not... |
"""
Django-environ allows you to utilize 12factor inspired environment
variables to configure your Django application.
"""
from __future__ import unicode_literals
import os
import sys
import re
import json
import warnings
import logging
logger = logging.getLogger(__file__)
try:
from django.core.exceptions import Im... |
import dbus
from dbus.mainloop.glib import DBusGMainLoop
from gettext import gettext as _
from plugins.rfid.rfidutils import strhex2bin, strbin2dec, find_device
from plugins.plugin import Plugin
from TurtleArt.tapalette import make_palette
from TurtleArt.tautils import debug_output
from TurtleArt.taprimitive import Pri... |
""" Sahana Eden Automated Test - HRM001 Create Staff
@copyright: 2011-2012 (c) Sahana Software Foundation
@license: MIT
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
... |
"""Test that the wallet resends transactions periodically."""
from collections import defaultdict
import time
from test_framework.blocktools import create_block, create_coinbase
from test_framework.messages import ToHex
from test_framework.mininode import P2PInterface, mininode_lock
from test_framework.test_framework i... |
import socket, string, re, select, errno
from structure import Structure
from random import randint
from struct import *
import time
CVS_REVISION = '$Revision: 526 $'
INADDR_ANY = '0.0.0.0'
BROADCAST_ADDR = '<broadcast>'
NETBIOS_NS_PORT = 137
NETBIOS_SESSION_PORT = 139
SMB_SESSION_PORT = 445
NODE_B = 0x0000
NODE_P = 0x... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.