content stringlengths 4 20k |
|---|
"""Utility classes for rendering to a texture.
It is mostly used for internal implementation of cocos, you normally shouldn't
need it. If you are curious, check implementation of effects to see an example.
"""
__docformat__ = 'restructuredtext'
from summa.gl_framebuffer_object import FramebufferObject
from pyglet im... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.che... |
import os, sys
import argparse
import time
import math
import csv
import re
#------------------------------------------------------ Main ----------------------------------------------------------
sys.stdout.flush()
print( "[ " + time.strftime('%d-%b-%Y %H:%M:%S',time.localtime()) + " ]" + "" )
# Pick up the comman... |
"""Locations where we look for configs, install stuff, etc"""
from __future__ import absolute_import
import os
import os.path
import platform
import site
import sys
import sysconfig
from distutils import sysconfig as distutils_sysconfig
from distutils.command.install import SCHEME_KEYS # type: ignore
from pip._inter... |
from __future__ import unicode_literals
import frappe, os
from frappe import _
from frappe.utils import cint
import frappe.defaults
from frappe.model.document import Document
class Company(Document):
def onload(self):
self.get("__onload").transactions_exist = self.check_if_transactions_exist()
def check_if_tra... |
import zookeeper, zktestbase, unittest, threading
ZOO_OPEN_ACL_UNSAFE = {"perms":zookeeper.PERM_ALL, "scheme":"world", "id" :"anyone"}
ZOO_ACL_READ = {"perms":zookeeper.PERM_READ, "scheme": "world",
"id":"anyone"}
class ACLTest(zktestbase.TestBase):
"""Test whether basic ACL setting and getting wor... |
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
import vtkdevide
class selectConnectedComponents(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# call parent constructor
ModuleBase.__init__(self, mo... |
ANSIBLE_METADATA = {'status': ['stableinterface'],
'supported_by': 'core',
'version': '1.0'}
EXAMPLES = r'''
# Downloading a JPEG and saving it to a file with the ansible command.
# Note the "dest" is quoted rather instead of escaping the backslashes
$ ansible -i hosts -c winrm ... |
import jinja2
import json
import os
import re
import urllib
import webapp2
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
import services
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions=['jinja2.... |
'''
SASSIE: Copyright (C) 2011 Joseph E. Curtis, Ph.D.
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 License, or
(at your option) any later version.
... |
import os.path, cv2, os
import numpy as np
class Image:
def __init__(self, conf):
self.image = None
self.configuration = conf
def loadImage(self, fn):
self.filename = fn
self.image = cv2.imread(self.filename, cv2.IMREAD_UNCHANGED)
if self.image == None:
... |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
Name : DB Manager
Description : Database manager plugin for QGIS
Date : May 23, 2011
copyright : (C) 2011 by Giuseppe Sucameli
email : <EMAIL>
**... |
from heat_integrationtests.common import test
from heat_integrationtests.functional import functional_base
create_user = '''
heat_template_version: 2014-10-16
description: test template to test user role assignment with user{domain}
parameters:
user_name:
type: string
label: User Name
description: Test u... |
import json
import logging
import re
import unittest
import urllib2
from vtctl import vtctl_client
import environment
import tablet
import utils
# range '' - 80
shard_0_master = tablet.Tablet()
shard_0_replica = tablet.Tablet()
# range 80 - ''
shard_1_master = tablet.Tablet()
shard_1_replica = tablet.Tablet()
# all... |
from .LayerPolygon import LayerPolygon
from UM.Math.Vector import Vector
from UM.Mesh.MeshBuilder import MeshBuilder
import numpy
class Layer:
def __init__(self, layer_id):
self._id = layer_id
self._height = 0.0
self._thickness = 0.0
self._polygons = []
self._element_count... |
import sys
import eventlet
eventlet.monkey_patch()
from oslo.config import cfg
from neutron.common import config
from neutron.i18n import _LI
from neutron.openstack.common import log as logging
from neutron import service
LOG = logging.getLogger(__name__)
def main():
# the configuration will be read into the ... |
# AsymmetricRandom Chess
import random
from pychess.Utils.const import VARIANTS_SHUFFLE, ASYMMETRICRANDOMCHESS
from pychess.Utils.Board import Board
class AsymmetricRandomBoard(Board):
variant = ASYMMETRICRANDOMCHESS
__desc__ = \
_("FICS wild/4: http://www.freechess.org/Help/HelpFiles/wild.html\n" +... |
import BoostBuild
t = BoostBuild.Tester(pass_toolset=0, pass_d0=False)
t.write("file.jam", """
actions update
{
echo updating $(<)
}
update x1 x2 ;
update x2 x3 ;
""")
# Updating x1 should force x2 to update as well.
t.run_build_system(["-ffile.jam", "x1"], stdout="""\
...found 3 targets...
...... |
#!/usr/bin/env python
# coding: utf-8
"""Test error messages."""
import os
import pytest
from xsuite import xcdo
from xsuite.tools import load_data
ds = load_data('pre', decode_times=False)
datadir = os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir, 'data')
filename = os.path.join(datadir, 'sr... |
""" Automate Commands """
from paver.easy import *
import paver.doctools
from paver.tasks import task
from pip.req import parse_requirements
from paver.setuputils import (
install_distutils_tasks
)
# -- REQUIRED-FOR: setup, sdist, ...
# NOTE: Adds a lot more python-project related tasks.
install_distutils_tasks()
... |
import abc
import six
NOTSET = object()
@six.add_metaclass(abc.ABCMeta)
class BaseCache(object):
"""Base Cache Abstraction
:params parsed_url: Parsed url object.
:params options: A dictionary with configuration parameters
for the cache. For example:
- default_ttl: An integer defining th... |
"""Serializers for defcon.status."""
from rest_framework import serializers
from defcon.status import models
# Models for the full API.
class ComponentSerializer(serializers.HyperlinkedModelSerializer):
"""Serializer for Component."""
class Meta:
"""Configuration."""
model = models.Componen... |
import product
import pricelist
import report
import partner
import wizard
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
"""
Helper classes and methods for running modulestore tests without Django.
"""
from importlib import import_module
from opaque_keys.edx.keys import UsageKey
from unittest import TestCase
from xblock.fields import XBlockMixin
from xmodule.x_module import XModuleMixin
from xmodule.modulestore import ModuleStoreEnum
fro... |
import bisect
from _pydevd_bundle.pydevd_constants import dict_items, NULL, KeyifyList
import pydevd_file_utils
class SourceMappingEntry(object):
__slots__ = ['source_filename', 'line', 'end_line', 'runtime_line', 'runtime_source']
def __init__(self, line, end_line, runtime_line, runtime_source):
as... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['stableinterface'],
'supported_by': 'core'}
DOCUMENTATION = r'''
---
module: win_group
version_added: "1.7"
short_description: Add and remove local groups
description:
- Add and remove local groups
options:
name:
... |
from __future__ import unicode_literals
from optparse import make_option
from datetime import datetime
import errno
import os
import re
import sys
import socket
from django.core.management.base import BaseCommand, CommandError
from django.core.servers.basehttp import run, get_internal_wsgi_application
from django.db ... |
import logging
import re
import shutil
import sys
import yum
from yum.misc import prco_tuple_to_string
from yum.packageSack import ListPackageSack
from yum.packages import parsePackages
from yum.repos import RepoStorage
try:
from spacewalk.satellite_tools.progress_bar import ProgressBar
except ImportError:
# p... |
# -*- coding: utf-8 -*-
from sympy import Integral, latex, Function
from sympy import pretty as xpretty
from sympy.vector import CoordSysCartesian, Vector, Dyadic, express
from sympy.abc import a, b, c
from sympy.core.compatibility import u_decode as u
from sympy.utilities.pytest import XFAIL
def pretty(expr):
"""... |
'''
django admin pages for courseware model
'''
from django import forms
from config_models.admin import ConfigurationModelAdmin
from django.contrib.auth.models import User
from student.models import UserProfile, UserTestGroup, CourseEnrollmentAllowed, DashboardConfiguration
from student.models import (
CourseEnro... |
import sys
from autofill_merge_common import SerializeProfiles, ColumnNameToFieldType
def main():
"""Serializes the output of the query 'SELECT * from autofill_profiles;'.
"""
COLUMNS = ['GUID', 'LABEL', 'FIRST_NAME', 'MIDDLE_NAME', 'LAST_NAME', 'EMAIL',
'COMPANY_NAME', 'ADDRESS_LINE_1', 'ADDRESS... |
"""
shared options and groups
The principle here is to define options once, but *not* instantiate them
globally. One reason being that options with action='append' can carry state
between parses. pip parses general options twice internally, and shouldn't
pass on state. To be consistent, all options will follow this de... |
import os
import logging
from autotest.client.shared import error
from virttest import libvirt_storage
from virttest import virsh
def run(test, params, env):
'''
Test the command virsh pool-create-as
(1) Call virsh pool-create-as
(2) Call virsh -c remote_uri pool-create-as
(3) Call virsh pool-c... |
"""Tests for SavedModel utils."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.core.framework import types_pb2
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework imp... |
from spack import *
class Loki(MakefilePackage):
"""Loki is a C++ library of designs, containing flexible implementations
of common design patterns and idioms."""
homepage = "http://loki-lib.sourceforge.net"
url = "https://downloads.sourceforge.net/project/loki-lib/Loki/Loki%200.1.7/loki-0.1.7.t... |
from __future__ import unicode_literals
from .common import InfoExtractor
class GrouponIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?groupon\.com/deals/(?P<id>[^/?#&]+)'
_TEST = {
'url': 'https://www.groupon.com/deals/bikram-yoga-huntington-beach-2#ooid=tubGNycTo_9Uxg82uESj4i61EYX8nyuf',
... |
from nova.compute import resource_tracker
from nova import objects
class FakeResourceTracker(resource_tracker.ResourceTracker):
"""Version without a DB requirement."""
def _create(self, context, values):
self._write_ext_resources(values)
self.compute_node = values
self.compute_node['i... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
import re
import ansible.module_utils.asa
from ansible.module_utils.basic import get_exception
from ansible.module_utils.network import NetworkModule, NetworkError
from ansible.... |
from sys import version_info
from collections import deque, Iterable
from operator import add, itemgetter, attrgetter, not_
from functools import partial
from itertools import (islice,
chain,
starmap,
repeat,
tee,
... |
from flask import request
from restpager import Pager
from sqlalchemy.orm import aliased
from sqlalchemy.sql import func
from grano.lib.exc import BadRequest
from grano.lib.args import arg_bool
from grano.model import Project, Relation
from grano.model import Entity, Property, Schema, db
from grano.views import filter... |
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import json
from builder.helper import get_tensor_size
from tensorflow.examples.tutorials.mnist import input_data
import os
import datetime
import math
VALIDATION_SIZE = 5000
mnist = input_data.read_data_sets('MNIST_data', one_hot=False, reshap... |
import inspect
import six
from nova.notifications.objects import base
from nova.objects import base as nova_base
from nova.objects import fields
@nova_base.NovaObjectRegistry.register_notification
class ExceptionPayload(base.NotificationPayloadBase):
# Version 1.0: Initial version
VERSION = '1.0'
fields... |
from euca2ools.commands.ec2 import EC2Request
import os
from requestbuilder import Arg
class CreateKeyPair(EC2Request):
DESCRIPTION = 'Create a new SSH key pair for use with instances'
ARGS = [Arg('KeyName', metavar='KEYPAIR',
help='name of the new key pair (required)'),
Arg('-f', ... |
import HTSeq
import numpy
from matplotlib import pyplot
bamfile = HTSeq.BAM_Reader( "SRR001432_head.bam" )
gtffile = HTSeq.GFF_Reader( "Homo_sapiens.GRCh37.56_chrom1.gtf" )
halfwinwidth = 3000
fragmentsize = 200
tsspos = HTSeq.GenomicArrayOfSets( "auto", stranded=False )
for feature in gtffile:
if feature.type == ... |
# -*- coding: utf-8 -*-
#------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Canal para oranline
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import urlparse,urllib2,urllib,re
import os, sys
from core imp... |
from test.test_support import verbose, TestSkipped, run_unittest
from _locale import (setlocale, LC_NUMERIC, RADIXCHAR, THOUSEP, nl_langinfo,
localeconv, Error)
import unittest
from platform import uname
if uname()[0] == "Darwin":
maj, min, mic = [int(part) for part in uname()[2].split(".")]
... |
from devsim import *
import devsim.python_packages.pythonmesh
def gmsh_reader(mesh, device, filename="", coordinates="", physical_names="", elements=""):
if (filename):
create_gmsh_mesh(mesh=mesh, file=filename)
else:
create_gmsh_mesh(mesh=mesh, coordinates=coordinates, physical_names=physical... |
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_... |
# pylint: disable=missing-docstring
# pylint: disable=redefined-outer-name
from lettuce import world, step
from common import course_location
from problems_setup import PROBLEM_DICT
from nose.tools import assert_in
@step(u'I am viewing a course with multiple sections')
def view_course_multiple_sections(step):
cr... |
import base64
from nose.tools import assert_equals
from verify_student.ssencrypt import (
aes_decrypt, aes_encrypt, encrypt_and_encode, decode_and_decrypt,
rsa_decrypt, rsa_encrypt
)
def test_aes():
key_str = "32fe72aaf2abb44de9e161131b5435c8d37cbdb6f5df242ae860b283115f2dae"
key = key_str.decode("hex... |
from __future__ import absolute_import
from django.conf import settings
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext_lazy as _
from sentry import roles
from sentry.models import Team, TeamSta... |
import operator
class accumulate:
def __init__(self, iterable, func = operator.add):
self.it = iter(iterable)
self._total = None
self.func = func
def __iter__(self):
return self
def __next__(self):
if not self._total:
self._total = next(self.it)... |
import uuid
from mock import Mock
from mock import patch
from testtools import TestCase
from trove.cluster.models import Cluster
from trove.cluster.models import ClusterTasks
from trove.cluster.models import DBCluster
from trove.common import cfg
from trove.common import exception
from trove.common import remote
from ... |
import time
import socket
NUM_TRIES = 10
request = "poipoipoipoi"
myAddress = '' #means 'all'
myPort = 21568
hisAddress = 'bbbb::1415:92cc:0:2'
hisPort = 7
delays = []
succ = 0
fail = 0
print "Testing udpEcho..."
for i in range(NUM_TRIES):
# log
output = []
output... |
"""Defines ``Group`` and ``UserPartition`` models for partitioning"""
from collections import namedtuple
# We use ``id`` in this file as the IDs of our Groups and UserPartitions,
# which Pylint disapproves of.
# pylint: disable=invalid-name, redefined-builtin
class Group(namedtuple("Group", "id name")):
"""
A... |
import logging
import os
from zipfile import is_zipfile, ZipFile
from django.conf import settings
from osgeo_importer.importers import VALID_EXTENSIONS
from osgeo_importer.utils import NoDataSourceFound, load_handler
OSGEO_IMPORTER = getattr(settings, 'OSGEO_IMPORTER', 'osgeo_importer.importers.OGRImport')
logger ... |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'UserProfile'
db.create_table('auth_userprofile', (
('id', self.gf('django.db.models.f... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['stableinterface'],
'supported_by': 'community'}
try:
import boto
import boto.ec2
from boto import route53
from boto.route53 import Route53Connection
from boto.route53.zone import Zone
HAS_BOTO = ... |
# -*- coding: utf-8 -*-
"""QGIS Unit tests for OGR GeoPackage QgsAbastractProviderConnection API.
.. note:: 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 2 of the License, or
(at you... |
"""address scope support in subnetpool
Revision ID: 1b4c6e320f79
Revises: 1c844d1677f7
Create Date: 2015-07-03 09:48:39.491058
"""
# revision identifiers, used by Alembic.
revision = '1b4c6e320f79'
down_revision = '1c844d1677f7'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('subn... |
import copy
import json
import time
import random
import operator
from dream.simulation.GUI.Shifts import Simulation as ShiftsSimulation
from dream.simulation.GUI.Default import schema
class Simulation(ShiftsSimulation):
def getConfigurationDict(self):
conf = ShiftsSimulation.getConfigurationDict(self)
conf... |
from __future__ import absolute_import
from __future__ import print_function
from typing import Any
from argparse import ArgumentParser
from django.core.management.base import BaseCommand
from zerver.models import get_realm_by_string_id, Realm
import sys
class Command(BaseCommand):
help = """Show the admins in a... |
from libcloud.backup.base import BackupDriver
class DummyBackupDriver(BackupDriver):
"""
Dummy Backup driver.
>>> from libcloud.backup.drivers.dummy import DummyBackupDriver
>>> driver = DummyBackupDriver('key', 'secret')
>>> driver.name
'Dummy Backup Provider'
"""
name = 'Dummy Back... |
__all__ = ['CBaseLoader', 'CSafeLoader', 'CLoader',
'CBaseDumper', 'CSafeDumper', 'CDumper']
from _yaml import CParser, CEmitter
from constructor import *
from serializer import *
from representer import *
from resolver import *
class CBaseLoader(CParser, BaseConstructor, BaseResolver):
def __init__(s... |
#-*- coding: utf-8 -*-
from django.contrib.auth.models import AnonymousUser
from django.core.exceptions import ObjectDoesNotExist
from shop.models import AddressModel
#===============================================================================
# Addresses handling
#================================================... |
"""Generic utilities for all python scripts."""
import atexit
import httplib
import os
import signal
import stat
import subprocess
import sys
import tempfile
import urlparse
import zipfile
def GetPlatformName():
"""Return a string to be used in paths for the platform."""
if IsWindows():
return 'win'
if IsM... |
from django.core.management.base import BaseCommand
from optparse import make_option
import sys
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--noinput', action='store_false', dest='interactive', default=True,
help='Tells Django to NOT prompt the user for in... |
"""Utilities to evaluate models with respect to a variable
"""
#
# License: BSD 3 clause
import warnings
import numpy as np
from .base import is_classifier, clone
from .cross_validation import check_cv
from .externals.joblib import Parallel, delayed
from .cross_validation import _safe_split, _score, _fit_and_score
f... |
"""
Texas - Ticket Sales System
Copyright (C) 2010 Ben Sarsgard
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 License, or
(at your option) any later ... |
"""
A peak element is an element that is greater than its neighbors.
Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that num[-1] = num[n] = -∞.
For example, i... |
name = 'api'
__doc__ = "Access to the raw dropbox API methods"
WRAPPED_METHODS = [
'account_info',
'add_copy_ref',
'create_copy_ref',
'delta',
'file_copy',
'file_create_folder',
'file_delete',
'file_move',
'get_file',
'get_file_and_metadata',
'media',
'metadata',
'put_file',
'request',
'restore',
'... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
.. py:currentmodule:: OxfordInstruments.MapRaw.MapRawFormat
:synopsis: Read Oxford Instruments map in the raw format.
.. moduleauthor:: Hendrix Demers <<EMAIL>>
Read Oxford Instruments map in the raw format.
"""
#######################################... |
from datetime import timedelta
import numpy as np
from pandas.core.groupby import BinGrouper, Grouper
from pandas.tseries.frequencies import to_offset, is_subperiod, is_superperiod
from pandas.tseries.index import DatetimeIndex, date_range
from pandas.tseries.tdi import TimedeltaIndex
from pandas.tseries.offsets impo... |
"""
Various complex queries that have been problematic in the past.
"""
from __future__ import unicode_literals
import threading
from django.db import models
from django.utils import six
from django.utils.encoding import python_2_unicode_compatible
class DumbCategory(models.Model):
pass
class ProxyCategory(Du... |
import codecs
import os
import subprocess
import sys
import re
import glob
from docutils import nodes, statemachine
from docutils.statemachine import ViewList
from docutils.parsers.rst import directives, Directive
#
# AutodocReporter is only good up to Sphinx 1.7
#
import sphinx
Use_SSI = sphinx.__version__[:3] >= '... |
"""
======================================================
Out-of-core classification of text documents
======================================================
This is an example showing how scikit-learn can be used for classification
using an out-of-core approach: learning from data that doesn't fit into main
memory. ... |
import errno
import re
import os
import sys
import subprocess
# Note that gcc uses unicode, which may depend on the locale. TODO:
# force LANG to be set to en_US.UTF-8 to get consistent warnings.
allowed_warnings = set([
"return_address.c:62",
"workqueue.c:480"
])
# Capture the name of the object file, can... |
from sklearn.feature_extraction.text import CountVectorizer
import indeed_scrape
import GrammarParser
import subprocess
import numpy as np
import logging
import os
from os import path
import numpy as np
data_dir = os.getenv('OPENSHIFT_DATA_DIR')
if data_dir is None:
data_dir = os.getenv('PWD')
logging = logging.g... |
from django.core.management.base import BaseCommand, CommandError
from django.core.management.color import no_style
from django.db import connections
from allauth.account import app_settings
from allauth.account.models import EmailAddress, EmailConfirmation
class Command(BaseCommand):
def handle(self, *args, **op... |
import errno
import os
import tempfile
from django.conf import settings
from django.contrib.sessions.backends.base import SessionBase, CreateError
from django.core.exceptions import SuspiciousOperation, ImproperlyConfigured
class SessionStore(SessionBase):
"""
Implements a file based session store.
"""
... |
import datetime
import operator
import re
from django.db import models
class LookupQueryEvaluator(object):
evaluators = ()
def __init__(self, rhs):
self.rhs = rhs
def __call__(self, lhs):
rhs = self.cast_rhs(lhs)
lhs = self.cast_lhs(lhs)
return all(evaluator(lhs, rhs) f... |
import json
import six
from base10.base import Dialect, Metric
from base10.exceptions import DialectError
class JSONDialect(Dialect):
"""
{
name: 'cpu_usage',
fields: {
user: 0.2,
free: 0.75
},
metadata: {
hostname: 'host-1'
},
... |
from django.test import TestCase
from django.test.client import Client
from django.contrib.auth.models import User
from django.conf import settings
from django_comment_common.models import (
Role, FORUM_ROLE_ADMINISTRATOR, FORUM_ROLE_MODERATOR, FORUM_ROLE_STUDENT)
from django_comment_common.utils import seed_permis... |
from os import environ
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks
from autobahn.twisted.wamp import ApplicationSession, ApplicationRunner
class Component(ApplicationSession):
"""
Application component that calls procedures which
produce complex results and sho... |
"""Context propagation examples when dealing with multi-threaded
applications.
"""
import threading
from ext import tracer, helpers
def main_thread_instrumented_only():
"""The main thread is instrumented but not its children."""
def do_some_work():
# code executed in children threads; they don't have... |
#!/usr/bin/env python
"""
Commands related to the syncing assets.
"""
from fnmatch import fnmatch
from glob import glob
import os
from fabric.api import prompt, task
import app_config
import utils
@task
def sync(path):
"""
Intelligently synchronize assets between S3 and local folder.
"""
ignore_glo... |
"""Abstract Transport class."""
import sys
_PY34 = sys.version_info >= (3, 4)
__all__ = ['BaseTransport', 'ReadTransport', 'WriteTransport',
'Transport', 'DatagramTransport', 'SubprocessTransport',
]
class BaseTransport:
"""Base class for transports."""
def __init__(self, extra=None)... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
import traceback
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ovirt import (
check_sdk,
create_connection,
get_dict_of_struct,
ovirt_facts... |
import re
import sys
from command import Command
CHANGE_RE = re.compile(r'^([1-9][0-9]*)(?:[/\.-]([1-9][0-9]*))?$')
class Download(Command):
common = True
helpSummary = "Download and checkout a change"
helpUsage = """
%prog {project change[/patchset]}...
"""
helpDescription = """
The '%prog' command download... |
from .core import (
SID_FIELD_NAME,
TS_FIELD_NAME,
)
from zipline.pipeline.common import (
BUYBACK_AMOUNT_FIELD_NAME,
BUYBACK_ANNOUNCEMENT_FIELD_NAME,
BUYBACK_TYPE_FIELD_NAME,
BUYBACK_UNIT_FIELD_NAME,
)
from zipline.pipeline.data import BuybackAuthorizations
from zipline.pipeline.loaders import ... |
# -*- coding: utf-8 -*-
"""The artifact definition."""
from __future__ import unicode_literals
from artifacts import errors
from artifacts import registry
class ArtifactDefinition(object):
"""Artifact definition interface.
Attributes:
conditions (list[str]): conditions.
description (str): description.
... |
# RUN: %{lit} %{inputs}/discovery | FileCheck --check-prefix=CHECK-BASIC %s
# CHECK-BASIC: Testing: 5 tests
# Check that regex-filtering works
#
# RUN: %{lit} --filter 'o[a-z]e' %{inputs}/discovery | FileCheck --check-prefix=CHECK-FILTER %s
# CHECK-FILTER: Testing: 2 of 5 tests
# Check that regex-filtering based on ... |
import copy
import types
from .vendor import six
from .vendor.lexicon import Lexicon
from .config import merge_dicts
from .parser import Context as ParserContext
from .tasks import Task
class Collection(object):
"""
A collection of executable tasks.
"""
def __init__(self, *args, **kwargs):
"... |
"""
Definitions of test cases with various interesting behaviors, to be used by
L{twisted.trial.test.test_tests} and other test modules to exercise different
features of trial's test runner.
See the L{twisted.trial.test.test_tests} module docstring for details about how
this code is arranged.
"""
from __future__ impo... |
"""
Adobe Portable Document Format (PDF) parser.
Author: Christophe Gisquet <<EMAIL>>
"""
from lib.hachoir_parser import Parser
from lib.hachoir_core.field import (
Field, FieldSet,
ParserError,
GenericVector,
UInt8, UInt16, UInt32,
String,
RawBytes)
from lib.hachoir_core.endian import LITTLE_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import re
import sys
import os
import glob
from . import helper
from .mockable_test_result import MockableTestResult
from runner import path_to_enlightenment
from libs.colorama import init, Fore, Style
init() # init colorama
class Sensei(MockableTestResu... |
from airflow.contrib.hooks.wasb_hook import WasbHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
class FileToWasbOperator(BaseOperator):
"""
Uploads a file to Azure Blob Storage.
:param file_path: Path to the file to load.
:type file_path: str
:para... |
import logging
import socket
import threading
import time
logger = logging.getLogger('eBus')
class eBus():
_items = []
def __init__(self, smarthome, host, port, cycle=240):
self._sh = smarthome
self._cycle = int(cycle)
self._sock = False
self.connected = False
self.ho... |
"""Information about mxnet."""
from __future__ import absolute_import
import os
import platform
import logging
def find_lib_path():
"""Find MXNet dynamic library files.
Returns
-------
lib_path : list(string)
List of all found path to the libraries.
"""
lib_from_env = os.environ.get('M... |
#!/usr/bin/env python
from PIL import Image
count = 0
solutions = 0
# Hole sizes.
TINY = 0
SMALL = 1
MEDIUM = 2
LARGE = 3
# Portion of hole.
MAJOR = 4
MINOR = 5
NAMES = ['tiny', 'small', 'medium', 'big', 'major', 'minor']
class Hole:
def __init__(self, size, portion):
self.size = size
self.po... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.