content
stringlengths
4
20k
# -*- 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 'Household.name' db.delete_column(u'survey_household', 'name') # Adding field 'Hou...
#!/usr/bin/env python3 from node import Node import datetime as d class Task: # todo class Task(Node): def __init__(self, description="", duration=d.timedelta(), start=d.datetime.now(), subtasks=[]): self.description = description self.duration = duration self.start = start self.su...
from sos.plugins import Plugin, UbuntuPlugin class Apparmor(Plugin, UbuntuPlugin): """Apparmor mandatory access control """ plugin_name = 'apparmor' profiles = ('security',) def setup(self): self.add_copy_spec([ "/etc/apparmor*" ]) self.add_forbidden_path("/et...
import logging l = logging.getLogger("abg") l.error("Before imports in app.py") # -*- coding: utf-8 -*- """The app module, containing the app factory function.""" from flask import Flask, render_template l.error("After Flask import") from abg_stats import commands, public, user l.error("blueprints") from abg_stats imp...
import json try: from docker.errors import APIError except ImportError: # missing docker-py handled in ansible.module_utils.docker.common pass from ansible.module_utils._text import to_native from ansible.module_utils.docker.common import AnsibleDockerClient class AnsibleDockerSwarmClient(AnsibleDockerC...
'''Utility functions.''' from __future__ import with_statement, print_function import sys from optparse import OptionParser import rsa.key def private_to_public(): '''Reads a private key and outputs the corresponding public key.''' # Parse the CLI options parser = OptionParser(usage='usage: %prog [opti...
from django.conf import settings from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse from django.db import models from stream_django.activity import Activity class ReviewWithActivity(Activity): """...
from six import text_type as unicode from robot.utils import (format_assign_message, get_elapsed_time, get_error_message, get_timestamp, plural_or_not) from robot.errors import (ContinueForLoop, DataError, ExecutionFailed, ExecutionFailures, ExecutionPassed, ExitForLo...
"""Model script to test TF-TensorRT integration.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.compiler.tensorrt.test import tf_trt_integration_test_base as trt_test from tensorflow.python.framework import constant_op from tensor...
#!/usr/bin/env python import os, sys, glob, subprocess, textwrap try: import setuptools assert int(setuptools.__version__.split(".", 1)[0]) >= 19 except (ImportError, AssertionError): msg = 'Error: Aegea failed to install because your version of setuptools is too old ({}; 19 is required). Run "make instal...
from test_plus.test import TestCase import instanotifier.parser.rss.test_utils as parser_utils from instanotifier.notification.serializers import RssNotificationSerializer, _compute_entry_id_hash class TestRssNotificationSerializer(TestCase): def setUp(self): self.feed_items = parser_utils.get_test_rss_f...
microcode = ''' def macroop PMADDWD_MMX_MMX { mmuli ufp3, mmx, mmxm, srcSize=2, destSize=4, ext = Signed + "| 0x10 | 0x20" mmuli ufp4, mmx, mmxm, srcSize=2, destSize=4, ext = Signed + "| 0x10" maddi mmx, ufp3, ufp4, size=4, ext=0 }; def macroop PMADDWD_MMX_M { ldfp ufp1, seg, sib, "DISPLACEMENT", dataS...
"""Frame objects that do the frame demarshaling and marshaling.""" import logging import struct from servicebus.pika import amqp_object from servicebus.pika import exceptions from servicebus.pika import spec from servicebus.pika.compat import byte LOGGER = logging.getLogger(__name__) class Frame(amqp_object.AMQPOb...
import re SHA1_RE = re.compile('^[a-fA-F0-9]{40}$') ROLL_DEPS_GIT_SVN_ID_RE = re.compile('^git-svn-id: .*@([0-9]+) .*$') # Regular expression that matches a single commit footer line. COMMIT_FOOTER_ENTRY_RE = re.compile(r'([^:]+):\s+(.+)') # Footer metadata key for commit position. COMMIT_POSITION_FOOTER_KEY = 'Cr-C...
#!/usr/bin/env python ''' Model code for managing sprites =============================== ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' from pyglet.gl import * from scene2d.drawable import * class SpriteLayer(object): '''Represents a group of sprites at the same z depth. ''' def __init__...
# Wrapper module for _socket, providing some additional facilities # implemented in Python. """\ This module provides socket operations and some related functions. On Unix, it supports IP (Internet Protocol) and Unix domain sockets. On other systems, it only supports IP. Functions specific for a socket are available a...
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os import glob import numpy as np import nibabel as nib import matplotlib.pylab as plt import matplotlib.image as mpimg from braincode.math import corr2_coef, make_2d_gaussian, make_2d_dog, make_2d...
from msrest.serialization import Model class ApplicationGatewayFirewallRule(Model): """A web application firewall rule. All required parameters must be populated in order to send to Azure. :param rule_id: Required. The identifier of the web application firewall rule. :type rule_id: int :par...
import sys from services.spawn import MobileTemplate from services.spawn import WeaponTemplate from resources.datatables import WeaponType from resources.datatables import Difficulty from resources.datatables import Options from java.util import Vector def addTemplate(core): mobileTemplate = MobileTemplate() mobi...
"""Command for removing a user from a group.""" from googlecloudsdk.calliope import arg_parsers from googlecloudsdk.compute.lib import base_classes from googlecloudsdk.compute.lib import user_utils class RemoveMembers(base_classes.NoOutputAsyncMutator, user_utils.UserResourceFetcher): """Remove ...
""" The core's core. """ from __future__ import print_function, division # used for canonical ordering of symbolic sequences # via __cmp__ method: # FIXME this is *so* irrelevant and outdated! ordering_of_classes = [ # singleton numbers 'Zero', 'One', 'Half', 'Infinity', 'NaN', 'NegativeOne', 'NegativeInfinity...
from openerp.osv import osv, fields from openerp.addons.edi import EDIMixin from openerp.tools.translate import _ from werkzeug import url_encode SALE_ORDER_LINE_EDI_STRUCT = { 'sequence': True, 'name': True, #custom: 'date_planned' 'product_id': True, 'product_uom': True, 'price_unit': True, ...
"""View for block details specialized for a GAS""" from django.http import HttpResponseRedirect from django.utils.translation import ugettext as _, ugettext_lazy as _lazy from django.core.urlresolvers import reverse from django.conf import settings from flexi_auth.models import ObjectWithContext from ajax_select.fiel...
""" Django settings for MythicApps project. Generated by 'django-admin startproject' using Django 1.8. 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 pat...
from gnuradio import gr, gr_unittest, digital, blocks from math import sqrt from numpy import random, vectorize class test_constellation_soft_decoder(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def helper_with_lut(self, prec, src_da...
# -*- coding: utf-8 -*- """ koala.api ~~~~~~~~~~~~~~~~~~ Contains base implementations for building an internal project API :copyright: (c) 2015 Lighthouse :license: LGPL """ from blinker import signal from google.appengine.ext import deferred __author__ = 'Matt Badger' # TODO: remove the defe...
from __future__ import unicode_literals import logging import notify2 logger = logging.getLogger('pulseaudio_dlna.notification') def show(title, message, icon=''): try: notice = notify2.Notification(title, message, icon) notice.set_timeout(notify2.EXPIRES_DEFAULT) notice.show() exce...
from __future__ import absolute_import from datetime import timedelta from django.utils import timezone from rest_framework import status from rest_framework.response import Response from sentry.api.base import DocSection from sentry.api.bases.group import GroupEndpoint from sentry.api.serializers import serialize fr...
ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'community'} from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.cloudstack import ( AnsibleCloudStack, cs_argument_spec, cs_required_together, )...
from __future__ import unicode_literals import webnotes from webnotes import _ from webnotes.utils import cint, cstr, date_diff, flt, formatdate, getdate, get_url_to_form, \ comma_or, get_fullname from webnotes import msgprint class LeaveDayBlockedError(webnotes.ValidationError): pass class OverlapError(webnotes.Val...
from openerp import api, models, fields class StockPicking(models.Model): _inherit = 'stock.picking' sale_comment = fields.Text(string='Internal comments') sale_propagated_comment = fields.Text( string='Propagated internal comments') @api.one @api.onchange('partner_id') def onchange_...
# -*- coding: utf-8 -*- """ Copyright (C) 2010 Dariusz Suchojad <dsuch at zato.io> Licensed under LGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib import logging from base64 import b64decode, b64encode # PyCrypto from ...
"""Message Resource, Action, Detail and user visible message. Use Resource, Action and Detail's combination to indicate the Event in the format of: EVENT: VOLUME_RESOURCE_ACTION_DETAIL Also, use exception-to-detail mapping to decrease the workload of classifying event in cinder's task code. """ from cinder.i18n imp...
from openerp.osv import fields,osv from openerp import tools class report_document_user(osv.osv): _name = "report.document.user" _description = "Files details by Users" _auto = False _columns = { 'name': fields.char('Year', size=64,readonly=True), 'month':fields.selection([('01','Januar...
from bs4 import BeautifulSoup from collections import Counter import urllib import urllib2 import sys import re import subprocess from subprocess import check_output import difflib import requests def contestarVeu(missatge): subprocess.Popen(["python","/home/pi/AleixDomo/Musica/pyvonabackground.py",missatge]) missat...
from allauth.socialaccount import app_settings from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class VKAccount(ProviderAccount): def get_profile_url(self): return 'https://vk.com/id%s' % self.account.extra_data.get...
import sys from django.template import TemplateSyntaxError from django.template.loader import render_to_string from django.utils.datastructures import SortedDict from horizon import exceptions from horizon.utils import html SEPARATOR = "__" CSS_TAB_GROUP_CLASSES = ["nav", "nav-tabs", "ajax-tabs"] CSS_ACTIVE_TAB_CLAS...
#!/usr/bin/env python """Patch IMP and RMF SWIG wrappers to search for Python extensions and DLLs in Python version-specific directories. These directories are created by the .exe Windows installers, and are not in the standard Python search path, so need to be added. We need to patch IMP/__init__.py so we ad...
#! python # -*- coding: utf-8 -*- # (c) 2010 Werner Mayer LGPL __author__ = "Werner Mayer <wmayer[at]users.sourceforge.net>" # Formulas: # M2 = P + b*r2 + t*u # S1 = (r2*M1 + r1*M2)/(r1+r2) # S2 = M2-b*r2 import math # 3d vector class class Vector: def __init__(self,x,y,z): self.x=x self.y=y ...
import pychart_util import color import line_style import chart_object import object_set import types import theme import fill_style_doc from pychart_types import * from scaling import * _keys = { "bgcolor" : (color.T, color.white, "The background color."), "line_style": (line_style.T, line_style.default, ...
from django.conf import settings from django.views.generic import TemplateView from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required from registration.views import register as registration_register from registration.forms imp...
from __future__ import absolute_import, division, print_function from cryptography.exceptions import ( UnsupportedAlgorithm, _Reasons ) from cryptography.hazmat.backends.interfaces import HMACBackend from cryptography.hazmat.primitives import constant_time from cryptography.hazmat.primitives.twofactor import Inval...
from __future__ import unicode_literals import boto3 import json import sure # noqa from botocore.exceptions import ClientError from nose.tools import assert_raises from moto import mock_sns from moto.sns.models import DEFAULT_PAGE_SIZE @mock_sns def test_subscribe_sms(): client = boto3.client('sns', region_n...
"""Tests for state updating ops that may have benign race conditions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.python.platform import numpy as np import tensorflow as tf class AssignOpTest(tf.test.TestCase): # NOTE(mrry): We...
from msrest.serialization import Model class Screen(Model): """The response for a Screen text request. :param original_text: The original text. :type original_text: str :param normalized_text: The normalized text. :type normalized_text: str :param auto_corrected_text: The autocorrected text ...
from openerp.osv import osv class cancel_statement_line(osv.osv_memory): _name = 'cancel.statement.line' _description = 'Cancel selected statement lines' def cancel_lines(self, cr, uid, ids, context): line_ids = context['active_ids'] line_obj = self.pool.get('account.bank.statement.line') ...
from __future__ import absolute_import, division, print_function __metaclass__ = type import pytest from units.modules.utils import set_module_args, exit_json, fail_json, AnsibleExitJson from ansible.module_utils import basic from ansible.modules.network.check_point import cp_mgmt_dns_domain OBJECT = { "name": "...
import Util import hashlib import gzip import bz2 from Exceptions import ExecutionException class Compressor(object): compressionFormats = ('gz', 'bz2') @staticmethod def compress(filename): pass @staticmethod def inflate(filename): cmd = Compressor._getInflateCom...
"""Tests for tensorflow.ops.stack_ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.compiler.tests.xla_test import XLATestCase from tensorflow.python.framework import dtypes from tensorflow.python.framework import o...
import time import unittest import grpc import grpc_testing from tests.testing import _application_common from tests.testing import _application_testing_common from tests.testing import _server_application from tests.testing.proto import services_pb2 class FirstServiceServicerTest(unittest.TestCase): def setUp...
"""Loading unittests.""" import os import re import sys import traceback import types import unittest from fnmatch import fnmatch from django.utils.unittest import case, suite try: from os.path import relpath except ImportError: from django.utils.unittest.compatibility import relpath __unittest = True de...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ :copyright: 2011, 2012 by OpenSlides team, see AUTHORS. :license: GNU GPL, see LICENSE for more details. """ VERSION = (2, 0, 0, 'alpha', 2) RELEASE = False def get_version(version=None, release=None): """Derives a PEP386-compliant version number from VER...
from pytest import raises from py2neo import Node, Relationship from py2neo.data import UniquenessError def test_can_merge_node_that_does_not_exist(graph, make_unique_id): label = make_unique_id() alice = Node(label, name="Alice") old_order = len(graph.nodes) graph.merge(alice, label, "name") ass...
from django.core.management import call_command from django.core.management.base import BaseCommand from django.db import connection class Command(BaseCommand): help = 'Runs a development server with data from the given fixture(s).' requires_system_checks = False def add_arguments(self, parser): ...
import logging from .arrange_maximize import ArrangeMaximize from .arrange_move_monitor import ArrangeMoveMonitor from .arrange_move_window import ArrangeMoveWindow from .arrange_multiple_windows import ArrangeMultipleWindows from .arrange_rotate import ArrangeRotate from .arrange_single_window import ArrangeSingleWin...
import os import unittest import lazylibrarian from lazylibrarian import versioncheck, version # # These tests MUST be executed in the root PROG_DIR directory. Otherwise # test for GIT install doesn't work correctly # execution is via python -m unittest discover -s lazylibrarian/unittests/ -v class VersionCheckTe...
import tempfile import os.path def _is_package_installed(module, name, easy_install, executable_arguments): executable_arguments = executable_arguments + ['--dry-run'] cmd = '%s %s %s' % (easy_install, ' '.join(executable_arguments), name) rc, status_stdout, status_stderr = module.run_command(cmd) retu...
""" Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this ...
"""This module is deprecated. Please use `airflow.providers.jenkins.hooks.jenkins`.""" import warnings # pylint: disable=unused-import from airflow.providers.jenkins.hooks.jenkins import JenkinsHook # noqa warnings.warn( "This module is deprecated. Please use `airflow.providers.jenkins.hooks.jenkins`.", Dep...
"""Scrapes Idaho committees for the latest term.""" from openstates.scrape import Scraper, Organization import lxml.html _COMMITTEE_URL = ( "https://legislature.idaho.gov/committees/%scommittees/" # house/senate ) _JOINT_URL = "https://legislature.idaho.gov/sessioninfo/2017/joint/" _CHAMBERS = {"upper": "senate...
from oslo_utils import uuidutils import webob from nova.api.openstack.compute import admin_actions \ as admin_actions_v21 from nova.api.openstack.compute.legacy_v2.contrib import admin_actions \ as admin_actions_v2 from nova.compute import vm_states from nova import exception from nova import objects f...
from textwrap import dedent import _pytest._code import py import pytest from _pytest.config import PytestPluginManager from _pytest.main import EXIT_NOTESTSCOLLECTED, EXIT_USAGEERROR @pytest.fixture(scope="module", params=["global", "inpackage"]) def basedir(request, tmpdir_factory): from _pytest.tmpdir import ...
from org.sikuli.basics import Debug from org.sikuli.script import Region as JRegion from org.sikuli.script import ObserverCallBack from org.sikuli.script.Constants import * import sys import inspect DEBUG=False class Region(JRegion): # support for with: # override all global sikuli functions by this region's...
"""Tests `FeedingQueueRunner` using arrays and `DataFrames`.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.client import session from tensorflow.python.estimator.inputs.queues.feeding_functions import _enqueue...
from msrest.serialization import Model class KeyOperationResult(Model): """The key operation result. Variables are only populated by the server, and will be ignored when sending a request. :ivar kid: Key identifier :vartype kid: str :ivar result: :vartype result: bytes """ _vali...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Bootstrap setuptools installation If you want to use setuptools in your package's setup.py, just include this file in the same directory with it, and add this to the top of your setup.py:: from ez_setup import use_setuptools use_setuptools() If you want to req...
DATE_FORMAT = 'j F Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j F Y H:i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'Y-m-d' SHORT_DATETIME_FORMAT = 'Y-m-d H:i' FIRST_DAY_OF_WEEK = 1 DATE_INPUT_FORMATS = ( '%Y-%m-%d', # '2006-10-25' '%m/%d/%Y', # '10/25/2006' ...
"""Simple API for simple things like sendig messages. The simplest way to send a message: >>> from pyxmpp2.simple import send_message >>> send_message("<EMAIL>", "bob's password", "<EMAIL>", ... "Hello Alice") Please note, though: - this is ine...
from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) from pants.base.payload import Payload from pants.base.target import Target class Resources(Target): """A set of files accessible as resources from the JVM classpa...
# -*- coding: utf-8 -*- #------------------------------------------------------------ # pelisalacarta - XBMC Plugin # Canal para peliculasonlineflv # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ #------------------------------------------------------------ import urlparse,urllib2,urllib,re import os, sys fro...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'community'} # This is a modification of @bcoca's `svc` module import os import re import traceba...
import mock from neutron.agent.l3 import ha_router from neutron.openstack.common import uuidutils from neutron.tests import base _uuid = uuidutils.generate_uuid class TestBasicRouterOperations(base.BaseTestCase): def setUp(self): super(TestBasicRouterOperations, self).setUp() def _create_router(sel...
class RequestError(Exception): def __init__(self, response, content=None, message=None): self.response = response self.content = content self.message = message def __str__(self): message = "ERROR!" if hasattr(self.response, 'status_code'): message += " HTTP S...
""" This is the test module to test query function of blade. """ import blade_test class TestQuery(blade_test.TargetTest): """Test cc_library """ def setUp(self): """setup method. """ self.doSetUp('test_query', full_targets=['...'], command='query') self.query_targets = ['test_quer...
from __future__ import print_function """ Miscellaneous utlity functions that have the potential for re-use. """ __revision__ = "$Id$" import tempfile import os import random import stat import textwrap import re def concat(list_of_lists): return [item for list in list_of_lists for item in list] def cleave_pa...
"""event participants Revision ID: 1322d3787305 Revises: 4e3e8abea884 Create Date: 2014-08-15 20:53:36.656057 """ # revision identifiers, used by Alembic. revision = '1322d3787305' down_revision = '1bc2536b8bc6' from alembic import op import sqlalchemy as sa def upgrade(): op.create_table( 'eventparti...
from __future__ import print_function import sys import numpy as np import cPickle as pkl import pprint RAND_NUMS = 100000000 def getEstimatedF2(counts, n): # Mean of all values. return np.mean(n*(2*np.asarray(counts) - 1)) # # def get_next_rand(rands): # retVal = -1 # try: # retVal = rands.po...
"""Attribute implementation for _Dispatch classes. The various listener targets for a particular event class are represented as attributes, which refer to collections of listeners to be fired off. These collections can exist at the class level as well as at the instance level. An event is fired off using code like th...
# -*- coding: utf-8 -*- # From: https://github.com/whtsky/WeRoBot/blob/develop/werobot/messages.py from .exceptions import ParseError MESSAGE_TYPES = {} def handle_for_type(type): def register(f): MESSAGE_TYPES[type] = f return f return register class WechatMessage(object): def __init_...
"""Tests for MultivariateNormalFullCovariance.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from scipy import stats from tensorflow.contrib import distributions from tensorflow.python.ops import array_ops from tensorflow.python.ops ...
import kwant from math import sqrt from matplotlib import pyplot import numpy as np from garn.geometry import hexagon, extension from garn.system_wide import Wire class Wire3D(Wire): """Wire3D facilitates the modelling of nanowire contact geometries in Kwant by actings as a help in constructing a hexagonal ...
from mpi4py.MPI import COMM_WORLD import maf @maf.test def test_bcast_string(self): '''here is some doc for you''' maf.log('here.') world = maf.MafComm.World maf.log('here..') val = 'm' * (world.rank + 3) maf.log('here...') if world.rank == 0: self.assert_equal("mmm", val) els...
""" timeformat.py Contains functions to format time periods. Based on code from the Django project and CloudBot contributors. The licensing for this module isn't solid, because I started working on this module before I had a proper system for tracking code licences. If your code is in this file and you have any queri...
#! /usr/bin/env python # -*- coding: utf-8 -*- import sys,os import traceback HEADER_LEN = 8 FILTER_LEN = 3 PARTITION_LEN = 3 SERIAL_LEN = 38 JCP_SERIAL_LEN = 35 # for jcp PARTITION_PREFIX_NBR = { 0:[40,4], 1:[37,7], 2:[34,10], 3:[30,14], 4:[27,17], 5:[24,20], 6:[20,24], } class convertpy:...
from __future__ import unicode_literals from django.contrib.auth.models import Group, User from tekis.members.models import TekisMember class TekisAuthBackend(object): """Backend that authenticates with the members database and creates a full Django user object if it succeeds """ def authenticate(...
#!/usr/bin/env python # coding: utf-8 import verification from mocking import mock, TestDouble from mock_registry import mock_registry from verification import VerificationError __copyright__ = "Copyright 2008-2010, Mockito Contributors" __license__ = "MIT" __maintainer__ = "Mockito Maintainers" __email__ = "<EMAIL>"...
from django.contrib.gis.db import models import datetime class Dataset(models.Model): name = models.CharField(max_length=100) identifier = models.CharField(max_length=50, unique=True, primary_key=True, db_index=True) objects = models.GeoManager() def __unicode__(self): return self.name PROGR...
from openerp.tests import common class TestMoveExplode(common.TransactionCase): def setUp(self): super(TestMoveExplode, self).setUp() cr, uid = self.cr, self.uid # Usefull models self.ir_model_data = self.registry('ir.model.data') self.sale_order_line = self.registry('sal...
"""Implementation of validators, post-processors and auto-complete functions. Validators ---------- Following is a short overview over how validators may be defined for fields. Inline validators (always executed):: class MyForm(...): myfield = MyField() def validate_myfield(form, field): ...
import sys __all__ = ['_reduce', '_set', '_next', '_groupby', '_sorted', '_update_wrapper'] # we support Python >= 2.3 assert sys.hexversion >= 0x020300f0 # On Python 3, reduce became a functools module function try: import functools _reduce = functools.reduce except (ImportError, AttributeError): _reduc...
""" =================== Universal Functions =================== Ufuncs are, generally speaking, mathematical functions or operations that are applied element-by-element to the contents of an array. That is, the result in each output array element only depends on the value in the corresponding input array (or arrays) a...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.module_utils.facts.network.base import NetworkCollector from ansible.module_utils.facts.network.generic_bsd import GenericBsdIfconfigNetwork class NetBSDNetwork(GenericBsdIfconfigNetwork): """ This is the Net...
import functools import logging from weblib.error import ResponseNotValid def integrity(integrity_func, integrity_errors=(ResponseNotValid,), ignore_errors=()): """ Args: :param integrity_func: couldb callable or string contains name of method to call """ def build_d...
import unittest from airflow.executors.local_executor import LocalExecutor from airflow.utils.state import State from airflow.utils.timeout import timeout class LocalExecutorTest(unittest.TestCase): TEST_SUCCESS_COMMANDS = 5 def execution_parallelism(self, parallelism=0): executor = LocalExecutor(p...
from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import ast from pants.contrib.python.checks.tasks.checkstyle.common import CheckstylePlugin # TODO(wickman) # # 1. open(foo) should always be done in a with context...
# Django settings for puzzle_captcha project. import os PROJECT_DIR = os.path.abspath(os.path.dirname(__file__)) PROJECT_NAME = PROJECT_DIR.split("/")[-1] DEBUG = False TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', '<EMAIL>'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db....
import numpy as np from sklearn.metrics.cluster import adjusted_mutual_info_score from sklearn.metrics.cluster import adjusted_rand_score from sklearn.metrics.cluster import completeness_score from sklearn.metrics.cluster import contingency_matrix from sklearn.metrics.cluster import entropy from sklearn.metrics.cluste...
import unittest from scrapy.http import Request from scrapy.item import BaseItem from scrapy.utils.spider import iterate_spider_output, iter_spider_classes from scrapy.spiders import CrawlSpider class MyBaseSpider(CrawlSpider): pass # abstract spider class MySpider1(MyBaseSpider): name = 'myspider1' class ...
# see: http://www.indjango.com/access-google-sheets-in-python-using-gspread/ # This will issue 100 HTTP requests to Google API: # for row in range(1, 101): # worksheet.update_cell(1, row, 'Bingo!') # While this is only two HTTP requests: # cell_list = worksheet.range('A1:A100') # for cell in cell_list: # cell....
import sys, unittest from ctypes import * structures = [] byteswapped_structures = [] if sys.byteorder == "little": SwappedStructure = BigEndianStructure else: SwappedStructure = LittleEndianStructure for typ in [c_short, c_int, c_long, c_longlong, c_float, c_double, c_ushort, c_uint...