content stringlengths 4 20k |
|---|
#!/usr/bin/env python
"""Windows specific actions.
Most of these actions share an interface (in/out rdfvalues) with linux actions
of the same name. Windows-only actions are registered with the server via
libs/server_stubs.py
"""
import binascii
import ctypes
import exceptions
import logging
import os
import tempfile... |
from sqlalchemy import Column, MetaData, Table
from glance.db.sqlalchemy.migrate_repo.schema import (
Boolean, DateTime, Integer, String, Text, from_migration_import) # noqa
def get_images_table(meta):
"""
Returns the Table object for the images table that
corresponds to the images table definition ... |
import sys
import unittest
from deap import tools
class LogbookTest(unittest.TestCase):
def setUp(self):
self.logbook = tools.Logbook()
print
def test_multi_chapters(self):
self.logbook.record(gen=0, evals=100, fitness={'obj 1' : {'avg' : 1.0, 'max' : 10},
... |
"""A module providing information about the necessity of brackets"""
from __future__ import print_function, division
from sympy.core.function import _coeff_isneg
# Default precedence values for some basic types
PRECEDENCE = {
"Lambda": 1,
"Xor": 10,
"Or": 20,
"And": 30,
"Relational": 35,
"Add... |
# -*- coding: utf-8 -*-
from ooni.utils import log
from ooni.utils.net import userAgents
from ooni.templates import httpt
from twisted.python import usage
from twisted.internet import defer
import random
class UsageOptions(usage.Options):
optParameters = [
['url', 'u', None, 'Specify a single URL to test.... |
from __future__ import unicode_literals
from django.db.backends import BaseDatabaseOperations
class DatabaseOperations(BaseDatabaseOperations):
def __init__(self, connection):
super(DatabaseOperations, self).__init__(connection)
def date_extract_sql(self, lookup_type, field_name):
# http://w... |
'''
This case can not execute parallelly
@author: Youyk
'''
import os
import zstacklib.utils.sizeunit as sizeunit
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.operations.host_operations as ho... |
from osv import fields, osv
from tools.translate import _
class account_invoice(osv.osv):
_inherit = 'account.invoice'
_columns = {
'corrispettivo': fields.boolean('Corrispettivo'),
}
def onchange_company_id(self, cr, uid, ids, company_id, part_id, type, invoice_line, currency_id, context=... |
import re
import json
# Azure interface classes
from azure.servicebus import ServiceBusService, Message, Topic, Rule, DEFAULT_RULE_NAME
from copy import deepcopy
from messagetools.iam_message import encode_message
from messagetools.iam_message import decode_message
from messagetools.dao_implementation.mock import... |
# -*- coding: utf-8 -*-
# vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 :
# pylint: disable=protected-access,line-too-long
import unittest
from swconfig_otb.sw import Sw
class TestSw(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestSw, self).__init__(*args, **kwargs)
sel... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
INSTALL:
apt-get install postgresql-contrib-9.1
RUN IN DBSHELL
CREATE EXTENSION IF NOT EXISTS unaccent;
USAGE:
DATABASES = {
'default': {
'ENGINE': 'opps.db.backends.postgresql_psycopg2',
...
}
}
SOUTH_DATABASE_ADAPTERS = {
'defaul... |
"""Functions for summarizing matrix datasets with repeated observations."""
import numpy as np
def xs(data):
"""Returns set of unique x-values."""
if data.ndim == 1:
# assume rec array
names = data.dtype.names
assert names and len(names) == 2, "Assuming record array with 2 fields"
return np.unique(... |
from __future__ import unicode_literals
import traceback
from datetime import date
from django.db import DatabaseError, IntegrityError
from django.test import TestCase, TransactionTestCase, ignore_warnings
from django.utils.encoding import DjangoUnicodeDecodeError
from .models import (
Author, Book, DefaultPerso... |
"""Config flow for Omnilogic integration."""
import logging
from omnilogic import LoginException, OmniLogic, OmniLogicException
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import callback
from homeassistant.help... |
from __future__ import absolute_import, division, unicode_literals
try:
from collections import OrderedDict
except ImportError:
try:
from ordereddict import OrderedDict
except ImportError:
OrderedDict = dict
import re
from pip._vendor.six import text_type
from . import _base
from ..utils... |
"""
Base class for account settings page.
"""
from common.test.acceptance.pages.lms import BASE_URL
from bok_choy.page_object import PageObject
from bok_choy.promise import EmptyPromise
from common.test.acceptance.pages.lms.fields import FieldsMixin
class AccountSettingsPage(FieldsMixin, PageObject):
"""
Te... |
from datetime import datetime
from uuid import uuid4
from shutil import move
from os.path import exists, dirname, join, getmtime, abspath
from thumbor.result_storages import BaseStorage
from thumbor.utils import logger
class Storage(BaseStorage):
PATH_FORMAT_VERSION = 'v2'
@property
def is_auto_webp(se... |
import math
import StringIO
import types
# the '_from_json_number' function returns either float or long.
__pychecker__ = 'no-returnvalues'
# character classes
WS = set([' ','\t','\r','\n','\b','\f'])
DIGITS = set([str(i) for i in range(0, 10)])
NUMSTART = DIGITS.union(['.','-','+'])
NUMCHARS = NUMSTART.union(['e','... |
import logging
import os
_logger = logging.getLogger(__name__ + ".deprecated")
# Skip warnings on runbots
_method = _logger.info if "OCA_RUNBOT" in os.environ else _logger.warning
_method("This module is DEPRECATED. See %s/README.rst.",
os.path.dirname(__file__)) |
import networkx as nx
from nose.tools import *
def small_ego_G():
"""The sample network from http://arxiv.org/pdf/1310.6753v1.pdf"""
edges=[('a','b'), ('a','c'), ('b','c'), ('b','d'),
('b', 'e'),('b','f'),('c','d'),('c','f'),('c','h'),('d','f'), ('e','f'),
('f','h'),('h','j'), ('h','k'),... |
from openerp.osv import fields, osv, orm
import openerp.addons.decimal_precision as dp
from openerp.tools.translate import _
from openerp import tools
class stock_change_product_qty(osv.osv_memory):
_name = "stock.change.product.qty"
_description = "Change Product Quantity"
_columns = {
'product_id... |
#! /usr/bin/python
import sys
import os
import StringIO
import unittest
# Show DepricationWarnings come from buildbot - it isn't default with Python 2.7 or newer.
# See https://bugs.webkit.org/show_bug.cgi?id=90161 for details.
import warnings
warnings.simplefilter('default')
class BuildBotConfigLoader(object):
... |
{
'name': 'Recurring Documents',
'version': '1.0',
'category': 'Tools',
'description': """
Create recurring documents.
===========================
This module allows to create new documents and add subscriptions on that document.
e.g. To have an invoice generated automatically periodically:
----------... |
# -*- coding: UTF8 -*-
import types
from TestSuite import TestSuite, desc, catch
from mqttcli import MqttClient
from nyamuk.event import *
from lib.env import gen_msg, debug
class PubSub(TestSuite):
tests = (
('a/b/c', 'a/b/c'),
('a/b/c', 'a/b/d' , False),
('a/+/c', 'a/b/c'),
('a... |
"""SCons.Tool.dvi
Common DVI Builder definition for various other Tool modules that use it.
"""
#
# Copyright (c) 2001 - 2014 The SCons Foundation
#
# 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 ... |
"""API for the glance service.
"""
from six.moves import zip as izip
from django.views import generic
from openstack_dashboard import api
from openstack_dashboard.api.rest import utils as rest_utils
from openstack_dashboard.api.rest import urls
CLIENT_KEYWORDS = {'resource_type', 'marker', 'sort_dir', 'sort_key', '... |
"""Support for Modbus Register sensors."""
import logging
import struct
from typing import Any, Optional, Union
from pymodbus.exceptions import ConnectionException, ModbusException
from pymodbus.pdu import ExceptionResponse
import voluptuous as vol
from homeassistant.components.sensor import DEVICE_CLASSES_SCHEMA, PL... |
"""Contains functions for evaluation and summarization of metrics.
The evaluation.py module contains helper functions for evaluating TensorFlow
modules using a variety of metrics and summarizing the results.
**********************
* Evaluating Metrics *
**********************
In the simplest use case, we use a model... |
# This code is so you can run the samples without installing the package
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
#
testinfo = "s, t 0.45, s, t 0.71, s, t 1, s, t 1.21, s, t 1.47, s, t 1.72, s, t 2.1, s, q"
tags = "RotoZoomTransition"
import cocos
from cocos.director impo... |
import logging
import uuid
import time
from stun import FullCone, OpenInternet
from collections import deque
from golem.core.hostaddress import ip_address_private, ip_network_contains, ipv4_networks
from server import Server
from tcpnetwork import TCPListeningInfo, TCPListenInfo, SocketAddress, TCPConnectInf... |
import sys
import numpy as np
from lxmls.parsing.dependency_reader import *
from lxmls.parsing.dependency_writer import *
from lxmls.parsing.dependency_features import *
from lxmls.parsing.dependency_decoder import *
from lxmls.util.my_math_utils import *
class DependencyParser():
'''
Dependency parser class
... |
from __future__ import unicode_literals
import logging
import warnings
from functools import update_wrapper
from django import http
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import NoReverseMatch, reverse
from django.template.response import TemplateResponse
from django.uti... |
from pbr.hooks import base
from pbr import packaging
class BackwardsCompatConfig(base.BaseConfig):
section = 'backwards_compat'
def hook(self):
self.config['include_package_data'] = 'True'
packaging.append_text_list(
self.config, 'dependency_links',
packaging.parse_de... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from difflib import SequenceMatcher
from kombu import version_info_t
from kombu.five import string_t
def fmatch_iter(needle, haystack, min_ratio=0.6):
for key in haystack:
ratio = SequenceMatcher(None, needle, key).ratio()
... |
"""
This package contains Docutils Writer modules.
"""
__docformat__ = 'reStructuredText'
import os.path
import sys
import docutils
from docutils import languages, Component
from docutils.transforms import universal
if sys.version_info < (2,5):
from docutils._compat import __import__
class Writer(Component):
... |
# coding=utf-8
"""Provenance Keys."""
from safe.definitions.layer_purposes import (
layer_purpose_exposure_summary,
layer_purpose_aggregate_hazard_impacted,
layer_purpose_aggregation_summary,
layer_purpose_analysis_impacted,
layer_purpose_exposure_summary_table,
layer_purpose_profiling
)
from ... |
from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import QApplication, QWidget
from ui_window import Ui_Window
class SimpleSelector(QWidget, Ui_Window):
def __init__(self, parent=None):
super(SimpleSelector, self).__init__(parent)
self.setupUi(self)
def on_elementLineEdit_returnPressed(sel... |
"""
Script that trains DAG models on delaney dataset.
"""
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import numpy as np
np.random.seed(123)
import tensorflow as tf
tf.set_random_seed(123)
import deepchem as dc
# Load Delaney dataset
delaney_tasks, del... |
# -*- coding: utf-8 -*-
from plone import api
from ploneintranet.notifications.message import Message
class Base(object):
''' A base adapter for creating a notification
'''
predicate = 'GLOBAL_NOTICE'
def __init__(self, context):
''' Initializes this adapter
'''
self.context =... |
import shutil
import tempfile
import unittest
class SDistTests(unittest.TestCase):
def _getTargetClass(self):
from pkginfo.sdist import SDist
return SDist
def _makeOne(self, filename=None, metadata_version=None):
if metadata_version is not None:
return self._getTargetClass... |
from django.contrib.contenttypes.fields import (
GenericForeignKey, GenericRelation,
)
from django.contrib.contenttypes.models import ContentType
from django.db import models
class Award(models.Model):
name = models.CharField(max_length=25)
object_id = models.PositiveIntegerField()
content_type = mode... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.errors import AnsibleUndefinedVariable
from ansible.module_utils.six import string_types
from ansible.module_utils._text import to_text
from ansible.plugins.action import ActionBase
class ActionModule(ActionBase):
... |
# coding=utf8
import random
import math
from module import *
class DiceError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
def roll(t):
testa = t[1].split("+", 1) #
testb = t[1].split("-", 1) #
if len(testa[0]) > len(testb[... |
import sys
import unittest
from django.core.exceptions import ImproperlyConfigured
from django.db import ProgrammingError
from django.utils import six
try:
from django.contrib.gis.db.backends.postgis.operations import PostGISOperations
HAS_POSTGRES = True
except ImportError:
HAS_POSTGRES = False
except Im... |
#!/bin/python
# -*- coding: utf-8 -*-
import comparators.pixel_comparator
import comparators.chained_image_comparator
import comparators.avg_pixel_comparator
import image_iterator
import sys
# Not really sets, since they may contain "duplicate" images(ie ones that when compared return True)
'''
Input:
image_sets:... |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding index on 'Feed', fields ['active_subscribers']
db.create_index('feeds', ['active_subscribers'])
... |
"""
rohmu - rohmu data transformation interface
Copyright (c) 2016 Ohmu Ltd
See LICENSE for details
"""
from . import IO_BLOCK_SIZE
from .compat import suppress
from .compressor import CompressionFile, DecompressionFile
from .encryptor import DecryptorFile, EncryptorFile
from .errors import InvalidConfigurationError
... |
# -*- coding: utf-8 -*-
"""
sphinx.theming
~~~~~~~~~~~~~~
Theming support for HTML builders.
:copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import os
import shutil
import zipfile
import tempfile
from os import path
from six import str... |
from openerp import models, fields, api
class OpResultTemplate(models.Model):
_name = 'op.result.template'
_description = 'Result Template'
_rec_name = 'name'
exam_session_id = fields.Many2one(
'op.exam.session', 'Exam Session', required=True)
name = fields.Char("Name", size=254, required... |
# -*- coding: utf-8 -*-
"""
flask.testing
~~~~~~~~~~~~~
Implements test support helpers. This module is lazily imported
and usually not used in production environments.
:copyright: (c) 2011 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
from contextlib import contextmana... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'certified'}
import time
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.... |
"""Test cases for end-to-end testing. Run with the server_tests script."""
import calendar
import datetime
import email
import email.header
import optparse
import os
import pytest
import re
import simplejson
import sys
import tempfile
import time
import unittest
import urlparse
from google.appengine.api import image... |
"""
SDoc
Copyright 2016 Set Based IT Consultancy
Licence MIT
"""
class Html:
"""
Utility class with functions for generating HTML code.
"""
# ------------------------------------------------------------------------------------------------------------------
@staticmethod
def escape(text, quo... |
import unittest
import numpy as np
import matplotlib.pylab as plt
from prototype.estimation.kf import KF
def gaussian_noise(sigma):
if type(sigma) in [np.matrix, np.array]:
return sigma**2 * np.random.randn(sigma.shape[0], 1)
else:
return sigma**2 * np.random.randn()
def plot_trajectory(st... |
from __future__ import absolute_import
from pydispatch import dispatcher
from scrapy.utils import signal as _signal
class SignalManager(object):
def __init__(self, sender=dispatcher.Anonymous):
self.sender = sender
def connect(self, receiver, signal, **kwargs):
"""
Connect a receiver... |
#
# Dalton Burke, CU Denver
#
from __future__ import absolute_import
from utils import ensure_dir, symlink_unless_exists
from .downloader import download_url, DownloadError
from datetime import datetime, timedelta
import pytz
import requests
import os
import os.path as osp
import sys
import logging
from six.moves im... |
from django import forms
from django.forms.models import inlineformset_factory
from django.utils.translation import ugettext_lazy as _
from wagtail.wagtailadmin.widgets import AdminPageChooser
from wagtail.wagtailsearch import models
class QueryForm(forms.Form):
query_string = forms.CharField(label=_("Search ter... |
import os
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth.tests.utils import skipIfCustomUser
from django.contrib.flatpages.models import FlatPage
from django.test import TestCase
from django.test.utils import override_settings
@override_settings(
LOGIN_URL='/... |
from typing import Iterable, TYPE_CHECKING, Callable
import gi
gi.require_version('AppIndicator3', '0.1')
from gi.repository import AppIndicator3
from blueman.main.indicators.GtkStatusIcon import build_menu
if TYPE_CHECKING:
from blueman.plugins.applet.Menu import MenuItemDict
from blueman.main.indicators.Gt... |
from .command import Command
from selenium.webdriver.common.alert import Alert
class SwitchTo:
def __init__(self, driver):
self._driver = driver
@property
def active_element(self):
"""
Returns the element with focus, or BODY if nothing has focus.
:Usage:
elemen... |
import pandas as pd
from bs4 import BeautifulSoup
import re
import hazm
import numpy as np
from sklearn.cross_validation import train_test_split
train = None
def fetch_data():
df = pd.DataFrame(data={'c1': [1111111, 2, 3], 'c2': [4, 5, 6]})
df.to_csv('test.tsv', sep="\t", index=False)
print(... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}
import re
from ansible.module_utils.nxos import get_config, load_config
from ansible.module_utils.nxos import nxos_argument_spec, check_args
from ansible.module_utils.basic import ... |
import subprocess,os, sys
zone_files_path="/etc/bind/zones"
def creating_for_zone():
domain_name= sys.argv[1]
ipaddr_nameServer= sys.argv[2]
old_file="/etc/bind/db.local"
os.chdir(zone_files_path)
new_zone_file="{0}{1}".format("db.",domain_name)
subprocess.call("cp /etc/bind/db.local new_zone_file",shell=True)
... |
##
## One-off script to export 6.002x users into the edX framework
##
## Could be modified to be general by:
## * Changing user_keys and up_keys to handle dates more cleanly
## * Providing a generic set of tables, rather than just users and user profiles
## * Handling certificates and grades
## * Handling merge/forks o... |
"""
Twisted server implementation.
This gateway allows you to expose functions in Twisted to AMF clients and
servers.
@see: U{Twisted homepage<http://twistedmatrix.com>}
@since: 0.1.0
"""
import sys
import os.path
try:
sys.path.remove('')
except ValueError:
pass
try:
sys.path.remove(os.path.dirname(os.... |
from pybin.mid.node import NodeService
from pybin.mid.other import OtherService
import requests
import socket
from bs4 import BeautifulSoup, SoupStrainer
URL = 'http://shopping.naver.com/detail/detail.nhn'
URL_2 = 'http://m.shopping.naver.com/detail/price_compare_list_area.nhn'
class DataService:
def __init__(se... |
from __future__ import absolute_import
import sys
import traceback
import cStringIO
from unittest import suite
from unittest import case
from unittest import runner
import mut
from . import actions
class MpiTestSuite(suite.TestSuite):
_instance = None
def __init__(self, *args, **kwargs):
suite.TestSuite.... |
from __future__ import print_function
import numpy as np
import tensorflow as tf
from A2_fullyconnected.main import SoftmaxwithSGD
import utility.logger_tool
import logging
class HiddenRelu(SoftmaxwithSGD):
def __init__(self):
SoftmaxwithSGD.__init__(self)
self.keep_prob = 1
return
... |
# -*- coding: utf-8 -*-
# Moduł obsługujący drugi (wpięty do portu o wyższym numerze)
# lub pojedynczy sygnalizator drogowy w zestawie Inteligentne Miasto
from time import sleep
import city
def off():
'''Wyłączenie wszystkich świateł'''
p = 3
while p >= 0:
a = city.read_port(p)
... |
def unique(ar, return_index=False, return_inverse=False, return_counts=False):
"""
Find the unique elements of an array.
Returns the sorted unique elements of an array. There are two optional
outputs in addition to the unique elements: the indices of the input array
that give the unique values, and... |
"""
Utility functions applicable across multiple pywbemtools commands.
"""
from __future__ import print_function, absolute_import
import os
import warnings
import inspect
from datetime import datetime
import mock
import six
import click
__all__ = []
# Env var for overriding the terminal width
TERMWIDTH_ENVVAR = 'PY... |
"""Adds Discogs album search support to the autotagger. Requires the
discogs-client library.
"""
from __future__ import division, absolute_import, print_function
import beets.ui
from beets import logging
from beets import config
from beets.autotag.hooks import AlbumInfo, TrackInfo, Distance
from beets.plugins import B... |
"""Parser for future statements
"""
from compiler import ast, walk
def is_future(stmt):
"""Return true if statement is a well-formed future statement"""
if not isinstance(stmt, ast.From):
return 0
if stmt.modname == "__future__":
return 1
else:
return 0
class FutureParser:
... |
#Test the FitPara classes
import sys
sys.path.append("/home/mscook/Desktop/PhD/Projects/pyParaTools")
from ParaParser import *
from CalcPara import *
from FitPara import *
from ParaUtils import *
print 80*'-'
print " Testing FitPara.py"
print 80*'-'
#python test_FitPara.py pre ~/Desktop/PREfit_python/TESTDATA/PDB... |
from . import test_resource
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
import rdflib, logging, neonx, sys, argparse, os.path
from rdflib import Graph
import FileParser as FP
import networkx as nx
logging.basicConfig(level=logging.DEBUG)
# Print Licence info
print "SEMNETCON Copyright (C) 2016 John Brennan and Stephen Bonner.\n\
This program comes with ABSOLUTELY NO WARRANTY.\n\
This is ... |
""" Module contains main loop and configuration of pyBinSim """
import logging
import time
import numpy as np
import pyaudio
from pybinsim.convolver import ConvolverFFTW
from pybinsim.filterstorage import FilterStorage
from pybinsim.osc_receiver import OscReceiver
from pybinsim.pose import Pose
from pybinsim.soundhand... |
"""
Stream All The Sources Addon
Copyright (C) 2017 k3l3vra
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 vers... |
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from mailchimp.exceptions import MailchimpWarning
import warnings
API_KEY = getattr(settings, 'MAILCHIMP_API_KEY', None)
if API_KEY is None:
raise ImproperlyConfigured('django-mailchimp requires the MAILCHIMP_API_KEY setting')... |
from test.test_support import verbose, sortdict
import warnings
warnings.filterwarnings("ignore", "the regex module is deprecated",
DeprecationWarning, __name__)
import regex
from regex_syntax import *
re = 'a+b+c+'
print 'no match:', regex.match(re, 'hello aaaabcccc world')
print 'successful s... |
from .bases import _StandardStemmer
from whoosh.compat import u
class SpanishStemmer(_StandardStemmer):
"""
The Spanish Snowball stemmer.
:cvar __vowels: The Spanish vowels.
:type __vowels: unicode
:cvar __step0_suffixes: Suffixes to be deleted in step 0 of the algorithm.
:type __step0_suff... |
#!/usr/bin/env python
import os
from setuptools import setup
def readreq(filename):
result = []
with open(filename) as f:
for req in f:
req = req.lstrip()
if req.startswith('-e ') or req.startswith('http:'):
idx = req.find('#egg=')
if idx >= 0:... |
"""
Iceland specific form helpers.
"""
from __future__ import absolute_import, unicode_literals
from django.contrib.localflavor.is_.is_postalcodes import IS_POSTALCODES
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import RegexField
from django.forms... |
import io
import unittest
import numpy as np
from Orange.data import ContinuousVariable, DiscreteVariable
from Orange.data.io import TabDelimFormat
class TestTabReader(unittest.TestCase):
def setUp(self):
DiscreteVariable._clear_cache()
def test_read_easy(self):
simplefile = """\
F... |
from m5.SimObject import SimObject
from m5.params import *
from BaseTLB import BaseTLB
class AlphaTLB(BaseTLB):
type = 'AlphaTLB'
cxx_class = 'AlphaISA::TLB'
cxx_header = "arch/alpha/tlb.hh"
size = Param.Int("TLB size")
class AlphaDTB(AlphaTLB):
size = 64
class AlphaITB(AlphaTLB):
size = 48 |
from pyasn1 import error
class TagMap:
def __init__(self, posMap={}, negMap={}, defType=None):
self.__posMap = posMap.copy()
self.__negMap = negMap.copy()
self.__defType = defType
def __contains__(self, tagSet):
return tagSet in self.__posMap or \
self.__... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Ansible module to configure .deb packages.
(c) 2014, Brian Coca <<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 published by
the Free Software Foundation, eithe... |
import os
import re
from lib.utility import shell_utils, misc
from scli import api_wrapper, config_file, prompt
from scli.constants import EbLocalDir, OptionSettingFile, OptionSettingEnvironmentType, \
ParameterSource, ParameterName, ServiceDefault
from scli.terminal.iam_terminal import IamTerminal
from scli.termi... |
import re
import tempfile
from wptrunner import update as wptupdate
from wptrunner.update.tree import Commit, CommitMessage, get_unique_name
class HgTree(wptupdate.tree.HgTree):
def __init__(self, *args, **kwargs):
self.commit_cls = kwargs.pop("commit_cls", Commit)
wptupdate.tree.HgTree.__init__(... |
"""
EasyBuild support for iimklc compiler toolchain (includes Intel compilers (icc, ifort), OpenMPI,
CUDA, Intel Math Kernel Library (MKL), and Intel FFTW wrappers.
:author: Stijn De Weirdt (Ghent University)
:author: Kenneth Hoste (Ghent University)
:author: Bart Oldeman (Compute Canada)
:author: Maxime Boissonneault... |
import unittest
from streamlink.plugins.turkuvaz import Turkuvaz
class TestPluginTurkuvaz(unittest.TestCase):
def test_can_handle_url(self):
should_match = [
'https://www.atv.com.tr/webtv/canli-yayin',
'http://www.a2tv.com.tr/webtv/canli-yayin',
'https://www.ahaber.com... |
from django.http import Http404
from django.shortcuts import get_object_or_404, render
from django_tables2 import RequestConfig
from .models import *
from .services import *
from .tables import *
def game_list(r):
games = tablify(get_game_list(),
GameListTable, r)
context = {'games': games... |
import pytest
from unittest import mock
import pendulum
from share.ingest.scheduler import IngestScheduler
from share.models.jobs import IngestJob
from share.models.ingest import SourceUniqueIdentifier
from tests import factories
@pytest.mark.django_db
class TestIngestScheduler:
@pytest.fixture
def mock_co... |
import unittest
import antlr3
import testbase
class TestRecognitionException(unittest.TestCase):
"""Tests for the antlr3.RecognitionException class"""
def testInitNone(self):
"""RecognitionException.__init__()"""
exc = antlr3.RecognitionException()
class TestEarlyExitException(unit... |
"""Intents for the Shopping List integration."""
from homeassistant.helpers import intent
import homeassistant.helpers.config_validation as cv
from . import DOMAIN, EVENT
INTENT_ADD_ITEM = "HassShoppingListAddItem"
INTENT_LAST_ITEMS = "HassShoppingListLastItems"
async def async_setup_intents(hass):
"""Set up th... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
r_regression_line.py
---------------------
Date : December 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
*******************... |
"""
bjson/jsonlib.py
Asynchronous Bidirectional JSON-RPC protocol implementation over TCP/IP
Copyright (c) 2010 David Martinez Marti
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditio... |
"""browsepict - Display all "cicn" resources found"""
import FrameWork
import EasyDialogs
from Carbon import Res
from Carbon import Qd
from Carbon import Win
from Carbon import Controls
from Carbon import List
from Carbon import Icn
import macresource
#
# Resource definitions
ID_MAIN=512
MAIN_LIST=1
MAIN_SHOW=2
# Wh... |
import product_price
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
from twisted.internet import defer
from twisted.python import failure, util
class Counter(object):
num = 0
let = 'a'
def incrLet(cls):
cls.let = chr(ord(cls.let) + 1)
incrLet = classmethod(incrLet)
def handleFailure(f):
print "errback"
print "we got an exception: %s" % (f.get... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.