<commit_before>#!/usr/bin/env python
import weakref
import dbus
import ibus
from ibus import keysyms
from ibus import modifier
from contextmanager import ContextManager
from factorymanager import FactoryManager
from connection import Connection
from panel import Panel, DummyPanel

class IBus (ibus.Object):
	def __init__ (self):
		ibus.Object.__init__ (self)
		self._connections = {}
		self._context_manager = ContextManager ()
		self._factory_manager = FactoryManager ()
		self._panel = DummyPanel ()

		self._focused_context = None
		self._last_focused_context = None
		self._context_handlers = []

		self._last_key = None

	def new_connection (self, dbusconn):
		assert dbusconn not in self._connections
		self._connections[dbusconn] = Connection (dbusconn)

	def remove_connection (self, dbusconn):
		assert dbusconn in self._connections

		# destroy the connection
		self._connections[dbusconn].destroy ()
		del self._connections[dbusconn]

	def _lookup_ibus_connection (self, dbusconn):
		if dbusconn not in self._connections:
			raise ibus.IBusException ("can not find ibus.Connection")
		return self._connections[dbusconn]

	##########################################################
	# methods for im context
	##########################################################
	def create_input_context (self, name, dbusconn):
		ibusconn = self._lookup_ibus_connection (dbusconn)
		context = self._context_manager.create_input_context (name, ibusconn)
		factory = self._factory_manager.get_default_factory ()
		if factory:
			engine = factory.create_engine ()
			context.set_engine (engine)
		return context.get_id ()

	def release_input_context (self, ic, dbusconn):
		ibusconn = self._lookup_ibus_connection (dbusconn)
		self._context_manager.release_input_context (ic, ibusconn)

	def focus_in (self, ic, dbusconn):
		context = self._lookup_context (ic, dbusconn)

		if self._focused_context != context and self._focused_context != None:
			map (self._focused_context.disconnect, self._context_handlers)
			self._context_handlers = []
			self._focused_context.focus_out ()

		# Install all callback functions
		id = context.connect ("update-preedit", self._update_preedit_cb)
		self._context_handlers.append (id)
		id = context.connect ("update-aux-string", self._update_aux_string_cb)
		self._context_handlers.append (id)
		id = context.connect ("update-lookup-table", self._update_lookup_table_cb)
		self._context_handlers.append (id)
		id = context.connect ("register-properties", self._register_properties_cb)
		self._context_handlers.append (id)
		id = context.connect ("update-property", self._update_property_cb)
		self._context_handlers.append (id)
		id = context.connect ("engine-lost", self._engine_lost_cb)
		self._context_handlers.append (id)
		id = context.connect ("destroy", self._context_destroy_cb)
		self._context_handlers.append (id)

		self._panel.reset ()
		self._focused_context = context
		self._last_focused_context = context
		context.focus_in ()

	def focus_out (self, ic, dbusconn):
		context = self._lookup_context (ic, dbusconn)
		if context == self._focused_context:
			map (self._focused_context.disconnect, self._context_handlers)
			self._context_handlers = []
			self._focused_context = None
		context.focus_out ()
		self._panel.reset ()

	def reset (self, ic, dbusconn):
		context = self._lookup_context (ic, dbusconn)
		context.reset ()

	def is_enabled (self, ic, dbusconn):
		context = self._lookup_context (ic, dbusconn)
		return context.is_enabled ()

	def process_key_event (self, ic, keyval, is_press, state,
								dbusconn, reply_cb, error_cb):
		context = self._lookup_context (ic, dbusconn)

		if self._filter_hotkeys (context, keyval, is_press, state):
			reply_cb (True)
			return
		else:
			context.process_key_event (keyval, is_press, state, reply_cb, error_cb)

	def set_cursor_location (self, ic, x, y, w, h, dbusconn):
		context = self._lookup_context (ic, dbusconn)
		context.set_cursor_location (x, y, w, h)
		self._panel.set_cursor_location (x, y, w, h)

	def _filter_hotkeys (self, context, keyval, is_press, state):
		if is_press and keyval == keysyms.space \
			and (state & ~modifier.MOD2_MASK) == modifier.CONTROL_MASK:
			enable = not context.is_enabled ()
			context.set_enable (enable)
			if context.get_engine () == None and enable:
				factory = self._factory_manager.get_default_factory ()
				if factory:
					engine = factory.create_engine ()
					context.set_engine (engine)
			return True
		return False

	def _lookup_context (self, ic, dbusconn):
		ibusconn = self._lookup_ibus_connection (dbusconn)
		return self._context_manager.lookup_context (ic, ibusconn)

	def _update_preedit_cb (self, context, text, attrs, cursor_pos, visible):
		assert self._focused_context == context

		self._panel.update_preedit_string (text, attrs, cursor_pos, visible)

	def _update_aux_string_cb (self, context, text, attrs, visible):
		assert self._focused_context == context

		self._panel.update_aux_string (text, attrs, visible)

	def _update_lookup_table_cb (self, context, lookup_table, visible):
		assert self._focused_context == context

		self._panel.update_lookup_table (lookup_table, visible)

	def _register_properties_cb (self, context, props):
		assert self._focused_context == context

		self._panel.register_properties (props)

	def _update_property_cb (self, context, prop):
		assert self._focused_context == context

		self._panel.update_property (prop)

	def _engine_lost_cb (self, context):
		assert self._focused_context == context

		self._panel.reset ()

	def _context_destroy_cb (self, context):
		assert context == self._focused_context
		self._context_handlers = []
		self._focused_context = None
		self._panel.reset ()

	##########################################################
	# methods for im engines
	##########################################################
	def register_factories (self, object_paths, dbusconn):
		ibusconn = self._lookup_ibus_connection (dbusconn)
		self._factory_manager.register_factories (object_paths, ibusconn)

	def dispatch_dbus_signal (self, dbusconn, message):
		ibusconn = self._lookup_ibus_connection (dbusconn)
		ibusconn.dispatch_dbus_signal (message)

	def _lookup_engine (self, dbusconn, path):
		ibusconn = self._lookup_ibus_connection (dbusconn)
		return self._factory_manager.lookup_engine (ibusconn, path)

	##########################################################
	# methods for panel
	##########################################################
	def register_panel (self, object_path, replace, dbusconn):
		if not isinstance (self._panel, DummyPanel) and replace == False:
			raise ibus.Exception ("has have a panel!")
		if not isinstance (self._panel, DummyPanel):
			self._panel.destroy ()
		ibusconn = self._lookup_ibus_connection (dbusconn)
		self._panel = Panel (ibusconn, object_path)
		self._panel.connect ("page-up", self._panel_page_up_cb)
		self._panel.connect ("page-down", self._panel_page_down_cb)
		self._panel.connect ("cursor-up", self._panel_cursor_up_cb)
		self._panel.connect ("cursor-down", self._panel_cursor_down_cb)
		self._panel.connect ("property-activate", self._panel_property_active_cb)
		self._panel.connect ("destroy", self._panel_destroy_cb)

	def _panel_page_up_cb (self, panel):
		assert panel == self._panel
		if self._focused_context:
			self._focused_context.page_up ()

	def _panel_page_down_cb (self, panel):
		assert panel == self._panel
		if self._focused_context:
			self._focused_context.page_down ()

	def _panel_cursor_up_cb (self, panel):
		assert panel == self._panel
		if self._focused_context:
			self._focused_context.cursor_up ()

	def _panel_cursor_down_cb (self, panel):
		assert panel == self._panel
		if self._focused_context:
			self._focused_context.cursor_down ()

	def _panel_property_active_cb (self, panel, prop_name):
		assert panel == self._panel
		if self._focused_context:
			self._focused_context.property_activate (prop_name)

	def _panel_destroy_cb (self, panel):
		if panel == self._panel:
			self._panel = DummyPanel ()

	##########################################################
	# general methods
	##########################################################
	def get_factories (self):
		return self._factory_manager.get_factories ()

	def get_factory_info (self, factory_path):
		return self._factory_manager.get_factory_info (factory_path)

	def set_factory (self, factory_path):
		if self._focused_context == None:
			return
		self._panel.reset ()
		factory = self._factory_manager.get_factory (factory_path)
		engine = factory.create_engine ()
		self._focused_context.set_engine (engine)

class IBusProxy (ibus.IIBus):
	SUPPORTS_MULTIPLE_CONNECTIONS = True

	def __init__ (self):
		ibus.IIBus.__init__ (self)
		self._ibus = IBus ()

	def new_connection (self, dbusconn):
		self._ibus.new_connection (dbusconn)

	def remove_connection (self, dbusconn):
		self._ibus.remove_connection (dbusconn)

	def dispatch_dbus_signal (self, dbusconn, message):
		return self._ibus.dispatch_dbus_signal (dbusconn, message)

	def GetIBusAddress (self, dbusconn):
		return self._ibus_addr

	def CreateInputContext (self, context_name, dbusconn):
		return self._ibus.create_input_context (context_name, dbusconn)

	def ReleaseInputContext (self, ic, dbusconn):
		self._ibus.release_input_context (ic, dbusconn)

	def RegisterFactories (self, object_paths, dbusconn):
		self._ibus.register_factories (object_paths, dbusconn)

	def UnregisterEngines (self, object_paths, dbusconn):
		self._ibus.unregister_engines (object_paths, dbusconn)

	def RegisterPanel (self, object_path, replace, dbusconn):
		self._ibus.register_panel (object_path, replace, dbusconn)

	def ProcessKeyEvent (self, ic, keyval, is_press, state, \
							dbusconn, reply_cb, error_cb):
		try:
			self._ibus.process_key_event (ic, keyval, is_press, state,
							dbusconn, reply_cb, error_cb)
		except Exception, e:
			error_cb (e)

	def SetCursorLocation (self, ic, x, y, w, h, dbusconn):
		self._ibus.set_cursor_location (ic, x, y, w, h, dbusconn)

	def FocusIn (self, ic, dbusconn):
		self._ibus.focus_in (ic, dbusconn)

	def FocusOut (self, ic, dbusconn):
		self._ibus.focus_out (ic, dbusconn)

	def Reset (self, ic, dbusconn):
		self._ibus.reset (ic, dbusconn)

	def IsEnabled (self, ic, dbusconn):
		return self._ibus.is_enabled (ic, dbusconn)

	def GetFactories (self, dbusconn):
		return self._ibus.get_factories ()

	def GetFactoryInfo (self, factory_path, dbusconn):
		return self._ibus.get_factory_info (factory_path)

	def SetFactory (self, factory_path, dbusconn):
		return self._ibus.set_factory (factory_path)

<commit_msg>Add {install, remove}_focused_context_handlers methods.<commit_after>#!/usr/bin/env python
import weakref
import dbus
import ibus
from ibus import keysyms
from ibus import modifier
from contextmanager import ContextManager
from factorymanager import FactoryManager
from connection import Connection
from panel import Panel, DummyPanel

class IBus (ibus.Object):
	def __init__ (self):
		ibus.Object.__init__ (self)
		self._connections = {}
		self._context_manager = ContextManager ()
		self._factory_manager = FactoryManager ()
		self._panel = DummyPanel ()

		self._focused_context = None
		self._last_focused_context = None
		self._context_handlers = []

		self._last_key = None

	def new_connection (self, dbusconn):
		assert dbusconn not in self._connections
		self._connections[dbusconn] = Connection (dbusconn)

	def remove_connection (self, dbusconn):
		assert dbusconn in self._connections

		# destroy the connection
		self._connections[dbusconn].destroy ()
		del self._connections[dbusconn]

	def _lookup_ibus_connection (self, dbusconn):
		if dbusconn not in self._connections:
			raise ibus.IBusException ("can not find ibus.Connection")
		return self._connections[dbusconn]

	##########################################################
	# methods for im context
	##########################################################
	def create_input_context (self, name, dbusconn):
		ibusconn = self._lookup_ibus_connection (dbusconn)
		context = self._context_manager.create_input_context (name, ibusconn)
		factory = self._factory_manager.get_default_factory ()
		if factory:
			engine = factory.create_engine ()
			context.set_engine (engine)
		return context.get_id ()

	def release_input_context (self, ic, dbusconn):
		ibusconn = self._lookup_ibus_connection (dbusconn)
		self._context_manager.release_input_context (ic, ibusconn)

	def focus_in (self, ic, dbusconn):
		context = self._lookup_context (ic, dbusconn)

		if self._focused_context != context and self._focused_context != None:
			self._remove_focused_context_handlers ()
			self._focused_context.focus_out ()

		self._focused_context = context
		self._install_focused_context_handlers ()

		self._panel.reset ()
		self._last_focused_context = context
		context.focus_in ()

	def focus_out (self, ic, dbusconn):
		context = self._lookup_context (ic, dbusconn)

		if context == self._focused_context:
			self._remove_focused_context_handlers ()
			self._focused_context = None

		context.focus_out ()
		self._panel.reset ()

	def reset (self, ic, dbusconn):
		context = self._lookup_context (ic, dbusconn)
		context.reset ()

	def is_enabled (self, ic, dbusconn):
		context = self._lookup_context (ic, dbusconn)
		return context.is_enabled ()

	def process_key_event (self, ic, keyval, is_press, state,
								dbusconn, reply_cb, error_cb):
		context = self._lookup_context (ic, dbusconn)

		if self._filter_hotkeys (context, keyval, is_press, state):
			reply_cb (True)
			return
		else:
			context.process_key_event (keyval, is_press, state, reply_cb, error_cb)

	def set_cursor_location (self, ic, x, y, w, h, dbusconn):
		context = self._lookup_context (ic, dbusconn)
		context.set_cursor_location (x, y, w, h)
		self._panel.set_cursor_location (x, y, w, h)

	def _filter_hotkeys (self, context, keyval, is_press, state):
		if is_press and keyval == keysyms.space \
			and (state & ~modifier.MOD2_MASK) == modifier.CONTROL_MASK:
			enable = not context.is_enabled ()
			context.set_enable (enable)
			if context.get_engine () == None and enable:
				factory = self._factory_manager.get_default_factory ()
				if factory:
					engine = factory.create_engine ()
					context.set_engine (engine)
			return True
		return False

	def _lookup_context (self, ic, dbusconn):
		ibusconn = self._lookup_ibus_connection (dbusconn)
		return self._context_manager.lookup_context (ic, ibusconn)

	def _install_focused_context_handlers (self):
		# Install all callback functions
		if self._focused_context == None:
			return
		signals = (
			("update-preedit", self._update_preedit_cb),
			("update-aux-string", self._update_aux_string_cb),
			("update-lookup-table", self._update_lookup_table_cb),
			("register-properties", self._register_properties_cb),
			("update-property", self._update_property_cb),
			("engine-lost", self._engine_lost_cb),
			("destroy", self._context_destroy_cb)
		)
		for name, handler in signals:
			id = self._focused_context.connect (name, handler)
			self._context_handlers.append (id)

	def _remove_focused_context_handlers (self):
		if self._focused_context == None:
			return
		map (self._focused_context.disconnect, self._context_handlers)
		self._context_handlers = []

	def _update_preedit_cb (self, context, text, attrs, cursor_pos, visible):
		assert self._focused_context == context

		self._panel.update_preedit_string (text, attrs, cursor_pos, visible)

	def _update_aux_string_cb (self, context, text, attrs, visible):
		assert self._focused_context == context

		self._panel.update_aux_string (text, attrs, visible)

	def _update_lookup_table_cb (self, context, lookup_table, visible):
		assert self._focused_context == context

		self._panel.update_lookup_table (lookup_table, visible)

	def _register_properties_cb (self, context, props):
		assert self._focused_context == context

		self._panel.register_properties (props)

	def _update_property_cb (self, context, prop):
		assert self._focused_context == context

		self._panel.update_property (prop)

	def _engine_lost_cb (self, context):
		assert self._focused_context == context

		self._panel.reset ()

	def _context_destroy_cb (self, context):
		assert context == self._focused_context
		self._remove_focused_context_handlers ()
		self._focused_context = None
		self._panel.reset ()

	##########################################################
	# methods for im engines
	##########################################################
	def register_factories (self, object_paths, dbusconn):
		ibusconn = self._lookup_ibus_connection (dbusconn)
		self._factory_manager.register_factories (object_paths, ibusconn)

	def dispatch_dbus_signal (self, dbusconn, message):
		ibusconn = self._lookup_ibus_connection (dbusconn)
		ibusconn.dispatch_dbus_signal (message)

	def _lookup_engine (self, dbusconn, path):
		ibusconn = self._lookup_ibus_connection (dbusconn)
		return self._factory_manager.lookup_engine (ibusconn, path)

	##########################################################
	# methods for panel
	##########################################################
	def register_panel (self, object_path, replace, dbusconn):
		if not isinstance (self._panel, DummyPanel) and replace == False:
			raise ibus.Exception ("has have a panel!")
		if not isinstance (self._panel, DummyPanel):
			self._panel.destroy ()
		ibusconn = self._lookup_ibus_connection (dbusconn)
		self._panel = Panel (ibusconn, object_path)
		self._panel.connect ("page-up", self._panel_page_up_cb)
		self._panel.connect ("page-down", self._panel_page_down_cb)
		self._panel.connect ("cursor-up", self._panel_cursor_up_cb)
		self._panel.connect ("cursor-down", self._panel_cursor_down_cb)
		self._panel.connect ("property-activate", self._panel_property_active_cb)
		self._panel.connect ("destroy", self._panel_destroy_cb)

	def _panel_page_up_cb (self, panel):
		assert panel == self._panel
		if self._focused_context:
			self._focused_context.page_up ()

	def _panel_page_down_cb (self, panel):
		assert panel == self._panel
		if self._focused_context:
			self._focused_context.page_down ()

	def _panel_cursor_up_cb (self, panel):
		assert panel == self._panel
		if self._focused_context:
			self._focused_context.cursor_up ()

	def _panel_cursor_down_cb (self, panel):
		assert panel == self._panel
		if self._focused_context:
			self._focused_context.cursor_down ()

	def _panel_property_active_cb (self, panel, prop_name):
		assert panel == self._panel
		if self._focused_context:
			self._focused_context.property_activate (prop_name)

	def _panel_destroy_cb (self, panel):
		if panel == self._panel:
			self._panel = DummyPanel ()

	##########################################################
	# general methods
	##########################################################
	def get_factories (self):
		return self._factory_manager.get_factories ()

	def get_factory_info (self, factory_path):
		return self._factory_manager.get_factory_info (factory_path)

	def set_factory (self, factory_path):
		if self._focused_context == None:
			return
		self._panel.reset ()
		factory = self._factory_manager.get_factory (factory_path)
		engine = factory.create_engine ()
		self._focused_context.set_engine (engine)

class IBusProxy (ibus.IIBus):
	SUPPORTS_MULTIPLE_CONNECTIONS = True

	def __init__ (self):
		ibus.IIBus.__init__ (self)
		self._ibus = IBus ()

	def new_connection (self, dbusconn):
		self._ibus.new_connection (dbusconn)

	def remove_connection (self, dbusconn):
		self._ibus.remove_connection (dbusconn)

	def dispatch_dbus_signal (self, dbusconn, message):
		return self._ibus.dispatch_dbus_signal (dbusconn, message)

	def GetIBusAddress (self, dbusconn):
		return self._ibus_addr

	def CreateInputContext (self, context_name, dbusconn):
		return self._ibus.create_input_context (context_name, dbusconn)

	def ReleaseInputContext (self, ic, dbusconn):
		self._ibus.release_input_context (ic, dbusconn)

	def RegisterFactories (self, object_paths, dbusconn):
		self._ibus.register_factories (object_paths, dbusconn)

	def UnregisterEngines (self, object_paths, dbusconn):
		self._ibus.unregister_engines (object_paths, dbusconn)

	def RegisterPanel (self, object_path, replace, dbusconn):
		self._ibus.register_panel (object_path, replace, dbusconn)

	def ProcessKeyEvent (self, ic, keyval, is_press, state, \
							dbusconn, reply_cb, error_cb):
		try:
			self._ibus.process_key_event (ic, keyval, is_press, state,
							dbusconn, reply_cb, error_cb)
		except Exception, e:
			error_cb (e)

	def SetCursorLocation (self, ic, x, y, w, h, dbusconn):
		self._ibus.set_cursor_location (ic, x, y, w, h, dbusconn)

	def FocusIn (self, ic, dbusconn):
		self._ibus.focus_in (ic, dbusconn)

	def FocusOut (self, ic, dbusconn):
		self._ibus.focus_out (ic, dbusconn)

	def Reset (self, ic, dbusconn):
		self._ibus.reset (ic, dbusconn)

	def IsEnabled (self, ic, dbusconn):
		return self._ibus.is_enabled (ic, dbusconn)

	def GetFactories (self, dbusconn):
		return self._ibus.get_factories ()

	def GetFactoryInfo (self, factory_path, dbusconn):
		return self._ibus.get_factory_info (factory_path)

	def SetFactory (self, factory_path, dbusconn):
		return self._ibus.set_factory (factory_path)

<|endoftext|>


<commit_before>#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

from logging import Logger
from typing import NamedTuple, Optional

from idb.grpc.idb_grpc import CompanionServiceStub

class CompanionClient(NamedTuple):
    stub: CompanionServiceStub
    is_local: bool
    udid: Optional[str]
    logger: Logger
    is_companion_available: bool = False
<commit_msg>Remove idb.grpc.types<commit_after><|endoftext|>


<commit_before>#!/usr/bin/env python
# vim: ts=4:sw=4:et:sts=4:ai:tw=80
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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 distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
# AUTHOR: Juan Carlos Fernandez <jcfernandez@redoop.org>

import argparse
import requests
import json
import nagiosplugin
import time

html_auth = None

def parser():
    version="0.1"
    parser = argparse.ArgumentParser(description="Check flume agent")
    parser.add_argument('-t','--test',action='store',type=str,required=True)
    parser.add_argument('--timeout_war',action='store',type=int,default=60,help="Seconds without receiving any msg")
    parser.add_argument('--timeout_crit',action='store',type=int,default=600,help="Seconds without receiving any msg")
    parser.add_argument('--url',action='store',type=str,required=True)
    parser.add_argument('--sources',nargs='*',type=str,action='store')
    parser.add_argument('--channels',nargs='*',type=str,action='store')
    parser.add_argument('--sinks',nargs='*',type=str,action='store')
    parser.add_argument('--batch_size',type=int,action='store',default=200)
    parser.add_argument('--field_split',type=str,help="String used to split fields to identify a metric",action='store',default=':')
    parser.add_argument('-v','--version', action='version', version='%(prog)s ' + version)
    args = parser.parse_args()
    emptys = 0
    if args.sources is None:
        emptys+=1
    if args.channels is None:
        emptys+=1
    if args.sinks is None:
        emptys+=1
    if args.test == "living" and emptys > 2:
        parser.error("At least one metric to check is required, --sources --channels and/or --sinks")
    if args.test == "in=out" and emptys > 1:
        parser.error("At least two metrics to check is required, --sources --channels and/or --sinks")
    return args

class Flume(nagiosplugin.Resource):

    def __init__(self,args):
        self.test = args.test
        self.url = args.url
        self.sources=args.sources
        self.channels=args.channels
        self.sinks=args.sinks
        self.field_split = args.field_split
        self.getMetrics()

    def getMetrics(self):
        response = requests.get(self.url)
        self.metrics = json.loads(response.content)

    def probe(self):
        if self.test == 'in=out':
            if self.sources is not None:
                sources = self.add_metrics(self.sources)
            if self.channels is not None:
                channels = self.add_metrics(self.channels)
            if self.sinks is not None:
                sinks = self.add_metrics(self.sinks)
            if sources is not None:
    	        if channels is not None:
                    yield nagiosplugin.Metric('Source=>Channel',sources-channels,context="io")
                else:
                    yield nagiosplugin.Metric('Source=>Sink',sources-sinks,context="io")
            if channels is not None and sinks is not None:
                yield nagiosplugin.Metric('Channel=>Sink',channels-sinks,context="io")
        if self.test == 'living':
            if self.sources is not None:
                for metric in self.sources:
            	    yield nagiosplugin.Metric(metric + ' Last msg', int(self.walk_dict(metric)),context = "LastMsg")
            if self.channels is not None:
                for metric in self.channels:
            	    yield nagiosplugin.Metric(metric + ' Last msg', int(self.walk_dict(metric)),context = "LastMsg")
            if self.sinks is not None:
                for metric in self.sinks:
        	        yield nagiosplugin.Metric(metric + ' Last msg', int(self.walk_dict(metric)),context = "LastMsg")

    def add_metrics(self,list_metrics):
        adder = 0
        for metric in list_metrics:
            adder+=int(self.walk_dict)
        return adder

    def walk_dict(self,path):
        subJson = self.metrics
        for field in path.split(self.field_split):
            subJson = subJson.get(field)
        return subJson

@nagiosplugin.guarded
def main():
    args = parser()
    check = nagiosplugin.Check(Flume(args),
        nagiosplugin.ScalarContext('io',
            args.batch_size,
            fmt_metric='{value} msg differs'),
        nagiosplugin.ScalarContext('LastMsg',
            str(int(time.time())*1000-args.timeout_war*1000)+':',
            str(int(time.time())*1000-args.timeout_crit*1000)+':',
            fmt_metric='Last msg recived in {value}'))
    check.main()

if __name__ == '__main__':
    main()
<commit_msg>Added some fixs<commit_after>#!/usr/bin/env python
# vim: ts=4:sw=4:et:sts=4:ai:tw=80
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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 distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
# AUTHOR: Juan Carlos Fernandez <jcfernandez@redoop.org>

import argparse
import requests
import json
import nagiosplugin
import time

html_auth = None

def parser():
    version="0.1"
    parser = argparse.ArgumentParser(description="Check flume agent")
    parser.add_argument('-t','--test',action='store',type=str,required=True)
    parser.add_argument('--timeout_war',action='store',type=int,default=60,help="Seconds without receiving any msg")
    parser.add_argument('--timeout_crit',action='store',type=int,default=600,help="Seconds without receiving any msg")
    parser.add_argument('--url',action='store',type=str,required=True)
    parser.add_argument('--sources',nargs='*',type=str,action='store')
    parser.add_argument('--channels',nargs='*',type=str,action='store')
    parser.add_argument('--sinks',nargs='*',type=str,action='store')
    parser.add_argument('--batch_size',type=int,action='store',default=200)
    parser.add_argument('--field_split',type=str,help="String used to split fields to identify a metric",action='store',default=':')
    parser.add_argument('-v','--version', action='version', version='%(prog)s ' + version)
    args = parser.parse_args()
    emptys = 0
    if args.sources is None:
        emptys+=1
    if args.channels is None:
        emptys+=1
    if args.sinks is None:
        emptys+=1
    if args.test == "living" and emptys > 2:
        parser.error("At least one metric to check is required, --sources --channels and/or --sinks")
    if args.test == "in=out" and emptys > 1:
        parser.error("At least two metrics to check is required, --sources --channels and/or --sinks")
    return args

class Flume(nagiosplugin.Resource):

    def __init__(self,args):
        self.test = args.test
        self.url = args.url
        self.sources=args.sources
        self.channels=args.channels
        self.sinks=args.sinks
        self.field_split = args.field_split
        self.getMetrics()

    def getMetrics(self):
        response = requests.get(self.url)
        self.metrics = json.loads(response.content)

    def probe(self):
        if self.test == 'in=out':
            if self.sources is not None:
                sources = self.add_metrics(self.sources)
            if self.channels is not None:
                channels = self.add_metrics(self.channels)
            if self.sinks is not None:
                sinks = self.add_metrics(self.sinks)
            if 'sources' in locals():
    	        if 'channels' in locals():
                    yield nagiosplugin.Metric('Source->Channel',sources-channels,context="io")
                else:
                    yield nagiosplugin.Metric('Source->Sink',sources-sinks,context="io")
            if 'channels' in locals() and 'sinks' in locals():
                yield nagiosplugin.Metric('Channel->Sink',channels-sinks,context="io")
        if self.test == 'living':
            if self.sources is not None:
                for metric in self.sources:
            	    yield nagiosplugin.Metric(metric + ' Last msg', int(self.walk_dict(metric)),context = "LastMsg")
            if self.channels is not None:
                for metric in self.channels:
            	    yield nagiosplugin.Metric(metric + ' Last msg', int(self.walk_dict(metric)),context = "LastMsg")
            if self.sinks is not None:
                for metric in self.sinks:
        	        yield nagiosplugin.Metric(metric + ' Last msg', int(self.walk_dict(metric)),context = "LastMsg")

    def add_metrics(self,list_metrics):
        adder = 0
        for metric in list_metrics:
            adder+=int(self.walk_dict(metric))
        return adder

    def walk_dict(self,path):
        subJson = self.metrics
        for field in path.split(self.field_split):
            subJson = subJson.get(field)
        return subJson

@nagiosplugin.guarded
def main():
    args = parser()
    check = nagiosplugin.Check(Flume(args),
        nagiosplugin.ScalarContext('io',
            args.batch_size,
            fmt_metric='{value} msg differs'),
        nagiosplugin.ScalarContext('LastMsg',
            str(int(time.time())*1000-args.timeout_war*1000)+':',
            str(int(time.time())*1000-args.timeout_crit*1000)+':',
            fmt_metric='Last msg recived in {value}'))
    check.main()

if __name__ == '__main__':
    main()
<|endoftext|>


<commit_before># IdioTest - idiotest/suite.py
# Copyright 2009 Dietrich Epp <depp@zdome.net>
# This source code is licensed under the GNU General Public License,
# Version 3. See gpl-3.0.txt for details.
"""IdioTest test suite.

A test suite scans a directory for test files and organizes them into
a single object.  This also contains code for importing test code and
running it.
"""
import os

def relpath(basepath, path):
    if path == basepath:
        return '.'
    if path.startswith(basepath + os.path.sep):
        return path[len(basepath) + len(os.path.sep):]
    raise Exception("Path %s not a subpath of %s" %
                    (repr(path), repr(basepath)))

class Test(object):
    """A single test.

    Each test is executed with the current working directory set to
    the parent directory of the file containing the test.  Tests are
    assumed to be callable objects which do not take any arguments.
    """
    def __init__(self, cwd, obj):
        self.cwd = cwd
        self.obj = obj
    def run(self):
        oldcwd = os.getcwd()
        try:
            os.chdir(self.cwd)
            self.obj()
        finally:
            os.chdir(oldcwd)

class TestFile(object):
    """A single file in a test suite.

    Each file can contain multiple tests.  All globals in a file which
    are callable and whose names don't start with an underscore are
    assumed to be individual tests.
    """
    def __init__(self, path, env):
        self.path = path
        self.env = env
    def load(self):
        env = dict(self.env)
        execfile(self.path, env, env)
        tests = {}
        names = []
        cwd = os.path.split(self.path)[0]
        for name, obj in env.items():
            if (name not in self.env and not name.startswith('_')
                and hasattr(obj, '__call__')):
                tests[name] = Test(cwd, obj)
                names.append(name)
        names.sort()
        self.tests = tests
        self.names = names

class TestSuite(object):
    """An entire suite of tests, spread across multiple files.

    TestSuite(root, env): Create a new test suite, where root is the
    path of the root directory containing all the tests, and env is a
    dictionary for globals that each of the test files will be
    executed in.
    """
    def __init__(self, root, env):
        self.root = root
        self.env = env
    def scan(self):
        """Scan the root directory for test files.

        """
        testfiles = {}
        testnames = []
        for dirpath, dirnames, filenames in os.walk(self.root):
            dirnames[:] = [dirname for dirname in dirnames
                           if not dirname.startswith('.')]
            if dirpath != self.root:
                base = relpath(self.root, dirpath) \
                    .replace(os.path.sep, '.') + '.'
            else:
                base = ''
            for filename in filenames:
                if filename.endswith('.py') and not filename.startswith('.'):
                    path = os.path.join(dirpath, filename)
                    path = os.path.normpath(path)
                    if path == 'test.py':
                        # This is probably the driver script
                        continue
                    name = base + filename[:-3]
                    testnames.append(name)
                    testfiles[name] = TestFile(path, self.env)
        self.files = testfiles
        self.names = testnames
<commit_msg>Fixed problem with tests in current directory.<commit_after># IdioTest - idiotest/suite.py
# Copyright 2009 Dietrich Epp <depp@zdome.net>
# This source code is licensed under the GNU General Public License,
# Version 3. See gpl-3.0.txt for details.
"""IdioTest test suite.

A test suite scans a directory for test files and organizes them into
a single object.  This also contains code for importing test code and
running it.
"""
import os

def relpath(basepath, path):
    if path == basepath:
        return '.'
    if path.startswith(basepath + os.path.sep):
        return path[len(basepath) + len(os.path.sep):]
    raise Exception("Path %s not a subpath of %s" %
                    (repr(path), repr(basepath)))

class Test(object):
    """A single test.

    Each test is executed with the current working directory set to
    the parent directory of the file containing the test.  Tests are
    assumed to be callable objects which do not take any arguments.
    """
    def __init__(self, cwd, obj):
        if cwd == '.':
            cwd = None
        self.cwd = cwd
        self.obj = obj
    def run(self):
        if self.cwd:
            oldcwd = os.getcwd()
            try:
                os.chdir(self.cwd)
                self.obj()
            finally:
                os.chdir(oldcwd)
        else:
            self.obj()

class TestFile(object):
    """A single file in a test suite.

    Each file can contain multiple tests.  All globals in a file which
    are callable and whose names don't start with an underscore are
    assumed to be individual tests.
    """
    def __init__(self, path, env):
        self.path = path
        self.env = env
    def load(self):
        env = dict(self.env)
        execfile(self.path, env, env)
        tests = {}
        names = []
        cwd = os.path.split(self.path)[0]
        for name, obj in env.items():
            if (name not in self.env and not name.startswith('_')
                and hasattr(obj, '__call__')):
                tests[name] = Test(cwd, obj)
                names.append(name)
        names.sort()
        self.tests = tests
        self.names = names

class TestSuite(object):
    """An entire suite of tests, spread across multiple files.

    TestSuite(root, env): Create a new test suite, where root is the
    path of the root directory containing all the tests, and env is a
    dictionary for globals that each of the test files will be
    executed in.
    """
    def __init__(self, root, env):
        self.root = root
        self.env = env
    def scan(self):
        """Scan the root directory for test files.

        """
        testfiles = {}
        testnames = []
        for dirpath, dirnames, filenames in os.walk(self.root):
            dirnames[:] = [dirname for dirname in dirnames
                           if not dirname.startswith('.')]
            if dirpath != self.root:
                base = relpath(self.root, dirpath) \
                    .replace(os.path.sep, '.') + '.'
            else:
                base = ''
            for filename in filenames:
                if filename.endswith('.py') and not filename.startswith('.'):
                    path = os.path.join(dirpath, filename)
                    path = os.path.normpath(path)
                    if path == 'test.py':
                        # This is probably the driver script
                        continue
                    name = base + filename[:-3]
                    testnames.append(name)
                    testfiles[name] = TestFile(path, self.env)
        self.files = testfiles
        self.names = testnames
<|endoftext|>


<commit_before>#!/usr/bin/env python
#
# Copyright (c) 2015 Intel Corporation.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of works must retain the original copyright notice, this
#   list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the original copyright
#   notice, this list of conditions and the following disclaimer in the
#   documentation and/or other materials provided with the distribution.
# * Neither the name of Intel Corporation nor the names of its contributors
#   may be used to endorse or promote products derived from this work without
#   specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors:
#         Hongjuan, Wang<hongjuanx.wang@intel.com>

import unittest
import os
import sys
import commands
import comm

class TestPackertoolsFunctions(unittest.TestCase):

    def test_manifest_versionCode(self):
        comm.setUp()
        comm.clear_versionCode()
        targetDir = comm.ConstPath + "/../testapp/example/"
        manfiestPath = targetDir + "manifest.json"
        os.chdir(targetDir)
        versionCode = " --app-versionCode=11"
        versionCodeBase = ""
        cmd = "python %smake_apk.py --package=org.xwalk.example --arch=%s --mode=%s --manifest=%s --project-dir=test" % \
            (comm.Pck_Tools, comm.ARCH, comm.MODE, manfiestPath)
        comm.versionCode(cmd, versionCode, versionCodeBase, self)
        comm.clear_versionCode()

    def test_manifest_no_versionCode(self):
        comm.setUp()
        comm.clear_versionCode()
        targetDir = comm.ConstPath + "/../testapp/example/"
        manfiestPath = targetDir + "manifest.json"
        os.chdir(targetDir)
        versionCode = ""
        versionCodeBase = ""
        cmd = "python %smake_apk.py --package=org.xwalk.example --arch=%s --mode=%s --manifest=%s --project-dir=test" % \
            (comm.Pck_Tools, comm.ARCH, comm.MODE, manfiestPath)
        comm.versionCode(cmd, versionCode, versionCodeBase, self)
        comm.clear_versionCode()

    def test_manifest_versionCodeBase(self):
        comm.setUp()
        comm.clear_versionCode()
        targetDir = comm.ConstPath + "/../testapp/example/"
        manfiestPath = targetDir + "manifest.json"
        os.chdir(targetDir)
        versionCode = ""
        versionCodeBase = ""
        versionCodeBase = " --app-versionCodeBase=1234567"
        cmd = "python %smake_apk.py --package=org.xwalk.example --arch=%s --mode=%s --manifest=%s --project-dir=test --app-version=1.0.0" % \
            (comm.Pck_Tools, comm.ARCH, comm.MODE, manfiestPath)
        comm.versionCode(cmd, versionCode, versionCodeBase, self)
        comm.clear_versionCode()

    def test_manifest_version_versionCode(self):
        comm.setUp()
        comm.clear_versionCode()
        targetDir = comm.ConstPath + "/../testapp/example/"
        manfiestPath = targetDir + "manifest.json"
        os.chdir(targetDir)
        versionCode = ""
        versionCodeBase = ""
        cmd = "python %smake_apk.py --package=org.xwalk.example --arch=%s --mode=%s --manifest=%s --project-dir=test --app-version=1.0.0.0" % \
            (comm.Pck_Tools, comm.ARCH, comm.MODE, manfiestPath)
        packstatus = commands.getstatusoutput(cmd)
        errorinfo = "please specify --app-versionCode or --app-versionCodeBase"
        self.assertNotEquals(0, packstatus[0])
        self.assertIn(errorinfo, packstatus[1])
        comm.clear_versionCode()

if __name__ == '__main__':
    unittest.main()
<commit_msg>[wrt] Update test description for versionCode<commit_after>#!/usr/bin/env python
#
# Copyright (c) 2015 Intel Corporation.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of works must retain the original copyright notice, this
#   list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the original copyright
#   notice, this list of conditions and the following disclaimer in the
#   documentation and/or other materials provided with the distribution.
# * Neither the name of Intel Corporation nor the names of its contributors
#   may be used to endorse or promote products derived from this work without
#   specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors:
#         Hongjuan, Wang<hongjuanx.wang@intel.com>

import unittest
import os
import sys
import commands
import comm

class TestPackertoolsFunctions(unittest.TestCase):

    def test_manifest_versionCode(self):
        comm.setUp()
        comm.clear_versionCode()
        targetDir = comm.ConstPath + "/../testapp/example/"
        manfiestPath = targetDir + "manifest.json"
        os.chdir(targetDir)
        versionCode = " --app-versionCode=11"
        versionCodeBase = ""
        cmd = "python %smake_apk.py --package=org.xwalk.example --arch=%s --mode=%s --manifest=%s --project-dir=test" % \
            (comm.Pck_Tools, comm.ARCH, comm.MODE, manfiestPath)
        comm.versionCode(cmd, versionCode, versionCodeBase, self)
        comm.clear_versionCode()

    def test_manifest_no_versionCode(self):
        comm.setUp()
        comm.clear_versionCode()
        targetDir = comm.ConstPath + "/../testapp/example/"
        manfiestPath = targetDir + "manifest.json"
        os.chdir(targetDir)
        versionCode = ""
        versionCodeBase = ""
        cmd = "python %smake_apk.py --package=org.xwalk.example --arch=%s --mode=%s --manifest=%s --project-dir=test" % \
            (comm.Pck_Tools, comm.ARCH, comm.MODE, manfiestPath)
        comm.versionCode(cmd, versionCode, versionCodeBase, self)
        comm.clear_versionCode()

    def test_manifest_versionCodeBase(self):
        comm.setUp()
        comm.clear_versionCode()
        targetDir = comm.ConstPath + "/../testapp/example/"
        manfiestPath = targetDir + "manifest.json"
        os.chdir(targetDir)
        versionCode = ""
        versionCodeBase = ""
        versionCodeBase = " --app-versionCodeBase=1234567"
        cmd = "python %smake_apk.py --package=org.xwalk.example --arch=%s --mode=%s --manifest=%s --project-dir=test --app-version=1.0.0" % \
            (comm.Pck_Tools, comm.ARCH, comm.MODE, manfiestPath)
        comm.versionCode(cmd, versionCode, versionCodeBase, self)
        comm.clear_versionCode()

    def test_manifest_version_versionCode(self):
        comm.setUp()
        comm.clear_versionCode()
        targetDir = comm.ConstPath + "/../testapp/example/"
        manfiestPath = targetDir + "manifest.json"
        os.chdir(targetDir)
        versionCode = ""
        versionCodeBase = ""
        cmd = "python %smake_apk.py --package=org.xwalk.example --arch=%s --mode=%s --manifest=%s --project-dir=test --app-version=1.0.0.0" % \
            (comm.Pck_Tools, comm.ARCH, comm.MODE, manfiestPath)
        packstatus = commands.getstatusoutput(cmd)
        errorinfo1 = "Error"
        errorinfo2 = "--app-versionCode"
        errorinfo3 = "--app-versionCodeBase"
        self.assertNotEquals(0, packstatus[0])
        self.assertIn(errorinfo1, packstatus[1])
        self.assertIn(errorinfo2, packstatus[1])
        self.assertIn(errorinfo3, packstatus[1])
        comm.clear_versionCode()

if __name__ == '__main__':
    unittest.main()
<|endoftext|>


<commit_before>#!/usr/bin/python
import pygame
import os
import copy
from pygame.locals import *
from enum import Enum

# TODO: move to commons (confirm)
SCREEN_TITLE = 'Chess'
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 640
BOARD_SIZE = 640
IMAGES_FOLDER_PATH = 'assets/images'

class Color(Enum):
    BLACK = (50, 50, 50)
    WHITE = (230, 230, 230)
    GREEN = (50, 200, 50)
    RED = (200, 50, 50)

    def get_rgb(code):
        if code == 0:
            return Color.BLACK.value
        if code == 1:
            return Color.WHITE.value
        if code == 2:
            return Color.GREEN.value
        if code == 3:
            return  Color.RED.value

def load_png(file_name):
    """ Load image and return image object"""
    fullname = os.path.join(IMAGES_FOLDER_PATH, file_name + '.png')
    try:
        image = pygame.image.load(fullname)
        if image.get_alpha() is None:
            image = image.convert()
        else:
            image = image.convert_alpha()
    except (pygame.error):
        print('Error loading image', fullname)
        raise(pygame.error('a'))
    return image

def draw_board(board, color_board):
    # TODO: comment this after integration (as docs)
    board = [
        ['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'], # 8
        ['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'], # 7
        ['.', '.', '.', '.', '.', '.', '.', '.'], # 6
        ['.', '.', '.', '.', '.', '.', '.', '.'], # 5
        ['.', '.', '.', '.', '.', '.', '.', '.'], # 4
        ['.', '.', '.', '.', '.', '.', '.', '.'], # 3
        ['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'], # 2
        ['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R'], # 1
        # a    b    c    d    e    f    g    h
    ]
    color_board = [
        [1, 2, 1, 0, 1, 0, 1, 0], # 8
        [0, 1, 0, 1, 0, 1, 0, 1], # 7
        [1, 3, 1, 0, 1, 0, 1, 0], # 6
        [0, 1, 0, 1, 0, 1, 0, 1], # 5
        [1, 0, 1, 0, 1, 0, 1, 0], # 4
        [0, 1, 0, 1, 0, 1, 0, 1], # 3
        [1, 0, 1, 0, 1, 0, 1, 0], # 2
        [0, 1, 0, 1, 0, 1, 0, 1], # 1
        #a  b  c  d  e  f  g  h
    ]

    board_surface = pygame.Surface((BOARD_SIZE, BOARD_SIZE)).convert()
    num_of_cells = len(board)
    cell_size = BOARD_SIZE / num_of_cells
    for row in range(num_of_cells):
        for col in range(num_of_cells):
            cell_rect = (col * cell_size, row * cell_size, cell_size, cell_size)
            cell_color = Color.get_rgb(color_board[row][col])
            board_surface.fill(cell_color, cell_rect)
            pawn = pygame.transform.scale(PAWN_IMAGE, (int(cell_size), int(cell_size)))
            board_surface.blit(pawn, cell_rect)

    return board_surface

if __name__ == '__main__':
    # Initialise screen
    pygame.init()
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    pygame.display.set_caption(SCREEN_TITLE)

    # Load images
    PAWN_IMAGE = load_png('chess-pieces/white-pawn')

    # Fill background
    background = pygame.Surface(screen.get_size())
    # Convert the Surface to the pixel format (necessary for all Surfaces)
    background = background.convert()
    background.fill(Color.WHITE.value)

    # Blit everything to the screen
    screen.blit(background, (0, 0))
    pygame.display.flip()

    # Event loop
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == QUIT:
                running = False

        screen.blit(background, (0, 0))
        # give it a margin if board is smaller than screen
        board_position = (
            (SCREEN_WIDTH - BOARD_SIZE) / 2,
            (SCREEN_HEIGHT - BOARD_SIZE) / 2,
        )
        screen.blit(draw_board(['test_board'], ['test_board_color']), board_position)
        pygame.display.flip()
<commit_msg>:rocket: CHS-40 Render chess pieces accordingly to board<commit_after>#!/usr/bin/python
import pygame
import os
import copy
from pygame.locals import *
from enum import Enum

# TODO: move to commons (confirm)
SCREEN_TITLE = 'Chess'
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 640
BOARD_SIZE = 640
IMAGES_FOLDER_PATH = 'assets/images'

class Color(Enum):
    BLACK = (100, 100, 100)
    WHITE = (230, 230, 230)
    GREEN = (50, 200, 50)
    RED = (200, 50, 50)

    def get_rgb(code):
        if code == 0:
            return Color.BLACK.value
        if code == 1:
            return Color.WHITE.value
        if code == 2:
            return Color.GREEN.value
        if code == 3:
            return  Color.RED.value

def load_png(file_name):
    """ Load image and return image object"""
    fullname = os.path.join(IMAGES_FOLDER_PATH, file_name + '.png')
    try:
        image = pygame.image.load(fullname)
        if image.get_alpha() is None:
            image = image.convert()
        else:
            image = image.convert_alpha()
    except (pygame.error):
        print('Error loading image', fullname)
        raise(pygame.error('a'))
    return image

class ChessPiece(pygame.sprite.Sprite):
    def __init__(self, image_file, rect):
        pygame.sprite.Sprite.__init__(self)
        self.image = load_png(image_file)
        self.rect = rect
        screen = pygame.display.get_surface()
        self.area = screen.get_rect()

def draw_board(board, color_board):
    # TODO: comment this after integration (as docs)
    board = [
        ['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'], # 8
        ['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'], # 7
        ['.', '.', '.', '.', '.', '.', '.', '.'], # 6
        ['.', '.', '.', '.', '.', '.', '.', '.'], # 5
        ['.', '.', '.', '.', '.', '.', '.', '.'], # 4
        ['.', '.', '.', '.', '.', '.', '.', '.'], # 3
        ['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'], # 2
        ['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R'], # 1
        # a    b    c    d    e    f    g    h
    ]
    color_board = [
        [1, 2, 1, 0, 1, 0, 1, 0], # 8
        [0, 1, 0, 1, 0, 1, 0, 1], # 7
        [1, 3, 1, 0, 1, 0, 1, 0], # 6
        [0, 1, 0, 1, 0, 1, 0, 1], # 5
        [1, 0, 1, 0, 1, 0, 1, 0], # 4
        [0, 1, 0, 1, 0, 1, 0, 1], # 3
        [1, 0, 1, 0, 1, 0, 1, 0], # 2
        [0, 1, 0, 1, 0, 1, 0, 1], # 1
        #a  b  c  d  e  f  g  h
    ]

    board_surface = pygame.Surface((BOARD_SIZE, BOARD_SIZE)).convert()
    num_of_cells = len(board)
    cell_size = BOARD_SIZE / num_of_cells
    for row in range(num_of_cells):
        for col in range(num_of_cells):
            cell_rect = (col * cell_size, row * cell_size, cell_size, cell_size)
            cell_color = Color.get_rgb(color_board[row][col])
            board_surface.fill(cell_color, cell_rect)

            # Check which image we shall blit on board_surface
            piece_image = None
            if board[row][col] == 'P':
                piece_image = WHITE_PAWN_IMAGE
            elif board[row][col] == 'R':
                piece_image = WHITE_ROOK_IMAGE
            elif board[row][col] == 'N':
                piece_image = WHITE_KNIGHT_IMAGE
            elif board[row][col] == 'B':
                piece_image = WHITE_BISHOP_IMAGE
            elif board[row][col] == 'Q':
                piece_image = WHITE_QUEEN_IMAGE
            elif board[row][col] == 'K':
                piece_image = WHITE_KING_IMAGE
            elif board[row][col] == 'p':
                piece_image = BLACK_PAWN_IMAGE
            elif board[row][col] == 'r':
                piece_image = BLACK_ROOK_IMAGE
            elif board[row][col] == 'n':
                piece_image = BLACK_KNIGHT_IMAGE
            elif board[row][col] == 'b':
                piece_image = BLACK_BISHOP_IMAGE
            elif board[row][col] == 'q':
                piece_image = BLACK_QUEEN_IMAGE
            elif board[row][col] == 'k':
                piece_image = BLACK_KING_IMAGE

            if piece_image is not None:
                chess_piece = pygame.transform.scale(piece_image, (int(cell_size), int(cell_size)))
                board_surface.blit(chess_piece, cell_rect)

    return board_surface

if __name__ == '__main__':
    # Initialise screen
    pygame.init()
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    pygame.display.set_caption(SCREEN_TITLE)

    # Load sprites
    WHITE_PAWN_IMAGE = load_png('chess-pieces/white-pawn')
    WHITE_BISHOP_IMAGE = load_png('chess-pieces/white-bishop')
    WHITE_KING_IMAGE = load_png('chess-pieces/white-king')
    WHITE_KNIGHT_IMAGE = load_png('chess-pieces/white-knight')
    WHITE_QUEEN_IMAGE = load_png('chess-pieces/white-queen')
    WHITE_ROOK_IMAGE = load_png('chess-pieces/white-rook')
    BLACK_PAWN_IMAGE = load_png('chess-pieces/black-pawn')
    BLACK_BISHOP_IMAGE = load_png('chess-pieces/black-bishop')
    BLACK_KING_IMAGE = load_png('chess-pieces/black-king')
    BLACK_KNIGHT_IMAGE = load_png('chess-pieces/black-knight')
    BLACK_QUEEN_IMAGE = load_png('chess-pieces/black-queen')
    BLACK_ROOK_IMAGE = load_png('chess-pieces/black-rook')

    # Fill background
    background = pygame.Surface(screen.get_size())
    # Convert the Surface to the pixel format (necessary for all Surfaces)
    background = background.convert()
    background.fill(Color.WHITE.value)

    # Blit everything to the screen
    screen.blit(background, (0, 0))
    pygame.display.flip()

    # Event loop
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == QUIT:
                running = False

        screen.blit(background, (0, 0))
        # give it a margin if board is smaller than screen
        board_position = (
            (SCREEN_WIDTH - BOARD_SIZE) / 2,
            (SCREEN_HEIGHT - BOARD_SIZE) / 2,
        )
        screen.blit(draw_board(['test_board'], ['test_board_color']), board_position)
        pygame.display.flip()
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals, with_statement
import io

import pytest

utf7s = [__import__('utf7')]
# test _utf7 also if it exists
try:
    utf7s.append(__import__('_utf7'))
except ImportError:
    pass

# fixture 'utf7' will be an usable utf7 module
def pytest_generate_tests(metafunc):
    if 'utf7' in metafunc.fixturenames:
        metafunc.parametrize(['utf7'], [[utf7] for utf7 in utf7s],
                             ids=[m.__name__ for m in utf7s])

def test_packb(utf7):
    assert utf7.packb(127) == b'\x7f'
    assert utf7.packb(256) == b'\x80\x02'
    assert utf7.packb(64) == b'\x40'
    assert utf7.packb(42) == b'\x2a'
    assert utf7.packb(65536) == b'\x80\x80\x04'
    assert utf7.packb(1234567890) == b'\xd2\x85\xd8\xcc\x04'
    assert utf7.packb(2 ** 64 - 1) == b'\xff' * 9 + b'\x01'
    assert utf7.packb(2 ** 64) == b'\x80' * 9 + b'\x02'
    assert utf7.packb(2 ** 128) == b'\x80' * 18 + b'\x04'

def test_unpackb(utf7):
    assert utf7.unpackb(b'\x00') == 0
    assert utf7.unpackb(b'\x7f') == 127
    assert utf7.unpackb(b'\x80\x02') == 256
    assert utf7.unpackb(b'\x40') == 64
    assert utf7.unpackb(b'\x2a') == 42
    assert utf7.unpackb(b'\x80\x80\x04') == 65536
    assert utf7.unpackb(b'\xd2\x85\xd8\xcc\x04') == 1234567890
    assert utf7.unpackb(b'\xff' * 9 + b'\x01') == 2 ** 64 - 1
    assert utf7.unpackb(b'\x80' * 9 + b'\x02') == 2 ** 64
    assert utf7.unpackb(b'\x80' * 18 + b'\x04') == 2 ** 128

def test_pack(utf7):
    buf = io.BytesIO()
    nums = [127, 256, 64, 42, 65536, 1234567890]
    for num in nums:
        assert utf7.pack(num, buf) > 0
    assert buf.getvalue() == \
        b'\x7f\x80\x02\x40\x2a\x80\x80\x04\xd2\x85\xd8\xcc\x04'

def test_unpack(utf7):
    buf = io.BytesIO(b'\x7f\x80\x02\x40\x2a\x80\x80\x04\xd2\x85\xd8\xcc\x04')
    nums = []
    for x in range(6):
        num = utf7.unpack(buf)
        nums.append(num)
    with pytest.raises(StopIteration):
        next(buf)
    assert nums == [127, 256, 64, 42, 65536, 1234567890]

def test_aliases(utf7):
    assert utf7.dump is utf7.pack
    assert utf7.dumps is utf7.packb
    assert utf7.load is utf7.unpack
    assert utf7.loads is utf7.unpackb
    assert utf7.encode is utf7.packb
    assert utf7.decode is utf7.unpackb

def test_negative(utf7):
    with pytest.raises(OverflowError):
        utf7.packb(-1)

def test_various_streams(utf7):
    import socket
    import tempfile
    server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_sock.bind(('127.0.0.1', 0))
    server_sock.listen(5)
    client_sock.connect(server_sock.getsockname())
    server_sock.accept()
    sock_file = client_sock.makefile()
    assert utf7.pack(65536, io.BytesIO()) == 3
    assert utf7.pack(65536, tempfile.TemporaryFile()) == 3
    assert utf7.pack(65536, sock_file) == 3
<commit_msg>pass socket writing test in Python 3<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals, with_statement
import io

import pytest

utf7s = [__import__('utf7')]
# test _utf7 also if it exists
try:
    utf7s.append(__import__('_utf7'))
except ImportError:
    pass

# fixture 'utf7' will be an usable utf7 module
def pytest_generate_tests(metafunc):
    if 'utf7' in metafunc.fixturenames:
        metafunc.parametrize(['utf7'], [[utf7] for utf7 in utf7s],
                             ids=[m.__name__ for m in utf7s])

def test_packb(utf7):
    assert utf7.packb(127) == b'\x7f'
    assert utf7.packb(256) == b'\x80\x02'
    assert utf7.packb(64) == b'\x40'
    assert utf7.packb(42) == b'\x2a'
    assert utf7.packb(65536) == b'\x80\x80\x04'
    assert utf7.packb(1234567890) == b'\xd2\x85\xd8\xcc\x04'
    assert utf7.packb(2 ** 64 - 1) == b'\xff' * 9 + b'\x01'
    assert utf7.packb(2 ** 64) == b'\x80' * 9 + b'\x02'
    assert utf7.packb(2 ** 128) == b'\x80' * 18 + b'\x04'

def test_unpackb(utf7):
    assert utf7.unpackb(b'\x00') == 0
    assert utf7.unpackb(b'\x7f') == 127
    assert utf7.unpackb(b'\x80\x02') == 256
    assert utf7.unpackb(b'\x40') == 64
    assert utf7.unpackb(b'\x2a') == 42
    assert utf7.unpackb(b'\x80\x80\x04') == 65536
    assert utf7.unpackb(b'\xd2\x85\xd8\xcc\x04') == 1234567890
    assert utf7.unpackb(b'\xff' * 9 + b'\x01') == 2 ** 64 - 1
    assert utf7.unpackb(b'\x80' * 9 + b'\x02') == 2 ** 64
    assert utf7.unpackb(b'\x80' * 18 + b'\x04') == 2 ** 128

def test_pack(utf7):
    buf = io.BytesIO()
    nums = [127, 256, 64, 42, 65536, 1234567890]
    for num in nums:
        assert utf7.pack(num, buf) > 0
    assert buf.getvalue() == \
        b'\x7f\x80\x02\x40\x2a\x80\x80\x04\xd2\x85\xd8\xcc\x04'

def test_unpack(utf7):
    buf = io.BytesIO(b'\x7f\x80\x02\x40\x2a\x80\x80\x04\xd2\x85\xd8\xcc\x04')
    nums = []
    for x in range(6):
        num = utf7.unpack(buf)
        nums.append(num)
    with pytest.raises(StopIteration):
        next(buf)
    assert nums == [127, 256, 64, 42, 65536, 1234567890]

def test_aliases(utf7):
    assert utf7.dump is utf7.pack
    assert utf7.dumps is utf7.packb
    assert utf7.load is utf7.unpack
    assert utf7.loads is utf7.unpackb
    assert utf7.encode is utf7.packb
    assert utf7.decode is utf7.unpackb

def test_negative(utf7):
    with pytest.raises(OverflowError):
        utf7.packb(-1)

def test_various_streams(utf7):
    import socket
    import tempfile
    server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_sock.bind(('127.0.0.1', 0))
    server_sock.listen(5)
    client_sock.connect(server_sock.getsockname())
    server_sock.accept()
    sock_file = client_sock.makefile('wb')
    assert utf7.pack(65536, io.BytesIO()) == 3
    assert utf7.pack(65536, tempfile.TemporaryFile()) == 3
    assert utf7.pack(65536, sock_file) == 3
<|endoftext|>


<commit_before>#! /usr/bin/env python
# This file is part of the dune-hdd project:
#   http://users.dune-project.org/projects/dune-hdd
# Copyright holders: Felix Schindler
# License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

import sys
from pybindgen import param, retval

from dune.pymor.core import prepare_python_bindings, inject_lib_dune_pymor, finalize_python_bindings
# from dune.pymor.discretizations import inject_StationaryDiscretizationImplementation
from dune.pymor.discretizations import inject_StationaryMultiscaleDiscretizationImplementation

def inject_Example(module, exceptions, interfaces, CONFIG_H):
    '''injects the user code into the module'''
    # first the discretization
    GridType = 'Dune::ALUGrid< 2, 2, Dune::simplex, Dune::conforming >'
    #GridType = 'Dune::SGrid< 2, 2 >'
    RangeFieldType = 'double'
    dimRange = '1'
    polOrder = '1'
    la_backend = 'Dune::Stuff::LA::ChooseBackend::eigen_sparse'
    if la_backend == 'Dune::Stuff::LA::ChooseBackend::eigen_sparse':
        MatrixType = 'Dune::Stuff::LA::EigenRowMajorSparseMatrix< ' + RangeFieldType + ' >'
        VectorType = 'Dune::Stuff::LA::EigenDenseVector< ' + RangeFieldType + ' >'
    elif la_backend == 'Dune::Stuff::LA::ChooseBackend::istl_sparse':
        MatrixType = 'Dune::Stuff::LA::IstlRowMajorSparseMatrix< ' + RangeFieldType + ' >'
        VectorType = 'Dune::Stuff::LA::IstlDenseVector< ' + RangeFieldType + ' >'
    OperatorType = 'Dune::Pymor::Operators::LinearAffinelyDecomposedContainerBased< ' + MatrixType + ', ' + VectorType + ' >'
    ProductType = OperatorType
    FunctionalType = 'Dune::Pymor::Functionals::LinearAffinelyDecomposedVectorBased< ' + VectorType + ' >'
    DiscretizationName = 'Dune::HDD::LinearElliptic::Discretizations::BlockSWIPDG'
    DiscretizationFullName = (DiscretizationName + '< '
                              + GridType + ', '
                              + RangeFieldType + ', '
                              + dimRange + ', ' + polOrder + ', '
                              + la_backend + '>')
    # discretization = inject_StationaryDiscretizationImplementation(
    inject_StationaryMultiscaleDiscretizationImplementation(module, exceptions, interfaces, CONFIG_H,
                                                            DiscretizationName,
                                                            Traits={'VectorType': VectorType,
                                                                    'OperatorType': OperatorType,
                                                                    'FunctionalType': FunctionalType,
                                                                    'ProductType': ProductType},
                                                            template_parameters=[GridType, RangeFieldType,
                                                                                dimRange, polOrder, la_backend])
    # then add the example
    def add_example(name):
        Example = module.add_class(name, template_parameters=[GridType], custom_name=name)
        Example.add_constructor([param('const std::string', 'partitioning'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'num_refinements'),
                                 param('const size_t', 'oversampling_layers'),
                                 param('const std::vector< std::string >', 'products'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'info_log_levels'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'debug_log_levels'),
                                 param('const bool', 'enable_warnings'),
                                 param('const bool', 'enable_colors'),
                                 param('const std::string', 'info_color'),
                                 param('const std::string', 'debug_color'),
                                 param('const std::string', 'warn_color')],
                                throw=exceptions)
        Example.add_constructor([param('const std::string', 'partitioning'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'num_refinements'),
                                 param('const size_t', 'oversampling_layers'),
                                 param('const std::vector< std::string >', 'products'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'info_log_levels'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'debug_log_levels'),
                                 param('const bool', 'enable_warnings'),
                                 param('const bool', 'enable_colors'),
                                 param('const std::string', 'info_color'),
                                 param('const std::string', 'debug_color')],
                                throw=exceptions)
        Example.add_constructor([param('const std::string', 'partitioning'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'num_refinements'),
                                 param('const size_t', 'oversampling_layers'),
                                 param('const std::vector< std::string >', 'products'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'info_log_levels'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'debug_log_levels'),
                                 param('const bool', 'enable_warnings'),
                                 param('const bool', 'enable_colors'),
                                 param('const std::string', 'info_color')],
                                throw=exceptions)
        Example.add_constructor([param('const std::string', 'partitioning'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'num_refinements'),
                                 param('const size_t', 'oversampling_layers'),
                                 param('const std::vector< std::string >', 'products'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'info_log_levels'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'debug_log_levels'),
                                 param('const bool', 'enable_warnings'),
                                 param('const bool', 'enable_colors')],
                                throw=exceptions)
        Example.add_constructor([param('const std::string', 'partitioning'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'num_refinements'),
                                 param('const size_t', 'oversampling_layers'),
                                 param('const std::vector< std::string >', 'products'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'info_log_levels'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'debug_log_levels'),
                                 param('const bool', 'enable_warnings')],
                                throw=exceptions)
        Example.add_constructor([param('const std::string', 'partitioning'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'num_refinements'),
                                 param('const size_t', 'oversampling_layers'),
                                 param('const std::vector< std::string >', 'products'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'info_log_levels'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'debug_log_levels')],
                                throw=exceptions)
        Example.add_constructor([param('const std::string', 'partitioning'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'num_refinements'),
                                 param('const size_t', 'oversampling_layers'),
                                 param('const std::vector< std::string >', 'products'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'info_log_levels')],
                                throw=exceptions)
        Example.add_constructor([param('const std::string', 'partitioning'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'num_refinements'),
                                 param('const size_t', 'oversampling_layers'),
                                 param('const std::vector< std::string >', 'products')],
                                throw=exceptions)
        Example.add_constructor([param('const std::string', 'partitioning'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'num_refinements'),
                                 param('const size_t', 'oversampling_layers')],
                                throw=exceptions)
        Example.add_constructor([param('const std::string', 'partitioning'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'num_refinements')],
                                throw=exceptions)
        Example.add_constructor([param('const std::string', 'partitioning')],
                                throw=exceptions)
        Example.add_constructor([], throw=exceptions)
        Example.add_method('discretization_and_return_ptr',
                           retval(DiscretizationFullName + ' *', caller_owns_return=True),
                           [], is_const=True, throw=exceptions,
                           custom_name='discretization')
        Example.add_method('visualize',
                           None,
                           [param('const std::string&', 'filename_prefix')],
                           is_const=True, throw=exceptions)
        Example.add_method('project',
                           retval(VectorType),
                           [param('const std::string', 'expression')], is_const=True, throw=exceptions)
        Example.add_method('compute_error',
                           retval(RangeFieldType),
                           [param('const ' + VectorType + '&', 'solution'),
                            param('const std::string', 'product_type'),
                            param('const Dune::Pymor::Parameter', 'mu'),
                            param('const Dune::Pymor::Parameter', 'mu_product')],
                           is_const=True, throw=exceptions)
        Example.add_method('compute_error',
                           retval(RangeFieldType),
                           [param('const ' + VectorType + '&', 'solution'),
                            param('const std::string', 'product_type'),
                            param('const Dune::Pymor::Parameter', 'mu')],
                           is_const=True, throw=exceptions)
        Example.add_method('compute_error',
                           retval(RangeFieldType),
                           [param('const ' + VectorType + '&', 'solution'),
                            param('const std::string', 'product_type')],
                           is_const=True, throw=exceptions)
        Example.add_method('compute_error',
                           retval(RangeFieldType),
                           [param('const ' + VectorType + '&', 'solution')],
                           is_const=True, throw=exceptions)
        Example.add_method('compute_jump_norm',
                           retval(RangeFieldType),
                           [param('const ' + VectorType + '&', 'solution_vector'),
                            param('const Dune::Pymor::Parameter', 'mu_product')],
                           is_const=True, throw=exceptions)
        Example.add_method('available_estimators',
                           retval('std::vector< std::string >'),
                           [],
                           is_const=True, throw=exceptions)
        Example.add_method('estimate',
                           retval(RangeFieldType),
                           [param('const ' + VectorType + '&', 'vector'),
                            param('const std::string', 'type'),
                            param('const Dune::Pymor::Parameter', 'mu_hat'),
                            param('const Dune::Pymor::Parameter', 'mu_bar'),
                            param('const Dune::Pymor::Parameter', 'mu')],
                           is_const=True, throw=exceptions)
        Example.add_method('estimate',
                           retval(RangeFieldType),
                           [param('const ' + VectorType + '&', 'vector'),
                            param('const std::string', 'type')],
                           is_const=True, throw=exceptions)
        Example.add_method('available_local_estimators',
                           retval('std::vector< std::string >'),
                           [],
                           is_const=True, throw=exceptions)
        Example.add_method('estimate_local',
                           retval('std::vector< ' + RangeFieldType + ' >'),
                           [param('const ' + VectorType + '&', 'vector'),
                            param('const std::string', 'type'),
                            param('const Dune::Pymor::Parameter', 'mu_hat'),
                            param('const Dune::Pymor::Parameter', 'mu_bar'),
                            param('const Dune::Pymor::Parameter', 'mu')],
                           is_const=True, throw=exceptions)
        Example.add_method('estimate_local',
                           retval('std::vector< ' + RangeFieldType + ' >'),
                           [param('const ' + VectorType + '&', 'vector'),
                            param('const std::string', 'type')],
                           is_const=True, throw=exceptions)
        Example.add_method('solve_for_local_correction',
                           retval(VectorType),
                           [param('std::vector< ' + VectorType + ' >&', 'local_vectors'),
                            param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'subdomain'),
                            param('const Dune::Pymor::Parameter', 'mu')],
                           is_const=True, throw=exceptions)
        Example.add_method('solve_for_local_correction',
                           retval(VectorType),
                           [param('std::vector< ' + VectorType + ' >&', 'local_vectors'),
                            param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'subdomain')],
                           is_const=True, throw=exceptions)
        Example.add_method('alpha',
                           retval(RangeFieldType),
                           [param('const Dune::Pymor::Parameter&', 'mu_1'),
                            param('const Dune::Pymor::Parameter&', 'mu_2')],
                           is_const=True, throw=exceptions)
        Example.add_method('gamma',
                           retval(RangeFieldType),
                           [param('const Dune::Pymor::Parameter&', 'mu_1'),
                            param('const Dune::Pymor::Parameter&', 'mu_2')],
                           is_const=True, throw=exceptions)
    add_example('Spe10Model1Example')
    add_example('OS2014Example')
    add_example('FiveSpotExample')
    add_example('LocalThermalblockExample')

if __name__ == '__main__':
    # prepare the module
    module, pybindgen_filename, config_h_filename = prepare_python_bindings(sys.argv[1:])
    # add all of libdunepymor
    module, exceptions, interfaces, CONFIG_H = inject_lib_dune_pymor(module, config_h_filename)
    # add example user code (see above)
    inject_Example(module, exceptions, interfaces, CONFIG_H)
    # and finally write the pybindgen .cc file
    finalize_python_bindings(module, pybindgen_filename)
<commit_msg>[examples...OS2014] bind local and oversampled discretizations<commit_after>#! /usr/bin/env python
# This file is part of the dune-hdd project:
#   http://users.dune-project.org/projects/dune-hdd
# Copyright holders: Felix Schindler
# License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

import sys
from pybindgen import param, retval

from dune.pymor.core import prepare_python_bindings, inject_lib_dune_pymor, finalize_python_bindings
from dune.pymor.discretizations import inject_StationaryDiscretizationImplementation
from dune.pymor.discretizations import inject_StationaryMultiscaleDiscretizationImplementation

def inject_Example(module, exceptions, interfaces, CONFIG_H):
    '''injects the user code into the module'''
    # first the discretization
    GridType = 'Dune::ALUGrid< 2, 2, Dune::simplex, Dune::conforming >'
    #GridType = 'Dune::SGrid< 2, 2 >'
    RangeFieldType = 'double'
    dimRange = '1'
    polOrder = '1'
    la_backend = 'Dune::Stuff::LA::ChooseBackend::eigen_sparse'
    if la_backend == 'Dune::Stuff::LA::ChooseBackend::eigen_sparse':
        MatrixType = 'Dune::Stuff::LA::EigenRowMajorSparseMatrix< ' + RangeFieldType + ' >'
        VectorType = 'Dune::Stuff::LA::EigenDenseVector< ' + RangeFieldType + ' >'
    elif la_backend == 'Dune::Stuff::LA::ChooseBackend::istl_sparse':
        MatrixType = 'Dune::Stuff::LA::IstlRowMajorSparseMatrix< ' + RangeFieldType + ' >'
        VectorType = 'Dune::Stuff::LA::IstlDenseVector< ' + RangeFieldType + ' >'
    space_backend = 'Dune::GDT::ChooseSpaceBackend::fem'
    OperatorType = 'Dune::Pymor::Operators::LinearAffinelyDecomposedContainerBased< ' + MatrixType + ', ' + VectorType + ' >'
    ProductType = OperatorType
    FunctionalType = 'Dune::Pymor::Functionals::LinearAffinelyDecomposedVectorBased< ' + VectorType + ' >'
    DiscretizationName = 'Dune::HDD::LinearElliptic::Discretizations::BlockSWIPDG'
    DiscretizationFullName = (DiscretizationName + '< '
                              + GridType + ', '
                              + RangeFieldType + ', '
                              + dimRange + ', ' + polOrder + ', '
                              + la_backend + '>')
    LocalDiscretizationName = 'Dune::HDD::LinearElliptic::Discretizations::SWIPDG'
    local_layer = 'Dune::Stuff::Grid::ChooseLayer::local'
    LocalDiscretizationFullName = (LocalDiscretizationName
                                   + '< ' + GridType + ', '
                                   + local_layer + ', '
                                   + RangeFieldType + ', '
                                   + dimRange + ', ' + polOrder + ', '
                                   + space_backend + ', '
                                   + la_backend + ' >')
    inject_StationaryDiscretizationImplementation(module, exceptions, interfaces, CONFIG_H,
                                                  LocalDiscretizationName,
                                                  Traits={'VectorType': VectorType,
                                                          'OperatorType': OperatorType,
                                                          'FunctionalType': FunctionalType,
                                                          'ProductType': ProductType},
                                                  template_parameters=[GridType, local_layer, RangeFieldType,
                                                                       dimRange, polOrder, space_backend, la_backend])
    oversampled_layer = 'Dune::Stuff::Grid::ChooseLayer::local_oversampled'
    OversampledDiscretizationFullName = (LocalDiscretizationName
                                         + '< ' + GridType + ', '
                                         + oversampled_layer + ', '
                                         + RangeFieldType + ', '
                                         + dimRange + ', ' + polOrder + ', '
                                         + space_backend + ', '
                                         + la_backend + ' >')
    inject_StationaryDiscretizationImplementation(module, exceptions, interfaces, CONFIG_H,
                                                  LocalDiscretizationName,
                                                  Traits={'VectorType': VectorType,
                                                          'OperatorType': OperatorType,
                                                          'FunctionalType': FunctionalType,
                                                          'ProductType': ProductType},
                                                  template_parameters=[GridType, oversampled_layer, RangeFieldType,
                                                                       dimRange, polOrder, space_backend, la_backend])
    # discretization = inject_StationaryDiscretizationImplementation(
    inject_StationaryMultiscaleDiscretizationImplementation(
            module, exceptions, interfaces, CONFIG_H,
            DiscretizationName,
            Traits={'VectorType': VectorType,
                    'OperatorType': OperatorType,
                    'FunctionalType': FunctionalType,
                    'ProductType': ProductType,
                    'LocalDiscretizationType': LocalDiscretizationFullName,
                    'OversampledDiscretizationType': OversampledDiscretizationFullName},
            template_parameters=[GridType, RangeFieldType,
                                 dimRange, polOrder, la_backend])
    # then add the example
    def add_example(name):
        Example = module.add_class(name, template_parameters=[GridType], custom_name=name)
        Example.add_constructor([param('const std::string', 'partitioning'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'num_refinements'),
                                 param('const size_t', 'oversampling_layers'),
                                 param('const std::vector< std::string >', 'products'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'info_log_levels'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'debug_log_levels'),
                                 param('const bool', 'enable_warnings'),
                                 param('const bool', 'enable_colors'),
                                 param('const std::string', 'info_color'),
                                 param('const std::string', 'debug_color'),
                                 param('const std::string', 'warn_color')],
                                throw=exceptions)
        Example.add_constructor([param('const std::string', 'partitioning'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'num_refinements'),
                                 param('const size_t', 'oversampling_layers'),
                                 param('const std::vector< std::string >', 'products'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'info_log_levels'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'debug_log_levels'),
                                 param('const bool', 'enable_warnings'),
                                 param('const bool', 'enable_colors'),
                                 param('const std::string', 'info_color'),
                                 param('const std::string', 'debug_color')],
                                throw=exceptions)
        Example.add_constructor([param('const std::string', 'partitioning'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'num_refinements'),
                                 param('const size_t', 'oversampling_layers'),
                                 param('const std::vector< std::string >', 'products'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'info_log_levels'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'debug_log_levels'),
                                 param('const bool', 'enable_warnings'),
                                 param('const bool', 'enable_colors'),
                                 param('const std::string', 'info_color')],
                                throw=exceptions)
        Example.add_constructor([param('const std::string', 'partitioning'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'num_refinements'),
                                 param('const size_t', 'oversampling_layers'),
                                 param('const std::vector< std::string >', 'products'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'info_log_levels'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'debug_log_levels'),
                                 param('const bool', 'enable_warnings'),
                                 param('const bool', 'enable_colors')],
                                throw=exceptions)
        Example.add_constructor([param('const std::string', 'partitioning'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'num_refinements'),
                                 param('const size_t', 'oversampling_layers'),
                                 param('const std::vector< std::string >', 'products'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'info_log_levels'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'debug_log_levels'),
                                 param('const bool', 'enable_warnings')],
                                throw=exceptions)
        Example.add_constructor([param('const std::string', 'partitioning'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'num_refinements'),
                                 param('const size_t', 'oversampling_layers'),
                                 param('const std::vector< std::string >', 'products'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'info_log_levels'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'debug_log_levels')],
                                throw=exceptions)
        Example.add_constructor([param('const std::string', 'partitioning'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'num_refinements'),
                                 param('const size_t', 'oversampling_layers'),
                                 param('const std::vector< std::string >', 'products'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'info_log_levels')],
                                throw=exceptions)
        Example.add_constructor([param('const std::string', 'partitioning'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'num_refinements'),
                                 param('const size_t', 'oversampling_layers'),
                                 param('const std::vector< std::string >', 'products')],
                                throw=exceptions)
        Example.add_constructor([param('const std::string', 'partitioning'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'num_refinements'),
                                 param('const size_t', 'oversampling_layers')],
                                throw=exceptions)
        Example.add_constructor([param('const std::string', 'partitioning'),
                                 param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'num_refinements')],
                                throw=exceptions)
        Example.add_constructor([param('const std::string', 'partitioning')],
                                throw=exceptions)
        Example.add_constructor([], throw=exceptions)
        Example.add_method('discretization_and_return_ptr',
                           retval(DiscretizationFullName + ' *', caller_owns_return=True),
                           [], is_const=True, throw=exceptions,
                           custom_name='discretization')
        Example.add_method('visualize',
                           None,
                           [param('const std::string&', 'filename_prefix')],
                           is_const=True, throw=exceptions)
        Example.add_method('project',
                           retval(VectorType),
                           [param('const std::string', 'expression')], is_const=True, throw=exceptions)
        Example.add_method('compute_error',
                           retval(RangeFieldType),
                           [param('const ' + VectorType + '&', 'solution'),
                            param('const std::string', 'product_type'),
                            param('const Dune::Pymor::Parameter', 'mu'),
                            param('const Dune::Pymor::Parameter', 'mu_product')],
                           is_const=True, throw=exceptions)
        Example.add_method('compute_error',
                           retval(RangeFieldType),
                           [param('const ' + VectorType + '&', 'solution'),
                            param('const std::string', 'product_type'),
                            param('const Dune::Pymor::Parameter', 'mu')],
                           is_const=True, throw=exceptions)
        Example.add_method('compute_error',
                           retval(RangeFieldType),
                           [param('const ' + VectorType + '&', 'solution'),
                            param('const std::string', 'product_type')],
                           is_const=True, throw=exceptions)
        Example.add_method('compute_error',
                           retval(RangeFieldType),
                           [param('const ' + VectorType + '&', 'solution')],
                           is_const=True, throw=exceptions)
        Example.add_method('compute_jump_norm',
                           retval(RangeFieldType),
                           [param('const ' + VectorType + '&', 'solution_vector'),
                            param('const Dune::Pymor::Parameter', 'mu_product')],
                           is_const=True, throw=exceptions)
        Example.add_method('available_estimators',
                           retval('std::vector< std::string >'),
                           [],
                           is_const=True, throw=exceptions)
        Example.add_method('estimate',
                           retval(RangeFieldType),
                           [param('const ' + VectorType + '&', 'vector'),
                            param('const std::string', 'type'),
                            param('const Dune::Pymor::Parameter', 'mu_hat'),
                            param('const Dune::Pymor::Parameter', 'mu_bar'),
                            param('const Dune::Pymor::Parameter', 'mu')],
                           is_const=True, throw=exceptions)
        Example.add_method('estimate',
                           retval(RangeFieldType),
                           [param('const ' + VectorType + '&', 'vector'),
                            param('const std::string', 'type')],
                           is_const=True, throw=exceptions)
        Example.add_method('available_local_estimators',
                           retval('std::vector< std::string >'),
                           [],
                           is_const=True, throw=exceptions)
        Example.add_method('estimate_local',
                           retval('std::vector< ' + RangeFieldType + ' >'),
                           [param('const ' + VectorType + '&', 'vector'),
                            param('const std::string', 'type'),
                            param('const Dune::Pymor::Parameter', 'mu_hat'),
                            param('const Dune::Pymor::Parameter', 'mu_bar'),
                            param('const Dune::Pymor::Parameter', 'mu')],
                           is_const=True, throw=exceptions)
        Example.add_method('estimate_local',
                           retval('std::vector< ' + RangeFieldType + ' >'),
                           [param('const ' + VectorType + '&', 'vector'),
                            param('const std::string', 'type')],
                           is_const=True, throw=exceptions)
        Example.add_method('solve_for_local_correction',
                           retval(VectorType),
                           [param('std::vector< ' + VectorType + ' >&', 'local_vectors'),
                            param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'subdomain'),
                            param('const Dune::Pymor::Parameter', 'mu')],
                           is_const=True, throw=exceptions)
        Example.add_method('solve_for_local_correction',
                           retval(VectorType),
                           [param('std::vector< ' + VectorType + ' >&', 'local_vectors'),
                            param('const ' + CONFIG_H['DUNE_STUFF_SSIZE_T'], 'subdomain')],
                           is_const=True, throw=exceptions)
        Example.add_method('alpha',
                           retval(RangeFieldType),
                           [param('const Dune::Pymor::Parameter&', 'mu_1'),
                            param('const Dune::Pymor::Parameter&', 'mu_2')],
                           is_const=True, throw=exceptions)
        Example.add_method('gamma',
                           retval(RangeFieldType),
                           [param('const Dune::Pymor::Parameter&', 'mu_1'),
                            param('const Dune::Pymor::Parameter&', 'mu_2')],
                           is_const=True, throw=exceptions)
    add_example('Spe10Model1Example')
    add_example('OS2014Example')
    add_example('FiveSpotExample')
    add_example('LocalThermalblockExample')

if __name__ == '__main__':
    # prepare the module
    module, pybindgen_filename, config_h_filename = prepare_python_bindings(sys.argv[1:])
    # add all of libdunepymor
    module, exceptions, interfaces, CONFIG_H = inject_lib_dune_pymor(module, config_h_filename)
    # add example user code (see above)
    inject_Example(module, exceptions, interfaces, CONFIG_H)
    # and finally write the pybindgen .cc file
    finalize_python_bindings(module, pybindgen_filename)
<|endoftext|>