content stringlengths 4 20k |
|---|
from math import tanh
from pysqlite2 import dbapi2 as sqlite
def dtanh(y):
#this effectively creates a smaller change multiplier when the value is closest to 0 (when the slope is steepest) P_D controller?
return 1.0-y*y
class SearchNet:
def __init__(self, dbname):
self.con = sqlite.connect(dbname)
def __del__(... |
import datetime, json, urllib2, os, errno, requests
# Open/create file, deleting info already in it so that we can make fresh info
file_name = open('data/311.json', 'w')
issues = []
working = {'issues':issues}
data = {}
# Get date in the past to start
start_date = (datetime.datetime.today() + datetime.timedelta(-180... |
# pylint: skip-file
# flake8: noqa
# pylint: disable=too-many-instance-attributes
class StorageClassConfig(object):
''' Handle service options '''
# pylint: disable=too-many-arguments
def __init__(self,
name,
provisioner,
parameters=None,
... |
from distutils.core import setup
import py2exe
setup(
console = [{
'script': 'izpack2jnlp.py',
'icon_resources': [(0, 'app.ico')]
}],
script_args=['py2exe', '--bundle-files', '1']
) |
from Kamaelia.UI.Tk.TkWindow import TkWindow
from Kamaelia.Support.Tk.Scrolling import ScrollingMenu
from Axon.Ipc import producerFinished, shutdownMicroprocess
import Tkinter
import pprint
class ArgumentsPanel(Tkinter.Frame):
def __init__(self, parent, theclass):
Tkinter.Frame.__init__(self, parent)
... |
from flask_wtf import Form
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, Email, Length
class SignupForm(Form):
first_name = StringField('First name', validators=[DataRequired("Please enter your first name.")])
last_name = StringField('Last name', validato... |
# -*- encoding: utf-8 -*-
'''HTTPHandler that supports a callback method for progress reports.
'''
import urllib2
import httplib
import logging
__all__ = ['urlopen']
logging.basicConfig()
LOG = logging.getLogger(__name__)
progress_callback = None
class ReportingSocket(object):
'''Wrapper around a socket. Give... |
from setuptools import setup, find_packages
VERSION = '0.6.0'
AUTHOR = 'Antoine Mercadal'
MAIL = '<EMAIL>'
URL = 'http://archipelproject.org'
LICENSE = 'AGPL'
NAME = 'archipel-agent-vmparking'
SHORTDESCRIPTION = "Handle the virtual ... |
"""Calculates the "intersection" of two unified diffs.
Given two diffs, A and B, it finds all hunks in B that had non-context lines
in A and prints them to stdout. This is useful to determine the hunks in B that
are relevant to A. The resulting file can be applied with patch(1) on top of A.
"""
__author__ = "<EMAIL>"... |
"""Unit tests for host collections.
:Requirement: Hostcollection
:CaseAutomation: Automated
:CaseLevel: Acceptance
:CaseComponent: HostCollections
:Assignee: swadeley
:TestType: Functional
:CaseImportance: High
:Upstream: No
"""
from random import choice
from random import randint
import pytest
from broker imp... |
from setuptools import setup, find_packages
from chamber.version import get_version
setup(
name='django-chamber',
version=get_version(),
description='Utilities library meant as a complement to django-is-core.',
author='Lubos Matl, Oskar Hollmann',
author_email='<EMAIL>, <EMAIL>',
url='http://... |
"""A generic class to build line-oriented command interpreters.
Interpreters constructed with this class obey the following conventions:
1. End of file on input is processed as the command 'EOF'.
2. A command is parsed out of each line by collecting the prefix composed
of characters in the identchars member.
3. A ... |
"""
@author: Jonah Haefner and Lane Carasik
Title: master_example.py
The purpose of this script is to ensure the four functions included in this package are functioning properly and as an example of use for the user.
It currently only provides checks for the inline geometry with the fluid at a Reynolds number ... |
import sys
from AbstractPatching import AbstractPatching
sys.path.append('../patch')
class FakePatching(AbstractPatching):
def __init__(self, hutil=None):
super(FakePatching,self).__init__(hutil)
self.pkg_query_cmd = 'dpkg-query -L'
self.gap_between_stage = 20
self.download_durat... |
"""Tests for specs-related summarization functions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.contrib.specs.python import specs
from tensorflow.contrib.specs.python import summaries
from tensorflow.python.framewo... |
"""Tests for gjslint --nostrict.
Tests errors that can be thrown by gjslint when not in strict mode.
"""
import os
import sys
import unittest
import gflags as flags
import unittest as googletest
from closure_linter import errors
from closure_linter import runner
from closure_linter.common import filetestcase
_RE... |
# -*- coding: utf-8 -*-
from __future__ import division, print_function, absolute_import
from numpy import abs, sum, cos, pi
from .go_benchmark import Benchmark
class YaoLiu04(Benchmark):
r"""
Yao-Liu 4 objective function.
This class defines the Yao-Liu function 4 [1]_ global optimization problem. This... |
from PyQt4.QtCore import QCoreApplication, QSettings
def chunks(l, n):
for i in xrange(0, len(l), n):
yield l[i:i+n]
QCoreApplication.setOrganizationName( "QGIS" )
QCoreApplication.setOrganizationDomain( "qgis.org" )
QCoreApplication.setApplicationName( "QGIS2" )
s = QSettings()
ba = s.value... |
"""Validation tests for master handler."""
import sys
import unittest
from pinball.master.master_handler import MasterHandler
from pinball.master.thrift_lib.ttypes import ArchiveRequest
from pinball.master.thrift_lib.ttypes import GroupRequest
from pinball.master.thrift_lib.ttypes import ModifyRequest
from pinball.mas... |
data = (
'Guo ', # 0x00
'Yin ', # 0x01
'Hun ', # 0x02
'Pu ', # 0x03
'Yu ', # 0x04
'Han ', # 0x05
'Yuan ', # 0x06
'Lun ', # 0x07
'Quan ', # 0x08
'Yu ', # 0x09
'Qing ', # 0x0a
'Guo ', # 0x0b
'Chuan ', # 0x0c
'Wei ', # 0x0d
'Yuan ', # 0x0e
'Quan ', # 0x0f
'Ku ', # 0x10
'F... |
from __future__ import absolute_import
from email.parser import FeedParser
import logging
import sys
from pip._vendor.packaging import specifiers
from pip._vendor.packaging import version
from pip._vendor import pkg_resources
from pip import exceptions
logger = logging.getLogger(__name__)
def check_requires_pyth... |
import ansible.constants as C
from ansible.inventory.host import Host
from ansible.inventory.group import Group
from ansible.inventory.expand_hosts import detect_range
from ansible.inventory.expand_hosts import expand_hostname_range
from ansible import errors
from ansible import utils
import shlex
import re
import ast
... |
""" Estensione della libreria requests """
import logging
import os
import requests
import version
# Configurazione del sistema di logging
logger = logging.getLogger(version.lib_name)
logger.addHandler(logging.NullHandler())
class Session(requests.Session):
"""Versione modificata di requests.Session"""
def __... |
from keystone.common import sql
from keystone import credential
from keystone import exception
class CredentialModel(sql.ModelBase, sql.DictBase):
__tablename__ = 'credential'
attributes = ['id', 'user_id', 'project_id', 'blob', 'type']
id = sql.Column(sql.String(64), primary_key=True)
user_id = sql.C... |
import argparse
import logging
import os
import sys
import tempfile
import threading
from os.path import abspath, dirname, exists, join
# Local imports
import builder
from builder import VirtualEnv
from builder.Logging import LogToFile
from builder.Utils import (
GetGitHubConfig, GetVersion, Is64bitInterpreter, Is... |
import warnings
from rope.base import exceptions, resourceobserver
from rope.base.oi import objectdb, memorydb, transform
class ObjectInfoManager(object):
"""Stores object information
It uses an instance of `objectdb.ObjectDB` for storing
information.
"""
def __init__(self, project):
s... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
class FootyRoomIE(InfoExtractor):
_VALID_URL = r'http://footyroom\.com/(?P<id>[^/]+)'
_TESTS = [{
'url': 'http://footyroom.com/schalke-04-0-2-real-madrid-2015-02/',
'info_dict': {
'id': 'scha... |
import sys
import os
import os.path
import subprocess
from glob import glob
import optparse
VALGRIND_CMD = 'valgrind --tool=memcheck --leak-check=yes --undef-value-errors=yes'
class TestProxy(object):
def __init__( self, test_exe_path, use_valgrind=False ):
self.test_exe_path = os.path.normpath( os.path.a... |
"""
ah-ipv6 protocl support class(es)
http://libvirt.org/formatnwfilter.html#nwfelemsRulesProtoMiscv6
"""
from virttest.libvirt_xml import accessors, xcepts
from virttest.libvirt_xml.nwfilter_protocols import base
class Ah_ipv6(base.TypedDeviceBase):
"""
Create new Ah_ipv6 xml instances
Properties:
... |
"""Functions for fetching remote datasets.
See :ref:`datasets` for more information.
"""
from . import fieldtrip_cmc
from . import brainstorm
from . import visual_92_categories
from . import kiloword
from . import eegbci
from . import hf_sef
from . import misc
from . import mtrf
from . import sample
from . import som... |
# encoding: utf-8
# module PyKDE4.kdeui
# from /usr/lib/python3/dist-packages/PyKDE4/kdeui.cpython-34m-x86_64-linux-gnu.so
# by generator 1.135
# no doc
# imports
import PyKDE4.kdecore as __PyKDE4_kdecore
import PyQt4.QtCore as __PyQt4_QtCore
import PyQt4.QtGui as __PyQt4_QtGui
import PyQt4.QtSvg as __PyQt4_QtSvg
cl... |
"""
========================================
Plot multi-class SGD on the iris dataset
========================================
Plot decision surface of multi-class SGD on iris dataset.
The hyperplanes corresponding to the three one-versus-all (OVA) classifiers
are represented by the dashed lines.
"""
print(__doc__)
... |
# -*- coding: utf-8 -*-
class IncorrectCaptchaColorsFormatError(Exception):
message = "Incorrect 'CAPTCHA_COLORS' setting format (must be iterable of two-string-value tuples)"
def __str__(self):
return self.message
class TooFewCaptchaColorsError(Exception):
message = "Please specify al least tw... |
import salabim as sim
import pytest
class X(sim.Component):
def setup(self, color='red'):
self.color = color
self.enter(components)
class Vehicle(sim.Component):
def setup(self):
self.enter(components)
class Car(Vehicle):
pass
class Bus(Vehicle):
pass
cla... |
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='1'
from os import listdir
import sys
import time
import tools.ops
import subprocess
import numpy as np
import tensorflow as tf
import scipy.misc as sm
from models.autoencoder_net import *
from tools.utilities import *
from tools.ops import *
from random import randint
... |
from . import global_vars
from .javascript_enhancements_settings import javaScriptEnhancements
from . import util
from .node import NodeJS
from .npm import NPM
from .flow import main as flow
from .flow.flow_cli import FlowCLI
from .flow.flow_ide_server import FlowIDEServer, flow_ide_clients, JavascriptEnhancementsStart... |
# coding=UTF-8
"""
Tests for signal handling in commerce djangoapp.
"""
from __future__ import absolute_import, unicode_literals
import base64
import json
import ddt
import httpretty
import mock
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.test import TestCase
from... |
# -*- coding: iso-8859-1 -*-
""" Codec for the Punicode encoding, as specified in RFC 3492
Written by Martin v. Löwis.
"""
import codecs
##################### Encoding #####################################
def segregate(str):
"""3.1 Basic code point segregation"""
base = []
extended = {}
for c in st... |
"""Test hammer displays SCons help for SCons help options (MEDIUM TEST)."""
import TestFramework
def main():
test = TestFramework.TestFramework()
expect = "usage: scons [OPTION] [TARGET] ..."
test.run(arguments="-h")
test.fail_test(test.stdout().find(expect) == -1)
test.run(arguments="--help")
test.f... |
from proteus.default_n import *
from proteus import (StepControl,
TimeIntegration,
NonlinearSolvers,
LinearSolvers,
LinearAlgebraTools,
NumericalFlux)
from proteus.mprans import RDLS
import redist_p as physics
from ... |
import sys
from sklearn.externals.six.moves import cStringIO as StringIO
import numpy as np
import scipy.sparse as sp
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_almost_equal
from sklearn.utils.testing import assert_less
from sklearn.utils.testing import assert_raises_regexp
... |
#!/usr/bin/env python
"""
Hacky helper application to collect form data.
"""
from werkzeug.serving import run_simple
from werkzeug.wrappers import Request, Response
def copy_stream(request):
from os import mkdir
from time import time
folder = 'request-%d' % time()
mkdir(folder)
environ = request.e... |
import mock
from rally.plugins.openstack.scenarios.sahara import (node_group_templates
as ngts)
from tests.unit import test
SAHARA_NGTS = ("rally.plugins.openstack.scenarios.sahara.node_group_templates"
".SaharaNodeGroupTemplates")
class SaharaNod... |
import os.path
import copy
import exporters
from ClassExporter import ClassExporter
from FunctionExporter import FunctionExporter
from EnumExporter import EnumExporter
from HeaderExporter import HeaderExporter
from VarExporter import VarExporter
from CodeExporter import CodeExporter
from exporterutils import ... |
ANSIBLE_METADATA = {'status': ['deprecated'],
'supported_by': 'community',
'metadata_version': '1.0'}
from ansible.module_utils.nxos import load_config, run_commands
from ansible.module_utils.nxos import nxos_argument_spec, check_args
from ansible.module_utils.basic import Ansib... |
import os
import os.path
import shutil
import sys
import tempfile
from distutils import errors
import commands
C_PYTHON_DEV = """
#include <Python.h>
int main(int argc, char **argv) { return 0; }
"""
C_PYTHON_DEV_ERROR_MESSAGE = """
Could not find <Python.h>. This could mean the following:
* You're on Ubuntu and h... |
# -*- coding: utf-8 -*-
import time
from openerp.report import report_sxw
from openerp import pooler
class account_voucher(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(account_voucher, self).__init__(cr, uid, name, context=context)
self.localcontext.update({
... |
from openturns import *
# Time grid over which all the processes will be defined
nt = 100
timeGrid = RegularGrid(0.0, 1.0, nt)
# Definition of the distribution
sigma = 1.0
myDistribution = Normal(0., sigma)
# Definition of the process
myProcess = WhiteNoise(myDistribution, timeGrid)
# We get a realization of the w... |
"""
Data migration creation command
"""
from __future__ import print_function
import sys
import os
import re
from optparse import make_option
try:
set
except NameError:
from sets import Set as set
from django.core.management.base import BaseCommand
from django.core.management.color import no_style
from djan... |
# -*- coding: utf-8 -*-
"""Tests sqlparse function."""
import pytest
from tests.utils import TestCaseBase
import sqlparse
import sqlparse.sql
from sqlparse import tokens as T
class SQLParseTest(TestCaseBase):
"""Tests sqlparse.parse()."""
def test_tokenize(self):
sql = 'select * from foo;'
... |
"""Initial magic commands and hooks for the spock IPython environment"""
__all__ = ['expconf', 'showscan', 'spsplot', 'debug_completer',
'debug', 'www',
'post_mortem', 'macrodata', 'edmac', 'spock_late_startup_hook',
'spock_pre_prompt_hook']
from .genutils import page, get_door, get_m... |
import logging
import time
from multiprocessing import Pool
from aliyun.log import LogClient
from aliyun.log.es_migration.collection_task import (CollectionTaskStatus,
run_collection_task)
from aliyun.log.es_migration.collection_task_config import CollectionTaskConf... |
"""
Convert jupyter notebook into the markdown format. The notebook outputs will be
removed.
It is heavily adapted from https://gist.github.com/decabyte/0ed87372774cf5d34d7e
"""
import sys
import io
import os
import argparse
import nbformat
def remove_outputs(nb):
"""Removes the outputs cells for a jupyter note... |
_readers = {}
_writers = {}
_set_readers = {}
_set_writers = {}
_extensions = {}
def register_reader(ttype, function, override=False):
'''
Register a table reader function.
Required Arguments:
*ttype*: [ string ]
The table type identifier. This is the string that will be used to
... |
import datetime
# file and directory names
CACHE = 'data/cache'
KNOWN = 'data/known'
REQUESTS = 'data/requests'
BLACKLIST = 'data/blacklist'
# CSV = 'aaa_' + str(datetime.datetime.now()).replace(' ', '_')[:-7] + '.csv'
CSV = 'aaa.csv'
# files to ignore in the requests directories
REQUEST_BLACKLIST = ['.keep', '.DS_St... |
"""
This module contains a base type which provides list-style mutations
without specific data storage methods.
See also http://www.aryehleib.com/MutableLists.html
Author: Aryeh Leib Taurog.
"""
class ListMixin(object):
"""
A base class which provides complete list interface.
Derived classes must call Lis... |
"""
Classes and interfaces for producing tree structures that represent
the internal organization of a text. This task is known as X{parsing}
the text, and the resulting tree structures are called the text's
X{parses}. Typically, the text is a single sentence, and the tree
structure represents the syntactic structure... |
from __future__ import absolute_import, print_function, unicode_literals, division
from flask_restful import abort
from flask.globals import g
from jormungandr.authentication import get_all_available_instances
from jormungandr.interfaces.v1.decorators import get_serializer
from jormungandr.interfaces.v1.serializer.api... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
from setuptools import setup
from setuptools.command.test import test as TestCommand
import codecs
import os
import re
here = os.path.abspath(os.path.dirname(__file__))
def read(*parts):
# intentionally *not* adding an encoding ... |
__all__ = ('GestureHistoryManager', 'GestureVisualizer')
from kivy.app import App
from kivy.clock import Clock
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.graphics import ... |
import time
from openerp.osv import fields, osv
from openerp.tools.translate import _
#
# Create an final invoice based on selected timesheet lines
#
#
# TODO: check unit of measure !!!
#
class final_invoice_create(osv.osv_memory):
_name = 'hr.timesheet.invoice.create.final'
_description = 'Create invoice fr... |
"""
"""
from __future__ import print_function, division
import os
from demo import *
import subprocess
import sys
sys.path.append(os.path.abspath('../problems/'))
# Get the git root directory
root=repo_dir = subprocess.Popen(['git'
,'rev-parse'
... |
"""Contains a client to communicate with the YouTube servers.
A quick and dirty port of the YouTube GDATA 1.0 Python client
libraries to version 2.0 of the GDATA library.
"""
# __author__ = '<EMAIL> (John Skidgel)'
import logging
import gdata.client
import gdata.youtube.data
import atom.data
import atom.http_c... |
from datetime import date, datetime
from dateutil import relativedelta
from openerp import tools
from openerp.osv import fields, osv
class crm_case_section(osv.osv):
_name = "crm.case.section"
_inherit = ['mail.thread', 'ir.needaction_mixin']
_description = "Sales Teams"
_order = "complete_name"
_... |
from __future__ import with_statement
import os
import sys
import inspect
from collections import OrderedDict
from os.path import join as pjoin
this_dir = os.path.abspath(os.path.split(__file__)[0])
sys.path.insert(0, os.path.join(this_dir, '../'))
from libcloud.compute .base import NodeDriver
from libcloud.compute.... |
{
'name': 'Brazilian Localization Account Product',
'summary': "Brazilian Localization Account Product",
'category': 'Localisation',
'license': 'AGPL-3',
'author': 'Akretion, Odoo Community Association (OCA)',
'website': 'http://odoo-brasil.org',
'version': '8.0.3.0.0',
'depends': [
... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_urlparse
from ..utils import (
ExtractorError,
js_to_json,
)
class ScreencastOMaticIE(InfoExtractor):
_VALID_URL = r'https?://screencast-o-matic\.com/watch/(?P<id>[0-9a-zA-Z]+)'
_TEST... |
from __future__ import absolute_import, division, print_function, unicode_literals
from json.encoder import encode_basestring_ascii as json_encode_string
from collections import namedtuple
from cStringIO import StringIO
from io import open
import csv
import os
import re
class Validator(object):
""" Base class fo... |
"""
Creates the default Site object.
"""
from django.apps import apps
from django.conf import settings
from django.core.management.color import no_style
from django.db import DEFAULT_DB_ALIAS, connections, router
def create_default_site(app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, **kwargs):
... |
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import StateData
from direct.gui.DirectGui import *
from direct.showbase import DirectObject
from pandac.PandaModules import *
from toontown.effects import DistributedFireworkShow
from toontown.nametag import NametagGlobals
from toontown.parties import... |
# -*- coding: utf-8 -*-
"""
pygments.styles.vim
~~~~~~~~~~~~~~~~~~~
A highlighting style for Pygments, inspired by vim.
: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 Keywor... |
from gnuradio import gr, gr_unittest, blocks
import os
from os.path import getsize
g_in_file = os.path.join(os.getenv("srcdir"), "test_16bit_1chunk.wav")
g_extra_header_offset = 36
g_extra_header_len = 18
class test_wavefile(gr_unittest.TestCase):
def setUp(self):
self.tb = gr.top_block()
def tearD... |
"""Code related to line charts."""
import copy
import warnings
from graphy import common
class LineStyle(object):
"""Represents the style for a line on a line chart. Also provides some
convenient presets.
Object attributes (Passed directly to the Google Chart API. Check there for
details):
width: Widt... |
import Queue
import os
import sys
import threading
_NUMBER_OF_WRITER_THREADS = 10
_HOME_ENV_NAME = 'HOMEPATH' if 'win32' == sys.platform else 'HOME'
_WORKING_DIR = os.path.join(os.environ[_HOME_ENV_NAME], 'webrtc_video_quality')
# I couldn't think of other way to handle this but through a global variable
g_frame_num... |
from odoo.tests.common import TransactionCase
class TestResourceCommon(TransactionCase):
def _define_calendar(self, name, attendances, tz):
return self.env['resource.calendar'].create({
'name': name,
'tz': tz,
'attendance_ids': [
(0, 0, {
... |
__all__ = [ 'Client', 'Listener', 'Pipe' ]
from Queue import Queue
families = [None]
class Listener(object):
def __init__(self, address=None, family=None, backlog=1):
self._backlog_queue = Queue(backlog)
def accept(self):
return Connection(*self._backlog_queue.get())
def close(self):... |
"""
The GeometryColumns and SpatialRefSys models for the Oracle spatial
backend.
It should be noted that Oracle Spatial does not have database tables
named according to the OGC standard, so the closest analogs are used.
For example, the `USER_SDO_GEOM_METADATA` is used for the GeometryColumns
model and the `SDO_... |
from boto.resultset import ResultSet
from boto.ec2.ec2object import EC2Object
class ReservedInstancesOffering(EC2Object):
def __init__(self, connection=None, id=None, instance_type=None,
availability_zone=None, duration=None, fixed_price=None,
usage_price=None, description=None,... |
import os
from wb import system, home_fn, choose_arch
def build_ddk(config, dir, x64):
ddk_path = config['DDK_PATH']
ddk_major = int(config['DDKVER_MAJOR'])
debug = 'PRODUCT_TAP_DEBUG' in config
return build_tap(ddk_path, ddk_major, debug, dir, x64)
def build_tap(ddk_path, ddk_major, debug, dir, x64):... |
import plotter
import common
import wx
import numpy
import math
import pubsub
from constants import *
from gnuradio import gr #for gr.prefs
import forms
##################################################
# Constants
##################################################
SLIDER_STEPS = 200
LOOP_BW_MIN_EXP, LOOP_BW_MAX_EXP ... |
# -*- coding: utf-8 -*-
""" Models for the stats application. """
# standard library
# django
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.translation import ugettext_lazy as _
# models
from base.models import BaseModel
from users.models import User
class Stat(BaseMode... |
from .utils import HTTPException
class RangeParser(object):
def __call__(self, header, file_size):
prefix = "bytes="
if not header.startswith(prefix):
raise HTTPException(416, message="Unrecognised range type %s" % (header,))
parts = header[len(prefix):].split(",")
ran... |
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.six.moves im... |
"""Views like in MTV."""
from __future__ import unicode_literals
import requests
from flask import (current_app, render_template, make_response, json, jsonify,
request, url_for)
from werkzeug.exceptions import NotFound
from .tasks import pull_request, push, get_headers
from .models import db, Acco... |
from __future__ import print_function, unicode_literals
import re
from requests.utils import dict_from_cookiejar
from sickbeard import logger, tvcache
from sickbeard.bs4_parser import BS4Parser
from six.moves.urllib.parse import quote_plus
from sickrage.helper.common import convert_size, try_int
from sickrage.provid... |
"""
Tests for the LTI outcome service handlers, both in outcomes.py and in tasks.py
"""
import ddt
from django.test import TestCase
from mock import patch, MagicMock
from student.tests.factories import UserFactory
from lti_provider.models import GradedAssignment, LtiConsumer, OutcomeService
import lti_provider.tasks ... |
__author__ = '<EMAIL> (Jeff Scudder)'
import os
import StringIO
import urlparse
import urllib
import httplib
ssl = None
try:
import ssl
except ImportError:
pass
class Error(Exception):
pass
class UnknownSize(Error):
pass
class ProxyError(Error):
pass
MIME_BOUNDARY = 'END_OF_PART'
def get_headers(... |
# coding=utf-8
from __future__ import unicode_literals
from random import randint
from .. import Provider as AddressProvider
class Provider(AddressProvider):
address_formats = ['{{street_address}}, {{city}}, {{postcode}}']
building_number_formats = ['#', '##', '###']
city_formats = ['{{city_prefix}} {{f... |
"""
Provides various throttling policies.
"""
from __future__ import unicode_literals
import time
from django.core.cache import cache as default_cache
from django.core.exceptions import ImproperlyConfigured
from rest_framework.compat import is_authenticated
from rest_framework.settings import api_settings
class Ba... |
import os
from os.path import isdir, isfile, join, basename
from django.conf import settings
from graphite.logger import log
from graphite.node import BranchNode, LeafNode
from graphite.readers import WhisperReader, GzippedWhisperReader, RRDReader
from graphite.util import find_escaped_pattern_fields
from . import fs... |
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.openstack im... |
import sklearn.datasets
import scipy as sp
new_post = \
"""Disk drive problems. Hi, I have a problem with my hard disk.
After 1 year it is working only sporadically now.
I tried to format it, but now it doesn't boot any more.
Any ideas? Thanks.
"""
print("""\
Dear reader of the 1st edition of 'Building Machine Le... |
import samba.getopt as options
import ldb
from samba import provision
from samba.samdb import SamDB
from samba.auth import system_session
from samba.netcmd.common import _get_user_realm_domain
from samba.netcmd import (
Command,
CommandError,
SuperCommand,
Option
)
class cmd_spn_list(Command):
... |
# -*- coding: utf-8 -*-
import re
from module.plugins.internal.Account import Account
from module.plugins.internal.Plugin import set_cookie
class FastshareCz(Account):
__name__ = "FastshareCz"
__type__ = "account"
__version__ = "0.11"
__status__ = "testing"
__description__ = """Fastshare... |
from abc import ABCMeta, abstractmethod
from biicode.common.model.symbolic.reference import References
from biicode.common.edition.block_holder import BlockHolder
class BiiAPI(object):
'''The main interface to user-access biicode published information'''
#TODO: Clearly specify raised Exceptions in each method... |
from cloudinit import log as logging
from cloudinit import sources
LOG = logging.getLogger(__name__)
class DataSourceNone(sources.DataSource):
def __init__(self, sys_cfg, distro, paths, ud_proc=None):
sources.DataSource.__init__(self, sys_cfg, distro, paths, ud_proc)
self.metadata = {}
se... |
#!/usr/bin/python
'''
Extract _("...") strings for translation and convert to Qt4 stringdefs so that
they can be picked up by Qt linguist.
'''
from subprocess import Popen, PIPE
import glob
import operator
OUT_CPP="src/qt/bitcoinstrings.cpp"
EMPTY=['""']
def parse_po(text):
"""
Parse 'po' format produced by x... |
"""
Make sure comdat folding optimization setting is extracted properly.
"""
import TestGyp
import sys
if sys.platform == 'win32':
test = TestGyp.TestGyp(formats=['msvs', 'ninja'])
CHDIR = 'linker-flags'
test.run_gyp('opt-icf.gyp', chdir=CHDIR)
test.build('opt-icf.gyp', chdir=CHDIR)
# We're specifying /D... |
from pygw.config import geowave_pkg
from pygw.store import DataStoreOptions
class AccumuloOptions(DataStoreOptions):
"""
Accumulo data store options.
"""
def __init__(self):
super().__init__(geowave_pkg.datastore.accumulo.config.AccumuloRequiredOptions())
def set_zookeeper(self, zookeepe... |
import os
from shlex import split
from shutil import copy2
from subprocess import check_call
from charms.docker.compose import Compose
from charms.reactive import hook
from charms.reactive import remove_state
from charms.reactive import set_state
from charms.reactive import when
from charms.reactive import when_not
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.