content string |
|---|
import uuid
import os
import errno
from copy import deepcopy
import yaml
from .errors import AlreadyInitializedError, NotInitializedError, \
InconsistentStateError
BLOCKADE_STATE_DIR = ".blockade"
BLOCKADE_STATE_FILE = ".blockade/state.yml"
BLOCKADE_ID_PREFIX = "blockade-"
BLOCKADE_STATE_VERSION = 1
def _assur... |
# A simple Particle class, renders the particle as an image.
class Particle(object):
def __init__(self, l, img):
self.acc = PVector(0, 0)
self.vx = randomGaussian() * 0.3
self.vy = randomGaussian() * 0.3 - 1.0
self.vel = PVector(self.vx, self.vy)
self.loc = l.get()
... |
#-*- python -*-
import logging
from datetime import datetime
import urllib2
# Non-stdlib imports
import pkg_resources
import pymongo
from tg import expose, validate, redirect, flash
from tg.decorators import with_trailing_slash, without_trailing_slash
from pylons import g, c, request, response
import formencode
from f... |
# -*- coding: utf-8 -*-
"""
pygments.formatters
~~~~~~~~~~~~~~~~~~~
Pygments formatters.
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
import sys
import types
import fnmatch
from os.path import basename
from pygments.form... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#...for the plotting.
import matplotlib.pyplot as plt
#...for the image manipulation.
import matplotlib.image as mpimg
#...for the MATH.
import numpy as np
# For scaling images.
import scipy.ndimage.interpolation as inter
#...for the colours.
from matplotlib import col... |
"""Makes sure that all EXE and DLL files in the provided directory were built
correctly.
In essense it runs a subset of BinScope tests ensuring that binaries have
/NXCOMPAT, /DYNAMICBASE and /SAFESEH.
"""
import os
import optparse
import sys
# Find /third_party/pefile based on current directory and script path.
sys.... |
from terminatorlib.util import dbg, err
from terminatorlib.version import APP_NAME, APP_VERSION
import socket
import threading
import SocketServer
import code
import sys
import readline
import rlcompleter
import re
def ddbg(msg):
# uncomment this to get lots of spam from debugserver
return
dbg(msg)
class Pytho... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
try:
from zabbix_api import ZabbixAPI, ZabbixAPISubClass
from zabbix_api import Already_Exists
HAS_ZABBIX_API = True
except ImportError:
HAS_ZABBIX_API = False
... |
# coding=utf-8
import sys
import pytest
from tinydb import TinyDB, where
from tinydb.storages import MemoryStorage
from tinydb.middlewares import Middleware
def test_purge(db):
db.purge()
db.insert({})
db.purge()
assert len(db) == 0
def test_all(db):
db.purge()
for i in range(10):
... |
from __future__ import unicode_literals
from django.contrib.contenttypes.fields import (
GenericForeignKey, GenericRelation,
)
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.http import urlquote... |
from django.core.management.base import BaseCommand, CommandError
from xmodule.modulestore.django import modulestore
from xmodule.modulestore.xml_importer import check_module_metadata_editability
from opaque_keys.edx.keys import CourseKey
from opaque_keys import InvalidKeyError
from opaque_keys.edx.locations import Sla... |
from os.path import join
import numpy
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration
from numpy.distutils.system_info import get_info
config = Configuration('linear_model', parent_package, top_path)
# cd fast needs CBLAS
blas_info = get_in... |
import math
import os
from core import perf_benchmark
from telemetry import benchmark
from telemetry import page as page_module
from telemetry.page import page_test
from telemetry import story
from telemetry.value import scalar
from metrics import power
class _DromaeoMeasurement(page_test.PageTest):
def __init__... |
from twisted.python import log
from twisted.internet import defer
from buildbot import util
from buildbot.util import subscription
from buildbot.util.eventual import eventually
if False: # for debugging
debuglog = log.msg
else:
debuglog = lambda m: None
class BaseLock:
"""
Class handling claiming and ... |
"""Sources for numpy arrays and pandas DataFrames."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.learn.python.learn.dataframe import transform
from tensorflow.contrib.learn.python.learn.dataframe.queues import feeding_functions
... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
try:
from pyVmomi import vim, vmodl
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
class VMwareMigrateVmk(object):
def __init__(self, module):
... |
from .core import encode, decode, alabel, ulabel, IDNAError
import codecs
import re
_unicode_dots_re = re.compile(u'[\u002e\u3002\uff0e\uff61]')
class Codec(codecs.Codec):
def encode(self, data, errors='strict'):
if errors != 'strict':
raise IDNAError("Unsupported error handling \"{0}\"".for... |
__author__ = "Julian Debatin"
__copyright__ = "The authors"
__license__ = "Apache 2"
__email__ = "<EMAIL>"
__status__ = "Production"
from ModuroModel.Spa.SpaSdbCdiInUa import SpaSdbCdiInUa
class SpaSdbCdiInDa(SpaSdbCdiInUa):
def __init__(self, sim, simthread):
SpaSdbCdiInUa.__init__(self, sim, simthread)... |
import numpy as np
from numpy.testing import *
class TestBuiltin(TestCase):
def test_run(self):
"""Only test hash runs at all."""
for t in [np.int, np.float, np.complex, np.int32, np.str, np.object,
np.unicode]:
dt = np.dtype(t)
hash(dt)
class TestRecord(Tes... |
from pyramid.response import Response
from pyramid.view import view_config
from beepaste.models.pastes import Pastes
from beepaste.pasteFunctions import pasteExists
from pyramid.httpexceptions import HTTPNotFound, HTTPFound
import base64
@view_config(route_name='view_raw', renderer='templates/pasteRaw.jinja2')
def vie... |
from django.conf.urls import url
from . import feeds
urlpatterns = [
url(r'^syndication/rss2/$', feeds.TestRss2Feed()),
url(r'^syndication/rss2/guid_ispermalink_true/$',
feeds.TestRss2FeedWithGuidIsPermaLinkTrue()),
url(r'^syndication/rss2/guid_ispermalink_false/$',
feeds.TestRss2FeedWith... |
"""Sitemap generation for CERN Open Data Portal."""
import arrow
from flask import current_app, url_for
from invenio_db import db
from invenio_pidstore.models import PersistentIdentifier, PIDStatus
from invenio_records.models import RecordMetadata
def _sitemapdtformat(dt):
"""Convert a datetime to a W3 Date and... |
#!/usr/bin/env python
# This is a standalone test for the regex inside validate-modules
# It is not suitable to add to the make tests target because the
# file under test is outside the test's sys.path AND has a hyphen
# in the name making it unimportable.
#
# To execute this by hand:
# 1) cd <checkoutdir>
# 2) so... |
from lxml import etree
import openerp
import openerp.tools as tools
from openerp.tools.safe_eval import safe_eval
import print_fnc
from openerp.osv.orm import BaseModel
class InheritDict(dict):
# Might be usefull when we're doing name lookup for call or eval.
def __init__(self, parent=None):
self.pare... |
from __future__ import absolute_import, division, print_function
from trakt.interfaces.base import Interface
from trakt.mapper.summary import SummaryMapper
import requests
class ShowsInterface(Interface):
path = 'shows'
def get(self, id, extended=None, **kwargs):
response = self.http.get(str(id), q... |
import pytest
from itertools import tee, izip
from testutils import get_co, get_bytecode
from equip import BytecodeObject
from equip.bytecode.utils import show_bytecode
import equip.utils.log as logutils
from equip.utils.log import logger
logutils.enableLogger(to_file='./equip.log')
from equip.analysis import Control... |
"""
Grayscale morphological operations
"""
import functools
import numpy as np
from scipy import ndimage as ndi
from .misc import default_selem
from ..util import pad, crop
__all__ = ['erosion', 'dilation', 'opening', 'closing', 'white_tophat',
'black_tophat']
def _shift_selem(selem, shift_x, shift_y):
... |
"""Parses the command line, discovers the appropriate benchmarks, and runs them.
Handles benchmark configuration, but all the logic for
actually running the benchmark is in Benchmark and PageRunner."""
import difflib
import hashlib
import inspect
import json
import os
import sys
from telemetry import benchmark
from ... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from os import path, walk
import re
from ansible.errors import AnsibleError
from ansible.module_utils.six import string_types
from ansible.module_utils._text import to_native, to_text
from ansible.plugins.action import ActionBase
... |
"""Tests for the client."""
# Need to import client to add the flags.
from grr.client import actions
# Load all the standard actions.
# pylint: disable=unused-import
from grr.client import client_actions
# pylint: enable=unused-import
from grr.client import comms
from grr.lib import flags
from grr.lib import rdfvalu... |
import getpass
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
from django.db import DEFAULT_DB_ALIAS
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--database', action='stor... |
#coding=utf-8
#2017.9.22,Flash,list & dictionary 嵌套
alien_0={"color":"green","points":5}
alien_1={"color":"yellow","points":10}
alien_2={"color":"red","points":15}
aliens=[alien_0,alien_1,alien_2]
for alien in aliens:
print (alien)
pizza={
'crust':'think',
'toppings':['mushrooms','extra cheese'],
}
print("You ord... |
import frappe
import json, re
import bleach, bleach_whitelist.bleach_whitelist as bleach_whitelist
from six import string_types
from bs4 import BeautifulSoup
def clean_html(html):
if not isinstance(html, string_types):
return html
return bleach.clean(clean_script_and_style(html),
tags=['div', 'p', 'br', 'ul', '... |
from numpy import *
import matplotlib.pyplot as p
import os, sys, inspect
path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../tools'))
if not path in sys.path:
sys.path.insert(1, path)
del path
from generate_circle_data import circle_data
cir=circle_data()
number_of_points_for_circle1=42
number_of_p... |
"""UI related functions."""
import time
from . import adb
def clear_notifications():
"""Clear all pending notifications."""
adb.run_shell_command(['service', 'call', 'notification', '1'])
def unlock_screen():
"""Unlocks the screen if it is locked."""
window_dump_output = adb.run_shell_command(['dumpsys', ... |
#!/usr/bin/env python
"""usage: %prog [options] filename
Parse a document to a tree, with optional profiling
"""
import sys
import os
import traceback
from optparse import OptionParser
from html5lib import html5parser, sanitizer
from html5lib.tokenizer import HTMLTokenizer
from html5lib import treebuilders, serializ... |
from interfaces import IStartup
from hk2.injection import Container, NoScope
from plugin_loaders.sysmod_plugin_loader import SysmodPluginLoader
from hk2.annotations import Service
from hk2.types import Annotations
import logging
log = logging.getLogger('hk2')
#=======================================================... |
"""The Extended Availability Zone Status API extension."""
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api.openstack import xmlutil
from nova import availability_zones as avail_zone
authorize = extensions.soft_extension_authorizer('compute',
... |
import fcntl
import re
import os
import select
import sys
import subprocess
from color import Coloring
from command import Command, MirrorSafeCommand
_CAN_COLOR = [
'branch',
'diff',
'grep',
'log',
]
class ForallColoring(Coloring):
def __init__(self, config):
Coloring.__init__(self, config, 'forall')
... |
from django.conf import settings
from .. import Tags, Warning, register
W003 = Warning(
"You don't appear to be using Django's built-in "
"cross-site request forgery protection via the middleware "
"('django.middleware.csrf.CsrfViewMiddleware' is not in your "
"MIDDLEWARE_CLASSES). Enabling the middle... |
from . import flickr
try:
from unittest.mock import patch
except ImportError:
from mock import patch
import os
import pytest
import re
PLUGIN_DIR = os.path.dirname(__file__)
TEST_DATA_DIR = os.path.join(PLUGIN_DIR, 'test_data')
@pytest.mark.parametrize('input,expected', [
('18873146680 large "test 1"',
... |
import os
# import ntpath
import re
import urllib
try:
import urllib2
except:
import urllib.request as urllib2
import urlparse
from collections import defaultdict
from aqt.utils import showInfo, showText
from .base import QueryResult, WebService, export, register, with_styles
@register(u'MDX server')
class R... |
"""
Django admin page for embargo models
"""
from django.contrib import admin
import textwrap
from config_models.admin import ConfigurationModelAdmin
from embargo.models import IPFilter, CountryAccessRule, RestrictedCourse
from embargo.forms import IPFilterForm, RestrictedCourseForm
class IPFilterAdmin(Configuration... |
from . import audio
import pytest
import re
@pytest.mark.parametrize('input,expected', [
('http://foo.bar https://bar.foo',
('http://foo.bar', 'https://bar.foo', None)),
('http://test.foo',
('http://test.foo', None, None)),
('https://test.foo',
('https://test.foo', None, None)),
('http:... |
"""Handles test distribution and results upload to app engine."""
import base64
import json
import math
import random
import time
import urllib
import urllib2
import zlib
import blobstore_upload
import client_logging
# Define the constants
_BLOBSTORE_UPLOAD_RETRIES = 3
_PIECES_UPLOAD_RETRIES = 3
_MAX_WAIT_TIME = ... |
""" Framework for generic http servers
This library contains *no* OpenERP-specific functionality. It should be
usable in other projects, too.
"""
import logging
import SocketServer
from BaseHTTPServer import *
from SimpleHTTPServer import SimpleHTTPRequestHandler
_logger = logging.getLogger(__name__)
class ... |
__doc__ = """
pdict has a dictionary like interface and a sqlite backend
It uses pickle to store Python objects and strings, which are then compressed
Multithreading is supported
"""
import os
import sys
import datetime
import sqlite3
import zlib
import threading
import md5
import shutil
import glob
try:
import cP... |
from .resource import Resource
class ApplicationGatewayFirewallRuleSet(Resource):
"""A web application firewall rule set.
Variables are only populated by the server, and will be ignored when
sending a request.
All required parameters must be populated in order to send to Azure.
:param id: Resou... |
import random
from pyrge import *
MAX_X = 640
MAX_Y = 420
class Asteroid(Entity, mixin.Wrapper):
LARGE = 0
MEDIUM = 1
SMALL = 2
def __init__(self, position=Vector(0,0), velocity=Vector(0,0), size=0):
super(Asteroid, self).__init__()
self.sizetype = size
self.reset(position,ve... |
from __future__ import unicode_literals
from django.db import router
class Operation(object):
"""
Base class for migration operations.
It's responsible for both mutating the in-memory model state
(see db/migrations/state.py) to represent what it performs, as well
as actually performing it agains... |
import copy
import locale
import logging
import re
import reportlab
import openerp.tools as tools
from openerp.tools.safe_eval import safe_eval as eval
from openerp.tools.misc import ustr
_logger = logging.getLogger(__name__)
_regex = re.compile('\[\[(.+?)\]\]')
def str2xml(s):
return (s or '').replace('&', '&... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.compat.tests import unittest
from ansible.compat.tests.mock import patch, MagicMock
from ansible.errors import AnsibleError, AnsibleParserError
from ansible.playbook.block import Block
from ansible.playbook.play impor... |
from __future__ import division, absolute_import, print_function
import numpy as np
from numpy.testing import *
from numpy.testing.noseclasses import KnownFailureTest
import nose
def test_slow():
@dec.slow
def slow_func(x, y, z):
pass
assert_(slow_func.slow)
def test_setastest():
@dec.setast... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import fnmatch
import json
import os
import os.path
import re
import sys
from distutils.version import LooseVersion
import packaging.specifiers
from ansible.module_utils.urls import open_url
BUNDLED_RE = re.compile(b'\\b_BUNDL... |
from boto.regioninfo import RegionInfo, get_regions
def regions():
"""
Get all available regions for the AWS DirectConnect service.
:rtype: list
:return: A list of :class:`boto.regioninfo.RegionInfo`
"""
from boto.directconnect.layer1 import DirectConnectConnection
return get_regions('dir... |
#!/usr/bin/env python
#
# tournament.py -- implementation of a Swiss-system tournament
#
import psycopg2
#connects to db
def connect():
"""Connect to the PostgreSQL database. Returns a database connection."""
return psycopg2.connect("dbname=tournament")
#deltes match records from database
def deleteMatches(... |
"""Unit tests for the Quality-time missing metrics collector."""
from .base import QualityTimeTestCase
class QualityTimeMissingMetricsTest(QualityTimeTestCase):
"""Unit tests for the Quality-time missing metrics collector."""
METRIC_TYPE = "missing_metrics"
def setUp(self):
"""Set up test data.... |
"""
keyword_substitution.py
Contains utility functions to help substitute keywords in a text body with
the appropriate user / course data.
Supported:
LMS:
- %%USER_ID%% => anonymous user id
- %%USER_FULLNAME%% => User's full name
- %%COURSE_DISPLAY_NAME%% => display name of the course
... |
from Tools.CList import CList
# down up
# Render Converter Converter Source
# a bidirectional connection
def cached(f):
name = f.__name__
def wrapper(self):
cache = self.cache
if cache is None:
return f(self)
if name not in cache:
cache[name] = (True, f(self))
return cache[name]... |
'''
Find and delete AWS resources matching the provided --match string. Unless
--yes|-y is provided, the prompt for confirmation prior to deleting resources.
Please use caution, you can easily delete you're *ENTIRE* EC2 infrastructure.
'''
import boto
import boto.ec2.elb
import optparse
import os
import os.path
impor... |
# -*- coding: utf-8 -*-
"""
flask
~~~~~
A microframework based on Werkzeug. It's extensively documented
and follows best practice patterns.
:copyright: (c) 2015 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
__version__ = '0.12.2'
# utilities we import from Werkzeug and... |
import json
import sys
from csv import DictWriter
from datetime import datetime
from io import StringIO
from bs4 import BeautifulSoup
from lxml.etree import iterparse
XML_FILE_PATH = sys.argv[1]
CSV_FILE_PATH = sys.argv[2]
HTML_FILE_PATH = 'data/2016-08-08-datasets-format.html'
def output(*args, **kwargs):
"""H... |
from sympy import atan2, factor, Float, I, Matrix, N, oo, pi, sqrt, symbols
from sympy.physics.gaussopt import (BeamParameter, CurvedMirror,
CurvedRefraction, FlatMirror, FlatRefraction, FreeSpace, GeometricRay,
RayTransferMatrix, ThinLens, conjugate_gauss_beams,
gaussian_conj , geometric_conj_ab, geometric_conj... |
"""GTFS ServicePeriod entity."""
import datetime
import entity
import geom
import util
import validation
class ServicePeriod(entity.Entity):
KEY = 'service_id'
REQUIRED = [
'service_id',
'monday',
'tuesday',
'wednesday',
'thursday',
'friday',
'saturday',
'sunday',
'start_date',... |
from south.db import db
from django.db import models
from mysite.search.models import *
class Migration:
def forwards(self, orm):
# Adding field 'Project.cached_contributor_count'
db.add_column('search_project', 'cached_contributor_count', orm['search.project:cached_contributor_count'... |
"""Creates a grd file for packaging the trace-viewer files.
This file is modified from the devtools generate_devtools_grd.py file.
"""
import errno
import os
import shutil
import sys
from xml.dom import minidom
kTracingResourcePrefix = 'IDR_TRACING_'
kGrdTemplate = '''<?xml version="1.0" encoding="UTF-8"?>
<grit ... |
from boto.ec2.ec2object import EC2Object, TaggedEC2Object
from boto.ec2.blockdevicemapping import BlockDeviceMapping
class ProductCodes(list):
def startElement(self, name, attrs, connection):
pass
def endElement(self, name, value, connection):
if name == 'productCode':
self.append... |
"""
==================================================
Plot the decision boundaries of a VotingClassifier
==================================================
Plot the decision boundaries of a `VotingClassifier` for
two features of the Iris dataset.
Plot the class probabilities of the first sample in a toy dataset
pred... |
'''
This module contains interfaces that support CRUD operations on ACL.
'''
import json
from . import splunk_rest_client as rest_client
from .packages.splunklib import binding
from .utils import retry
__all__ = ['ACLException',
'ACLManager']
class ACLException(Exception):
pass
class ACLManager(ob... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: win_firewall_rule
version_added: "2.0"
author:
- Artem Zinenko (@ar7z1)
- Timothy Vandenbrande (@TimothyVandenbrande)
short_description: Windo... |
from . import constants
# 255: Control characters that usually does not exist in any text
# 254: Carriage/Return
# 253: symbol (punctuation) that does not belong to word
# 252: 0 - 9
# Character Mapping Table:
Latin7_CharToOrderMap = ( \
255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00
255,255,2... |
import socket
import struct
import logging
def inet_ntop(family, ipstr):
if family == socket.AF_INET:
return socket.inet_ntoa(ipstr)
elif family == socket.AF_INET6:
v6addr = ':'.join(('%02X%02X' % (ord(i), ord(j)))
for i, j in zip(ipstr[::2], ipstr[1::2]))
ret... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import traceback
try:
import pyodbc
except ImportError:
pyodbc_found = False
else:... |
try:
import asyncio
except ImportError:
## Trollius >= 0.3 was renamed
import trollius as asyncio
from autobahn.asyncio.wamp import ApplicationSession
class Component(ApplicationSession):
"""
An application component that publishes an event every second.
"""
@asyncio.coroutine
def onJoin(se... |
"""A Transform that parses serialized tensorflow.Example protos."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
from tensorflow.contrib.learn.python.learn.dataframe import transform
from tensorflow.python.ops import parsing_ops
cla... |
"""Basic playback test. Checks playback, seek, and replay based on events.
This test uses the bear videos from the test matrix in h264, vp8, and theora
formats.
"""
import logging
import os
import pyauto_media
import pyauto
# HTML test path; relative to src/chrome/test/data.
_TEST_HTML_PATH = os.path.join('media',... |
#!/usr/bin/python -u
#
# this tests the DTD validation with the XmlTextReader interface
#
import sys
import glob
import string
import StringIO
import libxml2
# Memory debug specific
libxml2.debugMemory(1)
err=""
expect="""../../test/valid/rss.xml:177: element rss: validity error : Element rss does not carry attribute... |
"""
Support for Canary camera.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/camera.canary/
"""
import asyncio
import logging
from datetime import timedelta
import voluptuous as vol
from homeassistant.components.camera import Camera, PLATFORM_SCHEMA
f... |
#!/usr/bin/env python3
""" turtle-example-suite:
tdemo_peace.py
A simple drawing suitable as a beginner's
programming example. Aside from the
peacecolors assignment and the for loop,
it only uses turtle commands.
"""
from turtle import *
def main():
peacecolors = ("red3", "orange", "yellow"... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
class RabbitMqVhost(object):
def __init__(self, module, name, tracing, node):
self.module = module
self.name = name
self.tracing = tracing
self... |
import os
import re
import subprocess
from .. import vcs
from ..vcs import bind_to_repo, git, hg
def get_unique_name(existing, initial):
"""Get a name either equal to initial or of the form initial_N, for some
integer N, that is not in the set existing.
:param existing: Set of names that must not be ch... |
"""
Visualization for recurrent neural networks
"""
import numpy as np
from neon.util.compat import range
class VisualizeRNN(object):
"""
Visualzing weight matrices during training
"""
def __init__(self):
import matplotlib.pyplot
self.plt = matplotlib.pyplot
self.plt.interacti... |
from __future__ import unicode_literals
from django.contrib.auth.views import logout
from django.core.urlresolvers import NoReverseMatch, reverse_lazy
from django.shortcuts import resolve_url
from django.test import SimpleTestCase, ignore_warnings, override_settings
from django.utils import six
from django.utils.depre... |
#!/usr/bin/python
try:
from PyQt4 import QtCore, QtGui
QtCore.Signal = QtCore.pyqtSignal
QtCore.Slot = QtCore.pyqtSlot
except ImportError:
try:
from PySide import QtCore, QtGui
QtCore.QString = str
except ImportError:
raise ImportError("Cannot load either PyQt or PySide")
... |
import data_utils
import pandas as pd
import numpy as np
import tensorflow as tf
import math, random, itertools
import pickle
import time
import json
import os
import math
import data_utils
import pickle
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, precision_score, rec... |
"""
Python-Markdown Extra Extension
===============================
A compilation of various Python-Markdown extensions that imitates
[PHP Markdown Extra](http://michelf.com/projects/php-markdown/extra/).
Note that each of the individual extensions still need to be available
on your PYTHONPATH. This extension simply ... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'CarouselItem.button_title'
db.add_column(u'cmsplugin_boot... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import re
try:
from library.module_utils.network.f5.common import F5ModuleError
except ImportError:
from ansible.module_utils.network.f5.common import F5ModuleError
_CLEAN_HEADER_REGEX_BYTE = re.compile(b'^\\S[^\\r\\n]*$|^... |
from .mbcharsetprober import MultiByteCharSetProber
from .codingstatemachine import CodingStateMachine
from .chardistribution import EUCKRDistributionAnalysis
from .mbcssm import CP949SMModel
class CP949Prober(MultiByteCharSetProber):
def __init__(self):
MultiByteCharSetProber.__init__(self)
self.... |
# -*- coding: utf-8 -*-
"""
Lift ckernels to their appropriate rank so they always consume the full array
arguments.
"""
from __future__ import absolute_import, division, print_function
from pykit.ir import transform, Op
#------------------------------------------------------------------------
# Run
#--------------... |
import glob
import os
import mock
from nova import exception
from nova.pci import utils
from nova import test
class PciDeviceMatchTestCase(test.NoDBTestCase):
def setUp(self):
super(PciDeviceMatchTestCase, self).setUp()
self.fake_pci_1 = {'vendor_id': 'v1',
'device_id'... |
from openerp.osv import fields, osv
SPLIT_METHOD = [
('equal', 'Equal'),
('by_quantity', 'By Quantity'),
('by_current_cost_price', 'By Current Cost Price'),
('by_weight', 'By Weight'),
('by_volume', 'By Volume'),
]
class product_template(osv.osv):
_inherit = "product.template"
_columns = ... |
from __future__ import absolute_import
import os
import sys
import logging
from six.moves import map
log = logging.getLogger("main")
from ..master_task import AlgCleanerTask
from ..master_job import Job
from ..utils import SeqGroup, GLOBALS, hascontent, DATATYPES, pjoin
from .. import db
__all__ = ["Trimal"]
class ... |
fname=r'h:\tmp.txt'
import win32security,win32file,win32api,ntsecuritycon,win32con
new_privs = ((win32security.LookupPrivilegeValue('',ntsecuritycon.SE_SECURITY_NAME),win32con.SE_PRIVILEGE_ENABLED),
(win32security.LookupPrivilegeValue('',ntsecuritycon.SE_SHUTDOWN_NAME),win32con.SE_PRIVILEGE_ENABLED),
... |
"""Top-level presubmit script for Chromium media component.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into depot_tools.
"""
def _FilterFile(affected_file):
"""Return true if the file could contain code requiring a presubmit check."""
... |
#!/usr/bin/env python
import re, sys, operator, Queue, threading
# Two data spaces
word_space = Queue.Queue()
freq_space = Queue.Queue()
stopwords = set(open('../stop_words.txt').read().split(','))
# Worker function that consumes words from the word space
# and sends partial results to the frequency space
def proces... |
from __future__ import absolute_import
from . import backend as K
class Regularizer(object):
def set_param(self, p):
self.p = p
def set_layer(self, layer):
self.layer = layer
def __call__(self, loss):
return loss
def get_config(self):
return {'name': self.__class__._... |
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.contrib.auth.views import (
password_change, password_change_done, password_reset,
password_reset_complete, password_reset_confirm, password_res... |
"""
Blind Source Separation using the Jade Algorithm with Shogun
Based on the example from scikit-learn
http://scikit-learn.org/
Kevin Hughes 2013
"""
import numpy as np
import pylab as pl
from modshogun import RealFeatures
from modshogun import Jade
# Generate sample data
np.random.seed(0)
n_samples = 2000
time... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from datetime import datetime
from collections import defaultdict
import json
import time
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
from ansible.plugins.callback impor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.