code stringlengths 1 199k |
|---|
"""Tests for distutils.command.build_scripts."""
import os
import unittest
from distutils.command.build_scripts import build_scripts
from distutils.core import Distribution
import sysconfig
from distutils.tests import support
from test.test_support import run_unittest
class BuildScriptsTestCase(support.TempdirManager,
... |
"""
Example script to show some of the possibilities of the SynapseCollection class. We
connect neurons, and get the SynapseCollection with a GetConnections call. To get
a better understanding of the connections, we plot the weights between the
source and targets.
"""
import nest
import matplotlib.pyplot as plt
import ... |
"""
The LibVMI Library is an introspection library that simplifies access to
memory in a target virtual machine or in a file containing a dump of
a system's physical memory. LibVMI is based on the XenAccess Library.
Copyright 2011 Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporatio... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: vmware_guest_serial_port
short_description: Manage serial ports... |
from django.core import urlresolvers
from django.views.decorators import csrf
from django.conf.urls import patterns
def _patch_pattern(regex_pattern):
"""
Patch pattern callback using csrf_exempt. Enforce
RegexURLPattern callback to get resolved if required.
"""
regex_pattern._callback = \
c... |
import sys
from neutronclient.neutron.v2_0 import servicetype
from neutronclient.tests.unit import test_cli20
class CLITestV20ServiceProvidersJSON(test_cli20.CLITestV20Base):
id_field = "name"
def setUp(self):
super(CLITestV20ServiceProvidersJSON, self).setUp(
plurals={'tags': 'tag'}
... |
from collections import defaultdict
import time
import psutil
from checks import AgentCheck
from config import _is_affirmative
from utils.platform import Platform
DEFAULT_AD_CACHE_DURATION = 120
DEFAULT_PID_CACHE_DURATION = 120
ATTR_TO_METRIC = {
'thr': 'threads',
'cpu': 'cpu.pct',
... |
try:
from astropy.models import ParametricModel,Parameter,_convert_input,_convert_output
import numpy as np
class PowerLawModel(ParametricModel):
param_names = ['scale', 'alpha']
def __init__(self, scale, alpha, param_dim=1):
self._scale = Parameter(name='scale', val=scale, mclas... |
"""Tests for experimental iterator_ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.data.python.ops import iterator_ops
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.estimator import estimator
from te... |
import code
import cpp_util
from model import Platforms
from schema_util import CapitalizeFirstLetter
from schema_util import JsFunctionNameToClassName
import json
import os
import re
def _RemoveDescriptions(node):
"""Returns a copy of |schema| with "description" fields removed.
"""
if isinstance(node, dict):
... |
"""
>>> from voidptr_ext import *
Check for correct conversion
>>> use(get())
Check that None is converted to a NULL void pointer
>>> useany(get())
1
>>> useany(None)
0
Check that we don't lose type information by converting NULL
opaque pointers to None
>>> assert getnull() is None
>>> useany(getnull())... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import re
import json
from ansible.module_utils._text import to_text, to_bytes
from ansible.plugins.terminal import TerminalBase
from ansible.errors import AnsibleConnectionFailure
class TerminalModule(TerminalBase):
terminal_st... |
class Module:
def __init__(self, mainMenu, params=[]):
# metadata info about the module, not modified during runtime
self.info = {
# name for the module that will appear in module menus
'Name': 'Get FileServers',
# list of one or more authors for the module
... |
"""
@author: MHL
@license: GNU General Public License 2.0
@contact: michael.ligh@mnin.org
This file provides support for Vista SP1 and SP2 x64
"""
syscalls = [
[
'NtMapUserPhysicalPagesScatter', # 0x0
'NtWaitForSingleObject', # 0x1
'NtCallbackReturn', # 0x2
'NtReadFile', # 0x3
'N... |
"""Tests for rmsprop optimizer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
import math
from absl.testing import parameterized
import numpy as np
from tensorflow.contrib.optimizer_v2 import rmsprop
from tensorflow.python.framework import co... |
import Gaffer
import GafferScene
Gaffer.Metadata.registerNode(
GafferScene.DeleteOptions,
"description",
"""
A node which removes options from the globals.
""",
plugs = {
"names" : [
"description",
"""
The names of options to be removed. Names should be
separated by spaces and can use Gaffer's stand... |
from twisted.python import util, failure
from twisted.internet import defer
id = util.unsignedID
EVENTUAL, FULFILLED, BROKEN = range(3)
class Promise:
"""I am a promise of a future result. I am a lot like a Deferred, except
that my promised result is usually an instance. I make it possible to
schedule metho... |
import sys
import os
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.intersphinx',
'sphinx.ext.todo',
'sphinx.ext.coverage',
]
templates_path = ['templates']
source_suffix = '.rst'
project = 'MicroPython'
copyright = '2014, Damien P. George'
version = '1.4'
release = '1.4.5'
e... |
"""
Boolean geometry utilities.
"""
from __future__ import absolute_import
import __init__
import sys
__author__ = 'Enrique Perez (perez_enrique@yahoo.com)'
__credits__ = 'Art of Illusion <http://www.artofillusion.org/>'
__date__ = '$Date: 2008/02/05 $'
__license__ = 'GNU Affero General Public License http://www.gnu.or... |
from openerp.osv import osv, fields
from openerp.tools.translate import _
from openerp.addons.point_of_sale.point_of_sale import pos_session
class pos_session_opening(osv.osv_memory):
_name = 'pos.session.opening'
_columns = {
'pos_config_id' : fields.many2one('pos.config', string='Point of Sale', requi... |
"""This package holds the REST API that supports the Horizon dashboard
Javascript code.
It is not intended to be used outside of Horizon, and makes no promises of
stability or fitness for purpose outside of that scope.
It does not promise to adhere to the general OpenStack API Guidelines set out
in https://wiki.opensta... |
"""Functions to provide simpler and prettier logging."""
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 tensor... |
"""Test the getchaintips RPC.
- introduce a network split
- work on chains of different lengths
- join the network together again
- verify that getchaintips now returns two chain tips.
"""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal
class GetChainTipsTest ... |
import unittest
import time
from datetime import datetime
from app import create_app, db
from app.models import User, AnonymousUser, Role, Permission
class UserModelTestCase(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.app_context = self.app.app_context()
self.a... |
from ..libmp.backend import xrange
from .functions import defun, defun_wrapped, defun_static
@defun
def stieltjes(ctx, n, a=1):
n = ctx.convert(n)
a = ctx.convert(a)
if n < 0:
return ctx.bad_domain("Stieltjes constants defined for n >= 0")
if hasattr(ctx, "stieltjes_cache"):
stieltjes_ca... |
"""Common utilities for tests of the Cython layer of gRPC Python."""
import collections
import threading
from grpc._cython import cygrpc
RPC_COUNT = 4000
EMPTY_FLAGS = 0
INVOCATION_METADATA = (
('client-md-key', 'client-md-key'),
('client-md-key-bin', b'\x00\x01' * 3000),
)
INITIAL_METADATA = (
('server-ini... |
"""Test for environment_tools. These are SMALL and MEDIUM tests."""
import os
import unittest
import TestFramework
class EnvToolsTests(unittest.TestCase):
"""Tests for environment_tools module."""
def setUp(self):
"""Per-test setup."""
self.env = self.root_env.Clone()
def testFilterOut(self):
"""Test... |
from lettuce import step, world
from common import *
@step('There are no courses$')
def no_courses(step):
world.clear_courses()
create_studio_user()
@step('I click the New Course button$')
def i_click_new_course(step):
world.css_click('.new-course-button')
@step('I fill in the new course information$')
def ... |
"""Tests and Benchmarks for Densenet model."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gc
import time
import tensorflow as tf
import tensorflow.contrib.eager as tfe
from tensorflow.contrib.eager.python.examples.densenet import densenet
from ten... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = """
---
module: exos_facts
version_added: "2.7"
author:
- "Lance Richardson... |
"""Sparsemax op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorfl... |
import github.GithubObject
class PaginatedListBase:
def __init__(self):
self.__elements = list()
def __getitem__(self, index):
assert isinstance(index, (int, slice))
if isinstance(index, (int, long)):
self.__fetchToIndex(index)
return self.__elements[index]
... |
import os
import shutil
import tempfile
import vmprof
import prof_six as six
from _prof_imports import TreeStats, CallTreeStat
class VmProfProfile(object):
""" Wrapper class that represents VmProf Python profiling backend with API matching
the cProfile.
"""
def __init__(self):
self.stats = N... |
from pytest import mark
from translate.misc import wStringIO
from translate.storage import dtd, test_monolingual
def test_roundtrip_quoting():
specials = [
'Fish & chips',
'five < six',
'six > five',
'Use ',
'Use &nbsp;A "solution"',
"skop 'n bal",
'... |
"""Generate some standard test data for debugging TensorBoard.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import bisect
import math
import os
import os.path
import random
import shutil
import numpy as np
from six.moves import xrange # pylint: disabl... |
"""Escaping/unescaping methods for HTML, JSON, URLs, and others.
Also includes a few other miscellaneous string manipulation functions that
have crept in over time.
"""
from __future__ import absolute_import, division, print_function
import json
import re
from tornado.util import PY3, unicode_type, basestring_type
if P... |
from __future__ import unicode_literals
import frappe, re
from frappe.website.website_generator import WebsiteGenerator
from frappe.website.render import clear_cache
from frappe.utils import today, cint, global_date_format, get_fullname
from frappe.website.utils import find_first_image, get_comment_list
from frappe.tem... |
class PayPalFailure(Exception): pass |
name0_1_1_0_0_2_0 = None
name0_1_1_0_0_2_1 = None
name0_1_1_0_0_2_2 = None
name0_1_1_0_0_2_3 = None
name0_1_1_0_0_2_4 = None |
__version__="0.12.5" |
from openerp import tools
from openerp.osv import osv
from openerp.osv import fields
from openerp.tools.translate import _
class invite_wizard(osv.osv_memory):
""" Wizard to invite partners and make them followers. """
_name = 'mail.wizard.invite'
_description = 'Invite wizard'
def default_get(self, cr,... |
from django.apps import AppConfig
class WagtailAdminAppConfig(AppConfig):
name = 'wagtail.wagtailadmin'
label = 'wagtailadmin'
verbose_name = "Wagtail admin" |
import logging
access_logger = logging.getLogger('aiohttp.access')
client_logger = logging.getLogger('aiohttp.client')
internal_logger = logging.getLogger('aiohttp.internal')
server_logger = logging.getLogger('aiohttp.server')
web_logger = logging.getLogger('aiohttp.web')
ws_logger = logging.getLogger('aiohttp.websocke... |
import build_server
build_server.main()
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import logging
import optparse
import posixpath
import time
from local_renderer import LocalRenderer
class _RequestHandler(BaseHTTPRequestHandler):
'''A HTTPRequestHandler that outputs the docs page generated by Hand... |
import os
import httplib
import logging
import functools
from modularodm.exceptions import ValidationValueError
from framework.exceptions import HTTPError
from framework.analytics import update_counter
from website.addons.osfstorage import settings
logger = logging.getLogger(__name__)
LOCATION_KEYS = ['service', settin... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
module: sf_account_manager
short_description: Manage SolidFire accounts
ext... |
import sys
import re
import time
from XmTestLib import *
domain = XmTestDomain()
try:
domain.start(noConsole=True)
except DomainError, e:
if verbose:
print "Failed to create test domain because:"
print e.extra
FAIL(str(e))
status, output = traceCommand("xm destroy %s" % domain.getId())
if st... |
import os
import re
import subprocess
import sys
import urlparse
from wptrunner.update.sync import LoadManifest
from wptrunner.update.tree import get_unique_name
from wptrunner.update.base import Step, StepRunner, exit_clean, exit_unclean
from .tree import Commit, GitTree, Patch
import github
from .github import GitHub... |
from __future__ import absolute_import, division
import time
import os
try:
unicode
except NameError:
unicode = str
from . import LockBase, NotLocked, NotMyLock, LockTimeout, AlreadyLocked
class SQLiteLockFile(LockBase):
"Demonstrate SQL-based locking."
testdb = None
def __init__(self, path, threade... |
from django.db import models, DEFAULT_DB_ALIAS, connection
from django.contrib.auth.models import User
from django.conf import settings
class Animal(models.Model):
name = models.CharField(max_length=150)
latin_name = models.CharField(max_length=150)
count = models.IntegerField()
weight = models.FloatFie... |
def func(a1):
"""
Parameters:
a1 (:class:`MyClass`): used to call :def:`my_function` and access :attr:`my_attr`
Raises:
:class:`MyException`: thrown in case of any error
""" |
"""Tests for parabolic cylinder functions.
"""
import numpy as np
from numpy.testing import assert_allclose, assert_equal
import scipy.special as sc
def test_pbwa_segfault():
# Regression test for https://github.com/scipy/scipy/issues/6208.
#
# Data generated by mpmath.
#
w = 1.02276567211316867161
... |
"""Generate a dot graph from the output of several profilers."""
__author__ = "Jose Fonseca"
__version__ = "1.0"
import sys
import math
import os.path
import re
import textwrap
import optparse
try:
# Debugging helper module
import debug
except ImportError:
pass
def percentage(p):
return "%.02f%%" % (p*1... |
"""
The Twisted Daemon: platform-independent interface.
@author: Christopher Armstrong
"""
from twisted.application import app
from twisted.python.runtime import platformType
if platformType == "win32":
from twisted.scripts._twistw import ServerOptions, \
WindowsApplicationRunner as _SomeApplicationRunner
e... |
"""Tests for google.protobuf.pyext behavior."""
__author__ = 'anuraag@google.com (Anuraag Agrawal)'
import os
os.environ['PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION'] = 'cpp'
os.environ['PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION_VERSION'] = '2'
from google.apputils import basetest
from google.protobuf.internal import api_impl... |
"""Tests for TransformedDistribution."""
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.contrib import linalg
from tensorflow.contrib.distributions.python... |
import decimal
try:
import thread
except ImportError:
import dummy_thread as thread
from threading import local
from django.conf import settings
from django.db import DEFAULT_DB_ALIAS
from django.db.backends import util
from django.db.transaction import TransactionManagementError
from django.utils import dateti... |
def foo():
pass \
\
\ |
from django.conf import settings
from django.core.mail import send_mail
from django.core.urlresolvers import reverse
def send_validation(strategy, backend, code):
url = '{0}?verification_code={1}'.format(
reverse('social:complete', args=(backend.name,)),
code.code
)
url = strategy.request.bu... |
from __future__ import print_function
from pyspark import SparkContext
from pyspark.mllib.stat import Statistics
if __name__ == "__main__":
sc = SparkContext(appName="HypothesisTestingKolmogorovSmirnovTestExample")
# $example on$
parallelData = sc.parallelize([0.1, 0.15, 0.2, 0.3, 0.25])
# run a KS test... |
{
'!langcode!': 'fr',
'!langname!': 'Français',
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" est une expression optionnelle comme "champ1=\'nouvellevaleur\'". Vous ne pouvez mettre à jour ou supprimer les résultats d\'un JOIN',
'%s %%{row}... |
from django.contrib import admin
from django.db import models
class Band(models.Model):
name = models.CharField(max_length=100)
bio = models.TextField()
rank = models.IntegerField()
class Meta:
ordering = ('name',)
class Song(models.Model):
band = models.ForeignKey(Band)
name = models.Ch... |
class Token(object):
def __init__(self, start_mark, end_mark):
self.start_mark = start_mark
self.end_mark = end_mark
def __repr__(self):
attributes = [key for key in self.__dict__
if not key.endswith('_mark')]
attributes.sort()
arguments = ', '.join(['%s=%... |
import sys
import os
cwd = os.getcwd()
project_root = os.path.dirname(cwd)
sys.path.insert(0, project_root)
import pyramid_sms
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'SMS for Pyramid'
copyright = u'2016, Mikko Oht... |
from django.utils.functional import SimpleLazyObject
from mongo_auth import get_user as mongo_auth_get_user
def get_user(request):
if not hasattr(request, '_cached_user'):
request._cached_user = mongo_auth_get_user(request)
return request._cached_user
class AuthenticationMiddleware(object):
def proc... |
"""The initialization file for the Pywikibot framework."""
from __future__ import unicode_literals
__release__ = '2.0rc4'
__version__ = '$Id: e26392a530582f286edf2d99e729218b2e93405e $'
import datetime
import math
import re
import sys
import threading
import json
if sys.version_info[0] > 2:
from queue import Queue
... |
import urllib.request
from feedgen.feed import FeedGenerator
from post_parser import post_title, post_author, post_time, post_files_num
from misc import is_number
baseurl = 'http://phya.snu.ac.kr/xe/underbbs/'
url ='http://phya.snu.ac.kr/xe/index.php?mid=underbbs&category=372' # notices + general
f = open('srl_notices.... |
__version__= "$Version: $"
__rcsid__="$Id: $"
import matplotlib
from wx import MilliSleep
from wx import SplashScreen, SPLASH_CENTRE_ON_SCREEN, SPLASH_TIMEOUT
import os
import sys
import warnings
from . import zpickle
from .utils import *
from .dialogs.waxy import *
from .dialogs import *
from .run_sim import *
import ... |
import requests
import json
def test_api_endpoint_existence(todolist_app):
with todolist_app.test_client() as client:
resp = client.get('/tasks')
assert resp.status_code == 200
def test_task_creation(todolist_app):
with todolist_app.test_client() as client:
resp = client.jpost(
'/tasks', {
"title": "Firs... |
from pyvisdk.thirdparty import Enum
EventCategory = Enum(
'error',
'info',
'user',
'warning',
) |
import requests
import csv
from configparser import ConfigParser
config = ConfigParser()
config.read("config.cfg")
token = config.get("auth", "token")
domain = config.get("instance", "domain")
headers = {"Authorization" : "Bearer %s" % token}
source_course_id = 311693
csv_file = ""
payload = {'migration_type': 'course_... |
import math
import re
from collections import defaultdict
def matches(t1, t2):
t1r = "".join([t[-1] for t in t1])
t2r = "".join([t[-1] for t in t2])
t1l = "".join([t[0] for t in t1])
t2l = "".join([t[0] for t in t2])
t1_edges = [t1[0], t1[-1], t1r, t1l]
t2_edges = [t2[0], t2[-1], t2[0][::-1], t2... |
def is_isogram(s):
""" Determine if a word or phrase is an isogram.
An isogram (also known as a "nonpattern word") is a word or phrase without a repeating letter.
Examples of isograms:
- lumberjacks
- background
- downstream
"""
from collections import Counter
s = s.lower().strip()
... |
import argparse
from PGEnv import PGEnvironment
from PGAgent import PGAgent
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--gym_environment', type=str, default='Pong-v0',
help='OpenAI Gym Environment to be used (default to Pong-v0)')
parser.add_ar... |
from feature import *
from pymongo import MongoClient
from bson.binary import Binary as BsonBinary
import pickle
import os
from operator import itemgetter
import time
import sys
imagelocation = "" #Input Image path
indir = "" #Directory Path
client = MongoClient('mongodb://localhost:27017')
db = client.coil #Insert you... |
from outcome import Outcome
from odds import Odds
class Bin:
def __init__(
self,
*outcomes
):
self.outcomes = set([outcome for outcome in outcomes])
def add_outcome(
self,
outcome
):
self.outcomes.add(outcome)
def __str__(self):
return ', '.joi... |
"""The Tornado web framework.
核心模块, 参考示例使用代码:
- 重要模块:
- tornado.web
- tornado.ioloop # 根据示例,可知入口在此.参看: ioloop.py
- tornado.httpserver
The Tornado web framework looks a bit like web.py (http://webpy.org/) or
Google's webapp (http://code.google.com/appengine/docs/python/tools/webapp/)... |
"""
This script exposes a class used to read the Shapefile Index format
used in conjunction with a shapefile. The Index file gives the record
number and content length for every record stored in the main shapefile.
This is useful if you need to extract specific features from a shapefile
without reading the entire file.... |
from app.api_client.error import HTTPError
from app.helpers.login_helpers import generate_buyer_creation_token
from dmapiclient.audit import AuditTypes
from dmutils.email import generate_token, EmailError
from dmutils.forms import FakeCsrf
from ...helpers import BaseApplicationTest
from lxml import html
import mock
imp... |
import asyncio
import subprocess
import numpy as np
import time
comm = None
class Camera:
def __init__(self, notify):
self._process = None
self._now_pos = np.array([0., 0., 0.])
self._running = False
self._notify = notify
@asyncio.coroutine
def connect(self):
self._pr... |
from __future__ import unicode_literals
from abc import ABCMeta, abstractmethod
from django.core.files import File
from six import with_metaclass
from django.utils.module_loading import import_string
from rest_framework_tus import signals
from .settings import TUS_SAVE_HANDLER_CLASS
class AbstractUploadSaveHandler(with... |
import sys
import os
from unittest.mock import MagicMock
class Mock(MagicMock):
@classmethod
def __getattr__(cls, name):
return MagicMock()
MOCK_MODULES = ['face_recognition_models', 'Click', 'dlib', 'numpy', 'PIL']
sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES)
cwd = os.getcwd(... |
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … , ak) must ... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('artist', '0002_auto_20150322_1630'),
]
operations = [
migrations.CreateModel(
name='Event',
fields=[
('id', model... |
import sys
import os
cwd = os.getcwd()
parent = os.path.dirname(cwd)
sys.path.append(parent)
import cbh_core_model
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'cbh_core_model'
copyright = u'2015, Andrew Stretton'
versi... |
import numpy as np
import keras as ks
import matplotlib.pyplot as plt
from keras.datasets import boston_housing
from keras import models
from keras import layers
from keras.utils.np_utils import to_categorical
(train_data, train_targets), (test_data, test_targets) = boston_housing.load_data()
mean = train_data.mean(axi... |
"""
ckanutils
~~~~~~~~~
Provides methods for interacting with a CKAN instance
Examples:
literal blocks::
python example_google.py
Attributes:
CKAN_KEYS (List[str]): available CKAN keyword arguments.
"""
from __future__ import (
absolute_import, division, print_function, with_statement,
unicode_l... |
from .interactiveapp import InteractiveApplication, ENCODING
class InteractiveLoopApplication(InteractiveApplication):
def __init__(self, name, desc, version,
padding, margin, suffix, encoding=ENCODING):
super(InteractiveLoopApplication, self).__init__(
name, desc, version, padd... |
import re
import datetime
import time
while True:
#open the file for reading
file = open("test.txt")
content = file.read()
#Get timestamp
ts = time.time()
ist = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
#open file for read and close it neatly(wrap code in try/except)
... |
'''
This module corresponds to ARDroneLib/Soft/Common/navdata_common.h
'''
import ctypes
import functools
from pyardrone.utils.structure import Structure
uint8_t = ctypes.c_uint8
uint16_t = ctypes.c_uint16
uint32_t = ctypes.c_uint32
int16_t = ctypes.c_int16
int32_t = ctypes.c_int32
bool_t = ctypes.c_uint32 # ARDroneTo... |
import numpy as np
import scipy
from sklearn import preprocessing
from sklearn.feature_extraction import DictVectorizer
from sklearn.cross_validation import train_test_split
from sklearn.metrics import classification_report, confusion_matrix
from collections import Counter
from scipy.stats.stats import pearsonr
import ... |
import sys, os, fabric
class PiServicePolicies:
@staticmethod
def is_local():
return (not fabric.api.env.hosts or fabric.api.env.hosts[0] in ['localhost', '127.0.0.1', '::1'])
@staticmethod
def is_pi():
return os.path.isdir('/home/pi')
@staticmethod
def check_local_or_exit():
if not PiServicePol... |
import cv2, numpy as np
from dolphintracker.singlecam_tracker.camera_filter.FindDolphin import SearchBlobs
from dolphintracker.singlecam_tracker.camera_filter.BackGroundDetector import BackGroundDetector
import datetime
class PoolCamera(object):
def __init__(self, videofile, name, scene, maskObjectsNames, filters, fra... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: qb_docker_image
short_description: QB extension of Ansible's `d... |
from __future__ import unicode_literals
from django.db import models, migrations
from decimal import Decimal
import django.core.validators
class Migration(migrations.Migration):
dependencies = [
('farms', '0024_rain_and_irrigation_allow_null'),
]
operations = [
migrations.AlterField(
... |
import math
def trapezint(f, a, b, n) :
"""
Just for testing - uses trapazoidal approximation from on f from a to b with
n trapazoids
"""
output = 0.0
for i in range(int(n)):
f_output_lower = f( a + i * (b - a) / n )
f_output_upper = f( a + (i + 1) * (b - a) / n )
output ... |
"""
Created on Thu Mar 24 16:25:41 2016
@author: pavel
"""
from gi.repository import Gtk
import parameter_types as ptypes
from logger import Logger
logger = Logger.get_logger()
import gobject
gobject.threads_init()
def idle_add_decorator(func):
def callback(*args):
gobject.idle_add(func, *args)
return c... |
lookup = {}
lookup = dict()
lookup = {'age': 42, 'loc': 'Italy'}
lookup = dict(age=42, loc='Italy')
print(lookup)
print(lookup['loc'])
lookup['cat'] = 'cat'
if 'cat' in lookup:
print(lookup['cat'])
class Wizard:
# This actually creates a key value dictionary
def __init__(self, name, level):
self.lev... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('course_selection', '0018_auto_20150830_0319'),
]
operations = [
migrations.AlterUniqueTogether(
name='friend_relationship',
uniqu... |
from django.conf.urls import url
from .views import (
semseterResultxlsx,
)
urlpatterns=[
url(r'^semester-xlsx/(?P<collegeCode>\d+)/(?P<branchCode>\d+)/(?P<yearOfJoining>\d+)/(?P<semester>\d+)/$',semseterResultxlsx,name='semseterResultxlsx')
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.