code stringlengths 1 199k |
|---|
import json
from six import string_types
from custodia.message.common import InvalidMessage
from custodia.message.common import MessageHandler
class SimpleKey(MessageHandler):
"""Handles 'simple' messages"""
def parse(self, msg, name):
"""Parses a simple message
:param req: ignored
:para... |
import math as m
def near_to_target(lbot, targetX, targetY, nearDist = 50):
x, y, alpha = lbot.getPose()
distToTarget = m.sqrt(m.pow(x-targetX, 2) + m.pow(y-targetY, 2))
if distToTarget <= nearDist:
return True
return False |
import sys,os
import numpy as np
import velaINJMagnetControl as VIMC
a = VIMC.velaINJMagnetController(True,False)
print( np.array(a.getQuadNames())) |
'''
This file must hold keys for translatable messages
that are used as variables
it is important that a dummy _() function is used here
this way message key will be pulled into django.po
and can still be used as a variable in python files.
'''
_ = lambda v:v
__all__ = []
_('most relevant questions')
_('click to see mo... |
import json
import sys
import requests
from collections import Counter
from wapy.api import Wapy
from http.server import BaseHTTPRequestHandler, HTTPServer
wapy = Wapy('frt6ajvkqm4aexwjksrukrey')
def removes(yes):
no = ["Walmart.com", ".", ","]
for x in no:
yes = yes.replace(x, '')
return yes
def po... |
import sys
import unittest
import cbind
cbind.choose_cindex_impl(cbind.CLANG_CINDEX)
import suite_all
if __name__ == '__main__':
runner = unittest.TextTestRunner()
sys.exit(not runner.run(suite_all.suite_all).wasSuccessful()) |
from abjad.tools.durationtools import Duration
from abjad.tools.rhythmtreetools import RhythmTreeContainer, RhythmTreeLeaf
def test_rhythmtreetools_RhythmTreeNode_duration_01():
tree = RhythmTreeContainer(preprolated_duration=1, children=[
RhythmTreeLeaf(preprolated_duration=1),
RhythmTreeContainer(... |
import os
import sys
HOSTNAME = os.environ.get('QLF_HOSTNAME', 'localhost')
BASE_DIR = os.path.dirname(
os.path.dirname(os.path.abspath(__file__))
)
SECRET_KEY = os.environ.get('SECRET_KEY', os.urandom(32))
ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', HOSTNAME).split(',')
SITE_PAGES_DIRECTORY = os.path.join(BASE... |
"""
The module file for iosxr_facts
"""
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': [u'preview'],
'supported_by': 'network'}
DOCUMENTATION = """
---
module: iosxr_facts
version_adde... |
import pygame
if not pygame.font.get_init():
pygame.font.init()
TFont = {
'helvetica 8' : pygame.font.SysFont('helvetica',8),
'helvetica 10' : pygame.font.SysFont('helvetica',10),
'helvetica 12' : pygame.font.SysFont('helvetica',12),
'helvetica 16' : pygame.font.SysFont('helvetica',16,0),
... |
"""
@file generateITetrisIntersectionMetrics.py
@author Daniel Krajzewicz
@author Lena Kalleske
@author Michael Behrisch
@date 2007-10-25
@version $Id: generateITetrisIntersectionMetrics.py 14425 2013-08-16 20:11:47Z behrisch $
SUMO, Simulation of Urban MObility; see http://sumo-sim.org/
Copyright (C) 2009-201... |
from .polarpoint import PolarPoint
__all__ = [
'PolarPoint',
] |
import pytest
from django.template import Context, Template
from pootle.core.delegate import scores
def _render_str(string, context=None):
context = context or {}
context = Context(context)
return Template(string).render(context)
def test_templatetag_progress_bar():
rendered = _render_str("{% load commo... |
import _surface
import chimera
try:
import chimera.runCommand
except:
pass
from VolumePath import markerset as ms
try:
from VolumePath import Marker_Set, Link
new_marker_set=Marker_Set
except:
from VolumePath import volume_path_dialog
d= volume_path_dialog(True)
new_marker_set= d.new_marker_set
marker_set... |
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>'
import errno, socket, select, os
from Cookie import SimpleCookie
from contextlib import closing
from urlparse import parse_qs
... |
../../../../../../../../share/pyshared/papyon/service/AddressBook/scenario/contacts/block_contact.py |
from gi.repository import Gdk
from gi.repository import GdkPixbuf
from eye import Eye
from utils import svg_str_to_pixbuf
class Sleepy(Eye):
def __init__(self, fill_color):
Eye.__init__(self, fill_color)
self._pixbuf = svg_str_to_pixbuf(eye_svg())
def draw(self, widget, cr):
bounds = sel... |
""" UserProfileDB class is a front-end to the User Profile Database
"""
from __future__ import print_function
__RCSID__ = "$Id$"
import os
import sys
import hashlib
from DIRAC import S_OK, S_ERROR, gLogger, gConfig
from DIRAC.Core.Utilities import Time
from DIRAC.ConfigurationSystem.Client.Helpers import Registry
from ... |
import argparse
import os
from config import *
def main():
parser = argparse.ArgumentParser(prog=os.path.basename(__file__))
globals().update(load_config(parser))
parser.add_argument('--dataset', choices=datasets, required=False)
args = parser.parse_args()
# override default values
if args.datas... |
import system_tests
class TestFuzzedPoC(metaclass=system_tests.CaseMeta):
url = [
"https://github.com/Exiv2/exiv2/issues/210",
"https://github.com/Exiv2/exiv2/issues/209"
]
filename = system_tests.path("$data_path/2018-01-09-exiv2-crash-002.tiff")
commands = [
"$exiv2 -pR $filena... |
from .parser import IEMLParser |
import bottle
from bottle import get, post, route, static_file, view, HTTPError
import shared_state
import logging
logger = logging.getLogger(__name__)
@route('/unauth')
def login():
return HTTPError(401, 'Unauthorized')
@post('/login')
def login():
"""Authenticate users"""
username = post_get('username')
... |
__author__ = 'sushil'
class InvalidDateFormat(BaseException):
pass
class DateOutOfRange(BaseException):
pass
class InvalidDate(BaseException):
pass |
"""Example of how to convert a RayTransform operator to a tensorflow layer.
This example is similar to ``tensorflow_layer_matrix``, but demonstrates how
more advanced operators, such as a ray transform, can be handled.
"""
from __future__ import print_function
import tensorflow as tf
import numpy as np
import odl
impor... |
import json
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
class LoginRequiredMixin(object):
""" This works: class InterviewListView(LoginRequiredMixin, ListView)
This DOES NOT work: class InterviewListView(ListView, LoginRequiredMixin)
I'm not 100% sure that ... |
import logging
import json
import sys
from os.path import join
from hashlib import md5
from tempfile import NamedTemporaryFile
from flask import request
import superdesk
from superdesk.io.registry import register_feeding_service, register_feeding_service_parser
from superdesk.io.feeding_services import FeedingService
f... |
from flask import Flask, request
import json
import datetime
from ConfigParser import ConfigParser
import zmq
from monitor_kraken import request_pb2
from monitor_kraken import response_pb2
from monitor_kraken import type_pb2
app = Flask(__name__)
app.config.from_object('monitor_kraken.default_settings')
app.config.from... |
from django.db import models
from core.models import BillingSchedule
from core.models import Bill
from core.models import Account
from core.models import FileRepo
from core.models import Config
from core.models import Task |
"""
Classes used to model the roles used in the courseware. Each role is responsible for checking membership,
adding users, removing users, and listing members
"""
import logging
from abc import ABCMeta, abstractmethod
from collections import defaultdict
from django.contrib.auth.models import User
from opaque_keys.edx.... |
"""WebUI."""
from .websocket import WebsocketProxyHandler
def create_webapp(naumanni, **kwargs):
"""App factory.
:param CircleCore core: CircleCore Core
:param str base_url: ベースURL
:param int ws_port: Websocket Port Number
:return: WebUI App
:rtype: CCWebApp
"""
from .app import Naumanni... |
import os
import sys
import dotenv
dotenv.read_dotenv()
if __name__ == "__main__":
ENVIRONMENT = os.getenv('ENVIRONMENT')
if ENVIRONMENT == 'STAGING':
settings = 'staging'
elif ENVIRONMENT == 'PRODUCTION':
settings = 'production'
else:
settings = 'development'
os.environ.setd... |
{'name': 'Report to printer - Paper tray selection',
'version': '8.0.1.0.1',
'category': 'Printer',
'author': "Camptocamp,Odoo Community Association (OCA)",
'maintainer': 'Camptocamp',
'website': 'http://www.camptocamp.com/',
'license': 'AGPL-3',
'depends': ['base_report_to_printer',
],
'data': [
... |
from __future__ import unicode_literals
from __future__ import absolute_import
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('video_pipeline', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='videopipelineinteg... |
import os
import selinux
import tempfile
import unittest
import blivet
from tests import loopbackedtestcase
import blivet.formats.fs as fs
from blivet.size import Size
@unittest.skipUnless(selinux.is_selinux_enabled() == 1, "SELinux is disabled")
class SELinuxContextTestCase(loopbackedtestcase.LoopBackedTestCase):
... |
from __future__ import unicode_literals
import itertools
from collections import Counter
from weboob.capabilities.base import empty
from weboob.capabilities.housing import POSTS_TYPES
class HousingTest(object):
"""
Testing class to standardize the housing modules tests.
"""
# Fields to be checked for va... |
'''
numword for EN_GB
'''
from numword_en import NumWordEN
class NumWordENGB(NumWordEN):
'''
NumWord EN_GB
'''
def currency(self, val, longval=True):
'''
Convert to currency
'''
return self._split(val, hightxt=u"pound/s", lowtxt=u"pence",
j... |
import re
import sys
import avango.gua
class GuajacumTreePrinter():
"""
Recursively print the scene graph or subtrees of certain nodes.
This class will be hooked into avango.gua._gua.SceneGraph and
avango.gua._gua.Node to provide a printTree() method for
SceneGraph and Node objects.
"""
def ... |
"""
requests.hooks
~~~~~~~~~~~~~~
This module provides the capabilities for the Requests hooks system.
Available hooks:
``args``:
A dictionary of the arguments being sent to Request().
``pre_request``:
The Request object, directly before being sent.
``post_request``:
The Request object, directly after being... |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gw_app', '0002_auto_20181101_1545'),
]
operations = [
migrations.AddField(
model_name='nasmodel',
name='enabled',
field=models.BooleanField(default=True, ver... |
from vt_manager.controller.actions.ActionController import ActionController
from vt_manager.controller.drivers.VTDriver import VTDriver
from vt_manager.models.Action import Action
from vt_manager.models.VirtualMachine import VirtualMachine
import xmlrpclib, threading, logging, copy
from vt_manager.communication.utils.X... |
import numbers
from six import string_types
from pypif.obj.common.pio import Pio
from pypif.obj.common.scalar import Scalar
from pypif.obj.common.file_reference import FileReference
class Value(Pio):
"""
Information about a scalar, vector, or matrix, or a list of one of those.
"""
def __init__(self, nam... |
from __future__ import absolute_import
from salt import acl
from salttesting import TestCase, skipIf
from salttesting.mock import (
NO_MOCK,
NO_MOCK_REASON,
)
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../../')
@skipIf(NO_MOCK, NO_MOCK_REASON)
class ClientACLTestCase(TestCase):
'''... |
from time import time
class profile(object):
def __init__(self, name):
self._name = name
def __enter__(self):
self._start = time()
def __exit__(self, *args):
stop = time()
print "%s took %6.2f s" % (self._name, stop - self._start) |
import pytest
from indy import IndyError
from indy import did
from indy import wallet
from indy.error import ErrorCode
@pytest.mark.asyncio
@pytest.mark.parametrize("wallet_handle_cleanup", [False])
async def test_import_wallet_works(wallet_handle, wallet_config, credentials, export_config):
(_did, _verkey) = await... |
"""Utilities related to FeatureColumn."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.framework.python.framework import checkpoint_utils
from tensorflow.contrib.framework.python.framework import experimental
from tensorflow.contrib... |
from __future__ import division
from builtins import str
import h5py
import numpy as np
def create_minibatch_x(minibatches, minibatch_markers, epoch_axis):
"""
Helper function to build x axis for data captured per minibatch.
Arguments:
minibatches (int): how many total minibatches
minibatch_... |
import sqlalchemy
def upgrade(migrate_engine):
meta = sqlalchemy.MetaData()
meta.bind = migrate_engine
event = sqlalchemy.Table('event', meta, autoload=True)
event.c.logical_resource_id.alter(name='resource_name') |
import logging
import StringIO
from iso8601 import parse_date
from datetime import datetime
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from lr.model.base_model import appConfig
from lr.lib.base import BaseController, render
import json
impo... |
import os
from http.cookiejar import LWPCookieJar
from pants.process.lock import OwnerPrintingInterProcessFileLock
from pants.subsystem.subsystem import Subsystem
from pants.util.dirutil import safe_mkdir_for
from pants.util.memo import memoized_property
class Cookies(Subsystem):
options_scope = "cookies"
@clas... |
"""
Unit tests for the arpcache module
"""
import os
import subprocess
import sys
import unittest
import mock
import moduletests.src.arpcache
try:
# Python 2.x
from cStringIO import StringIO
except ImportError:
# Python 3.x
from io import StringIO
if sys.hexversion >= 0x3040000:
# contextlib.redirec... |
"""x509 module tests."""
import array
import types
from google.apputils import app
from google.apputils import basetest
import mox
import stubout
from pyasn1.type import univ
from simian.auth import x509
from simian.auth import tlslite_bridge
class Error(Exception):
"""Base Error."""
class X509ModuleTest(mox.MoxTestB... |
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.7.4
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
import unittest
import kubern... |
import re
import os
import random
import json
import string
import ctypes
from myexception import *
PATH = './img/'
dm2 = ctypes.WinDLL('./CrackCaptchaAPI.dll')
if not os.path.exists('./img'):
os.mkdir('./img')
def str_tr(content):
instr = "0123456789"
outstr ="QAEDTGUJOL"
trantab = string.maketrans(ins... |
"""Test alter op layout pass"""
import tvm
from tvm import relay
from tvm.relay.op import register_alter_op_layout
from tvm.relay import transform, analysis
def run_opt_pass(expr, passes):
passes = passes if isinstance(passes, list) else [passes]
mod = relay.Module.from_expr(expr)
seq = transform.Sequential... |
"""Let's Encrypt client errors."""
class Error(Exception):
"""Generic Let's Encrypt client error."""
class AccountStorageError(Error):
"""Generic `.AccountStorage` error."""
class AccountNotFound(AccountStorageError):
"""Account not found error."""
class ReverterError(Error):
"""Let's Encrypt Reverter e... |
"""Tests for tensorflow.python.client.Timeline."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import tensorflow as tf
from tensorflow.python.client import timeline
class TimelineTest(tf.test.TestCase):
def _validateTrace(self, chrome_trace_... |
import testtools
from tempest.api.object_storage import base
from tempest.common.utils import data_utils
from tempest import config
from tempest import exceptions
from tempest.test import attr
from tempest.test import HTTP_SUCCESS
QUOTA_BYTES = 10
QUOTA_COUNT = 3
SKIP_MSG = "Container quotas middleware not available."
... |
from .Node import error
SYNTAX_NODE_SERIALIZATION_CODES = {
# 0 is 'Token'. Needs to be defined manually
# 1 is 'Unknown'. Needs to be defined manually
'UnknownDecl': 2,
'TypealiasDecl': 3,
'AssociatedtypeDecl': 4,
'IfConfigDecl': 5,
'PoundErrorDecl': 6,
'PoundWarningDecl': 7,
'Pound... |
"""Support for RFXtrx devices."""
import binascii
from collections import OrderedDict
import logging
import RFXtrx as rfxtrxmod
import voluptuous as vol
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_NAME,
ATTR_STATE,
CONF_DEVICE,
CONF_DEVICES,
CONF_HOST,
CONF_PORT,
EVENT_HOMEASS... |
def split_camel_case(input):
def remove_camel_case(camel_case_input):
no_camel_case = ""
if len(camel_case_input) <= 0:
return ""
no_camel_case += camel_case_input[0].lower()
for c in camel_case_input[1:]:
if c.isupper():
no_camel_case += "_" +... |
"""
Neutron REST Proxy Plug-in for Big Switch and FloodLight Controllers.
NeutronRestProxy provides a generic neutron plugin that translates all plugin
function calls to equivalent authenticated REST calls to a set of redundant
external network controllers. It also keeps persistent store for all neutron
state to allow ... |
import sys
import os
sys.path.insert(0, os.path.abspath('../../'))
sys.path.insert(0, os.path.abspath('../'))
sys.path.insert(0, os.path.abspath('./'))
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.todo',
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
... |
"""Base classes for policy unit tests."""
import os
import fixtures
from oslo_config import cfg
from oslo_config import fixture as config_fixture
from oslo_policy import opts as policy_opts
from oslo_serialization import jsonutils
from oslotest import base
from monasca_api.common.policy import policy_engine
CONF = cfg.... |
import os
import platform
import re
import subprocess
import tempfile
import lit.formats
import lit.util
from lit.llvm import llvm_config
from lit.llvm.subst import ToolSubst
config.name = 'MLIR_INTEGRATION'
config.test_format = lit.formats.ShTest(not llvm_config.use_lit_shell)
config.suffixes = ['.mlir']
config.test_s... |
import calendar
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.contrib.auth.models import User
from django.contrib.admin.views.decorators import staff_member_required
from accounts.views import _backe... |
import unittest
from robot.parsing.model import TestCase, TestCaseFile
from robot.utils.asserts import assert_equals
from robotide.controller.commands import ChangeTag
from robotide.controller.filecontrollers import TestCaseFileController
from robotide.controller.macrocontrollers import TestCaseController
from robotide... |
from __future__ import print_function
import os
import sys
import warnings
sys.path.insert(1, os.path.join("..","..","..",".."))
import h2o
from h2o.estimators import H2OTargetEncoderEstimator
from h2o.exceptions import H2ODeprecationWarning
from h2o.utils.metaclass import fullname
from tests import pyunit_utils as pu
... |
"""Tests the mysql data store."""
import unittest
from grr.lib import server_plugins
import logging
from grr.lib import access_control
from grr.lib import config_lib
from grr.lib import data_store
from grr.lib import data_store_test
from grr.lib import flags
from grr.lib import test_lib
from grr.lib.data_stores import ... |
from enum import Enum
from math import *
__version__ = "0.3.0"
LIBCELLML_VERSION = "0.2.0"
STATE_COUNT = 3
VARIABLE_COUNT = 19
class VariableType(Enum):
VARIABLE_OF_INTEGRATION = 1
STATE = 2
CONSTANT = 3
COMPUTED_CONSTANT = 4
ALGEBRAIC = 5
EXTERNAL = 6
VOI_INFO = {"name": "time", "units": "milli... |
import json
from unittest import mock
from oslo_config import cfg
from solum.api.controllers.v1 import trigger
from solum.tests import base
from solum.tests import fakes
@mock.patch('pecan.request', new_callable=fakes.FakePecanRequest)
@mock.patch('pecan.response', new_callable=fakes.FakePecanResponse)
@mock.patch('sol... |
"""Test the flow archive."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import os
from absl import app
import mock
from grr_response_core.lib import utils
from grr_response_core.lib.rdfvalues import paths as rdf_paths
from grr_response_server.flows.gen... |
"""Commands related to networks are in this module"""
import click
import sys
from hil.cli.client_setup import client
@click.group()
def network():
"""Commands related to network"""
@network.command(name='create', short_help='Create a new network')
@click.argument('network')
@click.argument('owner')
@click.option('... |
import gtk
from objects.gradientcolor import GradientColor
from objects.gradient import Gradient
from interfaces.signalizable import Signalizable
class GradientLine(gtk.Viewport):
def __init__(self, moving_callback=None, color_callback=None, gradient=None):
"""
moving_callback - callback function to... |
import argparse
from dvc.command.base import CmdBase, append_doc_link, fix_subparsers
from dvc.command.config import CmdConfig
from dvc.compare import TabularData
from dvc.config import ConfigError
from dvc.exceptions import DvcException
from dvc.types import Dict, List
from dvc.ui import ui
from dvc.utils import forma... |
import os
from os import walk
templatePath = r'templates/serviceTemplate.txt'
writePath = r'/Source/Api/service-hmlFhirConverter/src/main/java/org/nmdp/hmlfhirconverter/service'
class ServiceGenerator:
def get_template(self):
with open(templatePath, 'r') as fileReader:
return fileReader.read()
... |
"""
磁盘监控模块
"""
from config import disk
from lib import core
import os,re
def init():
"对外接口"
sign=True
for t in disk.DISK_PATH:
warn,data=check(t)
if not warn:
login_time=time.time()
message="磁盘监控预警提示,磁盘使用率超过%s"%(disk.DISK_USED)+"%\n监控结果:"+data
message=mess... |
from a10sdk.common.A10BaseClass import A10BaseClass
class DfBitTransparency(A10BaseClass):
"""Class Description::
Add an empty IPv6 fragmentation header if IPv4 DF bit is zero (default:disabled).
Class df-bit-transparency supports CRUD Operations and inherits from `common/A10BaseClass`.
This class is th... |
from climate.api.v1.oshosts import service as service_api
from climate import tests
class RPCApiTestCase(tests.TestCase):
def setUp(self):
super(RPCApiTestCase, self).setUp()
self.s_api = service_api
self.fake_list = []
self.fake_computehost = {}
fake_get_computehosts = self.... |
import dpkt
import socket
import logging
l = logging.getLogger("simuvex.s_pcap")
class PCAP(object):
def __init__(self,path, ip_port_tup, init=True):
self.path = path
self.packet_num = 0
self.pos = 0
self.in_streams = []
self.out_streams = []
#self.in_buf = ''
... |
from syslog import syslog
module_name = "Syslog"
config = {
"prefix": "Default Prefix"
}
def handle_alert(message):
syslog("{} - {}".format(config["prefix"], message)) |
'''
session.py: defines the Session class used by the core-daemon daemon program
that manages a CORE session.
'''
import os, sys, tempfile, shutil, shlex, atexit, gc, pwd
import threading, time, random
from core.api import coreapi
if os.uname()[0] == "Linux":
from core.netns import nodes
from core.netns.vnet im... |
"""
sphinxcontrib.httpdomain
~~~~~~~~~~~~~~~~~~~~~~~~
The HTTP domain for documenting RESTful HTTP APIs.
:copyright: Copyright 2011 by Hong Minhee
:license: BSD, see LICENSE for details.
"""
import re
from docutils import nodes
from docutils.parsers.rst.roles import set_classes
from pygments.lexer i... |
from lino.api import dd
class Tag(dd.Model):
name = dd.CharField(max_length=100)
def __str__(self):
return self.name
@dd.receiver(dd.auto_create)
def my_auto_create_handler(sender, **kw):
print("My handler was called with {}".format(sender)) |
from pathutils import full_path
CONFIG = {
"entityid" : "urn:mace:example.com:saml:roland:sp",
"name" : "urn:mace:example.com:saml:roland:sp",
"description": "My own SP",
"service": {
"sp": {
"endpoints":{
"assertion_consumer_service": ["http://lingon.catalogix.se:808... |
import time
from multiprocessing import Lock
class IndexedTimeCache():
'''
@param ttl: Maxmimum Time to live for inserted item (first one will be applied)
'''
lock = Lock()
def __init__(self, ttl=30):
self.cache = dict()
self.ttl = ttl
def insert(self, index, data, ignore_fields=[]):
IndexedTimeCache.lock.a... |
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
exce... |
import itertools
from django.conf import settings
from django.db import models
from django.utils import translation as translation_utils
from olympia.addons.query import IndexCompiler, IndexQuery
def order_by_translation(qs, fieldname):
"""
Order the QuerySet by the translated field, honoring the current and
... |
from .iqr_session import IqrSession
from .iqr_controller import IqrController
__all__ = [
'IqrController',
'IqrSession',
] |
import pytz
from django.conf import settings
from django.utils.dates import MONTHS, WEEKDAYS, WEEKDAYS_ABBR
from django.utils.translation import gettext as _
WAGTAILADMIN_PROVIDED_LANGUAGES = [
('ar', 'Arabic'),
('ca', 'Catalan'),
('cs', 'Czech'),
('de', 'German'),
('el', 'Greek'),
('en', 'Engli... |
class NamespaceAlreadyRegistered(Exception):
pass
class NoParentFound(Exception):
pass |
"""This is the Bokeh charts interface. It gives you a high level API to build
complex plot is a simple way.
This is the Histogram class which lets you build your histograms just passing
the arguments to the Chart class and calling the proper functions.
"""
from __future__ import absolute_import
from ...models import Ra... |
import sys
sys.path.extend(['.', '..'])
import unittest
suite = unittest.TestLoader().loadTestsFromNames(
[
'test_c_lexer',
'test_c_ast',
'test_general',
'test_c_parser',
]
)
unittest.TextTestRunner(verbosity=1).run(suite) |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
import sys
import logging
logging.basicConfig(level=logging.DEBUG)
import uui... |
def get_type_name(type_name, sub_type=None):
""" Returns a Java type according to a spec type
"""
if type_name == "enum":
return type_name
elif type_name == "boolean":
return "Boolean"
elif type_name == "integer":
return "Long"
elif type_name == "time":
return "Fl... |
import sys
import matplotlib.pyplot as plt
import numpy as np
import sklearn.gaussian_process
import sklearn.kernel_approximation
import splitter
from appx_gaussian_processes import appx_gp
TRAINING_NUM = 1500
TESTING_NUM = 50000
ALPHA = .003
LENGTH_SCALE = 1
GAMMA = .5 / (LENGTH_SCALE ** 2)
COMPONENTS = 100
def interv... |
import itertools
import json
import os.path
import re
import sys
from json_parse import OrderedDict
_idl_generators_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
os.pardir, os.pardir, 'ppapi', 'generators')
if _idl_generators_path in sys.path:
import idl_parser
e... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cv2
from chainer import cuda
import chainer.serializers as S
from chainer import Variable
from fcn.models import FCN32s
import numpy as np
import cv_bridge
import jsk_apc2016_common
from jsk_topic_tools i... |
import m5
from m5.objects import *
require_sim_object("TrafficGen")
require_sim_object("CommMonitor")
cpu = TrafficGen(config_file = "tests/quick/se/70.tgen/tgen-dram-ctrl.cfg")
system = System(cpu = cpu, physmem = DDR3_1600_x64(),
membus = NoncoherentBus(width = 16),
clk_domain = SrcClo... |
import numpy as np
import scipy
from ..util.univariate_Gaussian import std_norm_cdf, std_norm_pdf
import scipy as sp
from ..util.misc import safe_exp, safe_square, safe_cube, safe_quad, safe_three_times
class GPTransformation(object):
"""
Link function class for doing non-Gaussian likelihoods approximation
... |
"""Base classes for classifiers"""
from ..core.classes import Processor
class BaseClassifier(Processor):
'''
The base class for classifiers.
'''
def __init__(self, *args, **kwargs):
super(BaseClassifier, self).__init__(*args, **kwargs)
self.classifier = None
class SklearnClassifier(BaseC... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.