content stringlengths 4 20k |
|---|
"""Test node responses to invalid transactions.
In this test we connect to one node over p2p, and test tx requests.
"""
from test_framework.test_framework import ComparisonTestFramework
from test_framework.comptool import TestManager, TestInstance, RejectResult
from test_framework.blocktools import *
import time
#... |
"""SCons.Tool.mslib
Tool-specific initialization for lib (MicroSoft library archiver).
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, ... |
"""Autoscaler/IGM/InstanceTemplate multiversion test."""
import compute_constants
import compute_resource_util
from compute_resource_util import ComputeResource
from compute_resource_util import Resources
def GenerateConfig(context):
"""Generate template config based on python objects."""
compute_resource_util.Se... |
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline ... |
#!/usr/bin/env python
#
# Test cases for tournament.py
from tournament import *
def testDeleteMatches():
deleteMatches()
print "1. Old matches can be deleted."
def testDelete():
deleteMatches()
deletePlayers()
print "2. Player records can be deleted."
def testCount():
deleteMatches()
d... |
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the relevant file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f... |
#!/usr/bin/python3
from netsnmp._api import get_async
from async_devtypes import SNMP_DEVTYPES
#import cx_Oracle
import zmq
import redis, hiredis
import logging, logging.handlers
import random, sys, threading, time
import multiprocessing as mp
# Python 2 support
try:
import queue
except:
import Queue as queue... |
import os
import zipfile
import shutil
from mxnet.test_utils import download
zip_file_path = 'models/msgnet_21styles.zip'
download('https://apache-mxnet.s3-accelerate.amazonaws.com/gluon/models/msgnet_21styles-2cb88353.zip', zip_file_path)
with zipfile.ZipFile(zip_file_path) as zf:
zf.extractall()
os.remove(... |
import unittest
from coalib.bearlib.languages.documentation.DocstyleDefinition import (
DocstyleDefinition)
from coalib.bearlib.languages.documentation.DocumentationComment import (
DocumentationComment)
from coalib.bearlib.languages.documentation.DocBaseClass import (
DocBaseClass)
from tests.bearlib.lang... |
from bs4 import BeautifulSoup
from django.test import TestCase
from wagtail.wagtailcore.whitelist import (
check_url,
attribute_rule,
allow_without_attributes,
Whitelister
)
class TestCheckUrl(TestCase):
def test_allowed_url_schemes(self):
for url_scheme in ['', 'http', 'https', 'ftp', 'ma... |
from parsl.config import Config
from parsl.data_provider.data_manager import default_staging
from parsl.data_provider.globus import GlobusStaging
from parsl.executors.threads import ThreadPoolExecutor
# If you are a developer running tests, make sure to update parsl/tests/configs/user_opts.py
# If you are a user copyi... |
#!/usr/bin/env python
# PySCUBA/src/PySCUBA/Tree_classes.py
# Affiliation: Harvard University
# Contact: <EMAIL>; <EMAIL>
"""Classes for flow or mass cytometry data processing, modified from the outdated 'fcm'
Python package by Jacob Frelinger.
"""
import re
import numpy as np
__all__ = ['Tree']
class ... |
from api.decorators import api_view, request_data_defaultdc, setting_required
from api.permissions import IsSuperAdmin
from api.accounts.permission.api_views import PermissionView
__all__ = ('permission_list', 'permission_manage')
@api_view(('GET',))
@request_data_defaultdc(permissions=(IsSuperAdmin,))
@setting_requ... |
from __future__ import unicode_literals
import datetime
import re
import uuid
from django.conf import settings
from django.db.backends.base.operations import BaseDatabaseOperations
from django.db.backends.utils import truncate_name
from django.utils import six, timezone
from django.utils.encoding import force_bytes, ... |
# -*- 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 field 'Configuration.value_number'
db.add_column(u'projects_configuration', 'value_number',
... |
#!/usr/bin/env python
import os
import optparse
import sys
import re
from pip.exceptions import InstallationError, CommandError, PipError
from pip.log import logger
from pip.util import get_installed_distributions, get_prog
from pip.vcs import git, mercurial, subversion, bazaar # noqa
from pip.baseparser import crea... |
"""
University of California, Irvine (UCI) Bag-of-Words format.
http://archive.ics.uci.edu/ml/datasets/Bag+of+Words
"""
from __future__ import with_statement
import logging
from collections import defaultdict
from gensim import utils
from gensim.corpora import Dictionary
from gensim.corpora import IndexedCorpus
fro... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import traceback
from ansible.module_utils.basic import AnsibleModule
from ansible.module_ut... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from warnings import catch_warnings
import numpy as np
from pandas import DataFrame, Series, MultiIndex, Panel
import pandas as pd
import pandas.util.testing as tm
from pandas.tests.frame.common import TestData
class TestDataFrameSubclassing(TestData):... |
#!/usr/bin/env python
# coding=utf8
"""
Created on 2014年2月15日
@author: liaoqiqi
"""
myfile = open("url_resrouces.txt")
lines = myfile.readlines()
print "use disconf;"
print 'delete from role_resource;'
for line in lines:
line = line.strip('\n')
if not line:
continue
if line[0] == '#':
... |
#!/usr/bin/env python
"""
test_ssh_connect: verify ssh connectivity
test_config_mode: verify enter config mode
test_commit_base: test std .commit()
test_commit_confirm: test commit with confirm
test_confirm_delay: test commit-confirm with non-std delay
test_no_confirm: test commit-confirm with no confirm
test_commit_ch... |
"""Top-level presubmit script for V8.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into gcl.
"""
import sys
_EXCLUDED_PATHS = (
r"^test[\\\/].*",
r"^testing[\\\/].*",
r"^third_party[\\\/].*",
r"^tools[\\\/].*",
)
# Regul... |
"""Component for the Somfy MyLink device supporting the Synergy API."""
import asyncio
import logging
from somfy_mylink_synergy import SomfyMyLinkSynergy
import voluptuous as vol
from homeassistant.components.cover import ENTITY_ID_FORMAT
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeas... |
# Django settings for demoproject project.
import djcelery
djcelery.setup_loader()
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', '<EMAIL>'),
)
CELERY_RESULT_BACKEND = "database"
BROKER_HOST = "localhost"
BROKER_PORT = 5672
BROKER_USER = "guest"
BROKER_PASSWORD = "guest"
BROKER_VHOST = "/"
MANAG... |
"""Verify interface implementations
$Id: verify.py 110699 2010-04-09 08:16:17Z regebro $
"""
from zope.interface.exceptions import BrokenImplementation, DoesNotImplement
from zope.interface.exceptions import BrokenMethodImplementation
from types import FunctionType, MethodType
from zope.interface.interface import from... |
# -*- encoding: utf-8 -*-
import sys
import unittest
from PyQt4 import QtGui
import pilasengine
class TestIniciar(unittest.TestCase):
app = QtGui.QApplication(sys.argv)
def setUp(self):
self.pilas = pilasengine.iniciar()
def testPuedeDeshabilitarTodosLosModos(self):
self.pilas.depurador... |
import termios
import sys
import os
import time
from common.text_opts import *
from common import trex_stats
from client_utils import text_tables
from collections import OrderedDict
import datetime
class SimpleBar(object):
def __init__ (self, desc, pattern):
self.desc = desc
self.pattern = pattern
... |
def main(request, response):
"""Code for generating large responses where the actual response data
isn't very important.
Two request parameters:
size (required): An integer number of bytes (no suffix) or kilobytes
("kb" suffix) or megabytes ("Mb" suffix).
string (optional): The... |
"""
WSGI config for registerAPI project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATIO... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import traceback
try:
import pyodbc
except ImportError:
pyodbc_found = False
else:... |
"""Generates the appropriate build.json data for all the bad_client tests."""
import collections
import yaml
TestOptions = collections.namedtuple('TestOptions', 'flaky cpu_cost')
default_test_options = TestOptions(False, 1.0)
# maps test names to options
BAD_CLIENT_TESTS = {
'badreq': default_test_options,
... |
import sys
import unittest
from telemetry.core import exceptions
class TestOutputStream(object):
def __init__(self):
self.output_data = []
def write(self, data):
assert isinstance(data, str)
self.output_data.append(data)
def flush(self):
pass
class BaseTestResultsUnittest(unittest.TestCase... |
#!/usr/bin/python
import sys
def find_gcode_line(lines, code, layer_height = None, retract_lift = None, reverse = False):
for line in reversed(lines) if reverse else lines:
if(code in line):
if(layer_height == retract_lift and lines[lines.index(line)] == lines[lines.index(line)+2]):
continue
... |
import agents as ag
import envgui as gui
import random
# ______________________________________________________________________________
loc_A, loc_B = (1, 1), (2, 1) # The two locations for the Vacuum world
def RandomVacuumAgent():
"Randomly choose one of the actions from the vacuum environment."
p = ag.Ra... |
import os
import sys
import struct
import datetime
# To use this script you will need to have installed package python-pyside which
# provides LGPL-licensed Python bindings for Qt. You will also need the package
# libqt4-sql-sqlite for Qt sqlite3 support.
#
# An example of using this script with Intel PT:
#
# $ perf ... |
from sympy.core import S, C, sympify
from sympy.core.basic import Basic
from sympy.core.containers import Tuple
from sympy.core.operations import LatticeOp, ShortCircuit
from sympy.core.function import Application, Lambda
from sympy.core.expr import Expr
from sympy.core.singleton import Singleton
class IdentityFunctio... |
from __future__ import absolute_import
import unittest
from xosgenx.generator import XOSProcessor, XOSProcessorArgs
from helpers import XProtoTestHelpers, FakeObject
import pdb
"""The function below is for eliminating warnings arising due to the missing policy_output_validator,
which is generated and loaded dynamicall... |
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
"""
Test that we can generate Visual Studio 9.0 project (.vcproj) and
solution (.sln) files that contain SCC information and look correct.
"""
import os
import TestSConsMSVS
test = TestSConsMSVS.TestSConsMSVS()
# Make the test infrastructure think we ha... |
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rcParams['axes.titlesize'] = 20
mpl.rcParams['xtick.labelsize'] = 16
mpl.rcParams['ytick.labelsize'] = 16
mpl.rcParams['axes.labelsize'] = 16
mpl.rcParams['xtick.major.size'] = 0
mpl.rcParams['ytick.major.size'] = 0
# 包含了狗,猫和猎豹的最高奔跑速度,还有对... |
# -*- coding:utf-8 -*-
# Import default settings from memopol core
# Then override if needed
from memopol.base.default_settings import * # pylint: disable=W0614,W0401
#==============================================================================
# Generic Django project settings
#===================================... |
import ast # for string-to-data conversion
import math
import sys
import copy
from PyQt4 import QtGui, QtCore
import pyaudio
import wave
class AudioTrack:
def __init__(*args, **kwargs):
self = args[0]
self._parent = args[1]
self.scene = self._parent.scene
# note: ... |
import json
import urllib
from sys import exit as sys_exit
# Derived from region_data_constants.cc.
_COUNTRIES = [
'AD', 'AE', 'AF', 'AG', 'AI', 'AL', 'AM', 'AN', 'AO', 'AQ', 'AR', 'AS',
'AT', 'AU', 'AW', 'AX', 'AZ', 'BA', 'BB', 'BD', 'BE', 'BF', 'BG', 'BH',
'BI', 'BJ', 'BL', 'BM', 'BN', 'BO', 'BR', 'BS',... |
import misc
import namearray
import util
import wx
# NameArray, or None if not loaded
nameArr = None
# if not already loaded, read the name database from disk and store it.
# returns False on errors.
def readNames(frame):
global nameArr
if nameArr:
# already loaded
return True
try:
... |
from django.db.models.signals import post_syncdb, post_save, pre_delete
from django.dispatch import receiver
from south.signals import post_migrate
from django.conf import settings
from footprint.main.policy.setup_scenario_policy import get_dev_acres
import models
from footprint.main.lib.functions import merge
from fo... |
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.utm_utils import UTM, UTMModule
from ansible.module_utils._text import to_native
def main(... |
"""
NetApp Data ONTAP cDOT single-SVM storage driver library.
This library extends the abstract base library and completes the single-SVM
functionality needed by the cDOT single-SVM Manila driver. This library
variant uses a single Data ONTAP storage virtual machine (i.e. 'vserver')
as defined in manila.conf to provi... |
from flask import Blueprint
from ggrc import settings
from ggrc.app import app
from ggrc.rbac import permissions
from ggrc.services.registry import service
from ggrc.views.registry import object_view
import ggrc_risk_assessments.models as models
# Initialize Flask Blueprint for extension
blueprint = Blueprint(
'ris... |
"""
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 la... |
from jinja2 import BaseLoader, TemplateNotFound
class ObjectLoader(BaseLoader):
def get_source(self, environment, obj):
return obj, None, None
class VarParser():
@staticmethod
def parse_kv_strings_to_dict(*args):
"""
Parse 1 or more string/dict objects containing template
variables in a final ... |
from neutron.api.v2 import attributes as attrs
from neutron.common import utils
from neutron.db import common_db_mixin
from neutron.db import portsecurity_db_common as ps_db_common
from neutron.extensions import portsecurity as psec
from neutron.i18n import _LI
from neutron.plugins.ml2 import driver_api as api
from osl... |
import threading
from threading import Thread
import time
import argparse
from pexpect import pxssh
import nmap
Found = False
Fails = 0
maxConnections = 5
connection_lock = threading.BoundedSemaphore(maxConnections)
def nmapScan(tgtHost):
nmapScan = nmap.PortScanner()
nmapScan.scan(tgtHost, '22')
state = nmapScan... |
"""
==========================
SGD: convex loss functions
==========================
A plot that compares the various convex loss functions supported by
:class:`sklearn.linear_model.SGDClassifier` .
"""
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
def modified_huber_loss(y_true, y_pred):
z ... |
"""Tests for parsing_utils.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.estimator.canned import parsing_utils
from tensorflow.python.feature_column import feature_column as fc
from tensorflow.python.framework import dtypes
f... |
import os, time, fnmatch, socket, errno
from os.path import isdir, isfile, join, exists, splitext, basename, realpath
import whisper
from graphite.remote_storage import RemoteStore
from django.conf import settings
try:
import rrdtool
except ImportError:
rrdtool = False
try:
import gzip
except ImportError:
gzi... |
"""Utilities to clip weights."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.gan.python.features.python import clip_weights_impl
# pylint: disable=wildcard-import
from tensorflow.contrib.gan.python.features.python.clip_weights_im... |
from __future__ import division
import random
import math
from common import prerun_each_obj
from model.helpers.candidate import Candidate
from helpers.a12 import a12
""" This contains the optimizers """
def de(model, frontier_size=10, cop=0.5, ea=0.5, repeat=100, threshold=0.01, era_size=10, era0=None, lives=5):
... |
#!/usr/bin/env python
#
# This python file contains utility scripts to manage Django translations.
# It has to be run inside the django git root directory.
#
# The following commands are available:
#
# * update_catalogs: check for new strings in core and contrib catalogs, and
# output how much string... |
import os
import unittest
from unittest import skipUnless
from django.contrib.gis.gdal import HAS_GDAL
from ..test_data import TEST_DATA, TestDS, get_ds_file
if HAS_GDAL:
from django.contrib.gis.gdal import DataSource, Envelope, OGRGeometry, GDALException, OGRIndexError, GDAL_VERSION
from django.contrib.gis.... |
__all__ = ['lex','yacc'] |
import os
from telemetry.core import util
from telemetry.unittest_util import tab_test_case
class MemoryCacheHTTPServerTest(tab_test_case.TabTestCase):
def setUp(self):
super(MemoryCacheHTTPServerTest, self).setUp()
self._test_filename = 'bear.webm'
_test_file = os.path.join(util.GetUnittestDataDir(), ... |
# -*- coding: utf-8 -*-
import mock
from nose.tools import * # noqa
from framework.auth.core import Auth
from framework.exceptions import PermissionsError
from tests.base import OsfTestCase
from tests.factories import UserFactory, ProjectFactory
from website.addons.zotero.tests.factories import (
ZoteroAccountF... |
"""Extensions to allow HTTPS requests with SSL certificate validation."""
import httplib
import re
import socket
import ssl
import vulpo
class InvalidCertificateException(httplib.HTTPException):
"""Raised when a certificate is provided with an invalid hostname."""
def __init__(self, host, cert, reason):
"""... |
#!/usr/bin/env python
''' fit best estimate of magnetometer offsets from ArduCopter flashlog
using the algorithm from Bill Premerlani
'''
import sys, time, os, math
# command line option handling
from optparse import OptionParser
parser = OptionParser("magfit_flashlog.py [options]")
parser.add_option("--verbose", ac... |
"""This module is an abstract layer over subprocess.Popen
It gives you highlevel control about how processes are run.
Example:
run = Runner(logfunc=print)
run('sleep 2', wait=True) # waits until the process exists
run(['ls', '--help'], flags='p') # pipes output to pager
run() # pr... |
"""
Tools for generating forms based on Django models.
"""
from wtforms import fields as f
from wtforms import Form
from wtforms import validators
from wtforms.compat import iteritems
from wtforms.ext.django.fields import ModelSelectField
__all__ = (
'model_fields', 'model_form',
)
class ModelConverterBase(obje... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import mechanize
import cookielib
import re
from time import sleep
from daemonize import daemonize
from time import gmtime, strftime
#creates a browser
br = mechanize.Browser()
url = 'http://www.gokano.com'
email = '<EMAIL>'
password = 'xxx'
@daemonize(stdout='gokan... |
import ImportData
import numpy as np
import CoulombMatrix
import cProfile, pstats, StringIO
import time
from datetime import datetime
import matplotlib.pyplot as plt
def fft_idx(X, k):
"""
This function does something.
:param X: parameter X
:param k: parameter k
:return: returns training indexes
... |
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 DownloadFile(Choreography):
def __init__(self, temboo_session):
"""
Create a ... |
"""
"Safe weakrefs", originally from pyDispatcher.
Provides a way to safely weakref any function, including bound methods (which
aren't handled by the core weakref module).
"""
import weakref, traceback
def safeRef(target, onDelete = None):
"""Return a *safe* weak reference to a callable target
target -- th... |
import os, numpy, PIL
from PIL import Image
def paging(BASE_INDEX):
# Access all PNG files in directory
allfiles=os.listdir(os.getcwd())
imlist=[filename for filename in allfiles if filename[-4:] in [".jpg",".JPG"]]
imlist = sorted(imlist)
base_imlist = imlist
WINDOWS = 10
left = BASE_IND... |
from msrest.serialization import Model
class Operation(Model):
"""Microsoft Insights API operation definition.
:param name: Operation name: {provider}/{resource}/{operation}
:type name: str
:param display: Display metadata associated with the operation.
:type display: ~azure.mgmt.monitor.models.O... |
#!/usr/bin/env python3
import shutil, sys, subprocess, argparse, pathlib
parser = argparse.ArgumentParser()
parser.add_argument('--private-dir', required=True)
parser.add_argument('-o', required=True)
parser.add_argument('cmparr', nargs='+')
contents = '''#include<stdio.h>
void flob() {
printf("Now flobbing.\\... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.compat.tests.mock import patch
from ansible.modules.network.nxos import nxos_interface
from .nxos_module import TestNxosModule, load_fixture, set_module_args
class TestNxosInterfaceModule(TestNxosModule):
module... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Unit tests for storage.py """
import sys
import os
import unittest
if os.path.isdir('gluon'):
sys.path.append(os.path.realpath('gluon'))
else:
sys.path.append(os.path.realpath('../'))
from storage import Storage
class TestStorage(unittest.Te... |
import socket
import httplib
from string import split, join
class Connection: # generic tcp connection wrapper
def __init__(self, server):
self.socket = None
self.server = server
def establish(self):
if self.socket == None:
s = socket.socket(socket.AF_INET, so... |
from __future__ import division
import math
from gnuradio import gr, gr_unittest, analog, blocks
class test_pll_refout(gr_unittest.TestCase):
def setUp(self):
self.tb = gr.top_block()
def tearDown(self):
self.tb = None
def test_pll_refout(self):
expected_result = ((1+0j),
... |
"""
csv.py - read/write/investigate CSV files
"""
import re
from _csv import Error, __version__, writer, reader, register_dialect, \
unregister_dialect, get_dialect, list_dialects, \
field_size_limit, \
QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE, \
... |
"""This module defines different MultiStageScheme classes which can be passed to a RKSolver"""
# Copyright (C) 2013 Johan Hake
#
# This file is part of DOLFIN.
#
# DOLFIN is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Sof... |
""" CLI interface for Rally. """
from __future__ import print_function
import sys
from rally.cmd import cliutils
from rally.cmd.commands import deployment
from rally.cmd.commands import info
from rally.cmd.commands import show
from rally.cmd.commands import task
from rally.cmd.commands import use
from rally.cmd.comm... |
"""Database setup and migration commands."""
from nova import utils
IMPL = utils.LazyPluggable(
'db_backend',
config_group='baremetal',
sqlalchemy='nova.virt.baremetal.db.sqlalchemy.migration')
def db_sync(version=None):
"""Migrate the database to `version` or the most recent version.""... |
import numpy as np
from matplotlib import pyplot as plt
from scipy import stats
from sklearn.tree import DecisionTreeClassifier
def plot_surface(model, X, y):
n_classes = 3
plot_colors = "ryb"
cmap = plt.cm.RdYlBu
plot_step = 0.02
plot_step_coarser = 0.5
x_min, x_max = X[:, 0].min() - 1, X[:,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
examples/ScriptingService/HelloWorld.py
-----------------------------------------------------------------------------
Copyright (C) 2006-2010 University of Dundee. All rights reserved.
This program is free software; you can redistribute it and/or modify
it und... |
from shinken_test import *
class TestConfig(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_dot_virg_in_command.cfg')
def test_dummy(self):
#
# Config is not correct because of a wrong relative path
# in the main config file
#
print "Get the h... |
from __future__ import unicode_literals
import datetime
import decimal
import hashlib
import logging
from time import time
from django.conf import settings
from django.utils.encoding import force_bytes
from django.utils.timezone import utc
logger = logging.getLogger('django.db.backends')
class CursorWrapper(objec... |
'''
Created on 2013/09/29
@author: duong
'''
from mrjob.job import MRJob
import re
WORD_RE = re.compile(r"[\w']+")
class MRMostUsedWord(MRJob):
def mapper_get_words(self, _, line):
# emit (word, 1) for each word in line
for word in WORD_RE.findall(line):
yield (word.lower(), 1)
... |
"""Module containing utility functions for reporting results."""
import logging
import os
import re
from pylib import buildbot_report
from pylib import constants
import flakiness_dashboard_results_uploader
def _LogToFile(results, test_type, test_suite, build_type):
"""Log results to local files which can be used... |
"""
Tests for vertical module.
"""
from fs.memoryfs import MemoryFS
from xmodule.tests import get_test_system
from xmodule.tests.xml import XModuleXmlImportTest
from xmodule.tests.xml import factories as xml
from xmodule.x_module import STUDENT_VIEW, AUTHOR_VIEW
class BaseVerticalBlockTest(XModuleXmlImportTest):
... |
import pytest
import os
import copy
from django.core.serializers.json import Deserializer
from representatives.models import Representative
from representatives.contrib.francedata import import_representatives
@pytest.mark.django_db
def test_francedata_import_representatives():
inputjson = os.path.join(os.path.d... |
"""Utility functions, node construction macros, etc."""
from itertools import islice
# Local imports
from .pgen2 import token
from .pytree import Leaf, Node
from .pygram import python_symbols as syms
from . import patcomp
###########################################################
### Common node-construction "macr... |
# -*- coding: utf-8 -*-
_folderT = [
"24 24 297 2",
" c None",
". c #FFFFFF",
"+ c #FDFEFF",
"@ c #FBFCFF",
"# c #FCFCFF",
"$ c #FDFFFF",
"% c #FFFFFD",
"& c #F6D021",
"* c #FACF0E",
"= c #FAD00F",
"- c #FAD00E",
"; c #FACF0C",
"> c #F5CD22",
", c #FBFBFF",
"' c #EEDA94",
") c #F2C32C",
"! c #F5D463"... |
from spack import *
class Libxc(Package):
"""Libxc is a library of exchange-correlation functionals for
density-functional theory."""
homepage = "http://www.tddft.org/programs/octopus/wiki/index.php/Libxc"
url = "http://www.tddft.org/programs/octopus/down.php?file=libxc/libxc-2.2.2.tar.gz"
... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: win_wait_for
version_added: '2.4'
short_description: Waits for a condition before continuing
description:
- You can wait for a set amount of time C... |
#!/usr/bin/env python
"""
Sampson's monastery data.
Shows how to read data from a zip file and plot multiple frames.
"""
__author__ = """Aric Hagberg (<EMAIL>)"""
# Copyright (C) 2010 by
# Aric Hagberg <<EMAIL>>
# Dan Schult <<EMAIL>>
# Pieter Swart <<EMAIL>>
# All rights reserved.
# BSD license.
... |
import io
from lingua.extractors import Extractor
from lingua.extractors import Message
from lingua.extractors import get_extractor
from mako.ext.extract import MessageExtractor
from mako import compat
class LinguaMakoExtractor(Extractor, MessageExtractor):
'''Mako templates'''
extensions = ['.mako']
def... |
from DIRAC.AccountingSystem.Client.Types.BaseAccountingType import BaseAccountingType
import DIRAC
__RCSID__ = "$Id$"
class Job(BaseAccountingType):
def __init__(self):
BaseAccountingType.__init__(self)
self.definitionKeyFields = [('User', 'VARCHAR(32)'),
('UserGroup', 'VAR... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import (
compat_HTTPError,
compat_str,
)
from ..utils import (
extract_attributes,
try_get,
urlencode_postdata,
ExtractorError,
)
class TVPlayerIE(InfoExtractor):
_VALID_URL = r'https?:... |
"""
This module collects helper functions and classes that "span" multiple levels
of MVC. In other words, these functions/classes introduce controlled coupling
for convenience's sake.
"""
import warnings
from django.core import urlresolvers
from django.db.models.base import ModelBase
from django.db.models.manager imp... |
"""
Test for asset XML generation / parsing.
"""
from path import path
from lxml import etree
from contracts import ContractNotRespected
import unittest
from opaque_keys.edx.locator import CourseLocator
from xmodule.assetstore import AssetMetadata
from xmodule.modulestore.tests.test_assetstore import AssetStoreTestDa... |
import sys
import os
import argparse
from PyQt5.QtWidgets import QApplication
from searchCOUNTERS.searchCOUNTERS_win import SCOUNTERS_mainwin
# -p "e:\msvs\tlm_new\Debug\withoutD2_D5\" -o 16 -k 200
def createParser():
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--path', nargs='?', he... |
import time
import unittest
import node
LEADER = 1
REED = 2
ED = 3
class Cert_6_1_2_REEDAttach(unittest.TestCase):
def setUp(self):
self.nodes = {}
for i in range(1,4):
self.nodes[i] = node.Node(i)
self.nodes[LEADER].set_panid(0xface)
self.nodes[LEADER].set_mode('rsdn... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.