text:
var should = require('chai').should(),
    module = require('../dist/pubsubcutioner');

var event1 = 'event1',
    event2 = 'event2',
    eventR = 'event.+',
    value1 = 'value1',
    value2 = 'value2';

describe('#publish-subscribe-simple', function() {
    it('Test subscribe and publish', function() {
        module.subscribe(event1, function(name, data){
            name.should.equal(event1);
            data.value.should.equal(value1);
        });
        module.publish(event1, {value: value1});
    });
    after(function() {
        module.unsubscribe(event1);
    });
});

describe('#publish-subscribe-regex', function() {
    it('Test subscribe and publish regex', function() {
        var results = {};
        module.subscribe(eventR, function(name, data){
            results[name] = data;
        });
        module.publish(event1, {value: value1});
        module.publish(event2, {value: value2});
        Object.keys(results).length.should.equal(2);
    });
    after(function() {
        module.unsubscribe(event1);
        module.unsubscribe(event2);
    });
});

describe('#publish-subscribe-exception', function() {
    it('Test subscribe and publish exceptions', function() {
        module.subscribe(event1, function(name, data){
            console.log('event published correctly!');
        });
        module.publish(event1, {});
        // if we made it here there is no crash :)
    });
    after(function() {
        module.unsubscribe(event1);
    });
});


text:
package apple.mediaplayer;

import java.io.*;
import java.nio.*;
import java.util.*;
import com.google.j2objc.annotations.*;
import com.google.j2objc.runtime.*;
import com.google.j2objc.runtime.block.*;
import apple.audiotoolbox.*;
import apple.corefoundation.*;
import apple.coregraphics.*;
import apple.coreservices.*;
import apple.foundation.*;
import apple.uikit.*;

/*<javadoc>*/
/*</javadoc>*/
@Adapter
public abstract class MPPlayableContentDataSourceAdapter
    extends Object
    implements MPPlayableContentDataSource {

    @NotImplemented("beginLoadingChildItemsAtIndexPath:completionHandler:")
    public void beginLoadingChildItems(NSIndexPath indexPath, @Block VoidBlock1<NSError> completionHandler) { throw new UnsupportedOperationException(); }
    @NotImplemented("childItemsDisplayPlaybackProgressAtIndexPath:")
    public boolean childItemsDisplayPlaybackProgress(NSIndexPath indexPath) { throw new UnsupportedOperationException(); }
    @NotImplemented("numberOfChildItemsAtIndexPath:")
    public @MachineSizedSInt long getNumberOfChildItems(NSIndexPath indexPath) { throw new UnsupportedOperationException(); }
    @NotImplemented("contentItemAtIndexPath:")
    public MPContentItem getContentItem(NSIndexPath indexPath) { throw new UnsupportedOperationException(); }

}

redpajama_set_name: RedPajamaGithub


text:
package madgik.exareme.worker.art.container;

import java.io.Serializable;

/**
 * @author heraldkllapi
 */
public interface ContainerJob extends Serializable {

    // TODO(DSD) check
    //  public JobResources getResources();
    ContainerJobType getType();
}


text:
import os
import sys
sys.path.append(os.getcwd())
from macdivert import MacDivert, DivertHandle
from impacket import ImpactDecoder
from signal import SIGINT, signal

__author__ = 'huangyan13@baidu.com'

def work():
    libdivert = MacDivert()
    decoder = ImpactDecoder.IPDecoder()
    with DivertHandle(libdivert, 0, "ip from any to any via en0") as fid:
        pcap = fid.open_pcap('sniff.pcap')
        # register stop loop signal
        signal(SIGINT, lambda x, y: fid.close())
        while not fid.closed:
            try:
                packet = fid.read(timeout=0.5)
            except:
                continue
            if packet.valid:
                if packet.proc:
                    proc_str = '%s: %d\t' % \
                               (packet.proc.comm, packet.proc.pid)
                else:
                    proc_str = 'Unknown process\t'

                if fid.is_inbound(packet.sockaddr):
                    direct_str = 'inbound'
                elif fid.is_outbound(packet.sockaddr):
                    direct_str = 'outbound'
                else:
                    direct_str = 'impossible packet!'

                print proc_str + direct_str
                print decoder.decode(packet.ip_data)
            if packet.valid and not fid.closed:
                # re-inject the packet
                fid.write(packet)
                # save the packet into sniff.pcap
                pcap.write(packet)

if __name__ == '__main__':
    work()


text:
import React, { Component } from 'react'

import SearchbarContainer from 'components/navbar/searchbar/SearchbarContainer'
import SettingsContainer from 'components/settings/SettingsContainer'

import './Navbar.css'

import logo from 'components/navbar/logo.svg'

class Navbar extends Component {
  render() {
    return (

            <SearchbarContainer />

            <button className="uk-offcanvas-close uk-close uk-icon uk-light" type="button" data-uk-close />

Remindre

<SearchbarContainer />

    )
  }
}

export default Navbar


text:
package com.cloudibpm.eso.reference;

import com.cloudibpm.core.reference.ReferenceDetail;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@Repository
public class ReferenceDetailEso  {

	private final JdbcTemplate jdbcTemplate;

	@Autowired
	public ReferenceDetailEso(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	/**
	 * Insert a new reference detail into repository. This method will insert or
	 * update values into all fields of fm_reference_detail.
	 *
	 * @param ref
	 *            ReferenceDetail
	 * @throws SQLException
	 */
	public void insert(final ReferenceDetail ref) throws SQLException {

		String sql = "insert into fm_reference_detail "
				+ "(Pk_ReferenceDetail,Code,Text,Description,ParentCode,Status,Fk_Parent,Fk_CurrOwner,Fk_Owner,CustomColumn1,CustomColumn2,CustomColumn3) "
				+ "values (?,?,?,?,?,?,?,?,?,?,?,?)";
		jdbcTemplate.update(sql, new PreparedStatementSetter() {
			@Override
			public void setValues(PreparedStatement stmt) throws SQLException {
				stmt.setString(1, ref.getId());
				stmt.setString(2, ref.getCode());
				stmt.setString(3, StringEscapeUtils.escapeSql(ref.getName()));
				stmt.setString(4, StringEscapeUtils.escapeSql(ref.getDescription()));
				stmt.setString(5, ref.getParentCode());
				stmt.setInt(6, ref.getStatus());
				stmt.setString(7, ref.getParent());
				stmt.setString(8, ref.getCurrOwner());
				stmt.setString(9, ref.getOwner());
				stmt.setString(10, StringEscapeUtils.escapeSql(ref.getCustomColumn1()));
				stmt.setString(11, StringEscapeUtils.escapeSql(ref.getCustomColumn2()));
				stmt.setString(12, StringEscapeUtils.escapeSql(ref.getCustomColumn3()));
			}
		});

	}

	public void update(final ReferenceDetail ref) throws SQLException {

		String sql = "update fm_reference_detail set"
				+ " Code=?,Text=?,Description=?,ParentCode=?,Status=?,Fk_Parent=?,CustomColumn1=?,CustomColumn2=?,CustomColumn3=? "
				+ "where Pk_ReferenceDetail=?";
		jdbcTemplate.update(sql, new PreparedStatementSetter() {
			@Override
			public void setValues(PreparedStatement stmt) throws SQLException {
				stmt.setString(1, ref.getCode());
				stmt.setString(2, StringEscapeUtils.escapeSql(ref.getName()));
				stmt.setString(3, StringEscapeUtils.escapeSql(ref.getDescription()));
				stmt.setString(4, ref.getParentCode());
				stmt.setInt(5, ref.getStatus());
				stmt.setString(6, ref.getParent());
				stmt.setString(7, StringEscapeUtils.escapeSql(ref.getCustomColumn1()));
				stmt.setString(8, StringEscapeUtils.escapeSql(ref.getCustomColumn2()));
				stmt.setString(9, StringEscapeUtils.escapeSql(ref.getCustomColumn3()));
				stmt.setString(10, ref.getId());
			}
		});

	}

	public void delete(final ReferenceDetail ref) throws SQLException {

		String sql = "delete from fm_reference_detail where Pk_ReferenceDetail=?";
		jdbcTemplate.update(sql, new Object[] { ref.getId() });

	}

	/**
	 *
	 * @param pk
	 * @return ReferenceDetail
	 * @throws Exception
	 */
	public ReferenceDetail queryByPk(String pk) throws Exception {

		String sql = "Select Pk_ReferenceDetail,Code,Text,Description,ParentCode,Status,Fk_Parent,Fk_CurrOwner,Fk_Owner,CustomColumn1,CustomColumn2,CustomColumn3 "
				+ "from fm_reference_detail where Pk_ReferenceDetail=?";
		List<ReferenceDetail> list = jdbcTemplate.query(sql, new Object[] { pk }, new RowMapper<ReferenceDetail>() {
			public ReferenceDetail mapRow(ResultSet rs, int rowNum) throws SQLException {
				return getReferenceDetailFromResultSet(new ReferenceDetail(), rs);
			}
		});

		if (!list.isEmpty())
			return list.get(0);
		else
			return null;
	}

	/**
	 *
	 * @param fk_curOwner
	 * @return ReferenceDetail List
	 * @throws Exception
	 */
	public List<ReferenceDetail> queryAllReferenceDetails(String fk_curOwner) throws Exception {

		String sql = "Select Pk_ReferenceDetail,Code,Text,Description,ParentCode,Status,Fk_Parent,Fk_CurrOwner,Fk_Owner,CustomColumn1,CustomColumn2,CustomColumn3 "
				+ "from fm_reference_detail where Fk_CurrOwner=?";
		List<ReferenceDetail> procList = jdbcTemplate.query(sql, new Object[] { fk_curOwner },
				new RowMapper<ReferenceDetail>() {
					public ReferenceDetail mapRow(ResultSet rs, int rowNum) throws SQLException {
						return getReferenceDetailFromResultSet(new ReferenceDetail(), rs);
					}
				});

		return procList;
	}

	/**
	 *
	 * @param parentCode
	 * @param fk_curOwner
	 * @return
	 * @throws Exception
	 */
	public List<ReferenceDetail> queryAllReferenceDetails(String parentCode, String fk_curOwner) throws Exception {

		if (parentCode == null || parentCode.equals("")) {
			String sql = "Select Pk_ReferenceDetail,Code,Text,Description,ParentCode,Status,Fk_Parent,Fk_CurrOwner,Fk_Owner,CustomColumn1,CustomColumn2,CustomColumn3 "
					+ "from fm_reference_detail where ParentCode is null and Fk_CurrOwner=?";
			List<ReferenceDetail> procList = jdbcTemplate.query(sql, new Object[] { fk_curOwner },
					new RowMapper<ReferenceDetail>() {
						public ReferenceDetail mapRow(ResultSet rs, int rowNum) throws SQLException {
							return getReferenceDetailFromResultSet(new ReferenceDetail(), rs);
						}
					});

			return procList;
		} else {
			String sql = "Select Pk_ReferenceDetail,Code,Text,Description,ParentCode,Status,Fk_Parent,Fk_CurrOwner,Fk_Owner,CustomColumn1,CustomColumn2,CustomColumn3 "
					+ "from fm_reference_detail where ParentCode=? and Fk_CurrOwner=?";
			List<ReferenceDetail> procList = jdbcTemplate.query(sql, new Object[] { parentCode, fk_curOwner },
					new RowMapper<ReferenceDetail>() {
						public ReferenceDetail mapRow(ResultSet rs, int rowNum) throws SQLException {
							return getReferenceDetailFromResultSet(new ReferenceDetail(), rs);
						}
					});

			return procList;
		}

	}

	public ReferenceDetail getReferenceDetailFromResultSet(ReferenceDetail ref, ResultSet rs) throws SQLException {
		ref.setId(rs.getString("Pk_ReferenceDetail"));
		ref.setCode(rs.getString("Code"));
		ref.setName(rs.getString("Text"));
		ref.setDescription(rs.getString("Description"));
		ref.setParentCode(rs.getString("ParentCode"));
		ref.setStatus(rs.getInt("Status"));
		ref.setParent(rs.getString("Fk_Parent"));
		ref.setCurrOwner(rs.getString("Fk_CurrOwner"));
		ref.setOwner(rs.getString("Fk_Owner"));
		ref.setCustomColumn1(rs.getString("CustomColumn1"));
		ref.setCustomColumn2(rs.getString("CustomColumn2"));
		ref.setCustomColumn3(rs.getString("CustomColumn3"));
		return ref;
	}

	public void deleteAllDetails(final String fk_ref) throws SQLException {

		String sql = "delete from fm_reference_detail where Fk_CurrOwner=?";
		jdbcTemplate.update(sql, new Object[] { fk_ref });

	}

}


text:
body {
	padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}

.post-current {
	border-left: 6px solid #636ee7;
}

.post-inner {
	margin-left: 10px;
	word-wrap: break-word;
}

.post-other {

	margin-top: 10px;
	margin-bottom: 10px;
	border-left: 6px solid #c3b8b8;
}


text:
bowandarrow
===========

## Bow and Arrow game in C.

### How to play:

To move the archer (up or down), press W or S (respectively).
To fire an arrow, press space.
Every balloon is worth 100 points.
When the game's over, each arrow left will give you extra 50 points.

Enjoy!

Coded by @joaosieben.


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>com.baselhack17</groupId>
    <artifactId>traffic-project-parent</artifactId>
    <version>0.1-SNAPSHOT</version>
  </parent>

  <artifactId>traffic-project-backend</artifactId>
  <version>0.1-SNAPSHOT</version>

  <properties>
    <java.version>1.8</java.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
      <version>1.5.8.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>joda-time</groupId>
      <artifactId>joda-time</artifactId>
      <version>2.9.9</version>
    </dependency>
    <dependency>
      <groupId>com.jayway.jsonpath</groupId>
      <artifactId>json-path</artifactId>
      <version>2.2.0</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>19.0</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <version>1.5.8.RELEASE</version>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.20.1</version>
      </plugin>
    </plugins>
  </build>

</project>


text:
<!--
  ~ The MIT License (MIT)
  ~
  ~ Copyright (c) 2014-2017 the original author or authors.
  ~
  ~ Permission is hereby granted, free of charge, to any person obtaining a copy
  ~ of this software and associated documentation files (the "Software"), to deal
  ~ in the Software without restriction, including without limitation the rights
  ~ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  ~ copies of the Software, and to permit persons to whom the Software is
  ~ furnished to do so, subject to the following conditions:
  ~
  ~ The above copyright notice and this permission notice shall be included in
  ~ all copies or substantial portions of the Software.
  ~
  ~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  ~ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  ~ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  ~ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  ~ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  ~ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  ~ THE SOFTWARE.
  ~
  -->

<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>tk.mybatis</groupId>
        <artifactId>mapper-parent</artifactId>
        <version>3</version>
    </parent>
    <artifactId>mapper-weekend</artifactId>
    <version>1.1.5</version>

    <name>weekend</name>
    <description>Mybatis通用Mapper扩展 - weekend</description>

    <developers>
        <developer>
            <name>liuyuyu</name>
            <email>liuyuyu2333@gmail.com</email>
        </developer>
        <developer>
            <name>abel533</name>
            <email>abel533@gmail.com</email>
        </developer>
        <developer>
            <name>chinaerserver</name>
            <email>chinaerserver@gmail.com</email>
        </developer>
    </developers>

    <properties>
        <jdk.version>1.8</jdk.version>
        <mapper-module.version>1.1.5</mapper-module.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
        </dependency>
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-core</artifactId>
            <version>${mapper-module.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-base</artifactId>
            <version>${mapper-module.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>


text:
/**
 * @Author: liushaobo2005@163.com
 * @Date: 2017.5.11 下午 6:40
 * @Desc: 公共组件 - FloatButton
 * @Name: FloatButton.js
 * @LifeCycle:https://github.com/kinshasa/react-native-qatest
 */

import React, {Component} from "react";
import {PanResponder, StyleSheet, View, Dimensions, Text, TouchableNativeFeedback} from "react-native";
import Util from "../../../common/utils/Util";
import {Actions} from "react-native-router-flux";

const window = Dimensions.get('window');

const CIRCLE_SIZE = 45;

const BTN_BACKGROUND_COLOR = '#B6B6B6';
const BTN_BACKGROUND_COLOR_TOUCH = '#838383';
var _previousLeft = window.width - CIRCLE_SIZE;
var _previousTop = window.height / 2;

var lastLeft = _previousLeft;
var lastTop = _previousTop;

/**
 自定义拖拽菜单
 **/
export default class FloatButton extends Component {

    constructor(props) {
        super(props);

        this.state = {
            style: {
                backgroundColor: BTN_BACKGROUND_COLOR,
            },
        };

    }

    times = {
        begin: 0, end: 0, diff: 0
    };

    //用户开始触摸屏幕的时候,是否愿意成为响应者;
    onStartShouldSetPanResponder = (evt, gestureState) => {
        Log('FloatButton::onStartShouldSetPanResponder');
        return true;
    };

    //在每一个触摸点开始移动的时候,再询问一次是否响应触摸交互;
    onMoveShouldSetPanResponder = (evt, gestureState) => {
        Log('FloatButton::onMoveShouldSetPanResponder');
        return true;
    };

    // 开始手势操作。给用户一些视觉反馈,让他们知道发生了什么事情!
    onPanResponderGrant = (evt, gestureState) => {
        this.times.begin = new Date().getTime();
        Log('FloatButton::onPanResponderGrant', this.times.begin);
        this.setState({
            style: {
                backgroundColor: BTN_BACKGROUND_COLOR_TOUCH,
                left: _previousLeft,
                top: _previousTop,
            }
        });
    };

    // 最近一次的移动距离为gestureState.move{X,Y}
    onPanResponderMove = (evt, gestureState) => {
        //Log('onPanResponderMove');
        _previousLeft = lastLeft + gestureState.dx;
        _previousTop = lastTop + gestureState.dy;

        if (_previousLeft <= 0) {
            _previousLeft = 0;
        }
        if (_previousTop <= 0) {
            _previousTop = 0;
        }
        if (_previousLeft >= Util.size.width - CIRCLE_SIZE) {
            _previousLeft = Util.size.width - CIRCLE_SIZE;
        }
        if (_previousTop >= Util.size.height - CIRCLE_SIZE) {
            _previousTop = Util.size.height - CIRCLE_SIZE;
        }

        //实时更新
        this.setState({
            style: {
                backgroundColor: BTN_BACKGROUND_COLOR_TOUCH,
                left: _previousLeft,
                top: _previousTop,
            }
        });
    };

    // 用户放开了所有的触摸点,且此时视图已经成为了响应者。
    // 一般来说这意味着一个手势操作已经成功完成。
    onPanResponderEnd = (evt, gestureState) => {
        this.times.end = new Date().getTime();
        Log('FloatButton::onPanResponderEnd', this.times.end);

        lastLeft = _previousLeft;
        lastTop = _previousTop;

        this.changePosition();
    };

    /**
     根据位置做出相应处理
     **/
    changePosition() {
        this.times.diff = this.times.end - this.times.begin;
        Log('FloatButton::changePosition', this.times.diff);

        if(this.times.diff < 200){
            //单次点击小于200毫秒,认为单点
            Log('FloatButton::changePosition() onClick and jump to Log');
            Actions.LoggerContainer();
        }

        if (_previousLeft + CIRCLE_SIZE / 2 <= Util.size.width / 2) {
            //left
            _previousLeft = lastLeft = 0;

            this.setState({
                style: {
                    backgroundColor: BTN_BACKGROUND_COLOR,
                    left: _previousLeft,
                    top: _previousTop,
                }
            });
        } else {
            _previousLeft = lastLeft = Util.size.width - CIRCLE_SIZE;

            this.setState({
                style: {
                    left: _previousLeft,
                    top: _previousTop,
                }
            });
        }
    }

    componentWillMount() {
        this._panResponder = PanResponder.create({
            onStartShouldSetPanResponder: this.onStartShouldSetPanResponder,
            onMoveShouldSetPanResponder: this.onMoveShouldSetPanResponder,
            onPanResponderGrant: this.onPanResponderGrant,
            onPanResponderMove: this.onPanResponderMove,
            onPanResponderRelease: this.onPanResponderEnd,
            onPanResponderTerminate: this.onPanResponderEnd,
        });
    }

    render() {
        return (
            <View
                {...this._panResponder.panHandlers}
                style={[FloatButtonStyles.circle, this.state.style]}>
                <TouchableNativeFeedback>
                    <Text style={FloatButtonStyles.text}>Dev</Text>
                </TouchableNativeFeedback>
            </View>
        );
    }
}

const FloatButtonStyles = StyleSheet.create({
    circle: {
        width: CIRCLE_SIZE,
        height: CIRCLE_SIZE,
        borderRadius: CIRCLE_SIZE / 2,
        backgroundColor: BTN_BACKGROUND_COLOR,
        position: 'absolute',
        top: _previousTop,
        left: _previousLeft,
        alignItems: 'center',
        justifyContent: 'center',
        opacity: 0.7,
    },
    text: {}
});


text:
// @filename: /src/foo.mts
export function foo() {
    return "";
}

// @filename: /src/bar.mts
// Extensionless relative path ES import in an ES module
import { foo } from "./foo"; // should error, suggest adding ".mjs"
import { baz } from "./baz"; // should error, ask for extension, no extension suggestion


text:
// An OS-independent sleep function.

#include BOSS_WEBRTC_U_system_wrappers__include__sleep_h //original-code:"system_wrappers/include/sleep.h"

#ifdef _WIN32
// For Sleep()
#include BOSS_FAKEWIN_V_windows_h //original-code:<windows.h>
#else
// For nanosleep()
#include <time.h>
#endif

namespace webrtc {

void SleepMs(int msecs) {
#ifdef _WIN32
  Sleep(msecs);
#else
  struct timespec short_wait;
  struct timespec remainder;
  short_wait.tv_sec = msecs / 1000;
  short_wait.tv_nsec = (msecs % 1000) * 1000 * 1000;
  nanosleep(&short_wait, &remainder);
#endif
}

}  // namespace webrtc


text:
namespace Rosalia.Core.Api
{
    using System;
    using Rosalia.Core.Api.Behaviors;
    using Rosalia.Core.Tasks;
    using Rosalia.Core.Tasks.Futures;
    using Rosalia.Core.Tasks.Results;

    public interface ITaskRegistryApi
    {
        ITaskFuture<T> Task<T>(
            string id,
            ITask<T> task,
            params ITaskBehavior[] behaviors) where T : class;

        ITaskFuture<T> Task<T>(
            string id,
            Func<TaskContext, ITaskResult<T>> task,
            params ITaskBehavior[] behaviors) where T : class;

        ITaskFuture<T> Task<T>(
            string id,
            Func<ITaskResult<T>> task,
            params ITaskBehavior[] behaviors) where T : class;

        ITaskFuture<T> Task<T>(
            string id,
            Func<TaskContext, ITask<T>> task,
            params ITaskBehavior[] behaviors) where T : class;

        ITaskFuture<T> Task<T>(
            string id,
            ITaskFuture<T> task,
            params ITaskBehavior[] behaviors) where T : class;

        ITaskFuture<Nothing> Task(
            string id,
            Action<TaskContext> task,
            params ITaskBehavior[] behaviors);

        ITaskFuture<Nothing> Task(
            string id,
            Action task,
            params ITaskBehavior[] behaviors);

        ITaskFuture<T> Task<T>(
            string id,
            ITaskRegistry<T> task,
            params ITaskBehavior[] behaviors) where T : class;

        ITaskFuture<T> Task<T>(
            string id,
            Func<TaskContext, ITaskRegistry<T>> task,
            params ITaskBehavior[] behaviors) where T : class;
    }
}


text:
module MedicinesHelper
end


text:
<?php

require_once ROOT_DIR . 'vendor/autoload.php';
use Mailgun\Mailgun;

/**
 *  Source: https://github.com/mailgun/mailgun-php
 */
class Mailer {
    private $mailgun;
    private $domain;

    // First, instantiate the SDK with your API credentials and define your domain.
    public function __construct() {
        $this->mailgun = new Mailgun(MAILGUN_API_KEY);
        $this->domain = MAINGUN_API_DOMAIN;
    }

    // compose and send your message.
    public function send($email) {
        // Build options

        $options = array(
            'from'    => $email->getFrom(),
            'to'      => $email->getTo(),
            'subject' => $email->getSubject()
            );
        if (null !== $email->getText()) {
            $options['text'] = $email->getText();
        }

        if (null !== $email->getHtml()) {
            $options['html'] = $email->getHtml();
        }

        $this->mailgun->sendMessage($this->domain, $options);
    }
}


text:
using namespace std;
using namespace xlinq;

template<typename T>
class ModuloSummator
{
private:
	T _moduloRoot;
public:
	ModuloSummator(T moduloRoot) : _moduloRoot(moduloRoot) {}

	T operator()(T first, T second)
	{
		return (first % _moduloRoot + second % _moduloRoot) % _moduloRoot;
	}
};

TEST(XlinqAggregateTest, EmptyCollectionThrowsException)
{
	auto numbers = list<int>();
	try
	{
		from(numbers) >> aggregate(std::plus<int>());
		FAIL();
	}
	catch (IterationFinishedException exc)
	{
	}
}

TEST(XlinqAggregateTest, AggregateAsSum)
{
	int numbers[] = { 3, 7, -32, 0, -1, 2 };
	ASSERT_EQ(-21, from(numbers) >> aggregate(std::plus<int>()));
}

TEST(XlinqAggregateTest, AggregateAsModuloSum)
{
	int numbers[] = { 3, 7, 32, 0, 1, 2 };
	ASSERT_EQ(3, from(numbers) >> aggregate(ModuloSummator<int>(7)));
}

TEST(XlinqAggregateResultTest, EmptyCollectionThrowsException)
{
	auto numbers = list<int>();
	try
	{
		from(numbers) >> aggregate(std::plus<int>());
		FAIL();
	}
	catch (IterationFinishedException exc)
	{
	}
}

TEST(XlinqAggregateResultTest, AggregateUsingDelegate)
{
	int numbers[] = { 3, 7, -32, 0, -1, 3 };
	auto result = (from(numbers) >> aggregate(0.1f, [](float first, int second) { return first + second * 0.1f; }));
	ASSERT_TRUE(0.001f > (-1.9f - result));
}


text:
package ch.ivyteam.ivy.maven.engine;

import static org.assertj.core.api.Assertions.assertThat;

import org.apache.maven.plugin.MojoExecutionException;
import org.junit.Rule;
import org.junit.Test;

import ch.ivyteam.ivy.maven.BaseEngineProjectMojoTest;
import ch.ivyteam.ivy.maven.engine.EngineControl.EngineState;
import ch.ivyteam.ivy.maven.log.LogCollector;
import ch.ivyteam.ivy.maven.test.StopTestEngineMojo;

public class TestEngineControl extends BaseEngineProjectMojoTest {
  @Rule
  public RunnableEngineMojoRule<StopTestEngineMojo> rule = new RunnableEngineMojoRule<StopTestEngineMojo>(
          StopTestEngineMojo.GOAL);

  @Test
  public void resolveEngineState() throws MojoExecutionException {
    EngineControl controller = rule.getMojo().createEngineController();
    assertThat(controller.state()).isNotNull();
  }

  @Test
  public void stopNotRunningEngine() throws Exception {
    EngineControl controller = rule.getMojo().createEngineController();
    controller.stop();
    assertThat(controller.state()).isEqualTo(EngineState.STOPPED);
  }

  @Test
  public void startAndStop() throws Exception {
    LogCollector log = new LogCollector();
    rule.getMojo().setLog(log);
    EngineControl controller = rule.getMojo().createEngineController();
    assertThat(controller.state()).isEqualTo(EngineState.STOPPED);
    controller.start();
    assertThat(controller.state()).isEqualTo(EngineState.RUNNING);
    controller.stop();
    assertThat(controller.state()).isEqualTo(EngineState.STOPPED);
    assertThat(log.getErrors()).isEmpty();
  }

  @Test
  public void evalutateIvyContext() {
    assertThat(EngineControl.evaluateIvyContextFromUrl("sys/info.xhtml")).isEmpty();
    assertThat(EngineControl.evaluateIvyContextFromUrl("/sys/info123.xhtml")).isEmpty();
    assertThat(EngineControl.evaluateIvyContextFromUrl("ivy/sys/info")).isEqualTo("ivy/");
    assertThat(EngineControl.evaluateIvyContextFromUrl("/ivy/sys/test")).isEqualTo("ivy/");
    assertThat(EngineControl.evaluateIvyContextFromUrl("")).isEmpty();
  }

}


text:
badger
======

Fetch this package with:

      go get github.com/kennylevinsen/gocrypto/badger

More info can be found at http://godoc.org/github.com/kennylevinsen/gocrypto/badger


text:
@interface SBSplashLogo : NVScreenSpacedRectangle {

}

@end


text:
import {ManagedReducerActionArgs} from 'angular-redux';

const actionKeys = {
  add: 'ADD_ALBUM',
  edit: 'EDIT_ALBUM',
  delete: 'DELETE_ALBUM'
};

export const actions = {
  addGenre: album => {
    return {
      type: actionKeys.add,
      payload: album
    }
  },
  editGenre: album => {
    return {
      type: actionKeys.edit,
      payload: album
    }
  },
  deleteGenre: id => {
    return {
      type: actionKeys.delete,
      payload: id
    }
  }
};

export const handlers = {
  [actionKeys.add]: (state, action) => {
    console.log('add handler');
    if (action.payload) {

    }
    return state;
  },
  [actionKeys.edit]: (state, action) => {
    console.log('edit handler!');
    return state;
  },
  [actionKeys.delete]: (state, action) => {
    console.log('delete handler!');
    return state;
  }
};


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

	<item android:drawable="@mipmap/ic_menu_query_hl"
	      android:state_checked="true"/>
	<item android:drawable="@mipmap/ic_menu_query_nor"
	      android:state_checked="false"/>
</selector>


text:
// Header file including the delay estimator handle used for testing.

#ifndef MODULES_AUDIO_PROCESSING_UTILITY_DELAY_ESTIMATOR_INTERNAL_H_
#define MODULES_AUDIO_PROCESSING_UTILITY_DELAY_ESTIMATOR_INTERNAL_H_

#include BOSS_WEBRTC_U_modules__audio_processing__utility__delay_estimator_h //original-code:"modules/audio_processing/utility/delay_estimator.h"

typedef union {
  float float_;
  int32_t int32_;
} SpectrumType;

typedef struct {
  // Pointers to mean values of spectrum.
  SpectrumType* mean_far_spectrum;
  // |mean_far_spectrum| initialization indicator.
  int far_spectrum_initialized;

  int spectrum_size;

  // Far-end part of binary spectrum based delay estimation.
  BinaryDelayEstimatorFarend* binary_farend;
} DelayEstimatorFarend;

typedef struct {
  // Pointers to mean values of spectrum.
  SpectrumType* mean_near_spectrum;
  // |mean_near_spectrum| initialization indicator.
  int near_spectrum_initialized;

  int spectrum_size;

  // Binary spectrum based delay estimator
  BinaryDelayEstimator* binary_handle;
} DelayEstimator;

#endif  // MODULES_AUDIO_PROCESSING_UTILITY_DELAY_ESTIMATOR_INTERNAL_H_


text:
package hr.fer.zemris.vhdllab.applets.editor.schema2.model.parameters.constraints;

import hr.fer.zemris.vhdllab.applets.editor.schema2.enums.EConstraintExplanation;
import hr.fer.zemris.vhdllab.applets.editor.schema2.interfaces.IParameterConstraint;

import java.util.Set;

public class BooleanConstraint implements IParameterConstraint {
	private Set<Object> validset;

	/**
	 * Konstruira constraint
	 * koji nema ogranicenja na vrijednosti,
	 * tj. moze poprimiti bilo koji cijeli broj.
	 *
	 */
	public BooleanConstraint() {
		validset = null;
	}

	/**
	 * Stvara constraint kojem je moguce
	 * podesiti koje vrijednosti prihvaca.
	 *
	 * @param validValues
	 * Null ako su sve vrijednosti dopustene,
	 * neki Set<Object> inace.
	 */
	public BooleanConstraint(Set<Object> validValues) {
		validset = validValues;
	}

	public boolean checkValue(Object object) {
		if (object == null) return false;
		if (!(object instanceof Boolean)) return false;
		if (validset == null) return true;
		Boolean val = (Boolean)object;
		if (!validset.contains(val)) return false;
		return true;
	}

	public EConstraintExplanation getExplanation(Object object) {
		if (object == null) return EConstraintExplanation.NULL_PASSED;
		if (!(object instanceof Boolean)) return EConstraintExplanation.WRONG_TYPE;
		if (validset == null) return EConstraintExplanation.ALLOWED;
		Boolean val = (Boolean)object;
		if (!(validset.contains(val))) return EConstraintExplanation.CONSTRAINT_BANNED;
		return EConstraintExplanation.ALLOWED;
	}

	public Set<Object> getPossibleValues() {
		return validset;
	}

	public void setPossibleValues(Set<Object> possibleValues) {
		validset = possibleValues;
	}

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Example: Using NodeList - Ducks Game</title>
    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Sans:400,700,400italic,700italic">
    <link rel="stylesheet" href="../../build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/css/main.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="shortcut icon" type="image/png" href="../assets/favicon.png">

Example: Using NodeList - Ducks Game

<link href="../assets/node/node.css" rel="stylesheet" type="text/css">

This example demonstrates how to use multiple NodeList features to build a simple game.

    <button id="button-reset" class="yui3-button">Reset</button>
    Ducks remaining: 10
    <input type="checkbox" id="show-attitude"/>Show attitude

The HTML

<div class='gallery'>
    <ul class="duck-row">
        <li></li> <!-- each of these will be a duck -->
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
    </ul>
    <div class="water">
        <img class="shadow" src="../assets/node/images/water-shadow.png"/>
        <img src="../assets/node/images/water.png"/>
    </div>
</div>
<button id="button-reset" class="yui3-button">Reset</button>
Ducks remaining: <span class="ducks-remain">10</span>
<input type="checkbox" id="show-attitude"/><label for="show-attitude">Show attitude</label>

YUI Instance

The use statement doesn't include node because it's loaded as a requirement of transition.

YUI().use('transition', 'button', function(Y){
    // code goes here
});

Setting Vars

The variable ducks is used for easily manipulating all the ducks at once.
We'll display various duck comments from the array squawkTextArr on a rotating basis.

var ducks = Y.all('.duck-row li'),
    ducksRemaining = 10, // value for UI display
    squawkTextIndex = 0, // index in the squawkTextArr to use next
    squawkTextArr = [   // duck comments
        '#@&~*Q!',
        'Hey!?',
        '911 on U!',
        "U&nbsp;fly's&nbsp;down",
        'duck&nbsp;pile!',
        'Ricochets&nbsp;kill!',
        'how&nbsp;sporting.',
        "shoe's&nbsp;untied"
    ];

Initializing the Ducks

Repetitive markup is added with the .append() method to all the ducks in the NodeList.
This keeps the original markup simple and clear.

// append the same content for each duck <li>
ducks.append('<img src="../assets/node/images/duck.png"/><div class="squawk"><div class="text">#@&~*Q!</div><div class="small-squawk-bubble"></div></div>');

All the ducks in the NodeList are given the set-up class with the .addClass() method.
This class is found on any duck that has the state of being set up, as opposed to being knocked down.

// give them all the set-up state class
ducks.addClass('set-up');

This state could be a Boolean property, but it's handy as a class,
because a NodeList can be made containing the squawks of all "set up" ducks in this way,
squawks = Y.all('.duck-row .set-up .squawk');
as we'll see in the makeDucksSquawk function.

Making the Ducks Swim

This uses transition to make the ducks swim right to left

// this makes the ducks move from right to left.
// When the duck on the far left disappears from view,
// it's added to the far right end of the row.
var makeDucksSwim = function () {
    var frontDuck;

    // move the duck row to the left one duck space over 2 seconds
    Y.one('.duck-row').transition({
        easing: 'linear',
        left: '-119px',
        duration: 2
    }, function () { // when the row finishes its right to left transition...
        // remove the first duck on the left
        // which has trasitioned out of view
        frontDuck = Y.one('.duck-row li').remove();

        // append the removed first duck onto the right end
        Y.one('.duck-row').appendChild(frontDuck);

        // set the position for the next makeDucksSwim()
        Y.one('.duck-row').setStyle('left', '10px');

        // if there are ducks remaining, make them swim again
        if (ducksRemaining > 0) {
            makeDucksSwim();
        }
    });
}
makeDucksSwim(); // this initializes the ducks swimming

Click Event Handler

// handles a click on a duck
var duckClick = function(e) {
    var squawks;

    // remove the squawk belonging to the duck that was clicked
    e.currentTarget.one('.squawk').setStyles({'top': '-400px', 'opacity': '1'});

    // makes the ducks appear to lay back when clicked
    e.target.transition({
        duration: 0.2,
        height: '3px',
        width: '133px'
    });

    // the clicked duck will no longer have the 'set-up' class/state
    e.currentTarget.removeClass('set-up');
    makeDucksSquawk(); // makes the ducks squawk
    updateDucksRemaining(); // update the number of ducks still set up
};

Squawking Ducks

// this makes the duck's squawks show and hide and get various text
var makeDucksSquawk = function(){
    squawks = Y.all('.duck-row .set-up .squawk'); // a NodeList of the squawks of set-up ducks
    if (Y.one('#show-attitude')._node.checked) {  // only have ducks squawk if the checkbox is checked
        // fill voice bubbles with next text string
        Y.all('.duck-row .set-up .squawk .text').setHTML(squawkTextArr[squawkTextIndex]);

        // increment the index to get the next squawk text
        squawkTextIndex = (squawkTextIndex += 1) % (squawkTextArr.length);
        squawks.transition({
            top: {
                delay: 0.5,
                value: '0px', // drop squawks into position from hidden
                duration: 0   // instant position change
            },
            opacity: { // fade out
                delay: 3.0,
                duration: 0.3,
                value: 0
            }
        }, function(e){
            // after squawks are faded out,
            // move them to hidden position and set opacity to 1 again
            squawks.setStyles({'top': '-400px', 'opacity': '1'});
        });
    }
}

Reset and Ducks Remaining

// This resets all ducks, "ducks remaining" counters, and row position
// make the duck images full height
// start them swimming
var reset = function() {
    Y.all('.duck-row li img').setStyle('height', '55px');
    Y.all('.duck-row li').addClass('set-up');
    updateDucksRemaining();
    makeDucksSwim();
}

// counts the ducks remaining, and updates the UI counter display
var updateDucksRemaining = function() {
    ducksRemaining = Y.all('.gallery li.set-up').size();
    Y.one('.ducks-remain').setHTML(ducksRemaining);
}

Prefer node.delegate() over nodelist.on()

Sometimes you need to create individual subscriptions for each Node in a
NodeList, but usually it's preferable to use
event delegation as shown in this example.

Listeners

// listeners
Y.one('.duck-row').delegate('click', duckClick, 'li');
Y.one('#button-reset').on('click', reset);

Complete Ducks Example Source

<style>
.gallery{
    position: relative;
    background: url(../assets/node/images/background.png);
    width: 638px;
    height: 180px;
    overflow: hidden;
    -moz-border-radius: 8px;
    -webkit-border-radius: 8px;
    border-radius: 8px;
    -moz-box-shadow: 0 0 45px #000 inset, 3px 0 6px rgba(0,0,0,0.8);
    -webkit-box-shadow: 0 0 45px #000 inset, 3px 0 6px rgba(0,0,0,0.8);
    border: 4px solid #637073;
    cursor: crosshair;
    margin: 0.5em 0 0.8em;
}

.water{
    position: absolute;
    top: 114px;
    left: 0;
    width: 677px;
    height: 50px;
}

.water img{
    position: absolute;
    top: 0;
    left: 0;
}

.water .shadow {
    left: 8px;
    opacity: 0.5;
    filter: alpha(opacity=30);
}

.duck-row {
    position: absolute;
    left: 10px;
    top: 57px;
    width: 1340px;
    padding: 0;
    margin: 0;
}

.duck-row li{
    position: relative;
    display: inline-block;
    zoom: 1; *display: inline; /* IE < 8: fake inline-block */
    width: 133px;
    height: 70px;
    margin: 0 -4px 0 0;
    vertical-align: bottom;
}

.duck-row li img{
    position: absolute;
    bottom: 7px;
    left: 0;
}

/* the voice bubble of the ducks */
.duck-row .squawk {
    position: absolute;
    top: -400px;
    left: 50px;
    -moz-border-radius: 4px;
    -webkit-border-radius: 4px;
    border-radius: 4px;
    background-color: #ffe;
    line-height: 1.2em;
    border: solid 1px #cc8;
    -moz-box-shadow: 2px 2px 2px rgba(0,0,0,0.2);
    -webkit-box-shadow: 2px 2px 2px rgba(0,0,0,0.2);
}

.duck-row .squawk .text{
    padding: 0.2em 0.4em 0.2em 0em;
    text-indent: 0.2em;
    overflow: hidden;
}

.small-squawk-bubble{
    position: absolute;
    bottom: -4px;
    left: -8px;
    width: 4px;
    height: 4px;
    border: solid 1px #cc8;
    -moz-border-radius: 3px;
    -webkit-border-radius: 3px;
    border-radius: 3px;
    background-color: #ffe;
    font-size: 2px;
}

#button-reset{
    margin-right: 2em;
}

.ducks-remain{
    font-size: 150%;
}

#show-attitude{
    margin-left: 8em;
}
</style>

    <div class='gallery'>
        <ul class="duck-row">
            <li></li> <!-- each of these will be a duck -->
            <li></li>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
        </ul>
        <div class="water">
            <img class="shadow" src="../assets/node/images/water-shadow.png"/>
            <img src="../assets/node/images/water.png"/>
        </div>
    </div>
    <button id="button-reset" class="yui3-button">Reset</button>
    Ducks remaining: <span class="ducks-remain">10</span>
    <input type="checkbox" id="show-attitude"/><label for="show-attitude">Show attitude</label>

<script>
YUI().use('transition', 'button', function (Y) {

    var ducks = Y.all('.duck-row li'),
        ducksRemaining = 10, // value for UI display
        squawkTextIndex = 0, // index in the squawkTextArr to use next
        squawkTextArr = [   // duck comments
            '#@&~*Q!',
            'Hey!?',
            '911 on U!',
            "U&nbsp;fly's&nbsp;down",
            'duck&nbsp;pile!',
            'Ricochets&nbsp;kill!',
            'how&nbsp;sporting.',
            "shoe's&nbsp;untied"
        ];

    // append the same content for each duck <li>
    ducks.append('<img src="../assets/node/images/duck.png"/><div class="squawk"><div class="text">#@&~*Q!</div><div class="small-squawk-bubble"></div></div>');

    // give them all the set-up state class
    ducks.addClass('set-up');

    // this makes the ducks move from right to left.
    // When the duck on the far left disappears from view,
    // it's added to the far right end of the row.
    var makeDucksSwim = function () {
        var frontDuck;

        // move the duck row to the left one duck space over 2 seconds
        Y.one('.duck-row').transition({
            easing: 'linear',
            left: '-119px',
            duration: 2
        }, function () { // when the row finishes its right to left transition...
            // remove the first duck on the left
            // which has trasitioned out of view
            frontDuck = Y.one('.duck-row li').remove();

            // append the removed first duck onto the right end
            Y.one('.duck-row').appendChild(frontDuck);

            // set the position for the next makeDucksSwim()
            Y.one('.duck-row').setStyle('left', '10px');

            // if there are ducks remaining, make them swim again
            if (ducksRemaining > 0) {
                makeDucksSwim();
            }
        });
    }
    makeDucksSwim(); // this initializes the ducks swimming

    // handles a click on a duck
    var duckClick = function(e) {
        var squawks;

        // remove the squawk belonging to the duck that was clicked
        e.currentTarget.one('.squawk').setStyles({'top': '-400px', 'opacity': '1'});

        // makes the ducks appear to lay back when clicked
        e.target.transition({
            duration: 0.2,
            height: '3px',
            width: '133px'
        });

        // the clicked duck will no longer have the 'set-up' class/state
        e.currentTarget.removeClass('set-up');
        makeDucksSquawk();
        updateDucksRemaining(); // update the number of ducks still set up
    };

    // this makes the duck's squawks show and hide and get various text
    var makeDucksSquawk = function(){
        squawks = Y.all('.duck-row .set-up .squawk'); // a NodeList of the squawks of set-up ducks
        if (Y.one('#show-attitude')._node.checked) {  // only have ducks squawk if the checkbox is checked
            // fill voice bubbles with next text string
            Y.all('.duck-row .set-up .squawk .text').setHTML(squawkTextArr[squawkTextIndex]);

            // increment the index to get the next squawk text
            squawkTextIndex = (squawkTextIndex += 1) % (squawkTextArr.length);
            squawks.transition({
                top: {
                    delay: 0.5,
                    value: '0px', // drop squawks into position from hidden
                    duration: 0   // instant position change
                },
                opacity: { // fade out
                    delay: 3.0,
                    duration: 0.3,
                    value: 0
                }
            }, function(e){
                // after squawks are faded out,
                // move them to hidden position and set opacity to 1 again
                squawks.setStyles({'top': '-400px', 'opacity': '1'});
            });
        }
    }

    // This resets all ducks, "ducks remaining" counters, and row position
    // make the duck images full height
    // start them swimming
    var reset = function() {
        Y.all('.duck-row li img').setStyle('height', '55px');
        Y.all('.duck-row li').addClass('set-up');
        updateDucksRemaining();
        makeDucksSwim();
    }

    // counts the ducks remaining, and updates the UI counter display
    var updateDucksRemaining = function() {
        ducksRemaining = Y.all('.gallery li.set-up').size();
        Y.one('.ducks-remain').setHTML(ducksRemaining);
    }

    // listeners
    Y.one('.duck-row').delegate('click', duckClick, 'li');
    Y.one('#button-reset').on('click', reset);
});
</script>

Examples

                                            Set and Get Properties

                                            DOM Methods

                                            DOM Methods - Store

                                            Handling DOM Events

                                            Using NodeList - Simple

                                            Using NodeList - Ducks Game

                                            Delegating Node Events

                                            Node Positioning

                                            Node Styling

                                            Adding Node Content - Burger Builder

                                            Showing and Hiding

Examples That Use This Component

                                            Photo Browser

                                            Portal Style Example

                                            Accessible Toolbar

                                            Accessible Menu Button

                                            Simple DOM Events

                                            Request XML data from Yahoo! Weather

                                            Request JSON using Yahoo! Pipes


text:
require 'image-inspector-client'
require 'kubeclient'

class ManageIQ::Providers::Kubernetes::ContainerManager::Scanning::Job < Job
  PROVIDER_CLASS = ManageIQ::Providers::Kubernetes::ContainerManager
  INSPECTOR_IMAGE_TAG = '2.1'.freeze
  INSPECTOR_PORT = 8080
  DOCKER_SOCKET = '/var/run/docker.sock'
  SCAN_CATEGORIES = %w(system software)
  POD_POLL_INTERVAL = 10
  IMAGES_GUEST_OS = 'Linux'
  INSPECTOR_HEALTH_PATH = '/healthz'
  ERRCODE_NOTFOUND = 404
  IMAGE_INSPECTOR_SA = 'inspector-admin'
  INSPECTOR_ADMIN_SECRET_PATH = '/var/run/secrets/kubernetes.io/inspector-admin-secret-'
  ATTRIBUTE_SECTION = 'cluster_settings'
  PROXY_ENV_VARIABLES = %w(no_proxy http_proxy https_proxy)

  def load_transitions
    self.state ||= 'initializing'
    {
      :initializing => {'initializing'     => 'waiting_to_start'},
      :start        => {'waiting_to_start' => 'pod_create'},
      :pod_wait     => {'pod_create'       => 'waiting_to_scan',
                        'waiting_to_scan'  => 'waiting_to_scan'},
      :analyze      => {'waiting_to_scan'  => 'scanning'},
      :data         => {'scanning'      => 'synchronizing',
                        'synchronizing' => 'synchronizing'},
      :cleanup      => {'synchronizing'    => 'pod_delete'},
      :abort_job    => {'*'                => 'aborting'},
      :cancel_job   => {'*'                => 'canceling'},
      :cancel       => {'*'                => 'canceling'},
      :finish       => {'pod_delete' => 'finished',
                        'aborting'   => 'finished',
                        'canceling'  => 'finished'},
    }
  end

  def initializing
    # exactly like job.dispatch_start except for storage bits
    _log.info "Dispatch Status is 'pending'"
    update(:dispatch_status => "pending")
  end

  def start
    image = target_entity
    return queue_signal(:abort_job, "no image found", "error") unless image
    return queue_signal(:abort_job, "cannot analyze non docker images", "error") unless image.docker_id

    namespace = ::Settings.ems.ems_kubernetes.miq_namespace

    update!(:options => options.merge(
      :docker_image_id => image.docker_id,
      :image_full_name => image.full_name,
      :pod_name        => "manageiq-img-scan-#{guid[0..4]}",
      :pod_port        => INSPECTOR_PORT,
      :pod_namespace   => namespace
    ))

    _log.info("Getting inspector-admin secret for pod [#{pod_full_name}]")
    begin
      inspector_admin_secret_name = inspector_admin_secret
    rescue SocketError, KubeException => e
      msg = "getting inspector-admin secret failed"
      _log.error("#{msg}: [#{e}]")
      return queue_signal(:abort_job, msg, "error")
    end

    pod = pod_definition(inspector_admin_secret_name)

    _log.info("Creating pod [#{pod_full_name}] to analyze docker image [#{options[:docker_image_id]}] [#{pod.to_json}]")
    begin
      kubernetes_client.create_pod(pod)
    rescue SocketError, KubeException => e
      msg = "pod creation for [#{pod_full_name}] failed"
      _log.error("#{msg}: [#{e}]")
      return queue_signal(:abort_job, msg, "error")
    end

    queue_signal(:pod_wait)
  end

  def pod_wait
    _log.info("waiting for pod #{pod_full_name} to be available")

    client       = kubernetes_client
    health_url   = pod_proxy_url(client, INSPECTOR_HEALTH_PATH)
    http_options = {
      :use_ssl     => health_url.scheme == 'https',
      :verify_mode => ext_management_system.verify_ssl_mode,
      :cert_store  => ext_management_system.ssl_cert_store,
    }

    # TODO: move this to a more appropriate place (lib)
    response = pod_health_poll(client, health_url, http_options)

    case response
    when Net::HTTPOK
      _log.info("pod #{pod_full_name} is ready and accessible")
      queue_signal(:analyze)
    when Net::HTTPServiceUnavailable
      # TODO: check that the pod wasn't terminated (exit code)
      # continue: pod is still not up and running
      _log.info("pod #{pod_full_name} is not available")
      queue_signal(:pod_wait,
                   :deliver_on => POD_POLL_INTERVAL.seconds.from_now.utc)
    else
      msg = "unknown access error to pod #{pod_full_name}: #{response}"
      _log.info(msg)
      queue_signal(:abort_job, msg, "error")
    end
  end

  def verify_scanned_image_id(metadata)
    actual = metadata.Id
    return nil if actual == options[:docker_image_id]
    msg = "cannot analyze image %s with id %s: detected ids were %s" % [
      options[:image_full_name], options[:docker_image_id][0..11], actual[0..11]]

    if metadata.RepoDigests
      metadata.RepoDigests.each do |repo_digest|
        return nil if repo_digest == options[:docker_image_id]
        sha_digest = repo_digest.split('@').last
        return nil if sha_digest == options[:docker_image_id].split('@').last
        msg << ", #{sha_digest[0..11]}"
      end
    end

    msg
  end

  def analyze
    image = target_entity
    return queue_signal(:abort_job, "no image found", "error") unless image

    _log.info("scanning image #{options[:docker_image_id]}")

    scan_args = {
      :pod_namespace => options[:pod_namespace],
      :pod_name      => options[:pod_name],
      :pod_port      => options[:pod_port],
      :guest_os      => IMAGES_GUEST_OS
    }

    verify_error = verify_scanned_image_id(image_inspector_client.fetch_metadata)
    if verify_error
      _log.error(verify_error)
      return queue_signal(:abort_job, verify_error, 'error')
    end

    collect_compliance_data(image)

    image.scan_metadata(SCAN_CATEGORIES,
                        "taskid" => jobid,
                        "host"   => MiqServer.my_server,
                        "args"   => [YAML.dump(scan_args)])
  end

  def collect_compliance_data(image)
    unless OpenscapResult.openscap_available?
      _log.warn "OpenSCAP Binary missing, skipping scan"
      return nil
    end
    _log.info "collecting compliance data for #{options[:docker_image_id]}"
    openscap_result = image.openscap_result || OpenscapResult.new(:container_image => image)
    openscap_result.attach_raw_result(image_inspector_client.fetch_oscap_arf)
    openscap_result.save
  rescue ImageInspectorClient::InspectorClientException => e
    _log.error("collecting compliance data for #{options[:docker_image_id]} with error: #{e}")
  end

  def synchronize
    image = target_entity
    return queue_signal(:abort_job, "no image found", "error") unless image

    image.sync_metadata(SCAN_CATEGORIES,
                        "taskid" => jobid,
                        "host"   => MiqServer.my_server)
  end

  def data(payload)
    payload_document = MiqXml.load(payload)

    if payload_document.root.name.downcase == "summary"
      case operation = payload_document.root.first.name.downcase
      when "scanmetadata" then synchronize
      when "syncmetadata" then queue_signal(:cleanup)
      else raise "Unknown operation #{operation}"
      end
    end
  end

  def delete_pod
    return if options[:pod_name].blank?
    client = kubernetes_client

    begin
      pod = client.get_pod(options[:pod_name], options[:pod_namespace])
    rescue KubeException => e
      if e.error_code == ERRCODE_NOTFOUND
        _log.info("pod #{pod_full_name} not found, skipping delete")
        return
      end
      # TODO: handle the cleanup at a later time
      raise
    end

    pod_jobid = pod.metadata.annotations['manageiq.org/jobid']

    # If the job id is not matching the pod was not created by this
    # job and ManageIQ instance.
    if pod_jobid != jobid
      _log.info("skipping delete for pod #{pod_full_name} with " \
                "job id #{pod_jobid}")
    else
      _log.info("deleting pod #{pod_full_name}")
      begin
        client.delete_pod(options[:pod_name], options[:pod_namespace])
      rescue SocketError, KubeException => e
        _log.info("pod #{pod_full_name} deletion failed: #{e}")
        # TODO: handle the cleanup at a later time
      end
    end
  end

  def cleanup(*args)
    image = target_entity
    if image
      # TODO: check job success / failure
      MiqEvent.raise_evm_job_event(image, :type => "scan", :suffix => "complete")
    end

    delete_pod

  ensure
    case self.state
    when 'aborting' then process_abort(*args)
    when 'canceling' then process_cancel(*args)
    else queue_signal(:finish, 'image analysis completed successfully', 'ok')
    end
  end

  def finish(*args)
    # exactly like job.dispatch_finish except for storage bits
    _log.info "Dispatch Status is 'finished'"
    update(:dispatch_status => "finished")
    process_finished(*args)
  end

  alias_method :abort_job, :cleanup

  def cancel(*_args)
    _log.info "Job Canceling"
    if self.state != "canceling" # ensure change of states
      signal :cancel
    else
      unqueue_all_signals
      queue_signal(:cancel_job)
    end
  end
  alias_method :cancel_job, :cleanup

  def queue_callback(state, msg, _)
    if state == "timeout" && self.state != "aborting"
      queue_signal(:abort_job, "Job Timeout: #{msg}", "error")
    end
  end

  private

  def ext_management_system
    @ext_management_system ||= ExtManagementSystem.find(options[:ems_id])
  end

  def kubernetes_client
    ext_management_system.connect(:service => PROVIDER_CLASS.ems_type)
  end

  def image_inspector_client
    kubeclient = kubernetes_client

    ImageInspectorClient::Client.new(
      pod_proxy_url(kubeclient, ''),
      'v1',
      :ssl_options    => {
        :verify_ssl => ext_management_system.verify_ssl_mode,
        :cert_store => ext_management_system.ssl_cert_store
      },
      :auth_options   => kubeclient.auth_options,
      :http_proxy_uri => kubeclient.http_proxy_uri
    )
  end

  def queue_options
    {
      :class_name  => "Job",
      :instance_id => id,
      :method_name => "signal",
      :priority    => MiqQueue::HIGH_PRIORITY,
      :role        => "smartstate",
      :task_id     => guid,
      :zone        => zone
    }
  end

  def unqueue_all_signals
    MiqQueue.unqueue(queue_options)
  end

  def queue_signal(*args, deliver_on: nil)
    MiqQueue.put_unless_exists(**queue_options, :args => args, :deliver_on => deliver_on) do |_msg, find_options|
      find_options.merge(
        :miq_callback => {
          :class_name  => self.class.to_s,
          :instance_id => id,
          :method_name => :queue_callback
        }
      )
    end
  end

  def pod_health_poll(client, health_url, http_opts)
    Net::HTTP.start(health_url.host, health_url.port, http_opts) do |http|
      request = Net::HTTP::Get.new(health_url.path)
      client.headers.each { |k, v| request[k.to_s] = v }
      return http.request(request)
    end
  end

  def pod_proxy_url(client, path = "")
    # TODO: change proxy_url in kubeclient to return URI
    pod_proxy = client.proxy_url(:pod,
                                 options[:pod_name],
                                 options[:pod_port],
                                 options[:pod_namespace])
    URI.parse(pod_proxy + path)
  end

  def pod_full_name
    "#{options[:pod_namespace]}/#{options[:pod_name]}"
  end

  def inspector_admin_secret
    kubeclient = kubernetes_client
    begin
      inspector_sa = kubeclient.get_service_account(IMAGE_INSPECTOR_SA, options[:pod_namespace])
      # TODO: support multiple imagePullSecrets. This depends on image-inspector support
      return inspector_sa.try(:imagePullSecrets).to_a[0].try(:name)
    rescue KubeException => e
      raise e unless e.error_code == ERRCODE_NOTFOUND
      _log.warn("Service Account #{IMAGE_INSPECTOR_SA} does not exist.")
    end
    return nil
  end

  def pod_definition(inspector_admin_secret_name)
    pod_def = {
      :apiVersion => "v1",
      :kind       => "Pod",
      :metadata   => {
        :name        => options[:pod_name],
        :namespace   => options[:pod_namespace],
        :labels      => {
          'name'         => options[:pod_name],
          'manageiq.org' => "true"
        },
        :annotations => {
          # in case hostname is not set and options[:miq_server_host] is nil, change ""
          'manageiq.org/hostname' => options[:miq_server_host] || "unknown",
          'manageiq.org/guid'     => options[:miq_server_guid],
          'manageiq.org/image'    => options[:image_full_name],
          'manageiq.org/jobid'    => jobid,
        }
      },
      :spec       => {
        :restartPolicy => 'Never',
        :containers    => [
          {
            :name            => "image-inspector",
            :image           => inspector_image,
            :imagePullPolicy => "Always",
            :command         => [
              "/usr/bin/image-inspector",
              "--chroot",
              "--image=#{options[:image_full_name]}",
              "--scan-type=openscap",
              "--serve=0.0.0.0:#{options[:pod_port]}"
            ],
            :ports           => [{:containerPort => options[:pod_port]}],
            :securityContext => {:privileged =>  true},
            :volumeMounts    => [
              {
                :mountPath => DOCKER_SOCKET,
                :name      => "docker-socket"
              }
            ],
            :env             => inspector_proxy_env_variables
          }
        ],
        :volumes       => [
          {
            :name     => "docker-socket",
            :hostPath => {:path => DOCKER_SOCKET}
          }
        ]
      }
    }

    add_secret_to_pod_def(pod_def, inspector_admin_secret_name) unless inspector_admin_secret_name.blank?
    Kubeclient::Resource.new(pod_def)
  end

  def add_secret_to_pod_def(pod_def, inspector_admin_secret_name)
    pod_def[:spec][:containers][0][:command].append("--dockercfg=" + INSPECTOR_ADMIN_SECRET_PATH +
                                                    inspector_admin_secret_name + "/.dockercfg")
    pod_def[:spec][:containers][0][:volumeMounts].append(
      :name      => "inspector-admin-secret",
      :mountPath => INSPECTOR_ADMIN_SECRET_PATH + inspector_admin_secret_name,
      :readOnly  => true)
    pod_def[:spec][:volumes].append(
      :name   => "inspector-admin-secret",
      :secret => {:secretName => inspector_admin_secret_name})
  end

  def inspector_image
    registry = ::Settings.ems.ems_kubernetes.image_inspector_registry
    repo = ::Settings.ems.ems_kubernetes.image_inspector_repository
    "#{registry}/#{repo}:#{INSPECTOR_IMAGE_TAG}"
  end

  def inspector_proxy_env_variables
    settings = ext_management_system.custom_attributes
    settings.where(:section => ATTRIBUTE_SECTION,
                   :name    => PROXY_ENV_VARIABLES).each_with_object([]) do |att, env|
      env << {:name  => att.name.upcase,
              :value => att.value} unless att.value.blank?
    end
  end
end


text:
package org.vaadin.gridutil.cell;

import com.vaadin.data.BeanPropertySet;
import com.vaadin.data.PropertySet;
import com.vaadin.data.ValueProvider;
import com.vaadin.data.converter.LocalDateToDateConverter;
import com.vaadin.data.provider.InMemoryDataProviderHelpers;
import com.vaadin.data.provider.ListDataProvider;
import com.vaadin.icons.VaadinIcons;
import com.vaadin.server.FontIcon;
import com.vaadin.server.SerializablePredicate;
import com.vaadin.server.Sizeable.Unit;
import com.vaadin.shared.ui.ValueChangeMode;
import com.vaadin.ui.*;
import com.vaadin.ui.components.grid.HeaderRow;
import com.vaadin.ui.themes.ValoTheme;
import org.vaadin.gridutil.cell.filter.BetweenFilter;
import org.vaadin.gridutil.cell.filter.EqualFilter;
import org.vaadin.gridutil.cell.filter.SimpleStringFilter;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.Map.Entry;

/**
 * GridCellFilter helper that has a bunch of different filtering types
 *
 * @author Marten Prieß (http://www.rocketbase.io)
 * @version 1.1
 */
public class GridCellFilter<T> implements Serializable {

    public static String STYLENAME_GRIDCELLFILTER = "gridcellfilter";

    private static Date MIN_DATE_VALUE = new Date(0); // 1970-01-01 00:00:00

    private static Date MAX_DATE_VALUE = new Date(32503676399000L); // 2999-12-31 23:59:59

    private Grid grid;

    private ListDataProvider<T> dataProvider;

    private HeaderRow filterHeaderRow;

    private Map<String, CellFilterComponent> cellFilters;

    private Map<String, SerializablePredicate> assignedFilters;

    private boolean visible = true;

    private List<CellFilterChangedListener> cellFilterChangedListeners;

    private PropertySet<T> propertySet;

    /**
     * keeps link to Grid and added HeaderRow

     * afterwards you need to set filter specification for each row

     * please take care that your Container implements Filterable!
     *
     * @param grid that should get added a HeaderRow that this component will manage
     */
    public GridCellFilter(Grid<T> grid, Class<T> beanType) {
        this.grid = grid;
        filterHeaderRow = grid.appendHeaderRow();
        cellFilters = new HashMap<>();
        assignedFilters = new HashMap<>();
        cellFilterChangedListeners = new ArrayList<>();

        if (!(grid.getDataProvider() instanceof ListDataProvider)) {
            throw new RuntimeException("works only with ListDataProvider");
        } else {
            dataProvider = (ListDataProvider<T>) grid.getDataProvider();
            propertySet = BeanPropertySet.get(beanType);
        }
    }

    /**
     * keeps link to Grid and added HeaderRow

     * afterwards you need to set filter specification for each row

     * please take care that your Container implements Filterable!
     *
     * @param grid that should get added a HeaderRow that this component will manage
     */
    public GridCellFilter(Grid<T> grid) {
        this(grid, grid.getBeanType());
    }

    /**
     * generated HeaderRow
     *
     * @return added HeaderRow during intialization
     */
    public HeaderRow getFilterRow() {
        return filterHeaderRow;
    }

    /**
     * get list of filtered ColumnIds
     *
     * @return id of all properties that are currently filtered
     */
    public Set<String> filteredColumnIds() {
        return assignedFilters.keySet();
    }

    /**
     * add a listener for filter changes
     *
     * @param listener that should get triggered on changes
     */
    public void addCellFilterChangedListener(CellFilterChangedListener listener) {
        cellFilterChangedListeners.add(listener);
    }

    /**
     * remove a listener for filter changes
     *
     * @param listener that should get removed
     * @return true when found and removed
     */
    public boolean removeCellFilterChangedListener(CellFilterChangedListener listener) {
        return cellFilterChangedListeners.remove(listener);
    }

    /**
     * notify all registered listeners
     */
    protected void notifyCellFilterChanged() {
        for (CellFilterChangedListener listener : cellFilterChangedListeners) {
            listener.changedFilter(this);
        }
    }

    /**
     * will remove or add the filterHeaderRow

     * The grid itself has no feature for changing the visibility of a headerRow
     *
     * @param visibile should get displayed?
     */
    public void setVisible(boolean visibile) {
        if (visible != visibile) {
            if (visibile) {
                filterHeaderRow = grid.appendHeaderRow();

                for (Entry<String, CellFilterComponent> entry : cellFilters.entrySet()) {
                    handleFilterRow(entry.getKey(), entry.getValue());
                }
            } else {
                clearAllFilters();
                for (Entry<String, CellFilterComponent> entry : cellFilters.entrySet()) {
                    if (null != filterHeaderRow.getCell(entry.getKey())) {
                        filterHeaderRow.getCell(entry.getKey())
                                .setText("");
                    }
                }
                grid.removeHeaderRow(filterHeaderRow);
            }
            visible = visibile;
        }
    }

    /**
     * get filter by columnId
     *
     * @param columnId id of property
     * @return CellFilterComponent
     */
    public CellFilterComponent getCellFilter(String columnId) {
        return cellFilters.get(columnId);
    }

    /**
     * removes all filters and clear all inputs
     */
    public void clearAllFilters() {
        for (Entry<String, CellFilterComponent> entry : cellFilters.entrySet()) {
            entry.getValue()
                    .clearFilter();
            removeFilter(entry.getKey(), false);
        }
        notifyCellFilterChanged();
    }

    /**
     * clear's a specific filter by columnId
     *
     * @param columnId id of property
     */
    public void clearFilter(String columnId) {
        cellFilters.get(columnId)
                .clearFilter();
        removeFilter(columnId);
    }

    /**
     * link component to headerRow and take care for styling
     *
     * @param columnId   id of property
     * @param cellFilter component will get added to filterRow
     */
    protected void handleFilterRow(String columnId, CellFilterComponent<?> cellFilter) {
        cellFilters.put(columnId, cellFilter);
        cellFilter.getComponent()
                .setWidth(100, Unit.PERCENTAGE);
        if (null != filterHeaderRow.getCell(columnId)) {
            filterHeaderRow.getCell(columnId)
                    .setComponent(cellFilter.getComponent());
            filterHeaderRow.getCell(columnId)
                    .setStyleName("filter-header");
        }
    }

    /**
     * checks assignedFilters replace already handled one and add new one
     *
     * @param filter   container filter
     * @param columnId id of property
     */
    public void replaceFilter(SerializablePredicate filter, String columnId) {
        assignedFilters.put(columnId, filter);
        refreshFilters();
    }

    private void refreshFilters() {
        dataProvider.clearFilters();
        SerializablePredicate<T> filter = null;
        for (Entry<String, SerializablePredicate> entry :
                assignedFilters.entrySet()) {
            final String columnId = entry.getKey();

            ValueProvider<T, ?> provider = null;
            try {
                provider = propertySet.getProperty(columnId).get().getGetter();
            } catch (Exception e) {
                try {
                    provider = grid.getColumn(columnId).getValueProvider();
                }catch (Exception ex){
                    e.printStackTrace();
                    ex.printStackTrace();
                    throw e;
                }
            }

            SerializablePredicate<T> singleFilter = InMemoryDataProviderHelpers.createValueProviderFilter(provider, entry.getValue());
            if (filter == null) {
                filter = singleFilter;
            } else {
                SerializablePredicate<T> tempFilter = filter;
                filter = (item -> tempFilter.test(item) && singleFilter.test(item));
            }
        }
        if (filter != null) {
            dataProvider.setFilter(filter);
        }
    }

    /**
     * remove the filter and notify listeners
     *
     * @param columnId id of property
     */
    public void removeFilter(String columnId) {
        removeFilter(columnId, true);
    }

    protected void removeFilter(String columnId, boolean notify) {
        if (assignedFilters.containsKey(columnId)) {
            assignedFilters.remove(columnId);
            refreshFilters();
            if (notify) {
                notifyCellFilterChanged();
            }
        }
    }

    /**
     * allows to add custom FilterComponents to the GridCellFilter
     *
     * @param columnId  id of property
     * @param component that implements the interface
     * @return your created component that is linked with the GridCellFilter
     */
    public CellFilterComponent setCustomFilter(String columnId, CellFilterComponent component) {
        handleFilterRow(columnId, component);
        return component;
    }

    /**
     * assign a SimpleStringFilter to grid for given columnId

     * could also be used for NumberField when you would like to do filter by startWith for example
     *
     * @param columnId        id of property
     * @param ignoreCase      property of SimpleStringFilter
     * @param onlyMatchPrefix property of SimpleStringFilter
     * @return CellFilterComponent that contains TextField
     */
    public CellFilterComponent<TextField> setTextFilter(String columnId, boolean ignoreCase, boolean onlyMatchPrefix) {
        return setTextFilter(columnId, ignoreCase, onlyMatchPrefix, null);
    }

    /**
     * assign a SimpleStringFilter to grid for given columnId

     * could also be used for NumberField when you would like to do filter by startWith for example
     *
     * @param columnId        id of property
     * @param ignoreCase      property of SimpleStringFilter
     * @param onlyMatchPrefix property of SimpleStringFilter
     * @param inputPrompt     hint for user
     * @return CellFilterComponent that contains TextField
     */
    public CellFilterComponent<TextField> setTextFilter(String columnId, boolean ignoreCase, boolean onlyMatchPrefix, String inputPrompt) {
        CellFilterComponent<TextField> filter = new CellFilterComponent<TextField>() {

            TextField textField = new TextField();

            String currentValue = "";

            public void triggerUpdate() {
                if (currentValue == null || currentValue.isEmpty()) {
                    removeFilter(columnId);
                } else {
                    replaceFilter(new SimpleStringFilter(currentValue, ignoreCase, onlyMatchPrefix), columnId);
                }
            }

            @Override
            public TextField layoutComponent() {
                textField.setPlaceholder(inputPrompt);
                textField.addStyleName(STYLENAME_GRIDCELLFILTER);
                textField.addStyleName(ValoTheme.TEXTFIELD_TINY);
                textField.setValueChangeTimeout(200);
                textField.setValueChangeMode(ValueChangeMode.TIMEOUT);
                // used to allow changes from outside
                textField.addValueChangeListener(e -> {
                    currentValue = textField.getValue();
                    triggerUpdate();
                });
                return textField;
            }

            @Override
            public void clearFilter() {
                textField.clear();
            }
        };
        handleFilterRow(columnId, filter);
        return filter;
    }

    /**
     * assign a EqualFilter to grid for given columnId
     *
     * @param columnId id of property
     * @param beanType class of selection
     * @param beans    selection for ComboBox
     * @return CellFilterComponent that contains ComboBox
     */
    public  CellFilterComponent<ComboBox> setComboBoxFilter(String columnId, Class beanType, List beans) {
        CellFilterComponent<ComboBox> filter = new CellFilterComponent<ComboBox>() {

            ComboBox comboBox = new ComboBox();

            public void triggerUpdate() {
                if (comboBox.getValue() != null) {
                    replaceFilter(new EqualFilter(comboBox.getValue()), columnId);
                } else {
                    removeFilter(columnId);
                }
            }

            @Override
            public ComboBox layoutComponent() {
                comboBox.setEmptySelectionAllowed(true);
                comboBox.addStyleName(STYLENAME_GRIDCELLFILTER);
                comboBox.addStyleName(ValoTheme.COMBOBOX_TINY);
                comboBox.setItems(beans);
                comboBox.addValueChangeListener(e -> triggerUpdate());
                return comboBox;
            }

            @Override
            public void clearFilter() {
                comboBox.setValue(null);
            }
        };

        handleFilterRow(columnId, filter);
        return filter;
    }

    /**
     * assign a EqualFilter to grid for given columnId
     *
     * @param columnId id of property
     * @return drawn comboBox in order to add some custom styles
     */
    public ComboBox setBooleanFilter(String columnId) {
        return setBooleanFilter(columnId, BooleanRepresentation.TRUE_VALUE, BooleanRepresentation.FALSE_VALUE);
    }

    /**
     * assign a EqualFilter to grid for given columnId
     *
     * @param columnId            id of property
     * @param trueRepresentation  specify caption and icon
     * @param falseRepresentation specify caption and icon
     * @return drawn comboBox in order to add some custom styles
     */
    public ComboBox setBooleanFilter(String columnId, BooleanRepresentation trueRepresentation, BooleanRepresentation falseRepresentation) {
        CellFilterComponent<ComboBox<BooleanRepresentation>> filter = new CellFilterComponent<ComboBox<BooleanRepresentation>>() {

            ComboBox<BooleanRepresentation> comboBox = new ComboBox();

            public void triggerUpdate() {
                if (comboBox.getValue() != null) {
                    replaceFilter(new EqualFilter(comboBox.getValue()
                            .getValue()), columnId);
                } else {
                    removeFilter(columnId);
                }
            }

            @Override
            public ComboBox<BooleanRepresentation> layoutComponent() {

                comboBox.setItemIconGenerator(BooleanRepresentation::getIcon);
                comboBox.setItemCaptionGenerator(BooleanRepresentation::getCaption);
                comboBox.setItems(Arrays.asList(trueRepresentation, falseRepresentation));

                comboBox.setEmptySelectionAllowed(true);
                comboBox.addStyleName(STYLENAME_GRIDCELLFILTER);
                comboBox.addStyleName(ValoTheme.COMBOBOX_TINY);
                comboBox.addValueChangeListener(e -> triggerUpdate());
                return comboBox;
            }

            @Override
            public void clearFilter() {
                comboBox.setValue(null);
            }
        };

        handleFilterRow(columnId, filter);
        return filter.getComponent();
    }

    /**
     * assign a BetweenFilter to grid for given columnId

     * only supports type of Integer, Double, Float, BigInteger and BigDecimal
     *
     * @param columnId id of property
     * @param type     type of the property
     * @return RangeCellFilterComponent that holds both TextFields (smallest and biggest as propertyId) and FilterGroup
     */
    public <T extends Number & Comparable<? super T>> RangeCellFilterComponentTyped<T, TextField, HorizontalLayout> setNumberFilter(String columnId, Class type) {
        return setNumberFilter(columnId, type, String.format("couldn't convert to %s", type.getSimpleName()), null, null);
    }

    /**
     * assign a BetweenFilter to grid for given columnId

     * only supports type of Integer, Double, Float, BigInteger and BigDecimal
     *
     * @param columnId              id of property
     * @param type                  type of the property
     * @param converterErrorMessage message to be displayed in case of a converter error
     * @param smallestInputPrompt   hint for user
     * @param biggestInputPrompt    hint for user
     * @return RangeCellFilterComponent that holds both TextFields (smallest and biggest as propertyId) and FilterGroup
     */
    public <T extends Number & Comparable<? super T>> RangeCellFilterComponentTyped<T, TextField, HorizontalLayout> setNumberFilter(String columnId, Class<T> type, String converterErrorMessage, String smallestInputPrompt, String biggestInputPrompt) {

        RangeCellFilterComponentTyped<T, TextField, HorizontalLayout> filter =
                RangeCellFilterComponentFactory.createForNumberType(
                        columnId,
                        type,
                        converterErrorMessage,
                        smallestInputPrompt,
                        biggestInputPrompt,
                        (serFilter, propertyId) -> this.replaceFilter(serFilter, propertyId),
                        this::removeFilter
                );

        handleFilterRow(columnId, filter);
        return filter;
    }

    /**
     * assign a BetweenFilter to grid for given columnId

     *
     * @param columnId id of property
     * @return RangeCellFilterComponent that holds both DateFields (smallest and biggest as propertyId) and FilterGroup
     */
    public RangeCellFilterComponent<DateField, HorizontalLayout> setDateFilter(String columnId) {
        return setDateFilter(columnId, null, true);
    }

    /**
     * assign a BetweenFilter to grid for given columnId

     *
     * @param columnId        id of property
     * @param dateFormat      the dateFormat to be used for the date fields.
     * @param excludeEndOfDay biggest value until the end of the day (DAY + 23:59:59.999)
     * @return RangeCellFilterComponent that holds both DateFields (smallest and biggest as propertyId) and FilterGroup
     */
    public RangeCellFilterComponent<DateField, HorizontalLayout> setDateFilter(String columnId, java.text.SimpleDateFormat dateFormat, boolean excludeEndOfDay) {
        Class<?> propertyType = propertySet.getProperty(columnId)
                .get()
                .getType();
        if (!Date.class.equals(propertyType)) {
            throw new IllegalArgumentException("columnId " + columnId + " is not of type Date");
        }
        RangeCellFilterComponent<DateField, HorizontalLayout> filter = new RangeCellFilterComponent<DateField, HorizontalLayout>() {

            private final LocalDateToDateConverter ldToDateConverter = new LocalDateToDateConverter();

            private DateField smallest;

            private DateField biggest;

            @Override
            public DateField getSmallestField() {
                if (smallest == null) {
                    smallest = genDateField(SMALLEST, dateFormat);
                }
                return smallest;
            }

            @Override
            public DateField getBiggestField() {
                if (biggest == null) {
                    biggest = genDateField(BIGGEST, dateFormat);
                }
                return biggest;
            }

            private DateField genDateField(final String propertyId, final SimpleDateFormat dateFormat) {
                return FieldFactory.genDateField(getBinder(), propertyId, dateFormat);
            }

            @Override
            public HorizontalLayout layoutComponent() {
                getHLayout().addComponent(getSmallestField());
                getHLayout().addComponent(getBiggestField());
                getHLayout().setExpandRatio(getSmallestField(), 1);
                getHLayout().setExpandRatio(getBiggestField(), 1);

                initBinderValueChangeHandler();

                return getHLayout();
            }

            private Date fixTiming(Date date, boolean excludeEndOfDay) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                calendar.set(Calendar.MILLISECOND, excludeEndOfDay ? 0 : 999);
                calendar.set(Calendar.SECOND, excludeEndOfDay ? 0 : 59);
                calendar.set(Calendar.MINUTE, excludeEndOfDay ? 0 : 59);
                calendar.set(Calendar.HOUR, excludeEndOfDay ? 0 : 23);
                return calendar.getTime();
            }

            private void initBinderValueChangeHandler() {
                getBinder().addValueChangeListener(e -> {
                    Object smallest = getBinder().getBean()
                            .getSmallest();
                    Object biggest = getBinder().getBean()
                            .getBiggest();
                    Date smallestDate = checkObject(smallest);
                    Date biggestDate = checkObject(biggest);
                    if (this.smallest != null || biggest != null) {
                        if (this.smallest != null && biggest != null && this.smallest.equals(biggest)) {
                            replaceFilter(new EqualFilter(this.smallest), columnId);
                        } else {
                            replaceFilter(new BetweenFilter(smallestDate != null ? fixTiming(smallestDate, true) : MIN_DATE_VALUE,
                                    biggestDate != null ? fixTiming(biggestDate, excludeEndOfDay) : MAX_DATE_VALUE), columnId);
                        }
                    } else {
                        removeFilter(columnId);
                    }
                });
            }

            private Date checkObject(Object value) {
                if (value instanceof LocalDate) {
                    return ldToDateConverter.convertToModel((LocalDate) value, null)
                            .getOrThrow(msg -> new IllegalArgumentException(msg));
                } else if (value instanceof Date) {
                    return (Date) value;
                }
                return null;
            }

            @Override
            public void clearFilter() {
                getBinder().setBean(new TwoValueObject());
            }
        };

        handleFilterRow(columnId, filter);
        return filter;
    }

    public static class BooleanRepresentation {

        public static BooleanRepresentation TRUE_VALUE = new BooleanRepresentation(true, VaadinIcons.CHECK_SQUARE, Boolean.TRUE.toString());

        public static BooleanRepresentation FALSE_VALUE = new BooleanRepresentation(false, VaadinIcons.CLOSE, Boolean.FALSE.toString());

        private boolean value;

        private FontIcon icon;

        private String caption;

        public BooleanRepresentation(Boolean value, FontIcon icon, String caption) {
            this.value = value;
            this.icon = icon;
            this.caption = caption;
        }

        public FontIcon getIcon() {
            return icon;
        }

        public String getCaption() {
            return caption;
        }

        public boolean getValue() {
            return value;
        }
    }
}


text:
package iso20022

// Choice of a payment instrument for the cash-in flow or cash-out flow.
type CashInOrOut6Choice struct {

	// Payment instrument for the cash-in flow.
	CashInPaymentInstrument *PaymentInstrument12Choice `xml:"CshInPmtInstrm"`

	// Payment instrument for the cash-out flow.
	CashOutPaymentInstrument *PaymentInstrument11Choice `xml:"CshOutPmtInstrm"`
}

func (c *CashInOrOut6Choice) AddCashInPaymentInstrument() *PaymentInstrument12Choice {
	c.CashInPaymentInstrument = new(PaymentInstrument12Choice)
	return c.CashInPaymentInstrument
}

func (c *CashInOrOut6Choice) AddCashOutPaymentInstrument() *PaymentInstrument11Choice {
	c.CashOutPaymentInstrument = new(PaymentInstrument11Choice)
	return c.CashOutPaymentInstrument
}


text:
import mpi
import time
from flWii.connectToMote import connectToMote
from flWii.moteCursor import MoteMouse
from tileMote import TileMote
from mouseUpdater import WiiMouseUpdater

def SetupMoteControl(cursor, app, displayWidth, displayHeight, moteId="00:17:AB:32:BF:EF", leds=(1,0,0,0), configUI=None, renderers = None, masterObjects=None, cursorListList=None, moteManager=None):
    tileMote = TileMote(cursor, displayWidth, displayHeight)
    if mpi.rank == 0:
        mote = connectToMote(moteId, leds, changeOnly=True)
        print "Setting up MoteMouse"
        moteMouse = MoteMouse(mote,tileMote)
    else:
        moteMouse = None
        mote = None

    app.addDynamicObject(WiiMouseUpdater(moteMouse, tileMote, configUI=configUI, renderers=renderers, masterObjects=masterObjects, cursorListList=cursorListList, moteManager=moteManager), addToRenderer=False)

    return mote, moteMouse, tileMote

class MoteManager: # FIXME prototype, move to separate file next
    def __init__(self, app, fullRect, masterCursors, configUI=None, renderers = None, masterObjects=None, cursorListList=None):
        mote, moteMouse, tileMote = SetupMoteControl(masterCursors[0], app, fullRect.width, fullRect.height, moteId=None, leds=(1,0,0,0),renderers=renderers, configUI=configUI, masterObjects=masterObjects, cursorListList=cursorListList, moteManager=self)
        mote2, moteMouse2, tileMote2 = SetupMoteControl(masterCursors[1], app, fullRect.width, fullRect.height, moteId=None, leds=(0,1,0,0),renderers=renderers, configUI=configUI, masterObjects=masterObjects, cursorListList=cursorListList, moteManager=self)
        mote3, moteMouse3, tileMote3 = SetupMoteControl(masterCursors[2], app, fullRect.width, fullRect.height, moteId=None, leds=(0,0,1,0),renderers=renderers, configUI=configUI, masterObjects=masterObjects, cursorListList=cursorListList, moteManager=self)
        mote4, moteMouse4, tileMote4 = SetupMoteControl(masterCursors[3], app, fullRect.width, fullRect.height, moteId=None, leds=(0,0,0,1),renderers=renderers, configUI=configUI, masterObjects=masterObjects, cursorListList=cursorListList, moteManager=self)

        self.connectedMoteDict = {}  # moteId: mote
        self.motes = [mote, mote2, mote3, mote4]
        self.moteMice = [moteMouse, moteMouse2, moteMouse3, moteMouse4]
        #self.tileMotes = [tileMote, tileMote2, tileMote3, tileMote4]
        self.disconnectedMoteIndexes = [0,1,2,3]
        self.moteDetector = None # should be set after it's created.
        self.idleTimeoutSecs = 60. # 5 * 60.
        self.idleCheckInterval =  15. # secs
        self.lastIdleCheckTime = time.time()

    def newMoteDetected(self, moteId):
        if len(self.disconnectedMoteIndexes) > 0:
            moteIndex = self.disconnectedMoteIndexes.pop(0)
            print "new mote detected:", moteId, moteIndex
            mote = self.motes[moteIndex]
            moteMouse = self.moteMice[moteIndex]
            #tileMote = self.tileMotes[moteIndex]
            mote.id = moteId
            self.connectedMoteDict[moteId] = moteIndex
            try:
                mote.connect()
                mote.setLeds(moteIndex==0, moteIndex==1, moteIndex==2, moteIndex==3)
                if mote.readThread == None:
                    mote.startReadThread()
                mote.irBasicModeOn(changeOnly=True)
                moteMouse.mote = mote
            except MoteConnectFailed:
                print "Mote Connect failed."

    def disconnectMote(self, moteId):
        if moteId in self.connectedMoteDict:
            moteIndex = self.connectedMoteDict[moteId]
            mote = self.motes[moteIndex]
            self.moteMice[moteIndex].moteMouse = None
            mote.disconnect()
            self.disconnectedMoteIndexes.insert(0, moteIndex)
            del self.connectedMoteDict[moteId] # marked as not connected, so connection attempts will start now.
        else:
            print "warning: disconnecting mote that wasn't connected."

    def getAlreadyConnectedIds(self):
        return self.connectedMoteDict.keys()

    def setMoteDetector(self, d):
        self.moteDetector = d

    def update(self, secs, app):
        if time.time() - self.lastIdleCheckTime > self.idleCheckInterval:
            self.lastIdleCheckTime = time.time()
            for moteId, moteIndex in self.connectedMoteDict.items():
                if self.moteMice[moteIndex].mote.getIdleSecs() > self.idleTimeoutSecs:
                    self.disconnectMote(moteId)
                    print "Mote Timeout, Will start searching in 5 sec (to avoid auto-reconnect)"
                    app.callLater(5.0, self.moteDetector.reinitiateSearching, [])
                print moteId, "idle Time:", self.moteMice[moteIndex].mote.getIdleSecs()

    def incrementNumMotes(self, numToAdd):
        num = (self.moteDetector.numToConnect + numToAdd) % 5
        if num == 0:
            num += 1
        self.moteDetector.numToConnect = num
        print "Total Wiimotes to be connected:", self.moteDetector.numToConnect

        if self.moteDetector.numToConnect > len(self.getAlreadyConnectedIds()):
            self.moteDetector.reinitiateSearching()


text:
const render_admin_emoji_list = require('../templates/admin_emoji_list.hbs');
const render_settings_emoji_settings_tip = require("../templates/settings/emoji_settings_tip.hbs");

const meta = {
    loaded: false,
};

exports.can_add_emoji = function () {
    if (page_params.is_guest) {
        return false;
    }

    if (page_params.is_admin) {
        return true;
    }

    // for normal users, we depend on the setting
    return !page_params.realm_add_emoji_by_admins_only;
};

function can_admin_emoji(emoji) {
    if (page_params.is_admin) {
        return true;
    }
    if (emoji.author_id === null) {
        // If we don't have the author information then only admin is allowed to disable that emoji.
        return false;
    }
    if (!page_params.realm_add_emoji_by_admins_only && people.is_my_user_id(emoji.author_id)) {
        return true;
    }
    return false;
}

exports.update_custom_emoji_ui = function () {
    const rendered_tip = render_settings_emoji_settings_tip({
        realm_add_emoji_by_admins_only: page_params.realm_add_emoji_by_admins_only,
    });
    $('#emoji-settings').find('.emoji-settings-tip-container').html(rendered_tip);
    if (page_params.realm_add_emoji_by_admins_only && !page_params.is_admin) {
        $('.admin-emoji-form').hide();
        $('#emoji-settings').removeClass('can_edit');
    } else {
        $('.admin-emoji-form').show();
        $('#emoji-settings').addClass('can_edit');
    }

    exports.populate_emoji(page_params.realm_emoji);
};

exports.reset = function () {
    meta.loaded = false;
};

function sort_author_full_name(a, b) {
    if (a.author.full_name > b.author.full_name) {
        return 1;
    } else if (a.author.full_name === b.author.full_name) {
        return 0;
    }
    return -1;
}

exports.populate_emoji = function (emoji_data) {
    if (!meta.loaded) {
        return;
    }

    for (const emoji of Object.values(emoji_data)) {
        // Add people.js data for the user here.
        if (emoji.author_id !== null) {
            emoji.author = people.get_by_user_id(emoji.author_id);
        } else {
            emoji.author = null;
        }
    }

    const emoji_table = $('#admin_emoji_table').expectOne();
    list_render.create(emoji_table, Object.values(emoji_data), {
        name: "emoji_list",
        modifier: function (item) {
            if (item.deactivated !== true) {
                return render_admin_emoji_list({
                    emoji: {
                        name: item.name,
                        display_name: item.name.replace(/_/g, ' '),
                        source_url: item.source_url,
                        author: item.author || '',
                        can_admin_emoji: can_admin_emoji(item),
                    },
                });
            }
            return "";
        },
        filter: {
            element: emoji_table.closest(".settings-section").find(".search"),
            predicate: function (item, value) {
                return item.name.toLowerCase().includes(value);
            },
            onupdate: function () {
                ui.reset_scrollbar(emoji_table);
            },
        },
        parent_container: $("#emoji-settings").expectOne(),
        sort_fields: {
            author_full_name: sort_author_full_name,
        },
        init_sort: ['alphabetic', 'name'],
    });

    loading.destroy_indicator($('#admin_page_emoji_loading_indicator'));
};

exports.build_emoji_upload_widget = function () {
    const get_file_input = function () {
        return $('#emoji_file_input');
    };

    const file_name_field = $('#emoji-file-name');
    const input_error = $('#emoji_file_input_error');
    const clear_button = $('#emoji_image_clear_button');
    const upload_button = $('#emoji_upload_button');
    const preview_text = $('#emoji_preview_text');
    const preview_image = $('#emoji_preview_image');

    return upload_widget.build_widget(
        get_file_input,
        file_name_field,
        input_error,
        clear_button,
        upload_button,
        preview_text,
        preview_image
    );
};

exports.set_up = function () {
    meta.loaded = true;

    loading.make_indicator($('#admin_page_emoji_loading_indicator'));

    // Populate emoji table
    exports.populate_emoji(page_params.realm_emoji);

    $('.admin_emoji_table').on('click', '.delete', function (e) {
        e.preventDefault();
        e.stopPropagation();
        const btn = $(this);

        channel.del({
            url: '/json/realm/emoji/' + encodeURIComponent(btn.attr('data-emoji-name')),
            error: function (xhr) {
                ui_report.generic_row_button_error(xhr, btn);
            },
            success: function () {
                const row = btn.parents('tr');
                row.remove();
            },
        });
    });

    const emoji_widget = exports.build_emoji_upload_widget();

    $(".organization form.admin-emoji-form").off('submit').on('submit', function (e) {
        e.preventDefault();
        e.stopPropagation();
        const emoji_status = $('#admin-emoji-status');
        $('#admin_emoji_submit').attr('disabled', true);
        const emoji = {};
        const formData = new FormData();

        for (const obj of $(this).serializeArray()) {
            emoji[obj.name] = obj.value;
        }

        for (const [i, file] of Array.prototype.entries.call($('#emoji_file_input')[0].files)) {
            formData.append('file-' + i, file);
        }
        channel.post({
            url: "/json/realm/emoji/" + encodeURIComponent(emoji.name),
            data: formData,
            cache: false,
            processData: false,
            contentType: false,
            success: function () {
                $('#admin-emoji-status').hide();
                ui_report.success(i18n.t("Custom emoji added!"), emoji_status);
                $("form.admin-emoji-form input[type='text']").val("");
                $('#admin_emoji_submit').removeAttr('disabled');
                emoji_widget.clear();
            },
            error: function (xhr) {
                $('#admin-emoji-status').hide();
                const errors = JSON.parse(xhr.responseText).msg;
                xhr.responseText = JSON.stringify({msg: errors});
                ui_report.error(i18n.t("Failed"), xhr, emoji_status);
                $('#admin_emoji_submit').removeAttr('disabled');
            },
        });
    });
};

window.settings_emoji = exports;