content stringlengths 4 20k |
|---|
"""Transforms Sparse to Dense Tensor."""
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.python.ops import sparse_ops
class Densify(transform.TensorFlowTransform):
"""... |
from . import InstanceResource, ListResource
from .util import normalize_dates, parse_date
class Media(InstanceResource):
""" Represents media associated with a :class:`Message`.
.. attribute:: sid
A 34 character string that uniquely identifies this resource.
.. attribute:: account_sid
... |
class OperandType:
""" Types of possible operands in an opcode.
Refer to the diStorm's documentation or diStorm's instructions.h
for more explanation about every one of them. """
(NONE,
IMM8,
IMM16,
IMM_FULL,
IMM32,
SEIMM8,
IMM16_1, # NEW
IMM8_1, # NEW
IMM8_2, # NEW
REG8,
REG16,
REG_FULL,
... |
"""Unittests for the subcmds module (mostly __init__.py than subcommands)."""
import unittest
import subcmds
class AllCommands(unittest.TestCase):
"""Check registered all_commands."""
def test_required_basic(self):
"""Basic checking of registered commands."""
# NB: We don't test all subcommands as we w... |
import unittest
from collections import OrderedDict
from mock import patch
from airflow import AirflowException
from airflow.operators.hive_stats_operator import HiveStatsCollectionOperator
class _FakeCol:
def __init__(self, col_name, col_type):
self.name = col_name
self.type = col_type
fake_c... |
"""Library replacing targets formmated ${like_this} with specified variables.
"""
__author__ = "komatsu"
import re
def ReplaceVariables(data, environment):
"""Replace all occurrence of the variable in data by the value.
Args:
data: the original data string
environment: a dict which maps from variable na... |
from setuptools import setup, find_packages
setup(
name='cmsplugin-feedparser',
version=__import__('cmsplugin_feedparser').__version__,
description=__import__('cmsplugin_feedparser').__doc__,
long_description=open('README.rst').read(),
author='David Thenon',
author_email='<EMAIL>',
url='htt... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
try:
from ansible.module_utils.network.avi.avi import (
avi_common_argument_spec, HAS_AVI, avi_ansible_api)
except ... |
import logging
from urllib import urlencode
from urllib2 import urlopen
import simplejson
import xml
from xml.parsers.expat import ExpatError
from geopy.geocoders.base import Geocoder
from geopy import Point, Location, util
class Google(Geocoder):
"""Geocoder using the Google Maps API."""
def __init__(... |
from trytond.backend.table import TableHandlerInterface
import logging
class TableHandler(TableHandlerInterface):
def __init__(self, cursor, model, module_name=None, history=False):
super(TableHandler, self).__init__(cursor, model,
module_name=module_name, history=history)
self._c... |
"""Jobs for recommendations."""
import ast
from core import jobs
from core.domain import exp_services
from core.domain import recommendations_services
from core.domain import rights_manager
from core.platform import models
(exp_models, recommendations_models,) = models.Registry.import_models([
models.NAMES.explor... |
from __future__ import unicode_literals
import json
import re
from .common import InfoExtractor
from ..utils import int_or_none
class PodomaticIE(InfoExtractor):
IE_NAME = 'podomatic'
_VALID_URL = r'^(?P<proto>https?)://(?P<channel>[^.]+)\.podomatic\.com/entry/(?P<id>[^?]+)'
_TESTS = [
{
... |
#!/usr/bin/env python
# PYTHON_ARGCOMPLETE_OK
"""A tool to aggregate data about Ansible source and testing into a sqlite DB for reporting."""
from __future__ import (absolute_import, print_function)
import argparse
import os
import requests
import sqlite3
import sys
DATABASE_PATH = os.path.expanduser('~/.ansible/rep... |
import os
from tests.unit import unittest
import boto
from boto.regioninfo import RegionInfo, load_endpoint_json, merge_endpoints
from boto.regioninfo import load_regions, get_regions
class TestRegionInfo(object):
def __init__(self, connection=None, name=None, endpoint=None,
connection_cls=None)... |
def main(request, response):
import simplejson as json
f = file('config.json')
source = f.read()
s = json.JSONDecoder().decode(source)
url1 = "http://" + s['host'] + ":" + str(s['ports']['http'][1])
url2 = "http://" + s['host'] + ":" + str(s['ports']['http'][0])
response.headers.set("Content... |
# apis_v1/documentation_source/position_list_for_opinion_maker_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def position_list_for_opinion_maker_doc_template_values(url_root):
"""
Show documentation about positionListForOpinionMaker
"""
required_query_parameter_list = [
... |
# -*- coding: utf-8 -*-
## @package inversetoon.geometry.ellipsoids
#
# Implementation of 2D ellipsoids.
# @author tody
# @date 2015/08/13
import math
import numpy as np
from numpy.linalg import eig, inv
## Ellipsoids
class Ellipsoids:
## Constructor
def __init__(self, points = []):
se... |
from gnuradio import gr, gr_unittest
class test_float_to_char (gr_unittest.TestCase):
def setUp (self):
self.tb = gr.top_block ()
def tearDown (self):
self.tb = None
def test_001(self):
src_data = (0.0, 1.1, 2.2, 3.3, 4.4, 5.5, -1.1, -2.2, -3.3)
expected_result = [0, 1, 2... |
"""
Kafka-Specific Utilities on networking
(This file contains the kafka-specific additions on the `sdk_networks` file)
"""
import sdk_agents
def check_endpoints_on_overlay(endpoints):
def check_ip_addresses_on_overlay():
# the overlay IP address should not contain any agent IPs
return len(set(ip... |
import logging
from django.contrib.sessions.backends.base import SessionBase, CreateError
from django.core.exceptions import SuspiciousOperation
from django.db import IntegrityError, transaction, router
from django.utils import timezone
from django.utils.encoding import force_text
class SessionStore(SessionBase):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Mirad'
SITENAME = u'بلاگ میراد(هوشمند بخوانید!)'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'Asia/Tehran'
DEFAULT_LANG = u'fa'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_... |
from json.tests import PyTest, CTest
class JSONTestObject:
pass
class TestRecursion(object):
def test_listrecursion(self):
x = []
x.append(x)
try:
self.dumps(x)
except ValueError:
pass
else:
self.fail("didn't raise ValueError on lis... |
"""distutils.command.install_data
Implements the Distutils 'install_data' command, for installing
platform-independent data files."""
# contributed by Bastian Kleineidam
__revision__ = "$Id$"
import os
from distutils.core import Command
from distutils.util import change_root, convert_path
class install_data(Comman... |
from django.template.defaultfilters import linebreaksbr
from django.test import SimpleTestCase
from django.utils.safestring import mark_safe
from ..utils import setup
class LinebreaksbrTests(SimpleTestCase):
"""
The contents in "linebreaksbr" are escaped according to the current
autoescape setting.
"... |
from .property import Property
class GraphElement(object):
def __init__(self, **kwargs):
self._graph = None
self._id = None
self._props = kwargs
@classmethod
def from_graph(cls, graph, element_id, props):
elem = cls(**props)
elem._graph = graph
elem._id = ... |
from __future__ import (absolute_import, division, print_function)
import unittest
from mantid.simpleapi import LoadNexusProcessed, IndirectCylinderAbsorption, DeleteWorkspace
from mantid.api import *
class IndirectCylinderAbsorption2Test(unittest.TestCase):
def setUp(self):
"""
Loads the reduced... |
"""
This module implements a transaction manager that can be used to define
transaction handling in a request or view function. It is used by transaction
control middleware and decorators.
The transaction manager can be in managed or in auto state. Auto state means the
system is using a commit-on-save strategy (actual... |
import os
from enigma import eConsoleAppContainer
from Components.Harddisk import harddiskmanager
opkgDestinations = []
opkgStatusPath = ''
def opkgExtraDestinations():
global opkgDestinations
return ''.join([" --add-dest %s:%s" % (i,i) for i in opkgDestinations])
def opkgAddDestination(mountpoint):
global opkgDe... |
"""Tests for Constrained Network Server."""
import os
import signal
import subprocess
import tempfile
import time
import unittest
import urllib2
import cherrypy
import cns
import traffic_control
# The local interface to test on.
_INTERFACE = 'lo'
class PortAllocatorTest(unittest.TestCase):
"""Unit tests for the Po... |
# -*- 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):
# Deleting field 'Page.publisher_state'
db.delete_column(u'cms_page', 'pu... |
{
"name": "This module inherits standard price field in mrp.bom",
"version": "3.3.2.8",
"author": "Vauxoo, Didotech",
"category": "Generic Modules",
"description": """This module inherits standard price field in mrp.bom and also sequence
""",
"website": "http://www.didotech.com",
"lic... |
from django import forms
DEFAULT_DATE_INPUT_FORMATS = (
'%Y-%m-%d', '%d/%m/%Y', '%d/%m/%y', # '2006-10-25', '25/10/2006', '25/10/06'
'%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006'
'%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006'
'%B %d %Y', '%B %d, %Y', ... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
RETURNS = '''
id:
description: Cinder's unique ID for this volume
returned: always
ty... |
# coding:utf-8
from view import route, url_for, View
from model.user import User
from tornado.web import authenticated
@route('/signin', name='signin')
class SignIn(View):
def get(self):
self.render('user/signin.html')
def post(self):
username = self.get_argument("username")
password ... |
''' Search Imgur for a random image '''
import ConfigParser
import datetime
import json
import logging
import random
import os
import requests
from hogar.Utils.StringUtils import ignore_case_replace
from hogar.static import values as static_values
logger = logging.getLogger(__name__)
api_base = 'https://api.imgur.c... |
from __future__ import with_statement
import sys
import types
import inspect
import time
import newrelic.core.memcache_node
import newrelic.api.transaction
import newrelic.api.time_trace
import newrelic.api.object_wrapper
class MemcacheTrace(newrelic.api.time_trace.TimeTrace):
node = newrelic.core.memcache_nod... |
import psycopg2.extensions
from django.db.backends.creation import BaseDatabaseCreation
from django.db.backends.util import truncate_name
class DatabaseCreation(BaseDatabaseCreation):
# This dictionary maps Field objects to their associated PostgreSQL column
# types, as strings. Column-type strings can conta... |
import arrow
import discord
from sigma.core.utilities.data_processing import user_avatar
from sigma.core.utilities.permission_processing import hierarchy_permit
from sigma.core.utilities.server_bound_logging import log_event
def generate_log_embed(message, target, reason):
log_response = discord.Embed(color=0xc... |
from django.http import HttpResponseNotFound, HttpResponseServerError, JsonResponse
from django.template import Context, Engine, loader, TemplateDoesNotExist
from django.utils.translation import gettext as _
from django.views.decorators.csrf import requires_csrf_token
def sentry_id_from_request(request):
if getat... |
import EpsImagePlugin
import string
##
# Simple Postscript graphics interface.
class PSDraw:
def __init__(self, fp=None):
if not fp:
import sys
fp = sys.stdout
self.fp = fp
def begin_document(self, id = None):
"Write Postscript DSC header"
# FIXME: inc... |
"""
Common code for all metrics
"""
# Authors: Alexandre Gramfort <<EMAIL>>
# Mathieu Blondel <<EMAIL>>
# Olivier Grisel <<EMAIL>>
# Arnaud Joly <<EMAIL>>
# Jochen Wersdorfer <<EMAIL>>
# Lars Buitinck <<EMAIL>>
# Joel Nothman <<EMAIL>>
# Noel Dawe <<EMAIL>... |
doctests = """
Test simple loop with conditional
>>> sum(i*i for i in range(100) if i&1 == 1)
166650
Test simple nesting
>>> list((i,j) for i in range(3) for j in range(4) )
[(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)]
Test nesting with the inner ... |
"""Contains the logic for `aq manage --list`."""
from types import ListType
from collections import defaultdict
from aquilon.exceptions_ import ArgumentError
from aquilon.worker.broker import BrokerCommand # pylint: disable=W0611
from aquilon.worker.commands.manage_hostname import validate_branch_commits
from aquilon... |
from feat import hacks
json = hacks.import_json()
from feat.common import reflect
from feat.interface.serialization import Capabilities, IVersionAdapter
from feat.common.serialization import base
TUPLE_ATOM = u".tuple"
BYTES_ATOM = u".bytes"
BYTES_ENCODING = "BASE64"
ENCODED_ATOM = u".enc"
SET_ATOM = u".set"
ENUM_... |
OLD_MPL = """\
This Source Code Form is subject to the terms of the Mozilla Public \
License, v. 2.0. If a copy of the MPL was not distributed with this \
file, You can obtain one at http://mozilla.org/MPL/2.0/.\
"""
MPL = """\
This Source Code Form is subject to the terms of the Mozilla Public \
License, v. 2.0. If a... |
from __future__ import unicode_literals
import frappe, random
from frappe.utils.make_random import add_random_children, get_random
from erpnext.setup.utils import get_exchange_rate
from erpnext.accounts.party import get_party_account_currency
def work():
frappe.set_user(frappe.db.get_global('demo_sales_user_2'))
if... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from nose.plugins.skip import SkipTest
try:
from ansible.modules.network.fortimanager import fmgr_provisioning
from .fortimanager_module import TestFortimanagerModule
from units.modules.utils import set_module_args
exc... |
import unittest
from eventlet.event import Event
from eventlet.api import spawn, sleep, with_timeout
import eventlet
from tests import LimitedTestCase
DELAY= 0.01
class TestEvent(LimitedTestCase):
def test_send_exc(self):
log = []
e = Event()
def waiter():
try:
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
=========================================================
Logistic Regression 3-class Classifier
=========================================================
Show below is a logistic-regression classifiers decision boundaries on the
`iris <https://en.wikipedia.org/wiki/Iris_... |
"""Common utilities used in testing"""
import os
import shutil
import subprocess
import sys
import fixtures
import testresources
import testtools
from testtools import content
from pbr import options
class DiveDir(fixtures.Fixture):
"""Dive into given directory and return back on cleanup.
:ivar path: The ... |
#!/usr/bin/env python
#
# Computes t-tests for time from action log events.
# Reads the output of actionlog_to_csv.py
#
import sys
from collections import Counter,namedtuple
from csv_unicode import UnicodeReader
from argparse import ArgumentParser
# Format of the CSV log files
import ptm_file_io
from ptm_stats import... |
#=======================================================================
# ConnectionEdge.py
#=======================================================================
'Classes used to describe the structural connection graph of a Model.'
from ..datatypes.helpers import get_nbits
from signals import InPort, ... |
"""Provides stubs for os, sys and subprocess for testing
This test allows one to test code that itself uses os, sys, and subprocess.
"""
import os
import re
import shlex
import sys
class Override(object):
def __init__(self, base_module, module_list):
stubs = {'adb_commands': AdbCommandsModuleStub,
... |
__all__ = ['SCHEDULER_ENABLED_LOG_LINE', 'SCHEDULER_DISABLED_LOG_LINE']
# Integration tests look for these loglines to validate scheduler enable/disable
SCHEDULER_ENABLED_LOG_LINE = 'Scheduler is enabled.'
SCHEDULER_DISABLED_LOG_LINE = 'Scheduler is disabled.' |
import compiler
from compiler.ast import flatten
import os, sys, time, unittest
import test.test_support
from random import random
# How much time in seconds can pass before we print a 'Still working' message.
_PRINT_WORKING_MSG_INTERVAL = 5 * 60
class TrivialContext(object):
def __enter__(self):
return s... |
"""Code coverage measurement for Python.
Ned Batchelder
http://nedbatchelder.com/code/coverage
"""
from coverage.version import __version__, __url__, version_info
from coverage.control import Coverage, process_startup
from coverage.data import CoverageData
from coverage.misc import CoverageException
from coverage.p... |
doctests = """
########### Tests mostly copied from test_listcomps.py ############
Test simple loop with conditional
>>> sum({i*i for i in range(100) if i&1 == 1})
166650
Test simple case
>>> {2*y + x + 1 for x in (0,) for y in (1,)}
{3}
Test simple nesting
>>> list(sorted({(i,j) for i in rang... |
from instal.firstprinciples.TestEngine import InstalSingleShotTestRunner, InstalTestCase
class ObligationViolate(InstalTestCase):
def test_violate_obligations_defined(self):
runner = InstalSingleShotTestRunner(input_files=["obligation/obligation.ial"], bridge_file=None,
... |
#!/usr/bin/env python
import os, sys
sys.path.insert ( 0, os.path.dirname(os.path.abspath(__file__) ) + "/../" )
import gepard
import json
import threading
import time
import types
import time
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
from glob import glob
a = gepard.JSAcc(... |
import hashlib
import string
import random
from google.appengine.ext import db
class Article(db.Model):
path = db.StringProperty(required = True)
content = db.TextProperty(default = '')
created = db.DateTimeProperty(auto_now_add = True)
def make_salt(length = 5):
return ''.join(random.choice(string.l... |
import os
import re
import sys
from coalib.misc import Constants
from coalib.output.ConfWriter import ConfWriter
from coalib.output.printers.LOG_LEVEL import LOG_LEVEL
from coalib.parsing.CliParsing import parse_cli
from coalib.parsing.ConfParser import ConfParser
from coalib.settings.Section import Section
from coali... |
# -*- coding: utf-8 -*-
"""A quick look at volatility of stock returns for 2009
Just an exercise to find my way around the pandas methods.
Shows the daily rate of return, the square of it (volatility) and
a 5 day moving average of the volatility.
No guarantee for correctness.
Assumes no missing values.
colors of lines... |
from django.conf import settings
from django.core.urlresolvers import reverse
from rest_core.rest_core.test import ManticomTestCase
from rest_user.rest_user.test.factories import UserFactory
__author__ = 'baylee'
class NotificationSettingsTestCase(ManticomTestCase):
def test_can_only_see_own_notification_setting... |
from django.contrib import admin
from oscar.core.loading import get_model
ConditionalOffer = get_model('offer', 'ConditionalOffer')
Condition = get_model('offer', 'Condition')
Benefit = get_model('offer', 'Benefit')
Range = get_model('offer', 'Range')
class ConditionAdmin(admin.ModelAdmin):
list_display = ('type... |
from operator import attrgetter
from django.conf import settings
from django.core.exceptions import FieldError
from django.db import connection
from django.test import TestCase
from models import (Chef, CommonInfo, ItalianRestaurant, ParkingLot, Place,
Post, Restaurant, Student, StudentWorker, Supplier, Worker, M... |
import re
xpath_tokenizer_re = re.compile(
"("
"'[^']*'|\"[^\"]*\"|"
"::|"
"//?|"
"\.\.|"
"\(\)|"
"[/.*:\[\]\(\)@=])|"
"((?:\{[^}]+\})?[^/\[\]\(\)@=\s]+)|"
"\s+"
)
def xpath_tokenizer(pattern, namespaces=None):
for token in xpath_tokenizer_re.findall(pattern):
tag =... |
from __future__ import print_function
import unittest
import numpy as np
import paddle.fluid.core as core
from op_test import OpTest
import paddle.fluid as fluid
from paddle.fluid import Program, program_guard
class TestSimilarityFocusOp(OpTest):
def setUp(self):
self.op_type = "similarity_focus"
... |
# -*- coding: utf-8 -*-
"""
pygments.formatters._mapping
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Formatter mapping definitions. This file is generated by itself. Everytime
you change something on a builtin formatter definition, run this script from
the formatters folder to update it.
Do not alter the FOR... |
# vim: set fileencoding=utf-8 :
from __future__ import absolute_import, division
import json
import unittest
from flask import Flask, url_for
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.alchemyview import AlchemyView
from dictalchemy import make_class_dictable
import colander as c
SQLALCHEMY_DATABASE... |
"""Test that a global ObjC object found before the process is started updates correctly."""
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TestObjCGlobalVar(TestBase):
mydir = TestBase.compute_mydir(__file__)
def setUp(s... |
# -*- coding:utf-8 -*-
import json
import urllib2
API_URL = 'https://api.direct.yandex.ru/live/v4/json/'
class DirectApi(object):
def __init__(self, login=None, token=None):
"""
:param login: Yandex Direct Login
:param token: Oauth-token
"""
self.login = login
sel... |
import math
import numpy
from chainer import cuda
from chainer import function
from chainer.utils import type_check
def _as_mat(x):
return x.reshape(x.shape[0], x.size // x.shape[0])
class Linear(function.Function):
"""Linear function (a.k.a. fully-connected layer or affine transformation).
This fun... |
import codecs
import sys
from datetime import datetime
from PythonConfluenceAPI import ConfluenceAPI
import Configuration
import CustomModules.SQL_Connector
from Configuration import MySQLConfig, ConfluenceConfig, MediaWIKIConfig
from Migration_to_xWiki.Users_association import Users
from CustomModules import Mechani... |
"""Implementing caching mechanisms for MySQL Fabric"""
from datetime import datetime, timedelta
from hashlib import sha1
import logging
import threading
from . import FabricShard
_LOGGER = logging.getLogger('myconnpy-fabric')
_CACHE_TTL = 1 * 60 # 1 minute
class CacheEntry(object):
"""Base class for MySQL F... |
# -*- test-case-name: buildbot.test.test_buildreq -*-
from twisted.trial import unittest
from buildbot import buildset, interfaces, sourcestamp
from buildbot.process import base
from buildbot.status import builder
from buildbot.changes.changes import Change
class Request(unittest.TestCase):
def testMerge(self):
... |
"""The Garmin Connect integration."""
import asyncio
from datetime import date, timedelta
import logging
from garminconnect import (
Garmin,
GarminConnectAuthenticationError,
GarminConnectConnectionError,
GarminConnectTooManyRequestsError,
)
from homeassistant.config_entries import ConfigEntry
from ho... |
"""runpy.py - locating and running Python code using the module namespace
Provides support for locating and running Python scripts using the Python
module namespace instead of the native filesystem.
This allows Python code to play nicely with non-filesystem based PEP 302
importers when locating support scripts as wel... |
"""
This module houses the ctypes initialization procedures, as well
as the notice and error handler function callbacks (get called
when an error occurs in GEOS).
This module also houses GEOS Pointer utilities, including
get_pointer_arr(), and GEOM_PTR.
"""
import logging
import os
import re
from ctypes import CD... |
from openerp.tests.common import TransactionCase
class TestProductIdChange(TransactionCase):
"""Test that when an included tax is mapped by a fiscal position, the included tax must be
subtracted to the price of the product.
"""
def setUp(self):
super(TestProductIdChange, self).setUp()
... |
# Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.parties.DistributedPartyTeamActivity
from direct.distributed.ClockDelta import globalClockDelta
from toontown.toonbase import TTLocalizer
from toontown.parties import PartyGlobals
from toontown.parties.DistributedPartyActivity import DistributedPar... |
"""
mbed SDK
Copyright (c) 2011-2014 ARM Limited
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wr... |
import copy
from pandocfilters import toJSONFilters, Para, Str, Header, Space, Link
def remove_includes(key, value, format, meta):
if key == 'Para' and value[0]['c'] == '[!INCLUDE':
return Para([Str("")])
return None
def promote_and_capitalize_sections(key, value, format, meta):
if key == 'Header'... |
from . import dataformat
from . import util
from .util import dbg
class SoundList(dataformat.Exportable):
name_struct = "sound_file"
name_struct_file = "sound_file"
struct_description = "one available sound file."
data_format = (
(True, "category", dataformat.EnumMember(
t... |
from keystone import config
from keystone import tests
from keystone.tests import test_sql_migrate_extensions
from keystone.tests import test_sql_upgrade
CONF = config.CONF
class PostgresqlMigrateTests(test_sql_upgrade.SqlUpgradeTests):
def setUp(self):
self.skip_if_env_not_set('ENABLE_LIVE_POSTGRES_TES... |
"""Helper functions for working with signals"""
import logging
from twisted.internet.defer import maybeDeferred, DeferredList, Deferred
from twisted.python.failure import Failure
from pydispatch.dispatcher import Any, Anonymous, liveReceivers, \
getAllReceivers, disconnect
from pydispatch.robustapply import robu... |
import re
import pytz
import datetime
from billy.scrape.events import EventScraper, Event
from openstates.utils import LXMLMixin
class WYEventScraper(EventScraper, LXMLMixin):
jurisdiction = 'wy'
_tz = pytz.timezone('US/Mountain')
def normalize_time(self, time_string):
time_string = time_string.... |
"""Compressed Block Sparse Row matrix format"""
__docformat__ = "restructuredtext en"
__all__ = ['bsr_matrix', 'isspmatrix_bsr']
from warnings import warn
import numpy as np
from data import _data_matrix
from compressed import _cs_matrix
from base import isspmatrix, _formats
from sputils import isshape, getdtype, ... |
from six import PY3
from six.moves import _thread
from datetime import datetime, timedelta, tzinfo
import copy
ZERO = timedelta(0)
__all__ = ['tzname_in_python2', 'enfold']
def tzname_in_python2(namefunc):
"""Change unicode output into bytestrings in Python 2
tzname() API changed in Python 3. It used to r... |
"""This module implements enough functionality to program the STM32F4xx over
DFU, without requiringdfu-util.
See app note AN3156 for a description of the DFU protocol.
See document UM0391 for a dscription of the DFuse file.
"""
from __future__ import print_function
import argparse
import re
import struct
import sys
... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'community'}
# ===========================================
# HipChat module specific support met... |
import os
import unittest
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '../lib'))
from systestlib import DutSystemTest, random_interface
class TestApiStpInterfaces(DutSystemTest):
def test_get(self):
for dut in self.duts:
dut.config(['default interface Ethernet1'])
... |
from xmodule.modulestore.django import modulestore
from xmodule.course_module import CourseDescriptor
from django.conf import settings
from microsite_configuration import microsite
def get_visible_courses():
"""
Return the set of CourseDescriptors that should be visible in this branded instance
"""
_... |
"""
Modified from torchvision
"""
import torch.nn as nn
import math
import torch.nn.functional as F
from torchvision.models.resnet import (
BasicBlock, resnet18, resnet34, resnet50, resnet101, resnet152,
)
__all__ = ['ResNet', 'resnet9', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152']
... |
"""
This script concurrently builds and migrates instances. This can be useful when
troubleshooting race-conditions in virt-layer code.
Expects:
novarc to be sourced in the environment
Helper Script for Xen Dom0:
# cat /tmp/destroy_cache_vdis
#!/bin/bash
xe vdi-list | grep "Glance Image" -C1 | grep ... |
"""
Check that types only get completed when necessary.
"""
import os, time
import unittest2
import lldb
from lldbtest import *
import lldbutil
class TypeCompletionTestCase(TestBase):
mydir = os.path.join("functionalities", "type_completion")
@unittest2.skipUnless(sys.platform.startswith("darwin"), "require... |
import json
import logging
import os.path
import sys
from cookiecutter.main import cookiecutter
def main():
context_json_path = sys.argv[1]
template_path = sys.argv[2]
output_path = sys.argv[3]
user_config_path = sys.argv[4]
user_config_path = user_config_path if os.path.isfile(user_config_path) e... |
MAX_IP_TRIES = 5
ZK_TIMEOUT = 60
TIME_DELAY_MIN = 30
TIME_DELAY_MAX = 60
DEFAULT_SLEEP = 600
DEFAULT_MAX_CHANGE_THRESHOLD = 20
METADATA_URL = "http://169.254.169.254/latest/meta-data/"
INSTANCE_ID_PATH = "instance-id"
PUBLIC_ADDRESS_PATH = "public-ipv4"
PRIVATE_ADDRESS_PATH = "local-ipv4"
MAC_PATH = "mac"
VPCID_PATH = ... |
"""
Common utilities for testing Soledad.
"""
import os
import tempfile
from twisted.internet import defer
from twisted.trial import unittest
from leap.common.testing.basetest import BaseLeapTest
from leap.soledad.client import Soledad
# TODO move to common module, or Soledad itself
# XXX remove duplication
TEST_US... |
from django.conf.urls import patterns, url
from charts import views
urlpatterns = patterns('',
# index page, to show the options
url(r'^$', views.index, name='index'),
url(r'^print_logs/$', views.printLogs),
url(r'^print_end_logs/$', views.printEndLogs),
# consumes log and cre... |
from raptiformica.actions.mesh import restart_consul_agent_if_necessary, ConsulSharedSecretChanged
from tests.testcase import TestCase
class TestRestartConsulAgentIfNecessary(TestCase):
def setUp(self):
self.raise_if_shared_secret_changed = self.set_up_patch(
'raptiformica.actions.mesh.raise_i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.