text:
package org.apereo.cas;

import lombok.extern.slf4j.Slf4j;
import org.apereo.cas.adaptors.generic.FileAuthenticationHandlerTests;
import org.apereo.cas.adaptors.generic.RejectUsersAuthenticationHandlerTests;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;

/**
 * This is {@link AllTestsSuite}.
 *
 * @author Misagh Moayyed
 * @since 5.0.0
 */
@RunWith(Suite.class)
@Suite.SuiteClasses({FileAuthenticationHandlerTests.class,
        RejectUsersAuthenticationHandlerTests.class})
@Slf4j
public class AllTestsSuite {
}


text:
module YouTube.Services
    ( browseChannel
    , browseMyChannel
    , createPlaylist
    , createPlaylists
    , deletePlaylist
    , findChannel
    , insertVideo
    , listPlaylist
    , listVideos
    ) where

import GoogleAPIsClient
import Helpers          (hashURL)
import Model            (Tournament(..))
import YouTube.Models

import Data.Foldable    (toList)
import Data.List        (find, intercalate)
import Data.Map    as M (empty, fromList, (!))

browseChannel :: YouTubeId -> Int -> Client [Playlist]
browseChannel cId count = unwrap <$> listChannelPlaylists cId count
  where unwrap (Playlists playlists) = playlists

browseMyChannel :: Int -> Client [Playlist]
browseMyChannel count = do
  requireOAuth2
  myChannel <- channelId <$> findMyChannel
  browseChannel myChannel count

createPlaylist :: Tournament -> Client Playlist
createPlaylist t = do
  requireOAuth2
  playlists <- browseMyChannel 1000
  findOrCreatePlaylist playlists t

createPlaylists :: [Tournament] -> Client (Tournament -> Playlist)
createPlaylists [] = return (M.empty M.!)
createPlaylists ts = do
  requireOAuth2
  playlists <- browseMyChannel 1000
  findOrCreatePlaylists playlists ts

deletePlaylist :: YouTubeId -> Client Bool
deletePlaylist pId = do
  requireOAuth2
  delete "/playlists" [ ("id", pId) ]

findChannel :: String -> Client Channel
findChannel name =
  firstChannel <$> get "/channels" parameters
    where parameters = [ ("part",       "id,contentDetails")
                       , ("forUsername", name              )
                       ]

insertVideo :: Video -> Int -> Playlist -> Client Success
insertVideo v pos pl = do
  requireOAuth2
  post "/playlistItems" parameters body
    where parameters = [ ("part", "snippet") ]
          body = Just (PlaylistItem "" vId pId pos)
          vId = videoId v
          pId = playlistId pl

listPlaylist :: YouTubeId -> Int -> Client Videos
listPlaylist pId count = do
  requireOAuth2
  listPlaylistVideosIds pId count >>= listVideos
    where listPlaylistVideosIds i c = extractVideosIds <$> listPlaylistContent i c
          extractVideosIds = map playlistItemVideoId . toList

listPlaylistContent :: YouTubeId -> PageSize -> Client PlaylistContent
listPlaylistContent pId = getMany "/playlistItems" parameters
    where part       = "contentDetails,snippet"
          parameters = [ ("part"      , part)
                       , ("playlistId", pId )
                       ]

listVideos :: [YouTubeId] -> Client Videos
listVideos vIds = toList <$> listVideosBatch (take 50 vIds) (drop 50 vIds)

listVideosBatch :: [YouTubeId] -> [YouTubeId] -> Client (Items Video)
listVideosBatch [] _ = return mempty
listVideosBatch ids otherIds = do
  let part       = "contentDetails,snippet"
      parameters = [ ("part", part               )
                   , ("id",   intercalate "," ids)
                   ]
  batch <- get "/videos" parameters
  mappend batch <$> listVideosBatch (take 50 otherIds) (drop 50 otherIds)

findMyChannel :: Client Channel
findMyChannel =
  firstChannel <$> get "/channels" parameters
    where parameters = [ ("part", "id,contentDetails"), ("mine", "true") ]

firstChannel :: Items Channel -> Channel
firstChannel (Items cs) = head cs

listChannelPlaylists :: YouTubeId -> PageSize -> Client Playlists
listChannelPlaylists cId = getMany "/playlists" parameters
  where part       = "contentDetails,snippet"
        parameters = [ ("part"      , part)
                     , ("channelId" , cId )
                     ]

findOrCreatePlaylists :: [Playlist] -> [Tournament] -> Client (Tournament -> Playlist)
findOrCreatePlaylists _ []  = return (\_ -> error "no tournament")
findOrCreatePlaylists ps ts = ((M.!) . M.fromList) <$> mapM (\t -> (,) t <$> findOrCreatePlaylist ps t) ts

findOrCreatePlaylist :: [Playlist] -> Tournament -> Client Playlist
findOrCreatePlaylist ps tournament = do
  let previous = find (samePlaylist playlist) ps
  case previous of
    Just found -> return found
    Nothing    -> post "/playlists" parameters body
      where parameters = [ ("part", "contentDetails,snippet,status") ]
            body = Just playlist
  where playlist = mkPlaylist tournament

samePlaylist :: Playlist -> Playlist -> Bool
samePlaylist p1 p2 = playlistTags p1 == playlistTags p2

mkPlaylist :: Tournament -> Playlist
mkPlaylist tournament = Playlist "" title description tags
  where title = tournamentName tournament
        description = tournamentURL tournament
        tag = hashURL $ tournamentURL tournament
        tags = Tags [tag]

redpajama_set_name: RedPajamaGithub


text:
Deface::Override.new(
  :virtual_path       => "spree/shared/_products",
  :name               => "products_direct_link",
  :replace            => "code[erb-loud]:contains('link_to small_image')",
  :text               => '<%= link_to small_image(product, :itemprop => "image"), product, :itemprop => "url", "data-real" => "http://#{Spree::Config.site_url}/products/#{product.permalink}" %>',
  :disabled           => false
)

Deface::Override.new(
  :virtual_path       => "spree/shared/_products",
  :name               => "products_direct_link_js",
  :insert_after       => "code[erb-silent]:contains('paginated_products.respond_to?(:num_pages)')",
  :partial            => 'spree/shared/direct_link_js',
  :disabled           => false
)


text:
import unittest
import os
from ptpy import PtSqlite

class PtSqliteTest(unittest.TestCase):
    sqlite = None
    db_path = "/tmp/test.db"
    def init_sqlite(self):
        self.sqlite = PtSqlite()
    def setUp(self):
        self.init_sqlite()

    def test_open(self):
        self.sqlite.open(self.db_path)
        self.assertTrue(os.path.exists(self.db_path))
    def test_delete_db(self):
        self.sqlite.open(self.db_path)
        self.sqlite.deleteDb(self.db_path)
        self.assertTrue(False == os.path.exists(self.db_path))

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


text:
//
//  JSAppsTableController.m
//  SyncDownLoadImg
//
//  Created by ShenYj on 16/8/23.
//  Copyright © 2016年 ___ShenYJ___. All rights reserved.
//

#import "JSAppsTableController.h"
#import "JSAppsModel.h"
#import "JSAppCell.h"
#import "UIImageView+JSWebCache.h"

static NSString * const reuseIdentifier = @"reuseIdentifier";

@implementation JSAppsTableController{

    NSArray <JSAppsModel *>      *_data;              //  数据容器

}

- (instancetype)init{
    self = [super init];
    if (self) {

        // 成员变量初始化
        _data = [JSAppsModel loadAppsData];

    }
    return self;
}

- (NSString *)title{
    return @"应用程序列表";
}

- (void)viewDidLoad{
    [super viewDidLoad];
    [self.tableView registerClass:[JSAppCell class] forCellReuseIdentifier:reuseIdentifier];

}

#pragma mark -- UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return _data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    JSAppCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier forIndexPath:indexPath];

    JSAppsModel *model = _data[indexPath.row];
    cell.textLabel.text = model.name;
    cell.detailTextLabel.text = model.download;

    // 使用UIImage+JSWebCache分类设置图片
    [cell.imageView js_imageUrlString:model.icon withPlaceHolderImage:@"user_default"];

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 68;
}

#pragma mark -- UITableViewDataDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    NSLog(@"----->ImageCacheCounts:%zd ----> OperationCacheCounts:%zd ---->CurrentOperationCounts:%zd",_imageCache.count,_operationCache.count,_queue.operationCount);

}

- (void)dealloc{
//    NSLog(@"%s",__func__);
}

#pragma mark  --  代码重构前的Cell数据源方法

//- (UITableViewCell *)originalDemotableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//    JSAppCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier forIndexPath:indexPath];
//
//    JSAppsModel *model = _data[indexPath.row];
//    cell.textLabel.text = model.name;
//    cell.detailTextLabel.text = model.download;
//
//    // 设置占位图
//    cell.imageView.image = [UIImage imageNamed:@"user_default"];
//
//    // 从缓存中取出图片
//    if ([_imageCache objectForKey:model.icon]) {
//        cell.imageView.image = [_imageCache objectForKey:model.icon];
//        NSLog(@"从内存图片缓存池中获取图片");
//        return cell;
//    }
//
//    // 从沙盒中获取图片
//    NSData *data = [NSData dataWithContentsOfFile:[_cachePath stringByAppendingPathComponent:model.icon.lastPathComponent]];
//    if (data) {
//        cell.imageView.image = [UIImage imageWithData:data];
//
//        // 进行内存缓存
//        [_imageCache setObject:[UIImage imageWithData:data] forKey:model.icon];
//
//        NSLog(@"从本地沙盒获取图片:(%@)",[_cachePath stringByAppendingPathComponent:model.icon.lastPathComponent]);
//        return cell;
//    }
//
//    // 判断操作是否存在
//    if ([_operationCache objectForKey:model.icon]) {
//        NSLog(@"图片正在下载中...");
//        return cell;
//    }
//
//
//    /*    block内部使用self,不能够说一定存在循环引用
//     self -> _operationCache和_queue -> downLoadImageOperation -> block -> self
//            _operationCache     ->    手动清除downLoadImageOperation
//            _queue              ->    当队列中的操作执行完毕后downLoadImageOperation会自动销毁
//     */
//    //__weak typeof(self) weakSelf = self;
//
//
//    NSBlockOperation *downLoadImageOperation = [NSBlockOperation blockOperationWithBlock:^{
//
//        [NSThread sleepForTimeInterval:5]; // 模拟延迟
//
//        // 下载图片
//        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:model.icon]];
//        UIImage *image = [UIImage imageWithData:data];
//
//        // 将下载好的图片进行内存缓存
//        // model.downloadImage = image;
//        [_imageCache setObject:image forKey:model.icon];
//
//        // 将下载好的图片做本地缓存
//        [data writeToFile:[_cachePath stringByAppendingPathComponent:model.icon.lastPathComponent] atomically:YES];
//
//        // 返回主线程刷新UI
//        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
//
//            // cell.imageView.image = image; 避免重用Cell中有正在执行的下载操作导致图片混乱,直接刷新TableView从内存获取图片
//            [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
//
//            // 清除操作缓存池中对应的操作
//            [_operationCache removeObjectForKey:model.icon];
//
//            /*      [_operationCache removeAllObjects];
//             假设操作的完成时间足够长,因为下载操作异步执行,CPU会随机执行线程上的操作,如果设置了优先级或执行某一线程的概率较高,那么可以肯定,完成有先后,只是不够明显
//             一旦某个操作提前完成执行了清空操作缓存池,当再次滚动TableView的时候,可能还会出现同一个下载操作重复添加到队列中的问题
//             所以不应该使用removeAllObjects方法来移除
//             */
//
//        }];
//    }];
//
//    // 添加到队列中
//    [_queue addOperation:downLoadImageOperation];
//
//    // 将每一个下载图片的操作都添加到操作缓存池中(如果操作已经存在,就不再重复执行)
//    [_operationCache setObject:downLoadImageOperation forKey:model.icon];
//
//    return cell;
//}

@end


text:
Django Social Auth backends system
==================================

Contents:

.. toctree::
   :maxdepth: 2

   openid
   oauth
   google
   twitter
   facebook
   linkedin
   github


text:
<?php
	class Usuario {
		private $idUsuario;
		private $nome;
		private $email;
		private $senha;
		private $classe;

		public function getId(){
			return $this->id;
		}
		public function setIdUsuario($id){
			$this->idUsuario = $id;
		}
		public function getNome(){
			return $this->nome;
		}
		public function setNome($nome){
			$this->nome = $nome;
		}
		public function getEmail(){
			return $this->email;
		}
		public function setEmail($email){
			$this->email = $email;
		}
		public function getSenha(){
			return $this->senha;
		}
		public function setSenha($senha){
			$this->senha = $senha;
		}
		public function getClasse(){
			return $this->classe;
		}
		public function setClasse($classe){
			$this->classe = $classe;
		}
	}
?>


text:
import logging = require('./logging');
import npm = require('./npm-package');
import environment = require('./environment')
var log = new logging.Log();

export class Grunt {
    grunt;
    registeredTasks: string[] = [];

    public constructor(grunt) {
        this.grunt = grunt;
    }

    public registerExternalTask(name: string, dependencies : string[], callback) {
        new npm.Package().installIfFileNotExist(name, dependencies, () => {
            process.chdir(global["relativeDir"]);
            if (name.indexOf("@") > 0) name = name.substring(0, name.indexOf("@"))
            this.grunt.loadNpmTasks(name);
            process.chdir(global["basedir"]);
            log.verbose.writeln("Grunt", "npm task " + name + " loaded");
            process.chdir(global["basedir"]);
            callback();
        });
    }

    public registerTask(name: string, description: string, onTaskStart: () => void) {
        if (this.registeredTasks.some((_) => _ === name)) {
            return;
        }

        this.registeredTasks.push(name);
        this.grunt.registerTask(name, description, onTaskStart);
        log.verbose.writeln("Grunt", "Loaded task " + name);
    }

    public initConfig(config : any) {
        this.grunt.initConfig(config);
    }

    public run(task : string) {
        if (environment.Settings.isVerbose())
            this.grunt.option("verbose", environment.Settings.isVerbose());
        if (environment.Settings.showStack())
            this.grunt.option("stack", environment.Settings.showStack());
        log.verbose.writeln("Grunt", "Schedule run for task " + task);
        this.grunt.task.run(task);
    }
}


text:
class HierarchyLevel {
	[ValidateNotNullOrEmpty()] [String]               $Name
	[ValidateNotNullOrEmpty()] [IO.DirectoryInfo]     $Directory

	[ValidateNotNullOrEmpty()] $Configuration
	[ValidateNotNullOrEmpty()] $EffectiveConfiguration

	[Package[]] getPackages() {
		throw("Must be used in overriden class")
	}

	[string] ToString() {
		return $this.Name
	}
}

class PackageRepository : HierarchyLevel {
	[Package[]] getPackages() {
		return @(Get-Package -Filter "$($this.Directory.Name):*/*")
	}
}

class PackageClass : HierarchyLevel {
	[ValidateNotNullOrEmpty()] [PackageRepository] $Repository

	[Package[]] getPackages() {
		return @(Get-Package -Filter "$($this.Repository.Directory.Name):$($this.Name)/*")
	}
}

class Package : HierarchyLevel {
	[ValidateNotNullOrEmpty()] [PackageRepository] $Repository
	[ValidateNotNullOrEmpty()] [PackageClass]      $Class

	[Package[]] getPackages() {
		return @($this)
	}
}

####################### Utility functions #######################

function Test-ArbitaryToken {
	param([string] $Id, [char[]] $IllegalChars = [IO.Path]::GetInvalidFileNameChars())
	return("$Id".ToCharArray() | Where-Object{(New-Object string @(,$IllegalChars)).Contains("$_")}).Count -eq 0
}

function Get-PropertyPathTokens {
	param([string] $PropertyPath)

	if ([string]::IsNullOrWhiteSpace($PropertyPath)) {
		return @()
	}

	$chars = "$PropertyPath".Trim(@("/", "`r", "`n", "`t")).ToCharArray()
	$quote = $false
	$acc = ""

	$tokens = New-Object "System.Collections.Generic.List[System.String]"

	for($i = 0; $i -lt $chars.Length; $i++){
		$c = $chars[$i]
		$cn = [char]0

		if ($i -lt $chars.Length - 1) {
			$cn = $chars[$i + 1]
		}

		if ($c -eq """") {
			if (($acc.Length -eq 0) -or ([int]$cn -eq 0) -or ($cn -eq "/")) {
				$quote = -not $quote
			}
            $acc += """" # we carry the quote to the output expression
		}
		elseif ([int]$c -le 32) {
			if ($quote){
				$acc += $c
			}
			else {
				continue # white-space outside quote? ignore!
			}
		}
		elseif ($c -eq "/") {
			if ($quote){
				$acc += $c
			}
			else {
				if (-not [string]::IsNullOrWhiteSpace($acc)) {
					$tokens.Add($acc)
					$acc = ""
				}
			}
		}
		else {
			$acc += $c
		}
	}

    if (-not [string]::IsNullOrWhiteSpace($acc)) {
		$tokens.Add($acc)
	}

	return @($tokens)
}

####################### External functions ######################

function Get-PackageConfiguration {
	param(
		[Parameter(ValueFromPipeline = $true, Mandatory = $true)] [HierarchyLevel] $Node
	)

	process {
		Write-Output $Node.EffectiveConfiguration.getObject()
	}
}

function Get-PackageRepository {
	param(
		[Parameter(Mandatory = $false, Position = 0)] [string] $Id
	)

	if ([string]::IsNullOrWhiteSpace($Id)) {
		$Id = $global:System.Environment.DefaultRepository
	}

	$SolutionRoot = Join-Path $global:System.RootDirectory $Id

	if ($Id -ne $global:System.Environment.DefaultRepository) {
		$Prefix = "$($Id):"
		$Suffix = " ($($Id))"
	}
	else {
		$Prefix = ""
		$Suffix = ""
	}

	$PackageRepositoryFolder = [IO.DirectoryInfo] $SolutionRoot
	$PackageRepositoryConfiguration = New-PropertyContainer (Join-Path $PackageRepositoryFolder.FullName "package.json")

	$PackageRepository = [PackageRepository] @{
		Name = $Id
		Directory = $PackageRepositoryFolder
		Configuration = $PackageRepositoryConfiguration
		EffectiveConfiguration = New-MergeContainer @($PackageRepositoryConfiguration) -PackageId $Id
	}

	return $PackageRepository
}

function Get-PackageClass {
	param(
		[Parameter(Mandatory = $false, Position = 0)] [string] $Filter = $null
	)

	if ([string]::IsNullOrWhiteSpace($Filter)) {
		$Filter = "*"
	}

	if ($Filter.Contains(":")) {
		$Tokens = $Filter.Split(@(":"), 2, [StringSplitOptions]::RemoveEmptyEntries)

		if ($Tokens.Length -eq 1) {
			$Filter = $Tokens[0]
			$RepositoryId = $global:System.Environment.DefaultRepository
		} else {
			$Filter = $Tokens[1]
			$RepositoryId = $Tokens[0]
		}
	} else {
		$RepositoryId = $global:System.Environment.DefaultRepository
	}

	$SolutionRoot = Join-Path $global:System.RootDirectory $RepositoryId

	if (-not (Test-Path $SolutionRoot -PathType Container)) {
		$Candidates = @()
	} else {
		$Candidates = @(Get-ChildItem -Path $SolutionRoot -Directory -Filter $Filter)
	}

	if ($RepositoryId -ne $global:System.Environment.DefaultRepository) {
		$Prefix = "$($RepositoryId):"
		$Suffix = " ($($RepositoryId))"
	}
	else {
		$Prefix = ""
		$Suffix = ""
	}

	if ($Candidates.Length -eq 0) {
		if (-not (Test-ArbitaryToken -Id $Filter -IllegalChars @("*", "?"))) {
			return
		}

		$PackageClassFolder = [IO.DirectoryInfo] (Join-Path $SolutionRoot $Filter)
		$PackageClassConfiguration = New-PropertyContainer (Join-Path $PackageClassFolder.FullName "package.json")

		$PackageRepositoryFolder = [IO.DirectoryInfo] $SolutionRoot
		$PackageRepositoryConfiguration = New-PropertyContainer (Join-Path $PackageRepositoryFolder.FullName "package.json")

		$PackageRepository = [PackageRepository] @{
			Name = $RepositoryId
			Directory = $PackageRepositoryFolder
			Configuration = $PackageRepositoryConfiguration
			EffectiveConfiguration = New-MergeContainer @($PackageRepositoryConfiguration) -PackageId $RepositoryId
		}

		$PackageClass = [PackageClass] @{
			Name = $PackageClassFolder.Name
			Directory = $PackageClassFolder
			Repository = $PackageRepository
			Configuration = $PackageClassConfiguration
			EffectiveConfiguration = New-MergeContainer @($PackageClassConfiguration, $PackageRepositoryConfiguration) -PackageId "$Prefix$($PackageClassFolder.Name)/*"
		}

		return @($PackageClass)
	}

	foreach($Candidate in $Candidates) {

		$PackageClassFolder = [IO.DirectoryInfo]$Candidate
		$PackageClassConfiguration = New-PropertyContainer (Join-Path $PackageClassFolder.FullName "package.json")

		$PackageRepositoryFolder = $PackageClassFolder.Parent
		$PackageRepositoryConfiguration = New-PropertyContainer (Join-Path $PackageRepositoryFolder.FullName "package.json")

		$PackageRepository = [PackageRepository] @{
			Name = "$($PackageRepositoryFolder.Parent.Name)$Suffix"
			Directory = $PackageRepositoryFolder
			Configuration = $PackageRepositoryConfiguration
			EffectiveConfiguration = New-MergeContainer @($PackageRepositoryConfiguration) -PackageId $RepositoryId
		}

		$PackageClass = [PackageClass] @{
			Name = $PackageClassFolder.Name
			Directory = $PackageClassFolder
			Repository = $PackageRepository
			Configuration = $PackageClassConfiguration
			EffectiveConfiguration = New-MergeContainer @($PackageClassConfiguration, $PackageRepositoryConfiguration) -PackageId "$Prefix$($PackageClassFolder.Name)/*"
		}

		Write-Output $PackageClass
	}
}

function Get-Package {
	param(
		[Parameter(Mandatory = $false, Position = 0)] [string] $Filter
	)

	if ([string]::IsNullOrWhiteSpace($Filter)) {
		$Filter = "*"
	}

	if ([string]::IsNullOrWhiteSpace($Filter)) {
		$Filter = "*"
	}

	if ($Filter.Contains(":")) {
		$Tokens = $Filter.Split(@(":"), 2, [StringSplitOptions]::RemoveEmptyEntries)

		if ($Tokens.Length -eq 1) {
			$Filter = $Tokens[0]
			$RepositoryId = $global:System.Environment.DefaultRepository
		} else {
			$Filter = $Tokens[1]
			$RepositoryId = $Tokens[0]
		}
	} else {
		$RepositoryId = $global:System.Environment.DefaultRepository
	}

	$SolutionRoot = Join-Path $global:System.RootDirectory $RepositoryId

	if ($Filter.Contains("/")) {
		$Tokens = $Filter.Split(@("/"), 2, [StringSplitOptions]::RemoveEmptyEntries)

		if ($Tokens.Length -eq 1) {
			$Name = $Tokens[0]
			$Class = "*"
		} else {
			$Name = $Tokens[1]
			$Class = $Tokens[0]
		}
	} else {
		$Name = $Filter
		$Class = "*"
	}

	if (-not (Test-Path $SolutionRoot -PathType Container)) {
		$Candidates = @()
	} else {
		$Candidates = @( `
			Get-ChildItem -Path $SolutionRoot -Directory -Filter $Class | Foreach-Object { `
			Get-ChildItem -Path $_.FullName -Directory -Filter $Name })
	}

	if ($RepositoryId -ne $global:System.Environment.DefaultRepository) {
		$Prefix = "$($RepositoryId):"
		$Suffix = " ($($RepositoryId))"
	}
	else {
		$Prefix = ""
		$Suffix = ""
	}

	if ($Candidates.Length -eq 0) {
		if (-not (Test-ArbitaryToken -Id "$Class\$Name" -IllegalChars @("*", "?"))) {
			return
		}

		$PackageFolder = [IO.DirectoryInfo] (Join-Path $SolutionRoot "$Class\$Name")
		$PackageConfiguration = New-PropertyContainer (Join-Path $PackageFolder.FullName "package.json")

		$PackageClassFolder = [IO.DirectoryInfo] (Join-Path $SolutionRoot "$Class")
		$PackageClassConfiguration = New-PropertyContainer (Join-Path $PackageClassFolder.FullName "package.json")

		$PackageRepositoryFolder = [IO.DirectoryInfo] $SolutionRoot
		$PackageRepositoryConfiguration = New-PropertyContainer (Join-Path $PackageRepositoryFolder.FullName "package.json")

		$PackageRepository = [PackageRepository] @{
			Name = $RepositoryId
			Directory = $PackageRepositoryFolder
			Configuration = $PackageRepositoryConfiguration
			EffectiveConfiguration = New-MergeContainer @($PackageRepositoryConfiguration) -PackageId $RepositoryId
		}

		$PackageClass = [PackageClass] @{
			Name = $PackageClassFolder.Name
			Directory = $PackageClassFolder
			Repository = $PackageRepository
			Configuration = $PackageClassConfiguration
			EffectiveConfiguration = New-MergeContainer @($PackageClassConfiguration, $PackageRepositoryConfiguration) -PackageId "$Prefix$($PackageClassFolder.Name)/*"
		}

		$Package = [Package] @{
			Name = $PackageFolder.Name
			Directory = $PackageFolder
			Repository = $PackageRepository
			Class = $PackageClass
			Configuration = $PackageConfiguration
			EffectiveConfiguration = New-MergeContainer @($PackageConfiguration, $PackageClassConfiguration, $PackageRepositoryConfiguration) -PackageId "$Prefix$($PackageClassFolder.Name)/$($PackageFolder.Name)"
		}

		return @($Package)
	}

	foreach($Candidate in $Candidates) {

		$PackageFolder = [IO.DirectoryInfo]$Candidate
		$PackageConfiguration = New-PropertyContainer (Join-Path $PackageFolder.FullName "package.json")

		$PackageClassFolder = $PackageFolder.Parent
		$PackageClassConfiguration = New-PropertyContainer (Join-Path $PackageClassFolder.FullName "package.json")

		$PackageRepositoryFolder = $PackageClassFolder.Parent
		$PackageRepositoryConfiguration = New-PropertyContainer (Join-Path $PackageRepositoryFolder.FullName "package.json")

		$PackageRepository = [PackageRepository] @{
			Name = "$($PackageRepositoryFolder.Parent.Name)$Suffix"
			Directory = $PackageRepositoryFolder
			Configuration = $PackageRepositoryConfiguration
			EffectiveConfiguration = New-MergeContainer @($PackageRepositoryConfiguration) -PackageId $Prefix.TrimEnd(":")
		}

		$PackageClass = [PackageClass] @{
			Name = $PackageClassFolder.Name
			Directory = $PackageClassFolder
			Repository = $PackageRepository
			Configuration = $PackageClassConfiguration
			EffectiveConfiguration = New-MergeContainer @($PackageClassConfiguration, $PackageRepositoryConfiguration) -PackageId "$Prefix$($PackageClassFolder.Name)/*"
		}

		$Package = [Package] @{
			Name = $PackageFolder.Name
			Directory = $PackageFolder
			Repository = $PackageRepository
			Class = $PackageClass
			Configuration = $PackageConfiguration
			EffectiveConfiguration = New-MergeContainer @($PackageConfiguration, $PackageClassConfiguration, $PackageRepositoryConfiguration) -PackageId "$Prefix$($PackageClassFolder.Name)/$($PackageFolder.Name)"
		}

		Write-Output $Package
	}
}

function Get-RepositoryItem {
	param(
		[Parameter(Mandatory = $false, Position = 0)] [string] $Filter
	)

	if ([string]::IsNullOrWhiteSpace($Filter)) {
		return Get-PackageRepository
	}

	if ($Filter.Trim() -eq ":" -or $Filter.Trim() -eq "/") {
		return @()
	}

	if ($Filter.Trim().EndsWith(":")) { # e.g. "src:"
		return Get-PackageRepository -Id $Filter.Trim().TrimEnd(":")
	}

	if ($Filter.Trim().StartsWith("/")) { # e.g. "/app"
		return Get-Package -Filter "*/$($Filter.Trim().TrimStart("/"))"
	}

	if ($Filter.Trim().EndsWith("/")) { # e.g. "app/"
		return Get-PackageClass -Filter "$($Filter.Trim().TrimEnd("/"))/*"
	}

	if ($Filter.Contains("/")) { # e.g. "app/package"
		return Get-Package -Filter $Filter
	}

	if ($Filter.Contains(":")) { # e.g. "src:app"
		return Get-PackageClass -Filter $Filter
	}

	# rest, e.g. "app"
	return Get-PackageClass -Filter $Filter
}

function Initialize-Package {
	[CmdLetBinding(SupportsShouldProcess=$true)]
	param(
		[Parameter(ValueFromPipeline = $true, Mandatory = $true)] [Package] $Package,
		[Parameter(Position = 0, Mandatory = $false)] [string] $Template,
		[Parameter(Mandatory = $false)] [System.Collections.Hashtable] $Properties = $null,
		[switch] $Overwrite,
		[switch] $Force
	)

	process {
		if ($Package -eq $null) {
			return
		}

		if (-not [string]::Equals($Package.GetType().BaseType.Name, "HierarchyLevel")) {
            Write-Error "Can't initialize ""$Package"": not a valid package reference"
            Return
        }

		$defaultTemplate = $Package.Class.EffectiveConfiguration.getProperty("DefaultTemplate")

		if ([string]::IsNullOrWhiteSpace($Template)) {
			$Template = $defaultTemplate
		}

		$templateSearchPaths = @(
			"templates",
			"tools\pacman\templates"
		)
		$templateExtensions = @(
			"template",
			"zip"
		)

		$foundTemplateFile = $null

		if(-not [string]::IsNullOrWhiteSpace($Template)){
			foreach($templateSearchPath in $templateSearchPaths) {
				foreach($templateExtension in $templateExtensions) {

					$templateFile = Join-Path $global:System.RootDirectory "$templateSearchPath\$Template.$templateExtension"
					$templateDir = Join-Path $global:System.RootDirectory "$templateSearchPath\$Template"

					if (Test-Path $templateDir -PathType Container) {
						$foundTemplateFile = $templateDir
						break
					}

					if (Test-Path $templateFile -PathType Leaf) {
						$foundTemplateFile = $templateFile
						break
					}
				}

				if ($foundTemplateFile -ne $null) {
					break
				}
			}

			if ($foundTemplateFile -eq $null) {
				Write-Error "Unable to find template ""$Template""."
				return
			}
		}

		if ($pscmdlet.ShouldProcess("$($Package.Class)/$Package", "Init:CreateDirectory")) {
			$null = $Package.Directory.Create()
		}

		if ($Package.Directory.Exists) {
			$preExistingFiles = @(Get-ChildItem $Package.Directory.FullName -File -Recurse).Length -gt 0
		}
		else {
			$preExistingFiles = @()
		}

		if ($pscmdlet.ShouldProcess("$($Package.Class)/$Package", "Init:CreatePackageConfiguration")) {
			$packageProps = New-PropertyContainer -Force (Join-Path $Package.Directory.FullName "package.json")

			$packageProps.setProperty("name", $Package.Name)
			$packageProps.setProperty("version", "0.1.0")
			$packageProps.setProperty("description", $Package.Name)
		}

		if ($foundTemplateFile -ne $null) {

			if (-not $Force -and $preExistingFiles) {
				Write-Error "The package directory ""$($Package.Directory.FullName)"" is not empty. If you wish to apply the template anyway, add the switch ""Force""."
				Return
			}

			if ($pscmdlet.ShouldProcess("$($Package.Class)/$Package", "Init:ExpandTemplate(""$foundTemplateFile"")")) {
				$templateContext = @{
					"Package" = $Package
					"Properties" = [PSCustomObject] $Properties
					"Metadata" = (New-PropertyContainer (Join-Path $Package.Directory.FullName "package.json"))
				}

				if ($templateContext.Properties -eq $null) {
					$templateContext.Properties = @{ }
				}

				Expand-TemplatePackage -TemplateFile $foundTemplateFile -Destination $Package.Directory.FullName -Force:$Overwrite -Context $templateContext -InformationAction "$InformationPreference" -Verbose:($VerbosePreference -ne "SilentlyContinue")
			}
		}

		Write-Output $Package
	}
}

function Get-PackageProperty {
	param(
		[Parameter(ValueFromPipeline = $true, Mandatory = $true)] [HierarchyLevel] $Package,
		[Parameter(Mandatory = $true, Position = 0)] [string] $Property
	)

	process {
		if ($Package -eq $null) {
			Return
		}

		if (-not [string]::Equals($Package.GetType().BaseType.Name, "HierarchyLevel")) {
            Write-Error "Can't read ""$Package"": not a valid package reference"
            Return
		}

		$tokens = Get-PropertyPathTokens -PropertyPath $Property

		if ($tokens -eq $null -or $tokens.Length -eq 0) {
			Return
		}

		Write-Verbose "Tokenizer result: $($tokens -join " -> ")"

		try {
			$propScript = [ScriptBlock]::Create("`$_.$(@($tokens) -join ".")")
		}
		catch {
			Write-Error "Invalid property path: $PropertyPath"
			Return
		}

		$Package.EffectiveConfiguration.getObject() | Foreach-Object -Process $propScript | Write-Output
	}
}

function Set-PackageProperty {
	[CmdLetBinding(SupportsShouldProcess=$true)]
	param(
		[Parameter(ValueFromPipeline = $true, Mandatory = $true)] $Package,
		[Parameter(Mandatory = $true, Position = 0)] [string] $Property,
		[Parameter(Mandatory = $false, Position = 1)] [string] $Value
	)

	process {
		if ($Package -eq $null) {
			Return
		}

		if (-not [string]::Equals($Package.GetType().BaseType.Name, "HierarchyLevel")) {
            Write-Error "Can't update ""$Package"": not a valid package reference"
            Return
		}

		if (-not $Package.Directory.Exists) {
			if ($pscmdlet.ShouldProcess("$($Package.Class)/$Package", "Config:InitPackage")) {
				if ($Package -is [Package]){
					$null = $Package | init
				}
				else {
					$null = New-Item -ItemType Directory -Path $Package.Directory.FullName
				}
			}
		}

		$tokens = @(Get-PropertyPathTokens -PropertyPath $Property)

		if ($tokens -eq $null -or $tokens.Length -eq 0) {
			Return
		}

		$head = @($tokens | Select-Object -SkipLast 1)
		$tail = $tokens | Select-Object -Last 1
		$node = $Package.Configuration

		if ($tail -eq $null) {
			Return
		}

		Write-Verbose "Tokenizer result: $($tokens -join " -> ")"

		foreach($token in $head) {
			$node = $node.getChild($token)
		}

		if ($pscmdlet.ShouldProcess("$($Package.Class)/$Package", "Config:WriteValue")) {
			$node.setProperty($tail, $Value)
		}

		Write-Output $Package
	}
}

####################### Aliases / Exports ######################

Set-Alias "pkg"  "Get-RepositoryItem"
Set-Alias "ppkg" "Get-Package"
Set-Alias "pcls" "Get-PackageClass"
Set-Alias "repo" "Get-PackageRepository"
Set-Alias "pcfg" "Get-PackageConfiguration"
Set-Alias "pget" "Get-PackageProperty"
Set-Alias "pset" "Set-PackageProperty"
Set-Alias "init" "Initialize-Package"

Export-ModuleMember -Function @(
	"Get-Package",
	"Get-PackageClass",
	"Get-PackageRepository",
	"Get-RepositoryItem",
	"Get-PackageProperty",
	"Get-PackageConfiguration",
	"Set-PackageProperty",
	"Initialize-Package"
) -Alias @(
	"pkg",
	"ppkg",
	"pcls",
	"repo",
	"prop",
	"pcfg",
	"init",
	"pget",
	"pset"
)


text:
package org.caleydo.view.domino.internal.tourguide;

import org.caleydo.core.view.opengl.layout.Column.VAlign;
import org.caleydo.core.view.opengl.layout2.renderer.GLRenderers;
import org.caleydo.vis.lineup.model.IRow;
import org.caleydo.vis.lineup.model.IntegerRankColumnModel;

import com.google.common.base.Function;

public class SizeRankColumnModel extends IntegerRankColumnModel {
	public SizeRankColumnModel(String label, Function<IRow, Integer> data) {
		super(GLRenderers.drawText(label, VAlign.CENTER), data);
	}

	public SizeRankColumnModel(SizeRankColumnModel copy) {
		super(copy);
	}

	@Override
	public SizeRankColumnModel clone() {
		return new SizeRankColumnModel(this);
	}

	@Override
	public int compare(IRow o1, IRow o2) {
		return -super.compare(o1, o2);
	}

}


text:
import cv2
import logging
from collections import namedtuple
from .detector import Detector, DetectorException

SimpleMotionDetectorConfig = namedtuple('SimpleMotionDetectorConfig',
                                        ['diff_threshold',
                                         'blurring_size',
                                         'object_min_area',
                                         'pixel_intensity_threshold'],
                                        verbose=False)

# The simple motion detector detects objects by just subtracting the
# current frame with the previous and then analyze the diff.
# If the number of diffing pixels exceeds the threshold an object is
# considered detected.
# The code is a somewhat modified version of an example on Adrian
# Rosebrock's blog post:
#
# http://www.pyimagesearch.com/2015/05/25/basic-motion-detection-and-tracking-with-python-and-opencv/
#
# The most notable difference is that the current frame is diffed against
# the previous frame and not the background.
class SimpleMotionDetector(Detector):

    def __init__(self, name, config):

        Detector.__init__(self,
                          name=name)

        self._logger = logging.getLogger(__name__)

        self._prev_frame = None
        self._blurring_size = config.blurring_size
        self._diff_threshold = config.diff_threshold
        self._object_min_area = config.object_min_area
        self._pixel_intensity_threshold = config.pixel_intensity_threshold

    def detect(self, frame):

        if self._prev_frame is None:
            # Special case: First run.
            # We can't make a diff, so just return an empty rectangles list.
            self._prev_frame = frame
            return []

        # Blur the frame in order to reduce noise
        frame = cv2.GaussianBlur(frame, (self._blurring_size, self._blurring_size), 0)

        # Do the actual diffing
        frame_delta = cv2.absdiff(self._prev_frame, frame)
        thresh = cv2.threshold(frame_delta,
                               self._pixel_intensity_threshold,
                               255, cv2.THRESH_BINARY)[1]

        thresh = cv2.dilate(thresh, None, iterations=2)
        (im2, contours, _) = cv2.findContours(thresh.copy(),
                                              cv2.RETR_EXTERNAL,
                                              cv2.CHAIN_APPROX_SIMPLE)

        rects = []
        total_contour_area = 0
        for c in contours:
            cur_area = cv2.contourArea(c)
            if cur_area < self._object_min_area:
                continue

            total_contour_area += cur_area

            # compute the bounding box for the contour, draw it on the frame,
            # and update the text
            rect = cv2.boundingRect(c)
            rects.append(rect)

        (height, width) = frame.shape
        total_frame_area = height * width
        diff_percentage = (total_contour_area * 100) / total_frame_area
        if diff_percentage < self._diff_threshold:
            # No significant difference between this frame and the previous
            rects = []

        self._prev_frame = frame

        return rects


text:
Flame.CheckboxView = Flame.ButtonView.extend({
    classNames: ['flame-checkbox-view'],
    isSticky: true,
    //Overwrite the parent handlebars as we're using render all the way!
    handlebars: null,

    render: function(context) {
        this._super(context);
        context.push("

");
        this.renderCheckMark(context);
        var title = Ember.none(this.get("title")) ? "" : this.get("title");
        context.push("" + title + "");
    },

    renderCheckMark: function(context) {
        var imgUrl = Flame.image('checkmark.png');
        context.push("

");
    }
});


text:
require 'yaml'
require 'slim'
require 'redcarpet'
require 'liquid'
require 'tilt'
require 'sinatra/base'
require 'sinatra/asset_pipeline'
require 'sprockets-less'
require 'sprockets-helpers'
require 'less'
require 'sass'
require 'uglifier'
require 'rollbar'
require 'rollbar/middleware/sinatra'
require 'autoprefixer-rails'
require 'cucumber/website/page'
require 'cucumber/website/config'
require 'cucumber/website/calendar'
require 'cucumber/website/events'
require 'cucumber/website/reference'

Slim::Engine.set_options(pretty: ENV['RACK_ENV'] != 'production')
Slim::Engine.disable_option_validator!
IGNORED_NOT_FOUND_PATHS = /^\/(maven|netbeans)/

# Sinatra app that displays a Jekyll app dynamically.
#
# Why? A couple of reasons:
#
# * We have special requirements for the generated docs. Seemed easier to go the dynamic route.
# * We want to have some dynamic content as well as "static".
#
# Supports several template engines: Markdown, Slim and Erb.
# All templates are pre-processed with Liquid.
#
# Markdown can be used to generate reference documentation. Features include:
#
# * Automatic generation of nested left nav based on Markdown headers
# * Uses Bootstrap scroll spy to collapse/expand nav items
# * Mini-smartypants. --- gets converted to an emdash
# * Use [carousel] to create a carousel of code samples for different languages
# * Use {} in headers to create unique anchors when there are clashes
#
module Cucumber
module Website
  class App < Sinatra::Application
    set :root,  File.dirname(__FILE__)

    # TODO: do we need these? Won't they be inferred from the root anyway?
    set :public_folder, Proc.new { File.join(root, 'public') }
    set :views, Proc.new { File.join(root, 'views') }

    set :assets_precompile, %w(main.js main.css cukeup.js cukeup.css *.png *.jpg *.svg *.eot *.ttf *.woff *.woff2)
    set :assets_css_compressor, :sass
    set :assets_js_compressor, :uglifier

    use Rollbar::Middleware::Sinatra
    register Sinatra::AssetPipeline
    AutoprefixerRails.install(sprockets)

    extend Config
    CONFIG = load_config(ENV['RACK_ENV'])

    pages = Page.all(CONFIG, views)

    CONFIG['site']['posts'] =
      pages.select(&:post?).select { |page| page.date < Time.now }
      .sort { |a, b| b.date <=> a.date }

    calendar_logger = Logger.new($stderr)
    calendars = CONFIG['site']['calendars'].map { |url| Cucumber::Website::Calendar.new(url, calendar_logger) }
    events = Cucumber::Website::Events.new(pages.select(&:event?), calendars)
    CONFIG['site']['events'] = events

    configure(:development, :production) do
      events.start(CONFIG['site']['calendar_refresh_interval'])
    end

    pages.each do |page|
      next unless page.primary?

      get page.path do
        headers.merge!(page.headers)

        if page.cacheable?
          timestamps = pages.map(&:timestamp) + [File.mtime(__FILE__)]
          last_modified timestamps.max
        end

        page.render(self)
      end
    end

    before do
      cache_control :public
    end

    before /(.*)\.html/ do
      url = params[:captures][0]
      redirect to(url), 301
    end

    helpers do
      include Sprockets::Helpers

      def nav_class(slug, name)
        slug == name ? 'active' : nil
      end

      def edit_url(template_path)
        "#{CONFIG['site']['edit_url']}/#{template_path}"
      end
    end

    error 500 do
      status 500
      slim :error
    end

    not_found do
      path_info = env['PATH_INFO']
      Rollbar.warning("Not found: #{path_info}", env) unless path_info.match(IGNORED_NOT_FOUND_PATHS)
      status 404
      slim :not_found
    end
  end
end
end


text:
<?php // lint >= 8.1

class Test
{
	public function __construct(protected int $promoted1, readonly private string $promoted2)
	{
	}
}


text:
package org.myeslib.hazelcast.storage;

import static com.google.common.base.Preconditions.checkNotNull;

import java.util.ConcurrentModificationException;

import lombok.extern.slf4j.Slf4j;

import org.myeslib.core.data.AggregateRootHistory;
import org.myeslib.core.data.UnitOfWork;
import org.myeslib.core.storage.UnitOfWorkJournal;

import com.google.inject.Inject;
import com.hazelcast.core.IMap;

@Slf4j
public class HzUnitOfWorkJournal<K> implements UnitOfWorkJournal<K> {

	private final IMap<K, AggregateRootHistory> pastTransactionsMap ;

	@Inject
	public HzUnitOfWorkJournal(IMap<K, AggregateRootHistory> pastTransactionsMap) {
		checkNotNull(pastTransactionsMap);
		this.pastTransactionsMap = pastTransactionsMap;
	}

	/*
	 * (non-Javadoc)
	 * @see org.myeslib.core.storage.UnitOfWorkJournal#append(java.lang.Object, org.myeslib.core.data.UnitOfWork)
	 */
	public void append(final K id, final UnitOfWork uow) {
		checkNotNull(id);
		checkNotNull(uow);
		final AggregateRootHistory history = getHistoryFor(id);
		if (!history.getLastVersion().equals(uow.getTargetVersion())){
			throw new ConcurrentModificationException(String.format("version %s does not match the expected %s ****",
																	history.getLastVersion().toString(),
																	uow.getTargetVersion().toString())
													 );

		}
		log.info("will set {}", id);
		history.add(uow);
		pastTransactionsMap.set(id, history); // hazelcast optimization --> set instead of put since is void
	}

	private AggregateRootHistory getHistoryFor(final K id) {
		// TODO WARNING https://github.com/hazelcast/hazelcast/issues/1593
		log.debug("looking for {} on map {} ", id, pastTransactionsMap.getName());
		AggregateRootHistory history = pastTransactionsMap.get(id);
		if (history==null) {
			log.debug("found NULL value for {} on map {} ", id, pastTransactionsMap.getName());
		}
		return history == null ? new AggregateRootHistory() : history;
	}

}


text:
package org.apache.apex.examples.csvformatter;

import javax.validation.constraints.NotNull;

import com.datatorrent.api.Context.OperatorContext;
import com.datatorrent.lib.io.fs.AbstractFileOutputOperator;

/**
 * HDFSoutput operator with implementation to write Objects to HDFS
 *
 * @param <T>
 *
 * @since 3.7.0
 */
public class HDFSOutputOperator<T> extends AbstractFileOutputOperator<T>
{

  @NotNull
  String outFileName;

  //setting default value
  String lineDelimiter = "\n";

  //Switch to write the files to HDFS - set to false to diable writes
  private boolean writeFilesFlag = true;

  int id;

  @Override
  public void setup(OperatorContext context)
  {
    super.setup(context);
    id = context.getId();
  }

  public boolean isWriteFilesFlag()
  {
    return writeFilesFlag;
  }

  public void setWriteFilesFlag(boolean writeFilesFlag)
  {
    this.writeFilesFlag = writeFilesFlag;
  }

  public String getOutFileName()
  {
    return outFileName;
  }

  public void setOutFileName(String outFileName)
  {
    this.outFileName = outFileName;
  }

  @Override
  protected String getFileName(T tuple)
  {
    return getOutFileName() + id;
  }

  public String getLineDelimiter()
  {
    return lineDelimiter;
  }

  public void setLineDelimiter(String lineDelimiter)
  {
    this.lineDelimiter = lineDelimiter;
  }

  @Override
  protected byte[] getBytesForTuple(T tuple)
  {
    String temp = tuple.toString().concat(String.valueOf(lineDelimiter));
    byte[] theByteArray = temp.getBytes();

    return theByteArray;
  }

  @Override
  protected void processTuple(T tuple)
  {
    //if (writeFilesFlag) {
    //}
    super.processTuple(tuple);
  }

}


text:
package iso20022

type FinancingStatusReason1Code string


text:
package com.ryanst.app.activity;

import android.databinding.DataBindingUtil;
import android.databinding.Observable;
import android.databinding.ObservableField;
import android.os.Bundle;
import android.view.View;

import com.ryanst.app.R;
import com.ryanst.app.bean.DataBindingBean;
import com.ryanst.app.bean.PlainObject;
import com.ryanst.app.core.BaseSlideActivity;
import com.ryanst.app.databinding.ActivityDataBindingBinding;

/**
 * Created by zhengjuntong on 16/5/4.
 */
public class DataBindingActivity extends BaseSlideActivity {

    //ActivityDataBindingBinding的命名来自于activity_data_binding 大写,去除_,然后在末尾加上Binding
    ActivityDataBindingBinding binding;
    DataBindingBean dataObject;
    private PlainObject plainObject;
    private int count;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_data_binding);
        dataObject = new DataBindingBean("data1", "data2");
        binding.setDataObject(dataObject);

        plainObject = new PlainObject(new ObservableField<>("content"), "plain");
        binding.setPlainObject(plainObject);

        binding.btnChangeTextToObject.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeText();
            }
        });

        binding.btnChangeObjectToText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeObject();
            }
        });

        count = 0;

        binding.testField.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                plainObject.content.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
                    @Override
                    public void onPropertyChanged(Observable observable, int i) {

                    }
                });

                plainObject.content.set("content" + (count++));
                plainObject.setPlainText("plain" + count);

                //binding.setVariable(BR.plainObject, plainObject);
                //无需调用这行,即可实现数据改变驱动UI变化的效果
                //如果调用这行的话,不是ObservableField的plainText也可以实现数据改变从而改变UI的效果
                //所以ObservableField的优势在于可以直接set从而驱动UI改变
            }
        });
    }

    //是不能通过改变View改变数据的
    private void changeText() {
        binding.tvText1.setText("text1->data1");
        binding.tvText2.setText("text2->data2");
        String data1 = dataObject.getData1();
        String data2 = dataObject.getData2();
        toast("1:" + data1 + "2:" + data2);
    }

    //可以通过改变数据从而改变View,因为set方法中调用了notifyPropertyChanged
    private void changeObject() {
        dataObject.setData1("data1->text1");
        dataObject.setData2("data2->text2");
    }
}


text:
package io.debezium.connector.mysql;

import com.github.shyiko.mysql.binlog.event.deserialization.AbstractRowsEventDataDeserializer;
import com.github.shyiko.mysql.binlog.event.deserialization.json.JsonBinary;
import io.debezium.DebeziumException;
import io.debezium.annotation.Immutable;
import io.debezium.config.CommonConnectorConfig.BinaryHandlingMode;
import io.debezium.connector.mysql.antlr.MySqlAntlrDdlParser;
import io.debezium.data.Json;
import io.debezium.jdbc.JdbcValueConverters;
import io.debezium.jdbc.TemporalPrecisionMode;
import io.debezium.relational.Column;
import io.debezium.relational.Table;
import io.debezium.relational.ValueConverter;
import io.debezium.time.Year;
import io.debezium.util.Strings;
import org.apache.kafka.connect.data.Decimal;
import org.apache.kafka.connect.data.Field;
import org.apache.kafka.connect.data.Schema;
import org.apache.kafka.connect.data.SchemaBuilder;
import org.apache.kafka.connect.errors.ConnectException;
import org.apache.kafka.connect.source.SourceRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.sql.Types;
import java.time.Duration;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAdjuster;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * MySQL-specific customization of the conversions from JDBC values obtained from the MySQL binlog client library.
 *

 * This class always uses UTC for the default time zone when converting values without timezone information to values
 * that require timezones. This is because MySQL {@code TIMESTAMP} values are always
 * stored in UTC (unlike {@code DATETIME} values)
 * and are replicated in this form. Meanwhile, the MySQL Binlog Client library will
 * {@link AbstractRowsEventDataDeserializer deserialize} these as {@link java.sql.Timestamp} values that have no
 * timezone and, therefore, are presumed to be in UTC. When the column is properly marked with a
 * {@link Types#TIMESTAMP_WITH_TIMEZONE} type, the converters will need to convert that {@link java.sql.Timestamp}
 * value into an {@link OffsetDateTime} using the default time zone, which always is UTC.
 *
 * @author Randall Hauch
 * @see com.github.shyiko.mysql.binlog.event.deserialization.AbstractRowsEventDataDeserializer
 */
@Immutable
public class MySqlValueConverters extends JdbcValueConverters {

  /**
   *
   */
  @FunctionalInterface
  public interface ParsingErrorHandler {
    void error(String message, Exception exception);
  }
  private static final String METHOD_GET_STATIC_JAVA_ENCODING = "getStaticJavaEncodingForMysqlCharset";
  private static final String METHOD_GET_JAVA_ENCODING = "getJavaEncodingForMysqlCharset";

  private static final String CLASS_CHARSET_MAPPING = "com.mysql.cj.CharsetMapping";

  private static final Logger LOGGER = LoggerFactory.getLogger(MySqlValueConverters.class);

  /**
   * Used to parse values of TIME columns. Format: 000:00:00.000000.
   */
  private static final Pattern TIME_FIELD_PATTERN = Pattern.compile("(\\-?[0-9]*):([0-9]*):([0-9]*)(\\.([0-9]*))?");

  /**
   * Used to parse values of DATE columns. Format: 000-00-00.
   */
  private static final Pattern DATE_FIELD_PATTERN = Pattern.compile("([0-9]*)-([0-9]*)-([0-9]*)");

  /**
   * Used to parse values of TIMESTAMP columns. Format: 000-00-00 00:00:00.000.
   */
  private static final Pattern TIMESTAMP_FIELD_PATTERN = Pattern.compile("([0-9]*)-([0-9]*)-([0-9]*) .*");

  /**
   * ===================== This is a diff from the original file ===========================
   * It's a hacky way for us to intentionally pass in the jdbc class loader to load 'com.mysql.cj.CharsetMapping'
   * class so that we can invoke the 'getJavaEncodingForMysqlCharset' static method. The usage of this class loader
   * is in 'charsetFor(Column column) ' method from line 341 to 354.
   */
  public static ClassLoader jdbcClassLoader;

  /**
   * A utility method that adjusts ambiguous
   * 2-digit year values of DATETIME, DATE, and TIMESTAMP types using these MySQL-specific rules:
   *

   *
Year values in the range 00-69 are converted to 2000-2069.

   *
Year values in the range 70-99 are converted to 1970-1999.

   *

   *
   * @param temporal the temporal instance to adjust; may not be null
   * @return the possibly adjusted temporal instance; never null
   */
  protected static Temporal adjustTemporal(Temporal temporal) {
    if (temporal.isSupported(ChronoField.YEAR)) {
      int year = temporal.get(ChronoField.YEAR);
      if (0 <= year && year <= 69) {
        temporal = temporal.plus(2000, ChronoUnit.YEARS);
      } else if (70 <= year && year <= 99) {
        temporal = temporal.plus(1900, ChronoUnit.YEARS);
      }
    }
    return temporal;
  }

  private final ParsingErrorHandler parsingErrorHandler;

  /**
   * Create a new instance that always uses UTC for the default time zone when_needed converting values without
   * timezone information to values that require timezones.
   *

   *
   * @param decimalMode how {@code DECIMAL} and {@code NUMERIC} values should be treated; may be null if
   *            {@link io.debezium.jdbc.JdbcValueConverters.DecimalMode#PRECISE} is to be used
   * @param temporalPrecisionMode temporal precision mode based on {@link io.debezium.jdbc.TemporalPrecisionMode}
   * @param bigIntUnsignedMode how {@code BIGINT UNSIGNED} values should be treated; may be null if
   *            {@link io.debezium.jdbc.JdbcValueConverters.BigIntUnsignedMode#PRECISE} is to be used
   * @param binaryMode how binary columns should be represented
   */
  public MySqlValueConverters(DecimalMode decimalMode, TemporalPrecisionMode temporalPrecisionMode,
                              BigIntUnsignedMode bigIntUnsignedMode, BinaryHandlingMode binaryMode) {
    this(decimalMode, temporalPrecisionMode, bigIntUnsignedMode, binaryMode, x -> x, (message, exception) -> {
      throw new DebeziumException(message, exception);
    });
  }

  /**
   * Create a new instance that always uses UTC for the default time zone when converting values without timezone
   * information to values that require timezones.
   *

   *
   * @param decimalMode how {@code DECIMAL} and {@code NUMERIC} values should be treated; may be null if
   *            {@link io.debezium.jdbc.JdbcValueConverters.DecimalMode#PRECISE} is to be used
   * @param temporalPrecisionMode temporal precision mode based on {@link io.debezium.jdbc.TemporalPrecisionMode}
   * @param bigIntUnsignedMode how {@code BIGINT UNSIGNED} values should be treated; may be null if
   *            {@link io.debezium.jdbc.JdbcValueConverters.BigIntUnsignedMode#PRECISE} is to be used
   * @param binaryMode how binary columns should be represented
   * @param adjuster a temporal adjuster to make a database specific time modification before conversion
   * @param parsingErrorHandler for errors during postponed binlog parsing
   */
  public MySqlValueConverters(DecimalMode decimalMode, TemporalPrecisionMode temporalPrecisionMode,
                              BigIntUnsignedMode bigIntUnsignedMode, BinaryHandlingMode binaryMode,
                              TemporalAdjuster adjuster, ParsingErrorHandler parsingErrorHandler) {
    super(decimalMode, temporalPrecisionMode, ZoneOffset.UTC, adjuster, bigIntUnsignedMode, binaryMode);
    this.parsingErrorHandler = parsingErrorHandler;
  }

  @Override
  protected ByteOrder byteOrderOfBitType() {
    return ByteOrder.BIG_ENDIAN;
  }

  @Override
  public SchemaBuilder schemaBuilder(Column column) {
    // Handle a few MySQL-specific types based upon how they are handled by the MySQL binlog client ...
    String typeName = column.typeName().toUpperCase();
    if (matches(typeName, "JSON")) {
      return Json.builder();
    }
    if (matches(typeName, "POINT")) {
      return io.debezium.data.geometry.Point.builder();
    }
    if (matches(typeName, "GEOMETRY")
      || matches(typeName, "LINESTRING")
      || matches(typeName, "POLYGON")
      || matches(typeName, "MULTIPOINT")
      || matches(typeName, "MULTILINESTRING")
      || matches(typeName, "MULTIPOLYGON")
      || isGeometryCollection(typeName)) {
      return io.debezium.data.geometry.Geometry.builder();
    }
    if (matches(typeName, "YEAR")) {
      return Year.builder();
    }
    if (matches(typeName, "ENUM")) {
      String commaSeperatedOptions = extractEnumAndSetOptionsAsString(column);
      return io.debezium.data.Enum.builder(commaSeperatedOptions);
    }
    if (matches(typeName, "SET")) {
      String commaSeperatedOptions = extractEnumAndSetOptionsAsString(column);
      return io.debezium.data.EnumSet.builder(commaSeperatedOptions);
    }
    if (matches(typeName, "SMALLINT UNSIGNED") || matches(typeName, "SMALLINT UNSIGNED ZEROFILL")
      || matches(typeName, "INT2 UNSIGNED") || matches(typeName, "INT2 UNSIGNED ZEROFILL")) {
      // In order to capture unsigned SMALLINT 16-bit data source, INT32 will be required to safely capture all valid
      // values
      // Source: https://kafka.apache.org/0102/javadoc/org/apache/kafka/connect/data/Schema.Type.html
      return SchemaBuilder.int32();
    }
    if (matches(typeName, "INT UNSIGNED") || matches(typeName, "INT UNSIGNED ZEROFILL")
      || matches(typeName, "INT4 UNSIGNED") || matches(typeName, "INT4 UNSIGNED ZEROFILL")) {
      // In order to capture unsigned INT 32-bit data source, INT64 will be required to safely capture all valid values
      // Source: https://kafka.apache.org/0102/javadoc/org/apache/kafka/connect/data/Schema.Type.html
      return SchemaBuilder.int64();
    }
    if (matches(typeName, "BIGINT UNSIGNED") || matches(typeName, "BIGINT UNSIGNED ZEROFILL")
      || matches(typeName, "INT8 UNSIGNED") || matches(typeName, "INT8 UNSIGNED ZEROFILL")) {
      switch (super.bigIntUnsignedMode) {
        case LONG:
          return SchemaBuilder.int64();
        case PRECISE:
          // In order to capture unsigned INT 64-bit data source, org.apache.kafka.connect.data.Decimal:Byte will be
          // required to safely capture all valid values with scale of 0
          // Source: https://kafka.apache.org/0102/javadoc/org/apache/kafka/connect/data/Schema.Type.html
          return Decimal.builder(0);
      }
    }
    // Otherwise, let the base class handle it ...
    return super.schemaBuilder(column);
  }

  @Override
  public ValueConverter converter(Column column, Field fieldDefn) {
    // Handle a few MySQL-specific types based upon how they are handled by the MySQL binlog client ...
    String typeName = column.typeName().toUpperCase();
    if (matches(typeName, "JSON")) {
      return (data) -> convertJson(column, fieldDefn, data);
    }
    if (matches(typeName, "GEOMETRY")
      || matches(typeName, "LINESTRING")
      || matches(typeName, "POLYGON")
      || matches(typeName, "MULTIPOINT")
      || matches(typeName, "MULTILINESTRING")
      || matches(typeName, "MULTIPOLYGON")
      || isGeometryCollection(typeName)) {
      return (data -> convertGeometry(column, fieldDefn, data));
    }
    if (matches(typeName, "POINT")) {
      // backwards compatibility
      return (data -> convertPoint(column, fieldDefn, data));
    }
    if (matches(typeName, "YEAR")) {
      return (data) -> convertYearToInt(column, fieldDefn, data);
    }
    if (matches(typeName, "ENUM")) {
      // Build up the character array based upon the column's type ...
      List<String> options = extractEnumAndSetOptions(column);
      return (data) -> convertEnumToString(options, column, fieldDefn, data);
    }
    if (matches(typeName, "SET")) {
      // Build up the character array based upon the column's type ...
      List<String> options = extractEnumAndSetOptions(column);
      return (data) -> convertSetToString(options, column, fieldDefn, data);
    }
    if (matches(typeName, "TINYINT UNSIGNED") || matches(typeName, "TINYINT UNSIGNED ZEROFILL")
      || matches(typeName, "INT1 UNSIGNED") || matches(typeName, "INT1 UNSIGNED ZEROFILL")) {
      // Convert TINYINT UNSIGNED internally from SIGNED to UNSIGNED based on the boundary settings
      return (data) -> convertUnsignedTinyint(column, fieldDefn, data);
    }
    if (matches(typeName, "SMALLINT UNSIGNED") || matches(typeName, "SMALLINT UNSIGNED ZEROFILL")
      || matches(typeName, "INT2 UNSIGNED") || matches(typeName, "INT2 UNSIGNED ZEROFILL")) {
      // Convert SMALLINT UNSIGNED internally from SIGNED to UNSIGNED based on the boundary settings
      return (data) -> convertUnsignedSmallint(column, fieldDefn, data);
    }
    if (matches(typeName, "MEDIUMINT UNSIGNED") || matches(typeName, "MEDIUMINT UNSIGNED ZEROFILL")
      || matches(typeName, "INT3 UNSIGNED") || matches(typeName, "INT3 UNSIGNED ZEROFILL")
      || matches(typeName, "MIDDLEINT UNSIGNED") || matches(typeName, "MIDDLEINT UNSIGNED ZEROFILL")) {
      // Convert MEDIUMINT UNSIGNED internally from SIGNED to UNSIGNED based on the boundary settings
      return (data) -> convertUnsignedMediumint(column, fieldDefn, data);
    }
    if (matches(typeName, "INT UNSIGNED") || matches(typeName, "INT UNSIGNED ZEROFILL")
      || matches(typeName, "INT4 UNSIGNED") || matches(typeName, "INT4 UNSIGNED ZEROFILL")) {
      // Convert INT UNSIGNED internally from SIGNED to UNSIGNED based on the boundary settings
      return (data) -> convertUnsignedInt(column, fieldDefn, data);
    }
    if (matches(typeName, "BIGINT UNSIGNED") || matches(typeName, "BIGINT UNSIGNED ZEROFILL")
      || matches(typeName, "INT8 UNSIGNED") || matches(typeName, "INT8 UNSIGNED ZEROFILL")) {
      switch (super.bigIntUnsignedMode) {
        case LONG:
          return (data) -> convertBigInt(column, fieldDefn, data);
        case PRECISE:
          // Convert BIGINT UNSIGNED internally from SIGNED to UNSIGNED based on the boundary settings
          return (data) -> convertUnsignedBigint(column, fieldDefn, data);
      }
    }

    // We have to convert bytes encoded in the column's character set ...
    switch (column.jdbcType()) {
      case Types.CHAR: // variable-length
      case Types.VARCHAR: // variable-length
      case Types.LONGVARCHAR: // variable-length
      case Types.CLOB: // variable-length
      case Types.NCHAR: // fixed-length
      case Types.NVARCHAR: // fixed-length
      case Types.LONGNVARCHAR: // fixed-length
      case Types.NCLOB: // fixed-length
      case Types.DATALINK:
      case Types.SQLXML:
        Charset charset = charsetFor(column);
        if (charset != null) {
          logger.debug("Using {} charset by default for column: {}", charset, column);
          return (data) -> convertString(column, fieldDefn, charset, data);
        }
        logger.warn("Using UTF-8 charset by default for column without charset: {}", column);
        return (data) -> convertString(column, fieldDefn, StandardCharsets.UTF_8, data);
      case Types.TIME:
        if (adaptiveTimeMicrosecondsPrecisionMode) {
          return data -> convertDurationToMicroseconds(column, fieldDefn, data);
        }
        return ((ValueConverter) (data -> convertTimestampToLocalDateTime(column, fieldDefn, data)))
          .and(super.converter(column, fieldDefn));
      case Types.TIMESTAMP:
        return ((ValueConverter) (data -> convertTimestampToLocalDateTime(column, fieldDefn, data)))
          .and(super.converter(column, fieldDefn));
      default:
        break;
    }

    // Otherwise, let the base class handle it ...
    return super.converter(column, fieldDefn);
  }

  /**
   * Return the {@link Charset} instance with the MySQL-specific character set name used by the given column.
   *
   * @param column the column in which the character set is used; never null
   * @return the Java {@link Charset}, or null if there is no mapping
   */
  protected Charset charsetFor(Column column) {
    String mySqlCharsetName = column.charsetName();
    if (mySqlCharsetName == null) {
      logger.warn("Column is missing a character set: {}", column);
      return null;
    }

    // This is a change from the original file, we are using the jdbcClassLoader to invoke the static
    // getJavaEncodingForMysqlCharset or getStaticJavaEncodingForMysqlCharset (since mysql connector 8.0.26) method
    // Following line is from original file. Instead of getting encoding from CharsetMapping we load the class
    // using jdbcClassLoader.
    // String encoding = CharsetMapping.getJavaEncodingForMysqlCharset(mySqlCharsetName);
    String encoding;
    Class<?> charsetMappingClass = null;
    try {
      charsetMappingClass = jdbcClassLoader.loadClass(CLASS_CHARSET_MAPPING);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(String.format("Failed to load class %s: %s", CLASS_CHARSET_MAPPING,
                                                 e.getMessage()), e);
    }
    Method getCharsetMethod = null;
    try {
      getCharsetMethod = charsetMappingClass.getMethod(METHOD_GET_JAVA_ENCODING, String.class);
    } catch (NoSuchMethodException e) {
      try {
        getCharsetMethod = charsetMappingClass.getDeclaredMethod(METHOD_GET_STATIC_JAVA_ENCODING, String.class);
        getCharsetMethod.setAccessible(true);
      } catch (NoSuchMethodException noSuchMethodException) {
        throw new RuntimeException(String.format("Failed to find method %s or %s for class %s",
                                                 METHOD_GET_JAVA_ENCODING, METHOD_GET_STATIC_JAVA_ENCODING,
                                                 CLASS_CHARSET_MAPPING));
      }
    }
    try {
      encoding = (String) getCharsetMethod.invoke(null, mySqlCharsetName);
    } catch (Exception e) {
      throw new RuntimeException(String.format("Error while using class loader to invoke '%s.%s' static method",
                                               CLASS_CHARSET_MAPPING, getCharsetMethod.getName()), e);
    }
    // end change from original file

    if (encoding == null) {
      logger.warn("Column uses MySQL character set '{}', which has no mapping to a Java character set",
                  mySqlCharsetName);
    } else {
      try {
        return Charset.forName(encoding);
      } catch (IllegalCharsetNameException e) {
        logger.error("Unable to load Java charset '{}' for column with MySQL character set '{}'", encoding,
                     mySqlCharsetName);
      }
    }
    return null;
  }

  /**
   * Convert the {@link String} {@code byte[]} value to a string value used in a {@link SourceRecord}.
   *
   * @param column the column in which the value appears
   * @param fieldDefn the field definition for the {@link SourceRecord}'s {@link Schema}; never null
   * @param data the data; may be null
   * @return the converted value, or null if the conversion could not be made and the column allows nulls
   * @throws IllegalArgumentException if the value could not be converted but the column does not allow nulls
   */
  protected Object convertJson(Column column, Field fieldDefn, Object data) {
    return convertValue(column, fieldDefn, data, "{}", (r) -> {
      if (data instanceof byte[]) {
        // The BinlogReader sees these JSON values as binary encoded, so we use the binlog client library's utility
        // to parse MySQL's internal binary representation into a JSON string, using the standard formatter.

        if (((byte[]) data).length == 0) {
          r.deliver(column.isOptional() ? null : "{}");
        } else {
          try {
            r.deliver(JsonBinary.parseAsString((byte[]) data));
          } catch (IOException e) {
            parsingErrorHandler.error("Failed to parse and read a JSON value on '" + column + "' value " +
                                        Arrays.toString((byte[]) data), e);
            r.deliver(column.isOptional() ? null : "{}");
          }
        }
      } else if (data instanceof String) {
        // The SnapshotReader sees JSON values as UTF-8 encoded strings.
        r.deliver(data);
      }
    });
  }

  /**
   * Convert the {@link String} or {@code byte[]} value to a string value used in a {@link SourceRecord}.
   *
   * @param column the column in which the value appears
   * @param fieldDefn the field definition for the {@link SourceRecord}'s {@link Schema}; never null
   * @param columnCharset the Java character set in which column byte[] values are encoded; may not be null
   * @param data the data; may be null
   * @return the converted value, or null if the conversion could not be made and the column allows nulls
   * @throws IllegalArgumentException if the value could not be converted but the column does not allow nulls
   */
  protected Object convertString(Column column, Field fieldDefn, Charset columnCharset, Object data) {
    return convertValue(column, fieldDefn, data, "", (r) -> {
      if (data instanceof byte[]) {
        // Decode the binary representation using the given character encoding ...
        r.deliver(new String((byte[]) data, columnCharset));
      } else if (data instanceof String) {
        r.deliver(data);
      }
    });
  }

  /**
   * Converts a value object for a MySQL {@code YEAR}, which appear in the binlog as an integer though returns from
   * the MySQL JDBC driver as either a short or a {@link java.sql.Date}.
   *
   * @param column the column definition describing the {@code data} value; never null
   * @param fieldDefn the field definition; never null
   * @param data the data object to be converted into a year literal integer value; never null
   * @return the converted value, or null if the conversion could not be made and the column allows nulls
   * @throws IllegalArgumentException if the value could not be converted but the column does not allow nulls
   */
  @SuppressWarnings("deprecation")
  protected Object convertYearToInt(Column column, Field fieldDefn, Object data) {
    return convertValue(column, fieldDefn, data, 0, (r) -> {
      Object mutData = data;
      if (data instanceof java.time.Year) {
        // The MySQL binlog always returns a Year object ...
        r.deliver(adjustTemporal(java.time.Year.of(((java.time.Year) data).getValue())).get(ChronoField.YEAR));
      } else if (data instanceof java.sql.Date) {
        // MySQL JDBC driver sometimes returns a Java SQL Date object ...
        // year from java.sql.Date is defined as number of years since 1900
        r.deliver(((java.sql.Date) data).getYear() + 1900);
      } else if (data instanceof String) {
        mutData = Integer.valueOf((String) data);
      }
      if (mutData instanceof Number) {
        // MySQL JDBC driver sometimes returns a short ...
        r.deliver(adjustTemporal(java.time.Year.of(((Number) mutData).intValue())).get(ChronoField.YEAR));
      }
    });
  }

  /**
   * Converts a value object for a MySQL {@code ENUM}, which is represented in the binlog events as an integer value
   * containing the index of the enum option. The MySQL JDBC driver returns a string containing the option,
   * so this method calculates the same.
   *
   * @param options the characters that appear in the same order as defined in the column; may not be null
   * @param column the column definition describing the {@code data} value; never null
   * @param fieldDefn the field definition; never null
   * @param data the data object to be converted into an {@code ENUM} literal String value
   * @return the converted value, or null if the conversion could not be made and the column allows nulls
   * @throws IllegalArgumentException if the value could not be converted but the column does not allow nulls
   */
  protected Object convertEnumToString(List<String> options, Column column, Field fieldDefn, Object data) {
    return convertValue(column, fieldDefn, data, "", (r) -> {
      if (data instanceof String) {
        // JDBC should return strings ...
        r.deliver(data);
      } else if (data instanceof Integer) {
        if (options != null) {
          // The binlog will contain an int with the 1-based index of the option in the enum value ...
          int value = ((Integer) data).intValue();
          if (value == 0) {
            // an invalid value was specified, which corresponds to the empty string '' and an index of 0
            r.deliver("");
          }
          int index = value - 1; // 'options' is 0-based
          if (index < options.size() && index >= 0) {
            r.deliver(options.get(index));
          }
        } else {
          r.deliver(null);
        }
      }
    });
  }

  /**
   * Converts a value object for a MySQL {@code SET}, which is represented in the binlog events contain a long number
   * in which every bit corresponds to a different option. The MySQL JDBC driver returns a string containing the
   * comma-separated options, so this method calculates the same.
   *
   * @param options the characters that appear in the same order as defined in the column; may not be null
   * @param column the column definition describing the {@code data} value; never null
   * @param fieldDefn the field definition; never null
   * @param data the data object to be converted into an {@code SET} literal String value; never null
   * @return the converted value, or null if the conversion could not be made and the column allows nulls
   * @throws IllegalArgumentException if the value could not be converted but the column does not allow nulls
   */
  protected Object convertSetToString(List<String> options, Column column, Field fieldDefn, Object data) {
    return convertValue(column, fieldDefn, data, "", (r) -> {
      if (data instanceof String) {
        // JDBC should return strings ...
        r.deliver(data);
      } else if (data instanceof Long) {
        // The binlog will contain a long with the indexes of the options in the set value ...
        long indexes = ((Long) data).longValue();
        r.deliver(convertSetValue(column, indexes, options));
      }
    });
  }

  /**
   * Determine if the uppercase form of a column's type exactly matches or begins with the specified prefix.
   * Note that this logic works when the column's {@link Column#typeName() type} contains the type name followed by
   * parentheses.
   *
   * @param upperCaseTypeName the upper case form of the column's {@link Column#typeName() type name}
   * @param upperCaseMatch the upper case form of the expected type or prefix of the type; may not be null
   * @return {@code true} if the type matches the specified type, or {@code false} otherwise
   */
  protected boolean matches(String upperCaseTypeName, String upperCaseMatch) {
    if (upperCaseTypeName == null) {
      return false;
    }
    return upperCaseMatch.equals(upperCaseTypeName) || upperCaseTypeName.startsWith(upperCaseMatch + "(");
  }

  /**
   * Determine if the uppercase form of a column's type is geometry collection independent of JDBC driver or server
   * version.
   *
   * @param upperCaseTypeName the upper case form of the column's {@link Column#typeName() type name}
   * @return {@code true} if the type is geometry collection
   */
  protected boolean isGeometryCollection(String upperCaseTypeName) {
    if (upperCaseTypeName == null) {
      return false;
    }

    return upperCaseTypeName.equals("GEOMETRYCOLLECTION") || upperCaseTypeName.equals("GEOMCOLLECTION")
      || upperCaseTypeName.endsWith(".GEOMCOLLECTION");
  }

  protected List<String> extractEnumAndSetOptions(Column column) {
    return MySqlAntlrDdlParser.extractEnumAndSetOptions(column.enumValues());
  }

  protected String extractEnumAndSetOptionsAsString(Column column) {
    return Strings.join(",", extractEnumAndSetOptions(column));
  }

  protected String convertSetValue(Column column, long indexes, List<String> options) {
    StringBuilder sb = new StringBuilder();
    int index = 0;
    boolean first = true;
    int optionLen = options.size();
    while (indexes != 0L) {
      if (indexes % 2L != 0) {
        if (first) {
          first = false;
        } else {
          sb.append(',');
        }
        if (index < optionLen) {
          sb.append(options.get(index));
        } else {
          logger.warn("Found unexpected index '{}' on column {}", index, column);
        }
      }
      ++index;
      indexes = indexes >>> 1;
    }
    return sb.toString();

  }

  /**
   * Convert the a value representing a POINT {@code byte[]} value to a Point value used in a {@link SourceRecord}.
   *
   * @param column the column in which the value appears
   * @param fieldDefn the field definition for the {@link SourceRecord}'s {@link Schema}; never null
   * @param data the data; may be null
   * @return the converted value, or null if the conversion could not be made and the column allows nulls
   * @throws IllegalArgumentException if the value could not be converted but the column does not allow nulls
   */
  protected Object convertPoint(Column column, Field fieldDefn, Object data) {
    final MySqlGeometry empty = MySqlGeometry.createEmpty();
    return convertValue(column, fieldDefn, data,
                        io.debezium.data.geometry.Geometry.createValue(fieldDefn.schema(), empty.getWkb(),
                                                                       empty.getSrid()), (r) -> {
      if (data instanceof byte[]) {
        // The binlog utility sends a byte array for any Geometry type, we will use our own binaryParse to parse the
        // byte to WKB, hence to the suitable class
        MySqlGeometry mySqlGeometry = MySqlGeometry.fromBytes((byte[]) data);
        if (mySqlGeometry.isPoint()) {
          r.deliver(io.debezium.data.geometry.Point.createValue(fieldDefn.schema(), mySqlGeometry.getWkb(),
                                                                mySqlGeometry.getSrid()));
        } else {
          throw new ConnectException("Failed to parse and read a value of type POINT on " + column);
        }
      }
    });
  }

  /**
   * Convert the a value representing a GEOMETRY {@code byte[]} value to a Geometry value used in a
   * {@link SourceRecord}.
   *
   * @param column the column in which the value appears
   * @param fieldDefn the field definition for the {@link SourceRecord}'s {@link Schema}; never null
   * @param data the data; may be null
   * @return the converted value, or null if the conversion could not be made and the column allows nulls
   * @throws IllegalArgumentException if the value could not be converted but the column does not allow nulls
   */
  protected Object convertGeometry(Column column, Field fieldDefn, Object data) {
    final MySqlGeometry empty = MySqlGeometry.createEmpty();
    return convertValue(column, fieldDefn, data,
                        io.debezium.data.geometry.Geometry.createValue(fieldDefn.schema(), empty.getWkb(),
                                                                       empty.getSrid()), (r) -> {
      if (data instanceof byte[]) {
        // The binlog utility sends a byte array for any Geometry type, we will use our own binaryParse to parse the
        // byte to WKB, hence to the suitable class
        if (data instanceof byte[]) {
          // The binlog utility sends a byte array for any Geometry type, we will use our own binaryParse to parse the
          // byte to WKB, hence to the suitable class
          MySqlGeometry mySqlGeometry = MySqlGeometry.fromBytes((byte[]) data);
          r.deliver(io.debezium.data.geometry.Geometry.createValue(fieldDefn.schema(), mySqlGeometry.getWkb(),
                                                                   mySqlGeometry.getSrid()));
        }
      }
    });
  }

  @Override
  protected ByteBuffer toByteBuffer(Column column, byte[] data) {
    // DBZ-254 right-pad fixed-length binary column values with 0x00 (zero byte)
    if (column.jdbcType() == Types.BINARY && data.length < column.length()) {
      data = Arrays.copyOf(data, column.length());
    }

    return super.toByteBuffer(column, data);
  }

  /**
   * Convert the a value representing a Unsigned TINYINT value to the correct Unsigned TINYINT representation.
   *
   * @param column the column in which the value appears
   * @param fieldDefn the field definition for the {@link SourceRecord}'s {@link Schema}; never null
   * @param data the data; may be null
   *
   * @return the converted value, or null if the conversion could not be made and the column allows nulls
   *
   * @throws IllegalArgumentException if the value could not be converted but the column does not allow nulls
   */
  protected Object convertUnsignedTinyint(Column column, Field fieldDefn, Object data) {
    return convertValue(column, fieldDefn, data, (short) 0, (r) -> {
      if (data instanceof Short) {
        r.deliver(MySqlUnsignedIntegerConverter.convertUnsignedTinyint((short) data));
      } else if (data instanceof Number) {
        r.deliver(MySqlUnsignedIntegerConverter.convertUnsignedTinyint(((Number) data).shortValue()));
      } else {
        // We continue with the original converting method (smallint) since we have an unsigned Tinyint
        r.deliver(convertSmallInt(column, fieldDefn, data));
      }
    });
  }

  /**
   * Convert the a value representing a Unsigned SMALLINT value to the correct Unsigned SMALLINT representation.
   *
   * @param column the column in which the value appears
   * @param fieldDefn the field definition for the {@link SourceRecord}'s {@link Schema}; never null
   * @param data the data; may be null
   *
   * @return the converted value, or null if the conversion could not be made and the column allows nulls
   *
   * @throws IllegalArgumentException if the value could not be converted but the column does not allow nulls
   */
  protected Object convertUnsignedSmallint(Column column, Field fieldDefn, Object data) {
    return convertValue(column, fieldDefn, data, 0, (r) -> {
      if (data instanceof Integer) {
        r.deliver(MySqlUnsignedIntegerConverter.convertUnsignedSmallint((int) data));
      } else if (data instanceof Number) {
        r.deliver(MySqlUnsignedIntegerConverter.convertUnsignedSmallint(((Number) data).intValue()));
      } else {
        // We continue with the original converting method (integer) since we have an unsigned Smallint
        r.deliver(convertInteger(column, fieldDefn, data));
      }
    });
  }

  /**
   * Convert the a value representing a Unsigned MEDIUMINT value to the correct Unsigned SMALLINT representation.
   *
   * @param column the column in which the value appears
   * @param fieldDefn the field definition for the {@link SourceRecord}'s {@link Schema}; never null
   * @param data the data; may be null
   *
   * @return the converted value, or null if the conversion could not be made and the column allows nulls
   *
   * @throws IllegalArgumentException if the value could not be converted but the column does not allow nulls
   */
  protected Object convertUnsignedMediumint(Column column, Field fieldDefn, Object data) {
    return convertValue(column, fieldDefn, data, 0, (r) -> {
      if (data instanceof Integer) {
        r.deliver(MySqlUnsignedIntegerConverter.convertUnsignedMediumint((int) data));
      } else if (data instanceof Number) {
        r.deliver(MySqlUnsignedIntegerConverter.convertUnsignedMediumint(((Number) data).intValue()));
      } else {
        // We continue with the original converting method (integer) since we have an unsigned Medium
        r.deliver(convertInteger(column, fieldDefn, data));
      }
    });
  }

  /**
   * Convert the a value representing a Unsigned INT value to the correct Unsigned INT representation.
   *
   * @param column the column in which the value appears
   * @param fieldDefn the field definition for the {@link SourceRecord}'s {@link Schema}; never null
   * @param data the data; may be null
   *
   * @return the converted value, or null if the conversion could not be made and the column allows nulls
   *
   * @throws IllegalArgumentException if the value could not be converted but the column does not allow nulls
   */
  protected Object convertUnsignedInt(Column column, Field fieldDefn, Object data) {
    return convertValue(column, fieldDefn, data, 0L, (r) -> {
      if (data instanceof Long) {
        r.deliver(MySqlUnsignedIntegerConverter.convertUnsignedInteger((long) data));
      } else if (data instanceof Number) {
        r.deliver(MySqlUnsignedIntegerConverter.convertUnsignedInteger(((Number) data).longValue()));
      } else {
        // We continue with the original converting method (bigint) since we have an unsigned Integer
        r.deliver(convertBigInt(column, fieldDefn, data));
      }
    });
  }

  /**
   * Convert the a value representing a Unsigned BIGINT value to the correct Unsigned INT representation.
   *
   * @param column the column in which the value appears
   * @param fieldDefn the field definition for the {@link SourceRecord}'s {@link Schema}; never null
   * @param data the data; may be null
   *
   * @return the converted value, or null if the conversion could not be made and the column allows nulls
   *
   * @throws IllegalArgumentException if the value could not be converted but the column does not allow nulls
   */
  protected Object convertUnsignedBigint(Column column, Field fieldDefn, Object data) {
    return convertValue(column, fieldDefn, data, 0L, (r) -> {
      if (data instanceof BigDecimal) {
        r.deliver(MySqlUnsignedIntegerConverter.convertUnsignedBigint((BigDecimal) data));
      } else if (data instanceof Number) {
        r.deliver(MySqlUnsignedIntegerConverter.convertUnsignedBigint(new BigDecimal(((Number) data).toString())));
      } else if (data instanceof String) {
        r.deliver(MySqlUnsignedIntegerConverter.convertUnsignedBigint(new BigDecimal((String) data)));
      } else {
        r.deliver(convertNumeric(column, fieldDefn, data));
      }
    });
  }

  /**
   * Converts a value object for an expected type of {@link java.time.Duration} to {@link Long} values that represents
   * the time in microseconds.
   *

   * Per the JDBC specification, databases should return {@link java.sql.Time} instances, but that's not working
   * because it can only handle Daytime 00:00:00-23:59:59. We use {@link java.time.Duration} instead that can handle
   * the range of -838:59:59.000000 to 838:59:59.000000 of a MySQL TIME type and transfer data as signed INT64 which
   * reflects the DB value converted to microseconds.
   *
   * @param column the column definition describing the {@code data} value; never null
   * @param fieldDefn the field definition; never null
   * @param data the data object to be converted into a {@link java.time.Duration} type; never null
   * @return the converted value, or null if the conversion could not be made and the column allows nulls
   * @throws IllegalArgumentException if the value could not be converted but the column does not allow nulls
   */
  protected Object convertDurationToMicroseconds(Column column, Field fieldDefn, Object data) {
    return convertValue(column, fieldDefn, data, 0L, (r) -> {
      try {
        if (data instanceof Duration) {
          r.deliver(((Duration) data).toNanos() / 1_000);
        }
      } catch (IllegalArgumentException e) {
      }
    });
  }

  protected Object convertTimestampToLocalDateTime(Column column, Field fieldDefn, Object data) {
    if (data == null && !fieldDefn.schema().isOptional()) {
      return null;
    }
    if (!(data instanceof Timestamp)) {
      return data;
    }

    return ((Timestamp) data).toLocalDateTime();
  }

  public static Duration stringToDuration(String timeString) {
    Matcher matcher = TIME_FIELD_PATTERN.matcher(timeString);
    if (!matcher.matches()) {
      throw new RuntimeException("Unexpected format for TIME column: " + timeString);
    }

    long hours = Long.parseLong(matcher.group(1));
    long minutes = Long.parseLong(matcher.group(2));
    long seconds = Long.parseLong(matcher.group(3));
    long nanoSeconds = 0;
    String microSecondsString = matcher.group(5);
    if (microSecondsString != null) {
      nanoSeconds = Long.parseLong(Strings.justifyLeft(microSecondsString, 9, '0'));
    }

    if (hours >= 0) {
      return Duration.ofHours(hours)
        .plusMinutes(minutes)
        .plusSeconds(seconds)
        .plusNanos(nanoSeconds);
    } else {
      return Duration.ofHours(hours)
        .minusMinutes(minutes)
        .minusSeconds(seconds)
        .minusNanos(nanoSeconds);
    }
  }

  public static LocalDate stringToLocalDate(String dateString, Column column, Table table) {
    final Matcher matcher = DATE_FIELD_PATTERN.matcher(dateString);
    if (!matcher.matches()) {
      throw new RuntimeException("Unexpected format for DATE column: " + dateString);
    }

    final int year = Integer.parseInt(matcher.group(1));
    final int month = Integer.parseInt(matcher.group(2));
    final int day = Integer.parseInt(matcher.group(3));

    if (year == 0 || month == 0 || day == 0) {
      LOGGER.warn("Invalid value '{}' stored in column '{}' of table '{}' converted to empty value", dateString,
                  column.name(), table.id());
      return null;
    }
    return LocalDate.of(year, month, day);
  }

  public static boolean containsZeroValuesInDatePart(String timestampString, Column column, Table table) {
    final Matcher matcher = TIMESTAMP_FIELD_PATTERN.matcher(timestampString);
    if (!matcher.matches()) {
      throw new RuntimeException("Unexpected format for DATE column: " + timestampString);
    }

    final int year = Integer.parseInt(matcher.group(1));
    final int month = Integer.parseInt(matcher.group(2));
    final int day = Integer.parseInt(matcher.group(3));

    if (year == 0 || month == 0 || day == 0) {
      LOGGER.warn("Invalid value '{}' stored in column '{}' of table '{}' converted to empty value", timestampString,
                  column.name(), table.id());
      return true;
    }
    return false;
  }
}


text:
package com.forerunnergames.tools.common.assets;

import com.forerunnergames.tools.common.id.Id;

public interface Asset extends Comparable <Asset>
{
  @Override
  int compareTo (final Asset asset);

  @Override
  int hashCode ();

  @Override
  boolean equals (final Object obj);

  @Override
  String toString ();

  String getName ();

  Id getId ();

  boolean doesNotHave (final Id id);

  boolean has (final String name);

  boolean hasName (final String name);

  boolean has (final Id id);

  boolean is (final Asset asset);

  boolean isNot (final Asset asset);
}


text:
from __future__ import unicode_literals

import collections
import importlib
import itertools
import six

# --------------------------------------------------
# Misc
# --------------------------------------------------

def _check_package(package_name):
    try:
        return importlib.import_module(package_name)
    except ImportError:
        msg = '{pkg} is required to use this functionality'
        raise ImportError(msg.format(pkg=package_name))

# --------------------------------------------------
# Validators
# --------------------------------------------------

def notimplemented(x):
    if x is not None:
        raise NotImplementedError
    return x

def validate_numeric(x, key):
    """ validate whether x is int, long or float"""
    if not is_numeric(x):
        raise ValueError('{key} must be numeric: {x}'.format(key=key, x=x))
    return x

def validate_numeric_or_none(x, key):
    """ validate whether x is int, long, float or None"""
    if x is None:
        return x
    return validate_numeric(x, key=key)

def validate_longitude(x, key):
    """ validate whether x is numeric, and between -180 and 180 """
    if not is_longitude(x):
        raise ValueError('{key} must be longitude, between -180 to 180: {x}'.format(key=key, x=x))
    return x

def validate_latitude(x, key):
    """ validate whether x is numeric, and between -90 and 90 """
    if not is_latitude(x):
        raise ValueError('{key} must be latitude, between -90 to 90: {x}'.format(key=key, x=x))
    return x

def validate_listlike(x, key):
    """ validate whether x is list-likes """
    if not is_listlike(x):
        raise ValueError('{key} must be list-likes: {x}'.format(key=key, x=x))
    if hasattr(x, '__array__'):
        # array interface, 0 dimensional array raises ValueError in
        # previous block
        x = x.__array__()
        # convert to python list as traitlets doesn't handle numpy scalar
        x = x.tolist()
    return x

def validate_listlike_even(x, key):
    """ validate whether x is list-likes which length is even-number """
    x = validate_listlike(x, key)
    if len(x) % 2 != 0:
        raise ValueError('{key} length must be an even number: {x}'.format(key=key, x=x))
    return x

def validate_listlike_lonlat(x, key):
    """ validate whether x is list-likes consists from lon, lat pairs """
    x = validate_listlike_even(x, key)
    try:
        all(validate_longitude(e, key=key) for e in x[::2])
        all(validate_latitude(e, key=key) for e in x[1::2])
        # validation will raise ValueError immediately
    except ValueError:
        msg = '{key} must be a list consists from longitude and latitude: {x}'
        raise ValueError(msg.format(key=key, x=x))

    return x

# --------------------------------------------------
# Check Functions
# --------------------------------------------------

# There is not is_bool and is_str, because these are single expression

def is_numeric(x):
    return isinstance(x, (six.integer_types, float))

def is_longitude(x):
    if is_numeric(x):
        return -180 <= x <= 180
    return False

def is_latitude(x):
    if is_numeric(x):
        return -90 <= x <= 90
    return False

try:
    import numpy as np
    listlike_types = (list, tuple, np.ndarray)
except ImportError:
    listlike_types = (list, tuple)

def is_listlike(x):
    """ whether the input can be regarded as list """
    if hasattr(x, '__array__'):
        # array interface
        x = x.__array__()
        if x.ndim == 0:
            # 0 dimensional array
            return False
    return isinstance(x, listlike_types)

def is_listlike_2elem(x):
    if is_listlike(x):
        if all(is_listlike(e) and len(e) == 2 for e in x):
            return True
    return False

def is_listlike_3elem(x):
    if is_listlike(x):
        if all(is_listlike(e) and len(e) == 2 for e in x):
            return True
    return False

# --------------------------------------------------
# Converter Functions
# --------------------------------------------------

def to_jsscalar(x):
    """ convert x to JavaScript representation """

    from cesiumpy.base import _CesiumObject, _CesiumEnum
    if isinstance(x, (_CesiumObject, _CesiumEnum)):
        return x.script

    if isinstance(x, bool):
        # convert to JavaScript repr
        x = 'true' if x else 'false'
    elif isinstance(x, six.string_types):
        x = '"{0}"'.format(x)
    elif isinstance(x, dict):
        x = ''.join(to_jsobject(x))
    elif isinstance(x, list):
        x = [str(to_jsscalar(e)) for e in x]
        x = '[{0}]'.format(', '.join(x))
    return x

def to_jsobject(x):
    """ convert x to JavaScript Object """

    results = ['{']

    # filter None
    dic = collections.OrderedDict()
    # do not use dict comprehension to keep property order
    for k, v in six.iteritems(x):
        if v is not None:
            dic[k] = v
    x = dic
    if len(x) == 0:
        return ['']

    for key, val in six.iteritems(x):
        val = to_jsscalar(val)
        results.append('{0} : {1}, '.format(key, val))
    results[-1] = results[-1][:-2]     # remove final comma
    results.append('}')
    return results

def _flatten_list_of_listlike(x):
    return list(itertools.chain(*x))


text:
class AddDesignationIdToProtectedArea < ActiveRecord::Migration
  def change
    add_column :protected_areas, :designation_id, :integer
  end
end