code
stringlengths
1
199k
from telegram import TelegramObject class ReplyMarkup(TelegramObject): pass
""" *************************************************************************** Hillshade.py --------------------- Date : October 2016 Copyright : (C) 2016 by Alexander Bruy Email : alexander dot bruy at gmail dot com ****************************************...
import re def partition(alist, indices): return [alist[i:j] for i, j in zip([0]+indices, indices+[None])] def grep(pattern, filename): """Given a regex *pattern* return the lines in the file *filename* that contains the pattern. """ return greplines(pattern, open(filename)) def greplines(pattern, li...
from django.core.management.base import BaseCommand, CommandError scripts = ['form', 'main', 'overview'] class Command(BaseCommand): args = '<script_name script_name ...>' help = 'Compile JavaScript code' def handle(self, *args, **options): import os if args: for script_name in a...
from markdown import Extension from markdown.inlinepatterns import Pattern from markdown.treeprocessors import Treeprocessor from markdown.util import etree from taiga.front import resolve from taiga.base.utils.slug import slugify import re class WikiLinkExtension(Extension): def __init__(self, project, *args, **kw...
import json import googleapiclient.discovery import six import main def test_get_request_body(): text = 'hello world' body = main.get_request_body(text, syntax=True, entities=True, sentiment=False) assert body.get('document').get('content') == text assert body.get('featu...
active_stream = None class InstructionStream(object): def __init__(self): self.instructions = list() self.previous_stream = None def __enter__(self): global active_stream self.previous_stream = active_stream active_stream = self return self def __exit__(self, ...
from django.conf import settings from django.core.exceptions import ImproperlyConfigured def setting(name, default=None, strict=False): """ Helper function to get a Django setting by name. If setting doesn't exists it can return a default or raise an error if in strict mode. :param name: Name of setting...
from telemetry.page import legacy_page_test from telemetry.timeline import model from telemetry.timeline import tracing_config from telemetry.value import scalar from metrics import power class ImageDecoding(legacy_page_test.LegacyPageTest): def __init__(self): super(ImageDecoding, self).__init__() self._powe...
from django.conf.urls import url from django.contrib.auth import views as django_views from . import views urlpatterns = [ url(r'^login/$', views.login, name='account_login'), url(r'^logout/$', views.logout, name='account_logout'), url(r'^signup/$', views.signup, name='account_signup'), url(r'^password/...
''' System tests for `jenkinsapi.jenkins` module. ''' import re import time try: import unittest2 as unittest except ImportError: import unittest from jenkinsapi_tests.systests.base import BaseSystemTest from jenkinsapi_tests.systests.job_configs import MATRIX_JOB from jenkinsapi_tests.test_utils.random_strings...
""" This module offers a generic date/time string parser which is able to parse most known formats to represent a date and/or time. """ from __future__ import unicode_literals import datetime import string import time import collections from io import StringIO from six import text_type, binary_type, integer_types from ...
from django.conf import settings from django.contrib.auth import authenticate from django.contrib.auth import login from registration import signals from registration.views import RegistrationView as BaseRegistrationView from registration.users import UserModel class RegistrationView(BaseRegistrationView): """ ...
''' Genesis Add-on Copyright (C) 2015 lambda 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. This pr...
import os from cloudinit.settings import PER_ALWAYS from cloudinit import util frequency = PER_ALWAYS def handle(name, cfg, cloud, log, _args): if "bootcmd" not in cfg: log.debug(("Skipping module named %s," " no 'bootcmd' key in configuration"), name) return with util.Extende...
import binascii import time from collections import deque from typing import Any, Deque, Dict, List, Optional, Tuple from .packet import ( PACKET_TYPE_HANDSHAKE, PACKET_TYPE_INITIAL, PACKET_TYPE_MASK, PACKET_TYPE_ONE_RTT, PACKET_TYPE_RETRY, PACKET_TYPE_ZERO_RTT, QuicStreamFrame, QuicTran...
import inspect import os import subprocess import socket import sys import time cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],".."))) if cmd_subfolder not in sys.path: sys.path.insert(0, cmd_subfolder) import mosq_test rc = 1 keepalive = 60...
"""Provides GUI tools to project an object into a Drawing Workbench page. This commands takes a 2D geometrical element and creates a projection that is displayed in a drawing page in the Drawing Workbench. This command should be considered obsolete as the Drawing Workbench is obsolete since 0.17. A similar command is n...
"""Light/LED support for the Skybell HD Doorbell.""" import logging from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_HS_COLOR, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, LightEntity, ) import homeassistant.util.color as color_util from . import DOMAIN as SKYBELL_DOMAIN, SkybellDevice _LOGG...
import math import numpy epsilon = 1e-12 def abs(v1): return numpy.absolute(v1) def norm(v1): """Given vector v1, return its norm. """ v1a = numpy.array(v1) norm = numpy.sqrt(numpy.sum(v1a * v1a)) return norm def normalise_line(p1, p2): """Given two points, return normal vector, magnitude an...
from sympy.combinatorics.free_groups import free_group, FreeGroup from sympy.core import Symbol from sympy.utilities.pytest import raises from sympy import oo F, x, y, z = free_group("x, y, z") def test_FreeGroup__init__(): x, y, z = map(Symbol, "xyz") assert len(FreeGroup("x, y, z").generators) == 3 assert...
""" Encoding Aliases Support This module is used by the encodings package search function to map encodings names to module names. Note that the search function converts the encoding names to lower case and replaces hyphens with underscores *before* performing the lookup. """ aliases = { # Latin-...
import os, sys, re import urllib __all__ = ['expand_uri_template', 'URITemplate'] def expand_uri_template(template, args): """Expand a URI template using the given args dictionary. """ return URITemplate(template).run(args) def _uri_encode_var(v): return urllib.quote(v, safe="-_.~!$&'()*+,;=:/?[]#@") cl...
import os import os.path from os.path import * import stat import re import sys def usage(): print "file-check.py <dir>" print "Must pass in a directory <dir>." exit(1) try: base_dir = sys.argv[1] if not isdir(base_dir): usage() except: usage() MPL_string="You can obtain one at http://mo...
import copy from tempest_lib.common.utils import data_utils from tempest_lib import exceptions from tempest.api.identity import base from tempest import manager from tempest import test class IdentityV3UsersTest(base.BaseIdentityV3Test): @classmethod def resource_setup(cls): super(IdentityV3UsersTest, c...
"""Various utilities used by XenServer plugins.""" import cPickle as pickle import errno import logging import os import shutil import signal import subprocess import tempfile import XenAPIPlugin LOG = logging.getLogger(__name__) CHUNK_SIZE = 8192 class CommandNotFound(Exception): pass def delete_if_exists(path): ...
"""A Python interface for creating TensorFlow servers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.core.protobuf import cluster_pb2 from tensorflow.core.protobuf import tensorflow_server_pb2 from tensorflow.python import pywrap_tensorfl...
from __future__ import absolute_import from collections import defaultdict from tornado import web from tornado import gen from celery import states from ..views import BaseHandler from ..utils.broker import Broker from ..api.control import ControlHandler class Monitor(BaseHandler): @web.authenticated def get(s...
import os import pytest import requests import subprocess import signal from os.path import ( abspath, basename, dirname, exists, join, relpath, split, splitext, ) from tests.plugins.upload_to_s3 import S3_URL from tests.plugins.utils import ( info, ok, red, warn, wri...
__author__ = 'Ruslan Spivak <ruslan.spivak@gmail.com>' class ASTVisitor(object): """Base class for custom AST node visitors. Example: >>> from slimit.parser import Parser >>> from slimit.visitors.nodevisitor import ASTVisitor >>> >>> text = ''' ... var x = { ... "key1": "value1", ...
"""Remove all lines after a given marker line. """ from __future__ import print_function import fileinput import sys def main(args): """Remove lines after marker.""" filename = args[0] marker = args[1] for line in fileinput.input(filename, inplace=1): print(line.rstrip()) if line.startsw...
import functools import imp import importlib import inspect import itertools import logging import os import re import sys import time import unittest import threading from os.path import join as opj import unittest import openerp import openerp.tools as tools import openerp.release as release from openerp.tools.safe_e...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import sys from ansible import constants as C from ansible import context from ansible.cli import CLI from ansible.cli.arguments import option_helpers as opt_help from ansible.errors import AnsibleOptionsError from ansible...
import os import sys from string import Template qrc_template = \ """ <!DOCTYPE RCC><RCC version="1.0"> <qresource> ${filelist} </qresource> </RCC> """ item_template = """ <file>${filename}</file>\n""" def generate(directory, qrc_file): files = [x for x in os.listdir(directory)] files.sort() print >> sys.st...
import re import math import random PREAMBLE = """ """[1:] class CaseGroup: def __init__(self, name, description, children): self.name = name self.description = description self.children = children class ShaderCase: def __init__(self): pass g_processedCases = {} def indentTextBlock(text, indent): indentSt...
"""Tests the graph freezing tool.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import tensorflow as tf from tensorflow.examples.image_retraining import retrain from tensorflow.python.framework import test_util from tensorflow.python.platform i...
"""Resampling dataset transformations.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.data.experimental.ops import batching from tensorflow.python.data.experimental.ops import interleave_ops from tensorflow.python...
"""Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" import os from ...base import (CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, Out...
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class CoinbaseAccount(ProviderAccount): def get_avatar_url(self): return None def to_str(self): return self.account.extra_data.get( 'name', ...
"""Bootstrap setuptools installation If you want to use setuptools in your package's setup.py, just include this file in the same directory with it, and add this to the top of your setup.py:: from ez_setup import use_setuptools use_setuptools() If you want to require a specific version of setuptools, set a down...
"""Tests for qutebrowser.config.configdata.""" import pytest from qutebrowser.config import configdata @pytest.mark.parametrize('sect', configdata.DATA.keys()) def test_section_desc(sect): """Make sure every section has a description.""" desc = configdata.SECTION_DESC[sect] assert isinstance(desc, str) def ...
import os from contextlib import contextmanager from socorro.lib.util import FakeLogger @contextmanager def temp_file_context(raw_dump_path, logger=None): """this contextmanager implements conditionally deleting a pathname at the end of a context if the pathname indicates that it is a temp file by having th...
"""Support for Lutron Caseta fans.""" from __future__ import annotations import logging from pylutron_caseta import FAN_HIGH, FAN_LOW, FAN_MEDIUM, FAN_MEDIUM_HIGH, FAN_OFF from homeassistant.components.fan import DOMAIN, SUPPORT_SET_SPEED, FanEntity from homeassistant.util.percentage import ( ordered_list_item_to_p...
from kombu import Exchange, Queue from st2common.transport import publishers EXECUTION_XCHG = Exchange('st2.execution', type='topic') class ActionExecutionPublisher(publishers.CUDPublisher): def __init__(self, urls): super(ActionExecutionPublisher, self).__init__(urls, EXECUTION_XCHG) def get_queue(name=Non...
import os import os.path as op from io import BytesIO from nose.tools import eq_, ok_ from flask import Flask, url_for from flask.ext.admin import form, helpers def _create_temp(): path = op.join(op.dirname(__file__), 'tmp') if not op.exists(path): os.mkdir(path) inner = op.join(path, 'inner') i...
import unittest import six from six.moves.urllib.parse import urlparse from scrapy.spiders import Spider from scrapy.utils.url import (url_is_from_any_domain, url_is_from_spider, add_http_if_no_scheme, guess_scheme, parse_url) __doctests__ = ['scrapy.utils.url'] class UrlUtilsTest(unittest...
import memory_test_expectations import page_sets from telemetry import benchmark from telemetry.page import page_test from telemetry.core.platform import tracing_category_filter from telemetry.core.platform import tracing_options from telemetry.timeline import counter from telemetry.timeline import model MEMORY_LIMIT_M...
import sys, os sys.path.insert(0, os.path.abspath('..')) import emcee from emcee import __version__ extensions = ['sphinx.ext.autodoc', 'sphinx.ext.mathjax', 'sphinx.ext.viewcode'] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = u'emcee' copyright = u'2012–2013, Dan Foreman-Mackey ...
"""SCons.Tool.lex Tool-specific initialization for lex. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ __revision__ = "src/engine/SCons/Tool/lex.py 2013/03/03 09:48:35 garyo" import os.path import SCons.Action...
import os from Renderer import Renderer from enigma import ePixmap from Tools.Directories import fileExists, SCOPE_SKIN_IMAGE, SCOPE_CURRENT_SKIN, resolveFilename class EGChSelPicon(Renderer): searchPaths = ('/%s/', '/media/usb/%s/', '/media/usb2/%s/', '/media/usb3/%s/', '/media/card/%s/', '/media/cf/%s/', '/etc/%s/',...
""" Bookmarks Python API. """ from django.conf import settings from eventtracking import tracker from xmodule.modulestore.django import modulestore from xmodule.modulestore.exceptions import ItemNotFoundError from . import DEFAULT_FIELDS, OPTIONAL_FIELDS from .models import Bookmark from .serializers import BookmarkSer...
""" Helper methods related to EdxNotes. """ import json import logging from json import JSONEncoder from uuid import uuid4 import requests from datetime import datetime from dateutil.parser import parse as dateutil_parse from opaque_keys.edx.keys import UsageKey from requests.exceptions import RequestException from dja...
"""Test configs for range.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.compat.v1 as tf from tensorflow.lite.testing.zip_test_utils import create_scalar_data from tensorflow.lite.testing.zip_test_utils import make_zip_of_tests from ten...
""" Session Management (from web.py) """ import os, time, datetime, random, base64 import os.path from copy import deepcopy try: import cPickle as pickle except ImportError: import pickle try: import hashlib sha1 = hashlib.sha1 except ImportError: import sha sha1 = sha.new import utils import we...
import sys import time from eventlet import event from eventlet import greenthread from neutron.openstack.common._i18n import _LE, _LW from neutron.openstack.common import log as logging LOG = logging.getLogger(__name__) _ts = lambda: time.time() class LoopingCallDone(Exception): """Exception to break out and stop ...
def before_all(context): setup_python_path() setup_context_with_global_params_test(context) def setup_context_with_global_params_test(context): context.global_name = "env:Alice" context.global_age = 12 def setup_python_path(): # -- NEEDED-FOR: formatter.user_defined.feature import os PYTHON...
""" Provides utility function for generating Sphinx-based documentation. """ from __future__ import absolute_import from behave.textutil import compute_words_maxsize, text as _text import codecs import six class DocumentWriter(object): """ Provides a simple "ReStructured Text Writer" to generate Sphinx-base...
"""Tests for the DeferredRunTest single test execution logic.""" import os import signal from testtools import ( skipIf, TestCase, TestResult, ) from testtools.content import ( text_content, ) from testtools.helpers import try_import from testtools.matchers import ( Equals, KeysEqual, ...
s = f"""foo{'<caret>bar'}baz"""
from collections import defaultdict import os import numpy as np from PIL import Image from pycocotools.coco import COCO from chainer import dataset from chainer.dataset.convert import to_device _bos = 0 _eos = 1 _unk = 2 _ignore = -1 def split(sentence): return sentence.lower().replace('.', ' .').replace(',', ' ,'...
from __future__ import print_function from PIL import Image, _binary try: import builtins except ImportError: import __builtin__ builtins = __builtin__ i32 = _binary.i32le def open(filename): """ Load texture from a Quake2 WAL texture file. By default, a Quake2 standard palette is attached to th...
from . import stock
import urllib from email.Utils import formatdate from django.utils.encoding import smart_str, force_unicode from django.utils.functional import allow_lazy def urlquote(url, safe='/'): """ A version of Python's urllib.quote() function that can operate on unicode strings. The url is first UTF-8 encoded before...
from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import logging import os import re import shutil from hashlib import sha1 from twitter.common.dirutil.fileset import fnmatch_translate_extended from pants.backend.jvm.t...
"""Tests for DenseLayer JIT compilation on the CPU and GPU devices.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import numpy as np from tensorflow.contrib.compiler import jit from tensorflow.core.protobuf import config_pb2 from tensorflow.pyt...
from auto_gen import DBWorkflow as _DBWorkflow from auto_gen import DBAbstraction, DBModule, DBGroup from id_scope import IdScope import copy class DBWorkflow(_DBWorkflow): def __init__(self, *args, **kwargs): _DBWorkflow.__init__(self, *args, **kwargs) self.objects = {} self.tmp_id = IdScop...
import jinja2 from jingo import env, register from access import acl from addons.models import Addon from bandwagon.models import Collection @register.function @jinja2.contextfunction def report_menu(context, request, report, obj=None): """Reports Menu. navigation for the various statistic reports.""" if obj: ...
"""Entry point for vispy's IPython bindings""" from distutils.version import LooseVersion def load_ipython_extension(ipython): """ Entry point of the IPython extension Parameters ---------- IPython : IPython interpreter An instance of the IPython interpreter that is handed over to the ex...
from __future__ import division, absolute_import, print_function import sys import gzip import os import threading from tempfile import NamedTemporaryFile import time import warnings import gc from io import BytesIO from datetime import datetime import numpy as np import numpy.ma as ma from numpy.lib._iotools import Co...
from cms.models.fields import PlaceholderField from cms.utils.compat.dj import python_2_unicode_compatible from django.core.urlresolvers import reverse from django.db import models from mptt.models import MPTTModel @python_2_unicode_compatible class Category(MPTTModel): parent = models.ForeignKey('self', blank=True...
from contextlib import contextmanager import signal @contextmanager def timer(seconds): """Return a timer context manager. If the code within the context does not finish within the given number of seconds, it will raise an AssertionError. """ def _handle_sigalrm(signum, frame): raise A...
import micropython as micropython micropython.opt_level(0) print(micropython.opt_level()) micropython.opt_level(1) print(micropython.opt_level()) micropython.opt_level(0) exec("print(__debug__)") micropython.opt_level(1) exec("print(__debug__)") exec("assert 0")
"""The Query type hierarchy for DBCore. """ from __future__ import (division, absolute_import, print_function, unicode_literals) import re from operator import mul from beets import util from datetime import datetime, timedelta import unicodedata class ParsingError(ValueError): """Abstract c...
""" Open Document Format (ODF) Writer. """ VERSION = '1.0a' __docformat__ = 'reStructuredText' import sys import os import os.path import tempfile import zipfile from xml.dom import minidom import time import re import StringIO import copy import urllib2 import docutils from docutils import frontend, nodes, utils, writ...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = """ module: consul short_description: "Add, modify & delete services within a c...
""" Tests for L{twisted.test.proto_helpers}. """ from zope.interface.verify import verifyObject from twisted.internet.interfaces import (ITransport, IPushProducer, IConsumer, IReactorTCP, IReactorSSL, IReactorUNIX, IAddress, IListeningPort, IConnector) from twisted.internet.address import IPv4Address from twist...
""" ================================== Reading epochs from a raw FIF file ================================== This script shows how to read the epochs from a raw file given a list of events. For illustration, we compute the evoked responses for both MEG and EEG data by averaging all the epochs. """ import mne from mne i...
""" Created on Sep 17, 2010 @author: barthelemy """ from __future__ import unicode_literals, absolute_import from threading import Thread import unittest from py4j.compat import range from py4j.java_gateway import JavaGateway from py4j.tests.java_gateway_test import ( start_example_app_process, sleep) class TestJVM...
"""SQL function API, factories, and built-in functions. """ from . import sqltypes, schema from .base import Executable, ColumnCollection from .elements import ClauseList, Cast, Extract, _literal_as_binds, \ literal_column, _type_from_args, ColumnElement, _clone,\ Over, BindParameter, FunctionFilter from .selec...
"""Email address parsing code. Lifted directly from rfc822.py. This should eventually be rewritten. """ __all__ = [ 'mktime_tz', 'parsedate', 'parsedate_tz', 'quote', ] import time, calendar SPACE = ' ' EMPTYSTRING = '' COMMASPACE = ', ' _monthnames = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul...
"""Test script for the gzip module. """ import unittest from test import test_support import os import io import struct gzip = test_support.import_module('gzip') data1 = """ int length=DEFAULTALLOC, err = Z_OK; PyObject *RetVal; int flushmode = Z_FINISH; unsigned long start_total_out; """ data2 = """/* zlibmodul...
"""Upload server for camlistore. To test: curl -v \ -d camliversion=1 \ http://localhost:8080/camli/stat curl -v -L \ -F sha1-126249fd8c18cbb5312a5705746a2af87fba9538=@./test_data.txt \ <the url returned by stat> curl -v -L \ -F sha1-22a7fdd575f4c3e7caa3a55cc83db8b8a6714f0f=@./test_data.txt \ <the url retur...
"""Tests for initializers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import tensorflow as tf distributions = tf.contrib.distributions class NormalTest(tf.test.TestCase): def testNormalConjugateKnownSigmaPosterior(self): with tf.Sess...
from __future__ import absolute_import, print_function from django.contrib import messages from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from sentry.auth.helper import AuthHelper from sentry.models import AuthProvider, Organization, OrganizationMember from sentry.w...
"""Wrappers for gsutil, for basic interaction with Google Cloud Storage.""" import contextlib import cStringIO import hashlib import logging import os import subprocess import sys import tarfile import urllib2 from telemetry.core import platform from telemetry.util import path PUBLIC_BUCKET = 'chromium-telemetry' PARTN...
DATE_FORMAT = 'j. F Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j. F Y H:i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y H:i' FIRST_DAY_OF_WEEK = 1 # Monday DATE_INPUT_FORMATS = ( '%Y-%m-%d', '%j.%m.%Y', '%j.%m.%y', # '2006-10-25', '25.10.2006', '25.10...
"""Verifies that Google Test warns the user when not initialized properly.""" __author__ = 'wan@google.com (Zhanyong Wan)' import gtest_test_utils import os import sys import unittest IS_WINDOWS = os.name == 'nt' IS_LINUX = os.name == 'posix' if IS_WINDOWS: BUILD_DIRS = [ 'build.dbg\\', 'build.opt\\', ...
ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = ''' --- module: rabbitmq_user short_description: Adds or removes users to RabbitMQ description: - Add or remove users to RabbitMQ and assign permissions version_added: "1.1...
from __future__ import unicode_literals from itertools import chain import types from django.apps import apps from . import Error, Tags, register @register(Tags.models) def check_all_models(app_configs=None, **kwargs): errors = [model.check(**kwargs) for model in apps.get_models() if app_configs is ...
"""Starter script for Nova EC2 API.""" import sys from oslo_config import cfg from oslo_log import log as logging from oslo_reports import guru_meditation_report as gmr from nova import config from nova import objects from nova import service from nova import utils from nova import version CONF = cfg.CONF CONF.import_o...
from __future__ import unicode_literals import datetime import decimal from collections import defaultdict from django.contrib.auth import get_permission_codename from django.core.exceptions import FieldDoesNotExist from django.core.urlresolvers import NoReverseMatch, reverse from django.db import models from django.db...
import sys import warnings from abc import ABCMeta, abstractmethod import numpy as np from scipy import sparse from .base import LinearModel, _pre_fit from ..base import RegressorMixin from .base import center_data, sparse_center_data from ..utils import check_array, check_X_y, deprecated from ..utils.validation import...
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 'AffectedUserByGroup' db.create_table('sentry_affecteduserbygroup', ( ('id', self.gf('sentry.db.models.field...
from test import CollectorTestCase from test import get_collector_config from test import unittest from mock import patch from diamond.collector import Collector from hadoop import HadoopCollector import os class TestHadoopCollector(CollectorTestCase): def setUp(self): config = get_collector_config('HadoopC...
"""Identity bijector.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import constant_op from tensorflow.python.ops.distributions import bijector from tensorflow.python.util import deprecation __all__ = [ "Identity", ] ...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import time from ansible import constants as C from ansible.errors import AnsibleError from ansible.playbook.included_file import IncludedFile from ansible.plugins import action_loader from ansible.plugins.strategy import StrategyBa...
from __future__ import unicode_literals import frappe from frappe.model.document import Document class AssetCategoryAccount(Document): pass
class Yuck: def __init__(self): self.i = 0 def make_dangerous(self): self.i = 1 def __hash__(self): # direct to slot 4 in table of size 8; slot 12 when size 16 return 4 + 8 def __eq__(self, other): if self.i == 0: # leave dict alone pass ...
import logging from ryu.lib.mac import haddr_to_str LOG = logging.getLogger('ryu.controller.mac_to_port') class MacToPortTable(object): """MAC addr <-> (dpid, port name)""" def __init__(self): super(MacToPortTable, self).__init__() self.mac_to_port = {} def dpid_add(self, dpid): LOG....
try: import cPickle as pickle except ImportError: import pickle from django.conf import settings from django.utils.hashcompat import md5_constructor from django.forms import BooleanField def security_hash(request, form, *args): """ Calculates a security hash for the given Form instance. This creates...