content
stringlengths
4
20k
#!/usr/bin/env python # # tournament.py -- implementation of a Swiss-system tournament # import bleach import datetime import psycopg2 def connect(): """Connect to the PostgreSQL database. Returns a database connection.""" return psycopg2.connect("dbname=tournament") def createTournament(name="Tournament On...
"""Plot loss curves from saved CSV files for the toy regression experiment. Example: -------- python plot_toy_regression.py """ import os import csv import ipdb import pickle as pkl from collections import defaultdict import numpy as np import scipy.ndimage import matplotlib.pyplot as plt import matplotlib.colors as...
ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} import traceback try: import ovirtsdk4.types as otypes except ImportError: pass from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ovirt impo...
"""Provides utilities to preprocess images. The preprocessing steps for VGG were introduced in the following technical report: Very Deep Convolutional Networks For Large-Scale Image Recognition Karen Simonyan and Andrew Zisserman arXiv technical report, 2015 PDF: http://arxiv.org/pdf/1409.1556.pdf ILSVRC 20...
from __future__ import absolute_import, division, print_function, unicode_literals from unittest import TestCase from datetime import datetime from hdgfrom.flow import Flow, Rate, Observation, Unit class EmptyFlowTests(TestCase): def setUp(self): self._flow = Flow() def test_has_water_body(self): ...
"""Support for Tasmota binary sensors.""" from homeassistant.components import binary_sensor from homeassistant.components.binary_sensor import BinarySensorEntity from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect import homeassistant.helpers.event as evt fro...
from django.core.urlresolvers import reverse from django.core import mail from oscar.apps.customer.models import CommunicationEventType from oscar.test.factories import UserFactory from oscar.test.testcases import WebTestCase class TestAnAdmin(WebTestCase): def setUp(self): self.staff = UserFactory(is_s...
from sqlalchemy import create_engine from sqlalchemy.dialects import sqlite class DBSqlite: def __init__(self, db): self.db = db def get_string_connection(self): url = "sqlite:///%s" % self.db['PATH_FILE'] return url def get_engine(self): return create_engine( ...
from oslo_config import cfg from oslo_log import log as logging from nova.scheduler import filters from nova.scheduler import utils LOG = logging.getLogger(__name__) CONF = cfg.CONF CONF.import_opt('weight_setting', 'nova.scheduler.weights.metrics', group='metrics') class MetricsFil...
import os import numpy as np import re import fnmatch import itertools from neighbors import neighbor_edges, neighbor_vertices from nodes import __node_properties from transformations import superimposition_matrix from placing_bb_func import __place_bb from operator import itemgetter #Connect two nodes to each ot...
from PyQt4 import QtGui, QtCore from datetime import datetime class NetworkLobbyWidget(QtGui.QWidget): #Provides a list of availabe network games and peers #User can click a game to join #Callbacks can be used to add or remove games and peers def __init__(self, win_parent = None): QtGui.QWidget.__i...
import unittest from webkitpy.common.host_mock import MockHost from webkitpy.common.system.systemhost_mock import MockSystemHost from webkitpy.layout_tests import run_webkit_tests from webkitpy.layout_tests.controllers.layout_test_runner import LayoutTestRunner, Sharder, TestRunInterruptedException from webkitpy.layou...
from __future__ import absolute_import from django.conf.urls import patterns from . import feeds urlpatterns = patterns('django.contrib.syndication.views', (r'^syndication/complex/(?P<foo>.*)/$', feeds.ComplexFeed()), (r'^syndication/rss2/$', feeds.TestRss2Feed()), (r'^syndication/rss2/guid_ispermalink_...
from __future__ import division, absolute_import, print_function from numpy.distutils.cpuinfo import cpu from numpy.distutils.fcompiler import FCompiler compilers = ['MIPSFCompiler'] class MIPSFCompiler(FCompiler): compiler_type = 'mips' description = 'MIPSpro Fortran Compiler' version_pattern = r'MIPS...
# -*- coding: utf-8 -*- """ flask.testsuite.ext ~~~~~~~~~~~~~~~~~~~ Tests the extension import thing. :copyright: (c) 2011 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import sys import unittest try: from imp import reload as reload_module except ImportError: reload...
import clr import re regexstring = IN[0] flags = IN[1] # process flags if flags == "1111": thisexp = re.compile(regexstring, re.IGNORECASE|re.LOCALE|re.DOTALL|re.MULTILINE) elif flags == "1110": thisexp = re.compile(regexstring, re.IGNORECASE|re.LOCALE|re.DOTALL) elif flags == "1101": thisexp = re.compile(regexstri...
#!/usr/bin/env python # http://trac.secdev.org/scapy/ticket/301 # scapy.contrib.description = RIPng # scapy.contrib.status = loads from scapy.packet import * from scapy.fields import * from scapy.layers.inet import UDP from scapy.layers.inet6 import * class RIPng(Packet): name = "RIPng header" fields_desc =...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import jsonfield.fields from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('monitoring', '000...
from __future__ import unicode_literals import os from ..utils import ( PostProcessingError, cli_configuration_args, encodeFilename, ) class PostProcessor(object): """Post Processor class. PostProcessor objects can be added to downloaders with their add_post_processor() method. When the dow...
data = ( 'cwik', # 0x00 'cwit', # 0x01 'cwip', # 0x02 'cwih', # 0x03 'cyu', # 0x04 'cyug', # 0x05 'cyugg', # 0x06 'cyugs', # 0x07 'cyun', # 0x08 'cyunj', # 0x09 'cyunh', # 0x0a 'cyud', # 0x0b 'cyul', # 0x0c 'cyulg', # 0x0d 'cyulm', # 0x0e 'cyulb', # 0x0f 'cyuls', # 0x1...
import argparse import os import libcst as cst import pathlib import sys from typing import (Any, Callable, Dict, List, Sequence, Tuple) def partition( predicate: Callable[[Any], bool], iterator: Sequence[Any] ) -> Tuple[List[Any], List[Any]]: """A stable, out-of-place partition.""" results = ([], [])...
"""DenseNet models for Keras. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from keras_applications import densenet from tensorflow.python.util.tf_export import tf_export DenseNet121 = densenet.DenseNet121 DenseNet169 = densenet.DenseNet169 DenseNet20...
import logging from conduct.util import systemCall from conduct.buildsteps import * app = None
from autothreadharness.harness_case import HarnessCase import unittest class Router_5_5_7(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 5 7' golden_devices_required = 3 def on_dialog(self, dialog, title): pass if __name__ == '__main__': unittest.main()
from __future__ import unicode_literals import re import json from .common import InfoExtractor from ..compat import ( compat_urlparse, ) from ..utils import ( ExtractorError, ) class SlideshareIE(InfoExtractor): _VALID_URL = r'https?://www\.slideshare\.net/[^/]+?/(?P<title>.+?)($|\?)' _TEST = { ...
#!/usr/bin/env python3 # -*- coding: utf8 -*- """ This script generates twolc files from database data. """ # 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 Licen...
""" Generate ``gitweb`` project list based on ``gitosis.conf``. To plug this into ``gitweb``, you have two choices. - The global way, edit ``/etc/gitweb.conf`` to say:: $projects_list = "/path/to/your/projects.list"; Note that there can be only one such use of gitweb. - The local way, create a new config file::...
# -*- coding: utf-8 -*- """ Tests for the configuration file/command-line arguments. """ # This test should be run from its directory. # TODO A configmanager object cannot parse multiple times a config file # and/or the command line, preventing to 'reload' a configuration. import os import config config_file_00 =...
""" Replaces someone saying a name with a tone over the name to 'hide' the name. The times that the names are spoken are taken from a transcript of the recording. """ import os from os.path import join from praatio import tgio from praatio import audioio path = join(".", "files") outputPath = join(path, "anonymized...
""" PNG picture file parser. Documents: - RFC 2083 http://www.faqs.org/rfcs/rfc2083.html Author: Victor Stinner """ from lib.hachoir_parser import Parser from lib.hachoir_core.field import (FieldSet, Fragment, ParserError, MissingField, UInt8, UInt16, UInt32, String, CString, Bytes, RawBytes, B...
from django.db.models.query import QuerySet, EmptyQuerySet from django.dispatch import dispatcher from django.db.models import signals from django.db.models.fields import FieldDoesNotExist # Size of each "chunk" for get_iterator calls. # Larger values are slightly faster at the expense of more storage space. GET_ITERA...
from __future__ import absolute_import from google.cloud.gapic.vision.v1 import image_annotator_client as iac from google.cloud.gapic.vision.v1 import enums from google.cloud.vision.decorators import add_single_feature_methods from google.cloud.vision.helpers import VisionHelpers from google.cloud.vision_v1 import ty...
import pytest # noqa from .common import SQLiteTests from ibis.compat import unittest from ibis import literal as L import ibis.expr.types as ir import ibis import sqlalchemy as sa class TestSQLiteFunctions(SQLiteTests, unittest.TestCase): def test_cast(self): at = self._to_sqla(self.alltypes) ...
"""Provide :class:`frozenbidict`, an immutable, hashable bidirectional mapping type.""" import typing as _t from ._delegating import _DelegatingBidict from ._typing import KT, VT class frozenbidict(_DelegatingBidict[KT, VT]): """Immutable, hashable bidict type.""" __slots__ = ('_hash',) # Work around ...
import ansible.utils as utils from ansible.utils import safe_eval import ansible.errors as errors def flatten(terms): ret = [] for term in terms: if isinstance(term, list): ret.extend(term) elif isinstance(term, tuple): ret.extend(term) else: ret.appe...
from __future__ import unicode_literals import frappe, os from frappe.modules import get_doc_path from jinja2 import Environment, Template, FileSystemLoader no_cache = 1 no_sitemap = 1 def get_context(context): context.type = frappe.local.form_dict.type context.txt = frappe.local.form_dict.txt context.update(get_i...
#! /usr/bin/python """ dispatch_async.py By Paul Malmsten, 2010 <EMAIL> This example continuously reads the serial port and dispatches packets which arrive to appropriate methods for processing in a separate thread. """ from xbee import XBee from xbee.helpers.dispatch import Dispatch import time import serial PORT...
ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} class CloudWatchEventRule(object): def __init__(self, module, name, client, schedule_expression=None, event_pattern=None, description=None, role_arn=None): self...
""" ISO 9660 (cdrom) file system parser. Documents: - Standard ECMA-119 (december 1987) http://www.nondot.org/sabre/os/files/FileSystems/iso9660.pdf Author: Victor Stinner Creation: 11 july 2006 """ from lib.hachoir_parser import Parser from lib.hachoir_core.field import (FieldSet, ParserError, UInt8, UInt32, ...
from functools import reduce from gi.repository import GdkX11 import pytest is_display_enabled = bool(GdkX11.X11Display.get_default()) def pytest_runtest_setup(item): if isinstance(item, pytest.Function): if item.iter_markers('with_display') and not is_display_enabled: pytest.skip("Cannot ru...
from django.test import TestCase from django.contrib.auth.models import User, Group, Permission from views import * def add_permissions(group, codenames): """ Add a permission to the group """ if isinstance(codenames, basestring): codenames = [codenames] for codename in codenames: perm = ge...
import json import logging import socket import requests from fuel_upgrade import errors from fuel_upgrade import utils logger = logging.getLogger(__name__) class KeystoneClient(object): """Simple keystone authentification client :param str username: is user name :param str password: is user password...
""" Django settings for shoppinglist project. Generated by 'django-admin startproject' using Django 1.8.5. 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/ """ # Build...
class ModuleDocFragment(object): # Standard files documentation fragment # Note: mode is overridden by the copy and template modules so if you change the description # here, you should also change it there. DOCUMENTATION = r''' options: mode: description: - The permissions the resulting file...
from __future__ import unicode_literals from django.conf import settings from django.utils.unittest import skipUnless from .base import SitemapTestsBase class FlatpagesSitemapTests(SitemapTestsBase): @skipUnless("django.contrib.flatpages" in settings.INSTALLED_APPS, "django.contrib.flatpages app...
import os def main(request, response): try: get_type = request.GET.first("types") status = 200 body = "" content_type = "text/plain" def file_get_contents(path): file_object = open( os.path.split( os.path.realpath(__file__))...
import webapp2 from google.appengine.ext import db import logging import sys import json from appconfig import Application, Experiment, Variation class ApplicationsHandler(webapp2.RequestHandler): def get(self): try: self.response.headers['Content-Type'] = 'application/json' q = ...
from __future__ import absolute_import from django.core.management.base import BaseCommand, CommandError from django.core.exceptions import ValidationError from zerver.lib.actions import do_change_is_admin from zerver.models import UserProfile class Command(BaseCommand): help = """Give an existing user administ...
from nova.tests.functional.v3 import test_servers from nova.tests.unit.image import fake class MultipleCreateJsonTest(test_servers.ServersSampleBase): extension_name = "os-multiple-create" def test_multiple_create(self): subs = { 'image_id': fake.get_valid_image_id(), 'host': ...
# Webhooks for external integrations. from typing import Dict from django.http import HttpRequest, HttpResponse from zerver.decorator import api_key_only_webhook_view from zerver.lib.request import REQ, has_request_variables from zerver.lib.response import json_success from zerver.lib.validator import check_bool, che...
from copy import deepcopy # noqa from django.core.urlresolvers import reverse from django import http from mox3.mox import IsA # noqa import six from horizon.workflows import views from openstack_dashboard import api from openstack_dashboard.dashboards.project.access_and_security \ import api_access from openst...
import os import sys path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "../") sys.path.insert(0, path) import unittest import systemml as sml import numpy as np from scipy.stats import kurtosis, skew, moment from pyspark.context import SparkContext sc = SparkContext.getOrCreate() dim = 5 m1 = np.array(...
"""Loader for the Labeled Faces in the Wild (LFW) dataset This dataset is a collection of JPEG pictures of famous people collected over the internet, all details are available on the official website: http://vis-www.cs.umass.edu/lfw/ Each picture is centered on a single face. The typical task is called Face Veri...
"""Forms for generating access tokens and clients.""" from oauthlib.oauth2.rfc6749.errors import InsecureTransportError, \ InvalidRedirectURIError from wtforms_alchemy import model_form_factory from wtforms import fields, validators, widgets from invenio.utils.forms import InvenioBaseForm from .models import Clie...
""" Test that nested persistent types work. """ import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class NestedPersistentTypesTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) def test_persistent_types(self): ""...
import re import keyword import functools __IDENTIFIER_PATTERN = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_]*$') def __isidentifier(s): if s in keyword.kwlist: return False return __IDENTIFIER_PATTERN.match(s) is not None def Enum(*args, **kwargs): """ Utility function for creating enumerations in python Exa...
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'FolderPermission.can_add_children' db.delete_column('filer_folderpermission', 'can_add_chi...
import websocket import requests import json class PokemonShowdownBot: def __init__(self): self.data = json.loads(open('config.json').read()) self.url = self.data['url'] self.rooms = [] self.openConnection() def onMessage(self, ws, message): print(message) if not message: return if '\n' not in messa...
from extensions.interactions import base class MusicNotesInput(base.BaseInteraction): """Interaction for music notes input.""" name = 'Music Notes Input' description = ( 'Allows learners to drag and drop notes onto the lines of a music ' 'staff.') display_mode = base.DISPLAY_MODE_SUPP...
# Auther: Alan """ 实现AlexNet网络结构:但是实际上AlexNet网络结构的餐率领有60M,其实际的参数量比后来的几个网络结构都要多,这里不选择 但是尝试实现更深层的卷积网络来查看性能 这里一共整理了4层 """ # Auther: Alan """ 将LeNet5应用在Cifar数据集上 """ import tensorflow as tf import random import os import scipy.io as sio import matplotlib.pyplot as plt # plt 用于显示图片 import matplotlib.image a...
# -*- coding: utf-8 -*- """ *************************************************************************** DirectorySelectorDialog.py --------------------- Date : May 2016 Copyright : (C) 2016 by Alexander Bruy Email : alexander dot bruy at gmail dot com *****...
import re import datetime def id_number_checksum(gd): """ Calculates a Swedish ID number checksum, using the "Luhn"-algoritm """ n = s = 0 for c in (gd['year'] + gd['month'] + gd['day'] + gd['serial']): tmp = ((n % 2) and 1 or 2) * int(c) if tmp > 9: tmp = sum([int(...
import random import numpy as np class Dataset: """ A mapping from column names to immutable arrays of equal length. """ def __init__(self, **data): self._data = {} self._length = None super().__init__() for column, data in data.items(): self[column] = data...
import csv import time import rospy import mavros from mavros_msgs.msg import Waypoint, WaypointList, CommandCode from mavros_msgs.srv import WaypointPull, WaypointPush, WaypointClear, \ WaypointSetCurrent FRAMES = { Waypoint.FRAME_GLOBAL: 'GAA', Waypoint.FRAME_GLOBAL_REL_ALT: 'GRA', Waypoint.FRAME_...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class Backtrack2: """ Backtrack dynamic algorithm for Shubik's 2-player dollar auction. """ def __init__(self, b1=50, b2=50, s=20): self.b1 = b1 self.b2 = b2 self.s = s self.a = None def backtrack(self): # a - ...
def main(request, response): import simplejson as json f = file('config.json') source = f.read() s = json.JSONDecoder().decode(source) url1 = "http://" + s['host'] + ":" + str(s['ports']['http'][1]) url2 = "http://" + s['host'] + ":" + str(s['ports']['http'][0]) _CSP = "script-src 'unsafe-in...
""" Course Structure api.py tests """ from .api import course_structure from openedx.core.djangoapps.content.course_structures.signals import listen_for_course_publish from xmodule.modulestore.django import SignalHandler from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from xmodule.modulestore.tes...
''' Created on Mar 31, 2015 @author: paepcke ''' import os import shutil import unittest from manageEdxDb import TrackLogPuller class TestManageDb(unittest.TestCase): csvFName1 = 'tracking.app2.tracking.tracking.log-20141008-1412767021.gz.2015-03-07T20_18_53.273290_7501.sql' csvFName2 = 'app1.tracking.tr...
# coding=utf-8 """ InaSAFE Disaster risk assessment tool developed by AusAid and World Bank - **GUI Test Cases.** 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...
import pickle from moviepy.editor import * from moviepy.video.tools.tracking import manual_tracking, to_fxfy # LOAD THE CLIP (subclip 6'51 - 7'01 of a chaplin movie) clip = VideoFileClip("../../videos/chaplin.mp4").subclip((6,51.7),(7,01.3)) # MANUAL TRACKING OF THE HEAD # the three next lines are for the manual t...
# -*- coding: utf-8 -*- """ flask.exthook ~~~~~~~~~~~~~ Redirect imports for extensions. This module basically makes it possible for us to transition from flaskext.foo to flask_foo without having to force all extensions to upgrade at the same time. When a user does ``from flask.ext.foo import...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json import sys from nose.plugins.skip import SkipTest if sys.version_info < (2, 7): raise SkipTest("F5 Ansible modules require Python >= 2.7") from ansible.compat.tests import unittest from ansible.compat.te...
#!/usr/bin/env python ''' Mere a test case than a useful example, showing various ways of setting configuration. ''' CONFIGS = [ { 'StartInfo': True, 'UseGlobalDebugFile': True, 'DebugFile': None, 'SyncTime': True, 'Connection': 'at', 'LockDevice': True, 'Deb...
""" ciphers.py: Ciphers! """ import functools import itertools from string import ascii_lowercase, ascii_uppercase def letter_to_num(letter: str, is_inversed=False) -> int: """ Takes a letter to a number! """ if letter in ascii_uppercase: num = ord(letter) - ord('A') ...
import re import os import collections import logging import enum import pyhit import mooseutils import moosesqa from .Requirement import Requirement from .LogHelper import LogHelper ISSUE_RE = re.compile(r'^([0-9a-f]{6,40})$|^(.*#[0-9]+)$', flags=re.MULTILINE) class RequirementLogHelper(LogHelper): COLOR_TEXT = ...
"""Content-oriented XBlocks.""" from string import Template from lxml import etree from web_fragments.fragment import Fragment from xblock.core import Scope, String, XBlock class HelloWorldBlock(XBlock): """A simple block: just show some fixed content.""" def fallback_view(self, view_name, context=None):...
"""Mapping a polymorphic-valued vertical table as a dictionary. Builds upon the dictlike.py example to also add differently typed columns to the "fact" table, e.g.:: Table('properties', metadata Column('owner_id', Integer, ForeignKey('owner.id'), primary_key=True), Column('key', Unico...
"""Unit tests for reviewboard.admin.validation.""" from __future__ import unicode_literals from django.forms import ValidationError from reviewboard.admin.validation import validate_bug_tracker from reviewboard.testing.testcase import TestCase class ValidationTests(TestCase): """Unit tests for reviewboard.admi...
# -*- coding: utf-8 -*- from openerp.tests import common class TestWebsiteBlogCommon(common.TransactionCase): def setUp(self): super(TestWebsiteBlogCommon, self).setUp() Users = self.env['res.users'] group_blog_manager_id = self.ref('base.group_website_designer') group_employee_i...
import warnings from django.views.generic.dates import ArchiveIndexView, DateDetailView, DayArchiveView, MonthArchiveView, \ YearArchiveView from django.views.generic.detail import DetailView from django.views.generic.list import ListView from django.views.generic.base import RedirectView from django.core.urlresol...
import uuid from time import mktime from sqlalchemy import Column, Integer, String, \ ForeignKey, BLOB, Float, Time, Boolean, DateTime from sqlalchemy.orm import relationship, deferred from sqlalchemy.sql.expression import func from pychron.database.core.base_orm import BaseMixin, NameMixin, UserMixin from pychro...
""" Container for the simple plot with functionality for data legend, saving data and manipulating the plot. For more advanced plotting save the data and use an external application. """ __author__ = 'Bitcraze AB' __all__ = ['PlotWidget'] from PyQt4 import QtCore, QtGui, uic from PyQt4.QtCore import Qt, pyqtSlot, py...
from __future__ import division, absolute_import, print_function import os import math import numpy as np from numpy.testing import run_module_suite, dec, assert_raises, assert_equal import util def _path(*a): return os.path.join(*((os.path.dirname(__file__),) + a)) class TestParameters(util.F2PyTest): #...
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor from ..utils import int_or_none class FranceInterIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?franceinter\.fr/player/reecouter\?play=(?P<id>[0-9]+)' _TEST = { 'url': 'http://www.franceinter.fr/player/ree...
""" The :mod:`sklearn.preprocessing` module includes scaling, centering, normalization, binarization and imputation methods. """ from ._function_transformer import FunctionTransformer from .data import Binarizer from .data import KernelCenterer from .data import MinMaxScaler from .data import MaxAbsScaler from .data ...
import httplib as http from flask import redirect, request import markupsafe from modularodm import Q from framework.auth.decorators import must_be_logged_in from framework.exceptions import HTTPError, PermissionsError from framework import status from website.tokens.exceptions import UnsupportedSanctionHandlerKind,...
''' Checks a policy_templates.json file for conformity to its syntax specification. ''' import json import optparse import os import re import sys LEADING_WHITESPACE = re.compile('^([ \t]*)') TRAILING_WHITESPACE = re.compile('.*?([ \t]+)$') # Matches all non-empty strings that contain no whitespaces. NO_WHITESPACE =...
from openerp import models, fields, api class QcInspection(models.Model): _inherit = 'qc.inspection' @api.multi def _prepare_inspection_lines(self, test, force_fill=False): data = super(QcInspection, self)._prepare_inspection_lines( test, force_fill=force_fill) new_data = [] ...
""" Test for LMS courseware app. """ import mock from mock import Mock from unittest import TestCase from django.core.urlresolvers import reverse from django.test.utils import override_settings from textwrap import dedent from xmodule.error_module import ErrorDescriptor from xmodule.modulestore.django import modulest...
DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3'}} INSTALLED_APPS = [ 'django', 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'nikola_auth', 'nikola_auth.tests' ] MIDDLEWARE_CLASSES = [ 'django.middleware.common.CommonMiddleware', 'djan...
r''' This tests the '_objects' attribute of ctypes instances. '_objects' holds references to objects that must be kept alive as long as the ctypes instance, to make sure that the memory buffer is valid. WARNING: The '_objects' attribute is exposed ONLY for debugging ctypes itself, it MUST NEVER BE MODIFIED! '_object...
#!/home/syberic/AOSServer/PySnip/venv/bin/python2 # # The Python Imaging Library # $Id$ # # this demo script illustrates pasting into an already displayed # photoimage. note that the current version of Tk updates the whole # image every time we paste, so to get decent performance, we split # the image into a set of ti...
from kivy.tests import async_run, UnitKivyApp def dropdown_app(): from kivy.app import App from kivy.uix.button import Button from kivy.uix.dropdown import DropDown from kivy.uix.label import Label class RootButton(Button): dropdown = None def on_touch_down(self, touch): ...
__all__ = ['less', 'cosh', 'arcsinh', 'add', 'ceil', 'arctan2', 'floor_divide', 'fmod', 'hypot', 'logical_and', 'power', 'sinh', 'remainder', 'cos', 'equal', 'arccos', 'less_equal', 'divide', 'bitwise_or', 'bitwise_and', 'logical_xor', 'log', 'subtract', 'invert', 'negative',...
#!/usr/bin/python import unittest import sys import os import copy srcdir = os.getenv('builddir') if not srcdir: srcdir = "." MODPATH = srcdir + "/.libs" #FIXME - is there a way to get this from libtool? def compat_assertItemsEqual(this, expected_seq, actual_seq, msg=None): return this.assertEqual(sorted(exp...
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor from ..utils import ( ExtractorError, int_or_none, update_url_query, ) class NaverIE(InfoExtractor): _VALID_URL = r'https?://(?:m\.)?tv(?:cast)?\.naver\.com/v/(?P<id>\d+)' _TESTS = [{ 'url': 'http://tv.naver.com/v/81652...
"""Ciphers module. Provide Asymmetric and Symmetric cipher functions.\ """ from enum import IntEnum from Crypto import Random from Crypto.Cipher import PKCS1_v1_5, AES from Crypto.PublicKey import RSA from Crypto.Random import random as rand from Crypto.Util import Counter class AESBlockCipher: class Size(IntEn...
import grpc # This code doesn't do much but makes sure the native extension is loaded # which is what we are testing here. channel = grpc.insecure_channel('localhost:1000') del channel print 'Success!'
"""File wrangling.""" from coverage.backward import to_string from coverage.misc import CoverageException import fnmatch, os, re, sys class FileLocator(object): """Understand how filenames work.""" def __init__(self): # The absolute path to our current directory. self.relative_dir = self.abs_...
import shutil import pytest from diffoscope.config import Config from diffoscope.presenters.text import output_text from diffoscope.comparators.binary import FilesystemFile from diffoscope.comparators.missing_file import MissingFile from diffoscope.comparators.utils.specialize import specialize from utils.data import...