content stringlengths 4 20k |
|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------------
import signal
import sys
import os
def mt_signal_handler(signal, frame):
global gout, goin
print '\nYou pressed Ctrl+C!'
goin.event.set()
time.sleep(0.1)
goin.event.... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
from django.core.files.uploadedfile import SimpleUploadedFile
from django.db import models
from django.forms import (
CharField, FileField, Form, ModelChoiceField, ModelForm,
)
from django.forms.models import ModelFormMetaclass
from d... |
from __future__ import absolute_import, unicode_literals, print_function
from rest_framework import serializers
from hyperkitty.models import Sender
class OptionalHyperlinkedRelatedField(serializers.HyperlinkedRelatedField):
def to_representation(self, obj):
value = getattr(obj, self.lookup_field)
... |
import os
import glob
import shutil
import settings
settings_dir = 'fortest/server1'
default_config = {'config': 'default'}
dev_config = {'config': 'dev'}
prod_config = {'config': 'prod'}
site_config = {'config': 'site'}
repo_dir = '/tmp/settings-repo'
git_settings_subdir = repo_dir + '/myapp1'
def setup_module():
... |
from __future__ import absolute_import
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.db import models
class Review(models.Model):
source = models.CharField(max_length=100)
content_type = model... |
import uuid
from openstack.network.v2 import floating_ip
from openstack.network.v2 import network
from openstack.network.v2 import port
from openstack.network.v2 import router
from openstack.network.v2 import subnet
from openstack.tests.functional import base
class TestFloatingIP(base.BaseFunctionalTest):
ROT_N... |
import logging
import logging.handlers
from traits.api import Any, Int, Str, Unicode
from colorlog import ColoredFormatter
import ansiconv
from automate.service import AbstractUserService
__all__ = ['LogStoreService']
class LogStoreService(AbstractUserService):
"""
Provides interface to log output. Us... |
#!/bin/python
import redis
import json
import time
import math
import sys
c = redis.StrictRedis(host='r-uf6db21c0dd00ee4.redis.rds.aliyuncs.com', password='')
cursor = 0
x={}
while True:
r = c.zscan('record_rds_all_score', cursor=cursor)
for k in r[1]:
pid = k[0]
info = c.get('adm_record_score... |
from openerp.osv import fields, orm, osv
from openerp import SUPERUSER_ID
from openerp.tools.translate import _
class ProjectTask(orm.Model):
_inherit = 'project.task'
def _get_marketplace(self, cr, uid, ids, prop, unknow_none, context=None):
# Get announcement or proposition linked to this task.
... |
import datetime
import pytz
from django.core.urlresolvers import reverse
from mock import patch
from courseware.access import has_access
from courseware.tests.helpers import LoginEnrollmentTestCase
from courseware.tests.factories import (
BetaTesterFactory,
StaffFactory,
GlobalStaffFactory,
Instructor... |
"""Tests for samba.dsdb."""
from samba.credentials import Credentials
from samba.samdb import SamDB
from samba.auth import system_session
from testtools.testcase import TestCase
from samba.ndr import ndr_unpack, ndr_pack
from samba.dcerpc import drsblobs
import ldb
import os
import samba
class DsdbTests(TestCase):
... |
"""Schema for packages.yaml configuration files.
.. literalinclude:: ../spack/schema/packages.py
:lines: 32-
"""
schema = {
'$schema': 'http://json-schema.org/schema#',
'title': 'Spack package configuration file schema',
'type': 'object',
'additionalProperties': False,
'patternProperties': {
... |
from __future__ import print_function
import os
import six
import pyrax
import pyrax.exceptions as exc
pyrax.set_setting("identity_type", "rackspace")
creds_file = os.path.expanduser("~/.rackspace_cloud_credentials")
pyrax.set_credential_file(creds_file)
pq = pyrax.queues
queues = pq.list()
if not queues:
print(... |
import ConfigParser
class Inputs:
versions = ["scrapbook15"]
default = ""
def __init__(self):
self.default = self.versions[0]
class Outputs:
versions = ["freemind09"]
default = ""
def __init__(self):
self.default = self.versions[0]
class Configuration:
__config = Config... |
from typing import List
import numpy
import torch
from allennlp.common import Registrable
from allennlp.common.util import JsonDict
from allennlp.nn import util
from allennlp.predictors import Predictor
class SaliencyInterpreter(Registrable):
"""
A `SaliencyInterpreter` interprets an AllenNLP Predictor's ou... |
from __future__ import print_function
from bokeh.browserlib import view
from bokeh.document import Document
from bokeh.embed import file_html
from bokeh.glyphs import Circle
from bokeh.objects import (
Plot, DataRange1d, LinearAxis, Grid, ColumnDataSource, PanTool, WheelZoomTool
)
from bokeh.resources import INLIN... |
from .windows import *
from ctypes import *
from .winuser import MAKEINTRESOURCE, LoadIcon, LoadCursor
import sys
import weakref
quit = False
class HandleMap(dict):
"""a special weakreference map for mapping window handles to python instances
when a python instance becomes garbage, the __dispose__ method of Handle... |
#!/usr/bin/env
# Copied from A Oram - seems to originally be from https://github.com/jhykes/rebin
import numpy as np
from scipy.interpolate import UnivariateSpline, RectBivariateSpline
class BoundedUnivariateSpline(UnivariateSpline):
"""
1D spline that returns a constant for x outside the specified domain.
... |
# encoding: utf-8
from __future__ import unicode_literals
import re
import json
import xml.etree.ElementTree
from .common import InfoExtractor
from ..compat import (
compat_parse_qs,
compat_str,
compat_urllib_parse,
compat_urllib_parse_urlparse,
compat_urllib_request,
compat_urlparse,
)
from .... |
"""
Provides a set of pluggable permission policies.
"""
from __future__ import unicode_literals
from django.http import Http404
from rest_framework.compat import is_authenticated
SAFE_METHODS = ('GET', 'HEAD', 'OPTIONS')
class BasePermission(object):
"""
A base class from which all permission classes sho... |
import pyfits as p
import matplotlib.pyplot as pl
from matplotlib.pylab import matshow
import matplotlib.mlab as mlab
from scipy.stats import norm
import numpy as n
from astroML.plotting import hist
from lmfit.models import SkewedGaussianModel
from sklearn.neighbors import KernelDensity as KDE
from astropy.stats import... |
"""Unit tests for BaseComponent."""
from typing import Any
from absl.testing import absltest
from robel.components.base import BaseComponent
from robel.utils.testing.mock_sim_scene import MockSimScene
class DummyComponent(BaseComponent):
"""Mock component for testing BaseComponent."""
def __init__(self, *... |
from gramps.gen.lib import EventType, EventRoleType
from gramps.gen.plug import Gramplet
from gramps.gui.widgets import Photo
from gramps.gen.display.name import displayer as name_displayer
from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
from gramps.gen.datehandler import get_date
... |
from __future__ import absolute_import
from __future__ import print_function
import numpy as np
np.random.seed(1337) # for reproducibility
from keras.datasets import reuters
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.layers.normalization import BatchNormali... |
from flask import jsonify, session
from indico.modules.oauth import oauth
from indico.modules.users import User
from indico.web.http_api.hooks.base import HTTPAPIHook
from indico.web.http_api.responses import HTTPAPIError
def fetch_authenticated_user():
valid, req = oauth.verify_request(['read:user'])
user =... |
__metaclass__ = type
__all__ = []
import os, sys
from jhbuild.errors import FatalError, BuildStateError
from jhbuild.utils.cmds import get_output
from jhbuild.versioncontrol import Repository, Branch, register_repo_type
def is_registered(archive):
location = os.path.join(os.environ['HOME'], '.arch-params',
... |
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
# this test has some wireframe geometry
# Make sure multisampling is disabled to avoid generating multiple
# regression images
... |
import datetime
import calendar
def mtime(t):
if isinstance(t, str):
t = datetime.datetime.strptime(t, '%Y-%m-%d %H:%M:%S').timetuple()
return datetime.datetime.utcfromtimestamp(calendar.timegm(t))
def from_rfc3339(t):
t = datetime.datetime.strptime(t[0:19], '%Y-%m-%dT%H:%M:%S').timetuple()
... |
"""
main views module to render pages.
"""
#import datetime
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils import importlib
from django.views.decorators.cache import never_cache
from django.http import HttpResponseRedirect, HttpResponseForbidden, Http404
fro... |
import sys
class TeamcityServiceMessages:
quote = {"'": "|'", "|": "||", "\n": "|n", "\r": "|r", ']': '|]', '[': '|['}
def __init__(self, output=sys.stdout, prepend_linebreak=False):
self.output = output
self.prepend_linebreak = prepend_linebreak
self.test_stack = []
"""
... |
from __future__ import unicode_literals
from datetime import timedelta
from celery.schedules import crontab
from flask import session, g
from indico.core.celery import celery
from indico.core.db import db
from indico.core.notifications import make_email, email_sender
from indico.modules.events.static import logger
f... |
import time
from selenium.common.exceptions import NoSuchElementException
class TDUtils():
def __init__(self, dir):
self.screenshot_count = 1
self.screenshot_dir = dir
self.driver = None
"""
Take screenshot and store files to defined location, with numbering prefix
:Args:
... |
def label_is_both(label):
return label in {'contenttypes'}
def label_is_auth(label):
""" Return if the label belongs exclusively to the auth_db. """
return label in {'auth', 'account', 'admin', 'sessions'}
def is_auth(obj, **hints):
if hints.get('target_db') == 'auth_db':
return True
ret... |
import os
import shutil
import sys
from color import Coloring
from command import InteractiveCommand, MirrorSafeCommand
from error import ManifestParseError
from project import SyncBuffer
from git_config import GitConfig
from git_command import git_require, MIN_GIT_VERSION
class Init(InteractiveCommand, MirrorSafeCom... |
"""
Verifies that msvs_list_excluded_files=0 doesn't list files that would
normally be in _excluded_files, and that if that flag is not set, then they
are still listed.
"""
import os
import TestGyp
test = TestGyp.TestGyp(formats=['msvs'], workdir='workarea_all')
# with the flag set to 0
try:
os.envi... |
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_... |
"""Classes to build sanitized HTML."""
__author__ = 'John Orr (<EMAIL>)'
import cgi
import re
def escape(strg):
return cgi.escape(strg, quote=1).replace("'", ''').replace('`', '`')
class Node(object):
"""Base class for the sanitizing module."""
@property
def sanitized(self):
raise... |
import json
import re
def basic_body_verification(body, url, is_json_check=True):
'''
Takes in a raw (stringy) response body, checks that it is non-empty,
and that it is valid JSON (i.e. can be deserialized into a dict/list of dicts)
Returns the deserialized body as a dict (or list of dicts), and also... |
import os
import utils.common as common
import utils.cryptojs as cryptojs
import json
from TestCase.MVSTestCase import *
class TestKeyfile(MVSTestCaseBase):
roles = MVSTestCaseBase.roles[:-1] # exclude Zac
need_mine = False
def test_dumpkeyfile(self):
description = "Alice & Bob & Cindy's multi-s... |
# -*- coding: utf-8 -*-
from .basededatos import BaseDeDatos
class PerPaciente(BaseDeDatos):
def obtener_uno(self, id_):
"""
Obtiene y retorna un objeto según el id dado.
:param id_: int >= 0
:return: object
"""
if id_ >= 0:
id_ = (id_,)
sql... |
from spack import *
class PerlVersion(PerlPackage):
"""Parse and manipulate Perl version strings"""
homepage = "http://search.cpan.org/~bdfoy/Perl-Version-1.013/lib/Perl/Version.pm"
url = "http://search.cpan.org/CPAN/authors/id/B/BD/BDFOY/Perl-Version-1.013_03.tar.gz"
version('1.013_03', 'b2c94... |
"""
Run Regression Test Suite
This module calls down into individual test cases via subprocess. It will
forward all unrecognized arguments onto the individual test scripts, other
than:
- `-extended`: run the "extended" test suite in addition to the basic one.
- `-win`: signal that this is running in a Windows... |
from supybot.test import *
try:
import sqlite
except ImportError:
sqlite = None
if sqlite:
class FactoidsTestCase(ChannelPluginTestCase):
plugins = ('Factoids',)
def testRandomfactoid(self):
self.assertError('random')
self.assertNotError('learn jemfinch as my primar... |
'''
>>> from data_members_ext import *
---- Test static data members ---
>>> v = Var('slim shady')
>>> Var.ro2a.x
0
>>> Var.ro2b.x
0
>>> Var.rw2a.x
0
>>> Var.rw2b.x
0
>>> v.ro2a.x
0
>>> v.ro2b.x
0
>>> v.rw2a.x
0
>>> v.rw2b.x
0
>>> Var.rw2a.x = 777
>>> Var.ro2a.x
777
>>> Var.ro2b.x
777
>>> Var.rw2a.x
777
>>> ... |
"""
This test file tests the lib/machine.py for attaching and detaching tokens
"""
HOSTSFILE = "tests/testdata/hosts"
from .base import MyTestCase
from privacyidea.lib.machine import (attach_token, detach_token, add_option,
delete_option, list_machine_tokens,
... |
# -*- coding: utf-8 -*-
# -*- mode: python; -*-
"""exec" "`dirname \"$0\"`/call.sh" "$0" "$@"; """
from __future__ import print_function
from __future__ import division
import sys
import os
from datetime import datetime, timedelta, tzinfo
import pytz
import collections
from operator import itemgetter
import json
__do... |
import pytest
from telegram import Update, User, ShippingAddress, ShippingQuery
@pytest.fixture(scope='class')
def shipping_query(bot):
return ShippingQuery(TestShippingQuery.id,
TestShippingQuery.from_user,
TestShippingQuery.invoice_payload,
... |
import numpy as np
from kernel import PseudoSpectralKernel, tendency_forward_euler, tendency_ab2, tendency_ab3
from numpy import pi
import logging
try:
import mkl
np.use_fastnumpy = True
except ImportError:
pass
try:
import pyfftw
pyfftw.interfaces.cache.enable()
except ImportError:
pass
c... |
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User, Group
from optparse import make_option
from sys import stdout
from csv import writer
FORMATS = [
'address',
'emails',
'google',
'outlook',
'linkedin',
'vcard',
]
def full_name(first_... |
"""Tests Keras integration with enable_mixed_precision_graph_rewrite()."""
import os
from tensorflow.python.framework import config
from tensorflow.python.keras import combinations
from tensorflow.python.keras import keras_parameterized
from tensorflow.python.keras import testing_utils
from tensorflow.python.keras.mi... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
def query_package(module, slackpkg_path, name):
import glob
import platform
m... |
"""
Validation information for an xblock instance.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import six
class ValidationMessage(object):
"""
A message containing validation information about an xblock.
"""
WARNING = "warning"
ERROR = "error"
TYP... |
"""
This plugin captures stdout during test execution. If the test fails
or raises an error, the captured output will be appended to the error
or failure output. It is enabled by default but can be disabled with
the options ``-s`` or ``--nocapture``.
:Options:
``--nocapture``
Don't capture stdout (any stdout out... |
__author__ = 'Frank Sehnke, <EMAIL>'
from . import sensors
import threading
from pybrain.utilities import threaded
from pybrain.tools.networking.udpconnection import UDPServer
from pybrain.rl.environments.environment import Environment
from scipy import ones, zeros, array, clip, arange, sqrt
from time import sleep
cl... |
from tools import config, ustr
fontsize = 12
#Make a python import for change function getImage in class EanBarCode
from openerp.addons.report_aeroo.barcode.EANBarCode import EanBarCode
class EanBarCodeInherit(EanBarCode):
def getImage(self, value, height = 50, xw=1, rotate=None, extension = "PNG", width = 5... |
{
'name': 'Calendar State',
'version': '8.0.1.0.0',
'category': 'Project Management',
'description': """
Calendar State
==============
""",
'author': 'ADHOC SA',
'website': 'www.adhoc.com.ar',
'depends': ['calendar'],
'data': [
'calendar_meeting_view.xml',
],
'dem... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from tornado.web import authenticated
from basehandlers import BaseHandler
class UploadFileHandler(BaseHandler):
@authenticated
def get(self):
if not self.current_user:
self.redirect("/login")
return
self.ren... |
from __future__ import print_function, division
from sympy.stats.drv import SingleDiscreteDistribution, SingleDiscretePSpace
from sympy import factorial, exp, S, sympify
from sympy.stats.rv import _value_check
__all__ = ['Geometric', 'Poisson']
def rv(symbol, cls, *args):
args = list(map(sympify, args))
dis... |
#!/usr/bin/env python
# LexGen.py - implemented 2002 by Neil Hodgson <EMAIL>
# Released to the public domain.
# Regenerate the Scintilla source files that list all the lexers.
# Should be run whenever a new lexer is added or removed.
# Requires Python 2.5 or later
# Files are regenerated in place with templates stored... |
from __future__ import print_function
import sys
import re
import hashlib
def error(s):
print('ERROR:', s, file=sys.stderr)
sys.exit(1)
# Functions are stored here, removing duplicates. Then they are printed.
class FunctionStore:
def __init__(self, namer):
self.functions = []
self.hash2idx... |
# python3
class JobQueue:
def __init__(self, num_workers=0, jobs=()):
self._num_workers = num_workers
self._jobs = list(jobs)
self._assigned_workers = [None] * len(self._jobs)
self._start_times = [None] * len(self._jobs)
@property
def num_workers(self):
return self... |
"""Module with functins for reading and writing files."""
__author__="Reinhard Fleissner"
__date__ ="$29.08.2014 18:21:40$"
# libraries
from PyQt4.QtGui import QFileDialog
def getOpenFileName(title, fileFormat, lineEdit, directory, wid):
filename = QFileDialog.getOpenFileName(wid, title, directory, fileFormat)
... |
"""Tests of grpc_reflection.v1alpha.reflection."""
import unittest
import grpc
from grpc_reflection.v1alpha import reflection
from grpc_reflection.v1alpha import reflection_pb2
from grpc_reflection.v1alpha import reflection_pb2_grpc
from google.protobuf import descriptor_pool
from google.protobuf import descriptor_p... |
import os
import sys
import codecs
from fnmatch import fnmatchcase
from distutils.util import convert_path
from setuptools import setup, find_packages
def read(fname):
return codecs.open(os.path.join(os.path.dirname(__file__), fname)).read()
# Provided as an attribute, so you can append to these instead
# of rep... |
from __future__ import absolute_import
from __future__ import with_statement
from Queue import Empty
from kombu import BrokerConnection, Exchange, Queue
from .utils import TestCase
from .utils import Mock
class SimpleBase(TestCase):
abstract = True
def Queue(self, name, *args, **kwargs):
q = name
... |
from __future__ import print_function
import os
import re
import sys
import settings
LICENSE = re.compile(
r'((#|//|\*) Copyright .*\n'
r')+\s?\2\n'
r'\s?\2 Licensed under the Apache License, Version 2.0 \(the "License"\);\n'
r'\s?\2 you may not use this file except in compliance with the License.\n'
... |
import datetime
from django.test import TestCase
from django.utils import timezone
from polls.models import Poll, Choice, Vote
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
import django_webtest
if User.objects.filter(username='dralley'):
user = User.objects.get(username=... |
""" The Machine/Job Features TimeLeft utility interrogates the MJF values
for the current CPU and Wallclock consumed, as well as their limits.
"""
import os
import time
import urllib
from DIRAC import gLogger, S_OK, S_ERROR
__RCSID__ = "$Id$"
class MJFTimeLeft( object ):
""" Class for creating objects that de... |
import json
import jsonschema
import pytest
from datetime import datetime
from normandy.recipes import signing
from pytest_testrail.plugin import testrail
def canonical_json(data):
return json.dumps(data, ensure_ascii=True, separators=(',', ':'), sort_keys=True).encode()
def check_action_schema_format(action)... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from ansible import constants as C
from . import InventoryParser
class InventoryIniParser(InventoryAggregateParser):
CONDITION="is_file(%s)"
def __init__(self, inven_directory):
directory = inven_direc... |
from __future__ import absolute_import
import ctypes
import hashlib
from st2reactor.container.partitioners import (
DefaultPartitioner,
get_all_enabled_sensors,
)
__all__ = ["HashPartitioner", "Range"]
# The range expression serialized is of the form `RANGE_START..RANGE_END|RANGE_START..RANGE_END ...`
SUB_RA... |
# -*- coding: utf-8 -*-
"""
There are two strategies of this hook.
1. double render: It means the files would be rendered once by cookiecutter and
also rendered by this module.
2. delete redundant file: In short, delete! Since I have all the possible
files, which should or should not be needed in the template, configur... |
from keystoneclient import base
from keystoneclient import exceptions
from keystoneclient.i18n import _
from keystoneclient import utils
class Trust(base.Resource):
"""Represents a Trust.
Attributes:
* id: a uuid that identifies the trust
* impersonation: allow explicit impersonation
... |
#https://www.exploit-db.com/exploits/37359/
def readx86( filee):
shellcode = r"\x31\xc9\x31\xc0\x31\xd2\x51\xb0\x05"
shellcode += filee
shellcode += r"\x89\xe3\xcd\x80\x89\xd9\x89\xc3\xb0\x03\x66"
shellcode += r"\xba\xff\x0f\x66\x42\xcd\x80\x31"
shellcode += r"\xc0\x31\xdb\xb3\x01\xb0\x04\xcd\x80\x31\xc0\xb0\x01... |
from south.db import db
from django.db import models
from chaining.models import *
class Migration:
def forwards(self, orm):
# Adding model 'Category'
db.create_table('chaining_category', (
('id', orm['chaining.Category:id']),
('name', orm['chaining.Category:na... |
from openstack import format
from openstack import resource2
from rackspace.load_balancer import load_balancer_service
class LoadBalancer(resource2.Resource):
resource_key = "loadBalancer"
resources_key = "loadBalancers"
base_path = "/loadbalancers"
service = load_balancer_service.LoadBalancerService... |
class Smartphone():
voltaje_maximo = 5
@classmethod
def _carga(cls, voltaje_entrante):
if voltaje_entrante > cls.voltaje_maximo:
print(f"Voltaje Entrada: {voltaje_entrante}V Mestoy quemando :C!!!")
else:
print(f"Voltaje Salida: {voltaje_entrante}V -- Cargando...")
... |
# -*- coding: utf-8 -*-
"""
Current25 Plugin
Copyright (C) 2011-2012 Olaf Lüke <<EMAIL>>
Copyright (C) 2014-2016 Matthias Bolte <<EMAIL>>
current25.py: Current25 Plugin Implementation
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published... |
import pymel.core as pm
from ..errors import errors
from ..maya_testing import general
import control
# plane
def build_plane(name=None, crv=None, spans=None,
direction='u', width_axis=None,
width=1, log=True):
'''Given a valid curve, build nurbs plane
Attributes:
name... |
#!/usr/bin/env python3
import sys
import re
MAPPING = {
'core_read.cpp': 'core_io.cpp',
'core_write.cpp': 'core_io.cpp',
}
def module_name(path):
if path in MAPPING:
path = MAPPING[path]
if path.endswith(".h"):
return path[:-2]
if path.endswith(".c"):
return path[:-2]
... |
import datetime
import types
from socorro.external.postgresql.missing_symbols import MissingSymbols
from socorro.unittest.external.postgresql.unittestbase import PostgreSQLTestCase
class IntegrationTestMissingSymbols(PostgreSQLTestCase):
"""Test socorro.external.postgresql.missing_symbols.MissingSymbols
clas... |
import unittest
from catkit import Gratoms
from catkit.gen.utils import to_gratoms
from ase.constraints import FixAtoms
from ase.build import molecule
import networkx as nx
class TestGratoms(unittest.TestCase):
"""Test features of the gratoms module."""
def test_edge_addition(self):
"""Test that edge... |
"""
Test ftpparse routine.
"""
import unittest
from linkcheck.ftpparse import ftpparse
patterns = (
# EPLF format
# http://pobox.com/~djb/proto/eplf.html
("+i8388621.29609,m824255902,/,\tdev",
dict(name='dev', tryretr=False, trycwd=True)),
("+i8388621.44468,m839956783,r,s10376,\tRFCEPLF",
di... |
from django.db import models
from jsonfield import JSONField
# Create your models here.
class Query(models.Model):
"""Represents a search term"""
KINGDOM_CHOICES = (
('All', 'Search all kingdoms'),
('Animalia', 'Animals'),
('Fungi', 'Fungi'),
('Plantae', 'Plants'),
)
... |
"""
DO NOT INSTANTIATE THIS CLASS!!!!
Instead use subclasses that actually contain the net architectures
General information about TensorNet
- Save will save the current sessions variables to the given path.
If no path given, it saves to 'self.dir/[timestamped net name].ckpt'
- Lo... |
from cms.test_utils.project.placeholderapp.views import example_view
from cms.utils.conf import get_cms_setting
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls.i18n import i18n_patterns
from django.views.i18n import javascript_catalog
fro... |
from psycopg2.extensions import AsIs
from skygear.utils import db
from .exc import AlreadyDeletedException
from .predicate import Predicate
from .pubsub import _publish_record_event
from .query import Query
from .record import ChatRecord
from .user_conversation import UserConversation
from .utils import _get_schema_n... |
import shutil
import sys
import logging
import tempfile
import unittest
import os
import anima
from anima.ui import IS_PYSIDE, IS_PYQT4, SET_PYSIDE
from anima.ui.testing import PatchedMessageBox
SET_PYSIDE()
if IS_PYSIDE():
from PySide import QtCore, QtGui
from PySide.QtTest import QTest
from PySide.QtC... |
import nose
import os
import shutil
import tempfile
import cle
TEST_BASE = os.path.join(os.path.dirname(os.path.realpath(__file__)),
os.path.join('..', '..', 'binaries'))
def test_runpath():
tempdir = tempfile.mkdtemp()
try:
runpath_file = os.path.join(TEST_BA... |
"""AWS Cloud Volumes Services - Manage Snapshots"""
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import ansible.module_utils.netapp as... |
"""Stubouts, mocks and fixtures for the test suite."""
import copy
import datetime
import six
from nova import exception
class FakeModel(object):
"""Stubs out for model."""
def __init__(self, values):
self.values = values
def __getattr__(self, name):
return self.values[name]
def _... |
import os
import sys
sys.path.insert( 0, os.path.normpath(os.path.join( os.path.dirname( __file__ ), '..') ))
from aql_tests import skip, AqlTestCase, runLocalTests
from aql.utils import Tempdir, Tempfile, removeUserHandler, addUserHandler, enableDefaultHandlers
from aql.main import Project, ProjectConfig, ErrorTool... |
'''
An negation detection algorithm based on known negation markers. This implementation is inspired by the NegEx algorithm (Chapman et al 2001)
It works by scanning for known explicit negating markers in the form of unigrams and bigrams.
A found pattern triggers a negated 'window' of specific size in tokens.
... |
import json
import os
import threading
from pylib import constants
_BLACKLIST_JSON = os.path.join(
constants.DIR_SOURCE_ROOT,
os.environ.get('CHROMIUM_OUT_DIR', 'out'),
'bad_devices.json')
# Note that this only protects against concurrent accesses to the blacklist
# within a process.
_blacklist_lock = thr... |
import binascii
from yabgp.tlv import TLV
from ..linkstate import LinkState
# https://datatracker.ietf.org/doc/draft-ietf-idr-bgp-ls-segment-routing-ext/?include_text=1
# 0 1 2 3
# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
# +-+-+... |
from __future__ import unicode_literals
from datetime import datetime
from decimal import Decimal
import warnings
from django.conf import settings
from django.test import TestCase
from django.test.utils import override_settings
from django.utils import timezone
from six import b, text_type
from six.moves.urllib.parse... |
from collections import deque
class BinarySearchTree(object):
def __init__(self, data, parent=None):
self.data = data
self.left = None
self.right = None
self.parent = parent
def insert(self, data):
if self.data:
if self.data < data:
if self.... |
from burp import IScanIssue
from array import array
import cgi
class ScanIssue( IScanIssue ):
def __init__( self, callbacks, baseRequestResponse, insertionPoint, channel ):
self._callbacks = callbacks
self._helpers = callbacks.getHelpers()
self._baseRequestResponse = baseRequestResponse
... |
"""
The utils module contains a number of utility functions used by other modules.
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
from numbers import Number
from random import uniform
from random import ... |
""" OpenERP core exceptions.
This module defines a few exception types. Those types are understood by the
RPC layer. Any other exception type bubbling until the RPC layer will be
treated as a 'Server error'.
If you consider introducing new exceptions, check out the test_exceptions addon.
"""
# kept for backward comp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.