text:
try:
    from Tkinter import Frame, N, S, E, W
except ImportError:
    from tkinter import Frame, N, S, E, W

class Animation(object):
    def __init__(self, w, ticks, config_function, duration=1, interval_time=None, easing_function=None, start_value=0, end_value=1, callback=None):
        self._w = w

        self._tick = 0
        self._total_ticks = float(ticks)

        if easing_function is None:
            self._easing_function = lambda x: x

        self._duration = duration

        if interval_time:
            self._interval_time = int(interval_time * 1000)
        else:
            self._interval_time = int(duration * 1000 / self._total_ticks)

        self._start_value = start_value
        self._end_value = end_value
        self._interval_value = end_value - start_value

        self._config_function = config_function

        self._callback = callback

    def start_animation(self, after=0):
        if after != 0:
            self.after(int(after*1000), self._animate)
        else:
            self._animate()

    def _animate(self):
        t =  self._tick / self._total_ticks

        value = self._start_value + self._interval_value * self._easing_function(t)
        self._config_function(value)

        self._tick += 1

        if self._tick <= self._total_ticks:
            self._w.after(self._interval_time, self._animate)
        else:
            if self._callback is not None:
                self._w.after(self._interval_time, self._callback)

class Stacked_Frame(Frame):
    def __init__(self, master, animate=False, animate_direction=W, **kw):
        Frame.__init__(self, master, **kw)
        self._list_of_widgets = []

        self._current_index = None
        self._current_widget = None

        self._animate = animate

        if animate:
            if animate_direction not in (E, W, N, S):
                raise ValueError("Invalid animate_direction value: %s"%animate_direction)

            self._animate_direction = animate_direction

        self._is_animating = False

    def add_widget(self, widget):
        self._list_of_widgets.append(widget)
        if self._current_index is None:
            self._current_index = 0
            self._show_widget(widget)

        index = len(self._list_of_widgets) - 1
        return index

    def remove_widget(self, widget):
        self._list_of_widgets.remove(widget)

    def insert_widget(self, index, widget):
        self._list_of_widgets.insert(index, widget)
        if self._current_index is None:
            self._current_index = 0

            self._show_widget(widget)

    def count(self):
        return len(self._list_of_widgets)

    def current_index(self):
        return self._current_index

    def index_of(self, widget):
        return self._list_of_widgets.index(widget)

    def set_current_index(self, index):
        if self._is_animating:
            return

        if index == self._current_index: return

        widget = self._list_of_widgets[index]
        self._current_index = index

        self._show_widget(widget)

    def set_current_widget(self, widget):
        if self._is_animating:
            return

        index = self._list_of_widgets.index(widget)
        self._current_index = index

        self._show_widget(widget)

    def widget(self, index):
        return self._list_of_widgets[index]

    def next(self):
        if self._current_index  == len(self._list_of_widgets) - 1:
            return

        if self._is_animating:
            return

        self._current_index += 1
        widget = self._list_of_widgets[self._current_index]

        self._show_widget(widget)

    def previous(self):
        if not self._current_index:
            return

        if self._is_animating:
            return

        self._current_index -= 1
        widget = self._list_of_widgets[self._current_index]

        self._show_widget(widget)

    def _show_widget(self, widget):
        if self._current_widget is None:
            self._current_widget = widget
            widget.place(x=0, y=0, relwidth=1, relheight=1)
        else:
            if self._animate:
                old_widget = self._current_widget

                widget.place(relwidth=1, relheight=1)

                if self._animate_direction == W:
                    start_value = 0
                    end_value = self.winfo_width()

                    def config_function(position):
                        widget.place(x=position, y=0, anchor=N+E)
                        old_widget.place(x=position, y=0, anchor=N+W)

                elif self._animate_direction == E:
                    start_value = self.winfo_width()
                    end_value = 0

                    def config_function(position):
                        widget.place(x=position, y=0, anchor=N+W)
                        old_widget.place(x=position, y=0, anchor=N+E)

                elif self._animate_direction == S:
                    start_value = 0
                    end_value = self.winfo_height()

                    def config_function(position):
                        widget.place(x=0, y=position, anchor=S+W)
                        old_widget.place(x=0, y=position, anchor=N+W)

                elif self._animate_direction == N:
                    start_value = self.winfo_height()
                    end_value = 0

                    def config_function(position):
                        widget.place(x=0, y=position, anchor=N+W)
                        old_widget.place(x=0, y=position, anchor=S+W)

                animation = Animation(
                    self,
                    ticks=20,
                    interval_time=0.05,
                    start_value=start_value,
                    end_value=end_value,
                    config_function=config_function,
                    callback=lambda widget=widget: self._on_finnish_animation(widget))

                animation.start_animation()
                self._is_animating = True
            else:
                self._current_widget.place_forget()
                self._current_widget = widget

                widget.place(x=0, y=0, relwidth=1, relheight=1)

    def _on_finnish_animation(self, widget):
        self._current_widget.place_forget()
        self._current_widget = widget

        self._is_animating = False

if __name__ == "__main__":
    try:
        from Tkinter import Tk, Button, Label
    except ImportError:
        from tkinter import Tk, Button, Label

    root = Tk()
    stack = Stacked_Frame(root, width=300, height=400, animate=True, animate_direction=S)
    stack.pack(padx=5)

    frame1 = Frame(stack, background="red")
    Label(frame1, text="this is frame1").pack(expand=True)

    frame2 = Frame(stack, background="white")
    Label(frame2, text="this is frame2").pack(expand=True)

    frame3 = Frame(stack, background="yellow")
    Label(frame3, text="this is frame3").pack(expand=True)

    frame4 = Frame(stack, background="green")
    Label(frame4, text="this is frame4").pack(expand=True)

    stack.add_widget(frame1)
    stack.add_widget(frame2)
    stack.add_widget(frame3)
    stack.add_widget(frame4)

    row = Frame(root)
    row.pack(fill="x", pady=10, padx=5)
    Button(row, text="previous", command= lambda: stack.previous()).pack(side="left")
    Button(row, text="next", command= lambda: stack.next()).pack(side="left", padx=(8,0))

    root.mainloop()


text:
require File.dirname(__FILE__) + '/spec_helper'

describe Workbler::Config do
  before(:each) do
    @config = Workbler::Config.new(File.dirname(__FILE__) + '/data/workble.yml')
  end

  it "should contain basic configuration" do
    @config.should_not be_nil
    @config[:host].should == '127.0.0.1'
    @config[:queue].should_not be_nil
  end

end

redpajama_set_name: RedPajamaGithub


text:
const assert = require('assert');
const testUtils = require('../test-utils');
const vertica = require('./index');

const connection = {
  name: 'test vertica',
  driver: 'vertica',
  host: 'localhost',
  username: 'dbadmin',
  maxRows: 10000,
};

const initSql = `
  DROP TABLE IF EXISTS test;

  CREATE TABLE test (id int);
  COMMIT;

  -- In vertica you must commit after insert
  INSERT INTO test (id) VALUES (1);
  INSERT INTO test (id) VALUES (2);
  INSERT INTO test (id) VALUES (3);
  COMMIT;
`;

describe('drivers/vertica', function () {
  before(function () {
    this.timeout(10000);
    return vertica.runQuery(initSql, connection);
  });

  it('tests connection', function () {
    return vertica.testConnection(connection);
  });

  it('getSchema()', function () {
    return vertica.getSchema(connection).then((schemaInfo) => {
      const column = testUtils.getColumn(schemaInfo, 'public', 'test', 'id');
      assert(column.hasOwnProperty('dataType'));
    });
  });

  it('runQuery under limit', function () {
    return vertica
      .runQuery('SELECT id FROM test WHERE id = 1;', connection)
      .then((results) => {
        assert(!results.incomplete, 'not incomplete');
        assert.equal(results.rows.length, 1, 'rows length');
      });
  });

  it('runQuery over limit', function () {
    const limitedConnection = { ...connection, maxRows: 2 };
    return vertica
      .runQuery('SELECT * FROM test;', limitedConnection)
      .then((results) => {
        assert(results.incomplete, 'incomplete');
        assert.equal(results.rows.length, 2, 'row length');
      });
  });

  it('returns descriptive error message', function () {
    let error;
    return vertica
      .runQuery('SELECT * FROM missing_table;', connection)
      .catch((e) => {
        error = e;
      })
      .then(() => {
        assert(error);
        assert(error.toString().indexOf('missing_table') > -1);
      });
  });
});


text:
   {{ exchange.exchange }}

   Buy

 {{ exchange.description }}


text:
<!DOCTYPE html>
<html>
<head>
    <script src="file:///android_asset/bundle-test.js"></script>
</head>
</html>


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".TestCrashActivity">

    <TextView
        android:id="@+id/number"
        android:text="100"
        android:padding="20dp"
        android:textSize="30dp"
        android:layout_width="wrap_content"
        android:background="@color/accent"
        android:layout_height="wrap_content" />
</android.support.constraint.ConstraintLayout>


text:
class LikePictureActivity < Activr::Activity

  entity :actor, :class => User, :humanize => :fullname
  entity :picture, :humanize => :title

  humanize "{{{actor}}} likes the picture {{{picture}}}"

end


text:
/**
 * Polyfills/Normalization for Fall-back Browsers
 * @module jsm.shims
 * @example console.log performance.now
 * @example classList dataset hidden insertAdjacentElement
 */
(function(global){
	"use strict";
	var methods=["debug","error","info","log","warn","dir","dirxml","table","trace","assert","count","markTimeline",
		"profile","profileEnd","time","timeEnd","timeStamp","timeline","timelineEnd","group","groupCollapsed",
		"groupEnd","clear"];
	/**
	 * @namespace jsm.shims
	 * @class Console
	 */
	/**
	 * Writes a message to the console.
	 * You may pass as many arguments as you'd like, and they will be joined together in a space-delimited line.
	 * @method log
	 * @param {*} [object]*
	 */
	/**
	 * Writes a message to the console, including a hyperlink to the line where it was called.
	 * @method debug
	 * @param {*} [object]*
	 */
	/**
	 * Writes a message to the console with the visual "info" icon and color coding and a hyperlink to the line where it was called.
	 * @method info
	 * @param {*} [object]*
	 */
	/**
	 * Writes a message to the console with the visual "warning" icon and color coding and a hyperlink to the line where it was called.
	 * @method warn
	 * @param {*} [object]*
	 */
	/**
	 * Writes a message to the console with the visual "error" icon and color coding and a hyperlink to the line where it was called.
	 * @method error
	 * @param {*} [object]*
	 */
	/**
	 * Tests that an expression is true. If not, it will write a message to the console and throw an exception.
	 * @method assert
	 * @param {Boolean} expression
	 * @param {*} [object]*
	 */
	/**
	 * Clears the console.
	 * @method clear
	 */
	/**
	 * Prints an interactive listing of all properties of the object. This looks identical to the view that you would see in the DOM Panel.
	 * @method dir
	 * @param {Object} object
	 */
	/**
	 * Prints the XML source tree of an HTML or XML element. This looks identical to the view that you would see in the HTML Panel. You can click on any node to inspect it in the HTML Panel.
	 * @method dirxml
	 * @param {Element} node
	 */
	/**
	 * Prints an interactive stack trace of JavaScript execution at the point where it is called.
	 * @method trace
	 */
	/**
	 * Writes a message to the console and opens a nested block to indent all future messages sent to the console. Call console.groupEnd() to close the block.
	 * @method group
	 * @param {*} [object]*
	 */
	/**
	 * Like console.group(), but the block is initially collapsed.
	 * @method groupCollapsed
	 * @param {String} title
	 * @param {*} [object]*
	 */
	/**
	 * Closes the most recently opened block created by a call to console.group() or console.groupCollapsed()
	 * @method groupEnd
	 * @param {String} title
	 */
	/**
	 * Creates a new timer under the given name. Call console.timeEnd() with the same name to stop the timer and print the time elapsed.
	 * @method time
	 * @param {String} name
	 */
	/**
	 * Stops a timer created by a call to console.time(name) and writes the time elapsed.
	 * @method timeEnd
	 * @param {String} name
	 */
	/**
	 * Creates a time stamp, which can be used together with HTTP traffic timing to measure when a certain piece of code was executed.
	 * @method timeStamp
	 * @param {String} name
	 */
	/**
	 * Turns on the JavaScript profiler.
	 * @method profile
	 * @param {String} [title]
	 */
	/**
	 * Turns off the JavaScript profiler and prints its report.
	 * @method profileEnd
	 */
	/**
	 * Writes the number of times that the line of code where count was called was executed.
	 * @method count
	 * @param {String} [title]
	 */
	/**
	 * Prints an error message together with an interactive stack trace of JavaScript execution at the point where the exception occurred.
	 * @method exception
	 * @param {Error} error-object
	 * @param {*} [arg]*
	 */
	/**
	 * Allows to log provided data using tabular layout.
	 * @method table
	 * @param {Object} data
	 * @param {Number} [columns]
	 */
	function Console(){}

	var console=global.console,
		log;
	if(typeof console!=="object"){
		log=function log(){
			//NOOP
		};
		methods.forEach(function(name){
			Console.prototype[name]=log;
		});
		global.console=new Console();
	}else{
		log=console.log;
		methods.forEach(function(name){
			if(typeof this[name]!=="function"){
				this[name]=log;
			}
		},console);
	}
	if(typeof define==="function"&&define.amd){
		define(function(){return console;});
	}
}(this));


text:
package graphview

import (
	osgraph "github.com/openshift/origin/pkg/oc/lib/graph/genericgraph"
	kubeedges "github.com/openshift/origin/pkg/oc/lib/graph/kubegraph"
	"github.com/openshift/origin/pkg/oc/lib/graph/kubegraph/analysis"
	kubegraph "github.com/openshift/origin/pkg/oc/lib/graph/kubegraph/nodes"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

type ReplicaSet struct {
	RS *kubegraph.ReplicaSetNode

	OwnedPods   []*kubegraph.PodNode
	CreatedPods []*kubegraph.PodNode
}

func AllReplicaSets(g osgraph.Graph, excludeNodeIDs IntSet) ([]ReplicaSet, IntSet) {
	covered := IntSet{}
	rsViews := []ReplicaSet{}

	for _, uncastNode := range g.NodesByKind(kubegraph.ReplicaSetNodeKind) {
		if excludeNodeIDs.Has(uncastNode.ID()) {
			continue
		}

		rsView, covers := NewReplicaSet(g, uncastNode.(*kubegraph.ReplicaSetNode))
		covered.Insert(covers.List()...)
		rsViews = append(rsViews, rsView)
	}

	return rsViews, covered
}

// MaxRecentContainerRestarts returns the maximum container restarts for all pods
func (rs *ReplicaSet) MaxRecentContainerRestarts() int32 {
	var maxRestarts int32
	for _, pod := range rs.OwnedPods {
		for _, status := range pod.Status.ContainerStatuses {
			if status.RestartCount > maxRestarts && analysis.ContainerRestartedRecently(status, metav1.Now()) {
				maxRestarts = status.RestartCount
			}
		}
	}
	return maxRestarts
}

// NewReplicationController returns the ReplicationController and a set of all the NodeIDs covered by the ReplicationController
func NewReplicaSet(g osgraph.Graph, rsNode *kubegraph.ReplicaSetNode) (ReplicaSet, IntSet) {
	covered := IntSet{}
	covered.Insert(rsNode.ID())

	rsView := ReplicaSet{}
	rsView.RS = rsNode

	for _, uncastPodNode := range g.PredecessorNodesByEdgeKind(rsNode, kubeedges.ManagedByControllerEdgeKind) {
		podNode := uncastPodNode.(*kubegraph.PodNode)
		covered.Insert(podNode.ID())
		rsView.OwnedPods = append(rsView.OwnedPods, podNode)
	}

	return rsView, covered
}

func MaxRecentContainerRestartsForRS(g osgraph.Graph, rsNode *kubegraph.ReplicaSetNode) int32 {
	if rsNode == nil {
		return 0
	}
	rs, _ := NewReplicaSet(g, rsNode)
	return rs.MaxRecentContainerRestarts()
}


text:
//
//  SDLTemplateConfiguration.h
//  SmartDeviceLink

#import "SDLTemplateColorScheme.h"
#import "SDLPredefinedLayout.h"

NS_ASSUME_NONNULL_BEGIN

/**
 Used to set an alternate template layout to a window.

 @since SDL 6.0
 */
@interface SDLTemplateConfiguration : SDLRPCStruct

/**
 Constructor with the required values.

 @param predefinedLayout A template layout an app uses to display information. The broad details of the layout are defined, but the details depend on the IVI system. Used in SetDisplayLayout.
 */
- (instancetype)initWithPredefinedLayout:(SDLPredefinedLayout)predefinedLayout;

// HAX: We are doing this because `template` is a C++ keyword and won't compile.
#ifndef __cplusplus
/**
 Init with the required values.

 @param template Predefined or dynamically created window template. Currently only predefined window template layouts are defined.
 */
- (instancetype)initWithTemplate:(NSString *)template;

/**
 Convenience constructor with all the parameters.

 @param template Predefined or dynamically created window template. Currently only predefined window template layouts are defined.
 @param dayColorScheme The color scheme to use when the head unit is in a light / day situation. If nil, the existing color scheme will be used.
 @param nightColorScheme The color scheme to use when the head unit is in a dark / night situation.
 */
- (instancetype)initWithTemplate:(NSString *)template dayColorScheme:(nullable SDLTemplateColorScheme *)dayColorScheme nightColorScheme:(nullable SDLTemplateColorScheme *)nightColorScheme;

/**
 Predefined or dynamically created window template. Currently only predefined window template layouts are defined.
 */
@property (strong, nonatomic) NSString *template;
#endif

#ifdef __cplusplus
/**
 Init with the required values.

 @param templateName Predefined or dynamically created window template. Currently only predefined window template layouts are defined.
 */
- (instancetype)initWithTemplate:(NSString *)templateName;

/**
 Convinience constructor with all the parameters.

 @param templateName Predefined or dynamically created window template. Currently only predefined window template layouts are defined.
 @param dayColorScheme The color scheme to use when the head unit is in a light / day situation. If nil, the existing color scheme will be used.
 @param nightColorScheme The color scheme to use when the head unit is in a dark / night situation.
 */
- (instancetype)initWithTemplate:(NSString *)templateName dayColorScheme:(nullable SDLTemplateColorScheme *)dayColorScheme nightColorScheme:(nullable SDLTemplateColorScheme *)nightColorScheme;

/**
 Predefined or dynamically created window template. Currently only predefined window template layouts are defined.
 */
@property (strong, nonatomic) NSString *templateName;
#endif

/**
 The color scheme to use when the head unit is in a light / day situation.
 */
@property (strong, nonatomic, nullable) SDLTemplateColorScheme *dayColorScheme;

/**
 The color scheme to use when the head unit is in a dark / night situation.
 */
@property (strong, nonatomic, nullable) SDLTemplateColorScheme *nightColorScheme;

@end

NS_ASSUME_NONNULL_END


text:
<?php

class Listing_url {

	private $ci;
	private $listingModel;

	public function __construct(){
		$this->ci =& get_instance();
		$this->ci->load->model("listing/listing_model");
		$this->listingModel = new listing_model();
	}
//url_builder lib name
	//validate_url for below function

	public function getListingUrl($listingId){
		//validate the listing for the given listingId
		$listingTitle = $this->listingModel->getListingTitle($listingId);
		if($listingTitle == false){
			return false;
		}
		else{
			$url = convertTextToUrl($listingTitle);
			return "$url/$listingId";
		}

	}
}

?>


text:
require 'spec_helper'

module FakeRedis
  describe "TransactionsMethods" do
    before(:each) do
      @client = Redis.new
    end

    it "should mark the start of a transaction block" do
      transaction = @client.multi do
        @client.set("key1", "1")
        @client.set("key2", "2")
        @client.mget("key1", "key2")
      end

      transaction.should be == ["OK", "OK", ["1", "2"]]
    end
  end
end


text:
package gov.nih.nci.cabig.caaers.dao;

import java.util.List;

import gov.nih.nci.cabig.caaers.DaoTestCase;
import gov.nih.nci.cabig.caaers.domain.ConfigProperty;
import gov.nih.nci.cabig.caaers.domain.ConfigPropertyType;
import gov.nih.nci.cabig.caaers.domain.Fixtures;
/**
 *
 * @author Biju Joseph
 *
 */
public class ConfigPropertyDaoTest extends DaoTestCase<ConfigPropertyDao> {

	protected void setUp() throws Exception {
		super.setUp();
	}

	public void testGetById(){
		ConfigProperty cp = getDao().getById(-1);
		assertNotNull(cp);
		assertNotNull(cp.getConfigType());
	}

	public void testGetByType() {
		List<ConfigProperty> props = getDao().getByType(ConfigPropertyType.REPORT_GROUP);
		assertEquals(2, props.size());
		assertEquals("EXP1", props.get(0).getCode());
		assertEquals(ConfigPropertyType.REPORT_GROUP, props.get(0).getConfigType());
	}

	public void testGetAll(){
		List<ConfigProperty> props = getDao().getAll();
		assertEquals(3, props.size());
	}

	public void testGetByTypeAndCode(){
		ConfigProperty cp = getDao().getByTypeAndCode(ConfigPropertyType.REPORT_GROUP, "EXP1");
		assertNotNull(cp);
		assertEquals("Expedited Report", cp.getName());
		cp = getDao().getByTypeAndCode(ConfigPropertyType.REPORT_GROUP, "RT_xx");
		assertNull(cp);
	}

	public void testSave(){
		{
			ConfigProperty cp = Fixtures.createConfigProperty("test");
			cp.setConfigType(ConfigPropertyType.UNKNOWN);
			getDao().save(cp);
		}
		interruptSession();
		{
			ConfigProperty cp = getDao().getByTypeAndCode(ConfigPropertyType.UNKNOWN, "test");
			assertNotNull(cp);
			assertNotNull(cp.getConfigType());
			assertEquals("test", cp.getCode());

		}
	}

    public void testRemoveAll(){
        {
           for(int i = 1 ; i < 5 ; i++){
               ConfigProperty cp = Fixtures.createConfigProperty("test" + i);
               cp.setConfigType(ConfigPropertyType.UNKNOWN);
               getDao().save(cp);
           }

        }
        interruptSession();
        {
            List<ConfigProperty> l = getDao().getByType(ConfigPropertyType.UNKNOWN);
            assertFalse(l.isEmpty());
            getDao().removeAll(l);
        }
        interruptSession();
        {
            List<ConfigProperty> l = getDao().getByType(ConfigPropertyType.UNKNOWN);
            assertTrue(l.isEmpty());
        }
    }

}


text:
<?php

namespace zeageorge\Object\exceptions;

/**
 * Description of InvalidCallException
 *
 * @author Zeakis George <zeageorge@gmail.com>
 */
class InvalidCallException extends ObjectException {

}


text:
package com.systematic.trading.strategy.entry.size;

import java.math.BigDecimal;

/**
 * A boundary / limit applicable to an entry position.
 *
 * @author CJ Hare
 */
public interface EntryPositionBounds {

	/**
	 * Retrieves the amount to spend on equities.
	 *
	 * @param funds
	 *            the liquid cash position.
	 * @return amount of capital to spend, never null
	 */
	BigDecimal bounds( BigDecimal funds );
}


text:
package model.carousell;

import lombok.Builder;
import lombok.Data;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;

@Builder
@Data
public class CarousellQuery {
	private int count;
	private int start;
	private sortType sort;
	public enum sortType {
		recent, popular
	}

	@JsonProperty("query")
	private String searchStr;

	public String toJson() {
		ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
		try {
			return ow.writeValueAsString(this);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return "";
		}
	}

}


text:
<!DOCTYPE html>

  <title>goog.ui.PopupColorPicker</title>

  <link rel="stylesheet" href="css/demo.css">
  <link rel="stylesheet" href="../css/colorpicker-simplegrid.css">

goog.ui.PopupColorPicker

  Show 1
  Show 2


text:
import * as Discord from 'discord.js';

import BaseModule from '../BaseModule';

/**
 * This is the base command class which all other commands are based on.
 */
abstract class BaseCommand extends BaseModule {
    /**
     * The pattern that a command responds to.
     */
    pattern: RegExp = /^!$/;

    /**
     * The description of what the command does.
     */
    description = 'I have no description :(';

    /**
     * The events that this module should react to.
     */
    methods: Array<keyof Discord.ClientEvents> = ['message'];

    /**
     * The action to take when this module is invoked.
     */
    async action(action: keyof Discord.ClientEvents, message: Discord.Message): Promise<void> {
        return this.execute(message);
    }

    /**
     * Checks to see if this message matches or not. If it returns true then we should act upon this message.
     */
    matches(message: Discord.Message): boolean {
        if (this.respondToAll) {
            return true;
        }

        if (message.system) {
            return false; // don't match system messages
        }

        if (message.author.bot) {
            return false; // don't respond to bot users
        }

        return message.cleanContent.match(this.pattern) !== null;
    }

    abstract execute(message: Discord.Message): Promise<void>;
}

export default BaseCommand;


text:
System.register(['angular2/http', 'angular2/core', 'rxjs/Observable', 'rxjs/subject/ReplaySubject', './MyToken', '../../node_modules/rx/dist/rx.all.js', 'rxjs/add/operator/map', 'rxjs/add/operator/count', 'rxjs/add/operator/filter', 'rxjs/add/operator/observeOn', 'rxjs/add/observable/from', 'rxjs/add/observable/fromArray'], function(exports_1) {
    var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
        var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
        if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
        else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
        return c > 3 && r && Object.defineProperty(target, key, r), r;
    };
    var __metadata = (this && this.__metadata) || function (k, v) {
        if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
    };
    var http_1, core_1, Observable_1, ReplaySubject_1, MyToken_1;
    var MyIGADataService;
    return {
        setters:[
            function (http_1_1) {
                http_1 = http_1_1;
            },
            function (core_1_1) {
                core_1 = core_1_1;
            },
            function (Observable_1_1) {
                Observable_1 = Observable_1_1;
            },
            function (ReplaySubject_1_1) {
                ReplaySubject_1 = ReplaySubject_1_1;
            },
            function (MyToken_1_1) {
                MyToken_1 = MyToken_1_1;
            },
            function (_1) {},
            function (_2) {},
            function (_3) {},
            function (_4) {},
            function (_5) {},
            function (_6) {},
            function (_7) {}],
        execute: function() {
            MyIGADataService = (function () {
                function MyIGADataService(http) {
                    var _this = this;
                    this.http = http;
                    this.myToken = MyToken_1.MyToken.getToken();
                    this.mylegislators = [];
                    this.representatives = [];
                    this.senators = [];
                    this.legislators = new ReplaySubject_1.ReplaySubject();
                    this.bills = new ReplaySubject_1.ReplaySubject();
                    this.biPartisanBills = new ReplaySubject_1.ReplaySubject();
                    this.billsList = new ReplaySubject_1.ReplaySubject();
                    this.legislatorsList = new ReplaySubject_1.ReplaySubject();
                    this.biPartisanBills1 = [];
                    this.bills1 = [];
                    this.getLegislatorsList()
                        .map(function (res) { return Observable_1.Observable.fromArray(res.json().items); }, Rx.Scheduler.immediate)
                        .mergeAll()
                        .subscribe(function (x) { return _this.legislatorsList.next(x); });
                    console.log(this.legislatorsList.count + 'is the count of legislators I received');
                    this.getBillsList()
                        .map(function (res) { return Observable_1.Observable.fromArray(res.json().items); })
                        .mergeAll()
                        .subscribe(function (x) { return _this.billsList.next(x); });
                    console.log('This is the end');
                    this.legislators.filter(function (x) { return x.chamber.name == 'House'; })
                        .subscribe(function (x) { return _this.representatives.push(x); });
                    this.legislators.filter(function (x) { return x.chamber.name == 'Senate'; })
                        .subscribe(function (x) { return _this.senators.push(x); });
                }
                MyIGADataService.prototype.followLegislator = function (inLeg) {
                };
                MyIGADataService.prototype.followBill = function (inUser, inbillName) {
                };
                MyIGADataService.prototype.getSessions = function () { };
                MyIGADataService.prototype.getConstitution = function () { };
                MyIGADataService.prototype.getChambers = function () {
                    return this.http.get('dapi/chambers.json');
                };
                MyIGADataService.prototype.getCalendars = function () { };
                MyIGADataService.prototype.getJournals = function () { };
                MyIGADataService.prototype.getLegislators = function () {
                    var headers = new http_1.Headers();
                    headers.append('Accept', 'application/json');
                    headers.append('Authorization', this.myToken);
                    return this.http.get('dapi/legislators.json');
                };
                MyIGADataService.prototype.getLegislators1 = function () {
                    console.log('Getting legislators');
                    var headers = new http_1.Headers();
                    headers.append('Accept', 'application/json');
                    headers.append('Authorization', this.myToken);
                    return this.http.get('https://api.iga.in.gov/2016/legislators?per_page=100000', { headers: headers });
                };
                MyIGADataService.prototype.getLegislatorsList = function () {
                    console.log('Getting legislators');
                    var headers = new http_1.Headers();
                    headers.append('Accept', 'application/json');
                    headers.append('Authorization', this.myToken);
                    return this.http.get('https://api.iga.in.gov/2016/legislators?per_page=300', { headers: headers });
                };
                MyIGADataService.prototype.getBillsList = function () {
                    console.log('Getting Bills List');
                    var headers = new http_1.Headers();
                    headers.append('Accept', 'application/json');
                    headers.append('Authorization', this.myToken);
                    return this.http.get('https://api.iga.in.gov/2016/bills?per_page=2000', { headers: headers });
                };
                MyIGADataService.prototype.getBills = function () {
                    console.log('Getting Bills');
                    var headers = new http_1.Headers();
                    headers.append('Accept', 'application/json');
                    headers.append('Authorization', this.myToken);
                    return this.http.get('https://api.iga.in.gov/2016/bills?per_page=2000', { headers: headers });
                };
                MyIGADataService.prototype.postBill = function (inBill) {
                    console.log('Posting Bills' + JSON.stringify(inBill));
                    var headers1 = new http_1.Headers();
                    headers1.append('Content-Type', 'application/json');
                    return this.http.post('http://localhost:8080/api/bill', JSON.stringify(inBill), { headers: headers1 });
                };
                MyIGADataService.prototype.postLegislator = function (inBill) {
                    console.log('Posting Legislator' + JSON.stringify(inBill));
                    var headers1 = new http_1.Headers();
                    headers1.append('Content-Type', 'application/json');
                    return this.http.post('http://localhost:8080/api/legislator', JSON.stringify(inBill), { headers: headers1 });
                };
                MyIGADataService.prototype.getBillDetails = function (link) {
                    console.log('Bill details called');
                    var headers = new http_1.Headers();
                    headers.append('Accept', 'application/json');
                    headers.append('Authorization', this.myToken);
                    var legLink = 'https://api.iga.in.gov' + link;
                    return this.http.get(legLink, { headers: headers })
                        .map(function (res) { return res.json(); });
                };
                MyIGADataService.prototype.getLegislatorDetails = function (link) {
                    var headers = new http_1.Headers();
                    headers.append('Accept', 'application/json');
                    headers.append('Authorization', this.myToken);
                    var legLink = 'https://api.iga.in.gov' + link;
                    return this.http.get(legLink, { headers: headers })
                        .map(function (res) { return res.json(); });
                };
                MyIGADataService.prototype.getLegislatorImage = function (link) {
                    var headers = new http_1.Headers();
                    headers.append('Accept', 'image/png');
                    headers.append('Authorization', this.myToken);
                    var legImageLink = 'https://api.iga.in.gov' + link;
                    return this.http.get(legImageLink, { headers: headers })
                        .map(function (res) { return res; });
                };
                MyIGADataService = __decorate([
                    core_1.Injectable(),
                    __metadata('design:paramtypes', [http_1.Http])
                ], MyIGADataService);
                return MyIGADataService;
            })();
            exports_1("MyIGADataService", MyIGADataService);
        }
    }
});
//# sourceMappingURL=MyIGADataService.js.map


text:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/select.h>
#include <sys/signal.h>

#include <X11/Xlib.h>
#include <X11/Xutil.h>

#include <winpr/crt.h>
#include <winpr/path.h>
#include <winpr/synch.h>
#include <winpr/image.h>
#include <winpr/sysinfo.h>

#include <freerdp/log.h>
#include <freerdp/codec/color.h>
#include <freerdp/codec/region.h>

#include "../shadow_screen.h"
#include "../shadow_client.h"
#include "../shadow_capture.h"
#include "../shadow_surface.h"
#include "../shadow_subsystem.h"
#include "../shadow_mcevent.h"

#include "x11_shadow.h"

#define TAG SERVER_TAG("shadow.x11")

int x11_shadow_enum_monitors(MONITOR_DEF* monitors, int maxMonitors);

#ifdef WITH_PAM

#include <security/pam_appl.h>

struct _SHADOW_PAM_AUTH_DATA
{
	const char* user;
	const char* domain;
	const char* password;
};
typedef struct _SHADOW_PAM_AUTH_DATA SHADOW_PAM_AUTH_DATA;

struct _SHADOW_PAM_AUTH_INFO
{
	char* service_name;
	pam_handle_t* handle;
	struct pam_conv pamc;
	SHADOW_PAM_AUTH_DATA appdata;
};
typedef struct _SHADOW_PAM_AUTH_INFO SHADOW_PAM_AUTH_INFO;

int x11_shadow_pam_conv(int num_msg, const struct pam_message** msg, struct pam_response** resp, void* appdata_ptr)
{
	int index;
	int pam_status = PAM_BUF_ERR;
	SHADOW_PAM_AUTH_DATA* appdata;
	struct pam_response* response;

	appdata = (SHADOW_PAM_AUTH_DATA*) appdata_ptr;

	if (!(response = (struct pam_response*) calloc(num_msg, sizeof(struct pam_response))))
		return PAM_BUF_ERR;

	for (index = 0; index < num_msg; index++)
	{
		switch (msg[index]->msg_style)
		{
			case PAM_PROMPT_ECHO_ON:
				response[index].resp = _strdup(appdata->user);
				if (!response[index].resp)
					goto out_fail;
				response[index].resp_retcode = PAM_SUCCESS;
				break;

			case PAM_PROMPT_ECHO_OFF:
				response[index].resp = _strdup(appdata->password);
				if (!response[index].resp)
					goto out_fail;
				response[index].resp_retcode = PAM_SUCCESS;
				break;

			default:
				pam_status = PAM_CONV_ERR;
				goto out_fail;
		}
	}

	*resp = response;
	return PAM_SUCCESS;

out_fail:
	for (index = 0; index < num_msg; ++index)
	{
		if (response[index].resp)
		{
			memset(response[index].resp, 0, strlen(response[index].resp));
			free(response[index].resp);
		}
	}
	memset(response, 0, sizeof(struct pam_response) * num_msg);
	free(response);
	*resp = NULL;
	return PAM_CONV_ERR;
}

int x11_shadow_pam_get_service_name(SHADOW_PAM_AUTH_INFO* info)
{
	if (PathFileExistsA("/etc/pam.d/lightdm"))
	{
		info->service_name = _strdup("lightdm");
	}
	else if (PathFileExistsA("/etc/pam.d/gdm"))
	{
		info->service_name = _strdup("gdm");
	}
	else if (PathFileExistsA("/etc/pam.d/xdm"))
	{
		info->service_name = _strdup("xdm");
	}
	else if (PathFileExistsA("/etc/pam.d/login"))
	{
		info->service_name = _strdup("login");
	}
	else if (PathFileExistsA("/etc/pam.d/sshd"))
	{
		info->service_name = _strdup("sshd");
	}
	else
	{
		return -1;
	}

	if (!info->service_name)
		return -1;

	return 1;
}

int x11_shadow_pam_authenticate(x11ShadowSubsystem* subsystem, const char* user, const char* domain, const char* password)
{
	int pam_status;
	SHADOW_PAM_AUTH_INFO* info;

	info = calloc(1, sizeof(SHADOW_PAM_AUTH_INFO));

	if (!info)
		return PAM_CONV_ERR;

	if (x11_shadow_pam_get_service_name(info) < 0)
		return -1;

	info->appdata.user = user;
	info->appdata.domain = domain;
	info->appdata.password = password;

	info->pamc.conv = &x11_shadow_pam_conv;
	info->pamc.appdata_ptr = &(info->appdata);

	pam_status = pam_start(info->service_name, 0, &(info->pamc), &(info->handle));

	if (pam_status != PAM_SUCCESS)
	{
		WLog_ERR(TAG, "pam_start failure: %s", pam_strerror(info->handle, pam_status));
		free(info);
		return -1;
	}

	pam_status = pam_authenticate(info->handle, 0);

	if (pam_status != PAM_SUCCESS)
	{
		WLog_ERR(TAG, "pam_authenticate failure: %s", pam_strerror(info->handle, pam_status));
		free(info);
		return -1;
	}

	pam_status = pam_acct_mgmt(info->handle, 0);

	if (pam_status != PAM_SUCCESS)
	{
		WLog_ERR(TAG, "pam_acct_mgmt failure: %s", pam_strerror(info->handle, pam_status));
		free(info);
		return -1;
	}

	free(info);

	return 1;
}

#endif

void x11_shadow_input_synchronize_event(x11ShadowSubsystem* subsystem, UINT32 flags)
{

}

void x11_shadow_input_keyboard_event(x11ShadowSubsystem* subsystem, UINT16 flags, UINT16 code)
{
#ifdef WITH_XTEST
	DWORD vkcode;
	DWORD keycode;
	BOOL extended = FALSE;

	if (flags & KBD_FLAGS_EXTENDED)
		extended = TRUE;

	if (extended)
		code |= KBDEXT;

	vkcode = GetVirtualKeyCodeFromVirtualScanCode(code, 4);

	if (extended)
		vkcode |= KBDEXT;

	keycode = GetKeycodeFromVirtualKeyCode(vkcode, KEYCODE_TYPE_EVDEV);

	if (keycode != 0)
	{
		XTestGrabControl(subsystem->display, True);

		if (flags & KBD_FLAGS_DOWN)
			XTestFakeKeyEvent(subsystem->display, keycode, True, CurrentTime);
		else if (flags & KBD_FLAGS_RELEASE)
			XTestFakeKeyEvent(subsystem->display, keycode, False, CurrentTime);

		XTestGrabControl(subsystem->display, False);

		XFlush(subsystem->display);
	}
#endif
}

void x11_shadow_input_unicode_keyboard_event(x11ShadowSubsystem* subsystem, UINT16 flags, UINT16 code)
{

}

void x11_shadow_input_mouse_event(x11ShadowSubsystem* subsystem, UINT16 flags, UINT16 x, UINT16 y)
{
#ifdef WITH_XTEST
	int button = 0;
	BOOL down = FALSE;
	rdpShadowServer* server;
	rdpShadowSurface* surface;

	server = subsystem->server;
	surface = server->surface;

	x += surface->x;
	y += surface->y;

	XTestGrabControl(subsystem->display, True);

	if (flags & PTR_FLAGS_WHEEL)
	{
		BOOL negative = FALSE;

		if (flags & PTR_FLAGS_WHEEL_NEGATIVE)
			negative = TRUE;

		button = (negative) ? 5 : 4;

		XTestFakeButtonEvent(subsystem->display, button, True, CurrentTime);
		XTestFakeButtonEvent(subsystem->display, button, False, CurrentTime);
	}
	else
	{
		if (flags & PTR_FLAGS_MOVE)
			XTestFakeMotionEvent(subsystem->display, 0, x, y, CurrentTime);

		if (flags & PTR_FLAGS_BUTTON1)
			button = 1;
		else if (flags & PTR_FLAGS_BUTTON2)
			button = 3;
		else if (flags & PTR_FLAGS_BUTTON3)
			button = 2;

		if (flags & PTR_FLAGS_DOWN)
			down = TRUE;

		if (button)
			XTestFakeButtonEvent(subsystem->display, button, down, CurrentTime);
	}

	XTestGrabControl(subsystem->display, False);

	XFlush(subsystem->display);
#endif
}

void x11_shadow_input_extended_mouse_event(x11ShadowSubsystem* subsystem, UINT16 flags, UINT16 x, UINT16 y)
{
#ifdef WITH_XTEST
	int button = 0;
	BOOL down = FALSE;
	rdpShadowServer* server;
	rdpShadowSurface* surface;

	server = subsystem->server;
	surface = server->surface;

	x += surface->x;
	y += surface->y;

	XTestGrabControl(subsystem->display, True);

	XTestFakeMotionEvent(subsystem->display, 0, x, y, CurrentTime);

	if (flags & PTR_XFLAGS_BUTTON1)
		button = 8;
	else if (flags & PTR_XFLAGS_BUTTON2)
		button = 9;

	if (flags & PTR_XFLAGS_DOWN)
		down = TRUE;

	if (button)
		XTestFakeButtonEvent(subsystem->display, button, down, CurrentTime);

	XTestGrabControl(subsystem->display, False);

	XFlush(subsystem->display);
#endif
}

static void x11_shadow_message_free(UINT32 id, SHADOW_MSG_OUT* msg)
{
	switch(id)
	{
		case SHADOW_MSG_OUT_POINTER_POSITION_UPDATE_ID:
			free(msg);
			break;

		case SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE_ID:
			free(((SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE*)msg)->xorMaskData);
			free(((SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE*)msg)->andMaskData);
			free(msg);
			break;

		default:
			WLog_ERR(TAG, "Unknown message id: %u", id);
			free(msg);
			break;
	}
}

int x11_shadow_pointer_position_update(x11ShadowSubsystem* subsystem)
{
	SHADOW_MSG_OUT_POINTER_POSITION_UPDATE* msg;
	UINT32 msgId = SHADOW_MSG_OUT_POINTER_POSITION_UPDATE_ID;

	msg = (SHADOW_MSG_OUT_POINTER_POSITION_UPDATE*) calloc(1, sizeof(SHADOW_MSG_OUT_POINTER_POSITION_UPDATE));

	if (!msg)
		return -1;

	msg->xPos = subsystem->pointerX;
	msg->yPos = subsystem->pointerY;
	msg->Free = x11_shadow_message_free;

	return shadow_client_boardcast_msg(subsystem->server, NULL, msgId, (SHADOW_MSG_OUT*) msg, NULL) ? 1 : -1;
}

int x11_shadow_pointer_alpha_update(x11ShadowSubsystem* subsystem)
{
	SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE* msg;
	UINT32 msgId = SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE_ID;

	msg = (SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE*) calloc(1, sizeof(SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE));

	if (!msg)
		return -1;

	msg->xHot = subsystem->cursorHotX;
	msg->yHot = subsystem->cursorHotY;
	msg->width = subsystem->cursorWidth;
	msg->height = subsystem->cursorHeight;

	if (shadow_subsystem_pointer_convert_alpha_pointer_data(subsystem->cursorPixels, TRUE,
			msg->width, msg->height, msg) < 0)
	{
		free (msg);
		return -1;
	}

	msg->Free = x11_shadow_message_free;

	return shadow_client_boardcast_msg(subsystem->server, NULL, msgId, (SHADOW_MSG_OUT*) msg, NULL) ? 1 : -1;
}

int x11_shadow_query_cursor(x11ShadowSubsystem* subsystem, BOOL getImage)
{
	int x, y, n, k;
	rdpShadowServer* server;
	rdpShadowSurface* surface;

	server = subsystem->server;
	surface = server->surface;

	if (getImage)
	{
#ifdef WITH_XFIXES
		UINT32* pDstPixel;
		XFixesCursorImage* ci;

		ci = XFixesGetCursorImage(subsystem->display);

		if (!ci)
			return -1;

		x = ci->x;
		y = ci->y;

		if (ci->width > subsystem->cursorMaxWidth)
			return -1;

		if (ci->height > subsystem->cursorMaxHeight)
			return -1;

		subsystem->cursorHotX = ci->xhot;
		subsystem->cursorHotY = ci->yhot;

		subsystem->cursorWidth = ci->width;
		subsystem->cursorHeight = ci->height;

		subsystem->cursorId = ci->cursor_serial;

		n = ci->width * ci->height;
		pDstPixel = (UINT32*) subsystem->cursorPixels;

		for (k = 0; k < n; k++)
		{
			/* XFixesCursorImage.pixels is in *unsigned long*, which may be 8 bytes */
			*pDstPixel++ = (UINT32) ci->pixels[k];
		}

		XFree(ci);

		x11_shadow_pointer_alpha_update(subsystem);
#endif
	}
	else
	{
		UINT32 mask;
		int win_x, win_y;
		int root_x, root_y;
		Window root, child;

		if (!XQueryPointer(subsystem->display, subsystem->root_window,
				&root, &child, &root_x, &root_y, &win_x, &win_y, &mask))
		{
			return -1;
		}

		x = root_x;
		y = root_y;
	}

	/* Convert to offset based on current surface */
	if (surface)
	{
		x -= surface->x;
		y -= surface->y;
	}

	if ((x != subsystem->pointerX) || (y != subsystem->pointerY))
	{
		subsystem->pointerX = x;
		subsystem->pointerY = y;

		x11_shadow_pointer_position_update(subsystem);
	}

	return 1;
}

int x11_shadow_handle_xevent(x11ShadowSubsystem* subsystem, XEvent* xevent)
{
	if (xevent->type == MotionNotify)
	{

	}
#ifdef WITH_XFIXES
	else if (xevent->type == subsystem->xfixes_cursor_notify_event)
	{
		x11_shadow_query_cursor(subsystem, TRUE);
	}
#endif
	else
	{

	}

	return 1;
}

void x11_shadow_validate_region(x11ShadowSubsystem* subsystem, int x, int y, int width, int height)
{
	XRectangle region;

	if (!subsystem->use_xfixes || !subsystem->use_xdamage)
		return;

	region.x = x;
	region.y = y;
	region.width = width;
	region.height = height;

#ifdef WITH_XFIXES
	XFixesSetRegion(subsystem->display, subsystem->xdamage_region, &region, 1);
	XDamageSubtract(subsystem->display, subsystem->xdamage, subsystem->xdamage_region, None);
#endif
}

int x11_shadow_blend_cursor(x11ShadowSubsystem* subsystem)
{
	int x, y;
	int nXSrc;
	int nYSrc;
	int nXDst;
	int nYDst;
	int nWidth;
	int nHeight;
	int nSrcStep;
	int nDstStep;
	int nSrcPad;
	int nDstPad;
	BYTE* pSrcData;
	BYTE* pDstData;
	BYTE* pSrcPixel;
	BYTE* pDstPixel;
	BYTE A, R, G, B;
	rdpShadowSurface* surface;

	surface = subsystem->server->surface;

	nXSrc = 0;
	nYSrc = 0;

	nWidth = subsystem->cursorWidth;
	nHeight = subsystem->cursorHeight;

	nXDst = subsystem->pointerX - subsystem->cursorHotX;
	nYDst = subsystem->pointerY - subsystem->cursorHotY;

	if (nXDst >= surface->width)
		return 1;

	if (nXDst < 0)
	{
		nXDst *= -1;

		if (nXDst >= nWidth)
			return 1;

		nXSrc = nXDst;
		nWidth -= nXDst;
		nXDst = 0;
	}

	if (nYDst >= surface->height)
		return 1;

	if (nYDst < 0)
	{
		nYDst *= -1;

		if (nYDst >= nHeight)
			return 1;

		nYSrc = nYDst;
		nHeight -= nYDst;
		nYDst = 0;
	}

	if ((nXDst + nWidth) > surface->width)
		nWidth = surface->width - nXDst;

	if ((nYDst + nHeight) > surface->height)
		nHeight = surface->height - nYDst;

	pSrcData = subsystem->cursorPixels;
	nSrcStep = subsystem->cursorWidth * 4;

	pDstData = surface->data;
	nDstStep = surface->scanline;

	nSrcPad = (nSrcStep - (nWidth * 4));
	nDstPad = (nDstStep - (nWidth * 4));

	pSrcPixel = &pSrcData[(nYSrc * nSrcStep) + (nXSrc * 4)];
	pDstPixel = &pDstData[(nYDst * nDstStep) + (nXDst * 4)];

	for (y = 0; y < nHeight; y++)
	{
		pSrcPixel = &pSrcData[((nYSrc + y) * nSrcStep) + (nXSrc * 4)];
		pDstPixel = &pDstData[((nYDst + y) * nDstStep) + (nXDst * 4)];

		for (x = 0; x < nWidth; x++)
		{
			B = *pSrcPixel++;
			G = *pSrcPixel++;
			R = *pSrcPixel++;
			A = *pSrcPixel++;

			if (A == 0xFF)
			{
				pDstPixel[0] = B;
				pDstPixel[1] = G;
				pDstPixel[2] = R;
			}
			else
			{
				pDstPixel[0] = B + (pDstPixel[0] * (0xFF - A) + (0xFF / 2)) / 0xFF;
				pDstPixel[1] = G + (pDstPixel[1] * (0xFF - A) + (0xFF / 2)) / 0xFF;
				pDstPixel[2] = R + (pDstPixel[2] * (0xFF - A) + (0xFF / 2)) / 0xFF;
			}

			pDstPixel[3] = 0xFF;
			pDstPixel += 4;
		}

		pSrcPixel += nSrcPad;
		pDstPixel += nDstPad;
	}

	return 1;
}

BOOL x11_shadow_check_resize(x11ShadowSubsystem* subsystem)
{
	MONITOR_DEF* virtualScreen;
	XWindowAttributes attr;
	XGetWindowAttributes(subsystem->display, subsystem->root_window, &attr);

	if (attr.width != subsystem->width || attr.height != subsystem->height)
	{
		/* Screen size changed. Refresh monitor definitions and trigger screen resize */
		subsystem->numMonitors = x11_shadow_enum_monitors(subsystem->monitors, 16);

		shadow_screen_resize(subsystem->server->screen);

		subsystem->width = attr.width;
		subsystem->height = attr.height;

		virtualScreen = &(subsystem->virtualScreen);
		virtualScreen->left = 0;
		virtualScreen->top = 0;
		virtualScreen->right = subsystem->width;
		virtualScreen->bottom = subsystem->height;
		virtualScreen->flags = 1;

		return TRUE;
	}

	return FALSE;
}

static int x11_shadow_error_handler_for_capture(Display * display, XErrorEvent * event)
{
    char msg[256];
    XGetErrorText(display, event->error_code, (char *) &msg, sizeof(msg));
	WLog_ERR(TAG, "X11 error: %s Error code: %x, request code: %x, minor code: %x",
			msg, event->error_code, event->request_code, event->minor_code);

	/* Ignore BAD MATCH error during image capture. Abort in other case */
	if (event->error_code != BadMatch)
	{
		abort();
	}

	return 0;
}

int x11_shadow_screen_grab(x11ShadowSubsystem* subsystem)
{
	int count;
	int status;
	int x, y;
	int width, height;
	XImage* image;
	rdpShadowScreen* screen;
	rdpShadowServer* server;
	rdpShadowSurface* surface;
	RECTANGLE_16 invalidRect;
	RECTANGLE_16 surfaceRect;
	const RECTANGLE_16 *extents;

	server = subsystem->server;
	surface = server->surface;
	screen = server->screen;

	count = ArrayList_Count(server->clients);

	if (count < 1)
		return 1;

	if ((count == 1) && subsystem->suppressOutput)
		return 1;

	surfaceRect.left = 0;
	surfaceRect.top = 0;
	surfaceRect.right = surface->width;
	surfaceRect.bottom = surface->height;

	XLockDisplay(subsystem->display);

	/*
	 * Ignore BadMatch error during image capture. The screen size may be
	 * changed outside. We will resize to correct resolution at next frame
	 */
	XSetErrorHandler(x11_shadow_error_handler_for_capture);

	if (subsystem->use_xshm)
	{
		image = subsystem->fb_image;

		XCopyArea(subsystem->display, subsystem->root_window, subsystem->fb_pixmap,
				subsystem->xshm_gc, 0, 0, subsystem->width, subsystem->height, 0, 0);

		status = shadow_capture_compare(surface->data, surface->scanline, surface->width, surface->height,
				(BYTE*) &(image->data[surface->width * 4]), image->bytes_per_line, &invalidRect);
	}
	else
	{
		image = XGetImage(subsystem->display, subsystem->root_window,
					surface->x, surface->y, surface->width, surface->height, AllPlanes, ZPixmap);

		if (!image)
		{
			/*
			 * BadMatch error happened. The size may have been changed again.
			 * Give up this frame and we will resize again in next frame
			 */
			goto fail_capture;
		}

		status = shadow_capture_compare(surface->data, surface->scanline, surface->width, surface->height,
				(BYTE*) image->data, image->bytes_per_line, &invalidRect);
	}

	/* Restore the default error handler */
	XSetErrorHandler(NULL);

	XSync(subsystem->display, False);

	XUnlockDisplay(subsystem->display);

	region16_union_rect(&(subsystem->invalidRegion), &(subsystem->invalidRegion), &invalidRect);
	region16_intersect_rect(&(subsystem->invalidRegion), &(subsystem->invalidRegion), &surfaceRect);

	if (!region16_is_empty(&(subsystem->invalidRegion)))
	{
		extents = region16_extents(&(subsystem->invalidRegion));

		x = extents->left;
		y = extents->top;
		width = extents->right - extents->left;
		height = extents->bottom - extents->top;

		freerdp_image_copy(surface->data, PIXEL_FORMAT_XRGB32,
				surface->scanline, x, y, width, height,
				(BYTE*) image->data, PIXEL_FORMAT_XRGB32,
				image->bytes_per_line, x, y, NULL);

		//x11_shadow_blend_cursor(subsystem);

		count = ArrayList_Count(server->clients);

		shadow_multiclient_publish_and_wait(subsystem->updateEvent);

		if (count == 1)
		{
			rdpShadowClient* client;

			client = (rdpShadowClient*) ArrayList_GetItem(server->clients, 0);

			if (client)
			{
				subsystem->captureFrameRate = shadow_encoder_preferred_fps(client->encoder);
			}
		}

		region16_clear(&(subsystem->invalidRegion));
	}

	if (!subsystem->use_xshm)
		XDestroyImage(image);

	return 1;

fail_capture:
	XSetErrorHandler(NULL);
	XSync(subsystem->display, False);
	XUnlockDisplay(subsystem->display);
	return 0;
}

int x11_shadow_subsystem_process_message(x11ShadowSubsystem* subsystem, wMessage* message)
{
	switch(message->id)
	{
		case SHADOW_MSG_IN_REFRESH_OUTPUT_ID:
		{
			UINT32 index;
			SHADOW_MSG_IN_REFRESH_OUTPUT* msg = (SHADOW_MSG_IN_REFRESH_OUTPUT*) message->wParam;

			if (msg->numRects)
			{
				for (index = 0; index < msg->numRects; index++)
				{
					region16_union_rect(&(subsystem->invalidRegion),
							&(subsystem->invalidRegion), &msg->rects[index]);
				}
			}
			else
			{
				RECTANGLE_16 refreshRect;

				refreshRect.left = 0;
				refreshRect.top = 0;
				refreshRect.right = subsystem->width;
				refreshRect.bottom = subsystem->height;

				region16_union_rect(&(subsystem->invalidRegion),
							&(subsystem->invalidRegion), &refreshRect);
			}
			break;
		}
		case SHADOW_MSG_IN_SUPPRESS_OUTPUT_ID:
		{
			SHADOW_MSG_IN_SUPPRESS_OUTPUT* msg = (SHADOW_MSG_IN_SUPPRESS_OUTPUT*) message->wParam;

			subsystem->suppressOutput = (msg->allow) ? FALSE : TRUE;

			if (msg->allow)
			{
				region16_union_rect(&(subsystem->invalidRegion),
							&(subsystem->invalidRegion), &(msg->rect));
			}
			break;
		}
		default:
			WLog_ERR(TAG, "Unknown message id: %u", message->id);
			break;
	}

	if (message->Free)
		message->Free(message);

	return 1;
}

void* x11_shadow_subsystem_thread(x11ShadowSubsystem* subsystem)
{
	XEvent xevent;
	DWORD status;
	DWORD nCount;
	UINT64 cTime;
	DWORD dwTimeout;
	DWORD dwInterval;
	UINT64 frameTime;
	HANDLE events[32];
	wMessage message;
	wMessagePipe* MsgPipe;

	MsgPipe = subsystem->MsgPipe;

	nCount = 0;
	events[nCount++] = subsystem->event;
	events[nCount++] = MessageQueue_Event(MsgPipe->In);

	subsystem->captureFrameRate = 16;
	dwInterval = 1000 / subsystem->captureFrameRate;
	frameTime = GetTickCount64() + dwInterval;

	while (1)
	{
		cTime = GetTickCount64();
		dwTimeout = (cTime > frameTime) ? 0 : frameTime - cTime;

		status = WaitForMultipleObjects(nCount, events, FALSE, dwTimeout);

		if (WaitForSingleObject(MessageQueue_Event(MsgPipe->In), 0) == WAIT_OBJECT_0)
		{
			if (MessageQueue_Peek(MsgPipe->In, &message, TRUE))
			{
				if (message.id == WMQ_QUIT)
					break;

				x11_shadow_subsystem_process_message(subsystem, &message);
			}
		}

		if (WaitForSingleObject(subsystem->event, 0) == WAIT_OBJECT_0)
		{
			if (XEventsQueued(subsystem->display, QueuedAlready))
			{
				XNextEvent(subsystem->display, &xevent);
				x11_shadow_handle_xevent(subsystem, &xevent);
			}
		}

		if ((status == WAIT_TIMEOUT) || (GetTickCount64() > frameTime))
		{
			x11_shadow_check_resize(subsystem);
			x11_shadow_screen_grab(subsystem);
			x11_shadow_query_cursor(subsystem, FALSE);

			dwInterval = 1000 / subsystem->captureFrameRate;
			frameTime += dwInterval;
		}
	}

	ExitThread(0);
	return NULL;
}

int x11_shadow_subsystem_base_init(x11ShadowSubsystem* subsystem)
{
	if (subsystem->display)
		return 1; /* initialize once */

	if (!getenv("DISPLAY"))
		setenv("DISPLAY", ":0", 1);

	if (!XInitThreads())
		return -1;

	subsystem->display = XOpenDisplay(NULL);

	if (!subsystem->display)
	{
		WLog_ERR(TAG, "failed to open display: %s", XDisplayName(NULL));
		return -1;
	}

	subsystem->xfds = ConnectionNumber(subsystem->display);
	subsystem->number = DefaultScreen(subsystem->display);
	subsystem->screen = ScreenOfDisplay(subsystem->display, subsystem->number);
	subsystem->depth = DefaultDepthOfScreen(subsystem->screen);
	subsystem->width = WidthOfScreen(subsystem->screen);
	subsystem->height = HeightOfScreen(subsystem->screen);
	subsystem->root_window = RootWindow(subsystem->display, subsystem->number);

	return 1;
}

int x11_shadow_xfixes_init(x11ShadowSubsystem* subsystem)
{
#ifdef WITH_XFIXES
	int xfixes_event;
	int xfixes_error;
	int major, minor;

	if (!XFixesQueryExtension(subsystem->display, &xfixes_event, &xfixes_error))
		return -1;

	if (!XFixesQueryVersion(subsystem->display, &major, &minor))
		return -1;

	subsystem->xfixes_cursor_notify_event = xfixes_event + XFixesCursorNotify;

	XFixesSelectCursorInput(subsystem->display, subsystem->root_window,
			XFixesDisplayCursorNotifyMask);

	return 1;
#else
	return -1;
#endif
}

int x11_shadow_xinerama_init(x11ShadowSubsystem* subsystem)
{
#ifdef WITH_XINERAMA
	int major, minor;
	int xinerama_event;
	int xinerama_error;

	x11_shadow_subsystem_base_init(subsystem);

	if (!XineramaQueryExtension(subsystem->display, &xinerama_event, &xinerama_error))
		return -1;

	if (!XDamageQueryVersion(subsystem->display, &major, &minor))
		return -1;

	if (!XineramaIsActive(subsystem->display))
		return -1;

	return 1;
#else
	return -1;
#endif
}

int x11_shadow_xdamage_init(x11ShadowSubsystem* subsystem)
{
#ifdef WITH_XDAMAGE
	int major, minor;
	int damage_event;
	int damage_error;

	if (!subsystem->use_xfixes)
		return -1;

	if (!XDamageQueryExtension(subsystem->display, &damage_event, &damage_error))
		return -1;

	if (!XDamageQueryVersion(subsystem->display, &major, &minor))
		return -1;

	if (major < 1)
		return -1;

	subsystem->xdamage_notify_event = damage_event + XDamageNotify;
	subsystem->xdamage = XDamageCreate(subsystem->display, subsystem->root_window, XDamageReportDeltaRectangles);

	if (!subsystem->xdamage)
		return -1;

#ifdef WITH_XFIXES
	subsystem->xdamage_region = XFixesCreateRegion(subsystem->display, NULL, 0);

	if (!subsystem->xdamage_region)
		return -1;
#endif

	return 1;
#else
	return -1;
#endif
}

int x11_shadow_xshm_init(x11ShadowSubsystem* subsystem)
{
	Bool pixmaps;
	int major, minor;
	XGCValues values;

	if (!XShmQueryExtension(subsystem->display))
		return -1;

	if (!XShmQueryVersion(subsystem->display, &major, &minor, &pixmaps))
		return -1;

	if (!pixmaps)
		return -1;

	subsystem->fb_shm_info.shmid = -1;
	subsystem->fb_shm_info.shmaddr = (char*) -1;
	subsystem->fb_shm_info.readOnly = False;

	subsystem->fb_image = XShmCreateImage(subsystem->display, subsystem->visual, subsystem->depth,
			ZPixmap, NULL, &(subsystem->fb_shm_info), subsystem->width, subsystem->height);

	if (!subsystem->fb_image)
	{
		WLog_ERR(TAG, "XShmCreateImage failed");
		return -1;
	}

	subsystem->fb_shm_info.shmid = shmget(IPC_PRIVATE,
			subsystem->fb_image->bytes_per_line * subsystem->fb_image->height, IPC_CREAT | 0600);

	if (subsystem->fb_shm_info.shmid == -1)
	{
		WLog_ERR(TAG, "shmget failed");
		return -1;
	}

	subsystem->fb_shm_info.shmaddr = shmat(subsystem->fb_shm_info.shmid, 0, 0);
	subsystem->fb_image->data = subsystem->fb_shm_info.shmaddr;

	if (subsystem->fb_shm_info.shmaddr == ((char*) -1))
	{
		WLog_ERR(TAG, "shmat failed");
		return -1;
	}

	if (!XShmAttach(subsystem->display, &(subsystem->fb_shm_info)))
		return -1;

	XSync(subsystem->display, False);

	shmctl(subsystem->fb_shm_info.shmid, IPC_RMID, 0);

	subsystem->fb_pixmap = XShmCreatePixmap(subsystem->display,
			subsystem->root_window, subsystem->fb_image->data, &(subsystem->fb_shm_info),
			subsystem->fb_image->width, subsystem->fb_image->height, subsystem->fb_image->depth);

	XSync(subsystem->display, False);

	if (!subsystem->fb_pixmap)
		return -1;

	values.subwindow_mode = IncludeInferiors;
	values.graphics_exposures = False;

	subsystem->xshm_gc = XCreateGC(subsystem->display, subsystem->root_window,
			GCSubwindowMode | GCGraphicsExposures, &values);

	XSetFunction(subsystem->display, subsystem->xshm_gc, GXcopy);
	XSync(subsystem->display, False);

	return 1;
}

int x11_shadow_enum_monitors(MONITOR_DEF* monitors, int maxMonitors)
{
	int index;
	Display* display;
	int displayWidth;
	int displayHeight;
	int numMonitors = 0;
	MONITOR_DEF* monitor;

	if (!getenv("DISPLAY"))
		setenv("DISPLAY", ":0", 1);

	display = XOpenDisplay(NULL);

	if (!display)
	{
		WLog_ERR(TAG, "failed to open display: %s", XDisplayName(NULL));
		return -1;
	}

	displayWidth = WidthOfScreen(DefaultScreenOfDisplay(display));
	displayHeight = HeightOfScreen(DefaultScreenOfDisplay(display));

#ifdef WITH_XINERAMA
	{
		int major, minor;
		int xinerama_event;
		int xinerama_error;
		XineramaScreenInfo* screen;
		XineramaScreenInfo* screens;

		if (XineramaQueryExtension(display, &xinerama_event, &xinerama_error) &&
				XDamageQueryVersion(display, &major, &minor) && XineramaIsActive(display))
		{
			screens = XineramaQueryScreens(display, &numMonitors);

			if (numMonitors > maxMonitors)
				numMonitors = maxMonitors;

			if (screens && (numMonitors > 0))
			{
				for (index = 0; index < numMonitors; index++)
				{
					screen = &screens[index];
					monitor = &monitors[index];

					monitor->left = screen->x_org;
					monitor->top = screen->y_org;
					monitor->right = monitor->left + screen->width;
					monitor->bottom = monitor->top + screen->height;
					monitor->flags = (index == 0) ? 1 : 0;
				}
			}

			XFree(screens);
		}
	}
#endif

	XCloseDisplay(display);

	if (numMonitors < 1)
	{
		index = 0;
		numMonitors = 1;

		monitor = &monitors[index];

		monitor->left = 0;
		monitor->top = 0;
		monitor->right = displayWidth;
		monitor->bottom = displayHeight;
		monitor->flags = 1;
	}

	return numMonitors;
}

int x11_shadow_subsystem_init(x11ShadowSubsystem* subsystem)
{
	int i;
	int pf_count;
	int vi_count;
	int nextensions;
	char** extensions;
	XVisualInfo* vi;
	XVisualInfo* vis;
	XVisualInfo template;
	XPixmapFormatValues* pf;
	XPixmapFormatValues* pfs;
	MONITOR_DEF* virtualScreen;

	subsystem->numMonitors = x11_shadow_enum_monitors(subsystem->monitors, 16);

	x11_shadow_subsystem_base_init(subsystem);

	if ((subsystem->depth != 24) && (subsystem->depth != 32))
	{
		WLog_ERR(TAG, "unsupported X11 server color depth: %d", subsystem->depth);
		return -1;
	}

	extensions = XListExtensions(subsystem->display, &nextensions);

	if (!extensions || (nextensions < 0))
		return -1;

	for (i = 0; i < nextensions; i++)
	{
		if (strcmp(extensions[i], "Composite") == 0)
			subsystem->composite = TRUE;
	}

	XFreeExtensionList(extensions);

	if (subsystem->composite)
		subsystem->use_xdamage = FALSE;

	pfs = XListPixmapFormats(subsystem->display, &pf_count);

	if (!pfs)
	{
		WLog_ERR(TAG, "XListPixmapFormats failed");
		return -1;
	}

	for (i = 0; i < pf_count; i++)
	{
		pf = pfs + i;

		if (pf->depth == subsystem->depth)
		{
			subsystem->bpp = pf->bits_per_pixel;
			subsystem->scanline_pad = pf->scanline_pad;
			break;
		}
	}
	XFree(pfs);

	ZeroMemory(&template, sizeof(template));
	template.class = TrueColor;
	template.screen = subsystem->number;

	vis = XGetVisualInfo(subsystem->display, VisualClassMask | VisualScreenMask, &template, &vi_count);

	if (!vis)
	{
		WLog_ERR(TAG, "XGetVisualInfo failed");
		return -1;
	}

	for (i = 0; i < vi_count; i++)
	{
		vi = vis + i;

		if (vi->depth == subsystem->depth)
		{
			subsystem->visual = vi->visual;
			break;
		}
	}
	XFree(vis);

	XSelectInput(subsystem->display, subsystem->root_window, SubstructureNotifyMask);

	subsystem->cursorMaxWidth = 256;
	subsystem->cursorMaxHeight = 256;
	subsystem->cursorPixels = _aligned_malloc(subsystem->cursorMaxWidth * subsystem->cursorMaxHeight * 4, 16);

	if (!subsystem->cursorPixels)
		return -1;

	x11_shadow_query_cursor(subsystem, TRUE);

	if (subsystem->use_xfixes)
	{
		if (x11_shadow_xfixes_init(subsystem) < 0)
			subsystem->use_xfixes = FALSE;
	}

	if (subsystem->use_xinerama)
	{
		if (x11_shadow_xinerama_init(subsystem) < 0)
			subsystem->use_xinerama = FALSE;
	}

	if (subsystem->use_xshm)
	{
		if (x11_shadow_xshm_init(subsystem) < 0)
			subsystem->use_xshm = FALSE;
	}

	if (subsystem->use_xdamage)
	{
		if (x11_shadow_xdamage_init(subsystem) < 0)
			subsystem->use_xdamage = FALSE;
	}

	if (!(subsystem->event = CreateFileDescriptorEvent(NULL, FALSE, FALSE,
							subsystem->xfds, WINPR_FD_READ)))
		return -1;

	virtualScreen = &(subsystem->virtualScreen);

	virtualScreen->left = 0;
	virtualScreen->top = 0;
	virtualScreen->right = subsystem->width;
	virtualScreen->bottom = subsystem->height;
	virtualScreen->flags = 1;

	WLog_INFO(TAG, "X11 Extensions: XFixes: %d Xinerama: %d XDamage: %d XShm: %d",
			subsystem->use_xfixes, subsystem->use_xinerama, subsystem->use_xdamage, subsystem->use_xshm);

	return 1;
}

int x11_shadow_subsystem_uninit(x11ShadowSubsystem* subsystem)
{
	if (!subsystem)
		return -1;

	if (subsystem->display)
	{
		XCloseDisplay(subsystem->display);
		subsystem->display = NULL;
	}

	if (subsystem->event)
	{
		CloseHandle(subsystem->event);
		subsystem->event = NULL;
	}

	if (subsystem->cursorPixels)
	{
		_aligned_free(subsystem->cursorPixels);
		subsystem->cursorPixels = NULL;
	}

	return 1;
}

int x11_shadow_subsystem_start(x11ShadowSubsystem* subsystem)
{
	if (!subsystem)
		return -1;

	if (!(subsystem->thread = CreateThread(NULL, 0,
			(LPTHREAD_START_ROUTINE) x11_shadow_subsystem_thread,
			(void*) subsystem, 0, NULL)))
	{
		WLog_ERR(TAG, "Failed to create thread");
		return -1;
	}

	return 1;
}

int x11_shadow_subsystem_stop(x11ShadowSubsystem* subsystem)
{
	if (!subsystem)
		return -1;

	if (subsystem->thread)
	{
		if (MessageQueue_PostQuit(subsystem->MsgPipe->In, 0))
			WaitForSingleObject(subsystem->thread, INFINITE);
		CloseHandle(subsystem->thread);
		subsystem->thread = NULL;
	}

	return 1;
}

x11ShadowSubsystem* x11_shadow_subsystem_new()
{
	x11ShadowSubsystem* subsystem;

	subsystem = (x11ShadowSubsystem*) calloc(1, sizeof(x11ShadowSubsystem));

	if (!subsystem)
		return NULL;

#ifdef WITH_PAM
	subsystem->Authenticate = (pfnShadowAuthenticate) x11_shadow_pam_authenticate;
#endif

	subsystem->SynchronizeEvent = (pfnShadowSynchronizeEvent) x11_shadow_input_synchronize_event;
	subsystem->KeyboardEvent = (pfnShadowKeyboardEvent) x11_shadow_input_keyboard_event;
	subsystem->UnicodeKeyboardEvent = (pfnShadowUnicodeKeyboardEvent) x11_shadow_input_unicode_keyboard_event;
	subsystem->MouseEvent = (pfnShadowMouseEvent) x11_shadow_input_mouse_event;
	subsystem->ExtendedMouseEvent = (pfnShadowExtendedMouseEvent) x11_shadow_input_extended_mouse_event;

	subsystem->composite = FALSE;
	subsystem->use_xshm = FALSE; /* temporarily disabled */
	subsystem->use_xfixes = TRUE;
	subsystem->use_xdamage = FALSE;
	subsystem->use_xinerama = TRUE;

	return subsystem;
}

void x11_shadow_subsystem_free(x11ShadowSubsystem* subsystem)
{
	if (!subsystem)
		return;

	x11_shadow_subsystem_uninit(subsystem);

	free(subsystem);
}

FREERDP_API int X11_ShadowSubsystemEntry(RDP_SHADOW_ENTRY_POINTS* pEntryPoints)
{
	pEntryPoints->New = (pfnShadowSubsystemNew) x11_shadow_subsystem_new;
	pEntryPoints->Free = (pfnShadowSubsystemFree) x11_shadow_subsystem_free;

	pEntryPoints->Init = (pfnShadowSubsystemInit) x11_shadow_subsystem_init;
	pEntryPoints->Uninit = (pfnShadowSubsystemInit) x11_shadow_subsystem_uninit;

	pEntryPoints->Start = (pfnShadowSubsystemStart) x11_shadow_subsystem_start;
	pEntryPoints->Stop = (pfnShadowSubsystemStop) x11_shadow_subsystem_stop;

	pEntryPoints->EnumMonitors = (pfnShadowEnumMonitors) x11_shadow_enum_monitors;

	return 1;
}


text:
package com.example.lit.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.lit.R;

/**
 * A simple {@link Fragment} subclass.
 */
public class FriendsFragment extends Fragment {

    public FriendsFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_friends, container, false);
    }

}


text:
/*
 * REST API Documentation for Schoolbus
 *
 * API Sample
 *
 * OpenAPI spec version: v1
 *
 *
 */

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
using SchoolBusAPI;
using System.Text;
using System.Net;
using Newtonsoft.Json;
using SchoolBusAPI.Models;

namespace SchoolBusAPI.Test
{
	public class SchoolBusOwnerNoteApiIntegrationTest
    {
		private readonly TestServer _server;
		private readonly HttpClient _client;

		/// <summary>
        /// Setup the test
        /// </summary>
		public SchoolBusOwnerNoteApiIntegrationTest()
		{
			_server = new TestServer(new WebHostBuilder()
            .UseEnvironment("Development")
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseStartup<Startup>());
            _client = _server.CreateClient();
		}

		[Fact]
		/// <summary>
        /// Integration test for SchoolbusownernotesBulkPost
        /// </summary>
		public async void TestSchoolbusownernotesBulkPost()
		{
            var request = new HttpRequestMessage(HttpMethod.Post, "/api/schoolbusownernotes/bulk");
            request.Content = new StringContent("[]", Encoding.UTF8, "application/json");
            var response = await _client.SendAsync(request);
            response.EnsureSuccessStatusCode();
        }

		[Fact]
		/// <summary>
        /// Integration test for SchoolbusownernotesGet
        /// </summary>
		public async void TestSchoolbusOwnerNotes()
		{
            // now create a school bus owner record

            var request = new HttpRequestMessage(HttpMethod.Post, "/api/schoolbusownernotes");
            SchoolBusOwnerNote schoolBusOwnerNote = new SchoolBusOwnerNote();

            var jsonString = schoolBusOwnerNote.ToJson();

            request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");

            var response = await _client.SendAsync(request);
            response.EnsureSuccessStatusCode();

            // parse as JSON.
            jsonString = await response.Content.ReadAsStringAsync();

            schoolBusOwnerNote = JsonConvert.DeserializeObject<SchoolBusOwnerNote>(jsonString);
            // get the id
            var id = schoolBusOwnerNote.Id;

            // now do an update.
            request = new HttpRequestMessage(HttpMethod.Put, "/api/schoolbusownernotes/" + id);
            request.Content = new StringContent(schoolBusOwnerNote.ToJson(), Encoding.UTF8, "application/json");
            response = await _client.SendAsync(request);
            response.EnsureSuccessStatusCode();

            // do a get.
            request = new HttpRequestMessage(HttpMethod.Get, "/api/schoolbusownernotes/" + id);
            response = await _client.SendAsync(request);
            response.EnsureSuccessStatusCode();

            // parse as JSON.
            jsonString = await response.Content.ReadAsStringAsync();
            schoolBusOwnerNote = JsonConvert.DeserializeObject<SchoolBusOwnerNote>(jsonString);

            // do a delete.
            request = new HttpRequestMessage(HttpMethod.Post, "/api/schoolbusownernotes/" + id + "/delete");
            response = await _client.SendAsync(request);
            response.EnsureSuccessStatusCode();

            // should get a 404 if we try a get now.
            request = new HttpRequestMessage(HttpMethod.Get, "/api/schoolbusownernotes/" + id);
            response = await _client.SendAsync(request);
            Assert.Equal(response.StatusCode, HttpStatusCode.NotFound);
        }

    }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE401_Memory_Leak__strdup_char_01.c
Label Definition File: CWE401_Memory_Leak__strdup.label.xml
Template File: sources-sinks-01.tmpl.c
*/
/*
 * @description
 * CWE: 401 Memory Leak
 * BadSource:  Allocate data using strdup()
 * GoodSource: Allocate data on the stack
 * Sinks:
 *    GoodSink: call free() on data
 *    BadSink : no deallocation of data
 * Flow Variant: 01 Baseline
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

#ifndef OMITBAD

void CWE401_Memory_Leak__strdup_char_01_bad()
{
    char * data;
    data = NULL;
    {
        char myString[] = "myString";
        /* POTENTIAL FLAW: Allocate memory from the heap using a function that requires free() for deallocation */
        data = strdup(myString);
        /* Use data */
        printLine(data);
    }
    /* POTENTIAL FLAW: No deallocation of memory */
    /* no deallocation */
    ; /* empty statement needed for some flow variants */
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
    char * data;
    data = NULL;
    /* FIX: Use memory allocated on the stack with ALLOCA */
    data = (char *)ALLOCA(100*sizeof(char));
    /* Initialize then use data */
    strcpy(data, "a string");
    printLine(data);
    /* POTENTIAL FLAW: No deallocation of memory */
    /* no deallocation */
    ; /* empty statement needed for some flow variants */
}

/* goodB2G uses the BadSource with the GoodSink */
static void goodB2G()
{
    char * data;
    data = NULL;
    {
        char myString[] = "myString";
        /* POTENTIAL FLAW: Allocate memory from the heap using a function that requires free() for deallocation */
        data = strdup(myString);
        /* Use data */
        printLine(data);
    }
    /* FIX: Deallocate memory initialized in the source */
    free(data);
}

void CWE401_Memory_Leak__strdup_char_01_good()
{
    goodG2B();
    goodB2G();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE401_Memory_Leak__strdup_char_01_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE401_Memory_Leak__strdup_char_01_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
"""Class wrappers to adapt BridgeDB old unittests in :mod:`bridgedb.Tests` to
be compatible with the newer :api:`twisted.trial` unittests in this directory.
"""

from __future__ import print_function
from __future__ import unicode_literals

import binascii
import doctest
import glob
import logging
import os
import warnings

from twisted.python import monkey
from twisted.trial import unittest

from bridgedb import Tests
from bridgedb.test import deprecated

warnings.filterwarnings('ignore', module="bridgedb\.Tests")
pyunit = __import__('unittest')

def generateTrialAdaptedDoctestsSuite():
    """Dynamically generates a :class:`unittest.TestSuite` all containing
    discovered doctests within the installed ``bridgedb`` package.
    """
    bridgedb     = __import__('bridgedb')
    fakedGlobals = globals().update({'bridgedb': bridgedb})
    modulePath   = bridgedb.__path__[0]

    #: The package directories to search for source code with doctests.
    packagePaths = [modulePath,
                    os.path.join(modulePath, 'parse'),
                    os.path.join(modulePath, 'test')]
    #: The source code files which will be searched for doctests.
    files = []
    #: The cls.testSuites which the test methods will be generated from.
    testSuites = []

    packages = [os.path.join(pkg, '*.py') for pkg in packagePaths]
    [files.extend(glob.glob(pkg)) for pkg in packages]

    for filename in files:
        testSuites.append(
            doctest.DocFileSuite(filename,
                                 module_relative=False,
                                 globs=fakedGlobals))
    return testSuites

def monkeypatchTests():
    """Monkeypatch the old unittests, replacing new, refactored code with their
    original equivalents from :mod:`bridgedb.test.deprecated`.

    The first patch replaces the newer parsing function,
    :func:`~bridgedb.parse.networkstatus.parseALine`, with the older,
    :func:`deprecated one <bridgedb.test.deprecated.parseORAddressLine>` (the
    old function was previously located at
    ``bridgedb.Bridges.parseORAddressLine``).

    The second patch replaces the new :class:`~bridgedb.parse.addr.PortList`,
    with the :class:`older one <bridgedb.test.deprecated.PortList>` (which
    was previously located at ``bridgedb.Bridges.PortList``).

    The third, forth, and fifth monkeypatches add some module-level attributes
    back into :mod:`bridgedb.Bridges`.

    :rtype: :api:`~twisted.python.monkey.MonkeyPatcher`
    :returns: A :api:`~twisted.python.monkey.MonkeyPatcher`, preloaded with
              patches from :mod:`bridgedb.test.deprecated`.
    """
    patcher = monkey.MonkeyPatcher()
    patcher.addPatch(Tests.networkstatus, 'parseALine',
                     deprecated.parseORAddressLine)
    patcher.addPatch(Tests.addr, 'PortList', deprecated.PortList)
    patcher.addPatch(Tests.bridgedb.Bridges, 'PORTSPEC_LEN', 16)
    patcher.addPatch(Tests.bridgedb.Bridges, 're_ipv4', deprecated.re_ipv4)
    patcher.addPatch(Tests.bridgedb.Bridges, 're_ipv6', deprecated.re_ipv6)
    patcher.addPatch(Tests.bridgedb.Bridges, 'HEX_FP_LEN', 40)
    patcher.addPatch(Tests.bridgedb.Bridges, 'toHex', binascii.b2a_hex)
    patcher.addPatch(Tests.bridgedb.Bridges, 'fromHex', binascii.a2b_hex)
    patcher.addPatch(Tests.bridgedb.Bridges, 'is_valid_fingerprint',
                     deprecated.is_valid_fingerprint)
    return patcher

class DynamicTestCaseMeta(type):
    """You know how scary the seemingly-arbitrary constants in elliptic curve
    cryptography seem? Well, I am over nine thousand times more scary. Dynamic
    warez… beware! Be afraid; be very afraid.

    :ivar testResult: An :class:`unittest.TestResult` adapted with
                      :api:`twisted.trial.unittest.PyUnitResultAdapter`, for
                      storing test failures and successes in.

    A base class which uses this metaclass should define the following class
    attributes:

    :ivar testSuites: A list of :class:`unittest.TestSuite`s (or their
                      :mod:`doctest` or :api:`twisted.trial` equivalents).
    :ivar methodPrefix: A string to prefix the generated method names
                        with. (default: 'test_')
    """

    testResult = unittest.PyUnitResultAdapter(pyunit.TestResult())

    def __new__(cls, name, bases, attrs):
        """Construct the initialiser for a new
        :api:`twisted.trial.unittest.TestCase`.
        """
        logging.debug("Metaclass __new__ constructor called for %r" % name)

        if not 'testSuites' in attrs:
            attrs['testSuites'] = list()
        if not 'methodPrefix' in attrs:
            attrs['methodPrefix'] = 'test_'

        testSuites   = attrs['testSuites']
        methodPrefix = attrs['methodPrefix']
        logging.debug(
            "Metaclass __new__() class %r(testSuites=%r, methodPrefix=%r)" %
            (name, '\n\t'.join([str(ts) for ts in testSuites]), methodPrefix))

        generatedMethods = cls.generateTestMethods(testSuites, methodPrefix)
        attrs.update(generatedMethods)
        #attrs['init'] = cls.__init__  # call the standard initialiser
        return super(DynamicTestCaseMeta, cls).__new__(cls, name, bases, attrs)

    @classmethod
    def generateTestMethods(cls, testSuites, methodPrefix='test_'):
        """Dynamically generate methods and their names for a
        :api:`twisted.trial.unittest.TestCase`.

        :param list testSuites: A list of :class:`unittest.TestSuite`s (or
                                their :mod:`doctest` or :api:`twisted.trial`
                                equivalents).
        :param str methodPrefix: A string to prefix the generated method names
                                 with. (default: 'test_')
        :rtype: dict
        :returns: A dictionary of class attributes whose keys are dynamically
                  generated method names (prefixed with **methodPrefix**), and
                  whose corresponding values are dynamically generated methods
                  (taken out of the class attribute ``testSuites``).
        """
        def testMethodFactory(test, name):
            def createTestMethod(test):
                def testMethod(*args, **kwargs):
                    """When this function is generated, a methodname (beginning
                    with whatever **methodPrefix** was set to) will also be
                    generated, and the (methodname, method) pair will be
                    assigned as attributes of the generated
                    :api:`~twisted.trial.unittest.TestCase`.
                    """
                    # Get the number of failures before test.run():
                    origFails = len(cls.testResult.original.failures)
                    test.run(cls.testResult)
                    # Fail the generated testMethod if the underlying failure
                    # count has increased:
                    if (len(cls.testResult.original.failures) > origFails):
                        fail = cls.testResult.original.failures[origFails:][0]
                        raise unittest.FailTest(''.join([str(fail[0]),
                                                         str(fail[1])]))
                    return cls.testResult
                testMethod.__name__ = str(name)
                return testMethod
            return createTestMethod(test)

        newAttrs = {}
        for testSuite in testSuites:
            for test in testSuite:
                origName = test.id()
                if origName.find('.') > 0:
                    origFunc = origName.split('.')[-2:]
                    origName = '_'.join(origFunc)
                if origName.endswith('_py'):  # this happens with doctests
                    origName = origName.strip('_py')
                methName = str(methodPrefix + origName).replace('.', '_')
                meth = testMethodFactory(test, methName)
                logging.debug("Set %s.%s=%r" % (cls.__name__, methName, meth))
                newAttrs[methName] = meth
        return newAttrs

class OldUnittests(unittest.TestCase):
    """A wrapper around :mod:`bridgedb.Tests` to produce :api:`~twisted.trial`
    compatible output.

    Generates a :api:`twisted.trial.unittest.TestCase` containing a
    test for each of the individual tests in :mod:`bridgedb.Tests`.

    Each test in this :api:`~twisted.trial.unittest.TestCase`` is dynamically
    generated from one of the old unittests in :mod:`bridgedb.Tests`. Then,
    the class is wrapped to cause the results reporting mechanisms to be
    :api:`~twisted.trial` compatible.

    :returns: A :api:`twisted.trial.unittest.TestCase`.
    """
    __metaclass__ = DynamicTestCaseMeta
    testSuites    = Tests.testSuite()
    testResult    = unittest.PyUnitResultAdapter(pyunit.TestResult())
    methodPrefix  = 'test_regressionsNewCode_'

class MonkeypatchedOldUnittests(unittest.TestCase):
    """A wrapper around :mod:`bridgedb.Tests` to produce :api:`~twisted.trial`
    compatible output.

    For each test in this ``TestCase``, one of the old unittests in
    bridgedb/Tests.py is run. For all of the tests, some functions and classes
    are :api:`twisted.python.monkey.MonkeyPatcher.patch`ed with old,
    deprecated code from :mod:`bridgedb.test.deprecated` to ensure that any
    new code has not caused any regressions.
    """
    __metaclass__ = DynamicTestCaseMeta
    testSuites    = Tests.testSuite()
    testResult    = unittest.PyUnitResultAdapter(pyunit.TestResult())
    methodPrefix  = 'test_regressionsOldCode_'
    patcher       = monkeypatchTests()

    def runWithPatches(self, *args):
        """Replaces :api:`~twisted.trial.unittest.TestCase.run` as the default
        methodName to run. This method calls ``run()`` though
        ``self.patcher.runWithPatches``, using the class **testResult** object.
        """
        self.patcher.runWithPatches(self.run, self.testResult)
        self.patcher.restore()

    def __init__(self, methodName='runWithPatches'):
        super(MonkeypatchedOldUnittests, self).__init__(methodName=methodName)

class TrialAdaptedDoctests(unittest.TestCase):
    """Discovers and runs all doctests within the ``bridgedb`` package.

    Finds all doctests from the directory that BridgeDB was installed in, in
    all Python modules and packages, and runs them with :api:`twisted.trial`.
    """
    __metaclass__ = DynamicTestCaseMeta
    testSuites    = generateTrialAdaptedDoctestsSuite()
    testResult    = unittest.PyUnitResultAdapter(pyunit.TestResult())
    methodPrefix  = 'test_doctestsIn_'


text:
export default function facebookReducer (
  state = {
    isAuthenticated: false,
    payload: null
  }, action) {
  switch (action.type) {
    case 'IS_AUTHENTICATED': {
      return {
        ...state,
        isAuthenticated: true,
        payload: action.payload
      }
    }
  }
  return state;
}


text:
<?php

namespace gries\Pokemath\Numbers;

use gries\Pokemath\PokeNumber;

class Plusle extends PokeNumber
{
    public function __construct()
    {
        parent::__construct('plusle');
    }
}


text:
namespace Ui {
class TelaPrincipal;
}

class TelaPrincipal : public QMainWindow
{
    Q_OBJECT

public:
    explicit TelaPrincipal(QWidget *parent = 0);
    ~TelaPrincipal();

private slots:
    void on_actionCadastrar_triggered();

    void on_actionCadastrar_6_triggered();

    void on_actionCadastrar_5_triggered();

    void on_actionCadastrar_4_triggered();

    void on_actionCadastrar_3_triggered();

    void on_actionCadastrar_2_triggered();

    void on_actionListar_triggered();

    void on_actionListar_2_triggered();

    void on_actionListar_3_triggered();

    void on_actionListar_4_triggered();

    void on_actionListar_5_triggered();

    void on_actionListar_6_triggered();

private:
    Ui::TelaPrincipal *ui;
};

#endif // TELAPRINCIPAL_H


text:
import unittest
import fractions
import GCD

class TestEuclideanGCD(unittest.TestCase):
    def test_gcd(self):
        self.assertEqual(fractions.gcd(30,50),GCD.greatest_common_divisor(30,50))
        self.assertEqual(fractions.gcd(55555,123450),GCD.greatest_common_divisor(55555,123450))
        self.assertEqual(fractions.gcd(-30,-50),GCD.greatest_common_divisor(-30,-50))
        self.assertEqual(fractions.gcd(-1234,1234),GCD.greatest_common_divisor(-1234,1234))

if __name__ == "__main__":
    unittest.main()


text:
USING_NS_CC;

Scene* MainMenuScene::createScene()
{
    auto scene = Scene::create();
    auto layer = MainMenuScene::create();
    scene->addChild(layer);
    return scene;
}

bool MainMenuScene::init()
{
    if ( !Layer::init() )
    {
        return false;
    }

    GameManager::getInstance()->resetGame();
    Size screenSize = Director::getInstance()->getVisibleSize();

    SpriteFrameCache::getInstance()->addSpriteFramesWithFile("res_default.plist");

    auto background = Sprite::create("TankTitle.png");
    background->setPosition(screenSize.width * 0.5, -background->getContentSize().height * 0.5);
    this->addChild(background, -1, kTagBackGround);
    auto act = MoveTo::create(3.0, Vec2(screenSize.width * 0.5, screenSize.height * 0.5));
    auto call = CallFuncN::create(CC_CALLBACK_1(MainMenuScene::showTankIcon, this));
    auto seq = Sequence::create(act, call, NULL);
    seq->setTag(kTagMoveToCenterAction);
    background->runAction(seq);

    MenuItemFont::setFontName("Verdana-Bold");
    MenuItemFont::setFontSize(20);

    auto beginItem = CCMenuItemFont::create("开始", CC_CALLBACK_1(MainMenuScene::beginItemTouched, this));
    beginItem->setPosition(screenSize.width * 0.5, screenSize.height * 0.4);
    auto optionItem = CCMenuItemFont::create("选项", CC_CALLBACK_1(MainMenuScene::optionItemTouched, this));
    optionItem->setPosition(screenSize.width * 0.5, screenSize.height * 0.3);

    auto menu = Menu::create(beginItem, optionItem, NULL);
    menu->setPosition(Vec2::ZERO);
    menu->setTag(100);
    background->addChild(menu, 1);

    return true;
}

void MainMenuScene::onEnter()
{
    Layer::onEnter();

    // Register Touch Event
    auto dispatcher = Director::getInstance()->getEventDispatcher();
    auto listener = EventListenerTouchOneByOne::create();
    listener->onTouchBegan = [](Touch* touch, Event* event) {
        cocos2d::log("You touched %f, %f", touch->getLocationInView().x, touch->getLocationInView().y);
        auto target = static_cast<MainMenuScene*>(event->getCurrentTarget());
        if (target->getChildByTag(kTagBackGround)->getNumberOfRunningActions() > 0) {
            target->getChildByTag(kTagBackGround)->stopAllActions();
            Size screenSize = Director::getInstance()->getVisibleSize();
            auto move = MoveTo::create(0.1f, Vec2(screenSize.width * 0.5, screenSize.height * 0.5));
            auto call = CallFuncN::create(CC_CALLBACK_1(MainMenuScene::showTankIcon, target));
            auto seq = Sequence::create(move, call, NULL);
            target->getChildByTag(kTagBackGround)->runAction(seq);
        }
        return true;
    };
    listener->onTouchMoved = [](Touch* touch, Event* event) {
        cocos2d::log("touch moved");
    };
    listener->onTouchEnded = [](Touch* touch, Event* event) {
        cocos2d::log("touch ended");
    };
    listener->setSwallowTouches(false);//不向下传递触摸
    dispatcher->addEventListenerWithSceneGraphPriority(listener, this);
}

void MainMenuScene::onExit()
{
    // You don't need to unregister listeners here as new API
    // removes all linked listeners automatically in CCNode's destructor
    // which is the base class for all cocos2d DRAWING classes

    Layer::onExit();
}

void MainMenuScene::showTankIcon(Ref* pSender)
{
    Size screenSize = Director::getInstance()->getVisibleSize();
    auto sprite = Sprite::createWithSpriteFrameName("tank11.png");
    sprite->setPosition(Vec2(screenSize.width * 0.4, screenSize.height * 0.4));
    sprite->setRotation(90);
    this->addChild(sprite);
    auto animation = AnimationHelper::createWithSpriteFrame("tank1", 2, 0.1);
    auto animate = Animate::create(animation);
    auto repeat = RepeatForever::create(animate);
    sprite->runAction(repeat);
}

void MainMenuScene::beginItemTouched(Ref* pSender)
{
    Director::getInstance()->replaceScene(LevelScene::createScene());
}

void MainMenuScene::optionItemTouched(Ref* pSender)
{

}


text:
'use strict';

/**
 * sub_sport enum
 *
 * ****WARNING**** This file is auto-generated! Do NOT edit this file.
 */

const BaseType = require('../type');
const FieldTypes = require('../fieldTypes');

const ValuesMap = {
	0: 'generic',
	1: 'treadmill',                // Run/Fitness Equipment
	2: 'street',                   // Run
	3: 'trail',                    // Run
	4: 'track',                    // Run
	5: 'spin',                     // Cycling
	6: 'indoor_cycling',           // Cycling/Fitness Equipment
	7: 'road',                     // Cycling
	8: 'mountain',                 // Cycling
	9: 'downhill',                 // Cycling
	10: 'recumbent',               // Cycling
	11: 'cyclocross',              // Cycling
	12: 'hand_cycling',            // Cycling
	13: 'track_cycling',           // Cycling
	14: 'indoor_rowing',           // Fitness Equipment
	15: 'elliptical',              // Fitness Equipment
	16: 'stair_climbing',          // Fitness Equipment
	17: 'lap_swimming',            // Swimming
	18: 'open_water',              // Swimming
	19: 'flexibility_training',    // Training
	20: 'strength_training',       // Training
	21: 'warm_up',                 // Tennis
	22: 'match',                   // Tennis
	23: 'exercise',                // Tennis
	24: 'challenge',               // Tennis
	25: 'indoor_skiing',           // Fitness Equipment
	26: 'cardio_training',         // Training
	27: 'indoor_walking',          // Walking/Fitness Equipment
	28: 'e_bike_fitness',          // E-Biking
	29: 'bmx',                     // Cycling
	30: 'casual_walking',          // Walking
	31: 'speed_walking',           // Walking
	32: 'bike_to_run_transition',  // Transition
	33: 'run_to_bike_transition',  // Transition
	34: 'swim_to_bike_transition', // Transition
	35: 'atv',                     // Motorcycling
	36: 'motocross',               // Motorcycling
	37: 'backcountry',             // Alpine Skiing/Snowboarding
	38: 'resort',                  // Alpine Skiing/Snowboarding
	39: 'rc_drone',                // Flying
	40: 'wingsuit',                // Flying
	41: 'whitewater',              // Kayaking/Rafting
	254: 'all'
};

class SubSport extends BaseType {
	static getValues() {
		return ValuesMap;
	}

	static getSourceType() {
		return FieldTypes.Enum;
	}
};

module.exports = SubSport;

SubSport.Generic = 0;
SubSport.Treadmill = 1;
SubSport.Street = 2;
SubSport.Trail = 3;
SubSport.Track = 4;
SubSport.Spin = 5;
SubSport.IndoorCycling = 6;
SubSport.Road = 7;
SubSport.Mountain = 8;
SubSport.Downhill = 9;
SubSport.Recumbent = 10;
SubSport.Cyclocross = 11;
SubSport.HandCycling = 12;
SubSport.TrackCycling = 13;
SubSport.IndoorRowing = 14;
SubSport.Elliptical = 15;
SubSport.StairClimbing = 16;
SubSport.LapSwimming = 17;
SubSport.OpenWater = 18;
SubSport.FlexibilityTraining = 19;
SubSport.StrengthTraining = 20;
SubSport.WarmUp = 21;
SubSport.Match = 22;
SubSport.Exercise = 23;
SubSport.Challenge = 24;
SubSport.IndoorSkiing = 25;
SubSport.CardioTraining = 26;
SubSport.IndoorWalking = 27;
SubSport.EBikeFitness = 28;
SubSport.Bmx = 29;
SubSport.CasualWalking = 30;
SubSport.SpeedWalking = 31;
SubSport.BikeToRunTransition = 32;
SubSport.RunToBikeTransition = 33;
SubSport.SwimToBikeTransition = 34;
SubSport.Atv = 35;
SubSport.Motocross = 36;
SubSport.Backcountry = 37;
SubSport.Resort = 38;
SubSport.RcDrone = 39;
SubSport.Wingsuit = 40;
SubSport.Whitewater = 41;
SubSport.All = 254;


text:
import React from 'react';
//
import { Basic, Advanced, Managers, Domain } from 'czechidm-core';

const treeTypeManager = new Managers.TreeTypeManager();
const identityManager = new Managers.IdentityManager();

/**
 * Contract's specific sync configuration
 *
 * @author Vít Švanda
 */
class SyncContractConfig extends Basic.AbstractContent {

  constructor(props, context) {
    super(props, context);
    this.state = {
      ...this.state,
      defaultTreeType: null,
      treeNodeSearchParameters: new Domain.SearchParameters().setFilter('treeTypeId', props.synchronizationConfig ? props.synchronizationConfig.defaultTreeType : Domain.SearchParameters.BLANK_UUID)
    };
  }

  getContentKey() {
    return 'acc:content.system.systemSynchronizationConfigDetail';
  }

  getData(allData) {
    if (this.refs.formSpecific) {
      return this.refs.formSpecific.getData(allData);
    }
  }

  isFormValid() {
    if (this.refs.formSpecific) {
      return this.refs.formSpecific.isFormValid();
    }
  }

  _onChangeTreeType(treeType) {
    const treeTypeId = treeType ? treeType.id : null;
    this.setState({
      treeTypeId,
      treeNodeSearchParameters: this.state.treeNodeSearchParameters.setFilter('treeTypeId', treeTypeId || Domain.SearchParameters.BLANK_UUID)
    }, () => {
      this.refs.defaultTreeNode.setValue(null);
    });
  }

  render() {
    const {treeNodeSearchParameters, treeTypeId} = this.state;
    const {synchronizationConfig, showLoading, isNew} = this.props;
    let resutlTreeTypeId = treeTypeId;
    if (!resutlTreeTypeId && synchronizationConfig) {
      resutlTreeTypeId = isNew ? treeTypeId : synchronizationConfig.defaultTreeType;
    }
    return (
      <Basic.AbstractForm ref="formSpecific" data={synchronizationConfig} showLoading={showLoading} className="panel-body">
        <Basic.SelectBox
          ref="defaultTreeType"
          required
          manager={treeTypeManager}
          label={this.i18n('contractConfigDetail.defaultTreeType.label')}
          helpBlock={this.i18n('contractConfigDetail.defaultTreeType.helpBlock')}
          onChange={this._onChangeTreeType.bind(this)}/>
        <Advanced.TreeNodeSelect
          ref="defaultTreeNode"
          label={this.i18n('contractConfigDetail.defaultTreeNode.label')}
          helpBlock={this.i18n('contractConfigDetail.defaultTreeNode.helpBlock')}
          forceSearchParameters={ treeNodeSearchParameters }
          hidden={ !resutlTreeTypeId }/>
        <Basic.SelectBox
          ref="defaultLeader"
          manager={identityManager}
          label={this.i18n('contractConfigDetail.defaultLeader.label')}
          helpBlock={this.i18n('contractConfigDetail.defaultLeader.helpBlock')}/>
        <Basic.Checkbox
          ref="startOfHrProcesses"
          label={this.i18n('contractConfigDetail.startOfHrProcesses.label')}
          helpBlock={this.i18n('contractConfigDetail.startOfHrProcesses.helpBlock')}/>
        <Basic.Checkbox
          ref="startAutoRoleRec"
          label={this.i18n('contractConfigDetail.startAutoRoleRec.label')}
          helpBlock={this.i18n('contractConfigDetail.startAutoRoleRec.helpBlock')}/>
      </Basic.AbstractForm>
    );
  }
}

export default SyncContractConfig;