content string |
|---|
from django.conf import settings
from django.core.cache import cache
import cronjobs
import feedparser
from bedrock.mozorg.models import TwitterCache
from bedrock.mozorg.util import get_tweets
@cronjobs.register
def update_feeds():
for name, url in settings.FEEDS.items():
feed_info = feedparser.parse(ur... |
import unittest
import tagfs.freebase_support as freebase_support
class WhenQueryWithOneFilerAndOneSelector(unittest.TestCase):
def setUp(self):
super(WhenQueryWithOneFilerAndOneSelector, self).setUp()
self.query = freebase_support.Query({'filter': 'filterValue', 'selector': None, })
def tes... |
"""
This module parse an UPnP device's XML definition in an Object.
@author: Raphael Slinckx
@copyright: Copyright 2005
@license: LGPL
@contact: U{<EMAIL><mailto:<EMAIL>>}
@version: 0.1.0
"""
__revision__ = "$id"
from xml.dom import minidom
import logging
# Allowed UPnP services to use when mapping ports/external a... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['stableinterface'],
'supported_by': 'curated'}
from ansible.module_utils.basic import *
from ansible.module_utils.ec2 import *
try:
import boto.ec2.autoscale
from boto.ec2.autoscale import ScalingPolicy
from... |
"""
======================================
Decision Tree Regression with AdaBoost
======================================
A decision tree is boosted using the AdaBoost.R2 [1] algorithm on a 1D
sinusoidal dataset with a small amount of Gaussian noise.
299 boosts (300 decision trees) is compared with a single decision tr... |
import res_country
import res_lang
import res_partner
import res_bank
import res_config
import res_currency
import res_font
import res_company
import res_users
import res_request
import res_lang
import ir_property
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
#!/usr/bin/env python
"""
Usage:
find-package.py --repourl=<repo-url> --package=<package-name> [--env|--iam] [--debug] [--filter=<filter>]
Attributes:
--repourl=<repourl> -r Repository URL eg. https://BUCKET_NAME.s3.amazonaws.com/cent6/
--package=<package-name> -p Package name to search for... |
import re
from supybot.commands import *
import supybot.plugins as plugins
import supybot.ircutils as ircutils
class Lart(plugins.ChannelIdDatabasePlugin):
_meRe = re.compile(r'\bme\b', re.I)
_myRe = re.compile(r'\bmy\b', re.I)
def _replaceFirstPerson(self, s, nick):
s = self._meRe.sub(nick, s)
... |
#!/usr/bin/python
"""
Handler for setting radius on the request.
"""
## MIT License
##
## Copyright (c) 2017, krishna bhogaonker
## 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 re... |
"""Contains layer utilies for input validation and format conversion.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.ops import variables
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.framework import s... |
from django.core.management.base import BaseCommand, CommandError
from django.db import DEFAULT_DB_ALIAS, connections
class Command(BaseCommand):
help = ("Runs the command-line client for specified database, or the "
"default database if none is provided.")
requires_system_checks = False
def add... |
"""Tests for baseline.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import shutil
import tempfile
import numpy as np
import six
from tensorflow.contrib.estimator.python.estimator import baseline
from tensorflow.contrib.estimator.python.... |
from __future__ import absolute_import
from __future__ import division
import math
from p2pool.util import math as math2
class DataViewDescription(object):
def __init__(self, bin_count, total_width):
self.bin_count = bin_count
self.bin_width = total_width/bin_count
def _shift(x, shift, pad_item... |
from __future__ import unicode_literals
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
from shuup.admin.utils.picotable import ChoicesFilter, Column, TextFilter
from shuup.admin.utils.views import PicotableListView
from shuup.core.models import Category, Product, ProductMode
... |
#!/usr/bin/env python
import sys
import time
import Queue
import traceback
import multiprocessing
from ansible.inventory import Inventory
from ansible.inventory.host import Host
from ansible.playbook.play import Play
from ansible.playbook.task import Task
from ansible.executor.connection_info import ConnectionInforma... |
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from setuptools import setup
from common_setup import common_setup
classifiers = [
'License :: OSI Approved :: MIT License',
'Development Status :: 5 - Production/Stable',
'Topic :: Software Development :: Libraries',
'To... |
"""
Link extractor based on lxml.html
"""
import re
from six.moves.urllib.parse import urlparse, urljoin
import lxml.etree as etree
from scrapy.selector import Selector
from scrapy.link import Link
from scrapy.utils.misc import arg_to_iter
from scrapy.utils.python import unique as unique_list, str_to_unicode
from sc... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.clou... |
"""
Cross-platform color text printing
Based on colorama (see pyqtgraph/util/colorama/README.txt)
"""
import sys, re
from .colorama.winterm import WinTerm, WinColor, WinStyle
from .colorama.win32 import windll
from ..python2_3 import basestring
_WIN = sys.platform.startswith('win')
if windll is not None:
winterm... |
import socket
import time
import httplib
from urllib import urlencode
from threading import Lock, Event
from django.conf import settings
from django.core.cache import cache
from graphite.node import LeafNode, BranchNode
from graphite.intervals import Interval, IntervalSet
from graphite.readers import FetchInProgress
fr... |
"""
Continuous to discrete transformations for state-space and transfer function.
"""
from __future__ import division, print_function, absolute_import
# March 29, 2011
import numpy as np
from scipy import linalg
from .ltisys import tf2ss, ss2tf, zpk2ss, ss2zpk
__all__ = ['cont2discrete']
def cont2discrete(sys, dt... |
from datetime import date
from django.conf import settings
from django.utils import six
from django.utils.crypto import constant_time_compare, salted_hmac
from django.utils.http import base36_to_int, int_to_base36
class PasswordResetTokenGenerator(object):
"""
Strategy object used to generate and check token... |
#!/usr/bin/env python
# coding: utf-8
from __future__ import unicode_literals
# Allow direct execution
import os
import sys
import unittest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from test.helper import get_params, try_rm
import io
import xml.etree.ElementTree
import youtu... |
import time
import random
import heapq
import itertools
import signal
choice = random.choice
now = time.time
count = itertools.count().next
pop = heapq.heappop
from twisted.internet import defer, task, error
from twisted.python import log, failure
from contrib.procpools.ampoule import commands, main
try:
DIE = s... |
#!/usr/bin/env python
# This will create golden files in a directory passed to it.
# A Test calls this internally to create the golden files
# So it can process them (so we don't have to checkin the files).
# Ensure msgpack-python and cbor are installed first, using:
# sudo apt-get install python-dev
# sudo apt-g... |
"""Append text to an option.
Usage:
append_to_option.py DELIMITER OPTION APPEND_STRING OPTION_STRING
For example, running
append_to_option.py , --jars myproject.jar --option1 value1 --jars otherproject.jar --option2 value2
will write to stdout
--option1 value1 --jars otherproject.jar,myproject.jar --o... |
from __future__ import print_function
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version... |
import sqlalchemy as sa
from .exc import ClassNotVersioned
from .expression_reflector import VersionExpressionReflector
from .operation import Operation
from .table_builder import TableBuilder
from .utils import adapt_columns, version_class, option
class RelationshipBuilder(object):
def __init__(self, versioning... |
from __future__ import division, print_function, absolute_import
import warnings
import numpy as np
from numpy import cos, sin, pi
from numpy.testing import TestCase, run_module_suite, assert_equal, \
assert_almost_equal, assert_allclose, assert_
from scipy.integrate import (quadrature, romberg, romb, newton_cote... |
from a10sdk.common.A10BaseClass import A10BaseClass
class DebugMonitor(A10BaseClass):
""" :param action: {"optional": true, "enum": ["create", "import", "export", "copy", "rename", "check", "replace", "delete"], "type": "string", "description": "'create': create; 'import': import; 'export': export; 'copy'... |
#!/usr/bin/python3
# This file is for preprocessing gcode and the new G29 Autobedleveling from Marlin
# It will analyse the first 2 Layer and return the maximum size for this part
# After this it will replace with g29_keyword = ';MarlinG29Script' with the new G29 LRFB
# the new file will be created in the same folder.... |
"""Support for BMW car locks with BMW ConnectedDrive."""
import logging
from bimmer_connected.state import LockState
from homeassistant.components.lock import LockEntity
from homeassistant.const import STATE_LOCKED, STATE_UNLOCKED
from . import DOMAIN as BMW_DOMAIN, BMWConnectedDriveBaseEntity
from .const import CON... |
import inspect
import os
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
DEFAULT_DB_ALIAS = 'default'
# Define some exceptions that mirror the PEP249 interface.
# We will rethrow any backend-specific errors using these
# common... |
#!/usr/bin/env python3
#
# Given Python's versioning history I'm going with `python3`.
#
# Usage:
# - `python3 -m venv venv`
# - `bash`
# - `source venv/bin/activate`
# - `pip install --upgrade pip`
# - `pip install -r requirements.txt`
# - `./generate-repo-files.py auth-41`
# Modules
import argparse
import subproces... |
"""Samba Python tests."""
import os
import ldb
import samba
import samba.auth
from samba import param
from samba.samdb import SamDB
from samba import credentials
import subprocess
import sys
import tempfile
import unittest
try:
from unittest import SkipTest
except ImportError:
class SkipTest(Exception):
... |
import os
import os.path
import re
from unittest import mock
from testtools.matchers import Contains, Equals
import snapcraft
from snapcraft.plugins import catkin_tools
from tests import unit
class CatkinToolsPluginBaseTestCase(unit.TestCase):
def setUp(self):
super().setUp()
class props:
... |
from peewee import *
from peewee import Using
from playhouse.read_slave import ReadSlaveModel
from playhouse.tests.base import database_initializer
from playhouse.tests.base import ModelTestCase
queries = []
def reset():
global queries
queries = []
class QueryLogDatabase(SqliteDatabase):
name = ''
... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: win_unzip
version_added: "2.0"
short_description: Unzips compressed files and archives on the Windows node
description:
- Unzips compressed files ... |
#! /usr/bin/env python
macros = [\
"slits.C",
"write_ntuple_to_file_advanced.C",
"write_ntuple_to_file.C",
"write_to_file.C",
"ExampleMacro.C",
"ExampleMacro_GUI.C",
"makeMySelector.C",
"RunMySelector.C",
"macro1.C",
"macro2.C",
"macro3.C",
"macro4.C",
"macro5.C",
"macro6.C",
"macro7.C",
"macro8.C",
"macro9.C",
"read_... |
from datetime import datetime, timedelta
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
class sale_order_dates(osv.osv):
"""Add several date fields to Sale Orders, computed or user-entered"""
_inherit = 'sale.order'
def _... |
# ASN.1 named integers
from pyasn1 import error
__all__ = [ 'NamedValues' ]
class NamedValues:
def __init__(self, *namedValues):
self.nameToValIdx = {}; self.valToNameIdx = {}
self.namedValues = ()
automaticVal = 1
for namedValue in namedValues:
if isinstance(na... |
"""Provides an interface for interaction with the encrypted sqlite database"""
from cryptolock.Database import Database
from cryptolock.security import encrypt, decrypt, ensure_key_validity
from cryptolock.exceptions import DocumentNotFoundException
from config import DB_NAME
class SecureDatabase(object):
"""Inte... |
from __future__ import unicode_literals, print_function
import frappe.utils
from collections import defaultdict
from rq import Worker, Connection
from frappe.utils.background_jobs import get_redis_conn, get_queue, get_queue_list
from frappe.utils.scheduler import is_scheduler_disabled
from six import iteritems
def ge... |
r"""
Random walks
============
Probability of a random walker to be on any given vertex after a given number
of steps starting from a given distribution.
"""
# sphinx_gallery_thumbnail_number = 2
import numpy as np
from scipy import sparse
from matplotlib import pyplot as plt
import pygsp as pg
N = 7
steps = [0, 1,... |
import logging
from celery import task
from celery_utils.persist_on_failure import LoggedPersistOnFailureTask
from django.conf import settings
from opaque_keys.edx.keys import CourseKey
from xmodule.modulestore.django import modulestore
from openedx.core.djangoapps.content.course_overviews.models import CourseOvervi... |
# -*- coding: utf-8 -*-
import bson
from modularodm import fields, Q
from modularodm.exceptions import ModularOdmException
from framework.mongo import StoredObject
from website.conferences.exceptions import ConferenceError
DEFAULT_FIELD_NAMES = {
'submission1': 'poster',
'submission2': 'talk',
'submissio... |
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from datetime import datetime
from ansible.plugins.callback import CallbackBase
class CallbackModule(CallbackBase):
"""
This callback module tells you how long your plays ran for.
"""
... |
import optparse
import os
import sys
from os.path import join as joinpath
import m5
from m5.defines import buildEnv
from m5.objects import *
from m5.util import addToPath, fatal
def getTestFilename(test_location):
file_chop_index = test_location.find('tests/')
if file_chop_index <= 0:
fatal('test_file... |
"""Cache lines from files.
This is intended to read lines from modules imported -- hence if a filename
is not found, it will look down the module search path for a file by
that name.
"""
import sys
import os
import tokenize
__all__ = ["getline", "clearcache", "checkcache"]
def getline(filename, lineno, module_globa... |
import pytest
from cfme import test_requirements
from cfme.infrastructure.provider import InfraProvider
from cfme.markers.env_markers.provider import ONE_PER_CATEGORY
from cfme.utils.appliance.implementations.ui import navigate_to
pytestmark = [
pytest.mark.long_running,
pytest.mark.provider(classes=[InfraPro... |
import HandRankings as Hand
from deuces.deuces import Card, Evaluator
class GameData:
def __init__(self, name, opponent_name, stack_size, bb):
# match stats
self.name = name
self.opponent_name = opponent_name
self.starting_stack_size = int(stack_size)
self.num_hands = 0
... |
from flask import Flask, render_template, request, jsonify, Response, abort, session, stream_with_context, redirect, g
from ast import literal_eval
import subprocess
import re
import requests
import json
import shutil
import time
import os
import sqlite3
import logging
import sys
import commands
import threading
minig... |
"""Tests for sync_replicas_optimizer.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import portpicker
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import ops
from tensorflow.python.ops import var... |
"""Run the first page of one benchmark for every module.
Only benchmarks that have a composable measurement are included.
Ideally this test would be comprehensive, however, running one page
of every benchmark would run impractically long.
"""
import os
import unittest
from telemetry import benchmark as benchmark_mod... |
import struct
import dns.exception
import dns.dnssec
import dns.rdata
_flags_from_text = {
'NOCONF': (0x4000, 0xC000),
'NOAUTH': (0x8000, 0xC000),
'NOKEY': (0xC000, 0xC000),
'FLAG2': (0x2000, 0x2000),
'EXTEND': (0x1000, 0x1000),
'FLAG4': (0x0800, 0x0800),
'FLAG5': (0x0400, 0x0400),
'US... |
"""Presubmit script for changes affecting chrome/browser/vr
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into depot_tools.
"""
import re
# chrome/PRESUBMIT.py blocks several linters due to the infeasibility of
# enforcing them on a large c... |
from __future__ import absolute_import
import time
import os
from . import (LockBase, LockFailed, NotLocked, NotMyLock, LockTimeout,
AlreadyLocked)
class LinkLockFile(LockBase):
"""Lock access to a file using atomic property of link(2).
>>> lock = LinkLockFile('somefile')
>>> lock = Link... |
"""check for signs of poor design"""
import re
from collections import defaultdict
from astroid import Function, If, InferenceError
from pylint.interfaces import IAstroidChecker
from pylint.checkers import BaseChecker
from pylint.checkers.utils import check_messages
# regexp for ignored argument name
IGNORED_ARGUME... |
"""
v2 Neutron Plug-in API specification.
:class:`NeutronPluginBaseV2` provides the definition of minimum set of
methods that needs to be implemented by a v2 Neutron Plug-in.
"""
import abc
import six
@six.add_metaclass(abc.ABCMeta)
class NeutronPluginBaseV2(object):
@abc.abstractmethod
def create_subnet(s... |
"""Kerberos authentication module"""
import logging
import os
from functools import wraps
from socket import getfqdn
import kerberos
# noinspection PyProtectedMember
from flask import Response, _request_ctx_stack as stack, g, make_response, request # type: ignore
from requests_kerberos import HTTPKerberosAuth
from a... |
from __future__ import unicode_literals, division, absolute_import
import logging
import urllib2
import httplib
import socket
from flexget import plugin
from flexget.event import event
log = logging.getLogger('spy_headers')
class CustomHTTPConnection(httplib.HTTPConnection):
def __init__(self, *args, **kwargs)... |
import stock_location
import invoice_mod
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
import json
import socket
import logging
from testfixtures import LogCapture
from twisted.internet import defer
from twisted.trial.unittest import TestCase
from scrapy.http import Request
from scrapy.crawler import CrawlerRunner
from scrapy.utils.python import to_unicode
from tests import mock
from tests.spiders impo... |
"""
NaiveBayes Example.
Usage:
`spark-submit --master local[4] examples/src/main/python/mllib/naive_bayes_example.py`
"""
from __future__ import print_function
import shutil
from pyspark import SparkContext
# $example on$
from pyspark.mllib.classification import NaiveBayes, NaiveBayesModel
from pyspark.mllib.util... |
from __future__ import absolute_import, division, unicode_literals
from . import _base
class Filter(_base.Filter):
def __init__(self, source, encoding):
_base.Filter.__init__(self, source)
self.encoding = encoding
def __iter__(self):
state = "pre_head"
meta_found = (self.enco... |
#!/usr/bin/python
'''
Copyright 2013 Google Inc.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
'''
'''
Gathers diffs between 2 JSON expectations files, or between actual and
expected results within a single JSON actual-results file,
and generates an old-vs-new diff... |
import re
import sys
import os
from .ansi import AnsiFore, AnsiBack, AnsiStyle, Style
from .winterm import WinTerm, WinColor, WinStyle
from .win32 import windll, winapi_test
winterm = None
if windll is not None:
winterm = WinTerm()
def is_stream_closed(stream):
return not hasattr(stream, 'closed') or strea... |
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
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 a... |
from hamcrest.core.base_matcher import BaseMatcher
IGNORED = object()
class MetricStructuredNameMatcher(BaseMatcher):
"""Matches a MetricStructuredName."""
def __init__(self,
name=IGNORED,
origin=IGNORED,
context=IGNORED):
"""Creates a MetricsStructuredNameMatcher... |
#!/usr/bin/env python
from __future__ import print_function
import argparse
import subprocess
import sys
import os
import numpy as np
from scipy.io import netcdf
##########################################################################
# FUNCTIONS
###################################################################... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
lasnoise.py
---------------------
Date : September 2013 and May 2016
Copyright : (C) 2013 by Martin Isenburg
Email : martin near rapidlasso point com
***... |
from flask.ext.security import Security, SQLAlchemyUserDatastore
from flask.ext.social import Social, SQLAlchemyConnectionDatastore
from logging.handlers import SMTPHandler
import logging
def init_error_logger_with_email_handler(app):
"""
Initialize a logger to send emails on error-level messages.
Unhandl... |
from libcloud.common.base import ConnectionKey, JsonResponse
__all__ = [
'API_HOST',
'BuddyNSException',
'BuddyNSResponse',
'BuddyNSConnection'
]
# Endpoint for buddyns api
API_HOST = 'www.buddyns.com'
class BuddyNSResponse(JsonResponse):
errors = []
objects = []
def __init__(self, res... |
# -*- coding: utf-8 -*-
"""
$Id: GCodeExporter.py 1092 2011-06-13 14:40:56Z sumpfralle $
Copyright 2010-2011 Lars Kruse <<EMAIL>>
Copyright 2008-2009 Lode Leroy
This file is part of PyCAM.
PyCAM is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published ... |
from augeas import Augeas
from Cheetah.Template import Template
import os
import subprocess
import components
import pykolab
from pykolab import utils
from pykolab.constants import *
from pykolab.translate import _
log = pykolab.getLogger('pykolab.setup')
conf = pykolab.getConf()
def __init__():
components.reg... |
"""
Tests to cover bulk create and update using serializers.
"""
from __future__ import unicode_literals
from django.test import TestCase
from rest_framework import serializers
class BulkCreateSerializerTests(TestCase):
"""
Creating multiple instances using serializers.
"""
def setUp(self):
c... |
from boto.exception import BotoServerError
class InvalidGrantTokenException(BotoServerError):
pass
class DisabledException(BotoServerError):
pass
class LimitExceededException(BotoServerError):
pass
class DependencyTimeoutException(BotoServerError):
pass
class InvalidMarkerException(BotoServerE... |
"""
Created on Mar 10, 2014
@author: jtaghiyar
"""
import os
import subprocess as sub
from kronos_version import kronos_version
from utils import Pipeline
from helpers import make_dir, Configurer
from workflow_manager import WorkFlow, WorkFlowManager
from plumber import Plumber
from string import Template
from tempfi... |
#!/usr/bin/python
import sys,os
import idl
(TYPE_DEFBOOL, TYPE_BOOL, TYPE_INT, TYPE_UINT, TYPE_STRING, TYPE_ARRAY, TYPE_AGGREGATE) = range(7)
def py_type(ty):
if ty == idl.bool:
return TYPE_BOOL
if ty.typename == "libxl_defbool":
return TYPE_DEFBOOL
if isinstance(ty, idl.Enumeration):
... |
"""
***************
Graphviz AGraph
***************
Interface to pygraphviz AGraph class.
Examples
--------
>>> G=nx.complete_graph(5)
>>> A=nx.to_agraph(G)
>>> H=nx.from_agraph(A)
See Also
--------
Pygraphviz: http://networkx.lanl.gov/pygraphviz
"""
# Copyright (C) 2004-2012 by
# Aric Hagberg <<EMAIL>>
# D... |
# -*- coding: utf-8 -*-
"""
pygments.styles.emacs
~~~~~~~~~~~~~~~~~~~~~
A highlighting style for Pygments, inspired by Emacs.
:copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.style import Style
from pygments.token import ... |
# -*- coding: utf-8 -*- # need this line because test utf-8 strings later
import os
import collections
from test.unit_tests.providers import common
from test.unit_tests.providers.common import ProviderTestCase
from totalimpact.providers.provider import Provider, ProviderContentMalformedError
from test.utils import s... |
import zipfile
from io import BytesIO
from django.conf import settings
from django.http import HttpResponse
from django.template import loader
def compress_kml(kml):
"Returns compressed KMZ from the given KML string."
kmz = BytesIO()
zf = zipfile.ZipFile(kmz, 'a', zipfile.ZIP_DEFLATED)
zf.writestr('d... |
import sys
import os
import re
import getopt
import glob
import json
import math
import sqlite3
import time
def file_put_json(dbname, d):
jstr = json.dumps(d, indent=4)
f = open(dbname, 'w', encoding='utf-8')
f.write(jstr)
f.close()
def file_get_json(dbname):
f = open(dbname, 'r', encoding='utf-8'... |
#!/usr/bin/env python3
import os
import sys
import time
import json
import shutil
import subprocess
from oeqa.oetest import oeRuntimeTest
from oeqa.utils.decorators import tag
class BlenoTest(oeRuntimeTest):
cleanup = False
bleno_prefix_dir = '/home/root'
def setUp(self):
'''
Insta... |
"""EDNS Options"""
NSID = 3
class Option(object):
"""Base class for all EDNS option types.
"""
def __init__(self, otype):
"""Initialize an option.
@param rdtype: The rdata type
@type rdtype: int
"""
self.otype = otype
def to_wire(self, file):
"""Conver... |
import copy
import os.path
from neutron import context
from neutron import policy
from neutron.api import extensions
from neutron.api.v2 import attributes
from neutron.tests import base
TEST_PATH = os.path.dirname(os.path.abspath(__file__))
class APIPolicyTestCase(base.BaseTestCase):
"""
Tests for REST AP... |
from __future__ import absolute_import
__all__ = ['RoleFeatures',
'RoleBrokerFeatures',
'RoleSubscriberFeatures',
'RolePublisherFeatures',
'RoleDealerFeatures',
'RoleCallerFeatures',
'RoleCalleeFeatures',
'ROLE_NAME_TO_CLASS']
import json, ... |
#!/usr/bin/env python
from __future__ import print_function
import hashlib
import sys
import simplejson as json
from docker_registry.core import exceptions
import docker_registry.storage as storage
store = storage.load()
images_cache = {}
ancestry_cache = {}
dry_run = True
def warning(msg):
print('# Warning... |
from __future__ import unicode_literals
import unittest
import tempfile
import shutil
import os
from glob import glob
from preupg.xmlgen.compose import XCCDFCompose, ComposeXML
from preupg.utils import FileHelper
from preupg import settings
try:
import base
except ImportError:
import tests.base as base
FOO_D... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import json
from ansible.module_utils.basic import AnsibleModule
class ImageFacts(object)... |
import logging
from celery import chain, shared_task
from instanotifier.fetcher.main import fetch
from instanotifier.parser.main import parse_and_save
from instanotifier.publisher.tasks import publish
from instanotifier.feedsource.models import FeedSource
@shared_task
def consume_feed(feedsource_pk):
feed_sourc... |
import sys
import subprocess
import os
import traceback
import signal
from zulip import RandomExponentialBackoff
def die(signal, frame):
# We actually want to exit, so run os._exit (so as not to be caught and restarted)
os._exit(1)
signal.signal(signal.SIGINT, die)
args = [os.path.join(os.path.dirname(sys.ar... |
"""
==============
phantom_import
==============
Sphinx extension to make directives from ``sphinx.ext.autodoc`` and similar
extensions to use docstrings loaded from an XML file.
This extension loads an XML file in the Pydocweb format [1] and
creates a dummy module that contains the specified docstrings. This
can be ... |
import unittest
from django.test import TransactionTestCase
from django.contrib.contenttypes.models import ContentType
from cities_light.models import Country, City
from gfk_autocomplete.forms import TaggedItemForm
from optionnal_gfk_autocomplete.forms import OptionnalTaggedItemForm
import autocomplete_light
clas... |
from boto.exception import JSONResponseError
from boto.opsworks import connect_to_region, regions, RegionInfo
from boto.opsworks.layer1 import OpsWorksConnection
from tests.compat import unittest
class TestOpsWorksConnection(unittest.TestCase):
opsworks = True
def setUp(self):
self.api = OpsWorksConn... |
# -*- coding: utf-8 -*-
# __
# /__) _ _ _ _ _/ _
# / ( (- (/ (/ (- _) / _)
# /
"""
Requests HTTP library
~~~~~~~~~~~~~~~~~~~~~
Requests is an HTTP library, written in Python, for human beings. Basic GET
usage:
>>> import requests
>>> r = requests.get('https://www.python.org')
>>> ... |
# -*- coding: utf-8 -*-
"""
pygments.styles.manni
~~~~~~~~~~~~~~~~~~~~~
A colorful style, inspired by the terminal highlighting style.
This is a port of the style used in the `php port`_ of pygments
by Manni. The style is called 'default' there.
:copyright: 2006-2007 by Armin Ronacher, Manni ... |
import errno
import logging
import os
from ConfigParser import NoSectionError, NoOptionError
log = logging.getLogger('gitosis.gitdaemon')
from gitosis import util
def export_ok_path(repopath):
p = os.path.join(repopath, 'git-daemon-export-ok')
return p
def allow_export(repopath):
p = export_ok_path(rep... |
"""Runs various libyuv tests through valgrind_test.py.
This script inherits the chrome_tests.py in Chrome, but allows running any test
instead of only the hard-coded ones. It uses the -t cmdline flag to do this, and
only supports specifying a single test for each run.
Suppression files:
The Chrome valgrind directory ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.