content string |
|---|
from odoo.tests import common
class TestAgreementOperatingUnit(common.TransactionCase):
def setUp(self):
super(TestAgreementOperatingUnit, self).setUp()
self.agreement_obj = self.env['agreement']
self.serviceprofile_obj = self.env['agreement.serviceprofile']
self.res_users_model =... |
from fxpt.qt.pyside import QtCore, QtWidgets
from . import search_line_edit, results_list_widget, searcher, cfg
class ClosePopupFilter(QtCore.QObject):
# noinspection PyMethodOverriding
def eventFilter(self, target, event):
eventType = event.type()
if eventType == QtCore.QEvent.WindowDeactiv... |
"""Unit test for Action dependency system."""
import unittest
from ClusterShell.Task import task_self
from Shine.Lustre.Actions.Action import CommonAction, ActionGroup, \
ACT_OK, ACT_WAITING, ACT_ERROR
class TestAction(CommonAction):
def __init__(self, cmd, timeout=None)... |
from oslo_config import cfg
from oslo_log import log as logging
from nova.i18n import _LW
from nova_solverscheduler.scheduler.solvers.constraints \
import num_instances_constraint
from nova_solverscheduler.scheduler.solvers import utils
CONF = cfg.CONF
CONF.import_opt('max_instances_per_host',
... |
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
class WalletTest (BitcoinTestFramework):
def check_fee_amount(self, curr_balance, balance_with_fee, fee_per_byte, tx_size):
"""Return curr_balance after asserting the fee was in range"""
fee = balance_... |
"""Tests for authbox.gpio_button"""
import unittest
from functools import partial
import authbox.gpio_button
from authbox import fake_gpio_for_testing
from authbox.compat import queue
from RPi import GPIO
class ImpatientQueue(queue.Queue):
def __init__(self, fake_time):
queue.Queue.__init__(self)
... |
from django.test import TestCase, LiveServerTestCase
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
# browser = webdriver.Chrome()
# browser.get('http://google.com')
# browser.quit()
# dr = webdriver.PhantomJS()
import json
from rest_framework.test import APIRequestFactory, APITestCase
... |
import csv
import matplotlib.pyplot as plt
import networkx as nx
import pickle
def plot_distribution(nx_graph, filename):
"""
Plots the in/out degree distribution of the Graph
:rtype : None
:param nx_graph: nx.Digraph() - Directed NetworkX Graph
:param filename: String - Name of the file to save t... |
import logging
import os
import time
from urllib2 import HTTPError, URLError
from djangoappengine.boot import PROJECT_DIR
from djangoappengine.utils import appid, have_appserver
REMOTE_API_SCRIPTS = (
'$PYTHON_LIB/google/appengine/ext/remote_api/handler.py',
'google.appengine.ext.remote_api.handler.applicati... |
# -*- coding: utf-8 -*-
"""
Rösch-MacAdam colour solid - Visible Spectrum Volume Computations
=================================================================
Defines the objects related to *Rösch-MacAdam* colour solid, visible spectrum
volume computations.
References
----------
- :cite:`Lindbloom2015` : Lindblo... |
"""
NIGHTRING measures the center coordinates and radius of one or more
night-time calibration rings. It calculates the current wavelength
zero point (A) for use in tracking the etalon drifts through the night.
It uses T. Williams code. The code assumes all the files are in the same directory. Also assumes that ... |
# -*- coding: UTF-8
#
# wizard
from globaleaks.orm import transact
from globaleaks.handlers.base import BaseHandler
from globaleaks.handlers.admin.context import db_create_context
from globaleaks.handlers.admin.receiver import db_create_receiver
from globaleaks.handlers.admin.user import db_create_admin_user
from glob... |
# -*- coding: utf-8 -*-
from django.contrib.gis.db import models
from django.template.defaultfilters import slugify
from django.utils.translation import ugettext_lazy as _
class Town(models.Model):
country_code = models.CharField(_('Country code'), max_length=2)
postal_code = models.IntegerField(_('Postal cod... |
# test_getopt.py
# David Goodger <<EMAIL>> 2000-08-19
from test.support import verbose, run_doctest, run_unittest, EnvironmentVarGuard
import unittest
import getopt
import os
sentinel = object()
class GetoptTests(unittest.TestCase):
def setUp(self):
self.env = EnvironmentVarGuard()
if "POSIXLY_C... |
"""Tests the Usage class implementation."""
import tensorflow as tf
import unittest
from .. dnc import usage
from numpy.testing import assert_array_almost_equal, assert_array_equal
def suite():
"""Create testing suite for all tests in this module."""
suite = unittest.TestSuite()
suite.addTes... |
import netaddr
import tempfile
import time
from apic_ml2.neutron.plugins.ml2.drivers.cisco.apic import (
network_constraints as anc)
from neutron.tests import base
class TestNetworkConstraints(base.BaseTestCase):
class MockSource(anc.NetworkConstraintsSource):
def get_subnet_constraints(self, tenant... |
import mock
import netaddr
from rally.plugins.openstack.context.network import networks as network_context
from tests.unit import test
NET = "rally.plugins.openstack.wrappers.network."
class NetworkTestCase(test.TestCase):
def get_context(self, **kwargs):
return {"task": {"uuid": "foo_task"},
... |
from threading import Thread
from array import array
from struct import pack
import pyaudio
class AudioPlayer:
'''
Consumes a 2D array in which each row is a list of floats between 0 and 1.
Each row represents one channel of audio data, and each float represents
an amplitude.
Map this data to a 2D... |
import pytest
from conda_devenv.devenv import load_yaml_dict
def test_load_yaml_dict(datadir):
conda_yaml_dict, environment = load_yaml_dict(str(datadir / "c.yml"))
assert set(environment.keys()) == {"PATH"}
assert set(environment["PATH"]) == {"b_path", "a_path"}
def test_load_yaml_dict_with_wrong_defi... |
from PyQt5.QtWidgets import QWidget, QFrame, QScrollArea, QToolButton, QGridLayout, QSizePolicy
from PyQt5.QtCore import Qt, QParallelAnimationGroup, QPropertyAnimation, QAbstractAnimation
class GroupWidget(QWidget):
def __init__(self, parent=None, title='', animation_duration=300):
"""
References... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}
import re
from ansible.module_utils.network.ios.ios import run_commands
from ansible.module_utils.network.ios.ios import ios_argument_spec, check_args
from ansible.module_utils.bas... |
from unittest.mock import Mock, patch
from scripts.assign_container_name import AssignContainerName
from tests.test_common import TestEPP, NamedMock
def fake_output(output_type):
return Mock(
output_type=output_type,
samples=[Mock(project=NamedMock(real_name='a_project_'))],
container=Name... |
import El
m = 2000
n = 4000
testMehrotra = True
testIPF = False
manualInit = False
display = False
progress = True
worldRank = El.mpi.WorldRank()
worldSize = El.mpi.WorldSize()
# Make Q a sparse semidefinite matrix
def Semidefinite(height):
Q = El.DistSparseMatrix()
Q.Resize(height,height)
localHeight = Q.Local... |
# -*- coding: utf-8 -*-
"""Predicates for edge data from BEL graphs."""
from functools import wraps
from typing import Any, Callable, Optional
from .typing import EdgePredicate
from .utils import part_has_modifier
from ..graph import BELGraph
from ...constants import (
ACTIVITY, ANNOTATIONS, ASSOCIATION, CAUSAL_... |
#!/usr/bin/python
import os
import re
import requests
import sys
import wget
def downloadTheThings(urlList):
dirNotConfirmed = True
while dirNotConfirmed:
directory = raw_input('Save in what directory? (Leave blank for current dir): ')
try:
if directory == '': # If blank, use current directory
... |
from oslo.config import cfg
from neutron.common import topics
from neutron.openstack.common import importutils
from neutron.openstack.common import log as logging
LOG = logging.getLogger(__name__)
SG_RPC_VERSION = "1.1"
security_group_opts = [
cfg.StrOpt(
'firewall_driver',
default='neutron.agent... |
'''
Programmer : EOF
E-mail : <EMAIL>
Date : 2015.12.12
File : naive_beyesian.py
'''
import numpy
PI = 3.14159
class NaiveBayesian:
"""
$ Key words explantion $
Feature(demention):
It also corresponding to dimentions of sample.
... |
# -*- coding: utf-8 -*-
'''
Genesis Add-on
Copyright (C) 2015 lambda
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 ... |
"""Functions for adding results to perf dashboard."""
# This file was copy-pasted over from:
# //build/scripts/slave/results_dashboard.py
# That file is now deprecated and this one is
# the new source of truth.
import calendar
import datetime
import httplib
import json
import os
import subprocess
import sys
import ti... |
"""Demonstration of ODL operators as pytorch modules.
This example shows how to wrap an ODL ``Operator`` as a
``torch.nn.Module`` that can be used as a layer in a Neural Network.
It supports backpropagation as well as inputs that contain extra dimensions
for, e.g., batches and channels.
"""
import numpy as np
import ... |
import wxversion
import sys
wxversion.select("2.8")
import wx
sys.path.insert(0,'twitstream')
sys.path.insert(0,'sendgrid')
sys.path.insert(0,'facebook')
sys.path.insert(0,'twilio')
import twiliohelp
import twiliostuff
import stream
import sendgridstuff
class main(wx.Frame): #Main Frame
def __init__(self,parent,id):
... |
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.txt')) as f:
README = f.read()
with open(os.path.join(here, 'CHANGES.txt')) as f:
CHANGES = f.read()
requires = [
'pyramid',
'pyramid_jinja2',
'pyramid_debu... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
if sys.version_info >= (3, 0):
from unittest.mock import patch
else:
from mock import patch
from pyfakefs import fake_filesystem_unittest
from shellfoundry.commands.pack_command import PackCommandExecutor
from tests.asserts import assertFileExist... |
'''
This is a set of plot functions dedicated to DANA. They allow to show
connections when user click on a unit and to display unit activity when mouse is
over a unit.
'''
from dana import *
from functools import partial
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
def format_coord(axis, x, y):
''... |
import atexit
import datetime
import logging
import multiprocessing
import os
import re
import signal
import sys
import time
from tornado.ioloop import IOLoop
from tornado.web import Application
import handlers
import settings
import template
_PID_FILE = 'motioneye.pid'
_CURRENT_PICTURE_REGEX = re.compile('^/pictur... |
import os
import unittest
from alligator.backends.locmem_backend import Client as LocmemClient
from alligator.backends.redis_backend import Client as RedisClient
from alligator.constants import (
ALL,
WAITING,
SUCCESS,
FAILED,
RETRYING,
CANCELED,
)
from alligator.gator import Gator
from alligat... |
# -*- coding: utf-8 -*-
"""
Base Class for Compile/Link information
"""
import os
import logging
log = logging.getLogger()
from blas_config.arch import binary_format
PKG_CONFIG_TEMPLATE = """
prefix={prefix}
exec_prefix=${{prefix}}
libdir={libdir}
includedir={includedir}
rpath=-Wl,-rpath -Wl,{libdir}
{body}
"""
... |
from unittest import mock
from django.utils import timezone
import pytest
import stripe
from model_mommy import mommy
from rest_framework.reverse import reverse
from restframework_stripe import models
from restframework_stripe.test import get_mock_resource
@mock.patch("stripe.Account.create")
@pytest.mark.django_... |
from django.shortcuts import render
from django.http import HttpResponse
from rest_framework import generics
from rest_framework.response import Response
from rest_framework import status
from api.models import *
from api.serializers import *
import cloudinary
# Create your views here.
def index(request):
return H... |
"""Command line tool for creating videoMD metadata."""
from __future__ import unicode_literals, print_function
import os
import sys
import click
import six
import videomd
from siptools.mdcreator import MetsSectionCreator
from siptools.utils import fix_missing_metadata, scrape_file
click.disable_unicode_literals_war... |
from django.core.management.base import BaseCommand, CommandError
from main.models import Platform, PlatformType, Country
import csv
# This file is part of https://github.com/cpina/science-cruise-data-management
#
# This project was programmed in a hurry without any prior Django experience,
# while circumnavigating th... |
import mock
from nova import exception
from nova import test
from nova.tests import fake_instance
from nova.virt.hyperv import vmops
class VMOpsTestCase(test.NoDBTestCase):
"""Unit tests for the Hyper-V VMOps class."""
def __init__(self, test_case_name):
super(VMOpsTestCase, self).__init__(test_case... |
import unittest
import numpy as np
from AnyQt.QtCore import QT_VERSION_STR
from Orange.data import Table, Domain, ContinuousVariable, DiscreteVariable
from Orange.widgets.tests.base import WidgetTest
from Orange.regression.knn import KNNRegressionLearner
QT_TOO_OLD = QT_VERSION_STR < '5.3'
try:
from Orange.widge... |
import xml.etree.ElementTree as ET
from requestbuilder import Arg
from euca2ools.commands.s3 import S3Request, validate_generic_bucket_name
class CreateBucket(S3Request):
DESCRIPTION = 'Create a new bucket'
ARGS = [Arg('bucket', route_to=None, help='name of the new bucket'),
Arg('--location', ro... |
# encoding:utf8
"""
DragonPy - Dragon 32 emulator in Python
=======================================
:created: 2014 by Jens Diemer - www.jensdiemer.de
:copyleft: 2014 by the DragonPy team, see AUTHORS for more details.
:license: GNU GPL v3 or above, see LICENSE for more details.
"""
from __future_... |
from openerp.osv import fields, osv
from openerp.tools.translate import _
class ineco_production_printmo(osv.osv_memory):
_name = 'ineco.production.printmo'
_description = 'Wizard inform print mo'
_columns = {
'is_print': fields.boolean('Print MO'),
}
def update_data(self, cr, uid... |
import os
import sys
import inspect
from collections import defaultdict
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
from plugz import PluginTypeBase
import errors
""" Main storage of the plugins."""
_loaded_plugins = defaultdict(list)
def register_plugin(f):
"""... |
from oslo_config import cfg
from oslo_utils import timeutils
from ceilometer.agent import plugin_base
from ceilometer.i18n import _
from ceilometer.ipmi.notifications import ironic as parser
from ceilometer.ipmi.platform import exception as ipmiexcept
from ceilometer.ipmi.platform import ipmi_sensor
from ceilometer.op... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('StateData', '0003_auto_20150603_1327'),
]
operations = [
migrations.AddField(
model_name='energyproduction',
... |
# -*- coding: utf-8 -*-
from admin_tools.menu import items, Menu
from admin_tools.menu.items import AppList, MenuItem
from congo.conf import settings
from django.apps import apps as django_apps
from django.core.urlresolvers import reverse
from django.utils.datastructures import SortedDict
from django.utils.trans... |
"""A wait callback to allow psycopg2 cooperation with gevent.
Use `patch_psycopg()` to enable gevent support in Psycopg.
"""
# Copyright (C) 2010-2012 Daniele Varrazzo <<EMAIL>>
# All rights reserved. See COPYING file for details.
from __future__ import absolute_import
import psycopg2
from psycopg2.extras import ... |
import sys
import os
import argparse
from clipper_admin import DockerContainerManager, ClipperConnection, ClipperException
from clipper_admin import version
CLIPPER_R_CONTAINER_BASE_IMAGE = "clipper/r-container-base:{}".format(
version.__version__)
if __name__ == "__main__":
parser = argparse.ArgumentParser(... |
"""
read_cell_by_cell.py
:copyright: (c) 2014-2015 by Onni Software Ltd.
:license: New BSD License, see LICENSE for more details
This shows how to use **Reader** class to go through a single
page spreadsheet, The output is::
1.0
2.0
3.0
4.0
5.0
6.0
7.0
8.0
9.0
"""
import os
import... |
"""
Graph test module.
This module contains tests of graph module
"""
import unittest
from app.logic.graph import Graph
from app.logic.graph_exception import GraphException
from app.logic.node_not_found_exception import NodeNotFoundException
from app.logic.node import Node
class TestGraph(unittest.TestCase):
def... |
# -*- coding: utf-8 -*-
import sys
import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('... |
#!/usr/bin/env python
"""Tests for gr1 fragment untilities."""
from __future__ import print_function
import logging
logging.basicConfig(level=logging.DEBUG)
logging.getLogger('tulip.ltl_parser_log').setLevel(logging.WARNING)
logging.getLogger('tulip.spec.form').setLevel(logging.WARNING)
logging.getLogger('omega').setL... |
from . import HermesTestCase
from .. import models, settings
class PostTestCase(HermesTestCase):
def test_short(self):
"""A Post should return the truncated body if there is no summary"""
expected = (
u"<p>I've got to find a way to escape the horrible ravages of youth. "
u"... |
"""
TO DO:
1)Lifespans
2)Ratio count
3)Equilibrium
4)Humans
"""
#IMPORT YOUR LIBRARIES
try :
from tkinter import *
except :
from Tkinter import *
from random import randint
from time import sleep, time
import uuid
from math import sqrt
#CONSTANTS
HEIGHT = 400
WIDTH = 800
#CONTROL VARIABLES
#startin... |
import logging
import os
import re
import subprocess
import threading
_CHROME_SRC = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)
_LLVM_SYMBOLIZER_PATH = os.path.join(
_CHROME_SRC, 'third_party', 'llvm-build', 'Release+Asserts', 'bin',
'llvm-symbolizer')
_BINARY = re.compile(r'0b[0,1]+')
_HEX ... |
# -*- coding: 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 model 'Slideshow'
db.create_table('demo_widgets_slideshow', (
('id', self.gf('django.db... |
import datetime
from pylab import plot, xlabel, ylabel, title, show
from portfolio.account_builder import AccountBuilder
from portfolio_creator.data_source import DataSource
from portfolio_creator.portfolio_creator import PortfolioCreator
from utilities.constants import Constants
from utilities.epoch_date_converter i... |
import uuid
import six
from nsq.http import nsqd, ClientException
from nsq.util import pack
from common import HttpClientIntegrationTest, ClientTest
class TestNsqdClient(ClientTest):
'''Testing the nsqd client in isolation'''
def setUp(self):
self.client = nsqd.Client('http://foo:1')
def test_mp... |
#!/usr/bin/env python
from __future__ import print_function
"""
Reciprocal space volume mapper
Transfers images into reciprocal space by pixel mapping
"""
import numpy, logging
from ImageD11 import parameters, transform, indexing, \
cImageD11, blobcorrector, rsv, ImageD11options
class rsv_mapper(object):
"... |
import logging
import os
LOG = logging.getLogger(__name__)
# fallback if locale parsing fails
FALLBACK = "en"
# those languages need the full language-code, the other ones
# can be abbreved
FULL = ["pt_BR",
"zh_CN", "zh_TW"]
def get_languages():
"""Helper that returns the split up languages"""
if not ... |
from pychron.pipeline.plot.panels.figure_panel import FigurePanel
from pychron.pipeline.plot.plotter.spectrum import Spectrum
# ============= local library imports ==========================
class SpectrumPanel(FigurePanel):
_figure_klass = Spectrum
def _get_init_xlimits(self):
return None, 0, 100... |
"""src URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based ... |
""" Comparison of sim-2.ms casa and ARL dirty images.
im.open('sim-2.ms')
im.defineimage(cellx='20arcsec', nx=512)
im.makeimage('sim-2.dirty')
im.makeimage('observed', 'casa_imaging_sim_2_dirty')
ia.open('casa_imaging_sim_2_dirty')
ia.tofits('casa_imaging_sim_2_dirty.fits')
"""
import sys
from data_models.parameters ... |
# Implementation of classic arcade game Pong
import simplegui
import random
# initialize globals - pos and vel encode vertical info for paddles
START_VELOCITY = 80
VELOCITY_INCREASE = 0.1
WIDTH = 600
HEIGHT = 400
HALF_WIDTH = WIDTH / 2
HALF_HEIGHT = HEIGHT / 2
BALL_RADIUS = 20
PAD_WIDTH = 8
PAD_HEIGHT = 80
HALF_PAD_W... |
import torch
# import numpy as np
from torch import nn, autograd, optim
from matplotlib import pyplot as plt
num_data_samples = 16
hidden_size = 8
batch_size = 16
# num_critic_steps = 5
# weight_clipping = 0.01
data_samples = torch.rand(num_data_samples, 1)
class Discriminator(nn.Module):
def __init__(self, hi... |
# -*- coding: 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 model 'UserProfile'
db.create_table(u'crowdataapp_userprofile', (
(u'id', self.gf('djan... |
"""
Based on "python-archive" -- https://pypi.org/project/python-archive/
Copyright (c) 2010 Gary Wilson Jr. <<EMAIL>> and contributors.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without re... |
# Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.golf.DistributedGolfCourse
from panda3d.core import TextNode, VBase4
from direct.interval.IntervalGlobal import Sequence, Func, Wait, LerpColorScaleInterval, Parallel
from direct.distributed import DistributedObject
from direct.directnotify import ... |
from PyQt4 import QtCore,QtGui
import sys
class StdOutRedirector:
def __init__(self,edit):
self.buff=''
self.edit = edit
self.__console__=sys.stdout
def write(self, output_stream):
self.buff+=output_stream
self.edit.setText(self.buff)
class MainFrame(QtGui.QDialog):
... |
from zope.interface import implements
from twisted.plugin import IPlugin
from twisted.python import usage, reflect
from twisted.application.service import IServiceMaker
from gloss.conf import settings
class Options(usage.Options):
"""Define the options accepted by the ``twistd multiple_mllp`` plugin"""
synopsi... |
from senlin.drivers import base
from senlin.drivers import sdk
class NeutronClient(base.DriverBase):
"""Fake Neutron V2 driver for test."""
def __init__(self, ctx):
self.fake_network = {
"status": "ACTIVE",
"subnets": [
"54d6f61d-db07-451c-9ab3-b9609b6b6f0b"
... |
import copy
from opus_core.logger import logger
from opus_core.datasets.dataset import Dataset
from opus_core.variables.variable_name import VariableName
from opus_core.simulation_state import SimulationState
from opus_core.aspect.dataset_aspect import DatasetAspect
class ExogenousAspectForDataset(DatasetAspect):
... |
from __future__ import absolute_import
import unittest
import bokeh.resources as resources
from bokeh.resources import _get_cdn_urls
WRAPPER = """Bokeh.$(function() {
foo
});"""
WRAPPER_DEV = '''require(["jquery", "main"], function($, Bokeh) {
Bokeh.set_log_level("info");
Bokeh.$(function() {
foo
... |
# -*- coding: utf-8 -*-
"""
dump_configuration.py
superlachaise_api
Created by Maxime Le Moine on 14/06/2015.
Copyright (c) 2015 Maxime Le Moine.
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
... |
# coding=utf-8
"""Dialog test.
.. 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; either version 2 of the License, or
(at your option) any later version.
"""
__author__ = '<EM... |
import json
def decode_predictions(preds, top=5, class_list_path=None):
"""Decodes the prediction of an ImageNet model.
Arguments:
preds: Numpy tensor encoding a batch of predictions.
top: integer, how many top-guesses to return.
class_list_path: Path to the canonical imagenet_class_index.json fi... |
#!/usr/bin/python
"""Test of structural navigation by blockquote."""
from macaroon.playback import *
import utils
sequence = MacroSequence()
sequence.append(KeyComboAction("<Control>Home"))
sequence.append(utils.StartRecordingAction())
sequence.append(KeyComboAction("q"))
sequence.append(utils.AssertPresentationAc... |
import io
from collections import ChainMap
from datetime import datetime
import pytest
from copier.config.factory import filter_config, make_config
from copier.config.objects import EnvOps
from copier.config.user_data import InvalidTypeError, query_user_data
from copier.types import AnyByStrDict
answers_data: AnyByS... |
from slimit.lexer import Lexer
from bs4 import BeautifulSoup
class Normalizor:
def __init__(self):
self.mapping = {
"TRY" :"A",
"CATCH" :"A",
"IF" :"E",
"ELSE" :"E",
"SWITCH" :"X",
"CASE" :"X",
"DEFAULT" :"X",
"WHILE" :"W",
"DO" :"W",... |
from fjord.base.tests import (
AnalyzerProfileFactory,
LocalizingClient,
reverse,
TestCase
)
from fjord.heartbeat.api_views import log_error
from fjord.heartbeat.tests import AnswerFactory, SurveyFactory
class TestHeartbeatHBData(TestCase):
client_class = LocalizingClient
def test_permissions... |
import numpy as np
from sklearn.externals.joblib import Memory
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
from sklearn.pipeline import make_pipeline
from utils import load_train_subjects, load_test_subjects
import matplotlib.pyplot as plt
... |
from .resource import Resource
class Snapshot(Resource):
"""Snapshot resource.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: Resource Id
:vartype id: str
:ivar name: Resource name
:vartype name: str
:ivar type: Resource type
:va... |
"""Converter construction support.
This module contains a base class for all converters, as well as supporting
structures. These structures are referred to as contexts.
The class hierarchy is as follows:
<your converter>
[extends] converter.Base
[extends] transformer.Base
[extends] gast... |
import os.path
from nova.api.openstack import common
from nova import utils
class ViewBuilder(object):
"""Base class for generating responses to OpenStack API image requests."""
def __init__(self, base_url, project_id=""):
"""Initialize new `ViewBuilder`."""
self.base_url = base_url
... |
#!/bin/env python
import ROOT as r
import sys,os
import numpy as np
from optparse import OptionParser
from wsuPythonUtils import checkRequiredArguments,setMinPT
if __name__ == "__main__":
parser = OptionParser(usage="Usage: %prog -i inputfile.root -o outputfile.root [-d]")
parser.add_option("-i", "--infile",... |
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
from past.utils import old_div
import logging
import datetime as pydt
import ... |
"""
Set up the plot figures, axes, and items to be done for each frame.
This module is imported by the plotting routines and then the
function setplot is called to set the plot parameters.
"""
from numpy import *
#from matplotlib.pylab import *
# import pyclaw.data
#--------------------------
def setplot(plotdata)... |
# -*- coding: utf-8 -*-
"""
@author: <EMAIL> / 2015,2016,2017
<EMAIL> / 2016, 2017
@license: GPL
"""
import sys,os
import qkit
# support both PyQt4 and 5
in_pyqt5 = False
in_pyqt4 = False
try:
from PyQt5 import QtCore, QtGui
from PyQt5.QtCore import pyqtSignal, pyqtSlot, QObject,QTimer
from PyQt5... |
# -*- coding: utf-8 -*-
import datetime
import json
import logging
import subprocess
from email.mime.text import MIMEText
from smtplib import SMTP
from smtplib import SMTP_SSL
from smtplib import SMTPAuthenticationError
from smtplib import SMTPException
from socket import error
import simplejson
from jira.client impor... |
if __name__ == "__main__":
dish = "szechuan chicken"
print(dish)
# String slices
print(dish[0:5])
print(dish[:4])
print(dish[9:])
print(dish[-8:-3])
print(dish[:])
# Some string methods
print('In upper case our string is "' + dish.upper())
print('We can find "masala" at lo... |
"""
Author: Dr. John T. Hwang <<EMAIL>>
This package is distributed under New BSD license.
"""
import numpy as np
import scipy.sparse
from numbers import Integral
from smt.utils.linear_solvers import get_solver
from smt.utils.line_search import get_line_search_class
from smt.surrogate_models.rmts import RMTS
from sm... |
"""Support for Azure DevOps."""
from __future__ import annotations
import logging
from typing import Any
from aioazuredevops.client import DevOpsClient
import aiohttp
from homeassistant.components.azure_devops.const import (
CONF_ORG,
CONF_PAT,
CONF_PROJECT,
DATA_AZURE_DEVOPS_CLIENT,
DOMAIN,
)
fr... |
"""
byceps.services.board.posting_command_service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from datetime import datetime
from typing import Tuple
from ...database import db
from ...events.board import (
BoardPost... |
"""This package contains the standard macroserver macros"""
__docformat__ = 'restructuredtext' |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from .pizza import *
from .ingredient_factory import IngredientFactory
class AbsPizzaStore(object):
def order_pizza(self):
raise NotImplementedError
def _create(self):
raise NotImplementedError
def _ingredient(self):
raise NotImpl... |
#!/usr/bin/env python
# coding=utf-8
import sys
from time import sleep
from lifxlan import BLUE, CYAN, GREEN, LifxLAN, ORANGE, PINK, PURPLE, RED, YELLOW
def main():
num_lights = None
if len(sys.argv) != 2:
print("\nDiscovery will go much faster if you provide the number of lights on your LAN:")
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.