text:
var url = ajaxurl;
var controller = "vsscan";
var option = "com_ose_firewall";

jQuery(document).ready(function($){
	//get object with colros from plugin and store it.
	var objColors = $('body').data('appStart').getColors();
	var colours = {
		white: objColors.white,
		dark: objColors.dark,
		red : objColors.red,
		blue: objColors.blue,
		green : objColors.green,
		yellow: objColors.yellow,
		brown: objColors.brown,
		orange : objColors.orange,
		purple : objColors.purple,
		pink : objColors.pink,
		lime : objColors.lime,
		magenta: objColors.magenta,
		teal: objColors.teal,
		textcolor: '#5a5e63',
		gray: objColors.gray
	}
	//generate random number for charts
	randNum = function(){
		//return Math.floor(Math.random()*101);
		return (Math.floor( Math.random()* (1+40-20) ) ) + 20;
	}
	initPlotChart($, [0,0], true);
	initPlotChart($, [0,0], false);
	initPieChartPage($, 20,100,1500, colours);
	$('#vsscan').on('click', function() {
		showLoading ();
		scanAntivirus (-2, 'vsscan', [], []);
	});
	$('#vsstop').on('click', function() {
		showLoading ();
		location.reload();
	});
	$('#vscont').on('click', function() {
		runAllScanAntivirus ('vsscan', cpuData=[], memData=[])
	});
});

var initPlotChart = function ($, data, cpu) {
	if (cpu =='')
	{
		cpu = false;
	}
	//define chart colours
	var chartColours = ['#3fc3a8', '#ed7a53', '#9FC569', '#bbdce3', '#9a3b1b', '#5a8022', '#2c7282'];
	var options = {
			grid: {
				show: true,
			    aboveData: true,
			    color:'#3f3f3f',
			    labelMargin: 15,
			    axisMargin: 0,
			    borderWidth: 0,
			    borderColor:null,
			    minBorderMargin: 0,
			    clickable: true,
			    hoverable: true,
			    autoHighlight: true,
			    mouseActiveRadius: 20
			},
	        series: {
	        	grow: {active:false},
	            lines: {
            		show: true,
            		fill: true,
            		lineWidth: 2,
            		steps: false
	            	},
	            points: {
	            	show:true,
	            	radius: 4,
	            	symbol: "circle",
	            	fill: true,
	            	borderColor: "#fff"
	            }
	        },
	        legend: { position: "se" },
	        colors: chartColours,
	        shadowSize:1,
	        tooltip: true, //activate tooltip
			tooltipOpts: {
				content: "%s : %y.0",
				shifts: {
					x: -30,
					y: -50
				}
			}
	};
	if (cpu == true)
	{
		var plot1 = $.plot($("#line-chart-cpu"),
			    [{
			    		label: "CPU Load",
			    		data: data,
			    		lines: {fillColor: "#f2f7f9"},
			    		points: {fillColor: "#3fc3a8"}
			    }], options);
	}
	else
	{
		var plot2 = $.plot($("#line-chart-memory"),
			    [{
			    		label: "Memory Usage",
			    		data: data,
			    		lines: {fillColor: "#f2f7f9"},
			    		points: {fillColor: "#3fc3a8"}
			    }], options);
	}

}

var initPieChartPage = function($, lineWidth, size, animateTime, colours) {
	$(".easy-pie-chart").easyPieChart({
        barColor: colours.dark,
        borderColor: colours.dark,
        trackColor: colours.gray,
        scaleColor: false,
        lineCap: 'butt',
        lineWidth: lineWidth,
        size: size,
        animate: animateTime
    });
    $(".easy-pie-chart-red").easyPieChart({
        barColor: colours.red,
        borderColor: colours.red,
        trackColor: '#fbccbf',
        scaleColor: false,
        lineCap: 'butt',
        lineWidth: lineWidth,
        size: size,
        animate: animateTime
    });
    $(".easy-pie-chart-green").easyPieChart({
        barColor: colours.green,
        borderColor: colours.green,
        trackColor: '#b1f8b1',
        scaleColor: false,
        lineCap: 'butt',
        lineWidth: lineWidth,
        size: size,
        animate: animateTime
    });
    $(".easy-pie-chart-blue").easyPieChart({
        barColor: colours.blue,
        borderColor: colours.blue,
        trackColor: '#d2e4fb',
        scaleColor: false,
        lineCap: 'butt',
        lineWidth: lineWidth,
        size: size,
        animate: animateTime
    });
    $(".easy-pie-chart-teal").easyPieChart({
        barColor: colours.teal,
        borderColor: colours.teal,
        trackColor: '#c3e5e5',
        scaleColor: false,
        lineCap: 'butt',
        lineWidth: lineWidth,
        size: size,
        animate: animateTime
    });
    $(".easy-pie-chart-purple").easyPieChart({
        barColor: colours.purple,
        borderColor: colours.purple,
        trackColor: '#dec1f5',
        scaleColor: false,
        lineCap: 'butt',
        lineWidth: lineWidth,
        size: size,
        animate: animateTime
    });
    $(".easy-pie-chart-orange").easyPieChart({
        barColor: colours.orange,
        borderColor: colours.orange,
        trackColor: '#f9d7af',
        scaleColor: false,
        lineCap: 'butt',
        lineWidth: lineWidth,
        size: size,
        animate: animateTime
    });
    $(".easy-pie-chart-lime").easyPieChart({
        barColor: colours.lime,
        borderColor: colours.lime,
        trackColor: '#cfed93',
        scaleColor: false,
        lineCap: 'butt',
        lineWidth: lineWidth,
        size: size,
        animate: animateTime
    });
}

function scanAntivirus (step, action, cpuData, memData) {
	jQuery(document).ready(function($){
		$.ajax({
	        type: "POST",
	        url: url,
	        dataType: 'json',
		    data: {
		    		option : option,
		    		controller:controller,
		    		action:action,
		    		task:action,
		    		step : step,
		    		centnounce:$('#centnounce').val()
		    },
	        success: function(data)
	        {
	        	hideLoading ();
	        	cpuData.push([cpuData.length, data.cpuload]);
	        	memData.push([memData.length, data.memory]);
	        	initPlotChart($, cpuData, true);
	        	initPlotChart($, memData, false);
	        	$('#p4text').html(data.summary);
	        	$('#last_file').html(data.last_file);
	        	if (step == -2 && data.cont==true)
	        	{
	        		scanAntivirus (-1, action, cpuData, memData);
	        	}
	        	else
	        	{
	        		runAllScanAntivirus (action, cpuData, memData);
	        	}
	        }
	      });
	});
}

function runAllScanAntivirus (action, cpuData, memData) {
	var s1 = scanVirusInd (action, cpuData, memData, 1);
	var s2 = scanVirusInd (action, cpuData, memData, 2);
	var s3 = scanVirusInd (action, cpuData, memData, 3);
	var s4 = scanVirusInd (action, cpuData, memData, 4);
	var s5 = scanVirusInd (action, cpuData, memData, 5);
	var s6 = scanVirusInd (action, cpuData, memData, 6);
	var s7 = scanVirusInd (action, cpuData, memData, 7);
	var s8 = scanVirusInd (action, cpuData, memData, 8);
	jQuery(document).ready(function($){
		$.when(s1, s2, s3, s4, s5, s6, s7, s8).then(
			function ( v1, v2, v3, v4, v5, v6, v7, v8 ) {
		});
	});
}

function scanVirusInd (action, cpuData, memData, type) {
	jQuery(document).ready(function($){
		$.ajax({
	        type: "POST",
	        url: url,
	        dataType: 'json',
		    data: {
		    		option : option,
		    		controller:controller,
		    		action:action,
		    		task:action,
		    		step:0,
		    		type:type,
		    		centnounce:$('#centnounce').val()
		    },
	        success: function(data)
	        {
	        	hideLoading ();
	        	if (type==2)
	        	{
	        		cpuData.push([cpuData.length, data.cpuload]);
		        	memData.push([memData.length, data.memory]);
		        	initPlotChart($, cpuData, true);
		        	initPlotChart($, memData, false);
	        	}
	        	$('#p4text').html(data.summary);
	        	$('#last_file').html(data.last_file);
	        	$('#easy-pie-chart-'+type).data('easyPieChart').update(data.completed);
	        	$('#easy-pie-chart-'+type).attr("data-percent",data.completed);
	        	$('#pie-'+type).html(data.completed+'%');
	        	if (data.cont==true)
	        	{
	        		scanVirusInd (action, cpuData, memData, type);
	        	}
	        	else
	        	{
	        		return true;
	        	}
	        },
		    error: function(XMLHttpRequest, textStatus, errorThrown) {
		    	scanVirusInd (action, cpuData, memData, type);
		    }
	      });
	});
}


text:
using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(WebHost.Startup))]
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.xml", Watch = true)]
namespace WebHost
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

const fs        = require('fs-extra');
const path      = require('path');
const Promise   = require('bluebird');
const Task      = require('./task');
const appRoot   = path.resolve('./');
const appConfig = require(`${appRoot}/src/app-config`);

class Clean extends Task {
  constructor(args) {
    super(Object.assign({}, args));
  }

  run() {
    const remove = Promise.promisify(fs.remove);
    const dir = path.resolve('./');

    return Promise.all([
      remove(`${dir}/${appConfig.app.buildDir}`),
      remove(`${dir}/${appConfig.app.tempDir}`),
    ]);
  }
}

module.exports = {
  new : (args) => new Clean(args),
};


text:
package mock.condition.annotation;

import fr.sii.ogham.core.builder.condition.RequiredClass;
import fr.sii.ogham.core.builder.condition.RequiredClasses;

@RequiredClasses(value={"class.required.2", "class.required.3"}, classes=@RequiredClass(value="class.required.1", alternatives={"class.alt.1", "class.alt.2"}))
public class SeveralRequiredClassWithAlternatives {

}


text:
/* articles_controller.js
 *
 * This file will control all the operations
 * associated with articles
 *
*/
// Dependencies
var express = require('express');
var router  = express.Router();
var models  = require('../models');
var Article = models.Article;
var Note = models.Note;
var mongoose = require('mongoose');

// Main "/" Route. This will redirect the user to the rendered React application
router.get("/", function(req, res) {
	res.sendFile(__dirname + "/public/index.html");
});

// This route will receive GET requests and send the articles stored in the db.
// This route will be called at the moment the page gets rendered
router.get("/api/saved", function(req, res) {
	// Find all the records, sort them in descending order, then limit the records to 10
	Article.find({}).sort([
		["date", "descending"]
	]).limit(10)
    .populate('note')
	.exec(function(err, articles) {
		if (err) throw err;
		res.send(articles);
	});
});

// This route will receive POST requests and store articles into the db.
router.post("/api/saved", function(req, res) {
	var entry = new Article({title:req.body.title,url:req.body.url,date:Date.now()});
	// Now, save that article to the db
	entry.save(function(err, doc) {
		// Log any errors
		if (err)
        {
            console.log(err);
        }
        else
        {
            res.json(doc);
        }
	});
});

// This route will receive DELETE requests and remove articles from the db.
router.delete("/api/saved", function(req, res) {
	var articleId = mongoose.Types.ObjectId(req.body.articleId);
	Article.findOneAndRemove(
		{ "_id": articleId},
		function(err, doc) {
			// Log any errors
			if (err)
	        {
	            console.log(err);
	        }
	        else
	        {
	            res.json(doc);
	        }
		}
	);
});

module.exports = router;


text:
title: Flex Basis Property
localeTitle: Свойство Flex Basis
---
# Основы Flex

Свойство `flex-basis` определяет размер `flex-item` вдоль основной оси контейнера flex. Основная ось горизонтальна, если `flex-direction` установлено в `row` и оно будет вертикальным, если свойство `flex-direction` установлено в `column` .

## Синтаксис

```css
flex-basis: auto | content | <width> | <height>;
```

## flex-basis: авто

`flex-basis: auto` просматривает основной размер элемента и определяет размер. Например, в горизонтальном гибком контейнере `auto` будет искать `width` и `height` если ось контейнера будет вертикальной.

Если размер не указан, `auto` будет возвращаться к `content` .

## flex-basis: контент

`flex-basis: content` разрешает размер, основанный на содержимом элемента, если только `width` или `height` не установлены с помощью стандартного `box-sizing` .

В обоих случаях, когда `flex-basis` является либо `auto` либо `content` , если указан основной размер, этот размер будет иметь приоритет.

## Flex-основа:

Это точно так же, как указание `width` или `height` , но только более гибкое. `flex-basis: 20em;` задает начальный размер элемента `20em` . Его окончательный размер будет основываться на доступном пространстве, мультипликаторе `flex-grow` и `flex-shrink` multiple.

В спецификации предлагается использование `flex` стенографической собственности. Это помогает создать `flex-basis` наряду с `flex-grow` и `flex-shrink` свойствами.

## Примеры

Вот строки отдельных гибких контейнеров и отдельных гибких элементов, показывающие, как `flex-basis` влияет на `box-sizing` .

![эффект гибкой основы по горизонтальной оси](https://vijayabharathib.github.io/fcc_guide_images/css/properties/flex-basis-horizontal.png)

Когда направление `flex-direction` - `column` , тот же `flex-basis` будет управлять свойством `height` . Пример ниже,

![пример гибкой контрольной высоты в вертикальном контейнере](https://vijayabharathib.github.io/fcc_guide_images/css/properties/flex-basis-vertical.png)

#### Дополнительная информация:

Дополнительные ссылки на следующие страницы:

*   [Уровень](https://drafts.csswg.org/css-flexbox-1/) спецификации CSS [1](https://drafts.csswg.org/css-flexbox-1/)
*   Страница «Сеть разработчиков Mozilla» на [гибкой основе](https://developer.mozilla.org/en-US/docs/Web/CSS/flex-basis#content)


text:
const gulp    = require('gulp');
const path    = require('path');
const readdir = require('recursive-readdir');
const source  = require('vinyl-source-stream');

const tasks   = {
    replace:     require('gulp-replace-task'),
    runSequence: require('run-sequence'),
    notify:      require('gulp-notify'),
    concat:      require('gulp-concat'),
    browserify:  require('browserify'),
    babelify:    require('babelify'),
    glob:        require('glob')
};

const vendorCss = [
    './node_modules/ionicons/dist/css/ionicons.css'
];

/* Paths and file names. */
const indexHtmlTemplate          = 'source/templates/index.html';
const sourceCssFolder            = 'source/assets/css/';
const sourceImgFolder            = 'source/assets/img/';
const indexHtmlDestionationFile  = 'web/index.html';
const sourceWebAppFolder         = 'source/client/';
const imgDestinationFolder       = 'web/assets/img';
const vendorCssFile              = 'vendor.css';
const cssDestinationFolder       = 'web/css';
const webAppDestinationFileName  = 'app.js';
const webAppDestinationFolder    = 'web/';
const indexHtmlDestinationFolder = 'web/';
const cssUrl                     = 'css/';

/* Returns the parent directory of a file. */
const parent = file => file.substring(0, file.lastIndexOf('/') + 1);

/* Concatenates a list of files into a string to embed in a HTML file. */
const filesListToString = function (files, template, joinWith) {
    return files
    .map(file => template.replace('%s', file))
    .join(joinWith);
};

/* Reads files in a folder and returns them in a list. */
const getFiles = function (directory) {
    return new Promise(function (resolve, reject) {
        readdir(directory, function (error, files) {
            if (error) {
                reject(error);
            } else {
                resolve(files);
            }
        });
    });
};

/* Gulp helper to replace a string in a file. */
const replaceInFile = function (file, destination, what, replacement) {
    return gulp
    .src(file, { base: parent(file) })
    .pipe(tasks.replace(what, replacement))
    .pipe(gulp.dest(destination));
};

/* Copies all vendor css files to the web folder. */
gulp.task('copy-vendor-css', function (vendorFiles, outputFileName, destinationFolder) {
    if (vendorCss.length) {
        return gulp
        .src(vendorCss)
        .pipe(tasks.concat(vendorCssFile))
        .pipe(tasks.replace({ patterns: [{
            match:       /\.\.\/fonts\//g,
            replacement: '../assets/fonts/'
        }] }))
        .pipe(gulp.dest(cssDestinationFolder));
    } else {
        return Promise.resolve();
    }
});

gulp.task('copy-images', () => (
    gulp
    .src(sourceImgFolder + '/**/*', { base: sourceImgFolder })
    .pipe(gulp.dest(imgDestinationFolder))
));

gulp.task('copy-css', () => (
    gulp
    .src(sourceCssFolder + '/**/*.css', { base: sourceCssFolder })
    .pipe(gulp.dest(cssDestinationFolder))
));

gulp.task('copy-vendor-fonts', () => (
    gulp
    .src('./node_modules/ionicons/dist/fonts/*')
    .pipe(gulp.dest('web/assets/fonts/'))
))

gulp.task('copy-fonts', () => (
    gulp
    .src('source/assets/fonts/*', { base: 'source/assets/fonts' })
    .pipe(gulp.dest('web/assets/fonts/'))
));

/* Takes all assets files and places them into the web root. */
gulp.task('copy-web-app', function () {
    const files = tasks.glob.sync(sourceWebAppFolder + '/**/*.js');

    return tasks.browserify({ entries: files })
    .transform(tasks.babelify.configure({ presets: ['es2015'] }))
    .bundle()
    .on('error', error => {
        console.log(
            'Could not run browserify !\n',
            error.message, error.stack
        );

        this.emit('end');
    })
    .on('error', tasks.notify.onError('Could not browserify your code !'))
    .pipe(source(webAppDestinationFileName))
    .pipe(gulp.dest(webAppDestinationFolder))
    .on('error', () => this.emit('end'));
});

/* Adds the index HTML template. */
gulp.task('copy-templates', function () {
    return gulp
    .src(indexHtmlTemplate, { base: parent(indexHtmlTemplate) })
    .pipe(gulp.dest(indexHtmlDestinationFolder));
});

/* Adds app files to the index.html template. */
gulp.task('insert-app', function () {
    return getFiles(sourceCssFolder)
    .then(function (files) {
        replaceInFile(
            indexHtmlDestionationFile,
            indexHtmlDestinationFolder, { patterns: [
                {
                    match:       /--STYLES--/,
                    replacement: filesListToString(
                        files.map(file => path.basename(file)).concat(vendorCss.length ? [vendorCssFile] : []),
                        '<link href="./'
                        + cssUrl
                        + '%s" rel="stylesheet" type="text/css" />',
                        '\n        '
                    )
                },
                {
                    match:       /--SCRIPTS--/,
                    replacement: (
                        '<script type="text/javascript" src="'
                        + webAppDestinationFileName + '">'
                        + '</script>'
                    )
                }
            ] }
        );
    });
});

/* Processes template files and saves them in the root. */
gulp.task('process-templates', function () {
    return tasks.runSequence('copy-templates', 'insert-app');
});

/* Task that puts assets in the web folder and transforms them. */
gulp.task('create-root', [
    'copy-vendor-fonts', 'copy-vendor-css',
    'copy-css', 'copy-web-app',
    'process-templates', 'copy-fonts',
    'copy-images'
]);


text:
import github3

config = {
    'id': 'github',
    'name': 'GitHub',
    'install': 'pip install github3.py',
    'module': 'app.github',
    'base_url': 'https://api.github.com/',
    'request_token_url': None,
    'access_token_url': 'https://github.com/login/oauth/access_token',
    'authorize_url': 'https://github.com/login/oauth/authorize',
    'request_token_params': {
        'scope': 'user'
    }
}

def get_api(connection, **kwargs):
    return github3.login(token=getattr(connection, 'access_token'))

def get_provider_user_id(response, **kwargs):
    print 'get_provider_user_id:'
    if response:
        gh = github3.login(token=response['access_token'])
        return str(gh.user().to_json()['id'])
    return None

def get_connection_values(response, **kwargs):
    if not response:
        return None

    access_token = response['access_token']
    gh = github3.login(token=access_token)
    user = gh.user().to_json()

    return dict(
        provider_id=config['id'],
        provider_user_id=str(user['id']),
        access_token=access_token,
        secret=None,
        display_name=user['login'],
        profile_url=user['html_url'],
        image_url=user['avatar_url']
    )


text:
package org.wso2.carbon.endpoint.ui.endpoints.template;

import org.apache.axiom.om.OMElement;
import org.apache.synapse.config.xml.endpoints.DefinitionFactory;
import org.apache.synapse.config.xml.endpoints.EndpointFactory;
import org.apache.synapse.config.xml.endpoints.TemplateEndpointSerializer;
import org.apache.synapse.endpoints.Template;
import org.wso2.carbon.endpoint.ui.endpoints.Endpoint;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class TemplateEndpoint extends Endpoint {

    public String getTagLocalName() {
        return "template";
    }

    public String getEpName() {
        return epName;
    }

    public void setEpName(String epName) {
        this.epName = epName;
    }

    private String epName;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    private String address;
    private String targetTemplate = null;

    public Map<String, String> getParameters() {
        return parameters;
    }

    public void setParameters(Map<String, String> parameters) {
        this.parameters = parameters;
    }

    private Map<String, String> parameters = new HashMap<String, String>();

    public String getTargetTemplate() {
        return targetTemplate;
    }

    public void setTargetTemplate(String targetTemplate) {
        this.targetTemplate = targetTemplate;
    }

    public void addParameter(String key, String value) {
        this.parameters.put(key, value);
    }

    public OMElement serialize(OMElement parent) {

        org.apache.synapse.endpoints.TemplateEndpoint templateEndpoint = new org.apache.synapse.endpoints.TemplateEndpoint();
        if (targetTemplate != null) {
            templateEndpoint.setTemplate(targetTemplate.trim());
        }

        //parameters
        for (String key : parameters.keySet()) {
            templateEndpoint.addParameter(key, parameters.get(key));
        }

        OMElement endpoint = new TemplateEndpointSerializer().serializeEndpoint(templateEndpoint);

        if (parent != null) {
            parent.addChild(endpoint);
        }
        return endpoint;
    }

    public void build(OMElement elem, boolean isAnonymous) {
        if (isAnonymous) {
            elem.addAttribute("name", "anonymous", elem.getOMFactory().createOMNamespace("", ""));
        }
        org.apache.synapse.endpoints.TemplateEndpoint templateEndpoint = (org.apache.synapse.endpoints.TemplateEndpoint) EndpointFactory.getEndpointFromElement(elem, isAnonymous, new Properties());
        buildData(templateEndpoint);
    }

    // templates are not supported for this endpoint type
    public void build(Template template, DefinitionFactory factory) {
    }

    private void buildData(org.apache.synapse.endpoints.TemplateEndpoint templateEndpoint) {
        if (templateEndpoint.getParameters() != null) {
            setParameters(templateEndpoint.getParameters());
        }
        setTargetTemplate(templateEndpoint.getTemplate());
    }

}


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

This tests proper handling of unicode-bidi: plaintext. You should not see any red.

!hello.

!שלום.

hello, לוי!

שלום, WebKit!

a
(
שלום, WebKit!
hello, לוי!
)


text:
def helper_fn1():
    print "helper_fn1"


text:
"""
The ``mlflow.fastai`` module provides an API for logging and loading fast.ai models. This module
exports fast.ai models with the following flavors:

fastai (native) format
    This is the main flavor that can be loaded back into fastai.
:py:mod:`mlflow.pyfunc`
    Produced for use by generic pyfunc-based deployment tools and batch inference.

.. _fastai.Learner:
    https://docs.fast.ai/basic_train.html#Learner
.. _fastai.Learner.export:
    https://docs.fast.ai/basic_train.html#Learner.export
"""
import os
import yaml
import tempfile
import shutil
import pandas as pd
import numpy as np

from mlflow import pyfunc
from mlflow.models import Model, ModelSignature, ModelInputExample
import mlflow.tracking
from mlflow.models.utils import _save_example
from mlflow.models.model import MLMODEL_FILE_NAME
from mlflow.tracking.artifact_utils import _download_artifact_from_uri
from mlflow.utils.environment import (
    _mlflow_conda_env,
    _validate_env_arguments,
    _process_pip_requirements,
    _process_conda_env,
    _CONDA_ENV_FILE_NAME,
    _REQUIREMENTS_FILE_NAME,
    _CONSTRAINTS_FILE_NAME,
    _PYTHON_ENV_FILE_NAME,
    _PythonEnv,
)
from mlflow.utils.requirements_utils import _get_pinned_requirement
from mlflow.utils.file_utils import write_to
from mlflow.utils.docstring_utils import format_docstring, LOG_MODEL_PARAM_DOCS
from mlflow.utils.model_utils import (
    _get_flavor_configuration,
    _validate_and_copy_code_paths,
    _add_code_from_conf_to_system_path,
    _validate_and_prepare_target_save_path,
)
from mlflow.utils.autologging_utils import (
    log_fn_args_as_params,
    safe_patch,
    batch_metrics_logger,
    autologging_integration,
)
from mlflow.tracking._model_registry import DEFAULT_AWAIT_MAX_SLEEP_SECONDS

FLAVOR_NAME = "fastai"

def get_default_pip_requirements(include_cloudpickle=False):
    """
    :return: A list of default pip requirements for MLflow Models produced by this flavor.
             Calls to :func:`save_model()` and :func:`log_model()` produce a pip environment
             that, at minimum, contains these requirements.
    """
    pip_deps = [_get_pinned_requirement("fastai")]
    if include_cloudpickle:
        pip_deps.append(_get_pinned_requirement("cloudpickle"))

    return pip_deps

def get_default_conda_env(include_cloudpickle=False):  # pylint: disable=unused-argument
    """
    :return: The default Conda environment for MLflow Models produced by calls to
             :func:`save_model()` and :func:`log_model()`.
    """
    return _mlflow_conda_env(additional_pip_deps=get_default_pip_requirements())

@format_docstring(LOG_MODEL_PARAM_DOCS.format(package_name=FLAVOR_NAME))
def save_model(
    fastai_learner,
    path,
    conda_env=None,
    code_paths=None,
    mlflow_model=None,
    signature: ModelSignature = None,
    input_example: ModelInputExample = None,
    pip_requirements=None,
    extra_pip_requirements=None,
    **kwargs,
):
    """
    Save a fastai Learner to a path on the local file system.

    :param fastai_learner: fastai Learner to be saved.
    :param path: Local path where the model is to be saved.
    :param conda_env: {{ conda_env }}
    :param code_paths: A list of local filesystem paths to Python file dependencies (or directories
                       containing file dependencies). These files are *prepended* to the system
                       path when the model is loaded.
    :param mlflow_model: MLflow model config this flavor is being added to.

    :param signature: :py:class:`ModelSignature <mlflow.models.ModelSignature>`
                      describes model input and output :py:class:`Schema <mlflow.types.Schema>`.
                      The model signature can be :py:func:`inferred <mlflow.models.infer_signature>`
                      from datasets with valid model input (e.g. the training dataset with target
                      column omitted) and valid model output (e.g. model predictions generated on
                      the training dataset), for example:

                      .. code-block:: python

                        from mlflow.models.signature import infer_signature
                        train = df.drop_column("target_label")
                        predictions = ... # compute model predictions
                        signature = infer_signature(train, predictions)
    :param input_example: Input example provides one or several instances of valid
                          model input. The example can be used as a hint of what data to feed the
                          model. The given example will be converted to a Pandas DataFrame and then
                          serialized to json using the Pandas split-oriented format. Bytes are
                          base64-encoded.
    :param pip_requirements: {{ pip_requirements }}
    :param extra_pip_requirements: {{ extra_pip_requirements }}

    :param kwargs: kwargs to pass to ``Learner.save`` method.

    .. code-block:: python
        :caption: Example

        import os

        import mlflow.fastai

        # Create a fastai Learner model
        model = ...

        # Start MLflow session and save model to current working directory
        with mlflow.start_run():
            model.fit(epochs, learning_rate)
            mlflow.fastai.save_model(model, 'model')

        # Load saved model for inference
        model_uri = "{}/{}".format(os.getcwd(), 'model')
        loaded_model = mlflow.fastai.load_model(model_uri)
        results = loaded_model.predict(predict_data)
    """
    import fastai
    from fastai.callback.all import ParamScheduler
    from pathlib import Path

    _validate_env_arguments(conda_env, pip_requirements, extra_pip_requirements)

    path = os.path.abspath(path)
    _validate_and_prepare_target_save_path(path)
    model_data_subpath = "model.fastai"
    model_data_path = os.path.join(path, model_data_subpath)
    model_data_path = Path(model_data_path)
    code_dir_subpath = _validate_and_copy_code_paths(code_paths, path)

    if mlflow_model is None:
        mlflow_model = Model()
    if signature is not None:
        mlflow_model.signature = signature
    if input_example is not None:
        _save_example(mlflow_model, input_example, path)

    # ParamScheduler currently is not pickable
    # hence it is been removed before export and added again after export
    cbs = [c for c in fastai_learner.cbs if isinstance(c, ParamScheduler)]
    fastai_learner.remove_cbs(cbs)
    fastai_learner.export(model_data_path, **kwargs)
    fastai_learner.add_cbs(cbs)

    pyfunc.add_to_model(
        mlflow_model,
        loader_module="mlflow.fastai",
        data=model_data_subpath,
        code=code_dir_subpath,
        conda_env=_CONDA_ENV_FILE_NAME,
        python_env=_PYTHON_ENV_FILE_NAME,
    )
    mlflow_model.add_flavor(
        FLAVOR_NAME,
        fastai_version=fastai.__version__,
        data=model_data_subpath,
        code=code_dir_subpath,
    )
    mlflow_model.save(os.path.join(path, MLMODEL_FILE_NAME))

    if conda_env is None:
        if pip_requirements is None:
            default_reqs = get_default_pip_requirements()
            # To ensure `_load_pyfunc` can successfully load the model during the dependency
            # inference, `mlflow_model.save` must be called beforehand to save an MLmodel file.
            inferred_reqs = mlflow.models.infer_pip_requirements(
                path,
                FLAVOR_NAME,
                fallback=default_reqs,
            )
            default_reqs = sorted(set(inferred_reqs).union(default_reqs))
        else:
            default_reqs = None
        conda_env, pip_requirements, pip_constraints = _process_pip_requirements(
            default_reqs,
            pip_requirements,
            extra_pip_requirements,
        )
    else:
        conda_env, pip_requirements, pip_constraints = _process_conda_env(conda_env)

    with open(os.path.join(path, _CONDA_ENV_FILE_NAME), "w") as f:
        yaml.safe_dump(conda_env, stream=f, default_flow_style=False)

    # Save `constraints.txt` if necessary
    if pip_constraints:
        write_to(os.path.join(path, _CONSTRAINTS_FILE_NAME), "\n".join(pip_constraints))

    # Save `requirements.txt`
    write_to(os.path.join(path, _REQUIREMENTS_FILE_NAME), "\n".join(pip_requirements))

    _PythonEnv.current().to_yaml(os.path.join(path, _PYTHON_ENV_FILE_NAME))

@format_docstring(LOG_MODEL_PARAM_DOCS.format(package_name=FLAVOR_NAME))
def log_model(
    fastai_learner,
    artifact_path,
    conda_env=None,
    code_paths=None,
    registered_model_name=None,
    signature: ModelSignature = None,
    input_example: ModelInputExample = None,
    await_registration_for=DEFAULT_AWAIT_MAX_SLEEP_SECONDS,
    pip_requirements=None,
    extra_pip_requirements=None,
    **kwargs,
):
    """
    Log a fastai model as an MLflow artifact for the current run.

    :param fastai_learner: Fastai model (an instance of `fastai.Learner`_) to be saved.
    :param artifact_path: Run-relative artifact path.
    :param conda_env: {{ conda_env }}
    :param code_paths: A list of local filesystem paths to Python file dependencies (or directories
                       containing file dependencies). These files are *prepended* to the system
                       path when the model is loaded.
    :param registered_model_name: This argument may change or be removed in a
                                  future release without warning. If given, create a model
                                  version under ``registered_model_name``, also creating a
                                  registered model if one with the given name does not exist.

    :param signature: :py:class:`ModelSignature <mlflow.models.ModelSignature>`
                      describes model input and output :py:class:`Schema <mlflow.types.Schema>`.
                      The model signature can be :py:func:`inferred <mlflow.models.infer_signature>`
                      from datasets with valid model input (e.g. the training dataset with target
                      column omitted) and valid model output (e.g. model predictions generated on
                      the training dataset), for example:

                      .. code-block:: python

                        from mlflow.models.signature import infer_signature
                        train = df.drop_column("target_label")
                        predictions = ... # compute model predictions
                        signature = infer_signature(train, predictions)
    :param input_example: Input example provides one or several instances of valid
                          model input. The example can be used as a hint of what data to feed the
                          model. The given example will be converted to a Pandas DataFrame and then
                          serialized to json using the Pandas split-oriented format. Bytes are
                          base64-encoded.

    :param kwargs: kwargs to pass to `fastai.Learner.export`_ method.
    :param await_registration_for: Number of seconds to wait for the model version to finish
                            being created and is in ``READY`` status. By default, the function
                            waits for five minutes. Specify 0 or None to skip waiting.
    :param pip_requirements: {{ pip_requirements }}
    :param extra_pip_requirements: {{ extra_pip_requirements }}
    :return: A :py:class:`ModelInfo <mlflow.models.model.ModelInfo>` instance that contains the
             metadata of the logged model.

    .. code-block:: python
        :caption: Example

        import fastai.vision as vis
        import mlflow.fastai
        from mlflow import MlflowClient

        def main(epochs=5, learning_rate=0.01):
            # Download and untar the MNIST data set
            path = vis.untar_data(vis.URLs.MNIST_SAMPLE)

           # Prepare, transform, and normalize the data
           data = vis.ImageDataBunch.from_folder(path, ds_tfms=(vis.rand_pad(2, 28), []), bs=64)
           data.normalize(vis.imagenet_stats)

           # Create the CNN Learner model
           model = vis.cnn_learner(data, vis.models.resnet18, metrics=vis.accuracy)

           # Start MLflow session and log model
           with mlflow.start_run() as run:
                model.fit(epochs, learning_rate)
                mlflow.fastai.log_model(model, 'model')

           # fetch the logged model artifacts
           artifacts = [f.path for f in MlflowClient().list_artifacts(run.info.run_id, 'model')]
           print("artifacts: {}".format(artifacts))

        main()

    .. code-block:: text
        :caption: Output

        artifacts: ['model/MLmodel', 'model/conda.yaml', 'model/model.fastai']
    """
    return Model.log(
        artifact_path=artifact_path,
        flavor=mlflow.fastai,
        registered_model_name=registered_model_name,
        fastai_learner=fastai_learner,
        conda_env=conda_env,
        code_paths=code_paths,
        signature=signature,
        input_example=input_example,
        await_registration_for=await_registration_for,
        pip_requirements=pip_requirements,
        extra_pip_requirements=extra_pip_requirements,
        **kwargs,
    )

def _load_model(path):
    from fastai.learner import load_learner

    return load_learner(os.path.abspath(path))

class _FastaiModelWrapper:
    def __init__(self, learner):
        self.learner = learner

    def predict(self, dataframe):
        dl = self.learner.dls.test_dl(dataframe)
        preds, _ = self.learner.get_preds(dl=dl)
        return pd.Series(map(np.array, preds.numpy())).to_frame("predictions")

def _load_pyfunc(path):
    """
    Load PyFunc implementation. Called by ``pyfunc.load_model``.

    :param path: Local filesystem path to the MLflow Model with the ``fastai`` flavor.
    """
    return _FastaiModelWrapper(_load_model(path))

def load_model(model_uri, dst_path=None):
    """
    Load a fastai model from a local file or a run.

    :param model_uri: The location, in URI format, of the MLflow model. For example:

                      - ``/Users/me/path/to/local/model``
                      - ``relative/path/to/local/model``
                      - ``s3://my_bucket/path/to/model``
                      - ``runs:/<mlflow_run_id>/run-relative/path/to/model``

                      For more information about supported URI schemes, see
                      `Referencing Artifacts <https://www.mlflow.org/docs/latest/tracking.html#
                      artifact-locations>`_.
    :param dst_path: The local filesystem path to which to download the model artifact.
                     This directory must already exist. If unspecified, a local output
                     path will be created.

    :return: A fastai model (an instance of `fastai.Learner`_).

    .. code-block:: python
        :caption: Example

        import mlflow.fastai

        # Define the Learner model
        model = ...

        # log the fastai Leaner model
        with mlflow.start_run() as run:
            model.fit(epochs, learning_rate)
            mlflow.fastai.log_model(model, "model")

        # Load the model for scoring
        model_uri = "runs:/{}/model".format(run.info.run_id)
        loaded_model = mlflow.fastai.load_model(model_uri)
        results = loaded_model.predict(predict_data)
    """
    local_model_path = _download_artifact_from_uri(artifact_uri=model_uri, output_path=dst_path)
    flavor_conf = _get_flavor_configuration(model_path=local_model_path, flavor_name=FLAVOR_NAME)
    _add_code_from_conf_to_system_path(local_model_path, flavor_conf)

    model_file_path = os.path.join(local_model_path, flavor_conf.get("data", "model.fastai"))
    return _load_model(path=model_file_path)

@autologging_integration(FLAVOR_NAME)
def autolog(
    log_models=True,
    disable=False,
    exclusive=False,
    disable_for_unsupported_versions=False,
    silent=False,
    registered_model_name=None,
):  # pylint: disable=unused-argument
    """
    Enable automatic logging from Fastai to MLflow.
    Logs loss and any other metrics specified in the fit
    function, and optimizer data as parameters. Model checkpoints
    are logged as artifacts to a 'models' directory.

    MLflow will also log the parameters of the
    `EarlyStoppingCallback <https://docs.fast.ai/callback.tracker.html#EarlyStoppingCallback>`_
    and `OneCycleScheduler <https://docs.fast.ai/callback.schedule.html#ParamScheduler>`_ callbacks

    :param log_models: If ``True``, trained models are logged as MLflow model artifacts.
                       If ``False``, trained models are not logged.
    :param disable: If ``True``, disables the Fastai autologging integration. If ``False``,
                    enables the Fastai autologging integration.
    :param exclusive: If ``True``, autologged content is not logged to user-created fluent runs.
                      If ``False``, autologged content is logged to the active fluent run,
                      which may be user-created.
    :param disable_for_unsupported_versions: If ``True``, disable autologging for versions of
                      fastai that have not been tested against this version of the MLflow client
                      or are incompatible.
    :param silent: If ``True``, suppress all event logs and warnings from MLflow during Fastai
                   autologging. If ``False``, show all events and warnings during Fastai
                   autologging.
    :param registered_model_name: If given, each time a model is trained, it is registered as a
                                  new model version of the registered model with this name.
                                  The registered model is created if it does not already exist.

    .. code-block:: python
        :caption: Example

        # This is a modified example from
        # https://github.com/mlflow/mlflow/tree/master/examples/fastai
        # demonstrating autolog capabilities.

        import fastai.vision as vis
        import mlflow.fastai
        from mlflow import MlflowClient

        def print_auto_logged_info(r):
            tags = {k: v for k, v in r.data.tags.items() if not k.startswith("mlflow.")}
            artifacts = [f.path for f in MlflowClient().list_artifacts(r.info.run_id, "model")]
            print("run_id: {}".format(r.info.run_id))
            print("artifacts: {}".format(artifacts))
            print("params: {}".format(r.data.params))
            print("metrics: {}".format(r.data.metrics))
            print("tags: {}".format(tags))

        def main(epochs=5, learning_rate=0.01):
            # Download and untar the MNIST data set
            path = vis.untar_data(vis.URLs.MNIST_SAMPLE)

            # Prepare, transform, and normalize the data
            data = vis.ImageDataBunch.from_folder(path, ds_tfms=(vis.rand_pad(2, 28), []), bs=64)
            data.normalize(vis.imagenet_stats)

            # Create CNN the Learner model
            model = vis.cnn_learner(data, vis.models.resnet18, metrics=vis.accuracy)

            # Enable auto logging
            mlflow.fastai.autolog()

            # Start MLflow session
            with mlflow.start_run() as run:
                model.fit(epochs, learning_rate)

            # fetch the auto logged parameters, metrics, and artifacts
            print_auto_logged_info(mlflow.get_run(run_id=run.info.run_id))

        main()

    .. code-block:: text
        :caption: output

        run_id: 5a23dcbcaa334637814dbce7a00b2f6a
        artifacts: ['model/MLmodel', 'model/conda.yaml', 'model/model.fastai']
        params: {'wd': 'None',
                 'bn_wd': 'True',
                 'opt_func': 'Adam',
                 'epochs': '5', '
                 train_bn': 'True',
                 'num_layers': '60',
                 'lr': '0.01',
                 'true_wd': 'True'}
        metrics: {'train_loss': 0.024,
                  'accuracy': 0.99214,
                  'valid_loss': 0.021}
        # Tags model summary omitted too long
        tags: {...}

    .. figure:: ../_static/images/fastai_autolog.png

        Fastai autologged MLflow entities
    """
    from fastai.learner import Learner
    from fastai.callback.hook import module_summary, layer_info, find_bs, _print_shapes
    from fastai.callback.all import EarlyStoppingCallback, TrackerCallback

    def getFastaiCallback(metrics_logger, is_fine_tune=False):
        from mlflow.fastai.callback import __MlflowFastaiCallback

        return __MlflowFastaiCallback(
            metrics_logger=metrics_logger,
            log_models=log_models,
            is_fine_tune=is_fine_tune,
        )

    def _find_callback_of_type(callback_type, callbacks):
        for callback in callbacks:
            if isinstance(callback, callback_type):
                return callback
        return None

    def _log_early_stop_callback_params(callback):
        if callback:
            try:
                earlystopping_params = {
                    "early_stop_monitor": callback.monitor,
                    "early_stop_min_delta": callback.min_delta,
                    "early_stop_patience": callback.patience,
                    "early_stop_comp": callback.comp.__name__,
                }
                mlflow.log_params(earlystopping_params)
            except Exception:  # pylint: disable=W0703
                return

    def _log_model_info(learner):
        # The process executed here, are incompatible with TrackerCallback
        # Hence it is removed and add again after the execution
        remove_cbs = [cb for cb in learner.cbs if isinstance(cb, TrackerCallback)]
        if remove_cbs:
            learner.remove_cbs(remove_cbs)

        xb = learner.dls.train.one_batch()[: learner.dls.train.n_inp]
        infos = layer_info(learner, *xb)
        bs = find_bs(xb)
        inp_sz = _print_shapes((x.shape for x in xb), bs)
        mlflow.log_param("input_size", inp_sz)
        mlflow.log_param("num_layers", len(infos))

        summary = module_summary(learner, *xb)

        # Add again TrackerCallback
        if remove_cbs:
            learner.add_cbs(remove_cbs)

        tempdir = tempfile.mkdtemp()
        try:
            summary_file = os.path.join(tempdir, "module_summary.txt")
            with open(summary_file, "w") as f:
                f.write(summary)
            mlflow.log_artifact(local_path=summary_file)
        finally:
            shutil.rmtree(tempdir)

    def _run_and_log_function(self, original, args, kwargs, unlogged_params, is_fine_tune=False):
        # Check if is trying to fit while fine tuning or not
        mlflow_cbs = [cb for cb in self.cbs if cb.name == "___mlflow_fastai"]
        fit_in_fine_tune = (
            original.__name__ == "fit" and len(mlflow_cbs) > 0 and mlflow_cbs[0].is_fine_tune
        )

        if not fit_in_fine_tune:
            log_fn_args_as_params(original, list(args), kwargs, unlogged_params)

        run_id = mlflow.active_run().info.run_id
        with batch_metrics_logger(run_id) as metrics_logger:

            if not fit_in_fine_tune:
                early_stop_callback = _find_callback_of_type(EarlyStoppingCallback, self.cbs)
                _log_early_stop_callback_params(early_stop_callback)

                # First try to remove if any already registered callback
                self.remove_cbs(mlflow_cbs)

                # Log information regarding model and data without bar and print-out
                with self.no_bar(), self.no_logging():
                    _log_model_info(learner=self)

                mlflowFastaiCallback = getFastaiCallback(
                    metrics_logger=metrics_logger, is_fine_tune=is_fine_tune
                )

                # Add the new callback
                self.add_cb(mlflowFastaiCallback)

            result = original(self, *args, **kwargs)

        return result

    def fit(original, self, *args, **kwargs):
        unlogged_params = ["self", "cbs", "learner", "lr", "lr_max", "wd"]
        return _run_and_log_function(
            self, original, args, kwargs, unlogged_params, is_fine_tune=False
        )

    safe_patch(FLAVOR_NAME, Learner, "fit", fit, manage_run=True)

    def fine_tune(original, self, *args, **kwargs):
        unlogged_params = ["self", "cbs", "learner", "lr", "lr_max", "wd"]
        return _run_and_log_function(
            self, original, args, kwargs, unlogged_params, is_fine_tune=True
        )

    safe_patch(FLAVOR_NAME, Learner, "fine_tune", fine_tune, manage_run=True)


text:
package iso20022

// Specifies the elements that identify a proxy appointed to represent a party authorised to vote at a shareholders meeting.
type Proxy3 struct {

	// Specifies the type of proxy.
	ProxyType []*ProxyType2Code `xml:"PrxyTp"`

	// Identifies an authorized proxy which has been assigned by the issuer of the meeting.
	PreassignedProxy *IndividualPerson16 `xml:"PrssgndPrxy,omitempty"`
}

func (p *Proxy3) AddProxyType(value string) {
	p.ProxyType = append(p.ProxyType, (*ProxyType2Code)(&value))
}

func (p *Proxy3) AddPreassignedProxy() *IndividualPerson16 {
	p.PreassignedProxy = new(IndividualPerson16)
	return p.PreassignedProxy
}


text:
order: 7
title:
  en-US: Filter and sorter
  zh-CN: 筛选和排序
---

## zh-CN

对某一列数据进行筛选,使用列的 `filters` 属性来指定需要筛选菜单的列,`onFilter` 用于筛选当前数据,`filterMultiple` 用于指定多选和单选。

对某一列数据进行排序,通过指定列的 `sorter` 函数即可启动排序按钮。`sorter: function(a, b) { ... }`, a、b 为比较的两个列数据。

使用 `defaultSortOrder` 属性,设置列的默认排序顺序。

## en-US

Use `filters` to generate filter menu in columns, `onFilter` to determine filtered result, and `filterMultiple` to indicate whether it's multiple or single selection.

Use `sorter` to make a column sortable. `sorter` can be a function of the type `function(a, b) { ... }` for sorting data locally.

Uses `defaultSortOrder` to make a column sorted by default.

If a `sortOrder` or `defaultSortOrder` is specified with the value `ascend` or `descend`, you can access this value from within the function passed to the `sorter` as explained above. Such a function can take the form: `function(a, b, sortOrder) { ... }`.

````jsx
import { Table } from 'igroot';

const columns = [{
  title: 'Name',
  dataIndex: 'name',
  filters: [{
    text: 'Joe',
    value: 'Joe',
  }, {
    text: 'Jim',
    value: 'Jim',
  }, {
    text: 'Submenu',
    value: 'Submenu',
    children: [{
      text: 'Green',
      value: 'Green',
    }, {
      text: 'Black',
      value: 'Black',
    }],
  }],
  // specify the condition of filtering result
  // here is that finding the name started with `value`
  onFilter: (value, record) => record.name.indexOf(value) === 0,
  sorter: (a, b) => a.name.length - b.name.length,
}, {
  title: 'Age',
  dataIndex: 'age',
  defaultSortOrder: 'descend',
  sorter: (a, b) => a.age - b.age,
}, {
  title: 'Address',
  dataIndex: 'address',
  filters: [{
    text: 'London',
    value: 'London',
  }, {
    text: 'New York',
    value: 'New York',
  }],
  filterMultiple: false,
  onFilter: (value, record) => record.address.indexOf(value) === 0,
  sorter: (a, b) => a.address.length - b.address.length,
}];

const data = [{
  key: '1',
  name: 'John Brown',
  age: 32,
  address: 'New York No. 1 Lake Park',
}, {
  key: '2',
  name: 'Jim Green',
  age: 42,
  address: 'London No. 1 Lake Park',
}, {
  key: '3',
  name: 'Joe Black',
  age: 32,
  address: 'Sidney No. 1 Lake Park',
}, {
  key: '4',
  name: 'Jim Red',
  age: 32,
  address: 'London No. 2 Lake Park',
}];

function onChange(pagination, filters, sorter) {
  console.log('params', pagination, filters, sorter);
}

ReactDOM.render(
  <Table columns={columns} dataSource={data} onChange={onChange} />,
  mountNode);
````


text:
//-----------------------------------------------------------------------
// <copyright file="VideoOverlayListener.cs" company="Google">
//
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------

namespace Tango
{
    using System;
    using System.Collections;
    using System.Runtime.InteropServices;
    using UnityEngine;

    /// <summary>
    /// Delegate for Tango image events.
    /// </summary>
    /// <param name="cameraId">The camera for the image.</param>
    /// <param name="imageBuffer">The image from the camera.</param>
    internal delegate void OnTangoImageAvailableEventHandler(TangoEnums.TangoCameraId cameraId,
                                                             TangoUnityImageData imageBuffer);

    /// <summary>
    /// Delegate for Tango texture events.
    /// </summary>
    /// <param name="cameraId">The camera that has an updated texture.</param>
    internal delegate void OnTangoCameraTextureAvailableEventHandler(TangoEnums.TangoCameraId cameraId);

    /// <summary>
    /// Delegate for Tango image events that can be called on any thread.
    /// </summary>
    /// <param name="cameraId">The camera for the image.</param>
    /// <param name="image">The image from the camera.</param>
    /// <param name="cameraMetadata">The image's camera metadata.</param>
    internal delegate void OnTangoImageMultithreadedAvailableEventHandler(TangoEnums.TangoCameraId cameraId,
                                                                          TangoImage image,
                                                                          TangoCameraMetadata cameraMetadata);

    /// <summary>
    /// Marshals Tango image data between the C callbacks in one thread and
    /// the main Unity thread.
    ///
    /// Only supports the color camera.
    /// </summary>
    internal static class VideoOverlayListener
    {
        /// <summary>
        /// The ID of the color camera.
        /// </summary>
        private const TangoEnums.TangoCameraId COLOR_CAMERA_ID = TangoEnums.TangoCameraId.TANGO_CAMERA_COLOR;

        /// <summary>
        /// The lock object used as a mutex.
        /// </summary>
        private static System.Object m_lockObject = new System.Object();

        private static VideoOverlayProvider.APIOnImageAvailable m_onImageAvailable;
        private static VideoOverlayProvider.APIOnTextureAvailable m_onTextureAvailable;
        private static VideoOverlayProvider.APIOnTextureAvailable m_onYUVTextureAvailable;

        private static TangoUnityImageData m_previousImageBuffer;
        private static bool m_shouldSendTextureMethodEvent;
        private static bool m_shouldSendByteBufferMethodEvent;

        /// <summary>
        /// DEPRECATED. Will be removed in a future SDK.
        /// </summary>
        private static bool m_shouldSendYUVTextureIdMethodEvent = false;

        /// <summary>
        /// Called when a new Tango image is available.
        /// </summary>
        private static OnTangoImageAvailableEventHandler m_onTangoImageAvailable;

        /// <summary>
        /// Called when a new Tango texture is available.
        /// </summary>
        private static OnTangoCameraTextureAvailableEventHandler m_onTangoCameraTextureAvailable;

        /// <summary>
        /// DEPRECATED: Called when a new Tango YUV texture is available (experimental version).
        /// </summary>
        private static OnTangoCameraTextureAvailableEventHandler m_onTangoYUVTextureAvailable;

        /// <summary>
        /// Called when a new TangoImage is available on the thread the image came from.
        /// </summary>
        private static OnTangoImageMultithreadedAvailableEventHandler m_onTangoImageMultithreadedAvailable;

        /// <summary>
        /// Initializes the <see cref="Tango.VideoOverlayListener"/> class.
        /// </summary>
        static VideoOverlayListener()
        {
            Reset();
        }

        /// <summary>
        /// Stop getting Tango image or texture callbacks.
        /// </summary>
        internal static void Reset()
        {
            // Avoid calling into tango_client_api before the correct library is loaded.
            if (m_onImageAvailable != null || m_onTextureAvailable != null || m_onYUVTextureAvailable != null)
            {
                VideoOverlayProvider.ClearCallback(COLOR_CAMERA_ID);
            }

            m_onImageAvailable = null;
            m_onTextureAvailable = null;
            m_onYUVTextureAvailable = null;
            m_previousImageBuffer = new TangoUnityImageData();
            m_shouldSendTextureMethodEvent = false;
            m_shouldSendByteBufferMethodEvent = false;
            m_shouldSendYUVTextureIdMethodEvent = false;
            m_onTangoImageAvailable = null;
            m_onTangoCameraTextureAvailable = null;
            m_onTangoYUVTextureAvailable = null;
            m_onTangoImageMultithreadedAvailable = null;
        }

        /// <summary>
        /// Clear just the Tango callbacks. External registered listeners are kept.
        /// </summary>
        internal static void ClearTangoCallbacks()
        {
            m_onTextureAvailable = null;
            m_onYUVTextureAvailable = null;
            m_onImageAvailable = null;
        }

        /// <summary>
        /// Register to get Tango texture events when the camera is updated.
        ///
        /// NOTE: Tango texture events happen on a different thread than the main Unity thread.
        /// </summary>
        internal static void SetCallbackTextureMethod()
        {
            if (m_onTextureAvailable != null)
            {
                Debug.Log("VideoOverlayProvider.SetCallbackTextureMethod() called when a callback is already set.");
                return;
            }

            Debug.Log("VideoOverlayProvider.SetCallbackTextureMethod()");
            m_onTextureAvailable = new VideoOverlayProvider.APIOnTextureAvailable(_OnTangoCameraTextureAvailable);
            VideoOverlayProvider.SetCallback(COLOR_CAMERA_ID, m_onTextureAvailable);
        }

        /// <summary>
        /// DEPRECATED: Register to get Tango texture events for the texture ID is updated.
        ///
        /// NOTE: Tango texture events happen on a different thread than the main
        /// Unity thread.
        /// </summary>
        /// <param name="videoOverlayTexture">The video overlay texture to use.</param>
        internal static void SetCallbackYUVTextureIdMethod(YUVTexture videoOverlayTexture)
        {
            if (videoOverlayTexture != null)
            {
                if (m_onYUVTextureAvailable != null)
                {
                    Debug.Log("VideoOverlayProvider.SetCallbackYUVTextureIdMethod() called when a callback is already set.");
                    return;
                }

                Debug.Log("VideoOverlayProvider.SetCallbackYUVTextureIdMethod()");
                m_onYUVTextureAvailable =
                    new VideoOverlayProvider.APIOnTextureAvailable(_OnTangoYUVTextureAvailable);
                VideoOverlayProvider.ExperimentalConnectTexture(
                    COLOR_CAMERA_ID, videoOverlayTexture, m_onYUVTextureAvailable);
            }
            else
            {
                Debug.Log("VideoOverlayListener.SetCallbackYUVTextureIdMethod() : No Texture2D found!");
            }
        }

        /// <summary>
        /// Register to get Tango image events for getting the texture byte buffer callback.
        ///
        /// NOTE: Tango image events happen on a different thread than the main
        /// Unity thread.
        /// </summary>
        internal static void SetCallbackByteBufferMethod()
        {
            if (m_onImageAvailable != null)
            {
                Debug.Log("VideoOverlayProvider.SetCallbackByteBufferMethod() called when a callback is already set.");
                return;
            }

            Debug.Log("VideoOverlayProvider.SetCallbackByteBufferMethod()");
            m_onImageAvailable = new VideoOverlayProvider.APIOnImageAvailable(_OnImageAvailable);
            VideoOverlayProvider.SetCallback(COLOR_CAMERA_ID, m_onImageAvailable);
        }

        /// <summary>
        /// Raise a Tango image event if there is new data.
        /// </summary>
        internal static void SendIfAvailable()
        {
            if (m_onImageAvailable == null && m_onTextureAvailable == null
                && m_onYUVTextureAvailable == null)
            {
                return;
            }

#if UNITY_EDITOR
            lock (m_lockObject)
            {
                if (VideoOverlayProvider.m_emulationIsDirty)
                {
                    VideoOverlayProvider.m_emulationIsDirty = false;

                    if (m_onTangoYUVTextureAvailable != null)
                    {
                        m_shouldSendYUVTextureIdMethodEvent = true;
                    }

                    if (m_onTangoCameraTextureAvailable != null)
                    {
                        m_shouldSendTextureMethodEvent = true;
                    }

                    if (m_onTangoImageAvailable != null || m_onTangoImageMultithreadedAvailable != null)
                    {
                        _FillEmulatedColorCameraData(m_previousImageBuffer);
                    }

                    if (m_onTangoImageMultithreadedAvailable != null)
                    {
                        GCHandle pinnedColorBuffer = GCHandle.Alloc(m_previousImageBuffer.data, GCHandleType.Pinned);
                        TangoImage emulatedImage;
                        TangoCameraMetadata emulatedCameraMetadata;
                        _GetEmulatedTangoImage(m_previousImageBuffer, pinnedColorBuffer, out emulatedImage,
                            out emulatedCameraMetadata);
                        m_onTangoImageMultithreadedAvailable(COLOR_CAMERA_ID, emulatedImage, emulatedCameraMetadata);
                    }

                    if (m_onTangoImageAvailable != null)
                    {
                        m_shouldSendByteBufferMethodEvent = true;
                    }
                }
            }
#endif

            lock (m_lockObject)
            {
                if (m_onTangoYUVTextureAvailable != null && m_shouldSendYUVTextureIdMethodEvent)
                {
                    m_onTangoYUVTextureAvailable(COLOR_CAMERA_ID);
                    m_shouldSendYUVTextureIdMethodEvent = false;
                }

                if (m_onTangoCameraTextureAvailable != null & m_shouldSendTextureMethodEvent)
                {
                    m_onTangoCameraTextureAvailable(COLOR_CAMERA_ID);
                    m_shouldSendTextureMethodEvent = false;
                }

                if (m_onTangoImageAvailable != null && m_shouldSendByteBufferMethodEvent)
                {
                    m_onTangoImageAvailable(COLOR_CAMERA_ID, m_previousImageBuffer);
                    m_shouldSendByteBufferMethodEvent = false;
                }
            }
        }

        /// <summary>
        /// Register a Unity main thread handler for the Tango image event.
        /// </summary>
        /// <param name="handler">Event handler to register.</param>
        internal static void RegisterOnTangoImageAvailable(OnTangoImageAvailableEventHandler handler)
        {
            if (handler != null)
            {
                m_onTangoImageAvailable += handler;
            }
        }

        /// <summary>
        /// Unregister a Unity main thread handler for the Tango image event.
        /// </summary>
        /// <param name="handler">Event handler to unregister.</param>
        internal static void UnregisterOnTangoImageAvailable(OnTangoImageAvailableEventHandler handler)
        {
            if (handler != null)
            {
                m_onTangoImageAvailable -= handler;
            }
        }

        /// <summary>
        /// Register a Unity main thread handler for the Tango texture event.
        /// </summary>
        /// <param name="handler">Event handler to register.</param>
        internal static void RegisterOnTangoCameraTextureAvailable(OnTangoCameraTextureAvailableEventHandler handler)
        {
            if (handler != null)
            {
                m_onTangoCameraTextureAvailable += handler;
            }
        }

        /// <summary>
        /// Unregister a Unity main thread handler for the Tango texture event.
        /// </summary>
        /// <param name="handler">Event handler to unregister.</param>
        internal static void UnregisterOnTangoCameraTextureAvailable(OnTangoCameraTextureAvailableEventHandler handler)
        {
            if (handler != null)
            {
                m_onTangoCameraTextureAvailable -= handler;
            }
        }

        /// <summary>
        /// DEPRECATED: Register a Unity main thread handler for the Tango texture event.
        /// </summary>
        /// <param name="handler">Event handler to register.</param>
        internal static void RegisterOnTangoYUVTextureAvailable(OnTangoCameraTextureAvailableEventHandler handler)
        {
            if (handler != null)
            {
                m_onTangoYUVTextureAvailable += handler;
            }
        }

        /// <summary>
        /// DEPRECATED: Unregister a Unity main thread handler for the Tango texture event.
        /// </summary>
        /// <param name="handler">Event handler to unregister.</param>
        internal static void UnregisterOnTangoYUVTextureAvailable(OnTangoCameraTextureAvailableEventHandler handler)
        {
            if (handler != null)
            {
                m_onTangoYUVTextureAvailable -= handler;
            }
        }

        /// <summary>
        /// Register a multithread handler for the Tango image event.
        /// </summary>
        /// <param name="handler">Event handler to register.</param>
        internal static void RegisterOnTangoImageMultithreadedAvailable(OnTangoImageMultithreadedAvailableEventHandler handler)
        {
            if (handler != null)
            {
                m_onTangoImageMultithreadedAvailable += handler;
            }
        }

        /// <summary>
        /// Unregister a multithread handler for the Tango image event.
        /// </summary>
        /// <param name="handler">Event handler to unregister.</param>
        internal static void UnregisterOnTangoImageMultithreadedAvailable(OnTangoImageMultithreadedAvailableEventHandler handler)
        {
            if (handler != null)
            {
                m_onTangoImageMultithreadedAvailable -= handler;
            }
        }

        /// <summary>
        /// Handle the callback sent by the Tango Service when a new image is sampled.
        /// </summary>
        /// <param name="callbackContext">Callback context.</param>
        /// <param name="cameraId">Camera identifier.</param>
        /// <param name="image">Image buffer.</param>
        /// <param name="cameraMetadata">Camera metadata for this image.</param>
        [AOT.MonoPInvokeCallback(typeof(VideoOverlayProvider.APIOnImageAvailable))]
        private static void _OnImageAvailable(
            IntPtr callbackContext, TangoEnums.TangoCameraId cameraId, ref TangoImage image,
            ref TangoCameraMetadata cameraMetadata)
        {
            if (cameraId != COLOR_CAMERA_ID)
            {
                return;
            }

            if (m_onTangoImageMultithreadedAvailable != null)
            {
                m_onTangoImageMultithreadedAvailable(cameraId, image, cameraMetadata);
            }

            lock (m_lockObject)
            {
                // This is correct because Tango is required to support YUV888 as Y plane, UV interleaved plane.
                int uvPlaneSize = image.m_planeSize2 + 1;
                if (m_previousImageBuffer.data == null)
                {
                    m_previousImageBuffer.data = new byte[image.m_planeSize0 + uvPlaneSize];
                }

                m_previousImageBuffer.width = image.m_width;
                m_previousImageBuffer.height = image.m_height;
                m_previousImageBuffer.stride = (uint)image.m_planeRowStride0;
                m_previousImageBuffer.timestamp = ((double)image.m_timestampNs) * Common.SECS_PER_NANOSECS;
                m_previousImageBuffer.format = image.m_format;
                m_previousImageBuffer.frame_number = cameraMetadata.m_frameNumber;

                //// Convert from YUV888 to NV21.
                //// Get Ys.
                Marshal.Copy(image.m_planeData0, m_previousImageBuffer.data, 0, image.m_planeSize0);

                //// Size of UV plane is image.plane_2_size + 1, since Tango guarantees that YUV888 has UV interleaved.
                Marshal.Copy(image.m_planeData2, m_previousImageBuffer.data, image.m_planeSize0, uvPlaneSize);

                m_shouldSendByteBufferMethodEvent = true;
            }
        }

        /// <summary>
        /// Handle the callback set by the Tango Service when a new image is available.
        /// </summary>
        /// <param name="callbackContext">Callback context.</param>
        /// <param name="cameraId">Camera identifier.</param>
        [AOT.MonoPInvokeCallback(typeof(VideoOverlayProvider.APIOnTextureAvailable))]
        private static void _OnTangoCameraTextureAvailable(IntPtr callbackContext, TangoEnums.TangoCameraId cameraId)
        {
            if (cameraId != COLOR_CAMERA_ID)
            {
                return;
            }

            lock (m_lockObject)
            {
                m_shouldSendTextureMethodEvent = true;
            }
        }

        /// <summary>
        /// DEPRECATED: Handle the callback set by the Tango Service when a new image is available.
        /// </summary>
        /// <param name="callbackContext">Callback context.</param>
        /// <param name="cameraId">Camera identifier.</param>
        [AOT.MonoPInvokeCallback(typeof(VideoOverlayProvider.APIOnTextureAvailable))]
        private static void _OnTangoYUVTextureAvailable(IntPtr callbackContext, TangoEnums.TangoCameraId cameraId)
        {
            if (cameraId != COLOR_CAMERA_ID)
            {
                return;
            }

            lock (m_lockObject)
            {
                m_shouldSendYUVTextureIdMethodEvent = true;
            }
        }

#if UNITY_EDITOR
        /// <summary>
        /// Fill out <c>colorCameraData</c> with emulated values from Tango.
        /// </summary>
        /// <param name="colorCameraData">The image data to fill out.</param>
        private static void _FillEmulatedColorCameraData(TangoUnityImageData colorCameraData)
        {
            VideoOverlayProvider.GetTangoEmulation(colorCameraData);
        }

        /// <summary>
        /// It's backwards, but fill tango image buffer data with already-emulated data.
        /// It is the responsibility of the caller to GC pin/free the colorImageData's data array.
        /// </summary>
        /// <returns>Emulated raw color buffer.</returns>
        /// <param name="colorImageData">Emulated color buffer data.</param>>
        /// <param name="pinnedColorBuffer">Pinned array of imageBuffer.data.</param>
        /// <param name="image"> TangoImage populated with emulator image data.</param>
        /// <param name="cameraMetadata">Camera metadata for emulated image.</param>
        private static void _GetEmulatedTangoImage(TangoUnityImageData colorImageData, GCHandle pinnedColorBuffer,
            out TangoImage image, out TangoCameraMetadata cameraMetadata)
        {
            image = new TangoImage();
            cameraMetadata = new TangoCameraMetadata();
            image.m_planeData0 = pinnedColorBuffer.AddrOfPinnedObject();
            image.m_planeData2 = new IntPtr(pinnedColorBuffer.AddrOfPinnedObject().ToInt64() + image.m_width * image.m_height);
            image.m_planeData1 = new IntPtr(image.m_planeData2.ToInt64() + 1);
            image.m_width = colorImageData.width;
            image.m_height = colorImageData.height;

            // The existing system assumes the whole image has the same row stride across all planes.
            int stride = (int) colorImageData.stride;
            image.m_planeRowStride0 = stride;
            image.m_planeRowStride1 = stride;
            image.m_planeRowStride2 = stride;
            image.m_planeRowStride3 = stride;

            image.m_format = colorImageData.format;
            image.m_timestampNs = Convert.ToInt64(colorImageData.timestamp / Common.SECS_PER_NANOSECS);
            cameraMetadata.m_frameNumber = colorImageData.frame_number;
            cameraMetadata.m_timestampNs = image.m_timestampNs;
        }
#endif
    }
}


text:
package androidx.mediarouter.app;

import static androidx.mediarouter.media.MediaRouter.RouteInfo.CONNECTION_STATE_CONNECTED;
import static androidx.mediarouter.media.MediaRouter.RouteInfo.CONNECTION_STATE_CONNECTING;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatDialog;
import androidx.mediarouter.R;
import androidx.mediarouter.media.MediaRouteSelector;
import androidx.mediarouter.media.MediaRouter;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * This class implements the route chooser dialog for {@link MediaRouter}.
 *

 * This dialog allows the user to choose a route that matches a given selector.
 *

 *
 * @see MediaRouteButton
 * @see MediaRouteActionProvider
 */
public class MediaRouteChooserDialog extends AppCompatDialog {
    static final String TAG = "MediaRouteChooserDialog";

    // Do not update the route list immediately to avoid unnatural dialog change.
    private static final long UPDATE_ROUTES_DELAY_MS = 300L;
    static final int MSG_UPDATE_ROUTES = 1;

    private final MediaRouter mRouter;
    private final MediaRouterCallback mCallback;

    private TextView mTitleView;
    private MediaRouteSelector mSelector = MediaRouteSelector.EMPTY;
    private ArrayList<MediaRouter.RouteInfo> mRoutes;
    private RouteAdapter mAdapter;
    private ListView mListView;
    private boolean mAttachedToWindow;
    private long mLastUpdateTime;
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message message) {
            switch (message.what) {
                case MSG_UPDATE_ROUTES:
                    updateRoutes((List<MediaRouter.RouteInfo>) message.obj);
                    break;
            }
        }
    };

    public MediaRouteChooserDialog(Context context) {
        this(context, 0);
    }

    public MediaRouteChooserDialog(Context context, int theme) {
        super(context = MediaRouterThemeHelper.createThemedDialogContext(context, theme, false),
                MediaRouterThemeHelper.createThemedDialogStyle(context));
        context = getContext();

        mRouter = MediaRouter.getInstance(context);
        mCallback = new MediaRouterCallback();
    }

    /**
     * Gets the media route selector for filtering the routes that the user can select.
     *
     * @return The selector, never null.
     */
    @NonNull
    public MediaRouteSelector getRouteSelector() {
        return mSelector;
    }

    /**
     * Sets the media route selector for filtering the routes that the user can select.
     *
     * @param selector The selector, must not be null.
     */
    public void setRouteSelector(@NonNull MediaRouteSelector selector) {
        if (selector == null) {
            throw new IllegalArgumentException("selector must not be null");
        }

        if (!mSelector.equals(selector)) {
            mSelector = selector;

            if (mAttachedToWindow) {
                mRouter.removeCallback(mCallback);
                mRouter.addCallback(selector, mCallback,
                        MediaRouter.CALLBACK_FLAG_PERFORM_ACTIVE_SCAN);
            }

            refreshRoutes();
        }
    }

    /**
     * Called to filter the set of routes that should be included in the list.
     *

     * The default implementation iterates over all routes in the provided list and
     * removes those for which {@link #onFilterRoute} returns false.
     *

     *
     * @param routes The list of routes to filter in-place, never null.
     */
    public void onFilterRoutes(@NonNull List<MediaRouter.RouteInfo> routes) {
        for (int i = routes.size(); i-- > 0; ) {
            if (!onFilterRoute(routes.get(i))) {
                routes.remove(i);
            }
        }
    }

    /**
     * Returns true if the route should be included in the list.
     *

     * The default implementation returns true for enabled non-default routes that
     * match the selector.  Subclasses can override this method to filter routes
     * differently.
     *

     *
     * @param route The route to consider, never null.
     * @return True if the route should be included in the chooser dialog.
     */
    public boolean onFilterRoute(@NonNull MediaRouter.RouteInfo route) {
        return !route.isDefaultOrBluetooth() && route.isEnabled()
                && route.matchesSelector(mSelector);
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitleView.setText(title);
    }

    @Override
    public void setTitle(int titleId) {
        mTitleView.setText(titleId);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.mr_chooser_dialog);

        mRoutes = new ArrayList<>();
        mAdapter = new RouteAdapter(getContext(), mRoutes);
        mListView = (ListView)findViewById(R.id.mr_chooser_list);
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(mAdapter);
        mListView.setEmptyView(findViewById(android.R.id.empty));
        mTitleView = findViewById(R.id.mr_chooser_title);

        updateLayout();
    }

    /**
     * Sets the width of the dialog. Also called when configuration changes.
     */
    void updateLayout() {
        getWindow().setLayout(MediaRouteDialogHelper.getDialogWidth(getContext()),
                ViewGroup.LayoutParams.WRAP_CONTENT);
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();

        mAttachedToWindow = true;
        mRouter.addCallback(mSelector, mCallback, MediaRouter.CALLBACK_FLAG_PERFORM_ACTIVE_SCAN);
        refreshRoutes();
    }

    @Override
    public void onDetachedFromWindow() {
        mAttachedToWindow = false;
        mRouter.removeCallback(mCallback);
        mHandler.removeMessages(MSG_UPDATE_ROUTES);

        super.onDetachedFromWindow();
    }

    /**
     * Refreshes the list of routes that are shown in the chooser dialog.
     */
    public void refreshRoutes() {
        if (mAttachedToWindow) {
            ArrayList<MediaRouter.RouteInfo> routes = new ArrayList<>(mRouter.getRoutes());
            onFilterRoutes(routes);
            Collections.sort(routes, RouteComparator.sInstance);
            if (SystemClock.uptimeMillis() - mLastUpdateTime >= UPDATE_ROUTES_DELAY_MS) {
                updateRoutes(routes);
            } else {
                mHandler.removeMessages(MSG_UPDATE_ROUTES);
                mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG_UPDATE_ROUTES, routes),
                        mLastUpdateTime + UPDATE_ROUTES_DELAY_MS);
            }
        }
    }

    void updateRoutes(List<MediaRouter.RouteInfo> routes) {
        mLastUpdateTime = SystemClock.uptimeMillis();
        mRoutes.clear();
        mRoutes.addAll(routes);
        mAdapter.notifyDataSetChanged();
    }

    private final class RouteAdapter extends ArrayAdapter<MediaRouter.RouteInfo>
            implements ListView.OnItemClickListener {
        private final LayoutInflater mInflater;
        private final Drawable mDefaultIcon;
        private final Drawable mTvIcon;
        private final Drawable mSpeakerIcon;
        private final Drawable mSpeakerGroupIcon;

        public RouteAdapter(Context context, List<MediaRouter.RouteInfo> routes) {
            super(context, 0, routes);
            mInflater = LayoutInflater.from(context);
            TypedArray styledAttributes = getContext().obtainStyledAttributes(new int[] {
                    R.attr.mediaRouteDefaultIconDrawable,
                    R.attr.mediaRouteTvIconDrawable,
                    R.attr.mediaRouteSpeakerIconDrawable,
                    R.attr.mediaRouteSpeakerGroupIconDrawable});
            mDefaultIcon = styledAttributes.getDrawable(0);
            mTvIcon = styledAttributes.getDrawable(1);
            mSpeakerIcon = styledAttributes.getDrawable(2);
            mSpeakerGroupIcon = styledAttributes.getDrawable(3);
            styledAttributes.recycle();
        }

        @Override
        public boolean areAllItemsEnabled() {
            return false;
        }

        @Override
        public boolean isEnabled(int position) {
            return getItem(position).isEnabled();
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            if (view == null) {
                view = mInflater.inflate(R.layout.mr_chooser_list_item, parent, false);
            }

            MediaRouter.RouteInfo route = getItem(position);
            TextView text1 = (TextView) view.findViewById(R.id.mr_chooser_route_name);
            TextView text2 = (TextView) view.findViewById(R.id.mr_chooser_route_desc);
            text1.setText(route.getName());
            String description = route.getDescription();
            boolean isConnectedOrConnecting =
                    route.getConnectionState() == CONNECTION_STATE_CONNECTED
                            || route.getConnectionState() == CONNECTION_STATE_CONNECTING;
            if (isConnectedOrConnecting && !TextUtils.isEmpty(description)) {
                text1.setGravity(Gravity.BOTTOM);
                text2.setVisibility(View.VISIBLE);
                text2.setText(description);
            } else {
                text1.setGravity(Gravity.CENTER_VERTICAL);
                text2.setVisibility(View.GONE);
                text2.setText("");
            }
            view.setEnabled(route.isEnabled());

            ImageView iconView = (ImageView) view.findViewById(R.id.mr_chooser_route_icon);
            if (iconView != null) {
                iconView.setImageDrawable(getIconDrawable(route));
            }
            return view;
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            MediaRouter.RouteInfo route = getItem(position);
            if (route.isEnabled()) {
                route.select();
                dismiss();
            }
        }

        private Drawable getIconDrawable(MediaRouter.RouteInfo route) {
            Uri iconUri = route.getIconUri();
            if (iconUri != null) {
                try {
                    InputStream is = getContext().getContentResolver().openInputStream(iconUri);
                    Drawable drawable = Drawable.createFromStream(is, null);
                    if (drawable != null) {
                        return drawable;
                    }
                } catch (IOException e) {
                    Log.w(TAG, "Failed to load " + iconUri, e);
                    // Falls back.
                }
            }
            return getDefaultIconDrawable(route);
        }

        private Drawable getDefaultIconDrawable(MediaRouter.RouteInfo route) {
            // If the type of the receiver device is specified, use it.
            switch (route.getDeviceType()) {
                case  MediaRouter.RouteInfo.DEVICE_TYPE_TV:
                    return mTvIcon;
                case MediaRouter.RouteInfo.DEVICE_TYPE_SPEAKER:
                    return mSpeakerIcon;
            }

            // Otherwise, make the best guess based on other route information.
            if (route instanceof MediaRouter.RouteGroup) {
                // Only speakers can be grouped for now.
                return mSpeakerGroupIcon;
            }
            return mDefaultIcon;
        }
    }

    private final class MediaRouterCallback extends MediaRouter.Callback {
        MediaRouterCallback() {
        }

        @Override
        public void onRouteAdded(MediaRouter router, MediaRouter.RouteInfo info) {
            refreshRoutes();
        }

        @Override
        public void onRouteRemoved(MediaRouter router, MediaRouter.RouteInfo info) {
            refreshRoutes();
        }

        @Override
        public void onRouteChanged(MediaRouter router, MediaRouter.RouteInfo info) {
            refreshRoutes();
        }

        @Override
        public void onRouteSelected(MediaRouter router, MediaRouter.RouteInfo route) {
            dismiss();
        }
    }

    static final class RouteComparator implements Comparator<MediaRouter.RouteInfo> {
        public static final RouteComparator sInstance = new RouteComparator();

        @Override
        public int compare(MediaRouter.RouteInfo lhs, MediaRouter.RouteInfo rhs) {
            return lhs.getName().compareToIgnoreCase(rhs.getName());
        }
    }
}


text:
var nast = require('./nice-ast');
var util = require('util');

/*
Creates an AST node from a plain object.

@class Represents an AST node.

@param {Object} node
  Plain object to use as template for node.
@param {AstNode} [parent]
  Parent node of this node.

@example
var node = new AstNode({type: 'string', value: 'Hello, world!'});
*/
function AstNode(node, parent) {
  /* {AstNode} Parent of this node.*/
  this.parent = parent || null;
  /* {AstNode} Previous sibling of this node. */
  this.prev = null;
  /* {AstNode} Next sibling of this node. */
  this.next = null;
  this._items = {};
  var self = this;
  Object.keys(node).forEach(function (key, i) {
    self[key] = node[key];
  });
}

function getNodeItem(key) {
  if (key in this._items) {
    return this._items[key];
  }
  if (this.parent) {
    return getNodeItem.call(this.parent, key);
  }
  return null;
}

/*
@param key Item key.
@param value Item value.
*/
AstNode.prototype.item = function (key, value) {
/*
@signature Gets an item value from a node. If the node doesn't have the item
key, a recursive search will continue up through the parents.
@returns Value for this item.
*/
  if (typeof value === 'undefined') {
    return getNodeItem.call(this, key);
  }
/*
@signature Sets an item value for a particular node. Node items act like scoped
variables. Values set for a parent node can be seen by children nodes.
*/
  this._items[key] = value;
};

/*
Properly connect siblings to this node.
@param Index of this node.
*/
AstNode.prototype.fix = function (index) {
  var nodes = this.parent.nodes;
  if (index > 0) {
    var prev = nodes[index - 1];
    prev.next = this;
    this.prev = prev;
  } else {
    this.prev = null;
  }
  if (index < nodes.length - 1) {
    var next = nodes[index + 1];
    next.prev = this;
    this.next = next;
  } else {
    this.next = null;
  }
};

/*
Get the index of a node.
@returns {integer}
*/
AstNode.prototype.index = function () {
  if (!this.parent || !this.parent.nodes) {
    return 0;
  }
  var nodes = this.parent.nodes;
  for (var i = 0; i < nodes.length; i++) {
    var child = nodes[i];
    if (child === this) {
      return i;
    }
  }
  return 0;
};

/*
Walk this node and its children, using the registered walk method. When a
node is appended, this is used to run all the rules for the appended node and
its children.
@param {AstNode} node Node to walk.
*/
AstNode.prototype.walk = function (node) {
  if (this._walk) {
    this._walk(node);
  }
}

/*
Insert node after this one.
@param {AstNode} node Node to insert.
*/
AstNode.prototype.after = function (node) {
  node = nast.extendAst(node);
  node.parent = this.parent;
  var nodes = this.parent.nodes;
  var index = this.index();
  nodes.splice(index + 1, 0, node);
  node.fix(index + 1);
  this.walk(node);
};

/*
Insert node before this one.
@param {AstNode} node Node to insert.
*/
AstNode.prototype.before = function (node) {
  if (this.prev) {
    this.prev.after(node);
  } else {
    this.parent.prepend(node);
  }
};

/*
Insert a new child node before any other child nodes.
@param {AstNode} node Node to prepend.
*/
AstNode.prototype.prepend = function (node) {
  node = nast.extendAst(node);
  this.nodes.unshift(node);
  node.parent = this;
  node.fix(0);
  this.walk(node);
};

/*
Insert a new child node after any other child nodes.
@param {AstNode} node Node to append.
*/
AstNode.prototype.append = function (node) {
  node = nast.extendAst(node);
  this.nodes.push(node);
  node.parent = this;
  node.fix(this.nodes.length - 1);
  this.walk(node);
};

/*
Remove this node.
*/
AstNode.prototype.remove = function () {
  this._removed = true;
  var index = this.index();
  this.parent.nodes.splice(index, 1);
  if (this.prev) {
    this.prev.fix(index - 1);
  }
  if (this.next) {
    this.next.fix(index);
  }
};

/*
Return a lisp-like representation of this node. Useful for debugging rules.
Gives you a terse look at the AST.
@returns {string}
*/
AstNode.prototype.lispify = function () {
  return nast.lispify(this);
};

/*
Returns true if this node has everything that node has.
@param {AstNode} node Node that has a subset of nodes/properties.
@returns {boolean}
*/
AstNode.prototype.like = function (node) {
  return nast.like(this, node);
};

/*
Return true if this node is idential to node.
@param {AstNode} node Node that has identical nodes/properties.
@returns {boolean}
*/
AstNode.prototype.equal = function (node) {
  return nast.equal(this, node);
};

/*
Get the PEG parser used to create this AST.
@return PEG parser.
*/
AstNode.prototype.parser = function () {
  var parser = null;
  if (this.grammarFile) {
    parser = nast.parserForGrammar(this.grammarFile);
  } else if (this.parent) {
    return this.parent.parser();
  }
  return parser;
};

/*
Compare this node to some arbitrary source. The source string will be
compiled to an AST, using the same grammar that was used to create this node.
@param {string} source Source code to parse and compare to this node.
*/
AstNode.prototype.likeSource = function (source) {
  var parser = this.parser();
  if (!parser) {
    return false;
  }
  var ast = parser.parse(source);
  var nodes = ast.nodes;
  if (nodes.length !== 1) {
    return false;
  }
  return this.like(nodes[0]);
};

/*
Return an AST without the sibling and parent references.
@returns {Object} Plain object.
*/
AstNode.prototype.ast = function () {
  return nast.cleanAst(this);
};

/*
Create an AST from source code.
@param {string} source Source code.
@returns {Object} AST.
*/
AstNode.prototype.fromSource = function (source) {
  var parser = this.parser();
  var ast = parser.parse(source);
  var node = ast.nodes[0];
  nast.walk(node, function (node) {
    delete node.pos;
    delete node.comments;
  });
  return node;
};

/*
Create an AST node from source code.
@param {string} source Source code.
@returns {Object} AST node.
*/
AstNode.prototype.nodeFromSource = function (source) {
  var node = this.fromSource(source);
  return nast.extendAst(node);
};

module.exports = AstNode;


text:
class TwitterSubscriber < ActionSubscriber::Base
  def tweet
    $messages << {
      :decoded => payload,
      :raw => raw_payload,
    }
  end
end

describe "Payload Decoding", :integration => true do
  let(:connection) { subscriber.connection }
  let(:draw_routes) do
    ::ActionSubscriber.draw_routes do
      default_routes_for TwitterSubscriber
    end
  end
  let(:subscriber) { TwitterSubscriber }
  let(:json_string) { '{"foo": "bar"}' }

  it "decodes json by default" do
    ::ActionSubscriber.start_subscribers!
    ::ActivePublisher.publish("twitter.tweet", json_string, "events", :content_type => "application/json")

    verify_expectation_within(2.0) do
      expect($messages).to eq Set.new([{
        :decoded => JSON.parse(json_string),
        :raw => json_string,
      }])
    end
  end

  context "Custom Decoder" do
    let(:content_type) { "foo/type" }

    before { ::ActionSubscriber.config.add_decoder(content_type => lambda{ |payload| :foo }) }
    after { ::ActionSubscriber.config.decoder.delete(content_type) }

    it "it decodes the payload using the custom decoder" do
      ::ActionSubscriber.start_subscribers!
      ::ActivePublisher.publish("twitter.tweet", json_string, "events", :content_type => content_type)

      verify_expectation_within(2.0) do
        expect($messages).to eq Set.new([{
          :decoded => :foo,
          :raw => json_string,
        }])
      end
    end
  end
end


text:
import * as React from 'react'
import { ApplicationTheme, getThemeName } from './lib/application-theme'

interface IAppThemeProps {
  readonly theme: ApplicationTheme
}

/**
 * A pseudo-component responsible for adding the applicable CSS
 * class names to the body tag in order to apply the currently
 * selected theme.
 *
 * This component is a PureComponent, meaning that it'll only
 * render when its props changes (shallow comparison).
 *
 * This component does not render anything into the DOM, it's
 * purely (a)busing the component lifecycle to manipulate the
 * body class list.
 */
export class AppTheme extends React.PureComponent<IAppThemeProps> {
  public componentDidMount() {
    this.ensureTheme()
  }

  public componentDidUpdate() {
    this.ensureTheme()
  }

  public componentWillUnmount() {
    this.clearThemes()
  }

  private ensureTheme() {
    const newThemeClassName = `theme-${getThemeName(this.props.theme)}`
    const body = document.body

    if (body.classList.contains(newThemeClassName)) {
      return
    }

    this.clearThemes()

    body.classList.add(newThemeClassName)
  }

  private clearThemes() {
    const body = document.body

    for (const className of body.classList) {
      if (className.startsWith('theme-')) {
        body.classList.remove(className)
      }
    }
  }

  public render() {
    return null
  }
}