content string |
|---|
"""Babysitter server starts instances of servers defined in a deployment
template.
Each server instance is started, monitored, and restarted as
necessary. Log files for each server are archived to S3 as
appropriate, custom cloud watch metrics are reported, and AWS SNS is
used to notify of any unrecoverable failures.
... |
"""Write the workbook global settings to the archive."""
# package imports
from ..shared.xmltools import Element, SubElement
from ..cell import absolute_coordinate
from ..shared.xmltools import get_document_content
from ..shared.ooxml import NAMESPACES, ARC_CORE, ARC_WORKBOOK, \
ARC_APP, ARC_THEME, ARC_STYLE, A... |
# COMMON CODE FOR MIGRATION
import re
from ansible.module_utils.basic import get_exception
from ansible.module_utils.netcfg import NetworkConfig, ConfigLine
from ansible.module_utils.shell import ShellError
try:
from ansible.module_utils.nxos import get_module
except ImportError:
from ansible.module_utils.nxo... |
"""Non-blocking HTTP client implementation using pycurl."""
from __future__ import absolute_import, division, print_function, with_statement
import collections
import logging
import pycurl
import threading
import time
from tornado import httputil
from tornado import ioloop
from tornado.log import gen_log
from tornad... |
import os
from rhn.i18n import bstr
from spacewalk.common import checksum
def get_package_header(filename=None, file_obj=None, fd=None):
# pylint: disable=E1103
if filename is not None:
stream = open(filename, mode='rb')
need_close = True
elif file_obj is not None:
stream = file_obj... |
"""Tests for distutils.command.bdist_wininst."""
import unittest
import os
from distutils.dist import Distribution
from distutils.command.bdist_wininst import bdist_wininst
from distutils.tests import support
class BuildWinInstTestCase(support.TempdirManager,
unittest.TestCase):
def te... |
"""Methods for reporting bugs."""
import subprocess, sys, os
__all__ = ['ReportFailure', 'BugReport', 'getReporters']
#
class ReportFailure(Exception):
"""Generic exception for failures in bug reporting."""
def __init__(self, value):
self.value = value
# Collect information about a bug.
cl... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
from __future__ import unicode_literals
TagNames = [
"A",
"ABBR",
"ACRONYM",
"ADDRESS",
"ALTGLYPH",
"ALTGLYPHDEF",
"ALTGLYPHITEM",
"ANIMATE",
"ANIMATEC... |
"""Unit tests for the write transform."""
import logging
import unittest
import apache_beam as beam
from apache_beam.io import iobase
from apache_beam.test_pipeline import TestPipeline
from apache_beam.transforms.ptransform import PTransform
from apache_beam.transforms.util import assert_that, is_empty
class _Test... |
from django.test import TestCase
from django.contrib.contenttypes.models import ContentType
from wagtail.wagtailadmin import widgets
from wagtail.wagtailcore.models import Page
from wagtail.tests.testapp.models import SimplePage, EventPage
class TestAdminPageChooserWidget(TestCase):
def setUp(self):
sel... |
import sys
from test import support
import unittest
from importlib import _bootstrap
from .. import util
from . import util as ext_util
@util.case_insensitive_tests
class ExtensionModuleCaseSensitivityTest(unittest.TestCase):
def find_module(self):
good_name = ext_util.NAME
bad_name = good_name.u... |
"""dagrun start end
Revision ID: 4446e08588
Revises: 561833c1c74b
Create Date: 2015-12-10 11:26:18.439223
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '4446e08588'
down_revision = '561833c1c74b'
branch_labels = None
depends_on = None
def upgrade(): # noqa... |
''' unit tests for Ansible module: na_ontap_vscan_scanner_pool '''
from __future__ import print_function
import json
import pytest
from units.compat import unittest
from units.compat.mock import patch, Mock
from ansible.module_utils import basic
from ansible.module_utils._text import to_bytes
import ansible.module_ut... |
#!/usr/bin/env python
import optparse
import os
import sys
import subprocess
root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def optional_dir():
return os.path.join(root_dir, 'optional')
def repo_dir(repo_name):
return os.path.join(root_dir, repo_name)
def get_repo_names():
retur... |
"""Wrong web_socket_do_extra_handshake signature.
"""
def no_web_socket_do_extra_handshake(request):
pass
def web_socket_transfer_data(request):
request.connection.write(
'sub/wrong_handshake_sig_wsh.py is called for %s, %s' %
(request.ws_resource, request.ws_protocol))
# vi:sts=4... |
"""Policy implementation that generates random actions."""
from __future__ import absolute_import
from __future__ import division
# Using Type Annotations.
from __future__ import print_function
from typing import cast
import tensorflow as tf
from tf_agents.distributions import masked
from tf_agents.policies import tf... |
import re
from ansible.module_utils.network import NetworkError, NetworkModule
from ansible.module_utils.network import add_argument, register_transport
from ansible.module_utils.network import to_list
from ansible.module_utils.shell import CliBase
from ansible.module_utils.netcli import Command
add_argument('context... |
"""
Tests for the `mo_pack.compress_wgdos` and `mo_pack.decompress_wgdos`
functions.
"""
from __future__ import absolute_import, division, print_function
import os
import unittest
import numpy as np
from numpy.testing import assert_array_equal, assert_almost_equal
import mo_pack
class TestPackWGDOS(unittest.Test... |
import builder
# Your site name
SITE_NAME="Newham3"
# The URL where tests will be submitted to
URL = "http://192.168.0.2/dash/submit.php?project=PJSIP"
# Test group
GROUP = "Experimental"
# PJSIP base directory
BASE_DIR = "/root/project/pjproject"
# List of additional ccdash options
#OPTIONS = ["-o", "out.xml", "-... |
"""
Alternate namespace for toolz such that all functions are curried
Currying provides implicit partial evaluation of all functions
Example:
Get usually requires two arguments, an index and a collection
>>> from toolz.curried import get
>>> get(0, ('a', 'b'))
'a'
When we use it in higher order ... |
""" Management command to update libraries' search index """
from __future__ import print_function
from textwrap import dedent
from django.core.management import BaseCommand, CommandError
from opaque_keys.edx.keys import CourseKey
from opaque_keys.edx.locator import LibraryLocator
from contentstore.courseware_index i... |
"""
============================
Underfitting vs. Overfitting
============================
This example demonstrates the problems of underfitting and overfitting and
how we can use linear regression with polynomial features to approximate
nonlinear functions. The plot shows the function that we want to approximate,
wh... |
# -*- encoding: utf-8 -*-
"""Test class for Template UI"""
from fauxfactory import gen_string
from nailgun import entities
from robottelo.constants import OS_TEMPLATE_DATA_FILE, SNIPPET_DATA_FILE
from robottelo.datafactory import generate_strings_list, invalid_values_list
from robottelo.decorators import run_only_on, t... |
from openerp.osv import fields, osv
from openerp.tools.translate import _
class res_company(osv.osv):
_inherit = 'res.company'
_columns = {
'project_time_mode_id': fields.many2one('product.uom', 'Project Time Unit',
help='This will set the unit of measure used in projects and tasks.\n' \
"I... |
import random
import sys
MPEG_SYNC_BYTE = 0x47
def make_fake_transport_stream_packet(npkts):
"""
Return a sequence of 8-bit ints that represents an MPEG Transport Stream packet.
@param npkts: how many 188-byte packets to return
FYI, each ATSC Data Frame contains two Data Fields, each of which contai... |
from openerp import tools
from openerp.addons.crm import crm
from openerp.osv import fields, osv
AVAILABLE_STATES = [
('draft', 'Draft'),
('open', 'Todo'),
('cancel', 'Cancelled'),
('done', 'Held'),
('pending', 'Pending')
]
class crm_phonecall_report(osv.osv):
""" Phone calls by user and sect... |
# -*- coding: utf-8 -*-
"""
pygments.lexers.igor
~~~~~~~~~~~~~~~~~~~~
Lexers for Igor Pro.
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer, words
from pygments.token import Text, Commen... |
from __future__ import absolute_import, division, unicode_literals
from datrie import Trie as DATrie
from six import text_type
from ._base import Trie as ABCTrie
class Trie(ABCTrie):
def __init__(self, data):
chars = set()
for key in data.keys():
if not isinstance(key, text_type):
... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'community'}
import datetime
import re
from ansible.module_utils.basic import AnsibleModule
from... |
#!/usr/bin/env python
from util import just_tokenize, make_tests, make_fails, TSTRING, STRING, SSTRING, ID, WHITE, NUMBER, INT, HEX, CCOMMENT, CMCOMMENT, PYCOMMENT, NEWLINE, ANY
def make_single(tok, *tests):
fn = just_tokenize(tok, WHITE)
return make_tests(globals(), tok.__name__, fn, tests)
def fail_single(... |
from corehq.apps.telerivet.models import TelerivetBackend, IncomingRequest
from corehq.apps.sms.api import incoming as incoming_sms
from corehq.apps.sms.util import strip_plus
from corehq.apps.ivr.api import incoming as incoming_ivr
from celery.task import task
from dimagi.utils.logging import notify_exception
from dja... |
"""
Vizualization tests
"""
##########################################################################
## Imports
##########################################################################
import unittest
import gvas.viz
from peak.util.imports import lazyModule
######################################################... |
import json, os, urllib, urlparse
def redirect(url, response):
response.add_required_headers = False
response.writer.write_status(301)
response.writer.write_header("access-control-allow-origin", "*")
response.writer.write_header("location", url)
response.writer.end_headers()
response.writer.wri... |
"""
Comparing two html documents.
"""
from __future__ import unicode_literals
import re
from django.utils import six
from django.utils.encoding import force_text, python_2_unicode_compatible
from django.utils.html_parser import HTMLParseError, HTMLParser
WHITESPACE = re.compile('\s+')
def normalize_whitespace(str... |
from ansible.modules.cloud.amazon.s3_bucket import compare_policies
small_policy_one = {
'Version': '2012-10-17',
'Statement': [
{
'Action': 's3:PutObjectAcl',
'Sid': 'AddCannedAcl2',
'Resource': 'arn:aws:s3:::test_policy/*',
'Effect': 'Allow',
... |
# -*- coding: utf-8 -*-
__author__= "Luis C. Pérez Tato (LCPT)"
__copyright__= "Copyright 2016, LCPT"
__license__= "GPL"
__version__= "3.0"
__email__= "<EMAIL>"
import sys
def getLg(soilClass):
'''
From a length greater than de distance "lg" the soil mouvement
can bi consideread as completely uncorrelated.
'... |
'''
Created on Jan 25, 2012
@author: Trung Dong Huynh
'''
import unittest
from prov.model import ProvBundle, ProvRecord, ProvExceptionCannotUnifyAttribute
import logging
import json
import examples
import os
logger = logging.getLogger(__name__)
class Test(unittest.TestCase):
def setUp(self):
... |
"""
==========
Kernel PCA
==========
This example shows that Kernel PCA is able to find a projection of the data
that makes data linearly separable.
"""
print(__doc__)
# Authors: Mathieu Blondel
# Andreas Mueller
# License: BSD 3 clause
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomp... |
"""
CLI interface for ripcord management.
"""
import logging
from oslo.config import cfg
from ripcord.common import config
from ripcord.db import migration as db_migration
from ripcord.openstack.common import log
CONF = cfg.CONF
LOG = log.getLogger(__name__)
def do_db_version():
"""Print database's current ... |
"""Unit tests for CaptionGenerator."""
import math
import numpy as np
import tensorflow as tf
from im2txt.inference_utils import caption_generator
class FakeVocab(object):
"""Fake Vocabulary for testing purposes."""
def __init__(self):
self.start_id = 0 # Word id denoting sentence start.
self.end_i... |
from backend.db import PostsaiDB
from response import ret200
import config
def fetchLatestConfig():
""" returns the currently active configuration """
rows = fetchConfigs(1)
if len(rows) < 1:
return "- .* .* .* .* Cannot fetch config from database"
latestConfig = rows[0]
# return mock()
... |
from StringIO import StringIO
from django.contrib.auth import models, management
from django.contrib.auth.management.commands import changepassword
from django.test import TestCase
class GetDefaultUsernameTestCase(TestCase):
def setUp(self):
self._getpass_getuser = management.get_system_username
de... |
# Type keys and specify shift key up/down
import subprocess
import sys
import argparse
import time
import os
class TypeKeys:
def __init__(self, *args, **kwargs):
self.shift = False
self.name = 'Tally.ERP 9'
self.window = 0
if 'WID' in os.environ:
self.window = os.enviro... |
#coding:utf8
'''
Created on 2013-5-8
@author: lan (www.9miao.com)
'''
from dbpool import dbpool
from MySQLdb.cursors import DictCursor
from numbers import Number
from twisted.python import log
def forEachPlusInsertProps(tablename,props):
assert type(props) == dict
pkeysstr = str(tuple(props.keys())).replace... |
"""
Support for eQ-3 Bluetooth Smart thermostats.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/climate.eq3btsmart/
"""
import logging
import voluptuous as vol
from homeassistant.components.climate import (
ClimateDevice, PLATFORM_SCHEMA, PRECISIO... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys,re
from handlers import *
from util import *
from rules import *
import logging
logging.basicConfig(level=logging.INFO)
class Parser:
"""
解析器父类
"""
def __init__(self, handler):
self.handler = handler # 处理程序对象
self.rules = [] # 判... |
# -*- coding:utf-8 -*-
import os
import glob
import zipfile
from sigal.gallery import Gallery
from sigal.settings import read_settings
CURRENT_DIR = os.path.dirname(__file__)
SAMPLE_DIR = os.path.join(CURRENT_DIR, 'sample')
SAMPLE_SOURCE = os.path.join(SAMPLE_DIR, 'pictures', 'dir1')
def make_gallery(**kwargs):
... |
import unittest
from django.utils import checksums
class TestUtilsChecksums(unittest.TestCase):
def check_output(self, function, value, output=None):
"""
Check that function(value) equals output. If output is None,
check that function(value) equals value.
"""
if output is... |
import pytest
from cli_config.tag import tag
from utility.nix_error import NixError
def test_tag_delete_no_tag(capsys):
with pytest.raises(SystemExit) as _excinfo:
tag.tag("nixconfig", ["delete"])
_out, _err = capsys.readouterr()
assert "2" in str(_excinfo.value), "Exception doesn't contain exp... |
# <EMAIL>
#
# This is a simple little module I wrote to make life easier. I didn't
# see anything quite like it in the library, though I may have overlooked
# something. I wrote this when I was trying to read some heavily nested
# tuples with fairly non-descriptive content. This is modeled very muc... |
from django.utils.translation import ungettext, ugettext as _
from django.utils.encoding import force_unicode
from django import template
from django.template import defaultfilters
from datetime import date
import re
register = template.Library()
def ordinal(value):
"""
Converts an integer to its ordinal as a... |
import time
from openerp.osv import fields, osv
class hr_salary_employee_bymonth(osv.osv_memory):
_name = 'hr.salary.employee.month'
_description = 'Hr Salary Employee By Month Report'
_columns = {
'start_date': fields.date('Start Date', required=True),
'end_date': fields.date('End Date', ... |
"""
Zinc Python Tools
A collection of Qt widgets and utilities building on the Python bindings for the OpenCMISS-Zinc Visualisation Library.
"""
classifiers = """\
Development Status :: 5 - Production/Stable
Intended Audience :: Developers
Intended Audience :: Education
Intended Audience :: Science/Research
License :... |
"""Exceptions that can be thrown by calliope tools.
The exceptions in this file, and those that extend them, can be thrown by
the Run() function in calliope tools without worrying about stack traces
littering the screen in CLI mode. In interpreter mode, they are not caught
from within calliope.
"""
from functools imp... |
#!/usr/bin/env python
import urllib2
import base64
import json
import xml
import sys
def post():
# Ensure that your stream format matches the rule format you intend to use (e.g. '.xml' or '.json')
# See below to edit the rule format used when adding and deleting rules (xml or json)
# Expected Enterprise Data Col... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: zabbix_screen
short_description: Create/update/delete Zabb... |
"""
This is the CmdOptions module which parses the users'
input and provides hint for users.
"""
import os
import traceback
import build_rules
import console
from blade_util import relative_path
# import these modules make build functions registered into build_rules
# TODO(chen3feng): Load build modules dynamic... |
import csv
import codecs
import cStringIO
import datetime
import isodate
import functools
import json
import re
from collections import OrderedDict
from django import http
from django.conf import settings
from . import models
class DateTimeEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance... |
import BoostBuild
t = BoostBuild.Tester(use_test_config=False)
t.write("jamroot.jam", """
project : requirements <library>lib//x ;
exe a : a.cpp foo ;
obj foo : foo.cpp : <variant>release ;
""")
t.write("a.cpp", """
void aux();
int main() { aux(); }
""")
t.write("foo.cpp", """
void gee();
void aux() { gee(); }
""")... |
import project_issue
import report
import res_config
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
from __future__ import print_function
import sys
from operator import add
import base64
from pyspark import SparkContext
from pyspark.sql import SQLContext
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: importfromdashdb <dash jdbc url>", file=sys.stderr)
exit(-1)
dashdb_jdb... |
# -*- coding: utf-8 -*-
import npyscreen
class MyAutoComplete(npyscreen.Autocomplete):
colors = ["Jaune","Bleu","Rouge","Vert", "Vert foncé"]
def auto_complete(self, input):
choices = []
for word in MyAutoComplete.colors:
if word.startswith(self.value):
choices.... |
import os
from .. import build
class ExtensionModule:
def __init__(self, interpreter):
self.interpreter = interpreter
self.snippets = set() # List of methods that operate only on the interpreter.
def is_snippet(self, funcname):
return funcname in self.snippets
def get_include_args(... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import (
compat_urllib_parse_unquote,
compat_xpath,
)
from ..utils import (
int_or_none,
find_xpath_attr,
xpath_text,
update_url_query,
)
class NozIE(InfoExtractor):
_VALID_URL = r'http... |
"File-based cache backend"
import hashlib
import os
import shutil
import time
try:
import cPickle as pickle
except ImportError:
import pickle
from django.core.cache.backends.base import BaseCache
class FileBasedCache(BaseCache):
def __init__(self, dir, params):
BaseCache.__init__(self, params)
... |
"""Implementation of JSONDecoder
"""
import re
import sys
import struct
from django.utils.simplejson.scanner import make_scanner
c_scanstring = None
__all__ = ['JSONDecoder']
FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL
def _floatconstants():
_BYTES = '7FF80000000000007FF0000000000000'.decode('he... |
r"""
=====================================================================
The Johnson-Lindenstrauss bound for embedding with random projections
=====================================================================
The `Johnson-Lindenstrauss lemma`_ states that any high dimensional
dataset can be randomly projected i... |
"""Test result object"""
import io
import sys
import traceback
from . import util
from functools import wraps
__unittest = True
def failfast(method):
@wraps(method)
def inner(self, *args, **kw):
if getattr(self, 'failfast', False):
self.stop()
return method(self, *args, **kw)
... |
import glob
import os
import sys
import warnings
from pkginfo.distribution import Distribution
from pkginfo._compat import STRING_TYPES
class Installed(Distribution):
def __init__(self, package, metadata_version=None):
if isinstance(package, STRING_TYPES):
self.package_name = package
... |
import procurement_jit
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
from unittest import mock
from automaton import exceptions as automaton_errors
from eventlet import semaphore
import fixtures
from futurist import periodics
from openstack import exceptions as os_exc
from oslo_config import cfg
import stevedore
from ironic_inspector.common import ironic as ir_utils
from ironic_inspec... |
import sys
from fx2load import *
def get_eeprom(addr,length):
assert f.isopen()
prom_val = '';
while len(prom_val)<length:
buf='\x00'*1024 # read 1024 bytes max at a time
transfer_len = length-len(prom_val) > 1024 and 1024 or length-len(prom_val)
ret=f.do_usb_command ( buf,
0xc0,
... |
import pytest
import six
from django.test import TestCase
from karaage.projects.forms import ProjectForm
from karaage.tests.fixtures import ProjectFactory
@pytest.mark.django_db
class ProjectFormTestCase(TestCase):
def setUp(self):
super(ProjectFormTestCase, self).setUp()
self.project = ProjectF... |
# -*- coding: utf-8 -*-
"""
werkzeug.debug
~~~~~~~~~~~~~~
WSGI application traceback debugger.
:copyright: (c) 2013 by the Werkzeug Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import json
import mimetypes
from os.path import join, dirname, basename, isfile
... |
"""
================================
Type Class Library: typelib.py
================================
version 1.0 (2000-03-27)
Homepage: [[http://gotools.sourceforge.net/]] (see sgflib.py)
Copyright (C) 2000 David John Goodger ([[mailto:<EMAIL>]]).
typelib.py comes with ABSOLUTELY NO WARRANTY. This is free software, ... |
from __future__ import absolute_import, division, unicode_literals
from types import ModuleType
try:
import xml.etree.cElementTree as default_etree
except ImportError:
import xml.etree.ElementTree as default_etree
__all__ = ["default_etree", "MethodDispatcher", "isSurrogatePair",
"surrogatePairTo... |
from tempest.api.compute import base
from tempest.common.utils import data_utils
from tempest import config
from tempest import exceptions
from tempest import test
CONF = config.CONF
class QuotasAdminNegativeTestJSON(base.BaseV2ComputeAdminTest):
force_tenant_isolation = True
@classmethod
def resource_s... |
"""
Query subclasses which provide extra functionality beyond simple data retrieval.
"""
from django.conf import settings
from django.core.exceptions import FieldError
from django.db import connections
from django.db.models.query_utils import Q
from django.db.models.constants import LOOKUP_SEP
from django.db.models.fi... |
from openerp.osv import osv
from edi import EDIMixin
from openerp import SUPERUSER_ID
RES_CURRENCY_EDI_STRUCT = {
#custom: 'code'
'symbol': True,
'rate': True,
}
class res_currency(osv.osv, EDIMixin):
_inherit = "res.currency"
def edi_export(self, cr, uid, records, edi_struct=None, context=None)... |
from openerp.osv import osv, fields
def referencable_models(self, cr, uid, context=None):
obj = self.pool.get('res.request.link')
ids = obj.search(cr, uid, [], context=context)
res = obj.read(cr, uid, ids, ['object', 'name'], context)
return [(r['object'], r['name']) for r in res]
class res_request_li... |
from __future__ import print_function
import argparse
import collections
import os
import sys
try:
from urllib.request import urlopen
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
from urllib import urlopen
try:
import mistune
except ImportError:
print("Mis... |
import os
from mi.logging import config
from mi.core.log import get_logger
from mi.core.exceptions import NotImplementedException
__author__ = 'wordenm'
log = get_logger()
class ParticleDataHandler(object):
def __init__(self):
self._samples = {}
self._failure = False
def addParticleSample(... |
import re
from pprint import pprint
from StringIO import StringIO
ProgISO8601Date = re.compile('(\d{4})-([01]\d)-([0-3]\d)')
def _get_next_row(d):
def _get_next_element(_list):
for element in _list:
yield element
return
row = {}
while True:
for key, column in d.iteritem... |
from __future__ import unicode_literals
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
class ModelBackend(object):
"""
Authenticates against settings.AUTH_USER_MODEL.
"""
def authenticate(self, username=None, password=None, **kwargs):
UserMod... |
import openerp
from openerp.report.interface import report_int
import openerp.tools as tools
from openerp.tools.safe_eval import safe_eval as eval
from lxml import etree
from openerp.report import render, report_sxw
import locale
import time, os
from operator import itemgetter
from datetime import datetime
class re... |
"""
Read/write tools for nonuniform electric field .grd format.
Matthew Grawe, grawe2 (at) illinois.edu
January 2017
"""
import numpy as np
def next_line(grd_file):
"""
next_line
Function returns the next line in the file
that is not a blank line, unless the line is
'', which is a typical EOF marker... |
# coding=utf-8
import unittest
"""945. Minimum Increment to Make Array Unique
https://leetcode.com/problems/minimum-increment-to-make-array-unique/description/
Given an array of integers A, a _move_ consists of choosing any `A[i]`, and
incrementing it by `1`.
Return the least number of moves to make every value in `... |
from ..core import GpGrid
from .. import likelihoods
from .. import kern
class GPRegressionGrid(GpGrid):
"""
Gaussian Process model for grid inputs using Kronecker products
This is a thin wrapper around the models.GpGrid class, with a set of sensible defaults
:param X: input observations
:param Y... |
from ctypes import *
import array
import gc
import unittest
class X(Structure):
_fields_ = [("c_int", c_int)]
init_called = False
def __init__(self):
self._init_called = True
class Test(unittest.TestCase):
def test_fom_buffer(self):
a = array.array("i", range(16))
x = (c_int * ... |
#!/usr/bin/env python
"""
Tests of utilities for dealing with ufl indexing and components vs flattened index spaces.
"""
from ufl import *
from ufl import product
from ufl.permutation import compute_indices
from uflacs.analysis.indexing import (map_indexed_arg_components,
map_c... |
# -*- coding: utf-8 -*-
from eclcli.common import command
from eclcli.common import exceptions
from eclcli.common import utils
from ..rcaclient.common.utils import objectify
class ListUser(command.Lister):
def get_parser(self, prog_name):
parser = super(ListUser, self).get_parser(prog_name)
ret... |
"""This test for the LFW require medium-size data dowloading and processing
If the data has not been already downloaded by running the examples,
the tests won't run (skipped).
If the test are run, the first execution will be long (typically a bit
more than a couple of minutes) but as the dataset loader is leveraging
... |
"""Various helper functions"""
__all__ = ['BasicAuth', 'FormData', 'parse_mimetype']
import base64
import binascii
import io
import os
import uuid
import urllib.parse
from collections import namedtuple
from wsgiref.handlers import format_date_time
from . import hdrs, multidict
class BasicAuth(namedtuple('BasicAuth'... |
import volatility.utils as utils
import volatility.plugins.gui.constants as consts
import volatility.plugins.gui.sessions as sessions
class Gahti(sessions.Sessions):
"""Dump the USER handle type information"""
def render_text(self, outfd, data):
profile = utils.load_as(self._config).profile
... |
"""Utilities to get a password and/or the current user name.
getpass(prompt[, stream]) - Prompt for a password, with echo turned off.
getuser() - Get the user name from the environment or password database.
GetPassWarning - This UserWarning is issued when getpass() cannot prevent
echoing of the passw... |
"""
Continuous to discrete transformations for state-space and transfer function.
"""
from __future__ import division, print_function, absolute_import
# March 29, 2011
import numpy as np
from scipy import linalg
from .ltisys import tf2ss, ss2tf, zpk2ss, ss2zpk
__all__ = ['cont2discrete']
def cont2discrete(sys, dt... |
# -*- coding: utf-8 -*-
"""Class representing the mapper for the formatter init files."""
from plasoscaffolder.bll.mappings import base_mapping_helper
from plasoscaffolder.bll.mappings import base_sqliteplugin_mapping
from plasoscaffolder.model import init_data_model
class FormatterInitMapping(
base_sqliteplugin_... |
import skimage
import skimage.io
import skimage.transform
import numpy as np
# synset = [l.strip() for l in open('synset.txt').readlines()]
# returns image of shape [224, 224, 3]
# [height, width, depth]
def load_image(path):
# load image
img = skimage.io.imread(path)
img = img / 255.0
assert (0 <= ... |
from django.shortcuts import render, render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.views import generic
from django.core.context_processors import csrf
from django.views.decorators.csrf import csrf_protect, csrf_exempt
from django.contrib import auth
from django.contrib.auth.... |
"""
SWF
"""
from tag import SWFTimelineContainer
from stream import SWFStream
from export import SVGExporter
try:
import cStringIO as StringIO
except ImportError:
import StringIO
class SWFHeaderException(Exception):
""" Exception raised in case of an invalid SWFHeader """
def __init__(self, message):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.