content stringlengths 4 20k |
|---|
"""
Testing signals before/after saving and deleting.
"""
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=20)
def __unicode__(self):
return self.name
class Book(models.Model):
name = models.CharField(max_length=20)
authors = models.ManyToManyField(... |
"""Generate and work with PEP 425 Compatibility Tags."""
from __future__ import absolute_import
import re
import sys
import warnings
import platform
import logging
import ctypes
try:
import sysconfig
except ImportError: # pragma nocover
# Python < 2.7
import distutils.sysconfig as sysconfig
import distut... |
"""
Helper for reading hive-site.xml
"""
import errno
import logging
import os.path
import re
import socket
from desktop.lib import security_util
from hadoop import confparse
import beeswax.conf
LOG = logging.getLogger(__name__)
_HIVE_SITE_PATH = None # Path to hive-site.xml
_HIVE_SITE_DICT = Non... |
# -*- coding: utf-8 -*-
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sites', '0001_initial'),
('api_admin', '0003_auto_20160404_1618'),
]
operations = [
migrations.AddField(
model... |
import mock
import pytest
from framework.auth.core import Auth
from osf.models import QuickFilesNode
from addons.osfstorage.models import OsfStorageFile
from osf.exceptions import MaxRetriesError
from api_tests.utils import create_test_file
from tests.utils import assert_items_equal
from tests.base import get_default_... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import json
import struct
from _shaded_thriftpy.thrift import TType
from .exc import TProtocolException
INTEGER = (TType.BYTE, TType.I16, TType.I32, TType.I64)
FLOAT = (TType.DOUBLE,)
VERSION = 1
def json_value(ttype, val, spec=None):
if ttype i... |
# Output
#
# $ ../../../pin -t ./triton.so -script ./examples/callback_after.py -- ./samples/crackmes/crackme_xor a
# 0x40056d: push rbp
# -> #0 = (bvsub (_ bv140735022953896 64) (_ bv8 64)) ; Aligns stack
# -> #1 = (_ bv140735022953936 64)
# -> #2 = (_ bv4195694 64) ; RIP
#
# 0x40056e: mov ... |
from Core import TreeClass as tc
import pandas as pd
file_original = open('input/test.txt', 'r')
file_predicted = open('input/full_hid25_re0-0007-test.txt', 'r')
original_temp = []
predicted_temp = []
for line in file_original:
original_tree = tc.ScoreTree(line)
for node in original_tree.allNodes():
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import shutil
import traceback
import select
import fcntl
import errno
HAS_LIBLXC = False
try:
import lxc as _lxc
HAS_LIBLXC = True
except ImportError:
pass
from ansible import constants as C
from ansible im... |
import browser.html
import re
class URL:
def __init__(self,src):
elts = src.split(maxsplit=1)
self.href = elts[0]
self.alt = ''
if len(elts)==2:
alt = elts[1]
if alt[0]=='"' and alt[-1]=='"':self.alt=alt[1:-1]
elif alt[0]=="'" and alt[-1]=="'":sel... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import collections
import os
import sys
import time
import threading
from itertools import chain
from ansible import constants as C
from ansible.plugins.cache.base import BaseCacheModule
try:
import memcache
except ImportErro... |
#!/usr/bin/env python
"""Find Kconfig symbols that are referenced but not defined."""
# (c) 2014-2015 Valentin Rothberg <<EMAIL>>
# (c) 2014 Stefan Hengelein <<EMAIL>>
#
# Licensed under the terms of the GNU GPL License version 2
import os
import re
import sys
from subprocess import Popen, PIPE, STDOUT
from optpars... |
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
__doc__ = """Memoizer
A metaclass implementation to count hits and misses of the computed
values that various methods cache in memory.
Use of this modules assumes that wrapped methods be coded to cache their
values in a consistent way. Here is an example... |
from __future__ import absolute_import, division, unicode_literals
from xml.dom import Node
import gettext
_ = gettext.gettext
from . import _base
class TreeWalker(_base.NonRecursiveTreeWalker):
def getNodeDetails(self, node):
if node.nodeType == Node.DOCUMENT_TYPE_NODE:
return _base.DOCTYP... |
from zope.interface import provider
from twisted.plugin import IPlugin
from twisted.application.service import ServiceMaker
from twisted.words import iwords
NewTwistedWords = ServiceMaker(
"New Twisted Words",
"twisted.words.tap",
"A modern words server",
"words")
TwistedXMPPRouter = ServiceMaker(
... |
from unittest import TestCase
from unittest.mock import (
Mock,
patch,
)
from pypika import Field
from fireant.database import Database
from fireant.middleware.decorators import connection_middleware
@connection_middleware
def test_fetch(database, query, **kwargs):
return kwargs.get('connection')
def ... |
from pylab import *
from matplotlib.collections import LineCollection
# In order to efficiently plot many lines in a single set of axes,
# Matplotlib has the ability to add the lines all at once. Here is a
# simple example showing how it is done.
N = 50
x = arange(N)
# Here are many sets of y to plot vs x
ys = [x+i f... |
def draw_scatter(fields,
category,
region,
output_name,
backgrounds,
signals=None,
data=None,
signal_scale=1.,
signal_colors=cm.spring,
classifier=None,
... |
import time
from datetime import datetime
from dateutil.relativedelta import relativedelta
from openerp.osv import fields, osv
from openerp.tools.translate import _
class account_aged_trial_balance(osv.osv_memory):
_inherit = 'account.common.partner.report'
_name = 'account.aged.trial.balance'
_descriptio... |
'''
Created on 26 Oct 2015
@author: Ruben.Alonso
@Description: Module created to manage all different errors and exceptions.
'''
import utils.logger.handler as LH
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class InputError(Error):
"""Exception raised for errors in t... |
"""
Provide L{ICredentialsChecker} implementations to be used in Conch protocols.
"""
import os, base64, binascii, errno
try:
import pwd
except ImportError:
pwd = None
else:
import crypt
try:
# get this from http://www.twistedmatrix.com/users/z3p/files/pyshadow-0.2.tar.gz
import shadow
except:
... |
import collections
import mock
import testtools
from neutron.db import api as db
from neutron.plugins.cisco.common import cisco_constants
from neutron.plugins.cisco.common import cisco_credentials_v2
from neutron.plugins.cisco.common import cisco_exceptions as c_exc
from neutron.plugins.cisco.common import config as c... |
'''Common test methods'''
from behave import *
@given(u'"{host}" hosts from dynamic inventory')
def step_impl(context, host):
context.inventory = "dynamic"
context.target_host = host
@given(u'"{host}" hosts from static inventory')
def step_impl(context, host):
context.inventory = "static"
context.ta... |
# -*- encoding: utf-8 -*-
import copy
from abjad.tools.topleveltools import iterate
from abjad.tools.topleveltools import mutate
def apply_full_measure_tuplets_to_contents_of_measures_in_expr(
expr, supplement=None):
r'''Applies full-measure tuplets to contents of measures in `expr`:
::
>>> staf... |
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.basic import AnsibleModule
from ansible.module_utils.network.comm... |
import os
import SourceModel.SM_File
from SmellDetector import Constants as CONSTS, Utilities
def detectSmells(folder, outputFile):
detectBrokenHie(folder, outputFile)
def detectBrokenHie(folder, outputFile):
modulesFolder = getModulesFolder(folder)
if modulesFolder:
for dir in os.listdir(module... |
import logging
from webkitpy.common import webkit_finder
_log = logging.getLogger(__name__)
class Config(object):
_FLAGS_FROM_CONFIGURATIONS = {
"Debug": "--debug",
"Release": "--release",
}
def __init__(self, executive, filesystem, port_implementation=None):
self._executive = ... |
# -*- coding: utf-8 -*-
"""
>>> from scipy import array
>>> from pybrain import datasets
>>> from copy import deepcopy
>>> d = datasets.dataset.DataSet()
>>> d.addField('input', 2)
>>> type(d.data['input'])
<type 'numpy.ndarray'>
>>> len(d.data['input'])
0
>>> x, y = d.data['in... |
"""
PRC (Palm resource) parser.
Author: Sebastien Ponce
Creation date: 29 october 2008
"""
from lib.hachoir_parser import Parser
from lib.hachoir_core.field import (FieldSet,
UInt16, UInt32, TimestampMac32,
String, RawBytes)
from lib.hachoir_core.endian import BIG_ENDIAN
class PRCHeader(FieldSet):
static... |
"""Tests for `tf.data.Dataset.from_sparse_tensor_slices()`."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
import numpy as np
from tensorflow.python.data.kernel_tests import checkpoint_test_base
from tensorflow.pyt... |
from openerp.osv import fields, osv
AVAILABLE_STATES = [
('draft', 'New'),
('cancel', 'Cancelled'),
('open', 'In Progress'),
('pending', 'Pending'),
('done', 'Closed')
]
class lead_test(osv.Model):
_name = "base.action.rule.lead.test"
_columns = {
'name': fields.char('Subject', si... |
"""Generate a CL to roll a DEPS entry to the specified revision number and post
it to Rietveld so that the CL will land automatically if it passes the
commit-queue's checks.
"""
import logging
import optparse
import os
import re
import sys
import find_depot_tools
import scm
import subprocess2
def die_with_error(msg... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
try:
import botocore
except ImportError:
pass # handled by AnsibleAWSModule
from a... |
# -*- coding: utf-8 -*-
"""
requests.utils
~~~~~~~~~~~~~~
This module provides utility functions that are used within Requests
that are also useful for external consumption.
"""
import cgi
import codecs
import os
import platform
import re
import sys
import zlib
from netrc import netrc, NetrcParseError
from . impor... |
import argparse
import collections
import datetime
import email.mime.text
import getpass
import os
import re
import smtplib
import subprocess
import sys
import tempfile
BUILD_DIR = os.path.dirname(__file__)
NACL_DIR = os.path.dirname(BUILD_DIR)
TOOLCHAIN_REV_DIR = os.path.join(NACL_DIR, 'toolchain_revisions')
PKG_VER ... |
from __future__ import unicode_literals
import datetime
import os
import subprocess
from django.utils.lru_cache import lru_cache
def get_version(version=None):
"Returns a PEP 440-compliant version number from VERSION."
version = get_complete_version(version)
# Now build the two parts of the version num... |
"""Utility functions for Windows builds.
These functions are executed via gyp-win-tool when using the ninja generator.
"""
import os
import re
import shutil
import subprocess
import stat
import string
import sys
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# A regex matching an argument corresponding to th... |
import json
from datetime import timedelta
from django.conf import settings
import requests
SURVEYS = {
'general': { # This is for users browsing the KB and navigation pages.
'email_collection_survey_id': 1002970,
'exit_survey_id': 991425,
'exit_survey_campaign_id': 878533,
},
'... |
"""
fs.wrapfs.hidedotfilesfs
========================
An FS wrapper class for hiding dot-files in directory listings.
"""
from fs.wrapfs import WrapFS
from fs.path import *
from fnmatch import fnmatch
class HideDotFilesFS(WrapFS):
"""FS wrapper class that hides dot-files in directory listings.
The listdir... |
from rest_framework import serializers
from ..models import *
from users.api.serializers import UserSerializer
class RoomInputSerializer(serializers.ModelSerializer):
class Meta:
model = Room
fields = ('id', 'name', 'members')
class RoomOutputSerializer(serializers.ModelSerializer):
class Meta:
model = Room
... |
import bisect
import logbook
import datetime
import pandas as pd
import numpy as np
from six import string_types
from sqlalchemy import create_engine
from zipline.assets import AssetDBWriter, AssetFinder
from zipline.data.loader import load_market_data
from zipline.utils import tradingcalendar
from zipline.errors imp... |
"""
utils
"""
from __future__ import print_function, unicode_literals
import sys
import shlex
import subprocess
import os
import io
import platform
DEBUG = bool(os.environ.get("SETUPTOOLS_SCM_DEBUG"))
def trace(*k):
if DEBUG:
print(*k)
sys.stdout.flush()
def ensure_stripped_str(str_or_bytes):
... |
"""Manipulates nodes using `iptables` to simulate non-standard network
conditions.
"""
import uuid
from qa_utils import AssertCommand
# String used as a comment for produced `iptables` results
IPTABLES_COMMENT_MARKER = "ganeti_qa_script"
class RulesContext(object):
def __init__(self):
self._nodes = set()
... |
# -*- coding: utf-8 -*-
"""
The :mod:`audiotsm.utils.windows` module contains window functions used for
digital signal processing.
"""
import numpy as np
def apply(buffer, window):
"""Applies a window to a buffer.
:param buffer: a matrix of shape (``m``, ``n``), with ``m`` the number of
channels an... |
# import shutil
# import PyPDF2
# import json
# import os
import requests
import re
import dateutil.parser as d
from datetime import date, timedelta
from bs4 import BeautifulSoup
from itertools import dropwhile
from .jobcontainer import JobContainer
from .org_urls import urls
from .utils_icims import get_icims_jobs
fro... |
import h5py
import numpy as np
def create_minibatch_x(minibatches, minibatch_markers, epoch_axis):
"""
Helper function to build x axis for data captured per minibatch
Arguments:
minibatches (int): how many total minibatches
minibatch_markers (int array): cumulative number of minibatches c... |
#!/usr/bin/env python
from __future__ import division, print_function, absolute_import
from os.path import join
def configuration(parent_package='',top_path=None):
from numpy.distutils.system_info import get_info, NotFoundError
from numpy.distutils.misc_util import Configuration
from scipy._build_utils i... |
from django import forms
from api.models import *
class LaunchForm(forms.ModelForm):
holdreason = forms.CharField(widget=forms.Textarea, required=False)
failreason = forms.CharField(widget=forms.Textarea, required=False)
class Meta:
model = Launch
fields = '__all__'
class LandingForm(fo... |
import os
import subprocess
import socket
import sys
import re
def do_hooks(hooks):
hook = os.path.basename(sys.argv[0])
try:
hook_func = hooks[hook]
except KeyError:
juju_log('INFO',
"This charm doesn't know how to handle '{}'.".format(hook))
else:
hook_func(... |
"""Input-pipeline utilities for Distribution strategies."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.data.experimental.ops import distribute
from tensorflow.python.data.experimental.ops.distribute_options import AutoShardPolicy... |
import urllib.request
import re
import time
import random
import socket
socket.setdefaulttimeout(3)
PAGES = 20
def saveProxy(proxy):
f = open("proxies.txt", "a")
f.write(proxy+"\n")
f.close()
def testProxy(proxy):
try:
urllib.request.URLopener(
{'http': 'http://'+proxy+"/"}).open... |
#!/usr/bin/env python
import socketio
import eventlet
import eventlet.wsgi
import time
from flask import Flask, render_template
from bridge import Bridge
from conf import conf
sio = socketio.Server()
app = Flask(__name__)
bridge = Bridge(conf)
msgs = []
@sio.on('connect')
def connect(sid, environ):
print("conn... |
import yaml
import networkx as nx
import matplotlib.pyplot as plt
from collections import defaultdict
import sys
class Topo:
def __init__(self, yaml_string):
self.raw = yaml.load(yaml_string)
self.G = nx.Graph()
self.hops = defaultdict(list)
self.hops_edges = defaultdict(list)
... |
import pycd3
class TestNode(pycd3.Node):
def __init__(self):
pycd3.Node.__init__(self)
self.x = 10
self.y = 11
self.s = "asdf"
self.d = 1.0
self.n = 10
self.addParameters()
def f(self, time, dt):
print "f"
print self.x
ret... |
from fsgamesys.drivers.messdriver import MessDriver
class MessA2600Driver(MessDriver):
CONTROLLER = {
"type": "controller",
"description": "Controller",
"mapping_name": "atari2600",
}
PORTS = [
{"description": "1st Controller", "types": [CONTROLLER]},
{"description... |
# -*- coding: utf-8 -*-
""" Tests checking the basic functionality of the Control/Explorer section.
Whether we can create/update/delete/assign/... these objects. Nothing with deep meaning.
Can be also used as a unit-test for page model coverage.
TODO: * Multiple expression types entering. (extend the update tests)
""... |
# -*- coding: utf-8 -*-
from contextlib import contextmanager
from django.core.urlresolvers import get_resolver, LocaleRegexURLResolver
from django.conf import settings
from django.utils import translation
from django.utils.translation import ugettext_lazy as _
from cms.exceptions import LanguageError
from cms.utils.... |
class ModuleDocFragment(object):
# AWS only documentation fragment
DOCUMENTATION = """
options:
ec2_url:
description:
- Url to use to connect to EC2 or your Eucalyptus cloud (by default the module will use EC2 endpoints).
Ignored for modules where region is required. Must be specified for a... |
# -*- coding: utf-8 -*-
"""
Tests the usecols functionality during parsing
for all of the parsers defined in parsers.py
"""
import pytest
import numpy as np
import pandas.util.testing as tm
from pandas import DataFrame, Index
from pandas._libs.lib import Timestamp
from pandas.compat import StringIO
class UsecolsT... |
from __future__ import unicode_literals
import frappe
import frappe.defaults
from frappe.utils import flt
from erpnext.accounts.utils import get_balance_on
@frappe.whitelist()
def get_companies():
"""get a list of companies based on permission"""
return [d.name for d in frappe.get_list("Company", fields=["name"],
... |
#!/usr/bin/env python
import datetime
import six
try:
import unittest2 as unittest
except ImportError:
import unittest
from csvkit import table
class TestColumn(unittest.TestCase):
def setUp(self):
self.c = table.Column(0, u'test', [u'test', u'column', None])
self.c2 = table.Column(0, ... |
import json
import urllib2
import logging
#import traceback
from pypes.component import Component
log = logging.getLogger(__name__)
class GeoCode(Component):
__metatype__ = 'TRANSFORMER'
def __init__(self):
# initialize parent class
Component.__init__(self)
# the field that ... |
# tk common message boxes
#
# this module provides an interface to the native message boxes
# available in Tk 4.2 and newer.
#
# written by Fredrik Lundh, May 1997
#
#
# options (all have default values):
#
# - default: which button to make default (one of the reply codes)
#
# - icon: which icon to display (see below)... |
"""
How to Use this File.
participants is a dictionary where a key is the name of the participant and the value is
a set of all the invalid selections for that participant.
participants = {'Bob': {'Sue', 'Jim'},
'Jim': {'Bob', 'Betty'},
} # And so on.
history is a dictionary where a key is the name of ... |
"""
Unit tests for degree centrality.
"""
from nose.tools import *
import networkx as nx
class TestDegreeCentrality:
def __init__(self):
self.K = nx.krackhardt_kite_graph()
self.P3 = nx.path_graph(3)
self.K5 = nx.complete_graph(5)
F = nx.Graph() # Florentine families
... |
#!/usr/bin/python
import logging
from xml.dom import minidom
from xml.dom import pulldom
BOOLEAN = "boolean"
STRING = "String"
GROUP = "Group"
# Interfaces that all FoursquareTypes implement.
DEFAULT_INTERFACES = ['FoursquareType']
# Interfaces that specific FoursqureTypes implement.
INTERFACES = {
}
DEFAULT_CLA... |
import functools
from keystone.openstack.common import importutils
def response_truncated(f):
"""Truncate the list returned by the wrapped function.
This is designed to wrap Manager list_{entity} methods to ensure that
any list limits that are defined are passed to the driver layer. If a
hints list... |
"""Denon HEOS Media Player."""
from __future__ import annotations
import asyncio
from datetime import timedelta
import logging
from pyheos import Heos, HeosError, const as heos_const
import voluptuous as vol
from homeassistant.components.media_player.const import DOMAIN as MEDIA_PLAYER_DOMAIN
from homeassistant.conf... |
from benchmark.test_types.framework_test_type import FrameworkTestType
from benchmark.test_types.verifications import basic_body_verification, verify_headers, verify_randomnumber_object
import json
class DBTestType(FrameworkTestType):
def __init__(self):
kwargs = {
'name': 'db',
... |
import collections
import numpy
import six
from chainer import cuda
from chainer import function
from chainer.utils import type_check
_args = 'float* y, float* x, int cdimy, int cdimx, int rdim, int coffset'
_preamble = '''
#define COPY(statement) \
int l = i / (rdim * cdimy); \
int c = i / rdim % cdim... |
"""
Copyright (C) 2013, Digium, Inc.
Kevin Harwell <<EMAIL>>
This program is free software, distributed under the terms of
the GNU General Public License Version 2.
"""
URL = 'deviceStates'
DEVICE = 'Stasis:Test'
INITIAL_STATE = 'NOT_INUSE'
CHANGED_STATE = 'INUSE'
def on_start(ari, event, test_obj):
# add a dev... |
import sys, unittest, struct, math, ctypes
from binascii import hexlify
from ctypes import *
def bin(s):
return hexlify(memoryview(s)).decode().upper()
# Each *simple* type that supports different byte orders has an
# __ctype_be__ attribute that specifies the same type in BIG ENDIAN
# byte order, and a __ctype_l... |
"""
Digital Ocean Driver
"""
from libcloud.utils.py3 import httplib
from libcloud.common.base import ConnectionUserAndKey, JsonResponse
from libcloud.compute.types import Provider, NodeState, InvalidCredsError
from libcloud.compute.base import NodeDriver
from libcloud.compute.base import Node, NodeImage, NodeSize, No... |
from __future__ import unicode_literals
from django.test import TestCase
from .models import Organiser, Pool, PoolStyle, Tournament
class ExistingRelatedInstancesTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.t1 = Tournament.objects.create(name='Tourney 1')
cls.t2 = Tournament.ob... |
"""Linear programming examples that show how to use the APIs."""
from google.apputils import app
from ortools.linear_solver import linear_solver2_pb2
from ortools.linear_solver import pywraplp
def RunLinearExampleNaturalLanguageAPI(optimization_problem_type):
"""Example of simple linear program with natural lang... |
"""Additional declarations for "fuzzy" attribute definitions."""
from __future__ import unicode_literals
import datetime
import decimal
import string
import warnings
from . import compat
from . import declarations
from . import random
random_seed_warning = (
"Setting a specific random seed for {} can still have... |
import logging
import threading
import eventlet
from eventlet import greenpool
from sahara.openstack.common import loopingcall
LOG = logging.getLogger(__name__)
def _thread_done(gt, *args, **kwargs):
"""Callback function to be passed to GreenThread.link() when we spawn()
Calls the :class:`ThreadGroup` to ... |
import time
import os
from flask import Flask, render_template, redirect
from .plots import empty_plot, loss_accuracy_plot
from .dataloader import LogDataLoader, to_dict
from ..callback import DBLogger
app = Flask(__name__)
db_folder = os.path.join(os.environ["HOME"], "tmp")
app.config["keras_log_db_path"] = "sqlite:... |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from builtins import * # noqa
import pytest
try:
import django # noqa
except ImportError:
pytest.skip("skipping django only tests", allow_module_level=True)
... |
import warnings
"""
Cryptographically strong pseudo-random number generator based on SHA256.
"""
class SHA256Expander:
"""
Provide a cryptographically strong pseudo-random number generator based on
SHA256. Hopefully this means that no attacker will be able to predict any
bit of output that he hasn't ... |
"""
The SparseL1Descent attack.
"""
import warnings
from distutils.version import LooseVersion
import tensorflow as tf
from cleverhans.attacks.attack import Attack
from cleverhans import utils_tf
from cleverhans.utils_tf import clip_eta, random_lp_vector
from cleverhans.compat import reduce_max, reduce_sum, softmax_... |
import os
import wheel.install
import wheel.archive
import hashlib
try:
from StringIO import StringIO
except ImportError:
from io import BytesIO as StringIO
import codecs
import zipfile
import pytest
import shutil
import tempfile
from contextlib import contextmanager
@contextmanager
def environ(key, value):
... |
"""
PAM module for python
Provides an authenticate function that will allow the caller to authenticate
a user against the Pluggable Authentication Modules (PAM) on the system.
Implemented using ctypes, so no compilation is necessary.
"""
__all__ = ['authenticate']
from ctypes import CDLL, POINTER, Structure, CFUNCTY... |
import json
import os
import tempfile
import shutil
import pytest
import requests_mock
from click.testing import CliRunner
# By doing this import we make sure that the plugin is made available
# but the entry points loading inside gg.main.
# An alternative would we to set `PYTHONPATH=. py.test` (or something)
# but t... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from six import PY3
from copy import deepcopy
from ansible.compat.tests import unittest
from ansible.compat.tests.mock import patch, mock_open
from ansible.plugins.callback import CallbackBase
import ansible.plugins.callback as c... |
import urllib
import urllib2
import cookielib
import time
import StringIO
import gzip
import sys
import re
import time
import os
import copy
import zlib
import random
import urlparse
_header = {'User-Agent':'Mozilla/5.0 (Windows NT 5.1; rv:36.0) Gecko/20100101 Firefox/36.0',
'Accept':'text/html,applicat... |
#!/usr/bin/env python3
# -*-coding:UTF-8 -*
"""
The Mails Module
======================
This module is consuming the Redis-list created by the Categ module.
It apply mail regexes on item content and warn if above a threshold.
"""
import os
import re
import sys
import uuid
import redis
import time
import datetime
... |
"""
Module providing functions for getting the list of timezones, writing timezone
configuration, valid timezones recognition etc.
"""
import os
import pytz
import langtable
from collections import OrderedDict
from pyanaconda import iutil
from pyanaconda.constants import THREAD_STORAGE
from pyanaconda.flags import f... |
import etcd
from tendrl.commons import objects
from tendrl.commons.objects import AtomExecutionFailedError
from tendrl.commons.utils import etcd_utils
from tendrl.commons.utils import log_utils as logger
class IsNodeTendrlManaged(objects.BaseAtom):
def __init__(self, *args, **kwargs):
super(IsNodeTendrlM... |
"""Tests for debugger functionalities in tf.Session with file:// URLs."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import shutil
import tempfile
from tensorflow.core.protobuf import config_pb2
from tensorflow.python.client import session
fr... |
#!/bin/python
import os, subprocess
import logging
from autotest.client import test
from autotest.client.shared import error
class gnome_vfs2(test.test):
"""
Autotest module for testing basic functionality
of gnome_vfs2
@author Ramesh YR, <EMAIL> ##
"""
version = 1
... |
"""
This suite of tests verifies that courses exported from one modulestore can be imported into
another modulestore and the result will be identical (ignoring changes to identifiers that are
the result of being imported into a course with a different course id).
It does this by providing facilities for creating and c... |
from eventlet import greenthread
from oslo_config import cfg
from oslo_db import exception as db_exc
from oslo_log import log as logging
import oslo_messaging
from oslo_serialization import jsonutils
from oslo_utils import timeutils
import sqlalchemy as sa
from sqlalchemy.orm import exc
from sqlalchemy import sql
from... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
################################################################################
# Documentation
################################################################################
ANSIBLE_METADATA = {'metadata_version': '1.1', 'statu... |
# -----------------------------------------------------------------------------
# yacc_rr.py
#
# A grammar with a reduce/reduce conflict
# -----------------------------------------------------------------------------
import sys
if ".." not in sys.path: sys.path.insert(0,"..")
import ply.yacc as yacc
from calclex impo... |
"""URL encoding support for messages types.
Protocol support for URL encoded form parameters.
Nested Fields:
Nested fields are repesented by dot separated names. For example, consider
the following messages:
class WebPage(Message):
title = StringField(1)
tags = StringField(2, repeated=True)
... |
from django.contrib.syndication.views import Feed
from django.shortcuts import get_object_or_404
from django_hosts.resolvers import reverse
from .models import FeedItem, FeedType
class BaseCommunityAggregatorFeed(Feed):
def item_title(self, item):
return item.title
def item_description(self, item):
... |
import os
import string
import math
import re
import subprocess
# I didn't implement getProperties, found it somewhere, just reads a java style
# properties file into a dictionary.
#Note: Fixed by Bryan Lunt <<EMAIL>> on Oct, 28, 2013 to handle properly escaped spaces in properties files.
import re
__property_separato... |
"""SCons.Tool.gcc
Tool-specific initialization for gcc.
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, 2010, 2011, 2012, 2013, 2014 Th... |
"""RPC compatible subprocess-type module.
This module defined both a task-side process class as well as a controller-side
process wrapper for easier access and usage of the task-side process.
"""
import logging
import os
import subprocess
import sys
import threading
import time
from legion.lib import common_lib
from... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.