content string |
|---|
microcode = '''
def macroop SAHF {
ruflags ah, dataSize=1
};
def macroop LAHF {
wruflags ah, t0, dataSize=1
};
''' |
"""A collection of modules for building different kinds of tree from
HTML documents.
To create a treebuilder for a new type of tree, you need to do
implement several things:
1) A set of classes for various types of elements: Document, Doctype,
Comment, Element. These must implement the interface of
_base.treebuilders... |
# -*- coding: iso-8859-1 -*-
#############################################################################################
# Name: unittest_Ingestor.py
# Description: test cases for Ingestor class
#############################################################################################
import sys,os,unittest
sys.pa... |
from View import BackgroundLayer
from Input import KeyListener
from Camera import Camera
from OpenGL.GL import *
from OpenGL.GLU import *
class Scene(BackgroundLayer, KeyListener):
def __init__(self, engine):
self.engine = engine
self.actors = []
self.camera = Camera()
self.worl... |
"""
Courseware page.
"""
from .course_page import CoursePage
class CoursewarePage(CoursePage):
"""
Course info.
"""
url_path = "courseware/"
xblock_component_selector = '.vert .xblock'
def is_browser_on_page(self):
return self.q(css='body.courseware').present
@property
def ... |
from django.db import models
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
class Award(models.Model):
name = models.CharField(max_length=25)
object_id = models.PositiveIntegerField()
content_type = models.ForeignKey(ContentType)
content_obje... |
import os
import os.path
import audio_profile
TEXT = "hello"
OUTPUT = "output.mp3"
EFFECTS_PROFILE_ID = "telephony-class-application"
def test_audio_profile(capsys):
if os.path.exists(OUTPUT):
os.remove(OUTPUT)
assert not os.path.exists(OUTPUT)
audio_profile.synthesize_text_with_audio_profile(TE... |
import helium
import unittest
class TestBitvec(unittest.TestCase):
def test_Fingerprint(self):
fp = helium.Fingerprint(8)
self.assertEqual(8, fp.numWords)
fp = helium.Fingerprint(1)
self.assertEqual('0000000000000000', fp.hex())
self.assertEqual('0000000000000000 000000000... |
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep th... |
# -*- encoding: utf-8 -*-
from .models import CityDict, CourseOrg, Teacher
import xadmin
_author_ = 'shishengjia'
_date_ = '05/01/2017 13:36'
class CityDictAdmin(object):
list_display = ['name', 'desc', 'add_time']
search_fields = ['name', 'desc']
list_filter = ['name', 'desc', 'add_time']
class Cour... |
"""
Developed by <EMAIL>
"""
import redis
from gluon import current
from gluon.storage import Storage
import time
import logging
import thread
logger = logging.getLogger("web2py.session.redis")
locker = thread.allocate_lock()
def RedisSession(*args, **vars):
"""
Usage example: put in models
from gluon.... |
import argparse
import collections
import csv
import re
import json
import os
import random
import subprocess
import sys
import time
import urllib2
import zlib
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
OWNERS_PATH = os.path.abspath(
os.path.join(BASE_DIR, '..', 'test', 'test_owners.csv'))
GCS_URL_BASE ... |
"""
Django settings for server project.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
NOTE: __generator-djangularjs__ may automatically modified this file.
"""
# Bu... |
#!/usr/bin/env python
from nose.tools import assert_equal
import networkx as nx
from networkx.algorithms import bipartite
from networkx.testing import assert_edges_equal, assert_nodes_equal
class TestBipartiteProject:
def test_path_projected_graph(self):
G=nx.path_graph(4)
P=bipartite.projected_gr... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from ansible.template import Templar
class IncludedFile:
def __init__(self, filename, args, task):
self._filename = filename
self._args = args
self._task = task
self._hosts ... |
from __future__ import absolute_import, division, print_function, \
with_statement
import os
import sys
import hashlib
import logging
import binascii
import struct
import base64
import datetime
import random
from shadowsocks import common
from shadowsocks.obfsplugin import plain
from shadowsocks.common import to_... |
# -*- coding: utf-8 -*-
#------------------------------------------------------------
# streamondemand - XBMC Plugin
# Canal para sports-main
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import urlparse,urllib2,urllib,re
import os, sys
from cor... |
import numpy as np
import warnings
from astropy.convolution import convolve_fft, MexicanHat2DKernel
import statsmodels.formula.api as sm
from pandas import Series, DataFrame
try:
from scipy.fftpack import fftn, ifftn, fftfreq
except ImportError:
from numpy.fft import fftn, ifftn, fftfreq
class Mexican_hat():... |
from __future__ import print_function
import subprocess
from tempfile import NamedTemporaryFile
from airflow.exceptions import AirflowException
from airflow.hooks.base_hook import BaseHook
from airflow.utils.file import TemporaryDirectory
class PigCliHook(BaseHook):
"""
Simple wrapper around the pig CLI.
... |
# DER encoder
from pyasn1.type import univ
from pyasn1.codec.cer import encoder
from pyasn1 import error
class SetOfEncoder(encoder.SetOfEncoder):
def _cmpSetComponents(self, c1, c2):
tagSet1 = isinstance(c1, univ.Choice) and \
c1.getEffectiveTagSet() or c1.getTagSet()
tagSet2 = i... |
# coding=utf-8
"""
Runs third party scripts and collects their output.
Scripts need to be +x and should output metrics in the form of
```
metric.path.a 1
metric.path.b 2
metric.path.c 3
```
They are not passed any arguments and if they return an error code,
no metrics are collected.
#### Dependencies
* [subproce... |
# encoding: 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):
db.execute("create unique index email on auth_user (email)")
pass
def backwards(self, orm):
db.execut... |
from __future__ import absolute_import, print_function, unicode_literals
import functools
import collections
def save_method_args(method):
"""
Wrap a method such that when it is called, we save the args and
kwargs with which it was called.
>>> class MyClass(object):
... @save_method_args
... |
from django.test import TestCase
from rest_framework import status
from rest_framework.response import Response
from rest_framework.test import APIRequestFactory
from rest_framework.viewsets import GenericViewSet
factory = APIRequestFactory()
class BasicViewSet(GenericViewSet):
def list(self, request, *args, **... |
import sys
from sklearn.externals.six.moves import cStringIO as StringIO
import numpy as np
import warnings
from sklearn.base import BaseEstimator
from sklearn.learning_curve import learning_curve, validation_curve
from sklearn.utils.testing import assert_raises
from sklearn.utils.testing import assert_warns
from sklea... |
from datetime import date
from openerp.tests.common import TransactionCase
from openerp.osv.orm import except_orm
class TestPeriodState(TransactionCase):
"""
Forbid creation of Journal Entries for a closed period.
"""
def setUp(self):
super(TestPeriodState, self).setUp()
cr, uid = sel... |
# -*- coding: utf-8 -*-
"""
A list of Mexican states for use as `choices` in a formfield.
This exists in this standalone file so that it's only imported into memory
when explicitly needed.
"""
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
# All 31 states, plus the `D... |
from openerp.addons.account.tests.account_test_classes import AccountingTestCase
class AccountTestUsers(AccountingTestCase):
"""Tests for diffrent type of user 'Accountant/Adviser' and added groups"""
def setUp(self):
super(AccountTestUsers, self).setUp()
self.res_user_model = self.env['res.... |
from pyspark.testing.sqlutils import ReusedSQLTestCase
class ConfTests(ReusedSQLTestCase):
def test_conf(self):
spark = self.spark
spark.conf.set("bogo", "sipeo")
self.assertEqual(spark.conf.get("bogo"), "sipeo")
spark.conf.set("bogo", "ta")
self.assertEqual(spark.conf.get... |
import webob.exc
from cinder.api import extensions
from cinder.api.openstack import wsgi
class FoxInSocksController(object):
def index(self, req):
return "Try to say this Mr. Knox, sir..."
class FoxInSocksServerControllerExtension(wsgi.Controller):
@wsgi.action('add_tweedle')
def _add_tweedle(... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
# take a list of files and (optionally) a list of paths
# return the first existing file found in the paths
# [file1, file2, file3], [path1, path2, path3]
# search order is:
# path1/file1
# path1/file2
# path1/file3
# path2/file1
#... |
import warnings
from django.core.exceptions import ValidationError
from django.db.models.query import QuerySet
from rest_framework.response import Response
class BaseMultipleModelMixin(object):
"""
Base class that holds functions need for all MultipleModelMixins/Views
"""
querylist = None
# Keys... |
# -*- coding: utf-8 -*-
"""
pygments.formatters.svg
~~~~~~~~~~~~~~~~~~~~~~~
Formatter for SVG output.
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.formatter import Formatter
from pygments.util import get_bool_opt, get... |
from __future__ import (absolute_import, division, print_function)
from units.compat import unittest
from units.compat.mock import MagicMock
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.playbook import Playbook
from ansible.plugins.callback import CallbackBase
from ansible.utils impor... |
#!/usr/bin/env python
from __future__ import unicode_literals
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
long_description = (
'Autosub is a utility for automatic speech recognition and subtitle generation. '
'It takes a video or an audio file as input, perfo... |
from django.template.defaultfilters import capfirst # noqa
from django.template.defaultfilters import floatformat # noqa
from django.utils.translation import ugettext as _ # noqa
from django.views.generic import TemplateView # noqa
from openstack_dashboard import usage
from openstack_dashboard.usage import base
... |
import operator
import warnings
from django import template
from django.template.defaultfilters import stringfilter
from django.utils import six
from django.utils.html import escape, format_html
register = template.Library()
@register.filter
@stringfilter
def trim(value, num):
return value[:num]
@register.fil... |
from collections import namedtuple
from ..exceptions import LocationParseError
class Url(namedtuple('Url', ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment'])):
"""
Datastructure for representing an HTTP URL. Used as a return value for
:func:`parse_url`.
"""
slots = ()
def __new... |
# -*- coding: utf-8 -*-
from datetime import datetime
from dateutil.relativedelta import relativedelta
from openerp import api, fields, models, tools
_INTERVALS = {
'hours': lambda interval: relativedelta(hours=interval),
'days': lambda interval: relativedelta(days=interval),
'weeks': lambda interval: r... |
from __future__ import absolute_import, unicode_literals
import logging
import os
import subprocess
import sys
from mozprocess.processhandler import ProcessHandlerMixin
from .logging import LoggingMixin
# Perform detection of operating system environment. This is used by command
# execution. We only do this once t... |
from __future__ import absolute_import
import sqlalchemy as sa
from sqlalchemy.orm import relationship
from sqlalchemy.schema import Index
from relengapi.blueprints.slaveloan import rest
from relengapi.lib import db
from relengapi.util import tz
_tbl_prefix = 'slaveloan_'
class Machines(db.declarative_base('releng... |
try:
import paramiko
from boto.manage.cmdshell import SSHClient
except ImportError:
paramiko = None
SSHClient = None
from tests.compat import mock, unittest
class TestSSHTimeout(unittest.TestCase):
@unittest.skipIf(not paramiko, 'Paramiko missing')
def test_timeout(self):
client_tmp =... |
from __future__ import unicode_literals
from ..lint import check_path
from .base import check_errors
import pytest
import six
def test_allowed_path_length():
basename = 29 * "test/"
for idx in range(5):
filename = basename + idx * "a"
errors = check_path("/foo/", filename, False)
che... |
import subprocess
from subprocess import PIPE
import os
import tempfile
try:
import ctypes
except ImportError:
import plat
if plat.HOST_PLATFORM == plat.WINDOWS:
raise EnvironmentError("ctypes module missing for Windows.")
ctypes = None
def get_startup_info():
# Hide the child process wi... |
class Qualifications:
def __init__(self, requirements=None):
if requirements == None:
requirements = []
self.requirements = requirements
def add(self, req):
self.requirements.append(req)
def get_as_params(self):
params = {}
assert(len(self.requirements)... |
"""
XML based calendar user proxy loader.
"""
__all__ = [
"XMLCalendarUserProxyLoader",
]
import types
from twisted.internet.defer import inlineCallbacks
from twext.python.log import Logger
from twistedcaldav.config import config, fullServerPath
from twistedcaldav.xmlutil import readXML
from txdav.who.delegat... |
# python standard library
from collections import namedtuple
Parameters = namedtuple("Parameters", "name parameters".split())
class TreeNode(object):
"""
A Class to represent a node in a tree with arbitrary number of children
"""
def __init__(self, cargo, children=None):
"""
:param:
... |
from flask import jsonify, request
from flask_restful import Resource
class Tls(Resource):
def __init__(self, dring):
self.dring = dring
def get(self):
data = request.args
if (not data):
return jsonify({
'status': 404,
'message': 'data not f... |
#!/usr/bin/env python
# Last modified: July 23rd, 2009
"""
pydiction.py 1.2 by Ryan Kulla (rkulla AT gmail DOT com).
Description: Creates a Vim dictionary of Python module attributes for Vim's
completion feature. The created dictionary file is used by
the Vim ftplugin "python_pydiction.vim... |
from django.conf import settings
HIGHLIGHTJS_DEFAULTS = {
"jquery_url": "//code.jquery.com/jquery.min.js",
"base_url": "//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.3/highlight.min.js",
"css_url": "//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.3/styles/{0}.min.css",
"include_jquery": False,
"... |
from testtools import testcase
from sahara.tests.integration.configs import config as cfg
from sahara.tests.integration.tests import base as b
from sahara.tests.integration.tests import cinder
from sahara.tests.integration.tests import cluster_configs
from sahara.tests.integration.tests import edp
from sahara.tests.in... |
"""
Sensor for Steam account status.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.steam_online/
"""
from blumate.helpers.entity import Entity
from blumate.const import CONF_API_KEY
ICON = 'mdi:steam'
REQUIREMENTS = ['steamodd==4.21']
# pylin... |
"""
Helps to implement authentication and authorization using Auth0.
Offers functions for generating the view functions needed to implement Auth0,
a login screen, callback maker, and a function decorator for protecting
endpoints.
"""
import flask
import requests
import functools
import json
import base64
import jwt
... |
__author__ = 'mouton'
from unittest import TestCase
from triggerExpressions import Rand, Evaluation
from database import Variable
from test.testsTriggersExpressions import simpleTests
from arithmeticExpressions import ALitteral
class TestRand(TestCase):
@classmethod
def setUpClass(cls):
import gramm... |
"""
Middleware decorator for removing headers.
"""
from __future__ import absolute_import
from functools import wraps
from openedx.core.djangoapps.header_control import force_header_for_response, remove_headers_from_response
def remove_headers(*headers):
"""
Decorator that removes specific headers from the... |
"""
Utility functions to deal with ppm (qemu screendump format) files.
@copyright: Red Hat 2008-2009
"""
import os, struct, time, re
from autotest_lib.client.bin import utils
# Some directory/filename utils, for consistency
def find_id_for_screendump(md5sum, dir):
"""
Search dir for a PPM file whose name en... |
apiAttachAvailable = u'API jest dost\u0119pne'
apiAttachNotAvailable = u'Niedost\u0119pny'
apiAttachPendingAuthorization = u'Autoryzacja w toku'
apiAttachRefused = u'Odmowa'
apiAttachSuccess = u'Sukces'
apiAttachUnknown = u'Nieznany'
budDeletedFriend = u'Usuni\u0119ty z listy znajomych'
budFriend = u'Znajomy'
budNeverB... |
import functools
import logging
def Memoize(f):
"""Decorator to cache return values of function."""
memoize_dict = {}
@functools.wraps(f)
def wrapper(*args, **kwargs):
key = repr((args, kwargs))
if key not in memoize_dict:
memoize_dict[key] = f(*args, **kwargs)
return memoize_dict[key]
ret... |
def stoprockpaperscissors():
global inmoov
global human
rest()
sleep(5)
if inmoov < human:
i01.mouth.speak("congratulations you won with" + str(human - inmoov) + "points")
sleep(3)
i01.mouth.speak(str(human) + "points to you and" + str(inmoov) + "points to me")
elif inmoov > human: ... |
import textwrap
import unittest
from conda_rpms.build import name_version_release
class Test_name_version_release(unittest.TestCase):
def _check_output(self, spec):
expected = {'name': 'foo', 'release':'2', 'version':'1'}
actual = name_version_release(textwrap.dedent(spec).split('\n'))
se... |
"""Test domain corner cases."""
from __future__ import absolute_import, print_function, unicode_literals
import unittest
from mailmanclient import Client
from six.moves.urllib_error import HTTPError
__metaclass__ = type
__all__ = [
'TestDomains',
]
class TestDomains(unittest.TestCase):
def setUp(self... |
Import ('env')
can_build = False
if env.get('BOOST_LIB_VERSION_FROM_HEADER'):
boost_version_from_header = int(env['BOOST_LIB_VERSION_FROM_HEADER'].split('_')[1])
if boost_version_from_header >= 56:
can_build = True
if not can_build:
print 'WARNING: skipping building the optional CSV datasource pl... |
import logging
import os
import sys
import warnings
from dataclasses import dataclass
from typing import List, Mapping
from pants.base.exception_sink import ExceptionSink
from pants.base.exiter import ExitCode
from pants.bin.remote_pants_runner import RemotePantsRunner
from pants.engine.environment import CompleteEnvi... |
"""
shared options and groups
The principle here is to define options once, but *not* instantiate them globally.
One reason being that options with action='append' can carry state between parses.
pip parse's general options twice internally, and shouldn't pass on state.
To be consistent, all options will follow this d... |
import math
import m5
from m5.objects import *
from m5.defines import buildEnv
from Ruby import create_topology
from Ruby import send_evicts
#
# Note: the cache latency is only used by the sequencer on fast path hits
#
class Cache(RubyCache):
latency = 3
def define_options(parser):
return
def create_system(o... |
from gi.repository import Gtk
from eolie.toolbar_actions import ToolbarActions
from eolie.toolbar_title import ToolbarTitle
from eolie.toolbar_end import ToolbarEnd
class Toolbar(Gtk.EventBox):
"""
Eolie toolbar
"""
def __init__(self, window, fullscreen=False):
"""
Init toolb... |
r"""Converts a trained checkpoint into a frozen model for mobile inference.
Once you've trained a model using the `train.py` script, you can use this tool
to convert it into a binary GraphDef file that can be loaded into the Android,
iOS, or Raspberry Pi example code. Here's an example of how to run it:
bazel run ten... |
import re
import sys
pat = re.compile('(?P<name>[^=]+)="(?P<value>[^"]*)" *')
counterPat = re.compile('(?P<name>[^:]+):(?P<value>[^,]*),?')
def parse(tail):
result = {}
for n,v in re.findall(pat, tail):
result[n] = v
return result
mapStartTime = {}
mapEndTime = {}
reduceStartTime = {}
reduceShuffleTime = {... |
import json
import uuid
from flask import Flask,request,make_response
from beaker.middleware import SessionMiddleware
app = Flask(__name__)
tenant_networks = []
tenant_ports = []
@app.route("/ws.v1/login", methods=["POST",])
def login():
assert "username" in request.form
assert "password" in request.form
re... |
from optparse import make_option
from django.contrib.gis import gdal
from django.core.management.base import LabelCommand, CommandError
def layer_option(option, opt, value, parser):
"""
Callback for `make_option` for the `ogrinspect` `layer_key`
keyword option which may be an integer or a string.
"""
... |
# -*- coding: utf-8 -*-
from .common import KARMA, TestForumCommon
from ..models.forum import KarmaError
from openerp.exceptions import UserError, AccessError
from openerp.tools import mute_logger
class TestForum(TestForumCommon):
@mute_logger('openerp.addons.base.ir.ir_model', 'openerp.models')
def test_as... |
import unittest
from swift_build_support.targets import StdlibDeploymentTarget
class HostTargetTestCase(unittest.TestCase):
def test_is_not_none_on_this_platform(self):
self.assertIsNotNone(StdlibDeploymentTarget.host_target())
class PlatformTargetsTestCase(unittest.TestCase):
def test_platform_con... |
"""Generate a keymap.json from a keymap.c file.
"""
import json
from milc import cli
import qmk.keymap
import qmk.path
@cli.argument('--no-cpp', arg_only=True, action='store_false', help='Do not use \'cpp\' on keymap.c')
@cli.argument('-o', '--output', arg_only=True, type=qmk.path.normpath, help='File to write to')... |
from __future__ import unicode_literals
import base64
import binascii
import hashlib
from django.dispatch import receiver
from django.conf import settings
from django.test.signals import setting_changed
from django.utils import importlib
from django.utils.datastructures import SortedDict
from django.utils.encoding im... |
# Implements _both_ a connectable client, and a connectable server.
#
# Note that we cheat just a little - the Server in this demo is not created
# via Normal COM - this means we can avoid registering the server.
# However, the server _is_ accessed as a COM object - just the creation
# is cheated on - so this is still ... |
"""Wrapper for using the Scikit-Learn API with Keras models.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
import types
import numpy as np
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.utils.generic_ut... |
__all__ = ['BaseRepresenter', 'SafeRepresenter', 'Representer',
'RepresenterError']
from error import *
from nodes import *
import datetime
import sys, copy_reg, types
class RepresenterError(YAMLError):
pass
class BaseRepresenter(object):
yaml_representers = {}
yaml_multi_representers = {}
de... |
'''
Created on Aug 22, 2011
@author: hussain.bohra
@author: fabioz
'''
import os
import sys
import unittest
#=======================================================================================================================
# Test
#================================================================================... |
import unittest
from metrics import test_page_test_results
from metrics import timeline
from telemetry.timeline import model as model_module
from telemetry.web_perf import timeline_interaction_record as tir_module
def _GetInteractionRecord(start, end):
return tir_module.TimelineInteractionRecord("test-record", star... |
import os
import re
def check(host, fs):
"""
check the svn config file
return with three logical value:
is svn config file missing, is auto-props missing, is the svn:mime-type for png missing
"""
cfg_file_path = config_file_path(host, fs)
try:
config_file = fs.read_text_file(cfg_... |
{
'name': 'Budgets Management',
'version': '1.0',
'category': 'Accounting & Finance',
'description': """
This module allows accountants to manage analytic and crossovered budgets.
==========================================================================
Once the Budgets are defined (in Invoicing/Budge... |
import os
import mock
from nectar.report import DownloadReport
import base_downloader
from pulp_puppet.common import constants
from pulp_puppet.plugins.importers.downloaders import exceptions, web
from pulp_puppet.plugins.importers.downloaders.web import HttpDownloader
TEST_SOURCE = 'http://forge.puppetlabs.com/'
... |
"""This code example creates a new mobile line item. Mobile features needs to be
enabled in your account to use mobile targeting. To determine which line
items exist, run get_all_line_items.py. To determine which orders exist, run
get_all_orders.py. To determine which placements exist, run
get_all_placements.py."""
__... |
from __future__ import (
unicode_literals,
print_function,
absolute_import,
division
)
from netprofile.common.modules import ModuleBase
from sqlalchemy.orm.exc import NoResultFound
from pyramid.i18n import TranslationStringFactory
_ = TranslationStringFactory('netprofile_entities')
class Module(ModuleBase):
de... |
import inspect
import re
from django.apps import apps as django_apps
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured, PermissionDenied
from django.middleware.csrf import rotate_token
from django.utils.crypto import constant_time_compare
from django.utils.module_loading import i... |
from flexlay import ObjMapObject
from flexlay.math import Point, Origin, Size, Sizef, Rectf
class ObjMapSpriteObject(ObjMapObject):
def __init__(self, sprite, pos, metadata):
super().__init__(pos, metadata)
self.sprite = sprite
self.pos = pos
self.metadata = metadata
def dra... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'certified'}
DOCUMENTATION = r'''
---
module: bigip_device_dns
short_description: Manage BIG-IP d... |
#!/usr/bin/python
# coding=utf-8
##########################################################################
from test import CollectorTestCase
from test import get_collector_config
from test import unittest
from mock import Mock
from mock import patch
from mock import call
from collections import Iterator
from diamon... |
import time
DAYS_PER_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def is_leap(year):
return (year % 4) == 0
def test():
seconds = 0
wday = 5 # Jan 1, 2000 was a Saturday
for year in range(2000, 2034):
print("Testing %d" % year)
yday = 1
for month in range(1, ... |
from __future__ import print_function
import re, time, threading, socket, SocketServer
from binascii import hexlify, unhexlify
from nacl.secret import SecretBox
from ..util import ipaddrs
from ..util.hkdf import HKDF
class TransitError(Exception):
pass
# The beginning of each TCP connection consists of the follow... |
from gevent import monkey; monkey.patch_all()
import gevent
import tweetstream
import getpass
from socketio import socketio_manage
from socketio.server import SocketIOServer
from socketio.namespace import BaseNamespace
def broadcast_msg(server, ns_name, event, *args):
pkt = dict(type="event",
name... |
from django.conf import settings
from django.contrib.flatpages.admin import FlatpageForm
from django.test import TestCase
class FlatpageAdminFormTests(TestCase):
def setUp(self):
self.form_data = {
'title': "A test page",
'content': "This is a test",
'sites': [settings.S... |
import sale_stock
import stock
import report
import company
import res_config
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
from client import exceptions as ex
from client.sources import ok_test
from client.sources.ok_test import models
import mock
import unittest
class LoadTest(unittest.TestCase):
NAME = 'valid'
VALID_FILE = 'test/' + NAME + '.py'
INVALID_FILE = 'invalid.ext'
def setUp(self):
self.patcherIsFile = ... |
'''
Created on Sep 29, 2010
@author: ivan
'''
import logging
from gi.repository import Gtk
from foobnix.gui.state import LoadSave
from foobnix.util.mouse_utils import is_double_left_click, is_rigth_click,\
right_click_optimization_for_trees, is_empty_click
from foobnix.helpers.menu import Popup
from foobnix.help... |
from crits.core.crits_mongoengine import EmbeddedCampaign
def migrate_indicator(self):
"""
Migrate to the latest schema version.
"""
migrate_2_to_3(self)
def migrate_2_to_3(self):
"""
Migrate from schema 2 to 3.
"""
if self.schema_version < 2:
migrate_1_to_2(self)
if sel... |
from django.shortcuts import get_object_or_404
from django_rest_logger import log
from knox.auth import TokenAuthentication
from knox.models import AuthToken
from rest_framework import status
from rest_framework.authentication import BasicAuthentication
from rest_framework.decorators import api_view
from rest_framework... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 31 20:05:23 2017
@author: DIP
@Copyright: Dipanjan Sarkar
"""
from sklearn import metrics
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder
from sklearn.base import clone
from sklearn.preprocessing impor... |
#mainscript
from __future__ import print_function
from collections import Counter
import csv,ast,re, itertools, glob,sys,os,datetime
import dresher_LSA as d
import main_1inventoryMover as m
import main_2inventoryParser2 as k
import main_3min_analysis as a1
import main_4efficiency_analysis as a2
"""
2017.0... |
# Create the quick lookup organism table
import Config
import sys, string
import MySQLdb
import Database
with Database.db as cursor :
# EMPTY EXISTING DATA
cursor.execute( "TRUNCATE TABLE " + Config.DB_QUICK + ".quick_organisms" )
cursor.execute( "TRUNCATE TABLE " + Config.DB_QUICK + ".quick_refseq_org... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.