content stringlengths 4 20k |
|---|
# -*- coding: utf-8 -*-
"""
InaSAFE Disaster risk assessment tool developed by AusAid -
**metadata module.**
Contact : <EMAIL>
.. 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; eit... |
#!/usr/bin/env python
'''
tables for STM32G474xx MCUs
'''
# additional build information for ChibiOS
build = {
"CHIBIOS_STARTUP_MK" : "os/common/startup/ARMCMx/compilers/GCC/mk/startup_stm32g4xx.mk",
"CHIBIOS_PLATFORM_MK" : "os/hal/ports/STM32/STM32G4xx/platform.mk"
}
# MCU parameters
mcu = {
# ram m... |
"""Tests for the RangeDataset serialization."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from tensorflow.python.data.experimental.kernel_tests.serialization import dataset_serialization_test_base
from tensorflow.python.data.ops import datas... |
from django.core.urlresolvers import reverse
from django.core import validators
from django.utils.encoding import force_text
from django.utils.translation import pgettext_lazy
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon import messages
... |
"""
This module contains essential stuff that should've come with Python itself ;)
"""
import os
import re
import inspect
import weakref
import errno
import six
from functools import partial, wraps
from scrapy.utils.decorators import deprecated
def flatten(x):
"""flatten(sequence) -> list
Returns a single, ... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
# Imported for backwards compat
from ansible.module_utils.common.json import AnsibleJSONEncoder
from ansible.parsing.vault import VaultLib
from ansible.parsing.yaml.objects import AnsibleVaultEncryptedUnicode
from ans... |
import sys
import re
import os
import csv
from datetime import datetime
from regex_library import *
'''
parse_OCR_files from Stdin
Input: (stdin) filename to be parsed
output CSV filename
# of lines to be parsed
Parse the input file for #lines
using the regex expressions, search input for Volume N... |
__author__ = 'kaloyan'
import unittest
import os
from importlib.machinery import SourceFileLoader
from daacompetition.util.parametrized_test import ParametrizedTestCase
from daacompetition.util.custom_decorators import timeout
class JudgeTest(ParametrizedTestCase):
'''trybva testovete da ima suffix za da razbera ... |
from functools import wraps
import json
import os
import sys
import time
from . import execution
from . import junit_output
from . import statusfile
ABS_PATH_PREFIX = os.getcwd() + os.sep
class ProgressIndicator(object):
def __init__(self):
self.runner = None
def SetRunner(self, runner):
self.runner ... |
import json
from openerp import http
from openerp.http import request
from openerp.addons.website.controllers.main import Website
class Website(Website):
@http.route(
'/website/field_autocomplete/<string:model>',
type='http',
auth='public',
methods=['GET'],
website=True,
... |
import datetime
import sys
from StringIO import StringIO
from lettuce.terrain import before, after
from subunit.v2 import StreamResultToBytes
from subunit.iso8601 import Utc
def open_file(filename):
"""
open a subunit file
this is not a context manager because it is used asynchronously by
hooks
... |
from trove.common.remote import guest_client
class UpgradeMessageSender(object):
"""
This class handles the business logic for sending
an rpc message to the guest
"""
@staticmethod
def create(context, instance_id, instance_version, location,
metadata=None):
instance_id... |
import platform
import logging
import os
if platform.system() == "Darwin":
from .osx import inhibit_sleep_osx, deinhibit_sleep_osx
inhibit_sleep = inhibit_sleep_osx
deinhibit_sleep = deinhibit_sleep_osx
elif platform.system() == "Windows":
import ctypes
ES_CONTINUOUS = 0x80000000
ES_SYSTEM_REQU... |
#!/usr/bin/python
"""
IP Packet class taken from:
# Copyright 1997, Corporation for National Research Initiatives
# written by Jeremy Hylton, <EMAIL>
"""
import sys, os
IPVERSION = 4
IP_DF = 0x4000
IP_MF = 0x2000
IP_MAXPACKET = 65535
IPTOS_LOWDELAY = 0x10
IPTOS_THROUGHPUT = 0x08
IPTOS_RELIABILITY = 0x04
IPTOS_PREC... |
import os
import unittest
PERF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
from telemetry.testing import system_stub
from telemetry.internal.testing import system_stub_test_module
class CloudStorageTest(unittest.TestCase):
SUCCESS_FILE_HASH = 'success'.zfill(40)
PUBLIC_FILE_HASH = 'public'.... |
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import Client
from django.test.utils import override_settings
from funfactory.helpers import urlparams
from mock import patch
from nose.tools import eq_, ok_
from mozillians.common.tests import TestCase
from mozi... |
from itertools import combinations
from copy import copy
import numpy as np
import bayesian
class DomainGraph(object):
def __init__(self, network=None):
"""Domain graph of a bayesian network
The DomainGraph class represents the domain graph of a Bayesian
network. It is an undirected grap... |
#!/usr/bin/env python
"""static - A stupidly simple WSGI way to serve static (or mixed) content.
(See the docstrings of the various functions and classes.)
Copyright (C) 2006-2009 Luke Arno - http://lukearno.com/
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesse... |
"""Presents a friendly base class for dashboard handlers."""
__author__ = 'Nick Retallack (<EMAIL>)'
from common import crypto
from common import jinja_utils
from modules.dashboard import dashboard
class AbstractDashboardHandler(dashboard.DashboardHandler):
"""Contains common patterns in dashboard handlers."""
... |
from django.test import TestCase
from advanced_reports.defaults import AdvancedReport
class AdvancedReportTest(TestCase):
def setUp(self):
self.report = AdvancedReport()
def test_tabbed_filter_fields(self):
self.report.tabbed_filter_fields = {
'card': {
'images': ... |
import sys
import inspect
registry = {}
calling_modules = {}
class MultiMethod(object):
def __init__(self, name):
self.name = name
self.typemap = {}
def __call__(self, *args):
types = tuple(arg.__class__ for arg in args)
function = self.typemap.get(types)
if function is... |
#!/usr/bin/env python
"""
This script checks the syntax of other python scripts.
It returns a bad error code to the parent if something goes wrong.
It's basically a more sophisticated version of something like this:
python2 -m py_compile $< || python3 -m py_compile $<
"""
import sys
import subprocess
if len(sys... |
"""
@summary: Module containing client functions for interacting with OpenTree web
services
@author: CJ Grady / Jeff Cavner
@version: 3.2.0
@status: release
@license: Copyright (C) 2015, University of Kansas Center for Research
Lifemapper Project, lifemapper [at] ku [dot] edu,
Biodi... |
import web
from social.strategies.base import BaseStrategy, BaseTemplateStrategy
class WebpyTemplateStrategy(BaseTemplateStrategy):
def render_template(self, tpl, context):
return web.template.render(tpl)(**context)
def render_string(self, html, context):
return web.template.Template(html)(*... |
import re
from util import LazyCorpusLoader
from reader import *
# Create a new corpus reader instance for each European language
danish = LazyCorpusLoader(
'europarl_raw/danish', EuroparlCorpusReader, r'ep-.*\.da', encoding='utf-8')
dutch = LazyCorpusLoader(
'europarl_raw/dutch', EuroparlCorpusReader, r'ep-.... |
"""Output the list of files to be generated by GRIT from an input.
"""
from __future__ import print_function
import getopt
import os
import sys
from grit import grd_reader
from grit.node import structure
from grit.tool import interface
class DetermineBuildInfo(interface.Tool):
"""Determine what files will be read... |
"""Test createwallet arguments.
"""
from test_framework.address import key_to_p2wpkh
from test_framework.descriptors import descsum_create
from test_framework.key import ECKey
from test_framework.test_framework import FujicoinTestFramework
from test_framework.util import (
assert_equal,
assert_raises_rpc_error... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('base', '0013_add_en_US'),
]
operations = [
migrations.CreateModel(
name='ChangedEntityLocale',
field... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
import datetime
try:
from nailgun import entities, entity_fields, entity_mixins
from nailgun.config import ServerConfig
HAS_NAILGUN_PACKAGE = True
except:
HAS_NAI... |
from error import *
from tokens import *
from events import *
from nodes import *
from loader import *
from dumper import *
try:
from cyaml import *
except ImportError:
pass
def scan(stream, Loader=Loader):
"""
Scan a YAML stream and produce scanning tokens.
"""
loader = Loader(stream)
w... |
import os
import json
from datetime import datetime
from InputObservers.InputObserver import InputObserver
from decorators.overrides import overrides
class StatisticsInputEventObserver(InputObserver):
"""This is the default observer for input events."""
def __init__(self):
super(InputObserver, self).__init__()
... |
#!/usr/bin/env python3
import re
import sys
import shutil
import os.path
import subprocess
import sysconfig
import reindent
import untabify
SRCDIR = sysconfig.get_config_var('srcdir')
def n_files_str(count):
"""Return 'N file(s)' with the proper plurality on 'file'."""
return "{} file{}".f... |
"""
Exceptions
"""
# Copyright: 2010, Gael Varoquaux
# License: BSD 3 clause
import sys
class JoblibException(Exception):
"""A simple exception with an error message that you can get to."""
def __init__(self, *args):
self.args = args
def __reduce__(self):
# For pickling
return s... |
import babel.dates
import time
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
import werkzeug.urls
from werkzeug.exceptions import NotFound
from openerp import http
from openerp import tools
from openerp.http import request
from openerp.tools.translate import _
from openerp.... |
from django.conf.urls import patterns, url
from django.contrib.formtools.tests.wizard.namedwizardtests.forms import (
SessionContactWizard, CookieContactWizard, Page1, Page2, Page3, Page4)
def get_named_session_wizard():
return SessionContactWizard.as_view(
[('form1', Page1), ('form2', Page2), ('form3'... |
import sys
import _pytest._code
def runpdb_and_get_report(testdir, source):
p = testdir.makepyfile(source)
result = testdir.runpytest_inprocess("--pdb", p)
reports = result.reprec.getreports("pytest_runtest_logreport")
assert len(reports) == 3, reports # setup/call/teardown
return reports[1]
cl... |
#!/usr/bin/env python
"""ug2html.py -- Creates HTML version of Robot Framework User Guide
Usage: ug2html.py [ cr(eate) | dist | zip ]
create .. Creates the user guide so that it has relative links to images,
library docs, etc. This version is stored in the version control
and distributed with th... |
from django.test import TestCase
from oscar.apps.wishlists.models import WishList
from oscar.core.compat import get_user_model
User = get_user_model()
class TestAWishlist(TestCase):
def test_can_generate_a_random_key(self):
key = WishList.random_key(6)
self.assertTrue(len(key) == 6)
class Tes... |
class CubeOrientation(object):
"""
The :class:`CubeOrientation <CubeOrientation>` class.
Rotations applied on the cube sometimes needs reorientation,
so this class keeps tracking these orientation changes.
"""
def __init__(self, faces=None):
"""
Initialize a plain cube ore a reo... |
import mock
import pytest
import six
import subprocess
from mercury.common.helpers import cli
from tests.common.unit.base import MercuryCommonUnitTest
class CLIResultUnitTest(MercuryCommonUnitTest):
"""Unit tests for mercury.common.helpers.cli.CLIResult"""
def test_setter(self):
"""Test setters for s... |
import json
import shlex
import os
import re
import sys
def get_version(pacman_output):
"""Take pacman -Qi or pacman -Si output and get the Version"""
lines = pacman_output.split('\n')
for line in lines:
if 'Version' in line:
return line.split(':')[1].strip()
return None
def query_... |
#!/usr/bin/env python
from nose.tools import *
import networkx as nx
class TestAttractingComponents(object):
def setUp(self):
self.G1 = nx.DiGraph()
self.G1.add_edges_from([(5,11),(11,2),(11,9),(11,10),
(7,11),(7,8),(8,9),(3,8),(3,10)])
self.G2 = nx.DiGraph(... |
#!/usr/bin/env python3
"""The app: very basic."""
# pylint: disable=cyclic-import, no-self-use, no-member, invalid-name, no-init
# pylint: disable=too-few-public-methods, no-name-in-module, import-error
from functools import lru_cache, wraps
from flask import request
from flask import current_app as app
from flask.e... |
# xml.etree test for cElementTree
import sys, struct
from test import support
from test.support import import_fresh_module
import unittest
cET = import_fresh_module('xml.etree.ElementTree',
fresh=['_elementtree'])
cET_alias = import_fresh_module('xml.etree.cElementTree',
... |
#!/usr/bin/python
#
# Raspberry Pi Home Sentry - RPI script to monitor home
#
#
# Descripton:
# Service to watch door status and alert if door is left open too long.
# Uses motion sensor to detect motion and delay alert.
# Illuminates LED when door is open.
#
# Jason A. Cox, @jasonacox
# https://github.com/... |
"""Represent a player."""
import kmg.monopoly.property as game_property
class IllegalPieceError(Exception):
"""Raise if an illegal piece name was added."""
class Piece(object):
"""A game piece."""
def __init__(self, name):
"""Create a game piece.
Args:
name: str.
"""
if name in ('Hat'... |
import gdb
from linux import cpus, utils
module_type = utils.CachedType("struct module")
def module_list():
global module_type
module_ptr_type = module_type.get_type().pointer()
modules = gdb.parse_and_eval("modules")
entry = modules['next']
end_of_list = modules.address
while entry != end... |
from m5.params import *
from m5.proxy import *
from Device import BasicPioDevice
from X86IntPin import X86IntSourcePin
class I8254(BasicPioDevice):
type = 'I8254'
cxx_class = 'X86ISA::I8254'
cxx_header = "dev/x86/i8254.hh"
int_pin = Param.X86IntSourcePin(X86IntSourcePin(),
'Pin to signal ti... |
from collections import namedtuple
PicResult = namedtuple("PicResult", ["frame", "k", "cluster_sizes"])
def power_iteration_clustering(self, source_column, destination_column, similarity_column, k=2, max_iterations=100,
initialization_mode = "random"):
"""
Power Iteration Clust... |
import etcAuthSource
import httpsAuthSource
import mysqlAuthSource
import pgAuthSource
import pgAuthSourceAlt
import radiusAuthSource
import smbAuthSource
import usAuthSource
import zodbAuthSource
import zodbBTreeAuthSource
#
# These have special requirements for external libraries
# that my not be present.
#
try:
i... |
#!/usr/bin/python2
'''
This example shows how to use the imaplib module.
In this case I use it to access my gmail account, upload messages, download messages
and more.
To see the documentation of the API use: pydoc imaplib
This thing started from me wanting to import my old mail to gmail and seeing
this blog post: ht... |
import re
import subprocess
def pgm_wrap(var, s):
"""Wrap given var access inside pgm_get. Assumes return value of
uint8_t in that var """
m = re.search(var + '\[[^\]]', s)
if not m:
return s
start = m.start()
brackets = 0
for i in range(start, s.__len__()):
if s[i] == '[... |
"""Metrics classes for computing the output of an evaluation."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import re
from tensorflow.contrib.summary import summary_ops
from tensorflow.python.eager import context
from tensorflow.python.eager import fu... |
"""
Base classes for PD test cases
Tests will usually inherit from one of these classes to have the controller
and/or dataplane automatically set up.
"""
import importlib
import ptf
from ptf.base_tests import BaseTest
from ptf import config
import ptf.testutils as testutils
#########################################... |
"""
Class for PXE bare-metal nodes.
"""
import datetime
import os
import jinja2
from oslo.config import cfg
from oslo.db import exception as db_exc
from nova.compute import flavors
from nova import exception
from nova.i18n import _
from nova import objects
from nova.openstack.common import fileutils
from nova.openst... |
import m5
from m5.objects import *
m5.util.addToPath('../configs/common')
import FSConfig
system = FSConfig.makeSparcSystem('atomic', SimpleMemory)
system.clk_domain = SrcClockDomain(clock = '1GHz')
system.cpu_clk_domain = SrcClockDomain(clock = '1GHz')
cpu = AtomicSimpleCPU(cpu_id=0, clk_domain = system.cpu_clk_domai... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Mail-Merge for Scribus. This file provides the Command Line Interface (all OS)
#
# For further information (manual, description, etc.) please visit:
# https://github.com/berteh/ScribusGenerator/
#
# v2.0 (2015-12-02): added features (merge, range, clean, save/load)
# v1.... |
import datetime
def time():
'''Overrideable version of datetime.datetime.today'''
if time.override_time:
return time.override_time
return datetime.time()
time.override_time = None
def today():
'''Overridable version of datetime.datetime.today'''
if today.override_time:
return to... |
# -*- coding: utf-8 -*-
from Plugins.Extensions.MediaPortal.plugin import _
from Plugins.Extensions.MediaPortal.resources.imports import *
class hdpornGenreScreen(MPScreen):
def __init__(self, session):
MPScreen.__init__(self, session, skin='MP_Plugin')
self["actions"] = ActionMap(["MP_Actions"], {
"ok" : s... |
"""Implementation of server API.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from treadmill import context
from treadmill import schema
class API:
"""Treadmill Server REST api."""
def __init__(self)... |
import re
from ansible.module_utils.basic import get_exception
from ansible.module_utils.netcli import CommandRunner
from ansible.module_utils.network import NetworkModule
import ansible.module_utils.dellos10
try:
from lxml import etree as ET
except ImportError:
import xml.etree.ElementTree as ET
class Facts... |
"""
Module implementing an object to create a thumbnail image of a web site.
"""
from __future__ import unicode_literals
from PyQt5.QtCore import pyqtSignal, QObject, QSize, Qt, QUrl
from PyQt5.QtGui import QPixmap, QImage, QPainter
from PyQt5.QtWebKitWidgets import QWebPage
from ..Network.NetworkAccessManagerProxy ... |
class MSA_info(object): #contains functions for setting aggregate information for the MSA
def __init__(self):
pass
def app_income_to_MSA(self, inputs): #set income bracket index
if inputs['income'] == 'NA ' or inputs['income'] == ' ':
return 5 #applicant income unavailable, feeds to 'income not available'... |
#!/usr/bin/env python
"""Test the process list module."""
import os
from grr.lib import action_mocks
from grr.lib import flags
from grr.lib import flow
from grr.lib import test_lib
# pylint: disable=unused-import
from grr.lib.flows.general import processes as _
# pylint: enable=unused-import
from grr.lib.rdfvalues im... |
import sys
from twisted.python import log
from twisted.internet import reactor
from autobahn.twisted.websocket import listenWS
from autobahn.wamp1.protocol import WampServerFactory, \
WampServerProtocol
class MyServerProtocol(WampServerProtocol):
def onSessionOpen(self):
... |
"""Evaluation utilities."""
import json
import re
import string
import unicodedata
import tensorflow.compat.v1 as tf
def normalize_answer(s):
"""Normalize answer."""
s = unicodedata.normalize("NFD", s)
def remove_articles(text):
return re.sub(r"\b(a|an|the)\b", " ", text)
def white_space_fix(text):
... |
from sympy.physics.quantum import Dagger
from sympy.physics.quantum.boson import BosonOp
from sympy.physics.quantum.fermion import FermionOp
from sympy.physics.quantum.operatorordering import (normal_order,
normal_ordered_form)
def test_normal_order():
a = BosonOp(... |
"""
answer_set.py: functionality for handling answer sets.
Copyright (C) 2014 Michael Kelly
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
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
ib-downloader3.py
Created on Tue Jul 5 15:53:45 2016
@author: nwillemse
"""
import click
import time
import pandas as pd
from sys import argv
from datetime import datetime
from ib.ext.Contract import Contract
from ib.opt import Connection
class Downloader:
de... |
import glob
import logging
import pyglet
from functions import *
from pyglet.image import Animation, AnimationFrame
ANIM_PATH = "resources/animations/"
def create_effect_animation(image_name):
img = pyglet.image.load(image_name)
columns = img.width // 192
rows = img.height // 192
effect_seq = pyglet.... |
"""
These views handle all actions in Studio related to import and exporting of
courses
"""
import logging
import os
import re
import shutil
import tarfile
from path import path
from tempfile import mkdtemp
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.core.exce... |
#!/usr/bin/env python
"""
Notify program finishing with email
*.py "msg"
"""
import smtplib
import sys
import socket
app_name = 'GIF Filtering'
hostname = socket.gethostname()
import os
cwd = os.getcwd()
g_config = {
'HOST': 'smtp.gmail.com',
'port': 587,
'FROM': '"%s ALERT" <<EMAIL>>' % app_na... |
from teuthology.orchestra import monkey
monkey.patch_all()
from cStringIO import StringIO
import os
from teuthology.orchestra import connection, remote, run
from teuthology.orchestra.test.util import assert_raises
from teuthology.exceptions import CommandCrashedError, ConnectionLostError
from pytest import skip
HOS... |
# -*- coding: utf-8 -*-
"""Public section, including homepage and signup."""
from flask import Blueprint, flash, redirect, render_template, request, current_app, session, g, app
from flask_login import login_required, login_user, logout_user, current_user
from flask_themes2 import render_theme_template, get_theme, get_... |
"""
Models.
"""
from config_models.models import ConfigurationModel
from django.db import models
from django.utils.translation import ugettext_lazy as _
class XBlockConfiguration(ConfigurationModel):
"""
XBlock configuration used by both LMS and Studio, and not specific to a particular template.
"""
... |
import json
class DockerNetworks:
def __init__(self, docker):
self.docker = docker
async def list(self):
data = await self.docker._query_json("networks")
return data
async def create(self, config):
config = json.dumps(config, sort_keys=True).encode("utf-8")
data =... |
"""
Graph utilities and algorithms
Graphs are represented with their adjacency matrices, preferably using
sparse matrices.
"""
# Authors: Aric Hagberg <<EMAIL>>
# Gael Varoquaux <<EMAIL>>
# Jake Vanderplas <<EMAIL>>
# License: BSD 3 clause
import numpy as np
from scipy import sparse
from .validati... |
from unittest import TestCase
from statstuff import statistics as stats
class Tests(TestCase):
def test_average(self):
self.assertEqual(None, stats.average([]))
self.assertEqual(1.5, stats.average([1, 2]))
self.assertEqual(25.35, stats.average([10.1, 20.8, 30.4, 40.1]))
def test_corr... |
import unittest
from autothreadharness.harness_case import HarnessCase
class Leader_9_2_5(HarnessCase):
role = HarnessCase.ROLE_LEADER
case = '9 2 5'
golden_devices_required = 1
def on_dialog(self, dialog, title):
pass
if __name__ == '__main__':
unittest.main() |
# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APIClient
from commons.base_testcase import BaseApiTestCase
class UserApiTestCase(BaseApiTestCase):
def test_user_read_detail(self):
url = reverse('user-detail', args=[s... |
import pytest
from api.base.settings.defaults import API_BASE
from api_tests.nodes.filters.test_filters import NodesListFilteringMixin, NodesListDateFilteringMixin
from osf_tests.factories import (
AuthUserFactory,
BookmarkCollectionFactory,
CollectionFactory,
NodeFactory,
PreprintFactory,
Proj... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
The config file for importing the example_data dataset into
ExampleNode.
Go to http://vamdc.tmy.se/doc/importing.html
for understanding what happens below.
Use this file this way (first edit base path) :
$ cd ../imptools
$ python run_rewrite.py ../nodes/ExampleNode/... |
"""Base class for MIME multipart/* type messages."""
__all__ = ['MIMEMultipart']
from email.mime.base import MIMEBase
class MIMEMultipart(MIMEBase):
"""Base class for MIME multipart/* type messages."""
def __init__(self, _subtype='mixed', boundary=None, _subparts=None,
**_params):
... |
"""
Copyright 2015 Rackspace
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 agreed to in writing, software
dist... |
from django.http import HttpResponse, Http404
from django.template import loader
from django.contrib.sites.models import get_current_site
from django.core import urlresolvers
from django.utils.encoding import smart_str
from django.core.paginator import EmptyPage, PageNotAnInteger
def index(request, sitemaps):
curr... |
""" Testing miobase module
"""
import numpy as np
from numpy.testing import assert_raises, assert_equal
from scipy.io.matlab.miobase import matdims
def test_matdims():
# Test matdims dimension finder
assert_equal(matdims(np.array(1)), (1, 1)) # numpy scalar
assert_equal(matdims(np.array([1])), (1, 1))... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
=========================================================
SVM Margins Example
=========================================================
The plots below illustrate the effect the parameter `C` has
on the separation line. A large value of `C` basically tells
our model that w... |
from django.core.management.base import BaseCommand, CommandError
from django.core.management import call_command
from django.conf import settings
from django.db import connection
from django.db.models import Q, F
from contactnetwork.distances import *
from protein.models import ProteinFamily
import time
import scipy
... |
import bleach
import json
from django import forms
from osf.models import CollectionProvider, CollectionSubmission
from admin.base.utils import get_nodelicense_choices, get_defaultlicense_choices, validate_slug
class CollectionProviderForm(forms.ModelForm):
collected_type_choices = forms.CharField(widget=forms.... |
#!/usr/bin/python3
"""planes GUI Widgets Demo
Copyright (c) 2014 Florian Berger <<EMAIL>>
"""
# This file is part of planes.
#
# planes 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... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Ansible module to manage A10 Networks slb virtual server objects
(c) 2014, Mischa Peters <<EMAIL>>,
Eric Chou <<EMAIL>>
This file is part of Ansible
Ansible is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as pu... |
import unittest
import hashlib
from utilities import logger_util
from api import malshr_api
class TestMalshrAPI(unittest.TestCase):
malshare = ''
md5 = ''
hash_md5 = ''
def setUp(self):
self.malshare = malshr_api.Malshare_API()
self.md5 = 'b63bff90e6a55c4a404a8a48d076de45'
sel... |
from urllib import request
from tarfile import open as tarOpen
def downloadDatabase(mirror):
"""
Download the database of packages and versions from the specified mirror.
Performs no parsing, just downloads it to ``/tmp/winry-testing.db``. In the
future this should be expanded to perform more error ha... |
import github.GithubObject
class PaginatedListBase:
def __init__(self):
self.__elements = list()
def __getitem__(self, index):
assert isinstance(index, (int, slice))
if isinstance(index, (int, long)):
self.__fetchToIndex(index)
return self.__elements[index]
... |
from i18n import _
import os, sys, time, types
import extensions, util, demandimport
def _pythonhook(ui, repo, name, hname, funcname, args, throw):
'''call python hook. hook is callable object, looked up as
name in python module. if callable returns "true", hook
fails, else passes. if hook raises exception... |
import copy
from tempest.lib.api_schema.response.compute.v2_1 import flavors as flavorsv21
from tempest.lib.api_schema.response.compute.v2_1 import parameter_types
# Note(gmann): This is schema for microversion 2.55 which includes the
# following changes:
# Add new PUT API
# Adds a ``description`` field to the follow... |
from gnuradio import gr, gr_unittest, blocks
class test_skiphead(gr_unittest.TestCase):
def setUp(self):
self.tb = gr.top_block()
self.src_data = [int(x) for x in range(65536)]
def tearDown(self):
self.tb = None
def test_skip_0(self):
skip_cnt = 0
expected_result ... |
from django.core.urlresolvers import reverse
from django.core.urlresolvers import reverse_lazy
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from openstack_dashboard import api
from openstack_dashboard.dashboards.admin.hypervisors.compute \
import... |
"""A CallTip window class for Tkinter/IDLE.
After ToolTip.py, which uses ideas gleaned from PySol
Used by the CallTips IDLE extension.
"""
from Tkinter import *
HIDE_VIRTUAL_EVENT_NAME = "<<calltipwindow-hide>>"
HIDE_SEQUENCES = ("<Key-Escape>", "<FocusOut>")
CHECKHIDE_VIRTUAL_EVENT_NAME = "<<calltipwindow-checkhide... |
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GObject
from gi.repository import GLib
import kismon.utils as utils
class NetworkList:
def __init__(self, networks, locate_network_on_map, on_signal_graph, config):
self.network_lines = {}
self.network_iter = {}... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.