text:
'use strict';

(function() {
    angular.module('sdm.uploadDicom.directives.sdmConfirmAnonymize',
        []).directive('sdmConfirmAnonymize',
        [function() {
            return {
                restrict: 'E',
                scope: false,
                replace: false,
                transclude: false,
                controller: function(){},
                controllerAs: 'sdmCAController',
                link: function($scope, $element, $attrs, sdmCAController) {
                    $scope.$parent.disableEvents();
                    //console.log($scope);

                    sdmCAController.cancel = function($event) {
                        $scope.$parent.$parent.data.anonymize = true;

                        $scope.$parent._hidePopover($event, 0);
                    }

                    sdmCAController.confirm = function($event) {
                        $scope.$parent.$parent.data.anonymize = false;
                        $scope.$parent._hidePopover($event, 0);
                    }
                }
            }
        }]
    );
})();


text:
@echo Off
set config=%1
if "%config%" == "" (
   set config=Release
)

set version=1.0.0
if not "%PackageVersion%" == "" (
   set version=%PackageVersion%
)

set nuget=
if "%nuget%" == "" (
	set nuget=nuget
)

%WINDIR%\Microsoft.NET\Framework\v4.0.30319\msbuild IEnumerableTrie.sln /p:Configuration="%config%" /m /v:M /fl /flp:LogFile=msbuild.log;Verbosity=diag /nr:false

mkdir Build
mkdir Build\lib
mkdir Build\lib\net40

%nuget% pack "IEnumerableTrie.nuspec" -NoPackageAnalysis -verbosity detailed -o Build -Version %version% -p Configuration="%config%"

redpajama_set_name: RedPajamaGithub


text:
define(function(require, exports, module) {

var oop = require("../lib/oop");
var Mirror = require("../worker/mirror").Mirror;
var lint = require("../worker/jshint").JSHINT;

var JavaScriptWorker = exports.JavaScriptWorker = function(sender) {
    Mirror.call(this, sender);
    this.setTimeout(500);
};

oop.inherits(JavaScriptWorker, Mirror);

(function() {

    this.onUpdate = function() {
        var value = this.doc.getValue();
        value = value.replace(/^#!.*\n/, "\n");

//        var start = new Date();
        var parser = require("../narcissus/jsparse");
        try {
            parser.parse(value);
        } catch(e) {
//            console.log("narcissus")
//            console.log(e);
            var chunks = e.message.split(":")
            var message = chunks.pop().trim();
            var lineNumber = parseInt(chunks.pop().trim()) - 1;
            this.sender.emit("narcissus", {
                row: lineNumber,
                column: null, // TODO convert e.cursor
                text: message,
                type: "error"
            });
            return;
        } finally {
//            console.log("parse time: " + (new Date() - start));
        }

//        var start = new Date();
//        console.log("jslint")
        lint(value, {undef: false, onevar: false, passfail: false});
        this.sender.emit("jslint", lint.errors);
//        console.log("lint time: " + (new Date() - start));
    }

}).call(JavaScriptWorker.prototype);

});


text:
ActiveRecord::Schema.define(version: 20151102041658) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "addresses", force: :cascade do |t|
    t.string   "line_1"
    t.string   "line_2"
    t.string   "city"
    t.integer  "state"
    t.integer  "zip"
    t.integer  "type"
    t.integer  "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  add_index "addresses", ["user_id"], name: "index_addresses_on_user_id", using: :btree

  create_table "profiles", force: :cascade do |t|
    t.string   "first_name"
    t.string   "middle_name"
    t.string   "maiden_name"
    t.string   "last_name"
    t.date     "birthday"
    t.integer  "gender"
    t.integer  "user_id"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
  end

  add_index "profiles", ["user_id"], name: "index_profiles_on_user_id", using: :btree

  create_table "users", force: :cascade do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.inet     "current_sign_in_ip"
    t.inet     "last_sign_in_ip"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
  add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree

end


text:
namespace Problem_4___Relevance_Index
{
    using System;
    using System.Text;
    using System.Collections.Generic;
    using System.Linq;

    class Startup
    {
        static string[] symbol = new string[] { " ", ",", ".", "(", ")", ";", "-", "!", "?" };

        static void Main()
        {
            string searchWord = Console.ReadLine();

            int numberOfParagraphs = int.Parse(Console.ReadLine());

            List<string> paragraph = new List<string>();
            List<int> indexes = new List<int>();

            for (int i = 0; i < numberOfParagraphs; i++)
            {
                var currentLineWords = Console.ReadLine().Split(symbol, StringSplitOptions.RemoveEmptyEntries);
                int relevanceIndex = 0;

                for (int j = 0; j < currentLineWords.Length; j++)
                {
                    string word = currentLineWords[j];
                    if (word.ToLower() == searchWord.ToLower())
                    {
                        relevanceIndex++;
                        currentLineWords[j] = word.ToUpper();
                    }
                }

                paragraph.Add(string.Join(" ", currentLineWords));
                indexes.Add(relevanceIndex);
            }

            List<string> sortedParagraphs = new List<string>();

            while (sortedParagraphs.Count < paragraph.Count)
            {
                int maxIndex = 0;
                int maxParagraphIndex = 0;
                for (int i = 0; i < indexes.Count; i++)
                {
                    if (maxIndex <  indexes[i])
                    {
                        maxIndex = indexes[i];
                        maxParagraphIndex = i;
                    }
                }
                sortedParagraphs.Add(paragraph[maxParagraphIndex]);
                indexes[maxParagraphIndex] = -1;
            }

            Console.WriteLine(string.Join(Environment.NewLine, sortedParagraphs));
        }
    }
}


text:
package scouter.lang.step;

import java.io.IOException;

import scouter.io.DataInputX;
import scouter.io.DataOutputX;

abstract public class StepSingle extends Step{

	public int parent;
	public int index;

	public int start_time;
	public int start_cpu;

	public int getOrder() {
		return index;
	}

	public void write(DataOutputX out) throws IOException {
		out.writeDecimal(parent);
		out.writeDecimal(index);
		out.writeDecimal(start_time);
		out.writeDecimal(start_cpu);
	}
	public Step read(DataInputX in) throws IOException {
		this.parent = (int) in.readDecimal();
		this.index = (int) in.readDecimal();
		this.start_time = (int) in.readDecimal();
		this.start_cpu = (int) in.readDecimal();
		return this;
	}
}


text:
package net.stevemoyer.vbrank.rest;
import javax.jdo.PersistenceManager;
//import javax.jdo.Query;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
//import javax.servlet.http.HttpServletRequest;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;

//import java.util.logging.Logger;

//import javax.servlet.http.HttpServletResponse;
@Singleton
public class AuthServletFilter implements Filter {
  @Inject  Provider<PersistenceManager> pmf;
  //private static final Logger log = Logger.getLogger(PlayerService.class.getName());
  public void doFilter(final ServletRequest request, final ServletResponse response,
      FilterChain chain)
    throws java.io.IOException, javax.servlet.ServletException {
    chain.doFilter(request,response);
    return;
    //    String url = ((HttpServletRequest)request).getRequestURL().toString();
    //    UserService userService = UserServiceFactory.getUserService();
    //    User user = userService.getCurrentUser();
    //    if(userService.isUserAdmin()) {
    //      chain.doFilter(request,response);
    //      return;
    //    }
    //    String emailAddress = user.getEmail();
    //    Query q = pm.newQuery(Player.class);
    //    q.setFilter("emailAddress == emailAddressParam");
    //    q.declareParameters("String emailAddressParam");
    //    q.setUnique(true);
    //    log.severe(url + " emailAddress:" + emailAddress);
    //    Object o = q.execute(emailAddress);
    //    Player player = (Player)o;
    //
    //    if(player != null) {
    //      log.severe(url + " player not null: " + player);
    //      chain.doFilter(request,response);
    //    }
    //
    //    log.severe(url + " player null");
    //    ((HttpServletResponse)response).setStatus(HttpServletResponse.SC_FORBIDDEN);
    //
  }
  public void init(FilterConfig filterConfig)
    throws ServletException {
  }
  public void destroy() {
  }
}


text:
from __future__ import absolute_import

from django.utils import timezone

from sentry.testutils import AcceptanceTestCase
from sentry.incidents.models import IncidentStatus

FEATURE_NAME = ["organizations:incidents", "organizations:project-detail"]

class ProjectDetailTest(AcceptanceTestCase):
    def setUp(self):
        super(ProjectDetailTest, self).setUp()
        self.user = self.create_user("foo@example.com")
        self.org = self.create_organization(name="Rowdy Tiger", owner=None)

        self.team1 = self.create_team(organization=self.org, name="Mariachi Band 1")
        self.team2 = self.create_team(organization=self.org, name="Mariachi Band 2")
        self.team3 = self.create_team(organization=self.org, name="Mariachi Band 3")
        self.team4 = self.create_team(organization=self.org, name="Mariachi Band 4")
        self.team5 = self.create_team(organization=self.org, name="Mariachi Band 5")
        self.team6 = self.create_team(organization=self.org, name="Mariachi Band 6")

        self.project = self.create_project(
            organization=self.org,
            teams=[self.team1, self.team2, self.team3, self.team4, self.team5, self.team6],
            name="Bengal",
        )
        self.create_member(user=self.user, organization=self.org, role="owner", teams=[self.team1])

        alert_rule = self.create_alert_rule(organization=self.org, projects=[self.project])
        self.create_incident(
            organization=self.org,
            title="Incident #1",
            date_started=timezone.now(),
            date_detected=timezone.now(),
            projects=[self.project],
            alert_rule=alert_rule,
            status=IncidentStatus.WARNING.value,
        )
        self.create_incident(
            organization=self.org,
            title="Incident #2",
            date_started=timezone.now(),
            date_detected=timezone.now(),
            projects=[self.project],
            alert_rule=alert_rule,
            status=IncidentStatus.CRITICAL.value,
        )
        self.create_incident(
            organization=self.org,
            title="Incident #3",
            date_started=timezone.now(),
            date_detected=timezone.now(),
            date_closed=timezone.now(),
            projects=[self.project],
            alert_rule=alert_rule,
            status=IncidentStatus.CLOSED.value,
        )

        self.create_release(project=self.project, version="1.0.0")
        self.create_release(project=self.project, version="1.1.0")
        self.create_release(project=self.project, version="1.2.3")
        self.create_release(project=self.project, version="2.0.5")
        self.create_release(project=self.project, version="2.3.3")
        self.create_release(project=self.project, version="3.3.3")

        self.login_as(self.user)
        self.path = u"/organizations/{}/projects/{}/".format(self.org.slug, self.project.slug)

    def test_simple(self):
        with self.feature(FEATURE_NAME):
            self.browser.get(self.path)
            self.browser.wait_until_not(".loading-indicator")
            self.browser.wait_until_not('[data-test-id="loading-placeholder"]')
            self.browser.snapshot("project detail")

    def test_no_feature(self):
        self.browser.get(self.path)
        self.browser.wait_until_not(".loading-indicator")
        self.browser.snapshot("project detail no feature")


text:
.class public Lcom/android/internal/app/MediaRouteChooserDialogFragment;
.super Landroid/app/DialogFragment;
.source "MediaRouteChooserDialogFragment.java"

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Lcom/android/internal/app/MediaRouteChooserDialogFragment$1;,
        Lcom/android/internal/app/MediaRouteChooserDialogFragment$VolumeSliderChangeListener;,
        Lcom/android/internal/app/MediaRouteChooserDialogFragment$LauncherListener;,
        Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteChooserDialog;,
        Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteComparator;,
        Lcom/android/internal/app/MediaRouteChooserDialogFragment$MediaRouterCallback;,
        Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;,
        Lcom/android/internal/app/MediaRouteChooserDialogFragment$ViewHolder;
    }
.end annotation

# static fields
.field public static final FRAGMENT_TAG:Ljava/lang/String; = "android:MediaRouteChooserDialogFragment"

.field private static final ITEM_LAYOUTS:[I = null

.field private static final TAG:Ljava/lang/String; = "MediaRouteChooserDialogFragment"

# instance fields
.field private mAdapter:Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;

.field final mCallback:Lcom/android/internal/app/MediaRouteChooserDialogFragment$MediaRouterCallback;

.field final mComparator:Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteComparator;

.field mDisplayService:Landroid/hardware/display/DisplayManager;

.field private mExtendedSettingsListener:Landroid/view/View$OnClickListener;

.field private mIgnoreCallbackVolumeChanges:Z

.field private mIgnoreSliderVolumeChanges:Z

.field private mInflater:Landroid/view/LayoutInflater;

.field private mLauncherListener:Lcom/android/internal/app/MediaRouteChooserDialogFragment$LauncherListener;

.field private mListView:Landroid/widget/ListView;

.field private mRouteTypes:I

.field mRouter:Landroid/media/MediaRouter;

.field private mVolumeIcon:Landroid/widget/ImageView;

.field private mVolumeSlider:Landroid/widget/SeekBar;

# direct methods
.method static constructor <clinit>()V
    .locals 1

    .prologue
    .line 64
    const/4 v0, 0x5

    new-array v0, v0, [I

    fill-array-data v0, :array_0

    sput-object v0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->ITEM_LAYOUTS:[I

    return-void

    nop

    :array_0
    .array-data 0x4
        #layout@media_route_list_item_top_header#a
        #layout@media_route_list_item_section_header#a
        #layout@media_route_list_item#a
        #layout@media_route_list_item_checkable#a
        #layout@media_route_list_item_collapse_group#a
    .end array-data
.end method

.method public constructor <init>()V
    .locals 2

    .prologue
    .line 89
    invoke-direct {p0}, Landroid/app/DialogFragment;-><init>()V

    .line 84
    new-instance v0, Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteComparator;

    invoke-direct {v0, p0}, Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteComparator;-><init>(Lcom/android/internal/app/MediaRouteChooserDialogFragment;)V

    iput-object v0, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mComparator:Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteComparator;

    .line 85
    new-instance v0, Lcom/android/internal/app/MediaRouteChooserDialogFragment$MediaRouterCallback;

    invoke-direct {v0, p0}, Lcom/android/internal/app/MediaRouteChooserDialogFragment$MediaRouterCallback;-><init>(Lcom/android/internal/app/MediaRouteChooserDialogFragment;)V

    iput-object v0, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mCallback:Lcom/android/internal/app/MediaRouteChooserDialogFragment$MediaRouterCallback;

    .line 90
    const/4 v0, 0x1

    const v1, #style@Theme.DeviceDefault.Dialog#t

    invoke-virtual {p0, v0, v1}, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->setStyle(II)V

    .line 91
    return-void
.end method

.method static synthetic access$000(Lcom/android/internal/app/MediaRouteChooserDialogFragment;)I
    .locals 1
    .parameter "x0"

    .prologue
    .line 60
    iget v0, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mRouteTypes:I

    return v0
.end method

.method static synthetic access$100(Lcom/android/internal/app/MediaRouteChooserDialogFragment;)Landroid/widget/ListView;
    .locals 1
    .parameter "x0"

    .prologue
    .line 60
    iget-object v0, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mListView:Landroid/widget/ListView;

    return-object v0
.end method

.method static synthetic access$200()[I
    .locals 1

    .prologue
    .line 60
    sget-object v0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->ITEM_LAYOUTS:[I

    return-object v0
.end method

.method static synthetic access$300(Lcom/android/internal/app/MediaRouteChooserDialogFragment;)Landroid/view/LayoutInflater;
    .locals 1
    .parameter "x0"

    .prologue
    .line 60
    iget-object v0, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mInflater:Landroid/view/LayoutInflater;

    return-object v0
.end method

.method static synthetic access$700(Lcom/android/internal/app/MediaRouteChooserDialogFragment;)Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;
    .locals 1
    .parameter "x0"

    .prologue
    .line 60
    iget-object v0, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mAdapter:Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;

    return-object v0
.end method

.method static synthetic access$800(Lcom/android/internal/app/MediaRouteChooserDialogFragment;)Z
    .locals 1
    .parameter "x0"

    .prologue
    .line 60
    iget-boolean v0, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mIgnoreCallbackVolumeChanges:Z

    return v0
.end method

.method static synthetic access$802(Lcom/android/internal/app/MediaRouteChooserDialogFragment;Z)Z
    .locals 0
    .parameter "x0"
    .parameter "x1"

    .prologue
    .line 60
    iput-boolean p1, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mIgnoreCallbackVolumeChanges:Z

    return p1
.end method

.method static synthetic access$900(Lcom/android/internal/app/MediaRouteChooserDialogFragment;)Landroid/widget/SeekBar;
    .locals 1
    .parameter "x0"

    .prologue
    .line 60
    iget-object v0, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mVolumeSlider:Landroid/widget/SeekBar;

    return-object v0
.end method

# virtual methods
.method changeVolume(I)V
    .locals 4
    .parameter "newValue"

    .prologue
    .line 161
    iget-boolean v2, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mIgnoreSliderVolumeChanges:Z

    if-eqz v2, :cond_1

    .line 170
    :cond_0
    :goto_0
    return-void

    .line 163
    :cond_1
    iget-object v2, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mRouter:Landroid/media/MediaRouter;

    iget v3, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mRouteTypes:I

    invoke-virtual {v2, v3}, Landroid/media/MediaRouter;->getSelectedRoute(I)Landroid/media/MediaRouter$RouteInfo;

    move-result-object v1

    .line 164
    .local v1, selectedRoute:Landroid/media/MediaRouter$RouteInfo;
    if-eqz v1, :cond_0

    invoke-virtual {v1}, Landroid/media/MediaRouter$RouteInfo;->getVolumeHandling()I

    move-result v2

    const/4 v3, 0x1

    if-ne v2, v3, :cond_0

    .line 166
    invoke-virtual {v1}, Landroid/media/MediaRouter$RouteInfo;->getVolumeMax()I

    move-result v0

    .line 167
    .local v0, maxVolume:I
    const/4 v2, 0x0

    invoke-static {p1, v0}, Ljava/lang/Math;->min(II)I

    move-result v3

    invoke-static {v2, v3}, Ljava/lang/Math;->max(II)I

    move-result p1

    .line 168
    invoke-virtual {v1, p1}, Landroid/media/MediaRouter$RouteInfo;->requestSetVolume(I)V

    goto :goto_0
.end method

.method public onAttach(Landroid/app/Activity;)V
    .locals 1
    .parameter "activity"

    .prologue
    .line 99
    invoke-super {p0, p1}, Landroid/app/DialogFragment;->onAttach(Landroid/app/Activity;)V

    .line 100
    const-string/jumbo v0, "media_router"

    invoke-virtual {p1, v0}, Landroid/app/Activity;->getSystemService(Ljava/lang/String;)Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/media/MediaRouter;

    iput-object v0, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mRouter:Landroid/media/MediaRouter;

    .line 101
    const-string v0, "display"

    invoke-virtual {p1, v0}, Landroid/app/Activity;->getSystemService(Ljava/lang/String;)Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/hardware/display/DisplayManager;

    iput-object v0, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mDisplayService:Landroid/hardware/display/DisplayManager;

    .line 102
    return-void
.end method

.method public onCreateDialog(Landroid/os/Bundle;)Landroid/app/Dialog;
    .locals 3
    .parameter "savedInstanceState"

    .prologue
    .line 204
    new-instance v0, Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteChooserDialog;

    invoke-virtual {p0}, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->getActivity()Landroid/app/Activity;

    move-result-object v1

    invoke-virtual {p0}, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->getTheme()I

    move-result v2

    invoke-direct {v0, p0, v1, v2}, Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteChooserDialog;-><init>(Lcom/android/internal/app/MediaRouteChooserDialogFragment;Landroid/content/Context;I)V

    return-object v0
.end method

.method public onCreateView(Landroid/view/LayoutInflater;Landroid/view/ViewGroup;Landroid/os/Bundle;)Landroid/view/View;
    .locals 6
    .parameter "inflater"
    .parameter "container"
    .parameter "savedInstanceState"

    .prologue
    const/4 v5, 0x0

    .line 175
    iput-object p1, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mInflater:Landroid/view/LayoutInflater;

    .line 176
    const v3, #layout@media_route_chooser_layout#t

    invoke-virtual {p1, v3, p2, v5}, Landroid/view/LayoutInflater;->inflate(ILandroid/view/ViewGroup;Z)Landroid/view/View;

    move-result-object v1

    .line 178
    .local v1, layout:Landroid/view/View;
    const v3, #id@volume_icon#t

    invoke-virtual {v1, v3}, Landroid/view/View;->findViewById(I)Landroid/view/View;

    move-result-object v3

    check-cast v3, Landroid/widget/ImageView;

    iput-object v3, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mVolumeIcon:Landroid/widget/ImageView;

    .line 179
    const v3, #id@volume_slider#t

    invoke-virtual {v1, v3}, Landroid/view/View;->findViewById(I)Landroid/view/View;

    move-result-object v3

    check-cast v3, Landroid/widget/SeekBar;

    iput-object v3, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mVolumeSlider:Landroid/widget/SeekBar;

    .line 180
    invoke-virtual {p0}, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->updateVolume()V

    .line 181
    iget-object v3, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mVolumeSlider:Landroid/widget/SeekBar;

    new-instance v4, Lcom/android/internal/app/MediaRouteChooserDialogFragment$VolumeSliderChangeListener;

    invoke-direct {v4, p0}, Lcom/android/internal/app/MediaRouteChooserDialogFragment$VolumeSliderChangeListener;-><init>(Lcom/android/internal/app/MediaRouteChooserDialogFragment;)V

    invoke-virtual {v3, v4}, Landroid/widget/SeekBar;->setOnSeekBarChangeListener(Landroid/widget/SeekBar$OnSeekBarChangeListener;)V

    .line 183
    iget-object v3, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mExtendedSettingsListener:Landroid/view/View$OnClickListener;

    if-eqz v3, :cond_0

    .line 184
    const v3, #id@extended_settings#t

    invoke-virtual {v1, v3}, Landroid/view/View;->findViewById(I)Landroid/view/View;

    move-result-object v0

    .line 185
    .local v0, extendedSettingsButton:Landroid/view/View;
    invoke-virtual {v0, v5}, Landroid/view/View;->setVisibility(I)V

    .line 186
    iget-object v3, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mExtendedSettingsListener:Landroid/view/View$OnClickListener;

    invoke-virtual {v0, v3}, Landroid/view/View;->setOnClickListener(Landroid/view/View$OnClickListener;)V

    .line 189
    .end local v0           #extendedSettingsButton:Landroid/view/View;
    :cond_0
    const v3, #id@list#t

    invoke-virtual {v1, v3}, Landroid/view/View;->findViewById(I)Landroid/view/View;

    move-result-object v2

    check-cast v2, Landroid/widget/ListView;

    .line 190
    .local v2, list:Landroid/widget/ListView;
    const/4 v3, 0x1

    invoke-virtual {v2, v3}, Landroid/widget/ListView;->setItemsCanFocus(Z)V

    .line 191
    new-instance v3, Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;

    invoke-direct {v3, p0}, Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;-><init>(Lcom/android/internal/app/MediaRouteChooserDialogFragment;)V

    iput-object v3, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mAdapter:Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;

    invoke-virtual {v2, v3}, Landroid/widget/ListView;->setAdapter(Landroid/widget/ListAdapter;)V

    .line 192
    iget-object v3, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mAdapter:Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;

    invoke-virtual {v2, v3}, Landroid/widget/ListView;->setOnItemClickListener(Landroid/widget/AdapterView$OnItemClickListener;)V

    .line 194
    iput-object v2, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mListView:Landroid/widget/ListView;

    .line 195
    iget-object v3, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mRouter:Landroid/media/MediaRouter;

    iget v4, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mRouteTypes:I

    iget-object v5, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mCallback:Lcom/android/internal/app/MediaRouteChooserDialogFragment$MediaRouterCallback;

    invoke-virtual {v3, v4, v5}, Landroid/media/MediaRouter;->addCallback(ILandroid/media/MediaRouter$Callback;)V

    .line 197
    iget-object v3, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mAdapter:Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;

    invoke-virtual {v3}, Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;->scrollToSelectedItem()V

    .line 199
    return-object v1
.end method

.method public onDetach()V
    .locals 3

    .prologue
    const/4 v2, 0x0

    .line 106
    invoke-super {p0}, Landroid/app/DialogFragment;->onDetach()V

    .line 107
    iget-object v0, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mLauncherListener:Lcom/android/internal/app/MediaRouteChooserDialogFragment$LauncherListener;

    if-eqz v0, :cond_0

    .line 108
    iget-object v0, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mLauncherListener:Lcom/android/internal/app/MediaRouteChooserDialogFragment$LauncherListener;

    invoke-interface {v0, p0}, Lcom/android/internal/app/MediaRouteChooserDialogFragment$LauncherListener;->onDetached(Lcom/android/internal/app/MediaRouteChooserDialogFragment;)V

    .line 110
    :cond_0
    iget-object v0, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mAdapter:Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;

    if-eqz v0, :cond_1

    .line 111
    iput-object v2, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mAdapter:Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;

    .line 113
    :cond_1
    iput-object v2, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mInflater:Landroid/view/LayoutInflater;

    .line 114
    iget-object v0, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mRouter:Landroid/media/MediaRouter;

    iget-object v1, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mCallback:Lcom/android/internal/app/MediaRouteChooserDialogFragment$MediaRouterCallback;

    invoke-virtual {v0, v1}, Landroid/media/MediaRouter;->removeCallback(Landroid/media/MediaRouter$Callback;)V

    .line 115
    iput-object v2, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mRouter:Landroid/media/MediaRouter;

    .line 116
    return-void
.end method

.method public onResume()V
    .locals 1

    .prologue
    .line 209
    invoke-super {p0}, Landroid/app/DialogFragment;->onResume()V

    .line 210
    iget-object v0, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mDisplayService:Landroid/hardware/display/DisplayManager;

    if-eqz v0, :cond_0

    .line 211
    iget-object v0, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mDisplayService:Landroid/hardware/display/DisplayManager;

    invoke-virtual {v0}, Landroid/hardware/display/DisplayManager;->scanWifiDisplays()V

    .line 213
    :cond_0
    return-void
.end method

.method public setExtendedSettingsClickListener(Landroid/view/View$OnClickListener;)V
    .locals 0
    .parameter "listener"

    .prologue
    .line 119
    iput-object p1, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mExtendedSettingsListener:Landroid/view/View$OnClickListener;

    .line 120
    return-void
.end method

.method public setLauncherListener(Lcom/android/internal/app/MediaRouteChooserDialogFragment$LauncherListener;)V
    .locals 0
    .parameter "listener"

    .prologue
    .line 94
    iput-object p1, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mLauncherListener:Lcom/android/internal/app/MediaRouteChooserDialogFragment$LauncherListener;

    .line 95
    return-void
.end method

.method public setRouteTypes(I)V
    .locals 2
    .parameter "types"

    .prologue
    .line 123
    iput p1, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mRouteTypes:I

    .line 124
    iget v1, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mRouteTypes:I

    and-int/lit8 v1, v1, 0x2

    if-eqz v1, :cond_1

    iget-object v1, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mDisplayService:Landroid/hardware/display/DisplayManager;

    if-nez v1, :cond_1

    .line 125
    invoke-virtual {p0}, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->getActivity()Landroid/app/Activity;

    move-result-object v0

    .line 126
    .local v0, activity:Landroid/content/Context;
    if-eqz v0, :cond_0

    .line 127
    const-string v1, "display"

    invoke-virtual {v0, v1}, Landroid/content/Context;->getSystemService(Ljava/lang/String;)Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Landroid/hardware/display/DisplayManager;

    iput-object v1, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mDisplayService:Landroid/hardware/display/DisplayManager;

    .line 133
    .end local v0           #activity:Landroid/content/Context;
    :cond_0
    :goto_0
    return-void

    .line 131
    :cond_1
    const/4 v1, 0x0

    iput-object v1, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mDisplayService:Landroid/hardware/display/DisplayManager;

    goto :goto_0
.end method

.method updateVolume()V
    .locals 5

    .prologue
    const/4 v4, 0x0

    const/4 v3, 0x1

    .line 136
    iget-object v1, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mRouter:Landroid/media/MediaRouter;

    if-nez v1, :cond_0

    .line 158
    :goto_0
    return-void

    .line 138
    :cond_0
    iget-object v1, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mRouter:Landroid/media/MediaRouter;

    iget v2, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mRouteTypes:I

    invoke-virtual {v1, v2}, Landroid/media/MediaRouter;->getSelectedRoute(I)Landroid/media/MediaRouter$RouteInfo;

    move-result-object v0

    .line 139
    .local v0, selectedRoute:Landroid/media/MediaRouter$RouteInfo;
    iget-object v2, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mVolumeIcon:Landroid/widget/ImageView;

    if-eqz v0, :cond_1

    invoke-virtual {v0}, Landroid/media/MediaRouter$RouteInfo;->getPlaybackType()I

    move-result v1

    if-nez v1, :cond_3

    :cond_1
    const v1, #drawable@ic_audio_vol#t

    :goto_1
    invoke-virtual {v2, v1}, Landroid/widget/ImageView;->setImageResource(I)V

    .line 143
    iput-boolean v3, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mIgnoreSliderVolumeChanges:Z

    .line 145
    if-eqz v0, :cond_2

    invoke-virtual {v0}, Landroid/media/MediaRouter$RouteInfo;->getVolumeHandling()I

    move-result v1

    if-nez v1, :cond_4

    .line 148
    :cond_2
    iget-object v1, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mVolumeSlider:Landroid/widget/SeekBar;

    invoke-virtual {v1, v3}, Landroid/widget/SeekBar;->setMax(I)V

    .line 149
    iget-object v1, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mVolumeSlider:Landroid/widget/SeekBar;

    invoke-virtual {v1, v3}, Landroid/widget/SeekBar;->setProgress(I)V

    .line 150
    iget-object v1, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mVolumeSlider:Landroid/widget/SeekBar;

    invoke-virtual {v1, v4}, Landroid/widget/SeekBar;->setEnabled(Z)V

    .line 157
    :goto_2
    iput-boolean v4, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mIgnoreSliderVolumeChanges:Z

    goto :goto_0

    .line 139
    :cond_3
    const v1, #drawable@ic_media_route_on_holo_dark#t

    goto :goto_1

    .line 152
    :cond_4
    iget-object v1, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mVolumeSlider:Landroid/widget/SeekBar;

    invoke-virtual {v1, v3}, Landroid/widget/SeekBar;->setEnabled(Z)V

    .line 153
    iget-object v1, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mVolumeSlider:Landroid/widget/SeekBar;

    invoke-virtual {v0}, Landroid/media/MediaRouter$RouteInfo;->getVolumeMax()I

    move-result v2

    invoke-virtual {v1, v2}, Landroid/widget/SeekBar;->setMax(I)V

    .line 154
    iget-object v1, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mVolumeSlider:Landroid/widget/SeekBar;

    invoke-virtual {v0}, Landroid/media/MediaRouter$RouteInfo;->getVolume()I

    move-result v2

    invoke-virtual {v1, v2}, Landroid/widget/SeekBar;->setProgress(I)V

    goto :goto_2
.end method


text:
@implementation UIAlertController (BBKitExtensions)

+ (UIAlertController *)BB_alertControllerWithError:(NSError *)error
{
    return [self.class alertControllerWithTitle:[error BB_alertTitle] message:[error BB_alertMessage] preferredStyle:UIAlertControllerStyleAlert];
}

@end


text:
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2012, OpenNebula Project Leads (OpenNebula.org)             */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

#include "RequestManager.h"
#include "NebulaLog.h"
#include <cerrno>

#include "RequestManagerPoolInfoFilter.h"
#include "RequestManagerInfo.h"
#include "RequestManagerDelete.h"
#include "RequestManagerAllocate.h"
#include "RequestManagerUpdateTemplate.h"
#include "RequestManagerChown.h"
#include "RequestManagerChmod.h"

#include "RequestManagerVirtualNetwork.h"
#include "RequestManagerVirtualMachine.h"
#include "RequestManagerVMTemplate.h"
#include "RequestManagerHost.h"
#include "RequestManagerImage.h"
#include "RequestManagerUser.h"
#include "RequestManagerAcl.h"

#include <sys/signal.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <cstring>

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

extern "C" void * rm_action_loop(void *arg)
{
    RequestManager *  rm;

    if ( arg == 0 )
    {
        return 0;
    }

    NebulaLog::log("ReM",Log::INFO,"Request Manager started.");

    rm = static_cast<RequestManager *>(arg);

    rm->am.loop(0,0);

    NebulaLog::log("ReM",Log::INFO,"Request Manager stopped.");

    return 0;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

extern "C" void * rm_xml_server_loop(void *arg)
{
    RequestManager *    rm;

    if ( arg == 0 )
    {
        return 0;
    }

    rm = static_cast<RequestManager *>(arg);

    // Set cancel state for the thread

    pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,0);

    pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,0);

    //Start the server

    rm->AbyssServer = new xmlrpc_c::serverAbyss(xmlrpc_c::serverAbyss::constrOpt()
        .registryP(&rm->RequestManagerRegistry)
        .logFileName(rm->xml_log_file)
        .socketFd(rm->socket_fd));

    rm->AbyssServer->run();

    return 0;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int RequestManager::setup_socket()
{
    int                 rc;
    int                 yes = 1;
    struct sockaddr_in  rm_addr;

    socket_fd = socket(AF_INET, SOCK_STREAM, 0);

    if ( socket_fd == -1 )
    {
        ostringstream oss;

        oss << "Can not open server socket: " << strerror(errno);
        NebulaLog::log("ReM",Log::ERROR,oss);

        return -1;
    }

    rc = setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));

    if ( rc == -1 )
    {
        ostringstream oss;

        oss << "Can not set socket options: " << strerror(errno);
        NebulaLog::log("ReM",Log::ERROR,oss);

        close(socket_fd);

        return -1;
    }

    fcntl(socket_fd,F_SETFD,FD_CLOEXEC); // Close socket in MADs

    rm_addr.sin_family      = AF_INET;
    rm_addr.sin_port        = htons(port);
    rm_addr.sin_addr.s_addr = INADDR_ANY;

    rc = bind(socket_fd,(struct sockaddr *) &(rm_addr),sizeof(struct sockaddr));

    if ( rc == -1)
    {
        ostringstream oss;

        oss << "Can not bind to port " << port << " : " << strerror(errno);
        NebulaLog::log("ReM",Log::ERROR,oss);

        close(socket_fd);

        return -1;
    }

    return 0;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int RequestManager::start()
{
    pthread_attr_t  pattr;
    ostringstream   oss;

    NebulaLog::log("ReM",Log::INFO,"Starting Request Manager...");

    int rc = setup_socket();

    if ( rc != 0 )
    {
        return -1;
    }

    register_xml_methods();

    pthread_attr_init (&pattr);
    pthread_attr_setdetachstate (&pattr, PTHREAD_CREATE_JOINABLE);

    pthread_create(&rm_thread,&pattr,rm_action_loop,(void *)this);

    pthread_attr_init (&pattr);
    pthread_attr_setdetachstate (&pattr, PTHREAD_CREATE_JOINABLE);

    oss << "Starting XML-RPC server, port " << port << " ...";
    NebulaLog::log("ReM",Log::INFO,oss);

    pthread_create(&rm_xml_server_thread,&pattr,rm_xml_server_loop,(void *)this);

    return 0;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void RequestManager::do_action(
        const string &  action,
        void *          arg)
{
    if (action == ACTION_FINALIZE)
    {
        NebulaLog::log("ReM",Log::INFO,"Stopping Request Manager...");

        pthread_cancel(rm_xml_server_thread);

        pthread_join(rm_xml_server_thread,0);

        NebulaLog::log("ReM",Log::INFO,"XML-RPC server stopped.");

        delete AbyssServer;

        if ( socket_fd != -1 )
        {
            close(socket_fd);
        }
    }
    else
    {
        ostringstream oss;
        oss << "Unknown action name: " << action;

        NebulaLog::log("ReM", Log::ERROR, oss);
    }
};

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void RequestManager::register_xml_methods()
{
    // User Methods
    xmlrpc_c::methodPtr user_change_password(new UserChangePassword());
    xmlrpc_c::methodPtr user_change_auth(new UserChangeAuth());

    // VMTemplate Methods
    xmlrpc_c::methodPtr template_instantiate(new VMTemplateInstantiate());

    // VirtualMachine Methods
    xmlrpc_c::methodPtr vm_deploy(new VirtualMachineDeploy());
    xmlrpc_c::methodPtr vm_migrate(new VirtualMachineMigrate());
    xmlrpc_c::methodPtr vm_action(new VirtualMachineAction());
    xmlrpc_c::methodPtr vm_savedisk(new VirtualMachineSaveDisk());
    //added by shenxy 20120227
    xmlrpc_c::methodPtr backup_info(new VirtualMachineBackupInfo());
    xmlrpc_c::methodPtr vm_backupdelete(new VirtualMachineBackupDelete());
    xmlrpc_c::methodPtr backupdisk_info(new VirtualMachineBackupDiskInfo());
    xmlrpc_c::methodPtr vm_backup(new VirtualMachineBackup());
    xmlrpc_c::methodPtr vm_recover(new VirtualMachineRecover());
    xmlrpc_c::methodPtr vm_backupdisk(new VirtualMachineBackupDisk());
    xmlrpc_c::methodPtr vm_changetemplate(new VirtualMachineChangeTemplate());
    xmlrpc_c::methodPtr vm_dynamicmount(new VirtualMachineDynamicMount());

    // VirtualNetwork Methods
    xmlrpc_c::methodPtr vn_addleases(new VirtualNetworkAddLeases());
    xmlrpc_c::methodPtr vn_rmleases(new VirtualNetworkRemoveLeases());
    xmlrpc_c::methodPtr vn_hold(new VirtualNetworkHold());
    xmlrpc_c::methodPtr vn_release(new VirtualNetworkRelease());

    // Update Template Methods
    xmlrpc_c::methodPtr image_update(new ImageUpdateTemplate());
    xmlrpc_c::methodPtr template_update(new TemplateUpdateTemplate());
    xmlrpc_c::methodPtr host_update(new HostUpdateTemplate());
    xmlrpc_c::methodPtr vn_update(new VirtualNetworkUpdateTemplate());
    xmlrpc_c::methodPtr user_update(new UserUpdateTemplate());

    // Allocate Methods
    xmlrpc_c::methodPtr vm_allocate(new VirtualMachineAllocate());
    xmlrpc_c::methodPtr image_allocate(new ImageAllocate());
    xmlrpc_c::methodPtr vn_allocate(new VirtualNetworkAllocate());
    xmlrpc_c::methodPtr group_allocate(new GroupAllocate());
    xmlrpc_c::methodPtr template_allocate(new TemplateAllocate());
    xmlrpc_c::methodPtr host_allocate(new HostAllocate());
    xmlrpc_c::methodPtr user_allocate(new  UserAllocate());

    // Delete Methods
    xmlrpc_c::methodPtr host_delete(new HostDelete());
    xmlrpc_c::methodPtr template_delete(new TemplateDelete());
    xmlrpc_c::methodPtr group_delete(new GroupDelete());
    xmlrpc_c::methodPtr vn_delete(new VirtualNetworkDelete());
    xmlrpc_c::methodPtr user_delete(new UserDelete());
    xmlrpc_c::methodPtr image_delete(new ImageDelete());

    // Info Methods
    xmlrpc_c::methodPtr vm_info(new VirtualMachineInfo());
    xmlrpc_c::methodPtr host_info(new HostInfo());
    xmlrpc_c::methodPtr template_info(new TemplateInfo());
    xmlrpc_c::methodPtr group_info(new GroupInfo());
    xmlrpc_c::methodPtr vn_info(new VirtualNetworkInfo());
    xmlrpc_c::methodPtr user_info(new UserInfo());
    xmlrpc_c::methodPtr image_info(new ImageInfo());

    // PoolInfo Methods
    xmlrpc_c::methodPtr hostpool_info(new HostPoolInfo());
    xmlrpc_c::methodPtr grouppool_info(new GroupPoolInfo());
    xmlrpc_c::methodPtr userpool_info(new UserPoolInfo());

    // PoolInfo Methods with Filtering
    xmlrpc_c::methodPtr vm_pool_info(new VirtualMachinePoolInfo());
    xmlrpc_c::methodPtr template_pool_info(new TemplatePoolInfo());
    xmlrpc_c::methodPtr vnpool_info(new VirtualNetworkPoolInfo());
    xmlrpc_c::methodPtr imagepool_info(new ImagePoolInfo());

     //added by shenxy 20120227
    xmlrpc_c::methodPtr vm_pool_statistic(new VirtualMachinePoolStatistic());

    // Host Methods
    xmlrpc_c::methodPtr host_enable(new HostEnable());

    // Image Methods
    xmlrpc_c::methodPtr image_persistent(new ImagePersistent());
    xmlrpc_c::methodPtr image_enable(new ImageEnable());
    xmlrpc_c::methodPtr image_chtype(new ImageChangeType());

    // Chown Methods
    xmlrpc_c::methodPtr vm_chown(new VirtualMachineChown());
    xmlrpc_c::methodPtr template_chown(new TemplateChown());
    xmlrpc_c::methodPtr vn_chown(new VirtualNetworkChown());
    xmlrpc_c::methodPtr image_chown(new ImageChown());
    xmlrpc_c::methodPtr user_chown(new UserChown());

    // Chmod Methods
    xmlrpc_c::methodPtr vm_chmod(new VirtualMachineChmod());
    xmlrpc_c::methodPtr template_chmod(new TemplateChmod());
    xmlrpc_c::methodPtr vn_chmod(new VirtualNetworkChmod());
    xmlrpc_c::methodPtr image_chmod(new ImageChmod());

    // ACL Methods
    xmlrpc_c::methodPtr acl_addrule(new AclAddRule());
    xmlrpc_c::methodPtr acl_delrule(new AclDelRule());
    xmlrpc_c::methodPtr acl_info(new AclInfo());

    /* VM related methods  */
    RequestManagerRegistry.addMethod("one.vm.deploy", vm_deploy);
    RequestManagerRegistry.addMethod("one.vm.action", vm_action);
    RequestManagerRegistry.addMethod("one.vm.migrate", vm_migrate);
    RequestManagerRegistry.addMethod("one.vm.savedisk", vm_savedisk);
    RequestManagerRegistry.addMethod("one.vm.allocate", vm_allocate);
    RequestManagerRegistry.addMethod("one.vm.info", vm_info);
    RequestManagerRegistry.addMethod("one.vm.chown", vm_chown);
    RequestManagerRegistry.addMethod("one.vm.chmod", vm_chmod);
    //added by shenxy 20120227
    RequestManagerRegistry.addMethod("one.backup.info", backup_info);
    RequestManagerRegistry.addMethod("one.backup.delete", vm_backupdelete);
    RequestManagerRegistry.addMethod("one.backupdisk.info", backupdisk_info);
    RequestManagerRegistry.addMethod("one.vm.backup", vm_backup);
    RequestManagerRegistry.addMethod("one.vm.recover", vm_recover);
    RequestManagerRegistry.addMethod("one.vm.backupdisk", vm_backupdisk);
    RequestManagerRegistry.addMethod("one.vm.changetemplate", vm_changetemplate);
    RequestManagerRegistry.addMethod("one.vm.dynamicmount", vm_dynamicmount);

    RequestManagerRegistry.addMethod("one.vmpool.info", vm_pool_info);
    //added by shenxy 20120227
    RequestManagerRegistry.addMethod("one.vmpool.statistic",vm_pool_statistic);

    /* VM Template related methods*/
    RequestManagerRegistry.addMethod("one.template.update", template_update);
    RequestManagerRegistry.addMethod("one.template.instantiate",template_instantiate);
    RequestManagerRegistry.addMethod("one.template.allocate",template_allocate);
    RequestManagerRegistry.addMethod("one.template.delete", template_delete);
    RequestManagerRegistry.addMethod("one.template.info", template_info);
    RequestManagerRegistry.addMethod("one.template.chown", template_chown);
    RequestManagerRegistry.addMethod("one.template.chmod", template_chmod);

    RequestManagerRegistry.addMethod("one.templatepool.info",template_pool_info);

    /* Host related methods*/
    RequestManagerRegistry.addMethod("one.host.enable", host_enable);
    RequestManagerRegistry.addMethod("one.host.update", host_update);
    RequestManagerRegistry.addMethod("one.host.allocate", host_allocate);
    RequestManagerRegistry.addMethod("one.host.delete", host_delete);
    RequestManagerRegistry.addMethod("one.host.info", host_info);

    RequestManagerRegistry.addMethod("one.hostpool.info", hostpool_info);

    /* Group related methods */
    RequestManagerRegistry.addMethod("one.group.allocate",  group_allocate);
    RequestManagerRegistry.addMethod("one.group.delete",    group_delete);
    RequestManagerRegistry.addMethod("one.group.info",      group_info);

    RequestManagerRegistry.addMethod("one.grouppool.info",  grouppool_info);

    /* Network related methods*/
    RequestManagerRegistry.addMethod("one.vn.addleases", vn_addleases);
    RequestManagerRegistry.addMethod("one.vn.rmleases", vn_rmleases);
    RequestManagerRegistry.addMethod("one.vn.hold", vn_hold);
    RequestManagerRegistry.addMethod("one.vn.release", vn_release);
    RequestManagerRegistry.addMethod("one.vn.allocate", vn_allocate);
    RequestManagerRegistry.addMethod("one.vn.update", vn_update);
    RequestManagerRegistry.addMethod("one.vn.delete", vn_delete);
    RequestManagerRegistry.addMethod("one.vn.info", vn_info);
    RequestManagerRegistry.addMethod("one.vn.chown", vn_chown);
    RequestManagerRegistry.addMethod("one.vn.chmod", vn_chmod);

    RequestManagerRegistry.addMethod("one.vnpool.info", vnpool_info);

    /* User related methods*/
    RequestManagerRegistry.addMethod("one.user.allocate", user_allocate);
    RequestManagerRegistry.addMethod("one.user.update", user_update);
    RequestManagerRegistry.addMethod("one.user.delete", user_delete);
    RequestManagerRegistry.addMethod("one.user.info", user_info);
    RequestManagerRegistry.addMethod("one.user.passwd", user_change_password);
    RequestManagerRegistry.addMethod("one.user.chgrp", user_chown);
    RequestManagerRegistry.addMethod("one.user.chauth", user_change_auth);

    RequestManagerRegistry.addMethod("one.userpool.info", userpool_info);

    /* Image related methods*/
    RequestManagerRegistry.addMethod("one.image.persistent", image_persistent);
    RequestManagerRegistry.addMethod("one.image.enable", image_enable);
    RequestManagerRegistry.addMethod("one.image.update", image_update);
    RequestManagerRegistry.addMethod("one.image.allocate", image_allocate);
    RequestManagerRegistry.addMethod("one.image.delete", image_delete);
    RequestManagerRegistry.addMethod("one.image.info", image_info);
    RequestManagerRegistry.addMethod("one.image.chown", image_chown);
    RequestManagerRegistry.addMethod("one.image.chmod", image_chmod);
    RequestManagerRegistry.addMethod("one.image.chtype", image_chtype);

    RequestManagerRegistry.addMethod("one.imagepool.info", imagepool_info);

    /* ACL related methods */
    RequestManagerRegistry.addMethod("one.acl.addrule", acl_addrule);
    RequestManagerRegistry.addMethod("one.acl.delrule", acl_delrule);
    RequestManagerRegistry.addMethod("one.acl.info",    acl_info);
};

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */


text:
const { text } = require('../../tools/domutil');

module.exports = {
  selector: '.snowreport_sponsorarea:nth-child(2) table tbody tr',
  parse: {
    name: 0,
    status: function(node) {
      let src = text(node, { child: '1/0', attribute: 'src' });
      return src.includes('cross') ? 'closed' : 'open';
    }
  }
};


text:
<?php
// https://github.com/doctrine/DoctrineORMModule/blob/master/docs/configuration.md
// https://github.com/doctrine/DoctrineORMModule/issues/122
// http://symfony.com/doc/current/cookbook/doctrine/multiple_entity_managers.html
// http://dan-homorodean.blogspot.com/2013/03/zf2-with-doctrineormmodule-using.html
return array(
    'doctrine' => array(
        'connection' => array(
            'orm_default' => array(
                'driverClass' => 'Doctrine\DBAL\Driver\PDOMySql\Driver',
                'params' => array(
                    'host' => 'localhost',
                    'port' => '3306',
                    'user' => 'root',
                    'password' => '1',
                    'dbname' => 'zf2tutorial',
                )
            ),
            'orm_customer' => array(
                'driverClass' => 'Doctrine\DBAL\Driver\PDOMySql\Driver',
                'params' => array(
                    'host' => 'localhost',
                    'port' => '3306',
                    'user' => 'root',
                    'password' => '1',
                    'dbname' => 'customer',
                )
            ),
        )
    )
);


text:
The runtime state for a container is persisted on disk so that external tools can consume and act on this information.
The runtime state is stored in a JSON encoded file.
It is recommended that this file is stored in a temporary filesystem so that it can be removed on a system reboot.
On Linux based systems the state information should be stored in `/run/opencontainer/containers`.
The directory structure for a container is `/run/opencontainer/containers/<containerID>/state.json`.
By providing a default location that container state is stored external applications can find all containers running on a system.

* **version** (string) Version of the OCI specification used when creating the container.
* **id** (string) ID is the container's ID.
* **pid** (int) Pid is the ID of the main process within the container.
* **root** (string) Root is the path to the container's bundle directory.

The ID is provided in the state because hooks will be executed with the state as the payload.
This allows the hook to perform clean and teardown logic after the runtime destroys its own state.

The root directory to the bundle is provided in the state so that consumers can find the container's configuration and rootfs where it is located on the host's filesystem.

*Example*

```json
{
    "id": "oc-container",
    "pid": 4422,
    "root": "/containers/redis"
}
```

## Lifecycle

### Create

Creates the container: file system, namespaces, cgroups, capabilities.

### Start (process)

Runs a process in a container.
Can be invoked several times.

### Stop (process)

Not sure we need that from runc cli.
Process is killed from the outside.

This event needs to be captured by runc to run onstop event handlers.

## Hooks

See [runtime configuration for hooks](./runtime-config.md)


text:
import requests
import sys
def login():
	s = requests.Session()
	login = {'email': input("Enter your email> "), 'password': input("Enter your password> ")}
	try:
		r = s.post("https://overcast.fm/login", data=login)
	except requests.exceptions.ConnectionError:
		print("You are not connected to the Internet!")
		exit()
	print("Your UUID is : %s" % s.cookies["o"])
	f = open("%s\\UUID.txt" % sys.path[0],"w")
	f.write(s.cookies['o'])
	f.close()


text:
const int CEditor::defaultBoxMarginDividor = 4;

CEditor::CEditor()
    : menu( 0 ), defaultObjectColor( RGB( 100, 90, 80 ) )
{}

bool CEditor::RegisterClass()
{
    WNDCLASSEX windowClass;
    ::ZeroMemory( &windowClass, sizeof( windowClass ) );
    windowClass.cbSize = sizeof( WNDCLASSEX );
    windowClass.lpfnWndProc = CEditor::windowProc;
    windowClass.hInstance = GetModuleHandle( 0 );
    windowClass.lpszClassName = L"CEditor";
    windowClass.hbrBackground = (HBRUSH)GetStockObject( GRAY_BRUSH );
    windowClass.lpszMenuName = MAKEINTRESOURCE( IDR_MENU1 );
    return (::RegisterClassEx( &windowClass ) != 0);
}

bool CEditor::Create()
{
    handle = CreateWindowEx( 0, L"CEditor", L"My Window", WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, GetModuleHandle( 0 ), this );

    createToolbar();

    return (handle != 0);
}

void CEditor::Show( int cmdShow )
{
    ShowWindow( handle, cmdShow );
    renderingWindow.Show( cmdShow );
    ShowWindow( setFontButton, cmdShow );
    ShowWindow( saveTextButton, cmdShow );
    ShowWindow( setColorButton, cmdShow );
    ShowWindow( addScriptButton, cmdShow );
}

std::shared_ptr<CStage>& CEditor::GetStage()
{
    return stage;
}

void CEditor::SetStage( std::shared_ptr<CStage> stage_ )
{
    stage = stage_;
    renderingWindow.SetStage( stage_ );
}

void CEditor::OnDestroy()
{
    DestroyMenu( menu );
    PostQuitMessage( 0 );
}

void CEditor::OnNCCreate( HWND _handle )
{
    handle = _handle;
}

void CEditor::OnCreate()
{
    editControl.Create( handle );
    CEditorWindow::RegisterClass();
    menu = LoadMenu( GetModuleHandle( 0 ), MAKEINTRESOURCE( IDR_MENU1 ) );
    renderingWindow.Create( handle );
    setFontButton = CreateWindow( L"BUTTON", L"Set Font", WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,
        10, 10, 100, 100, handle, (HMENU)IDC_MAIN_BUTTON,
        *(HINSTANCE*)GetWindowLongPtr( handle, GWLP_HINSTANCE ), NULL );
    saveTextButton = CreateWindow( L"BUTTON", L"Save Text", WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,
        10, 10, 100, 100, handle, (HMENU)IDC_MAIN_BUTTON,
        *(HINSTANCE*)GetWindowLongPtr( handle, GWLP_HINSTANCE ), NULL );
    setColorButton = CreateWindow( L"BUTTON", L"Set Color", WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,
        10, 10, 100, 100, handle, (HMENU)IDC_MAIN_BUTTON,
        *(HINSTANCE*)GetWindowLongPtr( handle, GWLP_HINSTANCE ), NULL );
    deleteColorButton = CreateWindow( L"BUTTON", L"Delete background", WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,
        10, 10, 100, 100, handle, (HMENU)IDC_MAIN_BUTTON,
        *(HINSTANCE*)GetWindowLongPtr( handle, GWLP_HINSTANCE ), NULL );
    addScriptButton = CreateWindow( L"BUTTON", L"Add Script", WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,
        10, 10, 100, 100, handle, (HMENU)IDC_MAIN_BUTTON,
        *(HINSTANCE*)GetWindowLongPtr( handle, GWLP_HINSTANCE ), NULL );

    EnableWindow( editControl.GetHandle(), false );
    EnableWindow( setFontButton, false );
    EnableWindow( saveTextButton, false );
    EnableWindow( setColorButton, false );
    EnableWindow( deleteColorButton, false );
    EnableWindow( addScriptButton, false );

}

CEditor* CEditor::GetWindowByHandle( HWND handle )
{
    return reinterpret_cast<CEditor*>(GetWindowLongPtr( handle, GWLP_USERDATA ));
}

void CEditor::SetActiveId( const IdType& id )
{
    activeId = id;
    wchar_t firstLetter = id[0];
    if( firstLetter == L't' ) {
        EnableWindow( setFontButton, true );
        EnableWindow( setColorButton, true );
        EnableWindow( deleteColorButton, false );
        EnableWindow( addScriptButton, true );
    } else {
        if( id == CObjectIdGenerator::GetEmptyId() ) {
            EnableWindow( setFontButton, false );
            EnableWindow( setColorButton, false );
            EnableWindow( deleteColorButton, false );
            EnableWindow( addScriptButton, false );
        } else {
            EnableWindow( setFontButton, false );
            EnableWindow( setColorButton, true );
            EnableWindow( deleteColorButton, true );
            EnableWindow( addScriptButton, true );
        }
    }
}

HBITMAP CEditor::MakeBitMapTransparent( HBITMAP hbmSrc )
{
    HDC hdcSrc, hdcDst;
    BITMAP bm;
    COLORREF clrTP, clrBK;
    HBITMAP hbmOld, hbmNew = NULL;

    if( (hdcSrc = CreateCompatibleDC( NULL )) != NULL ) {
        if( (hdcDst = CreateCompatibleDC( NULL )) != NULL ) {
            int nRow, nCol;
            GetObject( hbmSrc, sizeof( bm ), &bm );
            hbmOld = (HBITMAP)SelectObject( hdcSrc, hbmSrc );
            hbmNew = CreateBitmap( bm.bmWidth, bm.bmHeight, bm.bmPlanes, bm.bmBitsPixel, NULL );
            SelectObject( hdcDst, hbmNew );

            BitBlt( hdcDst, 0, 0, bm.bmWidth, bm.bmHeight, hdcSrc, 0, 0, SRCCOPY );

            clrTP = GetPixel( hdcDst, 1, 1 );// Get color of first pixel at 0,0
            clrBK = GetSysColor( COLOR_MENU );// Get the current background color of the menu

            for( nRow = 0; nRow < bm.bmHeight; nRow++ ) {// work our way through all the pixels changing their color
                for( nCol = 0; nCol < bm.bmWidth; nCol++ ) {// when we hit our set transparency color.
                    if( GetPixel( hdcDst, nCol, nRow ) == clrTP ) {
                        SetPixel( hdcDst, nCol, nRow, clrBK );
                    }
                }
            }
            DeleteDC( hdcDst );
        }
        DeleteDC( hdcSrc );
    }
    return hbmNew;// return our transformed bitmap.
}

HBITMAP CEditor::loadTransparentBitmap( HINSTANCE hInstance, int resource )
{
    return MakeBitMapTransparent( LoadBitmap( hInstance, MAKEINTRESOURCE( resource ) ) );
}

void CEditor::createToolbar()
{

    // Declare and initialize local constants.
    const int bitmapSize = 24;

    HINSTANCE hInstance = ::GetModuleHandle( 0 );

    handleToolbar = CreateToolbarEx( handle, WS_CHILD | WS_VISIBLE | CCS_TOP, 1,
        0, HINST_COMMCTRL, IDB_STD_LARGE_COLOR, NULL, 0, 0, 0, 0, 0, sizeof( TBBUTTON ) );

    //Enable multiple image lists
    SendMessage( handleToolbar, CCM_SETVERSION, static_cast<WPARAM>(5), 0 );

    //Add icons from default imagelist
    TBBUTTON tbb_buildin[] = {
        { STD_FILENEW, ID_FILE_NEW, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, reinterpret_cast<INT_PTR>(L"New") },
        { STD_FILEOPEN, ID_FILE_OPEN, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, reinterpret_cast<INT_PTR>(L"Open") },
        { STD_FILESAVE, ID_FILE_SAVE, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, reinterpret_cast<INT_PTR>(L"Save") },
    };
    SendMessage( handleToolbar, static_cast<UINT>(TB_ADDBUTTONS), _countof( tbb_buildin ), (LPARAM)&tbb_buildin );

    //Create custom imagelist
    HIMAGELIST hImageList = ImageList_Create( bitmapSize, bitmapSize, ILC_COLOR16 | ILC_MASK, 0, 0 );
    ImageList_Add( hImageList, loadTransparentBitmap( hInstance, IDB_RECTANGLE_24 ), NULL );
    ImageList_Add( hImageList, loadTransparentBitmap( hInstance, IDB_ELLIPSE_24 ), NULL );
    ImageList_Add( hImageList, loadTransparentBitmap( hInstance, IDB_TEXTBOX_24 ), NULL );
    ImageList_Add( hImageList, loadTransparentBitmap( hInstance, IDB_PLAY_24 ), NULL );
    ImageList_Add( hImageList, loadTransparentBitmap( hInstance, IDB_DELETE_24 ), NULL );
    ImageList_Add( hImageList, loadTransparentBitmap( hInstance, IDB_EDIT_24 ), NULL );
    SendMessage( handleToolbar, TB_SETIMAGELIST, static_cast<WPARAM>(1), (LPARAM)hImageList );

    TBBUTTON tbb[] =
    {
        { MAKELONG( 0, 1 ), ID_ADD_RECTANGLE, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, reinterpret_cast<INT_PTR>(L"Rectangle") },
        { MAKELONG( 1, 1 ), ID_ADD_ELLIPSE, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, reinterpret_cast<INT_PTR>(L"Ellipse") },
        { MAKELONG( 2, 1 ), ID_ADD_TEXT, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, reinterpret_cast<INT_PTR>(L"Textbox") },
        { MAKELONG( 3, 1 ), ID_PLAY_LAUNCHPLAYER, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, reinterpret_cast<INT_PTR>(L"Launch") },
        { MAKELONG( 4, 1 ), ID_DELETE_OBJECT, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, reinterpret_cast<INT_PTR>(L"Delete") },
        { MAKELONG( 5, 1 ), ID_EDIT, TBSTATE_ENABLED, TBSTYLE_BUTTON, {0}, 0, reinterpret_cast<INT_PTR>(L"Edit script") },
    };
    SendMessage( handleToolbar, static_cast<UINT>(TB_ADDBUTTONS), _countof( tbb ), reinterpret_cast<LPARAM>(&tbb) );

    SendMessage( handleToolbar, TB_AUTOSIZE, 0, 0 );
    ShowWindow( handleToolbar, TRUE );
}

void CEditor::OnSize()
{
    RECT rect;
    int middleX, nWidth, nHeight;
    int RELATIVE_WIDTH = 3;
    int RELATIVE_HEIGHT = 4;
    int RELATIVE_TOOLBAR = 20;
    ::GetClientRect( handle, &rect );
    middleX = (rect.left + rect.right) / RELATIVE_HEIGHT;
    nWidth = (rect.right - rect.left) * RELATIVE_WIDTH / RELATIVE_HEIGHT;

    RECT toolbarRect;
    ::GetClientRect( handleToolbar, &toolbarRect );
    int currentTop = rect.top + (toolbarRect.bottom - toolbarRect.top);
    nHeight = (rect.bottom - currentTop);

    SetWindowPos( renderingWindow.GetHandle(), HWND_TOP, middleX, currentTop, nWidth, nHeight, 0 );
    int widthOfButton = nWidth / RELATIVE_WIDTH;
    int yOfButton = nHeight * RELATIVE_WIDTH / RELATIVE_HEIGHT;
    int cyOfButton = nHeight / RELATIVE_TOOLBAR;
    SetWindowPos( editControl.GetHandle(), HWND_TOP, rect.left, currentTop, widthOfButton, yOfButton, 0 );
    SetWindowPos( setFontButton, HWND_TOP, rect.left, currentTop + yOfButton, widthOfButton, cyOfButton, 0 );
    SetWindowPos( saveTextButton, HWND_TOP, rect.left, currentTop + yOfButton + cyOfButton, widthOfButton, cyOfButton, 0 );
    SetWindowPos( setColorButton, HWND_TOP, rect.left, currentTop + yOfButton + cyOfButton * 2, widthOfButton, cyOfButton, 0 );
    SetWindowPos( deleteColorButton, HWND_TOP, rect.left, currentTop + yOfButton + cyOfButton * 3, widthOfButton, cyOfButton, 0 );
    SetWindowPos( addScriptButton, HWND_TOP, rect.left, currentTop + yOfButton + cyOfButton * 4, widthOfButton, cyOfButton, 0 );

    SendMessage( handleToolbar, TB_AUTOSIZE, 0, 0 );
}

void CEditor::GetText()
{
    int length = static_cast<int>(SendMessage( editControl.GetHandle(), WM_GETTEXTLENGTH, 0, 0 ));
    wchar_t *text = new wchar_t[length + 1];
    SendMessage( editControl.GetHandle(), WM_GETTEXT, length + 1, reinterpret_cast<LPARAM>(text) );
    //add functions here
    delete[] text;
}

void CEditor::OnCommandMenu( WPARAM wParam, LPARAM lParam )
{
    switch LOWORD( wParam )
    {
    case ID_ADD_RECTANGLE:
    {
        addObject( std::make_shared<CRectangleObject>( defaultObjectColor, generateDefaultBox(), 0 ) );
        break;
    }
    case ID_ADD_ELLIPSE:
    {
        addObject( std::make_shared<CEllipseObject>( defaultObjectColor, generateDefaultBox(), 0 ) );
        break;
    }
    case ID_ADD_TEXT:
    {
        addObject( std::make_shared<CTextBoxObject>( defaultObjectColor, generateDefaultBox(), 0, L"Text" ) );
        break;
    }
    case ID_FILE_NEW:
    {
        activeId = CObjectIdGenerator::GetEmptyId();
        *stage = CStage();
        renderingWindow.Redraw();
        break;
    }
    case ID_FILE_OPEN:
    {
        OnOpen();
        break;
    }
    case ID_FILE_SAVE:
    {
        OnSave();
        break;
    }
    case ID_PLAY_LAUNCHPLAYER:
    {
        CViewer viewer( *stage );
        if( viewer.Create() ) {
            const CViewerWindow& viewerWindow = viewer.GetViewerWindow();
            HWND viewerHandle = viewerWindow.GetHandle();
            MSG message;
            BOOL getMessageResult = 0;
            while( (getMessageResult = ::GetMessage( &message, viewerHandle, 0, 0 )) != 0 ) {
                if( getMessageResult == -1 ) {
                    break;
                }
                ::TranslateMessage( &message );
                ::DispatchMessage( &message );
            }
        }
        break;
    }
    case ID_EDIT:
    {

        CScriptEditor scriptEditor;

        if( scriptEditor.Create() ) {
            HWND scriptEditorWindow = scriptEditor.GetHandle();
            MSG message;
            BOOL getMessageResult = 0;
            while( (getMessageResult = GetMessage( &message, scriptEditorWindow, 0, 0 )) != 0 ) {
                if( getMessageResult == -1 ) {
                    break;
                }
                TranslateMessage( &message );
                DispatchMessage( &message );
            }
        }
        break;
    }
    case ID_DELETE_OBJECT:
    {
        stage->GetObjects().erase( activeId );
        SetActiveId( CObjectIdGenerator::GetEmptyId() );
        renderingWindow.Redraw();
        break;
    }
    case IDC_MAIN_BUTTON:
    {
        if( (HWND)lParam == saveTextButton ) {
            GetText();
        } else if( (HWND)lParam == setColorButton ) {
            onColorSelect();
        } else if( (HWND)lParam == deleteColorButton ) {
            onColorDelete();
        } else if( (HWND)lParam == addScriptButton ) {
            onFileSelect();
        } else if( (HWND)lParam == setFontButton ) {
            onFontSelect();
        }
        break;
    }
    }
}

void CEditor::OnCommand( WPARAM wParam, LPARAM lParam )
{
    if( HIWORD( wParam ) == 0 ) {
        OnCommandMenu( wParam, lParam );
        // return focus to the rendering window
        // now it can process mouse wheel again
        ::SetFocus( renderingWindow.GetHandle() );
    }
}

template<class ObjectClass>
void CEditor::addObject( std::shared_ptr<ObjectClass> object )
{
    bool isAdded = stage->AddObject( object->GetId(), object );
    if( isAdded ) {
        SetActiveId( object->GetId() );
    }
    renderingWindow.Redraw();
}

TBox CEditor::generateDefaultBox() const
{
    TBox box;
    RECT rect;
    GetWindowRect( renderingWindow.GetHandle(), &rect );
    box.right = 3 * (box.left = (rect.right - rect.left) / defaultBoxMarginDividor);
    box.bottom = 3 * (box.top = (rect.bottom - rect.top) / defaultBoxMarginDividor);
    return stage->GetViewPort().ConvertToModelCoordinates( box );
}

void CEditor::onColorSelect()
{
    CHOOSECOLOR chooseColor;
    static COLORREF customColors[16];
    ZeroMemory( &chooseColor, sizeof( chooseColor ) );
    chooseColor.lStructSize = sizeof( chooseColor );
    chooseColor.hwndOwner = handle;
    chooseColor.lpCustColors = reinterpret_cast<LPDWORD>(customColors);
    chooseColor.Flags = CC_FULLOPEN | CC_RGBINIT;
    chooseColor.rgbResult = stage->GetObjectById( activeId )->GetColor();
    if( ::ChooseColor( &chooseColor ) ) {
        stage->GetObjectById( activeId )->SetColor( chooseColor.rgbResult );
        renderingWindow.Redraw();
    }
}

void CEditor::onColorDelete()
{
    stage->GetObjectById( activeId )->SetColor( noColor );
    renderingWindow.Redraw();
}

void CEditor::onFontSelect()
{
    CHOOSEFONT chooseFont;
    static LOGFONT logFont;
    HFONT hFont;
    static DWORD rgbCurrent;
    ZeroMemory( &chooseFont, sizeof( chooseFont ) );
    chooseFont.lStructSize = sizeof( chooseFont );
    chooseFont.hwndOwner = handle;
    chooseFont.lpLogFont = &logFont;
    chooseFont.rgbColors = rgbCurrent;
    chooseFont.Flags = CF_SCREENFONTS | CF_EFFECTS;
    if( ::ChooseFont( &chooseFont ) ) {
        hFont = CreateFontIndirect( chooseFont.lpLogFont );
        reinterpret_cast<CTextBoxObject*>(stage->GetObjectById( activeId ).get())->SetColor( chooseFont.rgbColors );
        reinterpret_cast<CTextBoxObject*>(stage->GetObjectById( activeId ).get())->SetFont( hFont );
        renderingWindow.Redraw();
    }
}

void CEditor::OnOpen()
{
    OPENFILENAME openInfo;
    memset( &openInfo, 0, sizeof( openInfo ) );
    openInfo.lStructSize = sizeof( OPENFILENAME );
    openInfo.hwndOwner = handle;
    openInfo.lpstrFilter = L"PS project (*.ps)\0*.ps\0All Files (*.*)\0*.*\0\0";
    openInfo.nFilterIndex = 1;
    openInfo.nMaxFile = 1024;
    std::unique_ptr<WCHAR[]> filenamePtr( new WCHAR[openInfo.nMaxFile] );
    memset( filenamePtr.get(), 0, openInfo.nMaxFile );
    openInfo.lpstrFile = filenamePtr.get();
    openInfo.lpstrTitle = L"Open project";
    openInfo.lpstrDefExt = L".ps";
    openInfo.Flags = OFN_PATHMUSTEXIST | OFN_EXPLORER;
    if( ::GetOpenFileName( &openInfo ) ) {
        std::wstring filename( openInfo.lpstrFile );
        std::wifstream openStream( filename );
        std::wstring content( (std::istreambuf_iterator<wchar_t>( openStream )),
            (std::istreambuf_iterator<wchar_t>()) );
        JsonObjectDescription description =  CJsonWorker::GetNextObjectDescription( content );
        assert( description.type == JsonObjectType::MAP );
        CJsonMap stageNewJson( description.name, description.body );
        *stage = *CJsonConverter::FromJson( stageNewJson );
        renderingWindow.Redraw();
    }
}

void CEditor::OnSave() const
{
    OPENFILENAME filename;
    filename.lStructSize = sizeof( filename );
    filename.hwndOwner = handle;
    filename.hInstance = GetModuleHandleW( nullptr );
    filename.lpstrFilter = L"PS project (*.ps)\0*.ps\0All Files (*.*)\0*.*\0\0";
    filename.lpstrCustomFilter = 0;
    filename.nFilterIndex = 1;
    filename.nMaxFile = 1024;
    std::unique_ptr<wchar_t[]> name( new wchar_t[filename.nMaxFile] );
    filename.lpstrFile = name.get();
    filename.lpstrFile[0] = 0;
    filename.lpstrInitialDir = 0;
    filename.lpstrTitle = L"Save project";
    filename.nMaxFileTitle = 0;
    filename.lpstrDefExt = L".ps";
    filename.lCustData = 0;
    filename.lpfnHook = 0;
    filename.lpTemplateName = 0;
    filename.nFileOffset = 0;
    filename.nFileExtension = 0;
    filename.Flags = OFN_OVERWRITEPROMPT;

    if( ::GetSaveFileName( &filename ) ) {
        std::wofstream saveStream( filename.lpstrFile, std::ofstream::out );
        saveStream << stage->ToWString();
        saveStream.close();
    }
}

void CEditor::onFileSelect()
{
    OPENFILENAME filename;
    filename.lStructSize = sizeof( filename );
    filename.hwndOwner = handle;
    filename.hInstance = GetModuleHandleW( nullptr );
    filename.lpstrFilter = L"Python script (*.py)\0*.py\0All Files (*.*)\0*.*\0\0";
    filename.lpstrCustomFilter = 0;
    filename.nFilterIndex = 1;
    filename.nMaxFile = 1024;
    std::unique_ptr<wchar_t[]> name( new wchar_t[filename.nMaxFile] );
    filename.lpstrFile = name.get();
    filename.lpstrFile[0] = 0;
    filename.lpstrInitialDir = 0;
    filename.lpstrTitle = L"Add script";
    filename.nMaxFileTitle = 0;
    filename.lpstrDefExt = L".py";
    filename.lCustData = 0;
    filename.lpfnHook = 0;
    filename.lpTemplateName = 0;
    filename.nFileOffset = 0;
    filename.nFileExtension = 0;
    filename.Flags = OFN_FILEMUSTEXIST;

    if( ::GetOpenFileName( &filename ) ) {
        CScript script( filename.lpstrFile ); //Add choice of event type
        stage->addScript( EventType::EventClick, activeId, script );
        //stage->GetObjectById( activeId )->AddScript( EventType::EventClick, script );
    }
}

LRESULT CEditor::windowProc( HWND handle, UINT message, WPARAM wParam, LPARAM lParam )
{
    switch( message ) {
    case WM_NCCREATE:
    {
        CEditor* window = (CEditor*)((CREATESTRUCT*)lParam)->lpCreateParams;
        SetLastError( 0 );
        SetWindowLongPtr( handle, GWLP_USERDATA, (LONG_PTR)window );
        if( GetLastError() != 0 ) {
            return GetLastError();
        }
        window->OnNCCreate( handle );
        return DefWindowProc( handle, message, wParam, lParam );
    }
    case WM_CREATE:
    {
        CEditor* window = (CEditor*)GetWindowLongPtr( handle, GWLP_USERDATA );
        window->OnCreate();
        return DefWindowProc( handle, message, wParam, lParam );
    }
    case WM_SIZE:
    {
        CEditor* window = (CEditor*)GetWindowLongPtr( handle, GWLP_USERDATA );
        window->OnSize();
        return DefWindowProc( handle, message, wParam, lParam );
    }
    case WM_COMMAND:
    {
        CEditor* window = (CEditor*)GetWindowLongPtr( handle, GWLP_USERDATA );
        window->OnCommand( wParam, lParam );
        return DefWindowProc( handle, message, wParam, lParam );
    }
    case WM_DESTROY:
    {
        CEditor* window = (CEditor*)GetWindowLongPtr( handle, GWLP_USERDATA );
        window->OnDestroy();
        return 0;
    }
    default:
        return DefWindowProc( handle, message, wParam, lParam );
    }
}


text:
<?php

namespace FOS\UserBundle\Tests\Form\Type;

use FOS\UserBundle\Form\Type\ResettingFormType;
use FOS\UserBundle\Tests\TestUser;

class ResettingFormTypeTest extends ValidatorExtensionTypeTestCase
{
    public function testSubmit()
    {
        $user = new TestUser();

        $form = $this->factory->create(new ResettingFormType('FOS\UserBundle\Tests\TestUser'), $user);
        $formData = array(
            'plainPassword' => array(
                'first'         => 'test',
                'second'        => 'test',
            )
        );
        $form->submit($formData);

        $this->assertTrue($form->isSynchronized());
        $this->assertEquals($user, $form->getData());
        $this->assertEquals('test', $user->getPlainPassword());
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Beih. Nova Hedwigia 79: 310 (1984)

#### Original name
Lichen sabuletorum Schreb.

### Remarks
null


text:
namespace NetworkController.Client.Logic.DataTypes.Interfaces
{
    public interface IDeltaSliderState : ISliderState, IMeasuredDeltaState
    {
        /// <summary>
        /// The last value of the delta
        /// </summary>
        int LastValue { get; set; }
    }
}


text:
title: Cake joins the .NET foundation
category: Announcement
author: devlead
---
It's been an amazing journey since the push of the first public commit of Cake in May 2014, in just two years we've seen 72 releases, had more than 60 contributors, over a thousand issues and pull requests proposed. And on top of that a small eco system of more than 50 community provided Cake addins.

So firstly a huge thank you to all our contributors and adopters! This wouldn't have been possible without you! It's truly amazing to see the increase in contribution and adoption of Cake.

Today we're really excited and happy to share that Cake is joining the .NET foundation!

So what does this mean for Cake? It'll still be maintained and governed by the same team as now, but with the support and guidance of the .NET foundation, ensuring the longevity of the project.

Read more about Cake joining on the .NET foundation [blog](http://www.dotnetfoundation.org/blog/cake-welcome).

<!--excerpt-->
__About the .NET Foundation__

The .NET Foundation is an independent organization to foster open development and collaboration around the .NET ecosystem. It serves as a forum for community and commercial developers alike to broaden and strengthen the future of the .NET ecosystem by promoting openness and community participation to encourage innovation.

Learn more about the .NET foundation at [www.dotnetfoundation.org](http://www.dotnetfoundation.org/)

![DNF+Cake](https://cloud.githubusercontent.com/assets/1647294/15925895/60865fec-2e39-11e6-8d39-189d35d481d9.png)


text:
//=======================================================================
// Copyright (c) 2014-2020 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

/*!
 * \file
 * \brief EGBLAS wrappers for the scalar_add operation.
 */

#pragma once

#ifdef ETL_EGBLAS_MODE

#include "etl/impl/cublas/cuda.hpp"

#include <egblas.hpp>

#endif

namespace etl::impl::egblas {

#ifdef EGBLAS_HAS_SCALAR_SADD

static constexpr bool has_scalar_sadd = true;

/*!
 * \brief Adds the scalar beta to each element of the single-precision vector x
 * \param x The vector to add the scalar to (GPU pointer)
 * \param n The size of the vector
 * \param s The stride of the vector
 * \param beta The scalar to add
 */
inline void scalar_add(float* x, size_t n, size_t s, const float beta) {
    inc_counter("egblas");
    egblas_scalar_sadd(x, n, s, beta);
}

#else

static constexpr bool has_scalar_sadd = false;

#endif

#ifdef EGBLAS_HAS_SCALAR_DADD

static constexpr bool has_scalar_dadd = true;

/*!
 * \brief Adds the scalar beta to each element of the double-precision vector x
 * \param x The vector to add the scalar to (GPU pointer)
 * \param n The size of the vector
 * \param s The stride of the vector
 * \param beta The scalar to add
 */
inline void scalar_add(double* x, size_t n, size_t s, const double beta) {
    inc_counter("egblas");
    egblas_scalar_dadd(x, n, s, beta);
}

#else

static constexpr bool has_scalar_dadd = false;

#endif

#ifdef EGBLAS_HAS_SCALAR_CADD

static constexpr bool has_scalar_cadd = true;

/*!
 * \brief Adds the scalar beta to each element of the complex single-precision vector x
 * \param x The vector to add the scalar to (GPU pointer)
 * \param n The size of the vector
 * \param s The stride of the vector
 * \param beta The scalar to add
 */
inline void scalar_add(etl::complex<float>* x, size_t n, size_t s, const etl::complex<float> beta) {
    inc_counter("egblas");
    egblas_scalar_cadd(reinterpret_cast<cuComplex*>(x), n, s, complex_cast(beta));
}

/*!
 * \brief Adds the scalar beta to each element of the complex single-precision vector x
 * \param x The vector to add the scalar to (GPU pointer)
 * \param n The size of the vector
 * \param s The stride of the vector
 * \param beta The scalar to add
 */
inline void scalar_add(std::complex<float>* x, size_t n, size_t s, const std::complex<float> beta) {
    inc_counter("egblas");
    egblas_scalar_cadd(reinterpret_cast<cuComplex*>(x), n, s, complex_cast(beta));
}

#else

static constexpr bool has_scalar_cadd = false;

#endif

#ifdef EGBLAS_HAS_SCALAR_ZADD

static constexpr bool has_scalar_zadd = true;

/*!
 * \brief Adds the scalar beta to each element of the complex single-precision vector x
 * \param x The vector to add the scalar to (GPU pointer)
 * \param n The size of the vector
 * \param s The stride of the vector
 * \param beta The scalar to add
 */
inline void scalar_add(etl::complex<double>* x, size_t n, size_t s, const etl::complex<double> beta) {
    inc_counter("egblas");
    egblas_scalar_zadd(reinterpret_cast<cuDoubleComplex*>(x), n, s, complex_cast(beta));
}

/*!
 * \brief Adds the scalar beta to each element of the complex single-precision vector x
 * \param x The vector to add the scalar to (GPU pointer)
 * \param n The size of the vector
 * \param s The stride of the vector
 * \param beta The scalar to add
 */
inline void scalar_add(std::complex<double>* x, size_t n, size_t s, const std::complex<double> beta) {
    inc_counter("egblas");
    egblas_scalar_zadd(reinterpret_cast<cuDoubleComplex*>(x), n, s, complex_cast(beta));
}

#else

static constexpr bool has_scalar_zadd = false;

#endif

#ifndef ETL_EGBLAS_MODE

/*!
 * \brief Adds the scalar beta to each element of the single-precision vector x
 * \param x The vector to add the scalar to (GPU pointer)
 * \param n The size of the vector
 * \param s The stride of the vector
 * \param beta The scalar to add
 */
template <typename T>
inline void scalar_add([[maybe_unused]] T* x, [[maybe_unused]] size_t n, [[maybe_unused]] size_t s, [[maybe_unused]] const T beta) {
    cpp_unreachable("Invalid call to egblas::scalar_add");
}

#endif

} //end of namespace etl::impl::egblas


text:
package com.netflix.kayenta.prometheus.security;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.netflix.kayenta.prometheus.service.PrometheusRemoteService;
import com.netflix.kayenta.retrofit.config.RemoteService;
import com.netflix.kayenta.security.AccountCredentials;
import java.util.List;
import javax.validation.constraints.NotNull;
import lombok.Builder;
import lombok.Data;
import lombok.Singular;

@Builder
@Data
public class PrometheusNamedAccountCredentials
    implements AccountCredentials<PrometheusCredentials> {

  @NotNull private String name;

  @NotNull @Singular private List<Type> supportedTypes;

  @NotNull private PrometheusCredentials credentials;

  // The prometheus server location.
  @NotNull private RemoteService endpoint;

  @Override
  public String getType() {
    return "prometheus";
  }

  @JsonIgnore PrometheusRemoteService prometheusRemoteService;
}


text:
from functools import partial
from collections import OrderedDict

try:
    import shiboken
except ImportError:
    from PySide import shiboken
from PySide import QtGui, QtCore

from jukeboxcore.gui.main import JB_MainWindow

class WidgetToolTip(QtGui.QWidget):
    """A ToolTip that can be installed on a widget via :meth:`WidgetToolTip.install_tooltip`

    The tooltip is a selector for added widgets. The widgets are rendered to icons that are placed onto Buttons.
    If a button is clicked the widget receives focus.

    .. Warning:: Setting the layout after initialisation has no effect at the moment.

    There are a few properties and setters that can be changed. The affect might only take place after calling :meth:`WidgetToolTip.show`.
    Properties and setters:

      ::meth:`WidgetToolTip.alignment`: property for the alignment relative to the mouse
      ::meth:`WidgetToolTip.offset`: property for the offset relativ to the alignment
      ::meth:`WidgetToolTip.triggerevent`: property for the event that triggers the tooltip
      ::meth:`WidgetToolTip.setup_size`: setter for the size of one cell/button
      ::meth:`WidgetToolTip.setup_cyatimer`: setter for the time the widget waits before closing

    To use this tooltip for any widget that triggers a ToolTip event:

      1. Create the WidgetToolTip widget
      2. Install it on a widget
      3. Add Widgets to the WidgetToolTip

    Example::

      mainwidget = QtGui.QWidget()
      widget1 = QtGui.QWidget()
      widget2 = QtGui.QWidget()
      # Step 1 with the default parameters
      tooltip = WidgetToolTip(orientation=QtCore.Qt.Horizontal,
                              alignment=QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter,
                              offset=20,
                              parent=None,
                              flags=QtCore.Qt.CustomizeWindowHint)
      # Step 2
      tooltip.install_tooltip(mainwidget)
      # Step 3
      tooltip.add_widget(widget1)
      tooltip.add_widget(widget2)

    """

    def __init__(self, orientation=QtCore.Qt.Horizontal,
                 alignment=None,
                 offset=20,
                 interval=1000,
                 size=QtCore.QSize(160, 90),
                 triggerevent=QtCore.QEvent.ToolTip,
                 parent=None,
                 flags=QtCore.Qt.CustomizeWindowHint):  # hides title bar but gives a frames
        """Initialize the ToolTip in the given orientation with an optional parent and windowflags.

        :param orientation: the orientation of the tooltip. horizontal or vertical
        :type orientation: QtCore.Qt.Orientation
        :param parent: the parent of the widget
        :param alignment: affcts the positon of the popup relative to the mouse. If None, align left and vcenter is chosen
                          Use left, right, hcenter, top, bottom and vcenter only. Everything else will be ignored.
        :type alignment: QtCore.Qt.Alignment | None
        :param offset: The offset to the alignment in pixels
        :type offset: int
        :param interval: The time to wait for the tooltip to close in miliseconds
        :type interval: int
        :param size: The size of one cell/button
        :type size: QtCore.QSize
        :param triggerevent: The event that triggers the tooltip
        :type triggerevent: QtCore.QEvent.Type
        :type parent: QtGui.QWidget
        :param flags: the windowflags
        :type flags: QtCore.QtWindowFlags
        :raises: TypeError
        """
        super(WidgetToolTip, self).__init__(parent, flags)
        self._buttons = OrderedDict()
        self._triggerevent = triggerevent
        self._alignment = alignment
        self._offset = 20
        if alignment is None:
            self._alignment = QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter
        self.setup_layout(orientation)
        self.setup_size(size.width(), size.height())
        self.setup_cyatimer(interval)

    def setup_layout(self, orientation=None):
        """Setup the layout for the tooltip in the given orientation

        :param layout: the orentation of the layout
        :type layout: QtCore.Qt.Orientation | None
        :returns: None
        :rtype: None
        :raises: None
        """
        if orientation == QtCore.Qt.Horizontal or orientation is None:
            layout = QtGui.QHBoxLayout()
        elif orientation == QtCore.Qt.Vertical:
            layout = QtGui.QVBoxLayout()
        else:
            raise TypeError('Orientation is of wrong type! Allowed is QtCore.Qt.Horizontal and QtCore.Qt.Vertical. Given: %s' % orientation)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        self.setLayout(layout)

    def setup_size(self, width, height):
        """Set the width and height for one cell in the tooltip

        This is inderectly acomplished by setting the iconsizes for the buttons.

        :param width: the width of one cell, min. is 7 -> icon width = 0
        :type width: int
        :param height: the height of one cell, min. is 6 -> icon height = 0
        :type height: int
        :returns: None
        :rtype: None
        :raises: None
        """
        self._iconw = max(0, width - 7)
        self._iconh = max(0, height - 6)
        self.update_all_buttons()

    def setup_cyatimer(self, interval):
        """Setup the timer that will close the widget after the mouse left the widget for the time of interval

        :param interval: the time that the tooltip waits before it dissapears in milliseconds
        :type interval: int
        :returns: None
        :rtype: None
        :raises: None
        """
        self.cyatimer = QtCore.QTimer(self)
        self.cyatimer.setSingleShot(True)
        self.cyatimer.timeout.connect(self.hide)
        self._interval = interval

    def event(self, event):
        """Reimplementation of QWidget.event

        The widget is closed, when the window is deactivated.
        The widget is closed after the set interval if the mouse leaves the widget.
        The timer is stops when the mouse enters the widget before the interval ends.
        On show, the added widgets are rendered for the tooltip into buttons. The buttons
        are used to set the widget in focus.
        """
        if event.type() == QtCore.QEvent.WindowDeactivate:  # hide the tooltip
            self.cyatimer.stop()
            self.hide()
            return True
        if event.type() == QtCore.QEvent.Leave:  # start timer
            self.cyatimer.start(self._interval)
            return True
        if event.type() == QtCore.QEvent.Enter:  # reset/stop timer
            self.cyatimer.stop()
            return True
        if event.type() == QtCore.QEvent.Show:  # render the widgets
            self.cyatimer.stop()
            return True
        return super(WidgetToolTip, self).event(event)

    def create_button(self, widget):
        """Create a button that has the given widget rendered as an icon

        :param widget: the widget to render as icon
        :type widget: QtGui.QWidget
        :returns: the created button
        :rtype: QtGui.QAbstractButton
        :raises: None
        """
        btn = QtGui.QToolButton(self)
        btn.setIconSize(QtCore.QSize(self._iconw, self._iconh))
        self.update_button(btn, widget)
        return btn

    def update_button(self, button, widget):
        """Update the icon of the button with the given widget

        if the widget does not is invalid, it is deleted from the tooltip automatically.

        :param button: the button to update
        :type button: QtGui.QAbstractButton
        :param widget: the widget to render as icon
        :type widget: QtGui.QWidget
        :returns: None
        :rtype: None
        :raises: None
        """
        if not shiboken.isValid(widget):
            self.remove_widget(widget)
            return
        button.setIconSize(QtCore.QSize(self._iconw, self._iconh))
        pix = QtGui.QPixmap(widget.size())
        widget.render(pix)
        icon = QtGui.QIcon(pix)
        button.setIcon(icon)

    def update_all_buttons(self, ):
        """Update all buttons

        :returns: None
        :rtype: None
        :raises: None
        """
        for widget, button in self._buttons.items():
            self.update_button(button, widget)
        self.adjustSize()

    def focus_widget(self, checked=None, w=None):
        """Focus the given widget. Checked is ignored and only used as a slot for QAbstractButton.clicked.

        :param checked: The checked state of the button that was clicked
        :type checked: bool
        :param w: the widget to focus
        :type w: QtGui.QWidget
        :returns: None
        :raises: None
        """
        if w is None:
            return
        if w.isMinimized():
            w.showNormal()
        else:
            w.show()
        w.activateWindow()
        w.setFocus()

    def add_widget(self, widget):
        """Add the given widget to the tooltip

        :param widget: the widget to add
        :type widget: QtGui.QWidget
        :returns: None
        :rtype: None
        :raises: None
        """
        if self._buttons.get(widget):
            return
        btn = self.create_button(widget)
        cb = partial(self.focus_widget, w=widget)
        btn.clicked.connect(cb)
        self.layout().addWidget(btn)
        self._buttons[widget] = btn

    def remove_widget(self, widget):
        """Remove the given widget from the tooltip

        :param widget: the widget to remove
        :type widget: QtGui.QWidget
        :returns: None
        :rtype: None
        :raises: KeyError
        """
        button = self._buttons.pop(widget)
        self.layout().removeWidget(button)
        button.deleteLater()

    def eventFilter(self, watched, event):
        """Filter ToolTip events and display this tooltip widget, if watched requests a tooltip.

        :param watched: The watched object
        :type watched: QtCore.QObject
        :param event: The event sent by watched
        :type event: QtCore.QEvent
        :returns: True if the event was processed. False if the event should be passed on.
        :rtype: bool
        :raises: None
        """
        if event.type() == self._triggerevent:
            self.show()
            return True
        else:
            return False

    def get_position(self, ):
        """Return a recommended position for this widget to appear

        This implemenation returns a position so that the widget is vertically centerd on the mouse
        and 10 pixels left of the mouse

        :returns: the position
        :rtype: QPoint
        :raises: None
        """
        pos = QtGui.QCursor.pos()
        if self._alignment & QtCore.Qt.AlignLeft == QtCore.Qt.AlignLeft:
            pos.setX(pos.x() - self._offset)
        elif self._alignment & QtCore.Qt.AlignRight == QtCore.Qt.AlignRight:
            pos.setX(pos.x() - self.frameGeometry().width() + self._offset)
        elif self._alignment & QtCore.Qt.AlignHCenter == QtCore.Qt.AlignHCenter:
            pos.setX(pos.x() - self.frameGeometry().width()/2)
        if self._alignment & QtCore.Qt.AlignTop == QtCore.Qt.AlignTop:
            pos.setY(pos.y() - self._offset)
        elif self._alignment & QtCore.Qt.AlignBottom == QtCore.Qt.AlignBottom:
            pos.setY(pos.y() - self.frameGeometry().height() + self._offset)
        elif self._alignment & QtCore.Qt.AlignVCenter == QtCore.Qt.AlignVCenter:
            pos.setY(pos.y() - self.frameGeometry().height()/2)
        return pos

    def install_tooltip(self, parent):
        """Intall the tooltip on the parent so that it is shown when parent requests a tooltip

        :param parent: the parent object
        :type parent: QObject
        :returns: None
        :rtype: None
        :raises: None
        """
        parent.installEventFilter(self)

    @property
    def alignment(self):
        """Get the alginment of the tooltip relative to the mouse

        :returns: alignment
        :rtype: QtCore.Qt.Alignment
        :raises: None
        """
        return self._alignment

    @alignment.setter
    def alignment(self, alignment):
        """Set the alginment of the tooltip relative to the mouse

        :param alignment: The value for alignment
        :type alignment: QtCore.Qt.Alignment
        :raises: None
        """
        self._alignment = alignment

    @property
    def offset(self):
        """Return offset to the alignment in pixels

        :returns: offset
        :rtype: int
        :raises: None
        """
        return self._offset

    @offset.setter
    def offset(self, offset):
        """Set offset to the alginment in pixels

        :param offset: The value for offset
        :type offset: int
        :raises: None
        """
        self._offset = offset

    @property
    def triggerevent(self):
        """Return triggerevent

        :returns: triggerevent
        :rtype: QtCore.QEvent.Type
        :raises: None
        """
        return self._triggerevent

    @triggerevent.setter
    def triggerevent(self, eventtype):
        """Set triggerevent

        :param eventtype: The value for triggerevent
        :type eventtype: QtCore.QEvent.Type
        :raises: None
        """
        self._triggerevent = eventtype

    def get_widgets(self, ):
        """Return all registered Widgets

        :returns: list of widgets
        :rtype: list
        :raises: None
        """
        return self._buttons.keys()

    def show(self, ):
        """Reimplementation that moves the tooltip and updates the buttons

        :returns: None
        :rtype: None
        :raises: None
        """
        self.update_all_buttons()
        pos = self.get_position()
        self.move(pos)
        super(WidgetToolTip, self).show()

class JB_WindowToolTip(WidgetToolTip):

    def show(self, ):
        """Reimplementation of show to update all currently available JB_MainWindows

        :returns: None
        :rtype: None
        :raises: None
        """
        wins = set(JB_MainWindow.instances())
        widgets = set(self.get_widgets())
        for w in wins - widgets:
            self.add_widget(w)
        super(JB_WindowToolTip, self).show()