content string |
|---|
#!/usr/bin/python
"""
Ansible module to manage the ssh known_hosts file.
Copyright(c) 2014, Matthew Vernon <<EMAIL>>
This module 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 License, o... |
import hashlib
import os
import struct
import sys
from recipe_engine import recipe_test_api
# TODO(phajdan.jr): Clean up this somewhat ugly import.
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'resources'))
import bot_update
class BotUpdateTestApi(recipe_test_api.RecipeTestApi):
def output_json(self,... |
"""A POP3 client class.
Based on the J. Myers POP3 draft, Jan. 96
"""
# [heavily stealing from nntplib.py]
# Updated: Piers Lauder <<EMAIL>> [Jul '97]
# String method conversion and test jig improvements by ESR, February 2001.
# Added the POP3_SSL class. Methods loosely based on IMAP_SSL. Hector Urtubia <<EMA... |
from codecs import open
from os import path
from setuptools import setup, Extension
from Cython.Distutils import build_ext
import numpy
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.... |
from core.generalized import GeneralizedModel
from utils.functions import *
from scipy import *
from numpy.random import normal, permutation, rand, uniform
LAYER_MODEL_FNS = { 'binary': sigmoid,
'linear': linear }
LAYER_SAMPLE_FNS = { 'binary': sample_bernoulli,
'linear': l... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
Grass7AlgorithmProvider.py
---------------------
Date : April 2014
Copyright : (C) 2014 by Victor Olaya
Email : volayaf at gmail dot com
****************... |
"""Unit tests for oauth2client.clientsecrets."""
__author__ = '<EMAIL> (Joe Gregorio)'
import os
import unittest
from io import StringIO
import httplib2
from oauth2client import clientsecrets
DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
VALID_FILE = os.path.join(DATA_DIR, 'client_secrets.json')
INV... |
from openerp.osv import fields,osv
class report_workcenter_load(osv.osv):
_name="report.workcenter.load"
_description="Work Center Load"
_auto = False
_log_access = False
_columns = {
'name': fields.char('Week', size=64, required=True),
'workcenter_id': fields.many2one('mrp.workcen... |
'''
What could be better:
- what if the guesses are not valid ints?
- let them know if it's a near miss (a la Sub Search)?
- variable-sized grid?
- variable number of ships?
- show location of ship when player loses?
'''
from random import randint
from reportlab.lib.validators import isInt
def get... |
import ctypes
import CoreFoundation
import objc
import subprocess
import time
## from http://benden.us/journal/2014/OS-X-Power-Management-No-Sleep-Howto/
## http://alistra.ghost.io/2015/03/15/making-your-os-x-not-sleep-while-running-scripts/
def SetUpIOFramework():
# load the IOKit library
framework = c... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
Provides a command container for additional tox commands, used in "tox.ini".
COMMANDS:
* copytree
* copy
* py2to3
REQUIRES:
* argparse
"""
from glob import glob
import argparse
import inspect
import os.path
import shutil
import sys
import collections
__aut... |
#!/usr/bin/env python
# UserString is a wrapper around the native builtin string type.
# UserString instances should behave similar to builtin string objects.
import string
from test import test_support, string_tests
from UserString import UserString, MutableString
import warnings
class UserStringTest(
string_tes... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'metadata_version': '1.1'}
DOCUMENTATION = r'''
---
module: zfs_delegate_admin
short_description: Manage ZFS delegated a... |
import pytest
from marshmallow import validate, ValidationError, Schema
import marshmallow
import sqlalchemy as sa
from marshmallow_sqlalchemy import SQLAlchemySchema, SQLAlchemyAutoSchema, auto_field
from marshmallow_sqlalchemy.exceptions import IncorrectSchemaTypeError
from marshmallow_sqlalchemy.fields import Rela... |
"""
prepare_yelp_sentences.py
description: prepare the yelp data for training in convolutional recurrent architectures over sentences
"""
from nlpdatahandlers import YelpDataHandler
import cPickle as pickle
import logging
import numpy as np
from textclf.wordvectors.glove import GloVeBox
LOGGER_PREFIX = ' %s'
loggi... |
{
'name' : 'Invoicing',
'version' : '1.1',
'summary': 'Send Invoices and Track Payments',
'sequence': 30,
'description': """
Invoicing & Payments
====================
The specific and easy-to-use Invoicing system in Odoo allows you to keep track of your accounting, even when you are not an accountan... |
from eispice import *
from numpy import matrix
R0 = [[0.861113, 0], [0, 0.861113]]
L0 = [[231.832e-9, 38.1483e-9],[38.1483e-9, 231.819e-9]]
G0 = [[0,0],[0,0]]
C0 = [[156.163e-12, -8.60102e-12],[-8.60102e-12, 156.193e-12]]
Rs = [[0.368757e-3, 0],[0, 0.368757e-3]]
Gd = [[0,0],[0,0]]
cct = Circuit("TlineW Test")
cct.Vs... |
"Test harness for doctests."
# pylint: disable-msg=E0611,W0142
__metaclass__ = type
__all__ = [
'additional_tests',
]
import atexit
import doctest
import os
#from pkg_resources import (
# resource_filename, resource_exists, resource_listdir, cleanup_resources)
import unittest
DOCTEST_FLAGS = (
doctes... |
from .base import RegexVocabulary, left_pad, NoWildcardsVocabulary, NoRangeFillVocabulary, NoCheckVocabulary,\
ProcedureVocabulary, ModifierVocabulary
import re
from itertools import product
_hcpcs_split_regex = re.compile('^([A-Z]*)([0-9]+)([A-Z]*)$')
def hcpcs_split(code):
match = _hcpcs_split_regex.match(co... |
from __future__ import unicode_literals
import uuid
from django.conf import settings
from django.db.backends.base.operations import BaseDatabaseOperations
from django.utils import six, timezone
from django.utils.encoding import force_text
class DatabaseOperations(BaseDatabaseOperations):
compiler_module = "djan... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import copy
import os
import json
import tempfile
from yaml import YAMLError
from ansible.errors import AnsibleFileNotFound, AnsibleParserError
from ansible.errors.yaml_strings import YAML_SYNTAX_ERROR
from ansible.module_utils.ba... |
# coding: utf-8
from __future__ import unicode_literals
import random
from .common import InfoExtractor
from ..utils import (
xpath_text,
int_or_none,
ExtractorError,
)
class MioMioIE(InfoExtractor):
IE_NAME = 'miomio.tv'
_VALID_URL = r'https?://(?:www\.)?miomio\.tv/watch/cc(?P<id>[0-9]+)'
_... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_host_config_manager
short_description: Manage advance configurations about an E... |
import os
import shutil
import sys
import unittest
sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir))
from pylib import android_commands
# pylint: disable=W0212,W0702
class TestDeviceTempFile(unittest.TestCase):
def setUp(self):
if not os.getenv('BUILDTYPE'):
os.environ['BUILDTYPE'] = '... |
import os, time
import random
import StringIO
from openerp.report.render import render
from openerp.report.interface import report_int
from pychart import *
theme.use_color = 1
class external_pdf(render):
""" Generate External PDF """
def __init__(self, pdf):
render.__init__(self)
self.pdf... |
from __future__ import division, absolute_import, print_function
from numpy.testing import TestCase, assert_, run_module_suite
import numpy.distutils.fcompiler
g77_version_strings = [
('GNU Fortran 0.5.25 20010319 (prerelease)', '0.5.25'),
('GNU Fortran (GCC 3.2) 3.2 20020814 (release)', '3.2'),
('GNU Fo... |
import os
import sys
import unittest
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
BUILD_TOOLS_DIR = os.path.dirname(SCRIPT_DIR)
CHROME_SRC = os.path.dirname(os.path.dirname(os.path.dirname(BUILD_TOOLS_DIR)))
MOCK_DIR = os.path.join(CHROME_SRC, "third_party", "pymock")
# For the mock library
sys.path.append... |
# Originally written by Kevin Breen (@KevTheHermit):
# https://github.com/kevthehermit/RATDecoders/blob/master/BlueBanana.py
import os
import sys
import string
from zipfile import ZipFile
from cStringIO import StringIO
from Crypto.Cipher import AES
from lib.common.out import *
def decrypt_aes(key, data):
cipher ... |
"""
You can fit your LikelihoodModel using l1 regularization by changing
the method argument and adding an argument alpha. See code for
details.
The Story
---------
The maximum likelihood (ML) solution works well when the number of data
points is large and the noise is small. When the ML solution starts
"bre... |
from Pymacs import Let, lisp
from unittest import TestLoader
from itertools import groupby
import os
def symbol(sym):
return lisp[sym]
def discover(root_dir):
if not os.path.exists(root_dir):
return []
loader = TestLoader()
prev_dir = os.curdir
os.chdir(root_dir)
tests = loader.... |
# =============================================================================
# JPEG Image Descriptor - SMALL
# This file is part of the FuzzLabs Fuzzing Framework
#
#
# Original file MD5 sum: 4dde17f30fee6e6120a58d890a4ec572
# Original file SHA1 sum: 1e1d1c90b4b0dd9ad5719be96dcbfabf32ff9aee
#
# ===============... |
from ebdata.templatemaker.hole import Hole, OrHole, RegexHole, IgnoreHole
import unittest
class HoleEquality(unittest.TestCase):
def test_equal_hole(self):
self.assertEqual(Hole(), Hole())
def test_nonequal_hole(self):
self.assertNotEqual(Hole(), OrHole())
def test_equal_orhole(self):
... |
from django.core.urlresolvers import reverse
from django.forms import ValidationError # noqa
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon import messages
from openstack_dashboard import api
class ResizeVolumeForm(forms.SelfHandlingForm... |
__all__ = [
'SoftLayerDNSDriver'
]
from libcloud.common.softlayer import SoftLayerConnection
from libcloud.common.softlayer import SoftLayerObjectDoesntExist
from libcloud.dns.types import Provider, RecordType
from libcloud.dns.types import ZoneDoesNotExistError, RecordDoesNotExistError
from libcloud.dns.base imp... |
from .decorators import jit
import numba
@jit(device=True)
def all_sync(mask, predicate):
"""
If for all threads in the masked warp the predicate is true, then
a non-zero value is returned, otherwise 0 is returned.
"""
return numba.cuda.vote_sync_intrinsic(mask, 0, predicate)[1]
@jit(device=True... |
import sys, os, traceback, time
from genericworker import *
class SpecificWorker(GenericWorker):
def __init__(self, proxy_map):
super(SpecificWorker, self).__init__(proxy_map)
self.timer.timeout.connect(self.compute)
self.imu = DataImu()
self.Period = 100
self.timer.start(self.Period)
print("Start with ... |
import ConfigParser
import os
import pipes
import stat
import subprocess
try:
import MySQLdb
except ImportError:
mysqldb_found = False
else:
mysqldb_found = True
# ===========================================
# MySQL module specific support methods.
#
def db_exists(cursor, db):
res = cursor.execute("SH... |
import copy
import requests
from odlclient.version import __version__
from odlclient.datatypes import JsonObjectFactory, JSON_MAP, PLURALS
from odlclient.error import raise_errors, NotFound
UA = {
'content-type': 'application/json',
'user-agent': 'odlnclient/{0} '.format(__version__) +
'pyt... |
"""
==========================================================
Adjustment for chance in clustering performance evaluation
==========================================================
The following plots demonstrate the impact of the number of clusters and
number of samples on various clustering performance evaluation me... |
from cupy import elementwise
from cupy.logic import ufunc
logical_and = ufunc.create_comparison(
'logical_and', '&&',
'''Computes the logical AND of two arrays.
.. seealso:: :data:`numpy.logical_and`
''')
logical_or = ufunc.create_comparison(
'logical_or', '||',
'''Computes the logical OR o... |
from __future__ import unicode_literals
import itertools
import re
from .common import SearchInfoExtractor
from ..compat import (
compat_urllib_parse,
)
class GoogleSearchIE(SearchInfoExtractor):
IE_DESC = 'Google Video search'
_MAX_RESULTS = 1000
IE_NAME = 'video.google:search'
_SEARCH_KEY = 'g... |
from __future__ import unicode_literals
import frappe, json, sys
from frappe import _
from frappe.utils import cint, flt, now, cstr, strip_html
from frappe.model import default_fields
from frappe.model.naming import set_new_name
class BaseDocument(object):
ignore_in_getter = ("doctype", "_meta", "meta", "_table_field... |
from unittest import TestCase
from pybuilder.graph_utils import Graph, GraphHasCycles
class GraphUtilsTests(TestCase):
def test_should_find_trivial_cycle_in_graph_when_there_is_one(self):
graph_with_trivial_cycle = Graph({"a": "a"})
self.assertRaises(GraphHasCycles, graph_with_trivial_cycle.asser... |
import os
import tempfile
def package_installed(module, name, category):
cmd = [module.get_bin_path('pkginfo', True)]
cmd.append('-q')
if category:
cmd.append('-c')
cmd.append(name)
rc, out, err = module.run_command(' '.join(cmd))
if rc == 0:
return True
else:
return... |
from Screen import Screen
from Components.ActionMap import ActionMap
from Components.Converter.ClientsStreaming import ClientsStreaming
import skin
import gettext
from Components.Sources.StaticText import StaticText
class StreamingClientsInfo(Screen):
skin ="""<screen name="StreamingClientsInfo" position="center,cen... |
"""Test for preservation of unknown fields in the pure Python implementation."""
__author__ = '<EMAIL> (Bohdan Koval)'
try:
import unittest2 as unittest #PY26
except ImportError:
import unittest
from google.protobuf import unittest_mset_pb2
from google.protobuf import unittest_pb2
from google.protobuf import uni... |
from stoqlib.gui.test.uitestutils import GUITest
from stoqlib.gui.dialogs.loandetails import LoanDetailsDialog
class TestLoanDetails(GUITest):
def test_create(self):
loan = self.create_loan()
self.create_loan_item(loan=loan)
dialog = LoanDetailsDialog(self.store, loan)
self.check_... |
from odoo.api import model
from odoo.tools import email_normalize
from odoo.tools.sql import existing_tables
import pytz
import logging
from typing import Iterator, Mapping
from collections import abc
from dateutil.parser import parse
from dateutil.relativedelta import relativedelta
from odoo import _
_logger = logg... |
from xml.etree.ElementTree import ParseError
import pytest
from ..XMLParser import XMLParser
@pytest.mark.parametrize("s", [
'<foo> </foo>',
'<!DOCTYPE foo><foo> </foo>',
'<!DOCTYPE foo PUBLIC "fake" "id"><foo> </foo>',
'<!DOCTYPE foo PUBLIC "fake" "http://www.w3.org/TR/xhtml1/DTD/xht... |
"""Tests for google.protobuf.internal.service_reflection."""
__author__ = '<EMAIL> (Petar Petrov)'
import unittest
from google.protobuf import unittest_pb2
from google.protobuf import service_reflection
from google.protobuf import service
class FooUnitTest(unittest.TestCase):
def testService(self):
class Moc... |
#!/usr/bin/env python2
# MAG3110 : Three-axis magnetometer
# This script can calibrate the sensor and acquire data.
# It will output magnetic field on the three axis in micro Tesla.
import smbus
import os
import time
# I2C constants
bus = smbus.SMBus(1) # 0 if /dev/i2c-0 exists, 1 if /dev/i2c-1 exists
ADDR = 0x0E
... |
"""Utilities for the gRPC Python Beta API."""
import threading
import time
# implementations is referenced from specification in this module.
from grpc.beta import implementations # pylint: disable=unused-import
from grpc.beta import interfaces
from grpc.framework.foundation import callable_util
from grpc.framework.... |
# -*- coding: utf-8 -*-
import re
import time
import urlparse
from module.plugins.internal.Account import Account
from module.plugins.internal.Plugin import parse_html_form, set_cookie
class XFSAccount(Account):
__name__ = "XFSAccount"
__type__ = "account"
__version__ = "0.42"
__status__ = "t... |
"""Generate and work with PEP 425 Compatibility Tags."""
from __future__ import absolute_import
import re
import sys
import warnings
import platform
import logging
try:
import sysconfig
except ImportError: # pragma nocover
# Python < 2.7
import distutils.sysconfig as sysconfig
import distutils.util
from... |
# Webhooks for external integrations.
from __future__ import absolute_import
from typing import Any
from django.utils.translation import ugettext as _
from django.http import HttpRequest, HttpResponse
from zerver.lib.actions import check_send_message
from zerver.lib.response import json_success, json_error
from zerve... |
"""
This module adds shared support for generic cloud modules
In order to use this module, include it as part of a custom
module as shown below.
from ansible.module_utils.cloud import *
The 'cloud' module provides the following common classes:
* CloudRetry
- The base class to be used by other cloud prov... |
""" Testing
"""
import os
import sys
if sys.version_info[0] >= 3:
from io import BytesIO
cStringIO = BytesIO
else:
from cStringIO import StringIO as cStringIO
from StringIO import StringIO as BytesIO
from tempfile import mkstemp
import numpy as np
from numpy.compat import asbytes
from nose.tools ... |
import os
def changecvsroot(oldroot, newroot, *dirs):
def handle((oldroot, newroot), dirname, fnames):
if os.path.basename(dirname) == 'CVS' and 'Root' in fnames:
r = open(os.path.join(dirname, 'Root'), 'r').read().strip()
if r == oldroot:
fp = open(os.path.join(dirn... |
#
# To see the output of this macro, click begin_html <a href="gif/fillrandom.gif">here</a>. end_html
#
from ROOT import TCanvas, TPad, TFormula, TF1, TPaveLabel, TH1F, TFile
from ROOT import gROOT, gBenchmark
gROOT.Reset()
c1 = TCanvas( 'c1', 'The FillRandom example', 200, 10, 700, 900 )
c1.SetFillColor( 18 )
pad... |
# -*- coding: utf-8 -*-
import heapq
from .thing_type import _ThingType
def PTI_decorator__event(name):
def decorator(f):
if not hasattr(f, "_gaminator_events"):
f._gaminator_events = []
f._gaminator_events.append(name)
return f
return decorator
class _EventEmitterMix... |
from sqlalchemy.schema import Column
from sqlalchemy.schema import MetaData
from trove.db.sqlalchemy.migrate_repo.schema import String
from trove.db.sqlalchemy.migrate_repo.schema import Table
def upgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
instances = Table('instances', meta, a... |
class Peer(object):
def __init__(self, address, jobs, rel_perf, pubkey):
self.address = address # string: IP address
self.jobs = jobs # integer: number of CPUs
self.relative_performance = rel_perf
self.pubkey = pubkey # string: pubkey's fingerprint
self.shells = set() # set of strings
self.... |
# Webhooks for external integrations.
from __future__ import absolute_import
from django.utils.translation import ugettext as _
from zerver.lib.actions import check_send_message
from zerver.lib.response import json_success, json_error
from zerver.decorator import REQ, has_request_variables, api_key_only_webhook_view
fr... |
"""
The cmdshell module uses the paramiko package to create SSH connections
to the servers that are represented by instance objects. The module has
functions for running commands, managing files, and opening interactive
shell sessions over those connections.
"""
from boto.mashups.interactive import interactive_shell
im... |
"""
Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's
Smalltalk testing framework.
This module contains the core framework classes that form the basis of
specific test cases and suites (TestCase, TestSuite etc.), and also a
text-based utility class for running the tests and reporting the resu... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from ansible.compat.tests import unittest
from ansible.compat.tests.mock import patch, MagicMock
from ansible import constants as C
from ansible.cli import CLI
from ansible.errors import AnsibleError, AnsibleParserError... |
from __future__ import print_function
import time, sys, signal, atexit
from upm import pyupm_urm37 as sensorObj
def main():
# Instantiate a URM37 sensor on UART 0, with the reset pin on D2
sensor = sensorObj.URM37(0, 2)
## Exit handlers ##
# This function stops python from printing a stacktrace when y... |
"""Creates a tarball with V8 sources, but without .svn directories.
This allows easy packaging of V8, synchronized with browser releases.
Example usage:
export_v8_tarball.py /foo/bar
The above will create file /foo/bar/v8-VERSION.tar.bz2 if it doesn't exist.
"""
import optparse
import os
import re
import subproces... |
import numpy as np
from scipy.lib.lapack import flapack, clapack
FUNCS_TP = {'ssygv' : np.float32,
'dsygv': np.float,
'ssygvd' : np.float32,
'dsygvd' : np.float,
'ssyev' : np.float32,
'dsyev': np.float,
'ssyevr' : np.float32,
'dsyevr' : np.float,
... |
"""Logging that uses pickles.
TODO: add log that logs to a file.
"""
# twisted imports
from twisted.persisted import dirdbm
from twisted.internet import defer
from zope.interface import implements
# sibling imports
import base
class DirDBMLog:
"""Log pickles to DirDBM directory."""
implements(base.IComman... |
"""
Knowledge base module objects
"""
from django.db import models
from treeio.core.models import Object
from django.core.urlresolvers import reverse
from django.template import defaultfilters
from unidecode import unidecode
# KnowledgeFolder model
class KnowledgeFolder(Object):
""" KnowledgeFolder """
name = ... |
#!/usr/bin/python3
from gi.repository import Gio, CScreensaver
from dbusdepot.baseClient import BaseClient
class CinnamonClient(BaseClient):
"""
Simple client to talk to Cinnamon's dbus interface. Currently
its only use is for attempting to force an exit from overview
and expo mode (both of which do... |
from math import cos,sin, factorial
import random
import matplotlib.pyplot as plt
def randominput(n):
listA = []
for i in range(0,n):
ran = random.random()
listB = [i, ran]
listA.append( listB)
return listA
def forward(listinput, x):
dataSize = len(listinput)
#print ... |
import logging
import sys
import os
import openerp
from openerp import tools
from openerp.modules import module
_logger = logging.getLogger(__name__)
commands = {}
class CommandType(type):
def __init__(cls, name, bases, attrs):
super(CommandType, cls).__init__(name, bases, attrs)
name = getattr(... |
# -*- coding: utf-8 -*-
#------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Conector para sharpfile
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import urlparse,urllib2,urllib,re
import os
from core imp... |
"""The Categorical distribution class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.f... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
try:
import json
except ImportError:
import simplejson as json
def jsonify(result, format=False):
''' format JSON output (uncompressed or uncompressed) '''
if result is None:
return "{}"
result2 = resu... |
"""Generic (shallow and deep) copying operations.
Interface summary:
import copy
x = copy.copy(y) # make a shallow copy of y
x = copy.deepcopy(y) # make a deep copy of y
For module specific errors, copy.Error is raised.
The difference between shallow and deep copying is only relev... |
"""Test cycle management."""
__author__ = '<EMAIL> (Alexis O. Torres)'
import logging
import webapp2
from common.handlers import base
from models import test_cycle
class TestCyclesHandler(base.BaseHandler):
"""Handles managing of cycles."""
def get(self):
cycles = test_cycle.FetchTestCycles()
self.... |
import feedparser
import json
import logging
import requests
from django import http
from django.db.models import Q
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.models import User
from django.core.cache import cache
from django.views.decorators.csrf import csrf_exempt
f... |
from distutils.core import setup, Extension
import numpy
import os.path
numpy_inc = (os.path.dirname(numpy.__file__) +
'/core/include/numpy')
c_module = Extension('spherematch_c',
sources = ['pyspherematch.c'],
include_dirs = [ numpy_inc,
... |
"""Utilities to evaluate models with respect to a variable
"""
#
# License: BSD 3 clause
import warnings
import numpy as np
from .base import is_classifier, clone
from .cross_validation import check_cv
from .externals.joblib import Parallel, delayed
from .cross_validation import _safe_split, _score, _fit_and_score
f... |
"""
QGIS Processing Python additions.
This module contains stable API adding additional Python specific functionality
to the core QGIS c++ Processing classes.
"""
__author__ = 'Nathan Woodrow'
__date__ = 'November 2018'
__copyright__ = '(C) 2018, Nathan Woodrow'
from .algfactory import ProcessingAlgFactory
alg = Pr... |
"""Unit tests for the `iris.cube.Cube` class operators."""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
import iris
import iris.tests as tests
import numpy as np
import biggus
class Test_Lazy_Maths(tests.IrisTest):
def build_la... |
import sys
import types
from google.appengine.ext import db
from django import VERSION
from django.core.exceptions import ObjectDoesNotExist
from django.db.models.fields import Field
from django.db.models.options import Options
from django.db.models.loading import register_models, get_model
class ModelManager(objec... |
"""Tests for util.request module."""
import unittest
from django.conf import settings
from django.core.exceptions import SuspiciousOperation
from django.test.client import RequestFactory
from util.request import course_id_from_url, safe_get_host
class ResponseTestCase(unittest.TestCase):
""" Tests for response... |
"""Support for Blink system camera sensors."""
import logging
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import (
DEVICE_CLASS_SIGNAL_STRENGTH,
DEVICE_CLASS_TEMPERATURE,
SIGNAL_STRENGTH_DECIBELS_MILLIWATT,
TEMP_FAHRENHEIT,
)
from .const import DOMAIN, TYPE_TEMPER... |
"""
WSGI config for testproject project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATIO... |
from os import environ
import datetime
try:
import asyncio
except ImportError:
# Trollius >= 0.3 was renamed
import trollius as asyncio
from autobahn import wamp
from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner
class Component(ApplicationSession):
"""
An application compon... |
"""
Page classes to test either the Course Team page or the Library Team page.
"""
from bok_choy.promise import EmptyPromise
from bok_choy.page_object import PageObject
from ...tests.helpers import disable_animations
from .course_page import CoursePage
from . import BASE_URL
def wait_for_ajax_or_reload(browser):
... |
import mrp_product_produce
import mrp_price
import mrp_workcenter_load
import change_production_qty
import stock_move
#import mrp_change_standard_price
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
"""
===================================================================
Multi-output Decision Tree Regression
===================================================================
An example to illustrate multi-output regression with decision tree.
The :ref:`decision trees <tree>`
is used to predict simultaneously the ... |
"""
=============================
OOB Errors for Random Forests
=============================
The ``RandomForestClassifier`` is trained using *bootstrap aggregation*, where
each new tree is fit from a bootstrap sample of the training observations
:math:`z_i = (x_i, y_i)`. The *out-of-bag* (OOB) error is the average er... |
# −*− coding: UTF−8 −*−
from path import path
import os
import pickle
"""
A class providing dictionary access to a folder.
cribbed from http://bitbucket.org/howthebodyworks/fsdict
"""
def get_tmp_dir():
import tempfile
return tempfile.mkdtemp()
class FSDict(dict):
"""
provide dictionary access to ... |
# A simple setup script to create an executable running wxPython. This also
# demonstrates the method for creating a Windows executable that does not have
# an associated console.
#
# wxapp.py is a very simple "Hello, world" type wxPython application
#
# Run the build process by running the command 'python setup.... |
import sys
from django import forms
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import get_resolver
from django.shortcuts import render_to_response
from django.template import TemplateDoesNotExist
from django.views.debug import technical_500_response
from django.views.gener... |
"""Base64 content transfer encoding per RFCs 2045-2047.
This module handles the content transfer encoding method defined in RFC 2045
to encode arbitrary 8-bit data using the three 8-bit bytes in four 7-bit
characters encoding known as Base64.
It is used in the MIME standards for email to attach images, audio, and tex... |
import logging
import os
import py.path
import pytest
import subprocess
import sys
import tempfile
import time
from py.io import TextIO
from ulif.openoffice import oooctl
from ulif.openoffice.oooctl import check_port
from ulif.openoffice.testing import envpath_wo_virtualenvs
@pytest.fixture(scope='session')
def tmpdi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Function to build the A and B response matrices
# Torin Stetina
# June 1st, 2017
import numpy as np
def spin_eri(eriMO, sdim):
# ** Original algorithm based on function
# ** from joshuagoings.com/2013/05/27/tdhf-cis-in-python/
#
# Makes spin adapted 2 electr... |
"""Tests for ElasticAverageOptimizer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import portpicker
from tensorflow.python.client import session
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import ops
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.