text:
using Microsoft.DirectX.Direct3D;
using Microsoft.DirectX.DirectInput;
using System;
using System.Drawing;
using System.Windows.Forms;
using TGC.Core.Direct3D;
using TGC.Core.Input;
using TGC.Core.Mathematica;
using TGC.Core.SceneLoader;
using TGC.Core.Terrain;
using TGC.Examples.Example;
using TGC.Examples.UserControls;
using Effect = Microsoft.DirectX.Direct3D.Effect;

namespace TGC.Examples.ShadersExamples
{
    public class OutRun : TGCExampleViewer
    {
        public float acel_mouse_wheel = 20f;
        private TgcMesh car;
        public TGCVector3 car_Scale = new TGCVector3(0.5f, 0.5f, 0.5f);
        private F1Circuit circuito;

        public TGCVector3 desf = new TGCVector3(0, 20, 0); // 40
        public TGCVector3 dir;
        public float dist_cam = 13; //130;
        private Effect effect;
        public float ftime; // frame time
        private Surface g_pDepthStencil; // Depth-stencil buffer
        private Surface g_pDepthStencilOld; // Depth-stencil buffer
        private Texture g_pRenderTarget, g_pRenderTarget2, g_pRenderTarget3, g_pRenderTarget4, g_pRenderTarget5;

        private VertexBuffer g_pVBV3D;
        public bool mouseCaptured;
        public Point mouseCenter;
        private string MyShaderDir;

        public bool paused;
        public TGCVector3 pos;
        public float rotationSpeed = 0.1f;
        private TgcSkyBox skyBox;

        private TgcSimpleTerrain terrain;
        public float vel = 100f;

        public OutRun(string mediaDir, string shadersDir, TgcUserVars userVars, Panel modifiersPanel)
            : base(mediaDir, shadersDir, userVars, modifiersPanel)
        {
            Category = "Pixel y Vertex Shaders";
            Name = "Demo OutRun Avanzado";
            Description = "OutRun Circuit Demo, [P]-> pause, [M]->cursor lock";
        }

        public override void Init()
        {
            var d3dDevice = D3DDevice.Instance.Device;

            MyShaderDir = ShadersDir + "WorkshopShaders\\";

            circuito = new F1Circuit(MediaDir);

            //Cargar terreno: cargar heightmap y textura de color
            terrain = new TgcSimpleTerrain();
            terrain.loadHeightmap(MediaDir + "Heighmaps\\" + "TerrainTexture2.jpg",
                20, 0.1f, new TGCVector3(0, -125, 0));
            terrain.loadTexture(MediaDir + "Heighmaps\\" + "TerrainTexture2.jpg");

            //Crear SkyBox
            skyBox = new TgcSkyBox();
            skyBox.Center = new TGCVector3(0, 500, 0);
            skyBox.Size = new TGCVector3(10000, 10000, 10000);
            var texturesPath = MediaDir + "Texturas\\Quake\\SkyBox LostAtSeaDay\\";
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Up, texturesPath + "lostatseaday_up.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Down, texturesPath + "lostatseaday_dn.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Left, texturesPath + "lostatseaday_lf.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Right, texturesPath + "lostatseaday_rt.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Front, texturesPath + "lostatseaday_bk.jpg");
            skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Back, texturesPath + "lostatseaday_ft.jpg");
            skyBox.Init();

            var loader = new TgcSceneLoader();
            var scene = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Meshes\\Vehiculos\\Auto\\Auto-TgcScene.xml");
            car = scene.Meshes[0];

            //Cargar Shader personalizado
            string compilationErrors;
            effect = Effect.FromFile(D3DDevice.Instance.Device, MyShaderDir + "OutRun.fx",
                null, null, ShaderFlags.PreferFlowControl, null, out compilationErrors);
            if (effect == null)
            {
                throw new Exception("Error al cargar shader. Errores: " + compilationErrors);
            }
            //Configurar Technique dentro del shader
            effect.Technique = "DefaultTechnique";

            //Configurar FPS Camera
            Camera.SetCamera(new TGCVector3(315.451f, 40, -464.28490f), new TGCVector3(315.451f, 40, -465.28490f));

            reset_pos();

            // para capturar el mouse
            var focusWindows = D3DDevice.Instance.Device.CreationParameters.FocusWindow;
            mouseCenter = focusWindows.PointToScreen(new Point(focusWindows.Width / 2, focusWindows.Height / 2));
            mouseCaptured = true;
            Cursor.Hide();

            // stencil
            g_pDepthStencil = d3dDevice.CreateDepthStencilSurface(d3dDevice.PresentationParameters.BackBufferWidth,
                d3dDevice.PresentationParameters.BackBufferHeight,
                DepthFormat.D24S8, MultiSampleType.None, 0, true);
            g_pDepthStencilOld = d3dDevice.DepthStencilSurface;
            // inicializo el render target
            g_pRenderTarget = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth
                , d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget,
                Format.X8R8G8B8, Pool.Default);
            g_pRenderTarget2 = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth
                , d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget,
                Format.X8R8G8B8, Pool.Default);
            g_pRenderTarget3 = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth
                , d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget,
                Format.X8R8G8B8, Pool.Default);
            g_pRenderTarget4 = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth
                , d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget,
                Format.X8R8G8B8, Pool.Default);
            g_pRenderTarget5 = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth
                , d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget,
                Format.X8R8G8B8, Pool.Default);

            // Resolucion de pantalla
            effect.SetValue("screen_dx", d3dDevice.PresentationParameters.BackBufferWidth);
            effect.SetValue("screen_dy", d3dDevice.PresentationParameters.BackBufferHeight);

            CustomVertex.PositionTextured[] vertices =
            {
                new CustomVertex.PositionTextured(-1, 1, 1, 0, 0),
                new CustomVertex.PositionTextured(1, 1, 1, 1, 0),
                new CustomVertex.PositionTextured(-1, -1, 1, 0, 1),
                new CustomVertex.PositionTextured(1, -1, 1, 1, 1)
            };
            //vertex buffer de los triangulos
            g_pVBV3D = new VertexBuffer(typeof(CustomVertex.PositionTextured),
                4, d3dDevice, Usage.Dynamic | Usage.WriteOnly,
                CustomVertex.PositionTextured.Format, Pool.Default);
            g_pVBV3D.SetData(vertices, 0, LockFlags.None);
        }

        public void reset_pos()
        {
            // pongo el auto en el primer tramo de la ruta
            pos = circuito.pt_ruta[40];
            dir = circuito.pt_ruta[41] - pos;
            pos.Y += 15;
            dir.Y = 0;
            dir.Normalize();
        }

        public override void Update()
        {
            if (Input.keyPressed(Key.P))
                paused = !paused;

            if (paused)
                return;

            if (Input.keyPressed(Key.M))
            {
                mouseCaptured = !mouseCaptured;
                if (mouseCaptured)
                    Cursor.Hide();
                else
                    Cursor.Show();
            }

            vel += Input.WheelPos * acel_mouse_wheel;

            if (mouseCaptured || Input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT))
            {
                //float pitch = d3dInput.YposRelative * rotationSpeed;
                var heading = Input.XposRelative * rotationSpeed;
                dir = rotar_xz(dir, -heading);
            }

            if (mouseCaptured)
                Cursor.Position = mouseCenter;

            // aplico la velocidad
            pos = pos + dir * vel * ElapsedTime;

            // verifico si sigue en la ruta
            var H = circuito.updatePos(pos.X, pos.Z);
            if (!circuito.en_ruta)
            {
                // lo mando de nuevo a la ruta
                pos = circuito.que_pos_buena(pos.X, pos.Z);
            }

            // mantengo el auto en la ruta
            pos.Y = H;

            // actualizo la posiicon del auto
            car.Position = pos;
            car.Transform = CalcularMatriz(pos, car_Scale, -dir);

            // actualizo la camara
            Camera.SetCamera(pos - dir * dist_cam + desf, pos + desf);
            //this.Camera.SetCamera(new TGCVector3(500, 4000, 500), TGCVector3.Empty);
            Camera.UpdateCamera(ElapsedTime);
        }

        public override void Render()
        {
            ClearTextures();

            var device = D3DDevice.Instance.Device;
            effect.Technique = "DefaultTechnique";

            // guardo el Render target anterior y seteo la textura como render target
            var pOldRT = device.GetRenderTarget(0);
            var pSurf = g_pRenderTarget.GetSurfaceLevel(0);
            device.SetRenderTarget(0, pSurf);
            // hago lo mismo con el depthbuffer, necesito el que no tiene multisampling
            var pOldDS = device.DepthStencilSurface;
            device.DepthStencilSurface = g_pDepthStencil;

            device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);

            device.BeginScene();

            // -------------------------------------
            //Renderizar terreno
            terrain.Effect = effect;
            terrain.Technique = "DefaultTechnique";
            terrain.Render();
            // skybox
            skyBox.Render();
            //Renderizar pista
            circuito.render(effect);
            //Renderizar auto
            car.Effect = effect;
            car.Technique = "DefaultTechnique";
            car.Render();
            // -------------------------------------

            device.EndScene();

            pSurf.Dispose();

            // Ultima pasada vertical va sobre la pantalla pp dicha
            device.SetRenderTarget(0, pOldRT);
            device.DepthStencilSurface = g_pDepthStencilOld;
            device.BeginScene();

            effect.Technique = "FrameMotionBlur";
            device.VertexFormat = CustomVertex.PositionTextured.Format;
            device.SetStreamSource(0, g_pVBV3D, 0);
            effect.SetValue("g_RenderTarget", g_pRenderTarget);
            effect.SetValue("g_RenderTarget2", g_pRenderTarget2);
            effect.SetValue("g_RenderTarget3", g_pRenderTarget3);
            effect.SetValue("g_RenderTarget4", g_pRenderTarget4);
            effect.SetValue("g_RenderTarget5", g_pRenderTarget5);
            device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
            effect.Begin(FX.None);
            effect.BeginPass(0);
            device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2);
            effect.EndPass();
            effect.End();

            //TgcDrawText.Instance.drawText("Pos: " + this.Camera.Position, 0, 0, Color.Yellow);
            //TgcDrawText.Instance.drawText("Look At: " + CamaraManager.Instance.CurrentCamera.getLookAt(), 500, 0, Color.Yellow);

            if (circuito.en_ruta)
                DrawText.drawText("Tramo:" + circuito.pos_en_ruta, 0, 15, Color.Yellow);

            //TgcDrawText.Instance.drawText("dist_cam:" + dist_cam + "defY" + desf.Y, 0, 0, Color.Yellow);
            //TgcDrawText.Instance.drawText("vel:" + vel, 0, 0, Color.Yellow);

            RenderFPS();
            RenderAxis();
            device.EndScene();
            device.Present();

            ftime += ElapsedTime;
            if (ftime > 0.03f)
            {
                ftime = 0;
                var aux = g_pRenderTarget5;
                g_pRenderTarget5 = g_pRenderTarget4;
                g_pRenderTarget4 = g_pRenderTarget3;
                g_pRenderTarget3 = g_pRenderTarget2;
                g_pRenderTarget2 = g_pRenderTarget;
                g_pRenderTarget = aux;
            }
        }

        public override void Dispose()
        {
            circuito.dispose();
            car.Dispose();
            effect.Dispose();
            terrain.Dispose();
            skyBox.Dispose();

            g_pRenderTarget.Dispose();
            g_pRenderTarget2.Dispose();
            g_pRenderTarget3.Dispose();
            g_pRenderTarget4.Dispose();
            g_pRenderTarget5.Dispose();
            g_pDepthStencil.Dispose();
            g_pVBV3D.Dispose();
        }

        // helper
        public TGCMatrix CalcularMatriz(TGCVector3 Pos, TGCVector3 Scale, TGCVector3 Dir)
        {
            var VUP = TGCVector3.Up;

            var matWorld = TGCMatrix.Scaling(Scale);
            // determino la orientacion
            var U = TGCVector3.Cross(VUP, Dir);
            U.Normalize();
            var V = TGCVector3.Cross(Dir, U);
            TGCMatrix Orientacion = new TGCMatrix();
            Orientacion.M11 = U.X;
            Orientacion.M12 = U.Y;
            Orientacion.M13 = U.Z;
            Orientacion.M14 = 0;

            Orientacion.M21 = V.X;
            Orientacion.M22 = V.Y;
            Orientacion.M23 = V.Z;
            Orientacion.M24 = 0;

            Orientacion.M31 = Dir.X;
            Orientacion.M32 = Dir.Y;
            Orientacion.M33 = Dir.Z;
            Orientacion.M34 = 0;

            Orientacion.M41 = 0;
            Orientacion.M42 = 0;
            Orientacion.M43 = 0;
            Orientacion.M44 = 1;
            matWorld = matWorld * Orientacion;

            // traslado
            matWorld = matWorld * TGCMatrix.Translation(Pos);
            return matWorld;
        }

        public TGCVector3 rotar_xz(TGCVector3 v, float an)
        {
            return new TGCVector3((float)(v.X * Math.Cos(an) - v.Z * Math.Sin(an)), v.Y,
                (float)(v.X * Math.Sin(an) + v.Z * Math.Cos(an)));
        }
    }
}


text:
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.media.remote;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.MediaRouteChooserDialogFragment;
import android.support.v7.app.MediaRouteControllerDialogFragment;
import android.support.v7.app.MediaRouteDialogFactory;
import android.util.Log;

import com.google.android.gms.cast.CastMediaControlIntent;

import org.chromium.base.ApplicationStatus;
import org.chromium.base.ThreadUtils;
import org.chromium.base.VisibleForTesting;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.media.remote.RemoteVideoInfo.PlayerState;
import org.chromium.ui.widget.Toast;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * The singleton responsible managing the global resources for remote media playback (cast)
 */
public class RemoteMediaPlayerController implements MediaRouteController.UiListener {
    // Singleton instance of the class. May only be accessed from UI thread.
    private static RemoteMediaPlayerController sInstance;

    private static final String TAG = "VideoFling";

    private static final String DEFAULT_CASTING_MESSAGE = "Casting to Chromecast";

    private TransportControl mNotificationControl;
    private TransportControl mLockScreenControl;

    private Context mCastContextApplicationContext;
    // The Activity that was in the foreground when the video was cast.
    private WeakReference<Activity> mChromeVideoActivity;

    private List<MediaRouteController> mMediaRouteControllers;

    // points to mDefaultRouteSelector, mYouTubeRouteSelector or null
    private MediaRouteController mCurrentRouteController;

    private boolean mFirstConnection = true;

    // This is a key for meta-data in the package manifest.
    private static final String REMOTE_MEDIA_PLAYERS_KEY =
            "org.chromium.content.browser.REMOTE_MEDIA_PLAYERS";

    /**
     * The private constructor to make sure the object is only created by the instance() method.
     */
    private RemoteMediaPlayerController() {
        mChromeVideoActivity = new WeakReference<Activity>(null);
        mMediaRouteControllers = new ArrayList<MediaRouteController>();
    }

    /**
     * @return The poster image for the currently playing remote video, null if there's none.
     */
    public Bitmap getPoster() {
        if (mCurrentRouteController == null) return null;
        return mCurrentRouteController.getPoster();
    }

    /**
     * The singleton instance access method for native objects. Must be called on the UI thread
     * only.
     */
    public static RemoteMediaPlayerController instance() {
        ThreadUtils.assertOnUiThread();

        if (sInstance == null) sInstance = new RemoteMediaPlayerController();
        if (sInstance.mChromeVideoActivity.get() == null) sInstance.linkToBrowserActivity();

        return sInstance;
    }

    /**
     * Gets the MediaRouteController for a video, creating it if necessary.
     * @param frameUrl The Url of the frame containing the video
     * @return the MediaRouteController, or null if none.
     */
    public MediaRouteController getMediaRouteController(String sourceUrl, String frameUrl) {
        for (MediaRouteController controller: mMediaRouteControllers) {
            if (controller.canPlayMedia(sourceUrl, frameUrl)) {
                return controller;
            }
        }
        return null;
    }

    /**
     * Gets the default MediaRouteController, creating it if necessary.
     * @return the default MediaRouteController.
     */
    public List<MediaRouteController> getMediaRouteControllers() {
        return mMediaRouteControllers;
    }

    /**
     * Links this object to the Activity that owns the video, if it exists.
     *
     */
    private void linkToBrowserActivity() {

        Activity currentActivity = ApplicationStatus.getLastTrackedFocusedActivity();
        if (currentActivity != null) {
            mChromeVideoActivity = new WeakReference<Activity>(currentActivity);

            mCastContextApplicationContext = currentActivity.getApplicationContext();
            createMediaRouteControllers(currentActivity);
        }
    }

    /**
     * Create the mediaRouteControllers
     * @param context - the current Android Context
     */
    public void createMediaRouteControllers(Context context) {
        // We only need to do this once
        if (!mMediaRouteControllers.isEmpty()) return;
        try {
            ApplicationInfo ai = context.getPackageManager().getApplicationInfo(
                    context.getPackageName(), PackageManager.GET_META_DATA);
            Bundle bundle = ai.metaData;
            String classNameString = bundle.getString(REMOTE_MEDIA_PLAYERS_KEY);

            if (classNameString != null) {
                String[] classNames = classNameString.split(",");
                for (String className : classNames) {
                    Log.i(TAG, "Adding remote media route controller " + className.trim());
                    Class<?> mediaRouteControllerClass = Class.forName(className.trim());
                    Object mediaRouteController = mediaRouteControllerClass.newInstance();
                    assert mediaRouteController instanceof MediaRouteController;
                    mMediaRouteControllers.add((MediaRouteController) mediaRouteController);
                }
            }
        } catch (NameNotFoundException | ClassNotFoundException | SecurityException
                | InstantiationException | IllegalAccessException | IllegalArgumentException e) {
            // Should never happen, implies corrupt AndroidManifest
            Log.e(TAG, "Couldn't instatiate MediaRouteControllers", e);
            assert false;
        }
    }

    private void onStateReset(MediaRouteController controller) {

        if (!controller.initialize()) return;

        if (mFirstConnection) {
            controller.reconnectAnyExistingRoute();
            mFirstConnection = false;
        }

        if (mNotificationControl != null) {
            mNotificationControl.setRouteController(controller);
        }
        if (mLockScreenControl != null) {
            mLockScreenControl.setRouteController(controller);
        }
        controller.prepareMediaRoute();

        controller.addUiListener(this);
    }

    /**
     * Called when a lower layer requests that a video be cast. This will typically be a request
     * from Blink when the cast button is pressed on the default video controls.
     * @param player the player for which cast is being requested
     * @param frameUrl the URL of the frame containing the video, needed for YouTube videos
     */
    public void requestRemotePlayback(
            MediaRouteController.MediaStateListener player, MediaRouteController controller) {
        // If we are already casting then simply switch to new video.
        if (controller.isBeingCast()) {
            controller.playerTakesOverCastDevice(player);
            return;
        }
        Activity currentActivity = ApplicationStatus.getLastTrackedFocusedActivity();
        mChromeVideoActivity = new WeakReference<Activity>(currentActivity);

        if (mCurrentRouteController != null && controller != mCurrentRouteController) {
            mCurrentRouteController.release();
        }

        onStateReset(controller);
        if (controller.shouldResetState(player)) {
            controller.setMediaStateListener(player);
            showMediaRouteDialog(controller, currentActivity);
        }

    }

    /**
     * Called when a lower layer requests control of a video that is being cast.
     * @param player The player for which remote playback control is being requested.
     */
    public void requestRemotePlaybackControl(MediaRouteController.MediaStateListener player) {
        // Player should match currently remotely played item, but there
        // can be a race between various
        // ways that the a video can stop playing remotely. Check that the
        // player is current, and ignore if not.

        if (mCurrentRouteController == null) return;
        if (mCurrentRouteController.getMediaStateListener() != player) return;

        showMediaRouteControlDialog(mCurrentRouteController,
                ApplicationStatus.getLastTrackedFocusedActivity());
    }

    private void showMediaRouteDialog(MediaRouteController controller, Activity activity) {

        FragmentManager fm = ((FragmentActivity) activity).getSupportFragmentManager();
        if (fm == null) {
            throw new IllegalStateException("The activity must be a subclass of FragmentActivity");
        }

        MediaRouteDialogFactory factory = new ChromeMediaRouteDialogFactory();

        if (fm.findFragmentByTag(
                "android.support.v7.mediarouter:MediaRouteChooserDialogFragment") != null) {
            Log.w(TAG, "showDialog(): Route chooser dialog already showing!");
            return;
        }
        MediaRouteChooserDialogFragment f = factory.onCreateChooserDialogFragment();

        f.setRouteSelector(controller.buildMediaRouteSelector());
        f.show(fm, "android.support.v7.mediarouter:MediaRouteChooserDialogFragment");
    }

    private void showMediaRouteControlDialog(MediaRouteController controller, Activity activity) {

        FragmentManager fm = ((FragmentActivity) activity).getSupportFragmentManager();
        if (fm == null) {
            throw new IllegalStateException("The activity must be a subclass of FragmentActivity");
        }
        MediaRouteDialogFactory factory = new ChromeMediaRouteDialogFactory();

        if (fm.findFragmentByTag(
                "android.support.v7.mediarouter:MediaRouteControllerDialogFragment") != null) {
            Log.w(TAG, "showDialog(): Route controller dialog already showing!");
            return;
        }
        MediaRouteControllerDialogFragment f = factory.onCreateControllerDialogFragment();

        f.show(fm, "android.support.v7.mediarouter:MediaRouteControllerDialogFragment");
    }

     /**
     * Starts up the notification and lock screen with the given playback state.
     *
     * @param initialState the initial state of the notification
     * @param mediaRouteController the mediaRouteController for which these are needed
     */
    public void startNotificationAndLockScreen(PlayerState initialState,
            MediaRouteController mediaRouteController) {
        mCurrentRouteController = mediaRouteController;
        createNotificationControl();
        getNotification().show(initialState);
        createLockScreen();
        TransportControl lockScreen = getLockScreen();
        if (lockScreen != null) lockScreen.show(initialState);
    }

    /**
     * @return the currently playing MediaRouteController
     */
    public MediaRouteController getCurrentlyPlayingMediaRouteController() {
        return mCurrentRouteController;
    }

    /**
     * Set the current MediaRouteController
     * @param controller the controller
     */
    public void setCurrentMediaRouteController(MediaRouteController controller) {
        mCurrentRouteController = controller;
    }

    private TransportControl getNotification() {
        return mNotificationControl;
    }

    /**
     *
     */
    private void createNotificationControl() {
        mNotificationControl = NotificationTransportControl.getOrCreate(
                mChromeVideoActivity.get(), mCurrentRouteController);
        mNotificationControl.setError(null);
        mNotificationControl.setScreenName(mCurrentRouteController.getRouteName());
        mNotificationControl.addListener(mCurrentRouteController);
    }

    private TransportControl getLockScreen() {
        return mLockScreenControl;
    }

    private void createLockScreen() {
        mLockScreenControl = LockScreenTransportControl.getOrCreate(
                mChromeVideoActivity.get(), mCurrentRouteController);
        mLockScreenControl.setError(null);
        mLockScreenControl.setScreenName(mCurrentRouteController.getRouteName());
        mLockScreenControl.addListener(mCurrentRouteController);
        mLockScreenControl.setPosterBitmap(getPoster());
    }

    @Override
    public void onPrepared(MediaRouteController mediaRouteController) {

        startNotificationAndLockScreen(PlayerState.PLAYING, mediaRouteController);
    }

    @Override
    public void onPlaybackStateChanged(PlayerState oldState, PlayerState newState) {
        if (newState == PlayerState.PLAYING || newState == PlayerState.LOADING
                || newState == PlayerState.PAUSED) {
            TransportControl notificationControl = getNotification();
            if (notificationControl != null) notificationControl.show(newState);
            TransportControl lockScreen = getLockScreen();
            if (lockScreen != null) lockScreen.show(newState);
        }
    }

    @Override
    public void onError(int error, String errorMessage) {
        if (error == CastMediaControlIntent.ERROR_CODE_SESSION_START_FAILED) {
            showMessageToast(errorMessage);
        }
    }

    @Override
    public void onDurationUpdated(int durationMillis) {}

    @Override
    public void onPositionChanged(int positionMillis) {}

    @Override
    public void onTitleChanged(String title) {}

    @Override
    public void onRouteSelected(String routeName, MediaRouteController mediaRouteController) {
        if (mCurrentRouteController != mediaRouteController) {
            mCurrentRouteController = mediaRouteController;
            resetPlayingVideo();
        }
    }

    /**
     * Gets some text to tell the user that the video is being cast.
     * @param routeName The name of the route on which the video is being cast.
     * @return A String to be shown to the user.
     */
    public String getCastingMessage(String routeName) {
        String castingMessage = DEFAULT_CASTING_MESSAGE;
        if (mCastContextApplicationContext != null) {
            castingMessage = mCastContextApplicationContext.getString(
                    R.string.cast_casting_video, routeName);
        }
        return castingMessage;
    }

    // Note that, after switching MediaRouteControllers onRouteUnselected may be called for
    // the old media route controller, so this should not do anything to
    // mCurrentRouteController
    @Override
    public void onRouteUnselected(MediaRouteController mediaRouteController) {
        if (mediaRouteController == mCurrentRouteController) {
            mCurrentRouteController = null;
        }
    }

    private void showMessageToast(String message) {
        Toast toast = Toast.makeText(mCastContextApplicationContext, message, Toast.LENGTH_SHORT);
        toast.show();
    }

    private void resetPlayingVideo() {
        if (mNotificationControl != null) {
            mNotificationControl.setRouteController(mCurrentRouteController);
        }
        if (mLockScreenControl != null) {
            mLockScreenControl.setRouteController(mCurrentRouteController);
        }
    }

    @VisibleForTesting
    static RemoteMediaPlayerController getIfExists() {
        return sInstance;
    }

}

redpajama_set_name: RedPajamaGithub


text:
{% extends "base.html" %}
{% block content %}

Você tem certeza que deseja remover {{genderLetter}} {{dog.name}}?

			<form method="post" action="">
				{% csrf_token %}
				{% if redirect_field_value %}
				<input type="hidden" name="{{redirect_field_name}}" value="{{redirect_field_value}}"/>
				{% endif %}

					 Não, desejo voltar
					<button type="submit" class="btn btn-lg btn-danger"> Sim, desejo excluir</button>
				</button>
			</form>

{% endblock %}


text:
<?php
    class vProjects
    {
        // Génération de la vue "Projects" pour la page
        function generateView_pageDefault($private_projects, $public_projects)
        {
            echo "
";

            // Titre des catégories
            echo "

{{desktop.projects.private}}

{{desktop.projects.public}}

";

            // Liste des projets privés
            echo "

";

			echo "

					Nouveau projet personnel

			";

            for($i = 0; $i < count($private_projects); $i++)
            {
                echo "

                        {$private_projects[$i]["name"]}

                ";
            }

            echo "

";

            // Liste des projets publiques
            echo "

";

			echo "

					Nouveau projet public

			";

            for($i = 0; $i < count($public_projects); $i++)
            {
                echo "

                        {$public_projects[$i]["name"]}
                ";

				if($public_projects[$i]["owner"] === $_SESSION['session']['token'])
				{
					echo " ";
				}
				else
				{
					echo "";
				}

				echo "
";
            }

            echo "

";

            echo "
";
        }

        // Génération de l'éditeur
        function generateView_editor($return)
        {
            echo json_encode($return);
        }
    }
?>


text:
#pragma once
#include <aws/ram/RAM_EXPORTS.h>
#include <aws/ram/RAMRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace RAM
{
namespace Model
{

  /**
   */
  class AWS_RAM_API RejectResourceShareInvitationRequest : public RAMRequest
  {
  public:
    RejectResourceShareInvitationRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "RejectResourceShareInvitation"; }

    Aws::String SerializePayload() const override;

    /**
     *
Specifies the Amazon
     * Resoure Name (ARN) of the invitation that you want to reject.

     */
    inline const Aws::String& GetResourceShareInvitationArn() const{ return m_resourceShareInvitationArn; }

    /**
     *
Specifies the Amazon
     * Resoure Name (ARN) of the invitation that you want to reject.

     */
    inline bool ResourceShareInvitationArnHasBeenSet() const { return m_resourceShareInvitationArnHasBeenSet; }

    /**
     *
Specifies the Amazon
     * Resoure Name (ARN) of the invitation that you want to reject.

     */
    inline void SetResourceShareInvitationArn(const Aws::String& value) { m_resourceShareInvitationArnHasBeenSet = true; m_resourceShareInvitationArn = value; }

    /**
     *
Specifies the Amazon
     * Resoure Name (ARN) of the invitation that you want to reject.

     */
    inline void SetResourceShareInvitationArn(Aws::String&& value) { m_resourceShareInvitationArnHasBeenSet = true; m_resourceShareInvitationArn = std::move(value); }

    /**
     *
Specifies the Amazon
     * Resoure Name (ARN) of the invitation that you want to reject.

     */
    inline void SetResourceShareInvitationArn(const char* value) { m_resourceShareInvitationArnHasBeenSet = true; m_resourceShareInvitationArn.assign(value); }

    /**
     *
Specifies the Amazon
     * Resoure Name (ARN) of the invitation that you want to reject.

     */
    inline RejectResourceShareInvitationRequest& WithResourceShareInvitationArn(const Aws::String& value) { SetResourceShareInvitationArn(value); return *this;}

    /**
     *
Specifies the Amazon
     * Resoure Name (ARN) of the invitation that you want to reject.

     */
    inline RejectResourceShareInvitationRequest& WithResourceShareInvitationArn(Aws::String&& value) { SetResourceShareInvitationArn(std::move(value)); return *this;}

    /**
     *
Specifies the Amazon
     * Resoure Name (ARN) of the invitation that you want to reject.

     */
    inline RejectResourceShareInvitationRequest& WithResourceShareInvitationArn(const char* value) { SetResourceShareInvitationArn(value); return *this;}

    /**
     *
Specifies a unique, case-sensitive identifier that you provide to ensure the
     * idempotency of the request. This lets you safely retry the request without
     * accidentally performing the same operation a second time. Passing the same value
     * to a later call to an operation requires that you also pass the same value for
     * all other parameters. We recommend that you use a UUID type of
     * value..

If you don't provide this value, then Amazon Web Services
     * generates a random one for you.

     */
    inline const Aws::String& GetClientToken() const{ return m_clientToken; }

    /**
     *
Specifies a unique, case-sensitive identifier that you provide to ensure the
     * idempotency of the request. This lets you safely retry the request without
     * accidentally performing the same operation a second time. Passing the same value
     * to a later call to an operation requires that you also pass the same value for
     * all other parameters. We recommend that you use a UUID type of
     * value..

If you don't provide this value, then Amazon Web Services
     * generates a random one for you.

     */
    inline bool ClientTokenHasBeenSet() const { return m_clientTokenHasBeenSet; }

    /**
     *
Specifies a unique, case-sensitive identifier that you provide to ensure the
     * idempotency of the request. This lets you safely retry the request without
     * accidentally performing the same operation a second time. Passing the same value
     * to a later call to an operation requires that you also pass the same value for
     * all other parameters. We recommend that you use a UUID type of
     * value..

If you don't provide this value, then Amazon Web Services
     * generates a random one for you.

     */
    inline void SetClientToken(const Aws::String& value) { m_clientTokenHasBeenSet = true; m_clientToken = value; }

    /**
     *
Specifies a unique, case-sensitive identifier that you provide to ensure the
     * idempotency of the request. This lets you safely retry the request without
     * accidentally performing the same operation a second time. Passing the same value
     * to a later call to an operation requires that you also pass the same value for
     * all other parameters. We recommend that you use a UUID type of
     * value..

If you don't provide this value, then Amazon Web Services
     * generates a random one for you.

     */
    inline void SetClientToken(Aws::String&& value) { m_clientTokenHasBeenSet = true; m_clientToken = std::move(value); }

    /**
     *
Specifies a unique, case-sensitive identifier that you provide to ensure the
     * idempotency of the request. This lets you safely retry the request without
     * accidentally performing the same operation a second time. Passing the same value
     * to a later call to an operation requires that you also pass the same value for
     * all other parameters. We recommend that you use a UUID type of
     * value..

If you don't provide this value, then Amazon Web Services
     * generates a random one for you.

     */
    inline void SetClientToken(const char* value) { m_clientTokenHasBeenSet = true; m_clientToken.assign(value); }

    /**
     *
Specifies a unique, case-sensitive identifier that you provide to ensure the
     * idempotency of the request. This lets you safely retry the request without
     * accidentally performing the same operation a second time. Passing the same value
     * to a later call to an operation requires that you also pass the same value for
     * all other parameters. We recommend that you use a UUID type of
     * value..

If you don't provide this value, then Amazon Web Services
     * generates a random one for you.

     */
    inline RejectResourceShareInvitationRequest& WithClientToken(const Aws::String& value) { SetClientToken(value); return *this;}

    /**
     *
Specifies a unique, case-sensitive identifier that you provide to ensure the
     * idempotency of the request. This lets you safely retry the request without
     * accidentally performing the same operation a second time. Passing the same value
     * to a later call to an operation requires that you also pass the same value for
     * all other parameters. We recommend that you use a UUID type of
     * value..

If you don't provide this value, then Amazon Web Services
     * generates a random one for you.

     */
    inline RejectResourceShareInvitationRequest& WithClientToken(Aws::String&& value) { SetClientToken(std::move(value)); return *this;}

    /**
     *
Specifies a unique, case-sensitive identifier that you provide to ensure the
     * idempotency of the request. This lets you safely retry the request without
     * accidentally performing the same operation a second time. Passing the same value
     * to a later call to an operation requires that you also pass the same value for
     * all other parameters. We recommend that you use a UUID type of
     * value..

If you don't provide this value, then Amazon Web Services
     * generates a random one for you.

     */
    inline RejectResourceShareInvitationRequest& WithClientToken(const char* value) { SetClientToken(value); return *this;}

  private:

    Aws::String m_resourceShareInvitationArn;
    bool m_resourceShareInvitationArnHasBeenSet;

    Aws::String m_clientToken;
    bool m_clientTokenHasBeenSet;
  };

} // namespace Model
} // namespace RAM
} // namespace Aws


text:
namespace loggingapi {
namespace attributes {

Attribute::Attribute() {
    this->key_ = "";
    this->value_ = NULL;
}

Attribute::~Attribute() {
    delete this->value_;
}

std::string Attribute::getKey() const {
    return this->key_;
}

void Attribute::setKey(std::string k) {
    this->key_ = k;
}

AttributeValueInterface* Attribute::getValue() const {
    return this->value_;
}

void Attribute::setValue(AttributeValueInterface* v) {
    this->value_ = v;
}

bool Attribute::equals(const AttributeInterface& a) const {
    return (this->key_.compare(a.getKey()) == 0
            &&
            this->value_->compare(*(a.getValue())) ==
            AttributeValueInterface::COMPARE_RESULT_EQUAL);
}

}}  // namespaces


text:
ofFloatPixels sendPixels;

//--------------------------------------------------------------
void ofApp::setup(){
	ofSetFrameRate(60);
    // setup default servar @ port 9093
    server.setup(9093);

    // setup GPU particle stuff
    setupGPUParticles();
}

//--------------------------------------------------------------
void ofApp::update(){
    // update particles
    updateGPUParticles();

    // now, send position texture to clients
    posPingPong.src->readToPixels(sendPixels);
    server.sendBinary((char *)sendPixels.getPixels(), sendPixels.size() * sendPixels.getBytesPerChannel() );
}

//--------------------------------------------------------------
void ofApp::draw(){
    ofBackground(0);

    ofSetColor(100,255,255);
    renderFBO.draw(0,0);

    ofSetColor(255);
    ofDrawBitmapString("Fps: " + ofToString( ofGetFrameRate()), 15,15);
    ofDrawBitmapString("Connect a client to see same system sync!", 15, 30);
}

//--------------------------------------------------------------
void ofApp::setupGPUParticles(){
    particleSize = 30.0f;
    timeStep = 0.005f;
    numParticles = 1000;

    // Width and Heigth of the windows
    width = ofGetWindowWidth();
    height = ofGetWindowHeight();

    string shadersFolder;
    shadersFolder="shaders";

    // Loading the Shaders
    updatePos.load("",shadersFolder+"/posUpdate.frag");// shader for updating the texture that store the particles position on RG channels
    updateVel.load("",shadersFolder+"/velUpdate.frag");// shader for updating the texture that store the particles velocity on RG channels

    // Frag, Vert and Geo shaders for the rendering process of the spark image

#ifndef TARGET_WIN32
    updateRender.setGeometryInputType(GL_POINTS);
	updateRender.setGeometryOutputType(GL_TRIANGLE_STRIP);
	updateRender.setGeometryOutputCount(6);
    updateRender.load("shaders/render.vert","shaders/render.frag","shaders/render.geom");
#else
    updateRender.load("shaders/render.vert","shaders/render.frag");
#endif

    // Seting the textures where the information ( position and velocity ) will be
    textureRes = (int)sqrt((float)numParticles);
    numParticles = textureRes * textureRes;

    // 1. Making arrays of float pixels with position information
    float * pos = new float[numParticles*3];
    for (int x = 0; x < textureRes; x++){
        for (int y = 0; y < textureRes; y++){
            int i = textureRes * y + x;

            pos[i*3 + 0] = ofRandom(1.0); //x*offset;
            pos[i*3 + 1] = ofRandom(1.0); //y*offset;
            pos[i*3 + 2] = 0.0;
        }
    }
    // Load this information in to the FBO's texture
    posPingPong.allocate(textureRes, textureRes,GL_RGB32F);
    posPingPong.src->getTextureReference().loadData(pos, textureRes, textureRes, GL_RGB);
    posPingPong.dst->getTextureReference().loadData(pos, textureRes, textureRes, GL_RGB);
    delete [] pos;    // Delete the array

    // 2. Making arrays of float pixels with velocity information and the load it to a texture
    float * vel = new float[numParticles*3];
    for (int i = 0; i < numParticles; i++){
        vel[i*3 + 0] = ofRandom(-1.0,1.0);
        vel[i*3 + 1] = ofRandom(-1.0,1.0);
        vel[i*3 + 2] = 1.0;
    }
    // Load this information in to the FBO's texture
    velPingPong.allocate(textureRes, textureRes,GL_RGB32F);
    velPingPong.src->getTextureReference().loadData(vel, textureRes, textureRes, GL_RGB);
    velPingPong.dst->getTextureReference().loadData(vel, textureRes, textureRes, GL_RGB);
    delete [] vel; // Delete the array

    // Loading and setings of the variables of the textures of the particles
    sparkImg.loadImage("spark.png");
    imgWidth = sparkImg.getWidth();
    imgHeight = sparkImg.getHeight();

    // Allocate the final
    renderFBO.allocate(width, height, GL_RGB32F);
    renderFBO.begin();
    ofClear(0, 0, 0, 255);
    renderFBO.end();

    mesh.setMode(OF_PRIMITIVE_POINTS);
    for(int x = 0; x < textureRes; x++){
        for(int y = 0; y < textureRes; y++){
            mesh.addVertex(ofVec3f(x,y));
            mesh.addTexCoord(ofVec2f(x, y));
        }
    }
}

//--------------------------------------------------------------
void ofApp::updateGPUParticles(){
    // In each cycle it's going to update the velocity first and the the position
    // Each one one with a different shader and FBO.
    // Because on GPU you can't write over the texture that you are reading we are
    // using to pair of ofFbo attached together on what we call pingPongBuffer
    // Learn more about Ping-Pong at:
    //
    // http://www.comp.nus.edu/~ashwinna/docs/PingPong_FBO.pdf
    // http://www.seas.upenn.edu/~cis565/fbo.htm#setupgl4

    // Velocities PingPong
    //
    // It calculates the next frame and see if it's there any collition
    // then updates the velocity with that information
    //
    velPingPong.dst->begin();
    ofClear(0);
    updateVel.begin();
    updateVel.setUniformTexture("backbuffer", velPingPong.src->getTextureReference(), 0);   // passing the previus velocity information
    updateVel.setUniformTexture("posData", posPingPong.src->getTextureReference(), 1);  // passing the position information
    updateVel.setUniform1i("resolution", (int)textureRes);
    updateVel.setUniform2f("screen", (float)width, (float)height);
    updateVel.setUniform1f("timestep", (float)timeStep);

    // draw the source velocity texture to be updated
    velPingPong.src->draw(0, 0);

    updateVel.end();
    velPingPong.dst->end();

    velPingPong.swap();

    // Positions PingPong
    //
    // With the velocity calculated updates the position
    //
    posPingPong.dst->begin();
    ofClear(0);
    updatePos.begin();
    updatePos.setUniformTexture("prevPosData", posPingPong.src->getTextureReference(), 0); // Previus position
    updatePos.setUniformTexture("velData", velPingPong.src->getTextureReference(), 1);  // Velocity
    updatePos.setUniform1f("timestep",(float) timeStep );

    // draw the source position texture to be updated
    posPingPong.src->draw(0, 0);

    updatePos.end();
    posPingPong.dst->end();

    posPingPong.swap();

    // Rendering
    //
    // 1.   Sending this vertex to the Vertex Shader.
    //      Each one it's draw exactly on the position that match where it's stored on both vel and pos textures
    //      So on the Vertex Shader (that's is first at the pipeline) can search for it information and move it
    //      to it right position.
    // 2.   Once it's in the right place the Geometry Shader make 6 more vertex in order to make a billboard
    // 3.   that then on the Fragment Shader it's going to be filled with the pixels of sparkImg texture
    //
    renderFBO.begin();
    ofClear(0,0,0,0);
    updateRender.begin();
    updateRender.setUniformTexture("posTex", posPingPong.dst->getTextureReference(), 0);
    updateRender.setUniformTexture("sparkTex", sparkImg.getTextureReference() , 1);
    updateRender.setUniform1i("resolution", (float)textureRes);
    updateRender.setUniform2f("screen", (float)width, (float)height);
    updateRender.setUniform1f("size", (float)particleSize);
    updateRender.setUniform1f("imgWidth", (float)sparkImg.getWidth());
    updateRender.setUniform1f("imgHeight", (float)sparkImg.getHeight());

    ofPushStyle();
    ofEnableBlendMode( OF_BLENDMODE_ADD );
    ofSetColor(255);

    mesh.draw();

    ofDisableBlendMode();
    glEnd();

    updateRender.end();
    renderFBO.end();
    ofPopStyle();
}

//--------------------------------------------------------------
void ofApp::keyPressed(int key){

}

//--------------------------------------------------------------
void ofApp::keyReleased(int key){

}

//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){

}

//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){

}

//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){

}


text:
@if ($message = Session::get('status') or $message = $errors->first())

        @if ($closable)
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
        @endif

{{ $message }}

@endif


text:
package org.minimallycorrect.tickprofiler.minecraft.commands;

public class UsageException extends RuntimeException {
	public UsageException(String message) {
		super(message);
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Class StringExtensions
   </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Class StringExtensions
   ">
    <meta name="generator" content="docfx 2.18.2.0">

    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                Toggle navigation

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

          Show / Hide Table of Contents

Class StringExtensions

Inheritance

System.Object

StringExtensions

Inherited Members

      System.Object.ToString()

      System.Object.Equals(System.Object)

      System.Object.Equals(System.Object, System.Object)

      System.Object.ReferenceEquals(System.Object, System.Object)

      System.Object.GetHashCode()

      System.Object.GetType()

      System.Object.MemberwiseClone()

Namespace: CommonBotLibrary.Extensions

Assembly: cs.temp.dll.dll

Syntax

public static class StringExtensions

Methods

NoPunctuation(String)

Declaration

public static string NoPunctuation(this string s)

Parameters

        Type
        Name
        Description

        System.String
        s

Returns

        Type
        Description

        System.String

              Back to top

            &copy 2017 - Borja Canseco


text:
<?php

if(!defined("IN_LIVEZILLA"))
	die();

function abortTracking($_code)
{
	global $EXTERNALUSER;
	exit("lz_tracking_stop_tracking(".$_code.");");
}

function triggerEvents($chatRequest=false,$alert=false,$websitePush=false)
{
	global $BROWSER,$CONFIG,$EVENTS,$INTERNAL,$EXTERNALUSER,$STATS,$GROUPS;

	if(count($EVENTS)==0)
		return;

	$actionData = "";
	$url = $BROWSER->History[count($BROWSER->History)-1];
	$previous = (count($BROWSER->History) > 1) ? $BROWSER->History[count($BROWSER->History)-2]->Url->GetAbsoluteUrl() : "";
	$EXTERNALUSER->GetChatRequestResponses();

	foreach($EVENTS->Events as $event)
	{
		$match = false;
		if(!$event->IsActive || empty($url))
			continue;

		$urlor = (count($event->FunnelUrls) == 0 && $event->MatchesURLCriterias($url->Url->GetAbsoluteUrl(),$url->Referrer->GetAbsoluteUrl(),$previous,time()-($url->Entrance)));
		$urlfunnel = (count($event->FunnelUrls) > 0 && $event->MatchesURLFunnelCriterias($BROWSER->History));
		$global = $event->MatchesGlobalCriterias(count($BROWSER->History),($EXTERNALUSER->ExitTime-$EXTERNALUSER->FirstActive),$EXTERNALUSER->HasAcceptedChatRequest,$EXTERNALUSER->HasDeclinedChatRequest,($EXTERNALUSER->IsInChat() || $EXTERNALUSER->WasInChat()),$BROWSER->Query);

		if($global && ($urlfunnel || $urlor))
		{
			foreach(array($event->Goals,$event->Actions) as $elements)
				foreach($elements as $action)
				{
					$EventTrigger = new EventTrigger(CALLER_USER_ID,CALLER_BROWSER_ID,$action->Id,time(),1);
					$EventTrigger->Load();
					$aexists = $action->Exists(CALLER_USER_ID,CALLER_BROWSER_ID);
					if(!$EventTrigger->Exists || ($EventTrigger->Exists && $event->MatchesTriggerCriterias($EventTrigger)))
					{
						if(!$aexists)
						{
							$EventTrigger->Save($event->Id);
							if($action->Type < 2)
							{
								foreach($action->GetInternalReceivers() as $user_id)
								{
									$intaction = new EventActionInternal($user_id, $EventTrigger->Id);
									$intaction->Save();
								}
							}
							else if($action->Type == 2 && !defined("EVENT_INVITATION"))
							{
								$sender = getActionSender($action->Invitation->Senders,true);
								initData(false,true);
								if(!empty($sender) && $GROUPS[$sender->GroupId]->IsOpeningHour())
								{
									define("EVENT_INVITATION",true);
									$chatrequest = new ChatRequest($sender->UserSystemId,$sender->GroupId,CALLER_USER_ID,CALLER_BROWSER_ID,getActionText($sender,$action));
									$chatrequest->EventActionId = $action->Id;
									$chatrequest->Save();
									$BROWSER->LoadChatRequest();
									$chatRequest = true;
								}
							}
							else if($action->Type == 3 && !defined("EVENT_ALERT"))
							{
								define("EVENT_ALERT",true);
								$alert = new Alert(CALLER_USER_ID,CALLER_BROWSER_ID,$action->Value);
								$alert->EventActionId = $action->Id;
								$alert->Save();
								$BROWSER->LoadAlerts();
							}
							else if($action->Type == 4 && !defined("EVENT_WEBSITE_PUSH"))
							{
								define("EVENT_WEBSITE_PUSH",true);
								$sender = getActionSender($action->WebsitePush->Senders,false);
								$websitepush = new WebsitePush($sender->UserSystemId,$sender->GroupId,CALLER_USER_ID,CALLER_BROWSER_ID,getActionText($sender,$action),$action->WebsitePush->Ask,$action->WebsitePush->TargetURL);
								$websitepush->EventActionId = $action->Id;
								$websitepush->Save();
								$BROWSER->LoadWebsitePush();
							}
							else if($action->Type == 5 && STATS_ACTIVE)
							{
								$STATS->ProcessAction(ST_ACTION_GOAL,array(CALLER_USER_ID,$action->Id,($EXTERNALUSER->Visits==1)?1:0));
							}
						}
					}
					if($EventTrigger->Exists && $aexists)
						$EventTrigger->Update();
				}
		}
	}
	return $actionData;
}

function getActionSender($_senders,$_checkOnline,$hpriority=0)
{
	global $CONFIG,$INTERNAL;
	initData(true);
	foreach($_senders as $sender)
		if(isset($INTERNAL[$sender->UserSystemId]) && (!$_checkOnline || (($INTERNAL[$sender->UserSystemId]->LastActive > (time()-$CONFIG["timeout_clients"])) && $INTERNAL[$sender->UserSystemId]->Status == USER_STATUS_ONLINE)))
			if($hpriority <= $sender->Priority)
			{
				$hpriority = $sender->Priority;
				$asenders[] = $sender;
			}
			else
				break;
	if(!isset($asenders))
		return null;
	else
		return $asenders[array_rand($asenders,1)];
}

function getActionText($_sender,$_action)
{
	global $EXTERNALUSER,$INTERNAL;
	if(!empty($_action->Value))
		return $_action->Value;

	$sel_message = null;
	$group = new UserGroup($_sender->GroupId);
	foreach(array_merge($INTERNAL[$_sender->UserSystemId]->PredefinedMessages,$group->PredefinedMessages) as $message)
	{
		if(($message->IsDefault && (!$message->BrowserIdentification || empty($EXTERNALUSER->Language))) || ($message->BrowserIdentification && $EXTERNALUSER->Language == $message->LangISO))
		{
			$sel_message = $message;
			break;
		}
		else if($message->IsDefault && empty($_action->Value))
		{
			$sel_message = $message;
		}
	}

	if($_action->Type == 2 && $sel_message != null)
		$_action->Value = $sel_message->InvitationAuto;
	else if($_action->Type == 4)
	{
		$_action->Value = $sel_message->WebsitePushAuto;
		$_action->Value = str_replace("%url%",$_action->WebsitePush->TargetURL,$_action->Value);
	}

	$_action->Value = str_replace("%name%",$INTERNAL[$_sender->UserSystemId]->Fullname,$_action->Value);
	$_action->Value = str_replace("%email%",$INTERNAL[$_sender->UserSystemId]->Email,$_action->Value);
	$_action->Value = str_replace("%external_ip%",$_SERVER["REMOTE_ADDR"],$_action->Value);
	return $_action->Value;
}

function processActions($actionData = "")
{
	global $BROWSER,$CONFIG,$INTERNAL,$EVENTS,$GROUPS;
	if(!empty($BROWSER->ChatRequest))
	{
		initData(true,true);
		if(($INTERNAL[$BROWSER->ChatRequest->SenderSystemId]->LastActive < (time()-$CONFIG["timeout_clients"])) || $INTERNAL[$BROWSER->ChatRequest->SenderSystemId]->Status != USER_STATUS_ONLINE || !$GROUPS[$BROWSER->ChatRequest->SenderGroupId]->IsOpeningHour() || $BROWSER->ChatRequest->Closed)
		{
			$BROWSER->ChatRequest->SetStatus(false,false,true,true);
			$actionData .= "lz_tracking_close_request();";
			$BROWSER->ForceUpdate();
		}
		else if(isset($_GET[GET_TRACK_REQUEST_DECLINED]) || isset($_GET[GET_TRACK_REQUEST_ACCEPTED]))
		{
			if(isset($_GET[GET_TRACK_REQUEST_DECLINED]))
				$BROWSER->ChatRequest->SetStatus(false,false,true,true);

			if(isset($_GET[GET_TRACK_REQUEST_CLOSE]))
			{
				if(isset($_GET[GET_TRACK_REQUEST_ACCEPTED]))
					$BROWSER->ChatRequest->SetStatus(false,true,false,true);
				$actionData .= "lz_tracking_close_request();";
			}
			$BROWSER->ForceUpdate();
		}
		else if(!$BROWSER->ChatRequest->Accepted && !$BROWSER->ChatRequest->Declined)
		{
			if(empty($BROWSER->ChatRequest->EventActionId))
			{
				$invitationHTML = doReplacements($BROWSER->ChatRequest->CreateInvitationTemplate($CONFIG["gl_inv_template"],$CONFIG["gl_site_name"],$CONFIG["wcl_window_width"],$CONFIG["wcl_window_height"],LIVEZILLA_URL,$INTERNAL[$BROWSER->ChatRequest->SenderSystemId],$CONFIG["gl_inv_coc"]));
				$BROWSER->ChatRequest->Invitation = new Invitation($invitationHTML,$CONFIG["gl_inv_position"],$CONFIG["gl_inv_margin"][0],$CONFIG["gl_inv_margin"][1],$CONFIG["gl_inv_margin"][2],$CONFIG["gl_inv_margin"][3],$CONFIG["gl_inv_scroll_speed"],$CONFIG["gl_inv_template"],empty($CONFIG["gl_inv_no_scroll"]),$BROWSER->ChatRequest->Text,$CONFIG["gl_inv_coc"]);
			}
			else if(!isnull($action = $EVENTS->GetActionById($BROWSER->ChatRequest->EventActionId)))
			{
				$invitationHTML = doReplacements($BROWSER->ChatRequest->CreateInvitationTemplate($action->Invitation->Style,$CONFIG["gl_site_name"],$CONFIG["wcl_window_width"],$CONFIG["wcl_window_height"],LIVEZILLA_URL,$INTERNAL[$BROWSER->ChatRequest->SenderSystemId],$action->Invitation->CloseOnClick));
				$BROWSER->ChatRequest->Invitation = $action->Invitation;
				$BROWSER->ChatRequest->Invitation->Text = $BROWSER->ChatRequest->Text;
				$BROWSER->ChatRequest->Invitation->HTML = $invitationHTML;
			}
			$BROWSER->ChatRequest->SetStatus(true,false,false,false);
			$actionData .= $BROWSER->ChatRequest->Invitation->GetCommand();
			$BROWSER->ForceUpdate();
		}
	}
	if(!empty($BROWSER->WebsitePush))
	{
		if(isset($_GET[GET_TRACK_WEBSITE_PUSH_DECLINED]))
		{
			$BROWSER->WebsitePush->SetStatus(false,false,true);
		}
		else if(isset($_GET[GET_TRACK_WEBSITE_PUSH_ACCEPTED]) || (!$BROWSER->WebsitePush->Ask && !$BROWSER->WebsitePush->Displayed))
		{
			$BROWSER->WebsitePush->SetStatus(false,true,false);
			$actionData .= $BROWSER->WebsitePush->GetExecCommand();
		}
		else if($BROWSER->WebsitePush->Ask && !$BROWSER->WebsitePush->Accepted && !$BROWSER->WebsitePush->Declined)
		{
			$BROWSER->WebsitePush->SetStatus(true,false,false);
			$actionData .= $BROWSER->WebsitePush->GetInitCommand();
		}
	}
	if(!empty($BROWSER->Alert) && !$BROWSER->Alert->Accepted)
	{
		if(isset($_GET[GET_TRACK_ALERT_CONFIRMED]))
			$BROWSER->Alert->SetStatus(false,true);
		else
			$actionData .= $BROWSER->Alert->GetCommand();
	}
	return $actionData;
}

function getPollFrequency()
{
	global $CONFIG,$INTERNAL;
	if(!empty($CONFIG["gl_stmo"]))
		return $CONFIG["poll_frequency_tracking"];
	$row = mysql_fetch_array(queryDB(true,"SELECT COUNT(*) AS `ocount` FROM `".DB_PREFIX.DATABASE_OPERATORS ."` WHERE `last_active` > ".(time()-$CONFIG["timeout_clients"])), MYSQL_BOTH);
	if($row["ocount"] > 0)
		return $CONFIG["poll_frequency_tracking"];
	return $CONFIG["timeout_track"]-10;
}
?>


text:
title: Data - Python and ArchivesSnake for Archivists
revealOptions:
    transition: 'fade'
---

## Python and ArchivesSnake for Archivists

### Part 3: Data

---

### Getting a Resource (Collection)

* Login to an ArchivesSpace Instance
    * use port :8080
* Pick a resource (collection)
* Notice the URI

![Screenshot showing where URIs are found in the ArchivesSpace Staff interface.](https://raw.githubusercontent.com/gwiedeman/IntroPythonASnake/master/img/finduri.png)

---

### Getting a Resource (Collection)

* Use repo.resources(number) to get a resource

```python
from asnake.aspace import ASpace

aspace = ASpace()
repo = aspace.repositories(2)

collection = repo.resources(129)
print (collection)
```

---

### Lists

* `myList = ["thing1", "thing2", "thing3"]`
* Can be variables or any data type
* Lists have indexes: `myList[1]`
* Lists have lengths: `len(myList)`

---

### Lists

```python
from asnake.aspace import ASpace

aspace = ASpace()
repo = aspace.repositories(2)

#collection = repo.resources(129)
#print (collection)

thing2 = 25
myList = ["thing1", thing2, "thing3"]

print (type(myList))
print (len(myList))
print (myList[1])
```

---

### Lists

* Add to end of list: `myList.append("a thing")`
* Add by index: `myList.insert(1, "a thing")`
* Remove item with `myList.remove("a thing")`
* Test with: `25 in myList`

---

### Lists

```python
from asnake.aspace import ASpace

aspace = ASpace()
repo = aspace.repositories(2)

#collection = repo.resources(129)
#print (collection)

thing2 = 25
myList = ["thing1", thing2, "thing3"]

myList.append(thing2)

print (len(myList))

myList.remove(25)

print (myList)

myList.insert(0, "begin")
print (myList)

print (25 in myList)
```

---

### Dictionaries

* Key: Value sets
* `data = {"field": "a value", "Question": "Answer"}`
* Call with key
* `data["field"]`
* Changing or adding is the same

---

### Dictionaries

```python
from asnake.aspace import ASpace

aspace = ASpace()
repo = aspace.repositories(2)

#collection = repo.resources(129)
#print (collection)

data = {"field": "a value", "Question": "Answer"}

print (type(data))
print (data["Question"])
data["decription"] = "here's some info"
data["field"] = 336

print (data)
```

---

### Complex Data

* Dictionaries can hold lists and lists can hold dictionaries

```python
from asnake.aspace import ASpace

aspace = ASpace()
repo = aspace.repositories(2)

#collection = repo.resources(129)
#print (collection)

data = {"field": "a value",
    "Question": "Answer",
    "myList":  ["thing1", "thing2", "thing3"]
}

print (data["myList"][1])

```
---

### Using Objects

* ArchivesSnake uses objects
* Use dot syntax: `collection.title`
* `dir(collection)` lists attributes
* `type(collection.title)` shows data type
* `collection.json()` to turns object into a dictionary

---

### ArchivesSnake Objects

```python
from asnake.aspace import ASpace

aspace = ASpace()
repo = aspace.repositories(2)

collection = repo.resources(129)
print (collection.title)
print (dir(collection))
```

---

### ArchivesSnake Objects

```python
from asnake.aspace import ASpace

aspace = ASpace()
repo = aspace.repositories(2)

collection = repo.resources(129)
print (collection.title)
print (type(collection.id_0))
print (type(collection.extents))
```

---

### ArchivesSnake Objects

```python
from asnake.aspace import ASpace

aspace = ASpace()
repo = aspace.repositories(2)

collection = repo.resources(129)
print (collection.title)
print (collection.id_0)
print (collection.extents[0].number)
```

---

### Date Exercise

* Format collection date as EAD-style normal date
* Print it as a variable
    * 1933/1998
    * 1975-08-22/1988-12-30
* Cheatsheets:
    * [syntax](https://github.com/gwiedeman/IntroPythonASnake/blob/master/syntax.md)
    * [data](https://github.com/gwiedeman/IntroPythonASnake/blob/master/data.md)

---

### Date Exercise

* Format collection date as EAD-style normal date
* Print it as a variable
    * 1933/1998
    * 1975-08-22/1988-12-30
* `dir(object)`
* `type(object.attribute)`
* `string = string1 + "/" + string2`

---

### Iterating with Loops

* Repeats for every item in a list
* runs indented code
* code without inded runs on completion

```python
for newVar in myList:
    print (newVar)
print ("Loop Finished")
```

---

### Loop though a String

```python
from asnake.aspace import ASpace

aspace = ASpace()
repo = aspace.repositories(2)

collection = repo.resources(129)
title = collection.title

for letter in title:
    print (letter)

print ("finished!!")
```

---

### ArchivesSnake lets you loop though resources

```python
from asnake.aspace import ASpace

aspace = ASpace()
repo = aspace.repositories(2)

for collection in repo.resources:
    print (collection.title)
```

---

### For each resource

```python
from asnake.aspace import ASpace

aspace = ASpace()
repo = aspace.repositories(2)

for collection in repo.resources:
    line = collection.id_0 + ": " + collection.title
    print (line)
```

---

### Using an iterator

```python
from asnake.aspace import ASpace

aspace = ASpace()
repo = aspace.repositories(2)

count = 0
for collection in repo.resources:
    count = count + 1
    print (count)

print (str(count) + " total collections!")
```

* `count += 1` is the same as `count = count + 1`

---

### If else conditionals

```python
if "a" in myString:
    print ("yes")
else:
    print ("nope")
```

---

### If else conditionals

```python
if "a" in myString:
    print ("yes")
elif myString == "this string":
    print ("matches exactly")
elif myString.startswith("a"):
    print ("starts with a")
else:
    print ("nope")
```

---

### Collections with "The"

Which collections start with "The"?

```python
from asnake.aspace import ASpace

aspace = ASpace()
repo = aspace.repositories(2)

count = 0
for collection in repo.resources:
    count += 1
    if collection.title.lower().strip().startswith("the"):
        print (collection.title)

print (str(count) + " total collections!")
```

---

### Counting collection types

```python
from asnake.aspace import ASpace

aspace = ASpace()
repo = aspace.repositories(2)

papers = 0
records = 0
collectionCount = 0
for collection in repo.resources:
    if "papers" in collection.title.lower():
        papers += 1
    elif "records" in collection.title.lower():
        records += 1
    elif "collection" in collection.title.lower():
        collectionCount += 1
    else:
        print (collection.title)

print (str(papers) + " papers")
print (str(records) + " records")
print (str(collectionCount) + " collections")
```

---

### Collections Since 1980

```python
from asnake.aspace import ASpace

aspace = ASpace()
repo = aspace.repositories(2)

newer = False
for collection in repo.resources:
    for date in collection.dates:
        endDate = date.end
        print (endDate)
```

---

### Collections Since 1980

```python
from asnake.aspace import ASpace

aspace = ASpace()
repo = aspace.repositories(2)

newer = False
for collection in repo.resources:
    for date in collection.dates:
        endDate = date.end
        year = endDate.split("-")[0]
        if int(year) < 1950:
            print (collection.title)
```

---

### ArchivesSpace Trees

* Child archival objects
* Not full archival objects

```python
from asnake.aspace import ASpace

aspace = ASpace()
repo = aspace.repositories(2)

collection = repo.resources(35)
print (collection.tree.reify())
```

---

### ArchivesSpace Trees

```python
from asnake.aspace import ASpace

aspace = ASpace()
repo = aspace.repositories(2)

collection = repo.resources(35)
for child in collection.tree.children:
    print (child.title)
```

---

### Archival Objects from Trees

```python
from asnake.aspace import ASpace

aspace = ASpace()
repo = aspace.repositories(2)

collection = repo.resources(35)
for child in collection.tree.children:
    series = child.record
    print (series)
```

---

### Count the Extents

Do the extents add up?

```python
from asnake.aspace import ASpace

aspace = ASpace()
repo = aspace.repositories(2)

collection = repo.resources(35)
for extent in collection.extents:
    print (extent.number + " " + extent.extent_type)

total = 0
for child in collection.tree.children:
    series = child.record
    print (series.title)
    for seriesExtent in series.extents:
        print ("\t" + seriesExtent.number + " " + seriesExtent.extent_type)
        total = total + float(seriesExtent.number)

print (total)
```

---

## Python and ArchivesSnake for Archivists

[Part 4: Challenges](challenges.html)


text:
using NDomain.Bus.Transport;
using NDomain.CQRS;
using NDomain.EventSourcing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NDomain.Bus
{
    /// <summary>
    /// Represents a message bus abstraction that can be used to send one or multiple messages.
    /// </summary>
    public interface IMessageBus
    {
        Task Send(Message message);
        Task Send(IEnumerable<Message> messages);
    }

    public static class MessageBusExtensions
    {
        /// <summary>
        /// Converts any message into a <see cref="NDomain.Bus.Message"/> type and sends it.
        /// </summary>
        /// <typeparam name="TMessage">Type of the message to send</typeparam>
        /// <param name="bus">the bus instance used to send the message</param>
        /// <param name="message">payload to send</param>
        /// <param name="headers">optional headers to be sent</param>
        /// <returns>Task</returns>
        public static Task Send<TMessage>(this IMessageBus bus, TMessage message, Dictionary<string, string> headers = null)
        {
            var msg = new Message(message, typeof(TMessage).Name, headers);
            return bus.Send(msg);
        }
    }
}


text:
package com.microsoftopentechnologies.tooling.msservices.helpers;

import org.apache.xerces.dom.DeferredElementImpl;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

public class XmlHelper {

    public static Object getXMLValue(String xml, String xQuery, QName resultType) throws XPathExpressionException, IOException, SAXException, ParserConfigurationException {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();

        Document doc = db.parse(new InputSource(new StringReader(xml)));

        XPathFactory xPathfactory = XPathFactory.newInstance();

        XPath xPath = xPathfactory.newXPath();
        XPathExpression xPathExpression = xPath.compile(xQuery);
        return xPathExpression.evaluate(doc, resultType);
    }

    public static String getAttributeValue(Node node, String attributeName) {
        Node n = node.getAttributes().getNamedItem(attributeName);
        return (n == null) ? null : n.getNodeValue();
    }

    public static String getChildNodeValue(Node node, String elementName) {
        return ((DeferredElementImpl) node).getElementsByTagName(elementName).item(0).getTextContent();
    }

    public static String saveXmlToStreamWriter(Document doc) throws TransformerException {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(doc), new StreamResult(writer));

        return writer.getBuffer().toString();
    }
}


text:
namespace justify {

class LineAccumulator {
	public:
		LineAccumulator(
			const std::uint8_t  max_length,
			const std::uint8_t  offset,
			const std::uint32_t seed
		);
		~LineAccumulator();

		void operator()(const std::string& token);

	private:
		const std::uint8_t max_length_;
		const std::uint8_t offset_;

		std::mt19937 generator_;
		std::uint8_t length_;

		std::vector<
			std::pair<std::string, std::uint8_t>
		> tokens_;

		std::uint8_t getMissing() const;

		void justify();
		void discharge(const bool full);

};

}


text:
"""Retrieve data for battery sizing investigations.
18AUG2021
$ python3 battery.py -d 360 -m 5.4 -s 5
Passed options: Namespace(days=360, hours=None, maxbat=5.4, soc=5.0)
Parsed options: Namespace(days=360, hours=8640, maxbat=5400.0, soc=5000.0)

Max. Battery SoC : 5400 Wh 	 cumul : 19121 kWh
Max. Surplus     : 2662 Wh 	 cumul : 1381 kWh
Max. Shortage    : 5397 Wh 	 cumul : 1308 kWh

"""

import argparse
import os
import sqlite3
import warnings

import numpy as np
import pandas as pd

import constants

warnings.filterwarnings('ignore')

# runlist id for daemon :
MYID = 'DEFAULT'
# app_name :
HERE = os.path.realpath(__file__).split('/')
MYAPP = HERE[-3]
MYROOT = "/".join(HERE[0:-3])
NODE = os.uname()[1]
ROOM_ID = NODE[-2:]

# DATABASE = f"{MYROOT}/{constants.BATTERY['database']}"
DATABASE = constants.BATTERY['database']
print(DATABASE)

def fetch_data(hours_to_fetch):
    """

    Args:
        hours_to_fetch (int): number of hours of data to query from the DB

    Returns:
        (pandas.DataFrame): data queried

    """
    global DATABASE
    global OPTION
    where_condition = f" (sample_time >= datetime(\'now\', \'-{hours_to_fetch + 1} hours\'))"
    sql_query = f"SELECT sample_time, strftime('%s', sample_time) as hr, MIN(sample_time) as st, " \
                f"       T1in, T1out, T2in, T2out " \
                f"FROM kamstrup " \
                f"WHERE {where_condition} " \
                f"GROUP BY strftime('%Y%m%d%H', sample_time) "
    with sqlite3.connect(DATABASE) as con:
        df = pd.read_sql_query(sql_query,
                               con,
                               parse_dates='sample_time',
                               index_col='sample_time'
                               )
    # sort by datetime
    df = df.sort_index('index')
    # drop the column used for filtering
    df = df.drop(columns=['st'])
    dum = df.astype({'hr': 'int32'}) / 3600
    # convert the epoch seconds from str to int32 and into hours
    df['hr'] = dum['hr']
    # calculate the hourly values
    df = df.diff()
    # aggregate imports and exports
    df['in'] = (df['T1in'] + df['T2in']) / df['hr']
    df['out'] = (df['T1out'] + df['T2out']) / df['hr']
    # determine the hourly delta; surplus(+) or shortage(-)
    df['delta'] = df['in'] - df['out']
    # reset the index to be able to navigate through the rows
    df.reset_index(inplace=True)
    return df

def assess_battery(df):
    """

    Args:
        df (pandas.DataFrame): raw data from database

    Returns:
        (pandas.DataFrame): battery balance data added

    """
    global OPTION
    # set-up the battery with a pre-charge
    df['battery'] = OPTION.soc
    # start off the surplus at zero
    df['surplus'] = 0
    # start off the shortage at zero
    df['shortge'] = 0
    for i in range(1, len(df)):
        # determine battery SoC at the top of the hour
        bat_state = df.loc[i - 1, 'battery']
        # add the hour's surplus to the battery
        surplus = df.loc[i, 'out']
        bat_state += surplus
        surplus = 0
        # skim off the surplus that doesn't fit in the battery if it tops out
        if bat_state > OPTION.maxbat:
            surplus = bat_state - OPTION.maxbat
            bat_state = OPTION.maxbat
        # remove the hour's shortage from the battery
        shortge = df.loc[i, 'in']
        bat_state -= shortge
        shortge = 0
        # determine the energy to import if the battery is drained
        if bat_state < 0:
            shortge = 0 - bat_state
            bat_state = 0
        # store the balance
        df.loc[i, 'battery'] = bat_state
        df.loc[i, 'surplus'] = surplus
        df.loc[i, 'shortge'] = shortge

    df.reset_index(drop=True, inplace=True)
    return df

def assess_rev_battery(df):
    """

    Args:
        df (pandas.DataFrame): raw data from database

    Returns:
        (pandas.DataFrame): battery balance data added

    """
    global OPTION
    # set-up the battery with a pre-charge
    df['battery'] = OPTION.soc
    # start off the surplus at zero
    df['surplus'] = 0
    # start off the shortage at zero
    df['shortge'] = 0
    for i in range(1, len(df)):
        # determine battery SoC at the top of the hour
        bat_state = df.loc[i - 1, 'battery']

        # remove the hour's shortage from the battery
        shortge = df.loc[i, 'in']
        bat_state -= shortge
        shortge = 0
        # add the hour's surplus to the battery
        surplus = df.loc[i, 'out']
        bat_state += surplus
        surplus = 0
        # determine the energy to import if the battery is drained
        if bat_state < 0:
            shortge = 0 - bat_state
            bat_state = 0
        # skim off the surplus that doesn't fit in the battery if it tops out
        if bat_state > OPTION.maxbat:
            surplus = bat_state - OPTION.maxbat
            bat_state = OPTION.maxbat

        # store the balance
        df.loc[i, 'battery'] = bat_state
        df.loc[i, 'surplus'] = surplus
        df.loc[i, 'shortge'] = shortge

    df.reset_index(drop=True, inplace=True)
    return df

def main():
    """
      This is the main loop
      """
    global MYAPP
    global OPTION

    bat_data = fetch_data(OPTION.hours)
    data = assess_battery(bat_data)
    # pd.set_option("display.max_rows", None, "display.max_columns", None)
    # print(data)
    print(f"Max. Battery SoC : {np.max(data['battery']):.0f} Wh \t cumul : {np.sum(data['battery']) / 1000:.0f} kWh")
    print(f"Max. Surplus     : {np.max(data['surplus']):.0f} Wh \t cumul : {np.sum(data['surplus']) / 1000:.0f} kWh")
    print(f"Max. Shortage    : {np.max(data['shortge']):.0f} Wh \t cumul : {np.sum(data['shortge']) / 1000:.0f} kWh")

    # this doesn't return significant differences.
    # data = assess_rev_battery(bat_data)
    # pd.set_option("display.max_rows", None, "display.max_columns", None)
    # print("")
    # print(f"Max. Battery SoC : {np.max(data['battery']):.0f} Wh \t cumul : {np.sum(data['battery']) / 1000:.0f} kWh")
    # print(f"Max. Surplus     : {np.max(data['surplus']):.0f} Wh \t cumul : {np.sum(data['surplus']) / 1000:.0f} kWh")
    # print(f"Max. Shortage    : {np.max(data['shortge']):.0f} Wh \t cumul : {np.sum(data['shortge']) / 1000:.0f} kWh")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Fetch data")
    parser.add_argument('-hr',
                        '--hours',
                        type=int,
                        help='fetch hourly-data for <HOURS> hours '
                        )
    parser.add_argument('-d',
                        '--days',
                        type=int,
                        help='fetch hourly-data for <DAYS> days'
                        )
    parser.add_argument('-m',
                        '--maxbat',
                        default=5.0,
                        type=float,
                        help='maximum battery capacity [kWh]'
                        )
    parser.add_argument('-s',
                        '--soc',
                        type=float,
                        help='battery SoC [kWh]'
                        )
    OPTION = parser.parse_args()
    print(f"Passed options: {OPTION}")
    if not OPTION.hours or OPTION.hours == 0:
        OPTION.hours = 50
    if OPTION.days and OPTION.days > 0:
        OPTION.hours = OPTION.days * 24
    if OPTION.soc is None:
        OPTION.soc = OPTION.maxbat
    # scale to Wh
    OPTION.soc *= 1000
    OPTION.maxbat *= 1000

    print(f"Parsed options: {OPTION}")
    print("")
    main()


text:
<?php

/**
 * This file is part of the Spryker Demoshop.
 * For full license information, please view the LICENSE file that was distributed with this source code.
 */

namespace Pyz\Zed\ProductSale\Business;

interface ProductSaleFacadeInterface
{
    /**
     * @return \Generated\Shared\Transfer\ProductLabelProductAbstractRelationsTransfer[]
     */
    public function findProductLabelProductAbstractRelationChanges();
}


text:
\section{Message\+Buffer Class Reference}
\label{classMessageBuffer}\index{Message\+Buffer@{Message\+Buffer}}
Inheritance diagram for Message\+Buffer\+:\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[height=3.000000cm]{classMessageBuffer}
\end{center}
\end{figure}
\subsection*{Public Member Functions}
\begin{DoxyCompactItemize}
\item
{\bf Message\+Buffer} (unsigned short buffer\+Size=M\+A\+X\+\_\+\+M\+E\+S\+S\+A\+G\+E\+\_\+\+L\+E\+N\+G\+TH, bool perform\+Network\+Conversion=true)
\item
{\bf Message\+Buffer} (unsigned char $\ast$buffer\+Ptr, unsigned short buffer\+Size, bool perform\+Network\+Conversion=true)
\item
virtual {\bf $\sim$\+Message\+Buffer} ()
\item
void {\bf clean} ()
\item
unsigned char $\ast$ {\bf get\+Buffer} ()
\item
unsigned int {\bf get\+Buffer\+Length} ()
\item
unsigned int {\bf get\+Max\+Buffer\+Length} ()
\item
void {\bf set\+Insert\+Position} (unsigned short n\+Bytes)
\item
void {\bf set\+Network\+Conversion} (bool perform\+Network\+Conversion)
\item
void {\bf clear\+Buffer} ()
\item
void {\bf assign\+Buffer} (unsigned char $\ast$buffer\+Ptr, unsigned short buffer\+Size)
\item
void {\bf assign\+Empty\+Buffer} (unsigned char $\ast$buffer\+Ptr, unsigned short max\+Buffer\+Size)
\item
{\bf Message\+Buffer} \& {\bf operator$<$$<$} (int int\+Value)
\item
{\bf Message\+Buffer} \& {\bfseries operator$<$$<$} (unsigned char char\+Value)\label{classMessageBuffer_a551bcb283b590d954613b395296958ea}

\item
{\bf Message\+Buffer} \& {\bfseries operator$<$$<$} (unsigned short short\+Value)\label{classMessageBuffer_aa2ab455e5a2d9165db2149e42653f187}

\item
{\bf Message\+Buffer} \& {\bfseries operator$<$$<$} (unsigned int uint\+Value)\label{classMessageBuffer_af71605c4b1c89eedf108dcc7b0221fbb}

\item
{\bf Message\+Buffer} \& {\bfseries operator$<$$<$} (string \&string\+Value)\label{classMessageBuffer_ad9fd51746adc47ae47c79b0b8153eb73}

\item
{\bf Message\+Buffer} \& {\bfseries operator$<$$<$} (bool bool\+Value)\label{classMessageBuffer_af7aa4d06473c56f796495be918d0ac2c}

\item
{\bf Message\+Buffer} \& {\bfseries operator$<$$<$} ({\bf Mailbox\+Address} \&mailbox\+Value)\label{classMessageBuffer_aa2c70c2b734e29c5bc578be0e1f748d5}

\item
{\bf Message\+Buffer} \& {\bf operator$>$$>$} (int \&int\+Value)
\item
{\bf Message\+Buffer} \& {\bfseries operator$>$$>$} (unsigned char \&char\+Value)\label{classMessageBuffer_ac57752c30da4e3bd14417ac29dc002a6}

\item
{\bf Message\+Buffer} \& {\bfseries operator$>$$>$} (unsigned short \&short\+Value)\label{classMessageBuffer_ab2aef585a5a37e587f29e7da21f44a5b}

\item
{\bf Message\+Buffer} \& {\bfseries operator$>$$>$} (unsigned int \&uint\+Value)\label{classMessageBuffer_a634f1dd53abde314022a7d64ed8ed7a4}

\item
{\bf Message\+Buffer} \& {\bfseries operator$>$$>$} (string \&string\+Value)\label{classMessageBuffer_a246f8473335ce5f94bba9eb5c2a6ca64}

\item
{\bf Message\+Buffer} \& {\bfseries operator$>$$>$} (bool \&bool\+Value)\label{classMessageBuffer_a8fc7c8c27d13167bc128c304b6b448cc}

\item
{\bf Message\+Buffer} \& {\bfseries operator$>$$>$} ({\bf Mailbox\+Address} \&mailbox\+Value)\label{classMessageBuffer_aae51c6593edf71c99a97af104f051e47}

\item
bool {\bf are\+Contents\+Processed} ()
\item
string {\bf to\+String} ()
\end{DoxyCompactItemize}
\subsection*{Static Public Member Functions}
\begin{DoxyCompactItemize}
\item
static {\bf O\+P\+M\+Base} $\ast$ {\bf initialize} (int initializer)
\end{DoxyCompactItemize}
\subsection*{Additional Inherited Members}

\subsection{Constructor \& Destructor Documentation}
\index{Message\+Buffer@{Message\+Buffer}!Message\+Buffer@{Message\+Buffer}}
\index{Message\+Buffer@{Message\+Buffer}!Message\+Buffer@{Message\+Buffer}}
\subsubsection[{Message\+Buffer(unsigned short buffer\+Size=\+M\+A\+X\+\_\+\+M\+E\+S\+S\+A\+G\+E\+\_\+\+L\+E\+N\+G\+T\+H, bool perform\+Network\+Conversion=true)}]{\setlength{\rightskip}{0pt plus 5cm}Message\+Buffer\+::\+Message\+Buffer (
\begin{DoxyParamCaption}
\item[{unsigned short}]{buffer\+Size = {\ttfamily MAX\+\_\+MESSAGE\+\_\+LENGTH}, }
\item[{bool}]{perform\+Network\+Conversion = {\ttfamily true}}
\end{DoxyParamCaption}
)}\label{classMessageBuffer_a36cb07e689ea4bf59df9b7fb97c086ab}
Constructor

References Message\+Buffer().

Referenced by Message\+Buffer().

\index{Message\+Buffer@{Message\+Buffer}!Message\+Buffer@{Message\+Buffer}}
\index{Message\+Buffer@{Message\+Buffer}!Message\+Buffer@{Message\+Buffer}}
\subsubsection[{Message\+Buffer(unsigned char $\ast$buffer\+Ptr, unsigned short buffer\+Size, bool perform\+Network\+Conversion=true)}]{\setlength{\rightskip}{0pt plus 5cm}Message\+Buffer\+::\+Message\+Buffer (
\begin{DoxyParamCaption}
\item[{unsigned char $\ast$}]{buffer\+Ptr, }
\item[{unsigned short}]{buffer\+Size, }
\item[{bool}]{perform\+Network\+Conversion = {\ttfamily true}}
\end{DoxyParamCaption}
)}\label{classMessageBuffer_a2bdfb271aa5d6f41fb762862ceeaa55d}
Constructor

References Message\+Buffer().

\index{Message\+Buffer@{Message\+Buffer}!````~Message\+Buffer@{$\sim$\+Message\+Buffer}}
\index{````~Message\+Buffer@{$\sim$\+Message\+Buffer}!Message\+Buffer@{Message\+Buffer}}
\subsubsection[{$\sim$\+Message\+Buffer()}]{\setlength{\rightskip}{0pt plus 5cm}Message\+Buffer\+::$\sim$\+Message\+Buffer (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [virtual]}}\label{classMessageBuffer_a9b75bc9b932dd5ac39c35b35b4f18a80}
Virtual Destructor

\subsection{Member Function Documentation}
\index{Message\+Buffer@{Message\+Buffer}!are\+Contents\+Processed@{are\+Contents\+Processed}}
\index{are\+Contents\+Processed@{are\+Contents\+Processed}!Message\+Buffer@{Message\+Buffer}}
\subsubsection[{are\+Contents\+Processed()}]{\setlength{\rightskip}{0pt plus 5cm}bool Message\+Buffer\+::are\+Contents\+Processed (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}\label{classMessageBuffer_a5197b286c2cd806b1d8654eca141e2e2}
Method to return whether or not this Message Buffer has been completely deserialized based on the position of the deserialize\+From\+Ptr

Referenced by Distributed\+Mailbox\+::create\+Mailbox(), and Group\+Mailbox\+::create\+Mailbox().

\index{Message\+Buffer@{Message\+Buffer}!assign\+Buffer@{assign\+Buffer}}
\index{assign\+Buffer@{assign\+Buffer}!Message\+Buffer@{Message\+Buffer}}
\subsubsection[{assign\+Buffer(unsigned char $\ast$buffer\+Ptr, unsigned short buffer\+Size)}]{\setlength{\rightskip}{0pt plus 5cm}void Message\+Buffer\+::assign\+Buffer (
\begin{DoxyParamCaption}
\item[{unsigned char $\ast$}]{buffer\+Ptr, }
\item[{unsigned short}]{buffer\+Size}
\end{DoxyParamCaption}
)}\label{classMessageBuffer_aa169ea82877e13c796cf2a1ba4033e91}
Method to assign the contents of the buffer

Referenced by Local\+S\+M\+Mailbox\+::get\+Mailbox\+Address().

\index{Message\+Buffer@{Message\+Buffer}!assign\+Empty\+Buffer@{assign\+Empty\+Buffer}}
\index{assign\+Empty\+Buffer@{assign\+Empty\+Buffer}!Message\+Buffer@{Message\+Buffer}}
\subsubsection[{assign\+Empty\+Buffer(unsigned char $\ast$buffer\+Ptr, unsigned short max\+Buffer\+Size)}]{\setlength{\rightskip}{0pt plus 5cm}void Message\+Buffer\+::assign\+Empty\+Buffer (
\begin{DoxyParamCaption}
\item[{unsigned char $\ast$}]{buffer\+Ptr, }
\item[{unsigned short}]{max\+Buffer\+Size}
\end{DoxyParamCaption}
)}\label{classMessageBuffer_ac04f7e9aa9e84ae44f532a6c5b7e38dd}
Method to assign empty contents to the buffer \index{Message\+Buffer@{Message\+Buffer}!clean@{clean}}
\index{clean@{clean}!Message\+Buffer@{Message\+Buffer}}
\subsubsection[{clean()}]{\setlength{\rightskip}{0pt plus 5cm}void Message\+Buffer\+::clean (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [virtual]}}\label{classMessageBuffer_a5f97e8b2995f91fa097b1cf330fe11f6}
\doxyref{O\+P\+M\+Base}{p.}{classOPMBase} clean method gets called when the object gets released back into its pool

Implements {\bf O\+P\+M\+Base} \doxyref{}{p.}{classOPMBase_ad9ff8bb1ca9a1edfaaeb702f341713e9}.

References clear\+Buffer().

\index{Message\+Buffer@{Message\+Buffer}!clear\+Buffer@{clear\+Buffer}}
\index{clear\+Buffer@{clear\+Buffer}!Message\+Buffer@{Message\+Buffer}}
\subsubsection[{clear\+Buffer()}]{\setlength{\rightskip}{0pt plus 5cm}void Message\+Buffer\+::clear\+Buffer (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}\label{classMessageBuffer_a6762227db0063df8dc178b3898702102}
Method to clear out the buffer

Referenced by clean(), Distributed\+Mailbox\+::create\+Mailbox(), Group\+Mailbox\+::create\+Mailbox(), and Local\+S\+M\+Mailbox\+::get\+Mailbox\+Address().

\index{Message\+Buffer@{Message\+Buffer}!get\+Buffer@{get\+Buffer}}
\index{get\+Buffer@{get\+Buffer}!Message\+Buffer@{Message\+Buffer}}
\subsubsection[{get\+Buffer()}]{\setlength{\rightskip}{0pt plus 5cm}unsigned char $\ast$ Message\+Buffer\+::get\+Buffer (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}\label{classMessageBuffer_af531cf3d510640553a97257f1a912955}
Method to return the encapsulated buffer

Referenced by Distributed\+Mailbox\+::create\+Mailbox(), and Group\+Mailbox\+::create\+Mailbox().

\index{Message\+Buffer@{Message\+Buffer}!get\+Buffer\+Length@{get\+Buffer\+Length}}
\index{get\+Buffer\+Length@{get\+Buffer\+Length}!Message\+Buffer@{Message\+Buffer}}
\subsubsection[{get\+Buffer\+Length()}]{\setlength{\rightskip}{0pt plus 5cm}unsigned int Message\+Buffer\+::get\+Buffer\+Length (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}\label{classMessageBuffer_af762a91a8c47018d0babe6fb1c280563}
Return the size of the encapsulated buffer contents \index{Message\+Buffer@{Message\+Buffer}!get\+Max\+Buffer\+Length@{get\+Max\+Buffer\+Length}}
\index{get\+Max\+Buffer\+Length@{get\+Max\+Buffer\+Length}!Message\+Buffer@{Message\+Buffer}}
\subsubsection[{get\+Max\+Buffer\+Length()}]{\setlength{\rightskip}{0pt plus 5cm}unsigned int Message\+Buffer\+::get\+Max\+Buffer\+Length (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}\label{classMessageBuffer_aa77dc3c359fd77dab76eef8fdcc530a1}
Return the max buffer length \index{Message\+Buffer@{Message\+Buffer}!initialize@{initialize}}
\index{initialize@{initialize}!Message\+Buffer@{Message\+Buffer}}
\subsubsection[{initialize(int initializer)}]{\setlength{\rightskip}{0pt plus 5cm}{\bf O\+P\+M\+Base} $\ast$ Message\+Buffer\+::initialize (
\begin{DoxyParamCaption}
\item[{int}]{initializer}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [static]}}\label{classMessageBuffer_ab8e6c549bd00fed6a754169ed1bce678}
\doxyref{O\+P\+M\+Base}{p.}{classOPMBase} static initializer method for bootstrapping the objects
\begin{DoxyParams}{Parameters}
{\em initializer} & Here the initializer will be the message buffer size to create. This assumes that we will have an \doxyref{O\+PM}{p.}{classOPM} object pool for each size of Message Buffer that we need. \\
\hline
\end{DoxyParams}

Referenced by Distributed\+Mailbox\+Proxy\+::\+Distributed\+Mailbox\+Proxy(), Group\+Mailbox\+Proxy\+::\+Group\+Mailbox\+Proxy(), and Local\+S\+M\+Mailbox\+Proxy\+::\+Local\+S\+M\+Mailbox\+Proxy().

\index{Message\+Buffer@{Message\+Buffer}!operator$<$$<$@{operator$<$$<$}}
\index{operator$<$$<$@{operator$<$$<$}!Message\+Buffer@{Message\+Buffer}}
\subsubsection[{operator$<$$<$(int int\+Value)}]{\setlength{\rightskip}{0pt plus 5cm}{\bf Message\+Buffer} \& Message\+Buffer\+::operator$<$$<$ (
\begin{DoxyParamCaption}
\item[{int}]{int\+Value}
\end{DoxyParamCaption}
)}\label{classMessageBuffer_a2e33a7215d756ce35592ba9e238f1c25}
Overloaded insertion operators for the buffer

References Mailbox\+Address\+::inet\+Address, Mailbox\+Address\+::location\+Type, Mailbox\+Address\+::mailbox\+Name, Mailbox\+Address\+::mailbox\+Type, Mailbox\+Address\+::neid, Mailbox\+Address\+::redundant\+Role, Mailbox\+Address\+::shelf\+Number, and Mailbox\+Address\+::slot\+Number.

\index{Message\+Buffer@{Message\+Buffer}!operator$>$$>$@{operator$>$$>$}}
\index{operator$>$$>$@{operator$>$$>$}!Message\+Buffer@{Message\+Buffer}}
\subsubsection[{operator$>$$>$(int \&int\+Value)}]{\setlength{\rightskip}{0pt plus 5cm}{\bf Message\+Buffer} \& Message\+Buffer\+::operator$>$$>$ (
\begin{DoxyParamCaption}
\item[{int \&}]{int\+Value}
\end{DoxyParamCaption}
)}\label{classMessageBuffer_ae72aee5f48781456c4dd945fa041d017}
Overloaded extraction operators for the buffer

References Mailbox\+Address\+::inet\+Address, Mailbox\+Address\+::location\+Type, Mailbox\+Address\+::mailbox\+Name, Mailbox\+Address\+::mailbox\+Type, Mailbox\+Address\+::neid, Mailbox\+Address\+::redundant\+Role, Mailbox\+Address\+::shelf\+Number, and Mailbox\+Address\+::slot\+Number.

\index{Message\+Buffer@{Message\+Buffer}!set\+Insert\+Position@{set\+Insert\+Position}}
\index{set\+Insert\+Position@{set\+Insert\+Position}!Message\+Buffer@{Message\+Buffer}}
\subsubsection[{set\+Insert\+Position(unsigned short n\+Bytes)}]{\setlength{\rightskip}{0pt plus 5cm}void Message\+Buffer\+::set\+Insert\+Position (
\begin{DoxyParamCaption}
\item[{unsigned short}]{n\+Bytes}
\end{DoxyParamCaption}
)}\label{classMessageBuffer_a7acd8585185a7b1e35cd990e4e5058d8}
Method to control the insertion position into the buffer

Referenced by Distributed\+Mailbox\+::create\+Mailbox(), Group\+Mailbox\+::create\+Mailbox(), and Local\+S\+M\+Mailbox\+::get\+Mailbox\+Address().

\index{Message\+Buffer@{Message\+Buffer}!set\+Network\+Conversion@{set\+Network\+Conversion}}
\index{set\+Network\+Conversion@{set\+Network\+Conversion}!Message\+Buffer@{Message\+Buffer}}
\subsubsection[{set\+Network\+Conversion(bool perform\+Network\+Conversion)}]{\setlength{\rightskip}{0pt plus 5cm}void Message\+Buffer\+::set\+Network\+Conversion (
\begin{DoxyParamCaption}
\item[{bool}]{perform\+Network\+Conversion}
\end{DoxyParamCaption}
)}\label{classMessageBuffer_ace12cc1ef4e22d9946138010831853ac}
Method to set the Network Conversion mode.
\begin{DoxyParams}{Parameters}
{\em perform\+Network\+Conversion} & true is network bit conversion should be performed; otherwise false (for shared memory operations) \\
\hline
\end{DoxyParams}
\index{Message\+Buffer@{Message\+Buffer}!to\+String@{to\+String}}
\index{to\+String@{to\+String}!Message\+Buffer@{Message\+Buffer}}
\subsubsection[{to\+String()}]{\setlength{\rightskip}{0pt plus 5cm}string Message\+Buffer\+::to\+String (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}\label{classMessageBuffer_ac8d138f69669b78bbbdc243d5262b319}
String\textquotesingle{}ized debugging method \begin{DoxyReturn}{Returns}
string representation of the contents of this object
\end{DoxyReturn}

The documentation for this class was generated from the following files\+:\begin{DoxyCompactItemize}
\item
Message\+Buffer.\+h\item
Message\+Buffer.\+cpp\end{DoxyCompactItemize}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>CategoryExplorerLogRecordFilter (Apache Log4j 1.2.17 API)</title>
<meta name="date" content="2015-08-23">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

您的浏览器已禁用 JavaScript。

概览

程序包

类

使用

树

已过时

索引

帮助

上一个类

下一个类

框架

无框架

所有类

概要:

嵌套 |

字段 |

构造器 |

方法

详细资料:

字段 |

构造器 |

方法

org.apache.log4j.lf5.viewer.categoryexplorer

类 CategoryExplorerLogRecordFilter

java.lang.Object

org.apache.log4j.lf5.viewer.categoryexplorer.CategoryExplorerLogRecordFilter

所有已实现的接口:

LogRecordFilter

public class CategoryExplorerLogRecordFilter
extends java.lang.Object
implements LogRecordFilter

An implementation of LogRecordFilter based on a CategoryExplorerModel

作者:

Richard Wan

字段概要

字段

限定符和类型
字段和说明

protected CategoryExplorerModel
_model

构造器概要

构造器

构造器和说明

CategoryExplorerLogRecordFilter(CategoryExplorerModel model)

方法概要

方法

限定符和类型
方法和说明

boolean
passes(LogRecord record)

void
reset()

Resets the counters for the contained CategoryNodes to zero.

protected void
resetAllNodes()

从类继承的方法 java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

字段详细资料

_model

protected CategoryExplorerModel _model

构造器详细资料

CategoryExplorerLogRecordFilter

public CategoryExplorerLogRecordFilter(CategoryExplorerModel model)

方法详细资料

passes

public boolean passes(LogRecord record)

指定者:

passes 在接口中 LogRecordFilter

返回:

true if the CategoryExplorer model specified at construction
 is accepting the category of the specified LogRecord.  Has a side-effect
 of adding the CategoryPath of the LogRecord to the explorer model
 if the CategoryPath is new.

reset

public void reset()

Resets the counters for the contained CategoryNodes to zero.

resetAllNodes

protected void resetAllNodes()

概览

程序包

类

使用

树

已过时

索引

帮助

上一个类

下一个类

框架

无框架

所有类

概要:

嵌套 |

字段 |

构造器 |

方法

详细资料:

字段 |

构造器 |

方法

Copyright © 1999-2015 Apache Software Foundation. All Rights Reserved.