content string |
|---|
from __future__ import division
import sys, glob, time
sys.path.insert(0, glob.glob('../../lib/py/build/lib.*')[0])
from optparse import OptionParser
parser = OptionParser()
parser.add_option('--genpydir', type='string', dest='genpydir',
default='gen-py',
help='include this local di... |
"""Implementation of the Speciation Particle Swarm Optimization algorithm as
presented in *Li, Blackwell, and Branke, 2006, Particle Swarm with Speciation
and Adaptation in a Dynamic Environment.*
"""
import itertools
import math
import operator
import random
import numpy
try:
from itertools import imap
except:
... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""Script to encrypt config files.
Usage:
scripts/encrypt_conf.py confname1 confname2 ... confnameN
scripts/encrypt_conf.py credentials
"""
import io
import click
import yaycl_crypt
from . import link_config
from cfme.utils import conf
@click.group(help='Functi... |
#!/usr/bin/env python
from __future__ import print_function
from __future__ import absolute_import
__author__ = 'Tony Beltramelli - www.tonybeltramelli.com'
import os
import sys
import shutil
from classes.Utils import *
from classes.model.Config import *
argv = sys.argv[1:]
if len(argv) < 2:
print("Error: not e... |
from __future__ import with_statement
import os, sys
class TiLogger:
ERROR = 0
WARN = 1
INFO = 2
DEBUG = 3
TRACE = 4
def __init__(self, logfile, level=TRACE, output_stream=sys.stdout):
self.level = level
self.output_stream = output_stream
global _logfile
_logfile = logfile
if _logfile is not None:
l... |
"""Check variable ordering - bug #161"""
from __future__ import print_function
import numpy as np
import moose
def test_var_order():
"""The y values are one step behind the x values because of
scheduling sequences"""
nsteps = 5
simtime = nsteps
dt = 1.0
# fn0 = moose.Function('/fn0')
# fn0... |
##
# Control script Addon jython module.
#
# This module contains extention of the ControlScript class:
# - VirtualBox: this extention class is to be used to control Sun VirtualBox images.
##
from controlscript import *
import time
class ControlScriptAddon(ControlScript):
""" Control script Addon"""
def __init__(s... |
from pychess.Utils.const import KING, QUEEN, ROOK, BISHOP, KNIGHT, PAWN
from pychess.Utils.repr import reprSign, reprColor, reprPiece
class Piece:
def __init__ (self, color, piece, captured=False):
self.color = color
self.piece = piece
self.captured = captured
# in crazyho... |
import numpy as np
import sys
from six import StringIO, b
from gym import utils
import discrete_env
LEFT = 0
DOWN = 1
RIGHT = 2
UP = 3
MAPS = {
"4x4": [
"SFFF",
"FHFH",
"FFFH",
"HFFG"
],
"8x8": [
"SFFFFFFF",
"FFFFFFFF",
"FFFHFFFF",
"FFFFFHFF... |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Conector for openload.io
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
# by DrZ3r0
# ------------------------------------------------------------
# Modified by Shani
import re
class AADec... |
{
'name': 'Projects extensions for user roles',
'version': '1.0',
'category': 'Project Management',
'summary': 'Extend Project user roles to support more complex use cases',
'description': """\
Employees are now basic Project users, able to create new documents (Issues
or Tasks). These are kept edit... |
import io
import sys
import unittest
def resultFactory(*_):
return unittest.TestResult()
class TestSetups(unittest.TestCase):
def getRunner(self):
return unittest.TextTestRunner(resultclass=resultFactory,
stream=io.StringIO())
def runTests(self, *cases... |
"""
UUID related utilities and helper functions.
"""
import uuid
def generate_uuid():
return str(uuid.uuid4())
def is_uuid_like(val):
"""Returns validation of a value as a UUID.
For our purposes, a UUID is a canonical form string:
aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa
"""
try:
retu... |
from mock import (
patch, Mock
)
from pytest import raises
from kiwi.package_manager import PackageManager
from kiwi.exceptions import KiwiPackageManagerSetupError
class TestPackageManager:
def test_package_manager_not_implemented(self):
with raises(KiwiPackageManagerSetupError):
Package... |
import os
import sys
import shutil
import fnmatch
from zipfile import ZipFile, ZIP_DEFLATED
def findfiles(directory, mask):
def visit(files, dir, names):
for name in names:
if fnmatch.fnmatch(name, mask):
files.append(os.path.join(dir, name))
files = []
os.path.walk(dire... |
# -*- coding: utf-8 -*-
'''
Genesis Add-on
Copyright (C) 2015 lambda
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 3 of the License, or
(at your opt... |
import email_template
import wizard
import res_partner
import ir_actions
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
# -*- coding: utf-8 -*-
"""
InaSAFE Disaster risk assessment tool developed by AusAid -
**metadata module.**
Contact : <EMAIL>
.. note:: 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; eit... |
""" Test functions for fftpack.basic module
"""
from __future__ import division, absolute_import, print_function
from numpy import arange, asarray, zeros, dot, exp, pi, double, cdouble
import numpy.fft
from numpy.random import rand
try:
from scipy.fftpack import ifft, fft, fftn, irfft, rfft
except ImportError:
... |
import logging
from functools import partial
import math
import json
from django.http import HttpResponseBadRequest
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_http_methods
from django_future.csrf import ensure_csrf_cookie
from django.views.decorators.http... |
#
#
#
import numpy as np
import pandas as pd
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
import sys
# effective temperature prior
# inputs
Sbar = 60.
eSbar = 1.
Tinput = 8700.
# load spectral type |-> temperature conversion file
dt = {'ST': np.str, 'STix': np.float64, 'Teff':np.float64,... |
def module_exists(module_name):
try:
__import__(module_name)
except ImportError:
return False
else:
return True
if module_exists('browser') and module_exists('javascript'):
from browser import window, document
from javascript import JSObject, JSConstructor
GFX = JSObject(w... |
#!/usr/bin/env python
from utils.munin.base import MuninGraph
import redis
class NBMuninGraph(MuninGraph):
@property
def graph_config(self):
return {
'graph_category' : 'NewsBlur',
'graph_title' : 'NewsBlur Feed Counts',
'graph_vlabel' : 'Feeds Feed Counts',
... |
from django import forms
from django.contrib import admin
from django.contrib.flatpages.models import FlatPage
from django.utils.translation import ugettext_lazy as _
class FlatpageForm(forms.ModelForm):
url = forms.RegexField(label=_("URL"), max_length=100, regex=r'^[-\w/\.~]+$',
help_text = _("Example: ... |
import logging
logger = logging.getLogger(__name__)
from redbean.secure.identity import SessionIdentity
from redbean.secure.keeper import UserIdentityKeeper
from redbean.asyncid import AsyncID64
from test.security.app import rest, etcd_endpoint
user_id_generator = AsyncID64('/asyncid/user_sn', etcd_endpoint)
keeper ... |
"""BibAuthorId regressions tests."""
__revision__ = "$Id$"
from invenio.testutils import InvenioTestCase, \
run_test_suite, make_test_suite, test_web_page_content
from invenio.config import CFG_SITE_URL, \
CFG_INSPIRE_SITE, CFG_BIBAUTHORID_ENABLED
from invenio.dbquery import run_sql
import random
import st... |
"""Mocks for tests."""
__author__ = '<EMAIL> (Thomas Stromberg)'
import mocks
import nameserver
import unittest
class TestNameserver(unittest.TestCase):
def testInit(self):
ns = mocks.MockNameServer(mocks.GOOD_IP)
self.assertEquals(ns.ip, mocks.GOOD_IP)
self.assertEquals(ns.name, None)
ns = mocks.... |
"""The tests for the Rfxtrx light platform."""
from unittest.mock import call
import pytest
from homeassistant.components.light import ATTR_BRIGHTNESS
from homeassistant.components.rfxtrx import DOMAIN
from homeassistant.core import State
from tests.common import MockConfigEntry, mock_restore_cache
from tests.compon... |
# encoding: utf8
from quantiphy import (
Quantity, UnitConversion,
QuantiPhyError, IncompatibleUnits, UnknownPreference, UnknownConversion,
UnknownUnitSystem, InvalidRecognizer, UnknownFormatKey, UnknownScaleFactor,
InvalidNumber, ExpectedQuantity, MissingName,
)
Quantity.reset_prefs()
import math
impo... |
"""tests for operator_tapering.py"""
import unittest
from openfermion.ops.operators import FermionOperator, BosonOperator
from openfermion.transforms.repconversions.operator_tapering import (
freeze_orbitals, prune_unused_indices)
class FreezeOrbitalsTest(unittest.TestCase):
def test_freeze_orbitals_nonvani... |
import socket
from tornado import gen
from tornado.iostream import IOStream
from tornado.log import app_log
from tornado.stack_context import NullContext
from tornado.tcpserver import TCPServer
from tornado.testing import AsyncTestCase, ExpectLog, bind_unused_port, gen_test
class TCPServerTest(AsyncTestCase):
@g... |
"""Execute shell commands via os.popen() and return status, output.
Interface summary:
import commands
outtext = commands.getoutput(cmd)
(exitstatus, outtext) = commands.getstatusoutput(cmd)
outtext = commands.getstatus(file) # returns output of "ls -ld file"
A trailing newline is remov... |
import numpy as np
class linear_regression:
def __init__(self,batch_size=0,epochs=100,learning_rate=0.001,tolerance=0.00001,show_progress=True):
"""
The function initiaizes the class
Parameters
----------
batch_size: int
It defines the number of data se... |
import numpy as np
from lxmls.deep_learning.utils import (
Model,
glorot_weight_init,
index2onehot,
logsumexp
)
class NumpyLogLinear(Model):
def __init__(self, **config):
# Initialize parameters
weight_shape = (config['input_size'], config['num_classes'])
# after Xavier G... |
from . import product
from . import stock
from . import wizard
from . import product_price_history
from . import account_anglo_saxon_pos
from . import purchase |
"""
Corpus reader for corpora whose documents are xml files.
(note -- not named 'xml' to avoid conflicting w/ standard xml package)
"""
from api import CorpusReader
from util import *
from nltk.internals import deprecated
# Use the c version of ElementTree, which is faster, if possible:
try: from xml.etree import cE... |
import sys, os.path, io, string
# parsed error data
Errors = []
# error data model
class ErrorDef:
def __init__(self):
self.err_code = ""
self.err_define = None
self.err_string = ""
self.isWinError = False
self.linenum = ""
def escapeString( input ):
output = input.re... |
from __future__ import absolute_import, division, print_function, unicode_literals
import re
import logging
from guessit import u
from guessit.textutils import find_words
from babelfish import Language, Country
import babelfish
from guessit.guess import Guess
__all__ = ['Language', 'UNDETERMINED',
'sear... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.plugins.shell.sh import ShellModule as ShModule
from ansible.compat.six import text_type
from ansible.compat.six.moves import shlex_quote
class ShellModule(ShModule):
# Common shell filenames that this plugin ha... |
# -*- coding: utf-8 -*-
from django.db import models
from apps.titulos.models.CohorteExtensionAulica import CohorteExtensionAulica
import datetime
"Seguimiento de cada cohorte de la extensión áulica"
class CohorteExtensionAulicaSeguimiento(models.Model):
cohorte_extension_aulica = models.ForeignKey(CohorteExtensio... |
import logging
from openerp.osv import osv,fields
from openerp import _
#import pooler
logging.basicConfig(level=logging.DEBUG)
class make_medical_appointment_invoice(osv.osv_memory):
_name="oemedical.appointment.invoice"
def create_invoice(self, cr, uid, ids, context={}):
invoice_obj = self.pool.... |
# coding=utf-8
import pytest
from os.path import join
from xpaw.cmdline import main
from xpaw import __version__
def test_print_help(capsys):
with pytest.raises(SystemExit) as excinfo:
main(argv=['xpaw'])
assert excinfo.value.code == 0
out, _ = capsys.readouterr()
assert out.startswith('usag... |
#
# Tests of spherical Bessel functions.
#
import numpy as np
from numpy.testing import (assert_almost_equal, assert_allclose, dec,
assert_array_almost_equal)
from numpy import sin, cos, sinh, cosh, exp, inf, nan, r_, pi
from scipy.special import spherical_jn, spherical_yn, spherical_in, sp... |
"""
A Python "serializer". Doesn't do much serializing per se -- just converts to
and from basic Python data types (lists, dicts, strings, etc.). Useful as a basis for
other serializers.
"""
from django.conf import settings
from django.core.serializers import base
from django.db import models
from django.utils.encodin... |
'''
Robot testing for test volume operations for 2 hours. Will use weight fairly
strategy.
@author: Youyk
'''
import zstackwoodpecker.action_select as action_select
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.test_lib as test_lib
... |
""" Defines classes and functions for working with Qt's rich text system.
"""
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# Standard library imports
import io
import os
import re
# System librar... |
import os
from telemetry.page.actions import page_action
class ScrollAction(page_action.PageAction):
# TODO(chrishenry): Ignore attributes, to be deleted when usage in
# other repo is cleaned up.
def __init__(self, selector=None, text=None, element_function=None,
left_start_ratio=0.5, top_start_... |
"""
Iterator for RNN data
"""
from functools import wraps
import numpy as np
from theano import config
from pylearn2.sandbox.rnn.space import SequenceDataSpace
from pylearn2.sandbox.rnn.space import SequenceMaskSpace
from pylearn2.space import CompositeSpace
from pylearn2.utils import safe_izip
from pylearn2.utils.it... |
import os
import pytest
import textwrap
from sklearn import __version__
from sklearn.utils._openmp_helpers import _openmp_parallelism_enabled
def test_openmp_parallelism_enabled():
# Check that sklearn is built with OpenMP-based parallelism enabled.
# This test can be skipped by setting the environment varia... |
from TreeSerialize.TreeSerialize import deserialize, drawtree
'''
Needs Python 3+
'''
class Solution_old(object):
'''
Lowest Common Ancestor (LCA) in a Binary Tree (BT) : Takes additional space, not space optimized.
'''
def findPath(self, root, path, k):
'''
A Helper function to ma... |
# -*- coding: utf-8 -*-
from ..Qt import QtCore, QtGui
__all__ = ['FeedbackButton']
class FeedbackButton(QtGui.QPushButton):
"""
QPushButton which flashes success/failure indication for slow or asynchronous procedures.
"""
### For thread-safetyness
sigCallSuccess = QtCore.Signal(object, ... |
#!/usr/bin/env python
import os
import re
import copy
import time
import subprocess
import shutil
import datetime # not used but "sub-"imported by livestatus test.. (to be corrected..)
import sys # not here used but "sub-"imported by livestatus test.. (to be corrected..)
#
from shinken.modulesctx import modulesctx
fr... |
"""
Some unit tests for S3 MfaDelete with versioning
"""
import unittest
import time
from nose.plugins.attrib import attr
from boto.s3.connection import S3Connection
from boto.exception import S3ResponseError
from boto.s3.deletemarker import DeleteMarker
@attr('notdefault', 's3mfa')
class S3MFATest (unittest.TestCa... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.errors import AnsibleError
from ansible.plugins.lookup import LookupBase
CREDSTASH_INSTALLED = False
try:
import credstash
CREDSTASH_INSTALLED = True
except ImportError:
CREDSTASH_INSTALLED = False
clas... |
import volatility.utils as utils
import volatility.plugins.common as common
import volatility.scan as scan
import volatility.obj as obj
import volatility.cache as cache
import volatility.debug as debug
import socket
import volatility.plugins.overlays.windows.tcpip_vtypes as tcpip_vtypes
# Python's socket.AF_INET6 is 0... |
import copy
import json
import os
from ansible.module_utils.basic import AnsibleModule
try:
from openshift.helper.ansible import KubernetesAnsibleModuleHelper, ARG_ATTRIBUTES_BLACKLIST
from openshift.helper.exceptions import KubernetesException
HAS_K8S_MODULE_HELPER = True
except ImportError as exc:
H... |
"""A more or less complete user-defined wrapper around dictionary objects."""
class UserDict:
def __init__(self, dict=None, **kwargs):
self.data = {}
if dict is not None:
self.update(dict)
if len(kwargs):
self.update(kwargs)
def __repr__(self): return repr(self.d... |
import sys, random
from mrmpi import mrmpi
try:
import pypar
except:
import pypar_serial as pypar
# generate RMAT matrix entries
# emit one KV per edge: key = edge, value = NULL
def generate(itask,mr):
for m in xrange(ngenerate):
delta = order / 2
a1 = a; b1 = b; c1 = c; d1 = d
i = j = 0
fo... |
"""
Sample script showing the way to perform computations in blaze
This should be executable and result in an out of core execution to
generate the result of the expression
This illustrates the idea of:
- Using large in-disk arrays as operands
- Building expressions to evaluate in blaze
- Evaluate those expr... |
import boto
from boto.connection import AWSQueryConnection, AWSAuthConnection
from boto.exception import BotoServerError
import time
import urllib
import xml.sax
from boto.ecs.item import ItemSet
from boto import handler
class ECSConnection(AWSQueryConnection):
"""
ECommerce Connection
For more informatio... |
"""
Out-of-band default plugin commands available for OOB handler.
This module implements commands as defined by the MSDP standard
(http://tintin.sourceforge.net/msdp/), but is independent of the
actual transfer protocol (webclient, MSDP, GMCP etc). It also
implements several OOB commands unique to Evennia (both some
... |
"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2012-2014 Alex Forencich
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 restriction, including without limitation the... |
"""
Kill Bill
Kill Bill is an open-source billing and payments platform # noqa: E501
OpenAPI spec version: 0.22.22-SNAPSHOT
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibilit... |
from openerp.osv import osv, fields
class MailMailStats(osv.Model):
""" MailMailStats models the statistics collected about emails. Those statistics
are stored in a separated model and table to avoid bloating the mail_mail table
with statistics values. This also allows to delete emails send with mass maili... |
#!/usr/bin/env python
"""
@package mi.dataset.driver.wc_sbe.cspp
@file mi/dataset/driver/wc_sbe/cspp/wc_sbe_cspp_recovered_driver.py
@author Jeff Roy
@brief Driver for the wc_sbe_cspp instrument
Release notes:
Initial Release
"""
from mi.dataset.dataset_parser import DataSetDriverConfigKeys
from mi.dataset.dataset_... |
"""Word completion for GNU readline 2.0.
This requires the latest extension to the readline module. The completer
completes keywords, built-ins and globals in a selectable namespace (which
defaults to __main__); when completing NAME.NAME..., it evaluates (!) the
expression up to the last dot and completes its att... |
import PIL.Image
import math
class MapHelper(object):
@staticmethod
def new_image(width, height, alpha=False):
"""
Generates a new image using PIL.Image module
returns PIL.IMAGE OBJECT
"""
if alpha is True:
return PIL.Image.new('RGBA', (width, height), (0,... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import re
from stgit.compat import text
from stgit.config import config
from .base import Immutable
from .person import Person
class GitObject(Immutable):
"""Base class for all git objects. One git object... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
import ansible.module_utils.netapp as netapp_utils
HAS_NETAPP_LIB =... |
import dis
import re
import sys
from io import StringIO
import unittest
from math import copysign
from test.bytecode_helper import BytecodeTestCase
class TestTranforms(BytecodeTestCase):
def test_unot(self):
# UNARY_NOT POP_JUMP_IF_FALSE --> POP_JUMP_IF_TRUE'
def unot(x):
if not x =... |
"""A minimal interface mlp module."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
from six.moves import xrange # pylint: disable=redefined-builtin
from sonnet.python.modules import base
from sonnet.python.modules import basic
from so... |
from xml.dom.minidom import parseString
from django.core import mail
from django.template import Context, Template
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseNotFound
from django.contrib.auth.decorators import login_required, permission_required
from django.forms.forms import Form
from dja... |
"""
Runs through a reST file looking for old-style literals, and helps replace them
with new-style references.
"""
import re
import sys
import shelve
refre = re.compile(r'``([^`\s]+?)``')
ROLES = (
'attr',
'class',
"djadmin",
'data',
'exc',
'file',
'func',
'lookup',
'meth',
'm... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:
# http://binux.me
# Created on 2014-11-05 10:42:24
import time
import mysql.connector
class MySQLMixin(object):
@property
def dbcur(self):
try:
if self.conn.unread_result:
... |
"""
Tests of the LMS XBlock Runtime and associated utilities
"""
from django.contrib.auth.models import User
from django.conf import settings
from ddt import ddt, data
from mock import Mock
from unittest import TestCase
from urlparse import urlparse
from opaque_keys.edx.locations import SlashSeparatedCourseKey
from lm... |
import os
import sys
import logging
import platform
import gtk
import gobject
from rednotebook.gui.customwidgets import UrlButton, CustomComboBoxEntry
from rednotebook.gui.customwidgets import ActionButton
from rednotebook.gui import browser
from rednotebook.util import filesystem, utils
from rednotebook import info... |
import warnings
from scrapy.exceptions import ScrapyDeprecationWarning
DEPRECATED_SETTINGS = [
('TRACK_REFS', 'no longer needed (trackref is always enabled)'),
('RESPONSE_CLASSES', 'no longer supported'),
('DEFAULT_RESPONSE_ENCODING', 'no longer supported'),
('BOT_VERSION', 'no longer used (user agent ... |
import logging
import webdav
import webdav_server
import document_webdav
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
def quantiles(self, column_name, quantiles):
"""
Returns a new frame with Quantiles and their values.
Parameters
----------
:param column_name: (str) The column to calculate quantiles on
:param quantiles: (List[float]) The quantiles being requested
:return: (Frame) A new frame with two col... |
from django.contrib.auth.models import User
from django.contrib.comments.forms import CommentForm
from django.contrib.comments.models import Comment
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from django.test import TestCase
from regressiontests.comment_tests... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'certified'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.net_tools.nio... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: bigip_monitor_tcp
short_description: Manages F5 BIG-IP LTM ... |
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
clean_html,
int_or_none,
parse_duration,
parse_iso8601,
parse_resolution,
url_or_none,
)
class CCMAIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?ccma\.cat/(?:[... |
c_uuid = None
def store_c_uuid():
global c_uuid
c_uuid = next(iter(reality.resources_by_logical_name('C'))).uuid
def check_c_replaced():
test.assertNotEqual(c_uuid,
next(iter(reality.resources_by_logical_name('C'))).uuid)
test.assertIsNotNone(c_uuid)
example_template = Templa... |
from shinken.objects.satellitelink import SatelliteLink, SatelliteLinks
from shinken.property import IntegerProp, StringProp
class BrokerLink(SatelliteLink):
"""TODO: Add some comment about this class for the doc"""
id = 0
my_type = 'broker'
properties = SatelliteLink.properties.copy()
properties.... |
# -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.template.loader import render_to_string
from django.core.paginator import Paginator
from actstream.models import Action, target_stream, user_stream
from cyclope.core import frontend
import cyclope.... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.module_utils.facts.collector import BaseFactCollector
try:
import selinux
HAVE_SELINUX = True
except ImportError:
HAVE_SELINUX = False
SELINUX_MODE_DICT = {1: 'enforcing',
0: 'permiss... |
try:
from pyVmomi import vim, vmodl
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
def find_hostsystem(content):
host_system = get_all_objs(content, [vim.HostSystem])
for host in host_system:
return host
return None
def main():
argument_spec = vmware_argument_spec()
... |
import argparse
import array
import re
import socket
import struct
import subprocess
import sys
import mozinfo
import mozlog
if mozinfo.isLinux:
import fcntl
class NetworkError(Exception):
"""Exception thrown when unable to obtain interface or IP."""
def _get_logger():
logger = mozlog.get_default_logg... |
"""
Video Outlines
We only provide the listing view for a video outline, and video outlines are
only displayed at the course level. This is because it makes it a lot easier to
optimize and reason about, and it avoids having to tackle the bigger problem of
general XBlock representation in this rather specialized format... |
def test():
def gen(n):
for x in xrange(n):
yield str(x)
def f_1(xs):
"""
:type xs: list of int
"""
return xs
def f_2(xs):
"""
:type xs: collections.Sequence of int
"""
return xs
def f_3(xs):
"""
:type xs... |
#!/usr/bin/env python
# coding:utf-8
# 并发进程的类 by xzr
import multiprocessing
import time
import subprocess
import os
import sys
import traceback
import threading
#import Queue
def get_now():
tf = '%Y-%m-%d %H:%M:%S'
return time.strftime(tf, time.localtime())
_Cpus = multiprocessing.cpu_count()
class xBF:
... |
"""Test maasserver messages."""
from __future__ import (
absolute_import,
print_function,
unicode_literals,
)
str = None
__metaclass__ = type
__all__ = []
import json
import socket
from maasserver.exceptions import NoRabbit
from maasserver.messages import (
MAASMessenger,
MESSENGER_EVENT,
... |
#!/usr/bin/python
from ansible.module_utils.basic import *
from ansible.module_utils.ec2 import *
try:
import boto.ec2.autoscale
from boto.ec2.autoscale import ScalingPolicy
from boto.exception import BotoServerError
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
def create_scaling_policy(... |
from __future__ import print_function
import time, sys, signal, atexit
from upm import pyupm_ms5803 as sensorObj
def main():
# Instantiate a MS5803 instance using bus 0 and default i2c address
sensor = sensorObj.MS5803(0)
# For SPI, bus 0, you would pass -1 as the address, and a valid pin for CS:
# MS... |
import sys, os, traceback
from cStringIO import StringIO
from aqt.qt import *
from aqt.utils import showInfo, openFolder, isWin, openLink, \
askUser
from zipfile import ZipFile
import aqt.forms
import aqt
from aqt.downloader import download
# in the future, it would be nice to save the addon id and unzippped file ... |
import os
# template arguments and dynamic arguments of individual benchmark types
# Example benchmark name: "BM_UnaryPingPong<TCP, NoOpMutator, NoOpMutator>/0/0"
_BM_SPECS = {
'BM_UnaryPingPong': {
'tpl': ['fixture', 'client_mutator', 'server_mutator'],
'dyn': ['request_size', 'response_size'],
... |
"""
Tests for the LTI provider views
"""
from unittest.mock import MagicMock, patch
from django.test import TestCase
from django.test.client import RequestFactory
from django.urls import reverse
from opaque_keys.edx.locator import BlockUsageLocator, CourseLocator
from common.djangoapps.student.tests.factories impor... |
{
'name': 'Warehouse Management System',
'version': '1.2',
'category': 'Generic Modules/Inventory Control',
'description': """This module is extensions to stock module""",
'author': 'SYLEAM',
'website': 'http://www.syleam.fr/',
'depends': [
'base',
'stock',
],
'init_x... |
# -*- coding : utf8 -*-
"""
.. module:: 3seg
:synopsis: Equations and solutions for the three-segment model
.. moduleauthor:: Moritz Maus <<EMAIL>>
"""
# format: l1, l2, l3, c1, c2]
from pylab import (array, arccos, linspace, vstack, figure, clf, plot, xlabel,
ylabel, show, savefig, sqrt, xlim, ylim, ax... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.