content stringlengths 4 20k |
|---|
__author__ = u'schmatz'
import configuration
import os
import sys
import errors
import shutil
class DirectoryController(object):
def __init__(self,config):
assert isinstance(config,configuration.Configuration)
self.config = config
self.root_dir = self.config.system.get_current_working_direct... |
import report_intrastat
import report
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
#!/usr/bin/python
print "Program attempts to log into an XAPI server to fetch a list of VMs and"
print "a list of debug objects. It then chooses the first debug object, "
print "queries the int->float map and then calls the 'recycle' message using"
print "that map as an argument"
print
import getopt, sys, xapi
url =... |
from __future__ import annotations
import logging
import shutil
from abc import ABCMeta, abstractmethod
from pathlib import Path, PurePath, PurePosixPath
from typing import TYPE_CHECKING, Any, Dict, Iterator, Optional
from urllib.parse import urljoin
import jinja2
from lander.ext.theme._jinjaloader import ThemeTempl... |
# -*- coding: utf-8 -*-
r""" This package implements the louvain algorithm in ``C++`` and exposes it to
python. It relies on ``(python-)igraph`` for it to function. Besides the
relative flexibility of the implementation, it also scales well, and can be run
on graphs of millions of nodes (as long as they can fit in mem... |
from random import choice, random, sample
from utils.command_set import CommandSet
class QuestSegment:
def __init__(self, quest):
self.quest = quest
self.quest_manager = self.quest.quest_manager
self.channel = self.quest_manager.channel
self.channel_manager = self.channel.channel_... |
import logging
class ProgramKeywords(object):
def __init__(self):
self.mood = None # type: unicode
self.time_period = None # type: unicode
self.character = None # type: unicode
self.theme = None # type: unicode
self.setting = None # type: unicode
self.subj... |
# -*- coding: utf-8 -*-
import datetime
import constants
# Choose and configure the browser of your choice
def get_browser():
return webdriver.Chrome()
# The host and port where the tested ap shoud listen.
HOST = '127.0.0.1'
PORT = 8080
# The host alias set in the /etc/hosts file.
# The actual tests will navi... |
#!/usr/bin/env python
import struct
from io import BytesIO
TAG_TYPE_METADATA = 18
##################################################
# AMF0
##################################################
AMF_TYPE_NUMBER = 0x00
AMF_TYPE_BOOLEAN = 0x01
AMF_TYPE_STRING = 0x02
AMF_TYPE_OBJECT = 0x03
AMF_TYPE_MOVIECLIP = 0x04
AMF_TY... |
# coding: utf-8
import logging
from socket import gethostname
from .compat import JSONEncoder
from .compat import json, text_type
class JSONFormatter(logging.Formatter):
"""
Formatter to convert LogRecord into JSON.
Thanks to: https://github.com/lobziik/rlog
"""
def __init__(self, *args, **kwargs... |
bl_info = {
"name": "LipSync Importer & Blinker",
"author": "Yousef Harfoush - bat3a ;)",
"version": (0, 5, 1),
"blender": (2, 70, 0),
"location": "3D window > Tool Shelf",
"description": "Plots Moho (Papagayo, Jlipsync, Yolo) file "
"to frames and adds automatic blinking",
"warning"... |
# coding: utf-8
import os
import time
import click
from pip.utils import rmtree
from pip.vcs.git import Git
from brewchecker.settings import settings
def echo(message=None, nl=True, err=False, _color=None):
log = settings.get('LOG')
msg = message if message else ''
if nl: # Nasty click.echo's bug =(
... |
"""
[2016-04-01] Challenge #260 [Hard] Never Ending Snake
https://www.reddit.com/r/dailyprogrammer/comments/4cw095/20160401_challenge_260_hard_never_ending_snake/
# Description
Sleether Yn is a neverending snake, and like all neverending snakes, she loves drinking neverending soda and eating
baloney. She also hates w... |
from __future__ import absolute_import
from __future__ import with_statement
import os
import sys
from mock import Mock
from celery import Celery
from celery import app as _app
from celery.app import defaults
from celery.app.base import BaseApp
from celery.loaders.base import BaseLoader
from celery.platforms import ... |
"""
To run this, you'll need to have installed.
* scikit-learn
Does two benchmarks
First, we fix a training set, increase the number of
samples to classify and plot number of classified samples as a
function of time.
In the second benchmark, we increase the number of dimensions of the
training set, classify a sam... |
"""End-to-end test for the user score example.
Code: beam/sdks/python/apache_beam/examples/complete/game/user_score.py
Usage:
python setup.py nosetests --test-pipeline-options=" \
--runner=TestDataflowRunner \
--project=... \
--staging_location=gs://... \
--temp_location=gs://... \
--o... |
"""
Regression tests for defer() / only() behavior.
"""
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Item(models.Model):
name = models.CharField(max_length=15)
text = models.TextField(default="xyzzy")
value = models.IntegerF... |
from __future__ import annotations
import inspect
import os
import re
from enum import Enum
from typing import Dict, Iterable, List, Pattern, Sequence
from pants.option.errors import ParseError
from pants.util.eval import parse_expression
from pants.util.memo import memoized_method
class UnsetBool:
"""A type th... |
{
'name': 'Costa Rica - Accounting',
'version': '0.1',
'url': 'http://launchpad.net/openerp-costa-rica',
'author': 'ClearCorp S.A.',
'website': 'http://clearcorp.co.cr',
'category': 'Localization/Account Charts',
'description': """
Chart of accounts for Costa Rica.
==========================... |
from settings_handler import settings
import os
import smtplib
import mimetypes
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.MIMEAudio import MIMEAudio
from email.MIMEImage import MIMEImage
from email.Encoders import encode_base64
def ... |
"""
ShellLogger: Unix shell command invocation logger
Usage: shelllogger [-s, --sanitize outfilename] <logfilename>
Upon invocation, it will spawn a new shell (either tcsh or bash, depending upon
SHELL variable).
Directory can be specified by setting (and exporting) the SHELLLOGGERDIR
environment variable to a dire... |
# object.__new__(cls) is the only way in Python to allocate empty
# (non-initialized) instance of class.
# See e.g. http://infohost.nmt.edu/tcc/help/pubs/python/web/new-new-method.html
# TODO: Find reference in CPython docs
try:
# If we don't expose object.__new__ (small ports), there's
# nothing to test.
o... |
import unittest
from test._mock_backport import Mock
from dart.engine.emr.actions.consume_subscription import consume_subscription
from dart.engine.emr.exception.exception import ActionFailedButConsumeSuccessfulException
from dart.engine.emr.steps import StepWrapper
from dart.model.action import Action, ActionData
fro... |
from OpenGL.GL import *
from .. GLGraphicsItem import GLGraphicsItem
from ... import QtGui
__all__ = ['GLAxisItem']
class GLAxisItem(GLGraphicsItem):
"""
**Bases:** :class:`GLGraphicsItem <pyqtgraph.opengl.GLGraphicsItem>`
Displays three lines indicating origin and orientation of local coordinate sys... |
#!/usr/bin/env python
"""Extend a ttx file with additional data.
Takes a ttx file and one or more directories containing image files named
after sequences of codepoints, extends the cmap, hmtx, GSUB, and GlyphOrder
tables in the source ttx file based on these sequences, and writes out a new
ttx file.
This can also a... |
from optparse import make_option
import threading
from webkitpy.tool.multicommandtool import AbstractDeclarativeCommand
class AbstractLocalServerCommand(AbstractDeclarativeCommand):
server = None
launch_path = "/"
def __init__(self):
options = [
make_option("--httpd-port", action="st... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
try:
import psycopg2
import psycopg2.extras
except ImportError:
postgresqldb_found = False
else:
postgresqldb_found = True
class NotSupportedError(Exception):
... |
#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <<EMAIL>>'
__docformat__ = 'restructuredtext en'
import textwrap, os, glob
... |
#!/usr/bin/env pypy
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys
import re
import time
import subprocess
import functools
import os
import signal
import argparse
import importlib
import multiprocessing
import random
import sunfish
import xboard
############################################... |
import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from java.util import Vector
def addTemplate(core):
mobileTemplate = MobileTemplate()
mobi... |
from enigma import *
from Screens.Screen import Screen
from Components.ActionMap import ActionMap
from Components.Sources.List import List
from Tools.Directories import resolveFilename, SCOPE_CURRENT_SKIN
from Tools.LoadPixmap import LoadPixmap
from Components.Button import Button
from Components.Label import Label
fro... |
from mpi4py import MPI
import mpiunittest as unittest
try:
import ctypes
except ImportError:
ctypes = None
class TestCTYPES(unittest.TestCase):
objects = [
MPI.DATATYPE_NULL,
MPI.INT,
MPI.DOUBLE,
MPI.REQUEST_NULL,
MPI.INFO_NULL,
MPI.INFO_ENV,
MPI.ERR... |
from gnuradio import gr, atsc
import math, os
def main():
print os.getpid()
tb = gr.top_block()
u = gr.file_source(gr.sizeof_float,"/tmp/atsc_pipe_2")
input_rate = 19.2e6
IF_freq = 5.75e6
# 1/2 as wide because we're designing lp filter
symbol_rate = atsc.ATSC_SYMBOL_RATE/2.
NTAPS = 279
tt... |
from django.core.management.base import BaseCommand
def module_to_dict(module, omittable=lambda k: k.startswith('_')):
"""Convert a module namespace to a Python dictionary."""
return {k: repr(v) for k, v in module.__dict__.items() if not omittable(k)}
class Command(BaseCommand):
help = """Displays diffe... |
################### :D #################
# all available renderers must be listed here
renderers = 'Cineman Vray'
#creates script panel/options
p = nuke.Panel('Smart Comper')
p.addEnumerationPulldown('renderers', renderers)
p.addBooleanCheckBox('AutoCrop', False)
p.addBooleanCheckBox('Add Grade Nodes', False)
#brings u... |
from app.config.cplog import CPLog
from app.config.db import Movie, MovieETA, Session as Db
from app.lib.cron.base import cronBase
from app.lib.provider.rss import rss
from dateutil.parser import parse
from sqlalchemy.sql.expression import or_
from urllib import urlencode
import Queue
import cherrypy
import time
import... |
"""
Fixture to create a course and course components (XBlocks).
"""
import mimetypes
import json
import datetime
from textwrap import dedent
from collections import namedtuple
from path import Path as path
from opaque_keys.edx.keys import CourseKey
from . import STUDIO_BASE_URL
from .base import XBlockContainerFix... |
"""Classes that replace tkinter gui objects used by an object being tested.
A gui object is anything with a master or parent paramenter, which is
typically required in spite of what the doc strings say.
"""
class Event:
'''Minimal mock with attributes for testing event handlers.
This is not a gui object, but... |
from fife import fifechan
from fife.extensions.pychan.attrs import Attr, BoolAttr, PointAttr
from fife.extensions.pychan.properties import ImageProperty
from common import text2gui
from basictextwidget import BasicTextWidget
class Button(BasicTextWidget):
"""
A basic push button.
"""
def __init__(self,
pa... |
"""
cleanNetShp -- Tools to clean spatial Network Shapefiles.
"""
import pysal
import numpy
__author__ = "Charles R. Schmidt <<EMAIL>>"
__all__ = ['snap_verts', 'find_nodes', 'split_at_nodes']
def snap_verts(shp,tolerance=0.001,arc=True):
"""
snap_verts -- Snap verts that are within tolerance meters of each ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Project Haystack version definitions.
# (C) 2018 VRT Systems
#
# vim: set ts=4 sts=4 et tw=78 sw=4 si:
"""
Project Haystack Version comparison.
Project Haystack does not use a standard versioning scheme like Semantic
Versioning, rather, they have a Major.Minor scheme. This... |
import os
import random
import time
import six
from rally.common.i18n import _
from rally import osclients
from rally.plugins.openstack import scenario
from rally.task import atomic
class FuelEnvManager(object):
def __init__(self, client):
self.client = client
def get(self, env_id):
try:
... |
import _surface
import chimera
try:
import chimera.runCommand
except:
pass
from VolumePath import markerset as ms
try:
from VolumePath import Marker_Set, Link
new_marker_set=Marker_Set
except:
from VolumePath import volume_path_dialog
d= volume_path_dialog(True)
new_marker_set= d.new_marker_set
marker_set... |
"""
The MIT License (MIT)
Copyright (c) 2014 NTHUOJ team
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, ... |
from metamodel import *
class DommExport(object):
"""docstring for DommExport"""
def __init__(self,):
super(DommExport, self).__init__()
def render_enum(self, f, enum):
"""
This method renders Enumeration in dot format and writes into f buffer.
It adds every literal name i... |
"""
Built-in, globally-available admin actions.
"""
from django import template
from django.core.exceptions import PermissionDenied
from django.contrib.admin import helpers
from django.contrib.admin.util import get_deleted_objects, model_ngettext
from django.db import router
from django.shortcuts import render_to_resp... |
import re
from style import Style, TextProperties, ListLevelProperties
from text import ListStyle,ListLevelStyleNumber,ListLevelStyleBullet
"""
Create a <text:list-style> element from a string or array.
List styles require a lot of code to create one level at a time.
These routines take a string and delimiter, or a l... |
from lxml import etree
import webob
from nova.api.openstack.compute.contrib import extended_ips
from nova.api.openstack import xmlutil
from nova import compute
from nova.objects import instance as instance_obj
from nova.openstack.common import jsonutils
from nova import test
from nova.tests.api.openstack import fakes
... |
from pylab import *
from scipy import constants as const
import numpy as np
con_h = const.h/const.e
con_k = const.k/const.e
np.seterr(all = "ignore")
parsec = 3.08567758e16
m1 = 5.0 # central mass
alfa = 0.5 # accretion parameter
mass_flow = 5.0 # mass flow from disk
Rc = 1.0*10.0**-4 # diameter of central ob... |
# -*- coding: utf-8 -*-
#
# Test links:
# http://speedy.sh/ep2qY/Zapp-Brannigan.jpg
import re
from module.plugins.internal.SimpleHoster import SimpleHoster, create_getInfo
class SpeedyshareCom(SimpleHoster):
__name__ = "SpeedyshareCom"
__type__ = "hoster"
__version__ = "0.06"
__status__ = "te... |
#!/usr/bin/env python3
import os
import pygit2
import dmm
from mapmerge import merge_map
def main(repo):
if repo.index.conflicts:
print("You need to resolve merge conflicts first.")
return 1
try:
repo.lookup_reference('MERGE_HEAD')
print("Not running mapmerge for merge commit."... |
import numpy
import cPickle as pkl
import gzip
def fopen(filename, mode='r'):
if filename.endswith('.gz'):
return gzip.open(filename, mode)
return open(filename, mode)
class TextIterator:
"""Simple Bitext iterator."""
def __init__(self, source, target,
source_dict, target_d... |
from core.himesis import Himesis
import uuid
class HdfacilitiesSolveRefNeighborhoodSchoolServiceChildDistrictSpecialFacilityPerson(Himesis):
def __init__(self):
"""
Creates the himesis graph representing the DSLTrans rule dfacilitiesSolveRefNeighborhoodSchoolServiceChildDistrictSpecialFa... |
"""Adds xref targets to the top of files."""
import sys
import os
testing = False
DONT_TOUCH = (
'./index.txt',
)
def target_name(fn):
if fn.endswith('.txt'):
fn = fn[:-4]
return '_' + fn.lstrip('./').replace('/', '-')
def process_file(fn, lines):
lines.insert(0, '\n')
lin... |
from argparse import ArgumentParser
from typing import Any
from django.core.management.base import CommandError
from zerver.lib.actions import do_change_full_name
from zerver.lib.management import ZulipBaseCommand
class Command(ZulipBaseCommand):
help = """Change the names for many users."""
def add_argumen... |
"""Google Cloud Endpoints module."""
# pylint: disable=wildcard-import
from __future__ import absolute_import
import logging
from protorpc import message_types
from protorpc import messages
from protorpc import remote
from .api_config import api, method
from .api_config import AUTH_LEVEL, EMAIL_SCOPE
from .api_conf... |
"""
.. versionadded:: 0.9.2
Functions for wrapping strings in ANSI color codes.
Each function within this module returns the input string ``text``, wrapped
with ANSI color codes for the appropriate color.
For example, to print some text as green on supporting terminals::
from fabric.colors import green
pri... |
from xml.etree import ElementTree
from xml.parsers.expat import ExpatError
from django.utils import six
from allauth.socialaccount import providers
from allauth.socialaccount.providers.oauth.client import OAuth
from allauth.socialaccount.providers.oauth.views import (OAuthAdapter,
... |
from __future__ import unicode_literals
import logging
from django import forms
from django.core.mail.message import EmailMessage
from django.utils.translation import ugettext as _
from shoop.notify.base import Action, Binding
from shoop.notify.enums import ConstantUse, TemplateUse
from shoop.notify.typology import ... |
r"""A demo which runs object detection on camera frames.
Requires cv2 from `sudo apt-get install python3-opencv`
python3 examples/jetson_camera_demo \
--model data/traffic_model_edgetpu.tflite \
--label data/traffic_label_map.pbtxt
Press Q key to exit.
"""
import argparse
import time
from automl_video_ondevice i... |
# pylint: disable=missing-docstring
from lettuce import world, step
from common import i_am_registered_for_the_course, section_location, visit_scenario_item
@step('I view the word cloud and it has rendered')
def word_cloud_is_rendered(_step):
assert world.is_css_present('.word_cloud')
@step('the course has a W... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
import socket
import xmlrpclib
webfaction = xmlrpclib.ServerProxy('https://api.webfaction.com/')
def main():
module = AnsibleModule(
argument_spec=dict(
mailbox_n... |
# coding: utf-8
from __future__ import unicode_literals
import random
from .common import InfoExtractor
from ..compat import compat_urllib_parse
from ..utils import (
sanitized_Request,
xpath_text,
)
class MatchTVIE(InfoExtractor):
_VALID_URL = r'https?://matchtv\.ru/?#live-player'
_TEST = {
... |
"""
Test project subcontroller
"""
import os
import sys
import glob
import unittest
from cement.core import handler
from cement.utils import shell, test
from test_default import PmTest, safe_makedir
from scilifelab.pm.core.project import ProjectController, ProjectRmController
from scilifelab.pm.core.production import P... |
import unittest
from hamcrest import assert_that, instance_of, is_, is_not
import mock
from netman.core.objects.flow_control_switch import FlowControlSwitch
from netman.core import switch_factory
from netman.core.objects.switch_base import SwitchBase
from netman.adapters.switches.remote import RemoteSwitch
from netm... |
import random
class Token:
global word
global nextList
def __init__(self, word, nextWord):
self.word = word
self.nextList = dict()
self.update_next(nextWord)
def update_next(self, nextWord):
if nextWord in self.nextList:
self.nextList[nextWord] += 1
... |
import os
from ruamel.yaml import YAML
from bot import defaults as bot_defaults
from bot.lib.logger import create_logger
log = create_logger('Configuration')
yaml = YAML(typ='safe')
yaml.default_flow_style = False
class Configuration:
"""
Manages a YAML configuration file
"""
def __init__(self, pat... |
#!/usr/bin/env python
from nose.tools import *
from nose import SkipTest
import networkx as nx
def test_valid_degree_sequence1():
n = 100
p = .3
for i in range(10):
G = nx.erdos_renyi_graph(n,p)
deg = list(G.degree().values())
assert_true( nx.is_valid_degree_sequence(deg, method='eg... |
async def asyncgen():
yield 10
async def run():
{i for i in <warning descr="Expected 'collections.Iterable', got 'AsyncGenerator[int, Any]' instead">asyncgen()</warning>}
[i for i in <warning descr="Expected 'collections.Iterable', got 'AsyncGenerator[int, Any]' instead">asyncgen()</warning>]
{i: i ** 2... |
from agon_ratings.models import OverallRating
from dialogos.models import Comment
from django.contrib.contenttypes.models import ContentType
from django.db.models import Avg
from haystack import indexes
from geonode.maps.models import Layer
class LayerIndex(indexes.SearchIndex, indexes.Indexable):
id = indexes.In... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from rpython.rlib.objectmodel import we_are_translated
class ExitException(Exception):
def __init__(self, status_msg):
self.exit_status = status_msg
def is_user(self):
return False
class SchemeException(Exception):
_attrs_ = ["msg", "w_exn_... |
"""Tests of the pnacl driver.
This tests that help messages are available in all of the drivers.
"""
from driver_env import env
import driver_test_utils
import driver_tools
pnacl_ar = __import__("pnacl-ar")
pnacl_as = __import__("pnacl-as")
pnacl_clang = __import__("pnacl-clang")
pnacl_dis = __import__("pnacl-dis")
... |
from os.path import dirname, join
from bokeh.core.properties import Any, Dict, Instance, String
from bokeh.models import ColumnDataSource, LayoutDOM
# This defines some default options for the Graph3d feature of vis.js
# See: http://visjs.org/graph3d_examples.html for more details. Note
# that we are fixing the size ... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from units.compat.mock import patch
from ansible.modules.network.netvisor import pn_vrouter_bgp
from units.modules.utils import set_module_args
from .nvos_module import TestNvosModule
class TestVrouterBGPModule(TestNvosModule):
... |
"""Supports reading and processing text files."""
import codecs
import logging
import os
import sys
_log = logging.getLogger(__name__)
class TextFileReader(object):
"""Supports reading and processing text files.
Attributes:
file_count: The total number of files passed to this instance
... |
from Tkinter import *
def keyPressed(event):
canvas = event.widget.canvas
# first process keys that work even if the game is over
if (event.char == "q"):
gameOver(canvas)
elif (event.char == "r"):
init(canvas)
elif (event.char == "d"):
canvas.data["inDebugMode"] = not canvas... |
#coding: utf8
import traceback
from django.shortcuts import render
from django.views.decorators.cache import cache_page
from django.views.decorators.cache import never_cache
from django.http import JsonResponse, HttpResponse
from ssbc import settings
from search.models import Hash, FileList, StatusReport, RecKeywords... |
# coding: utf-8
"""
Salt Edge Account Information API
API Reference for services # noqa: E501
OpenAPI spec version: 5.0.0
Contact: <EMAIL>
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import swagger_client
from swa... |
from StringIO import StringIO
from unicodecsv import DictReader
from unicodecsv import Error as CSVError
import logging
import colander
from grano.core import db
from grano.model import File
from grano.logic.references import ProjectRef, AccountRef
from grano.lib.exc import BadRequest
log = logging.getLogger(__name_... |
#!/usr/bin/env python
import wx
import getopt
import sys
import os
sys.path.append(os.getenv("PAPARAZZI_HOME") + "/sw/lib/python")
import messages_tool
class MessagePicker(wx.Frame):
def __init__(self, parent, callback, initIvy = True):
wx.Frame.__init__(self, parent, name="MessagePicker", title=u'Message Pi... |
from ironicclient.common import utils
from ironicclient.openstack.common import cliutils
def _print_driver_show(driver):
fields = ['name', 'hosts']
data = dict([(f, getattr(driver, f, '')) for f in fields])
cliutils.print_dict(data, wrap=72)
def do_driver_list(cc, args):
"""List of enabled drivers."... |
from nose.tools import assert_raises
import gevent
import sys
from zerorpc import zmq
import zerorpc
from testutils import teardown, random_ipc_endpoint
def test_close_server_bufchan():
endpoint = random_ipc_endpoint()
server_events = zerorpc.Events(zmq.ROUTER)
server_events.bind(endpoint)
server = z... |
"""Testing.
See the @{$python/test} guide.
Note: `tf.test.mock` is an alias to the python `mock` or `unittest.mock`
depending on the python version.
@@main
@@TestCase
@@test_src_dir_path
@@assert_equal_graph_def
@@get_temp_dir
@@is_built_with_cuda
@@is_gpu_available
@@gpu_device_name
@@compute_gradient
@@compute_gra... |
from __future__ import unicode_literals
import unittest, frappe, re, email
from frappe.test_runner import make_test_records
make_test_records("User")
make_test_records("Email Account")
class TestEmail(unittest.TestCase):
def setUp(self):
frappe.db.sql("""delete from `tabEmail Unsubscribe`""")
frappe.db.sql("""d... |
import unittest
from ...compatibility import StringIO
from ..helperfunctions import _xml_to_list
from ...worksheet import Worksheet
class TestAssembleWorksheet(unittest.TestCase):
"""
Test assembling a complete Worksheet file.
"""
def test_assemble_xml_file(self):
"""Test writing a worksheet ... |
from __future__ import unicode_literals
import os
from collections import OrderedDict
from django.core.files.storage import FileSystemStorage
from django.core.management.base import CommandError, BaseCommand
from django.core.management.color import no_style
from django.utils.encoding import smart_text
from django.uti... |
import datetime
import time
from django.utils.tzinfo import LocalTimezone
from django.utils.translation import ungettext, ugettext
def timesince(d, now=None):
"""
Takes two datetime objects and returns the time between d and now
as a nicely formatted string, e.g. "10 minutes". If d occurs after now,
... |
import mock
from nova import db
from nova import exception
from nova.objects import compute_node
from nova.objects import service
from nova.openstack.common import jsonutils
from nova.openstack.common import timeutils
from nova.tests.objects import test_objects
NOW = timeutils.utcnow().replace(microsecond=0)
fake_sta... |
"""add_nova_net_id_column_to_share_networks
Revision ID: 17115072e1c3
Revises: 38e632621e5a
Create Date: 2015-02-05 18:07:19.062995
"""
# revision identifiers, used by Alembic.
revision = '17115072e1c3'
down_revision = '38e632621e5a'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column(... |
# -----------------------------------------------------------------------------
# yacc_unused.py
#
# A grammar with an unused rule
# -----------------------------------------------------------------------------
import sys
if ".." not in sys.path: sys.path.insert(0,"..")
import ply.yacc as yacc
from calclex import tok... |
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
class Event(models.Model):
# Oracle can have problems with a column named "date"
date = models.DateField(db_column="event_date")
class Parent(models.Model):
name = models.CharField(max_length=128)
class Child(mo... |
"""Support for WebDav Calendar."""
from datetime import datetime, timedelta
import logging
import re
import voluptuous as vol
from homeassistant.components.calendar import (
PLATFORM_SCHEMA, CalendarEventDevice, get_date)
from homeassistant.const import (
CONF_NAME, CONF_PASSWORD, CONF_URL, CONF_USERNAME, CON... |
"""This is a generic test to test CSS reflow speed of a given URL."""
__author__ = '<EMAIL> (Lindsey Simon)'
__version__ = '0.1'
import logging
import re
import sys
import time
import getopt
import time
import os
import unittest
from selenium import selenium
logging.getLogger().setLevel(logging.DEBUG)
logging.basi... |
# -----------------------------------------------------------------------------
# lex_optimize3.py
#
# Writes table in a subdirectory structure.
# -----------------------------------------------------------------------------
import sys
if ".." not in sys.path: sys.path.insert(0,"..")
import ply.lex as lex
tokens = (
... |
from distutils.errors import DistutilsOptionError
from setuptools.command.setopt import edit_config, option_base, config_file
def shquote(arg):
"""Quote an argument for later parsing by shlex.split()"""
for c in '"', "'", "\\", "#":
if c in arg:
return repr(arg)
if arg.split() != [arg... |
# -*- coding: utf-8 -*-
"""
jinja2.sandbox
~~~~~~~~~~~~~~
Adds a sandbox layer to Jinja as it was the default behavior in the old
Jinja 1 releases. This sandbox is slightly different from Jinja 1 as the
default behavior is easier to use.
The behavior can be changed by subclassing the environm... |
import unittest
from mock import Mock
from xmodule.html_module import HtmlModule
from . import get_test_system
class HtmlModuleSubstitutionTestCase(unittest.TestCase):
descriptor = Mock()
def test_substitution_works(self):
sample_xml = '''%%USER_ID%%'''
module_data = {'data': sample_xml}
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.apps import apps
from django.conf import settings
from django.core import checks
def check_user_model(**kwargs):
errors = []
cls = apps.get_model(settings.AUTH_USER_MODEL)
# Check that REQUIRED_FIELDS is a list
if not isins... |
import re
import socket
import sys
import traceback
from ansible.module_utils.basic import env_fallback
from ansible.module_utils.network.common.utils import to_list, ComplexList
from ansible.module_utils.connection import exec_command, ConnectionError
from ansible.module_utils.six import iteritems
from ansible.module... |
#!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2019 Fortinet, Inc.
#
# This program 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 Lic... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.