text:
<?php
// Get the PHP helper library from https://twilio.com/docs/libraries/php
// following the instructions to install it with Composer.
require_once "vendor/autoload.php";
use Twilio\TwiML\MessagingResponse;

// make an associative array of senders we know, indexed by phone number
$people = array(
    "+14158675308" => "Curious George",
    "+12349013030" => "Boots",
    "+12348134522" => "Virgil",
);

// if the sender is known, then greet them by name
// otherwise, consider them just another monkey
$name = $people[$_REQUEST['From']] ?: 'Monkey';

$response = new MessagingResponse();
$response->message("{$name}, thanks for the message!");

header("content-type: text/xml");
echo $response;


text:
<?xml version="1.0" encoding="UTF-8" ?>
<h:html xmlns:h="http://www.w3.org/1999/xhtml" xmlns:orx="http://openrosa.org/jr/xforms" xmlns="http://www.w3.org/2002/xforms" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:jr="http://openrosa.org/javarosa" xmlns:vellum="http://commcarehq.org/xforms/vellum">
	<h:head>
		<ext vellum:ignore="retain"><content /></ext>
		<h:title>Untitled Form</h:title>
		<model>
			<instance>
				<data xmlns:jrm="http://dev.commcarehq.org/jr/xforms" xmlns="http://openrosa.org/formdesigner/4552C9DD-F297-49CD-8606-AB59AD2C4EA7" uiVersion="1" version="1" name="Untitled Form">
					<question/>
				</data>
			</instance>
			<bind nodeset="/data/question" type="xsd:string"/>
			<itext>
				<translation lang="en" default="">
					<text id="question-label">
						<value>question</value>
					</text>
				</translation>
			</itext>
		</model>
	</h:head>
	<h:body>
		<input ref="/data/question">
			<label ref="jr:itext('question-label')"/>
		</input>
	</h:body>
</h:html>

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace PSU\Rave\Batch;

class ProcessActiveUsersWithMobile extends \PSU\Rave\Batch {
	/*
	 * constructor
	 */
	public function __construct() {
		parent::__construct( 'rave_process_active_users_with_mobile' );
	}//end __construct

	/*
	 * This function is used to load the necessary population
	 */
	public function load() {
		$query = new \PSU\Population\Query\RaveEligibleUsersWithMobile();
		$this->eligible_users = $this->load_population( $query );

		$rb = new \Rave\Batch();
		$this->rave_users = $rb->getEnrollmentReport();
	}//end load

	/*
	 * This function is used to populate the necessary user array for processing.
	 *
	 * @param $records \b override the records to be sent to script utility.  Format: array( $wp_id => $wp_id, etc )
	 */
	public function prepare( $records = null ) {
		if( ! $this->eligible_users || ! $this->rave_users ) {
			$this->load();
		}//end if

		$this->to_process = $this->eligible_users;

		$this->prepare_script_util( $records ?: $this->to_process );
	}//end prepare

	/*
	 * Loop through the array that we have to process, and perform the add action.
	 * I wish there was a way to move the loop logic to the parent class...
	 */
	public function process( $num = 50 ) {
		$select = $this->util->select();

		$selected_users = array_chunk($select, $num, true);

		foreach( (array) $selected_users[0] as $wp_id => $script_info ) {

			$args = array(
				'primary_field' => 'wp_id',
				'primary_field_data' => $wp_id,
			);

			if( $rave_user = \PSU\Rave\User::get( $wp_id ) ) {
				//If the user exists in Rave, but has no phone numbers, lets add their Banner mobile number unconfirmed
				if( $rave_user->phones()->count() === 0 ) {

					$phone_args = array(
						'wp_id' => $wp_id,
						'phone' => $script_info['mobile_number'],
					);
					$phone = new \PSU\Rave\Phone( $phone_args );
					$phone->save('no_confirm');
					try {
						if( $rave_user->save() ) {
							$this->util->delete( $args );
						} else {
							$this->util->set_flag( $args, 'savefail' );
						}//end else
					} catch( \Exception $e ) {
						$this->util->set_flag( $args, 'savefail' );
					}//end catch
				}//end if
			} else {

				try {
					$rave_user = \PSU\Rave\User::create( $wp_id );

					$phone_args = array(
						'wp_id' => $wp_id,
						'phone' => $script_info['mobile_number'],
					);
					$phone = new \PSU\Rave\Phone( $phone_args );
					$phone->save('no_confirm');
					try {
						if( $rave_user->save() ) {
							$this->util->delete( $args );
						} else {
							$this->util->set_flag( $args, 'savefail' );
						}//end else
					} catch( \Exception $e ) {
						$this->util->set_flag( $args, 'savefail' );
					}//end catch
				} catch( \Exception $e ) {
					$this->util->set_flag( $args, 'createfail' );
				}//end catch

				if( $this->debug ) {
					echo ( $rave_user ? 'Created: ' : 'Failed to create: ' ) . $wp_id . "\n";
				}//end if
			}// end else

		}//end foreach

		return count( $this->util->select() );
	}//end process

}//end ProcessActiveUsers


text:
module Jekyll
  require 'less'
  class LessConverter < Converter
    safe true
    priority :normal

    def matches(ext)
      ext =~ /less/i
    end

    def output_ext(ext)
      ".css"
    end

    def convert(content)
      begin
        Less::Parser.new.parse(content).to_css
      rescue StandardError => e
        puts "Less error:" + e.message
      end
    end
  end
end


text:
(function() {
  'use strict';
  //jshint latedef: nofunc
  angular
    .module('cloudscalers.controllers')
    .controller('AuthenticatedSessionController', AuthenticatedSessionController);

  function AuthenticatedSessionController($scope, User, Account, CloudSpace, LoadingDialog,
    $route, $window, $timeout, $location, ipCookie, $ErrorResponseAlert) {

    $scope.setCurrentCloudspace = setCurrentCloudspace;
    $scope.checkDisabledAccount = checkDisabledAccount;
    $scope.setCurrentAccount = setCurrentAccount;
    $scope.loadSpaces = loadSpaces;
    $scope.invalidAccount = invalidAccount;
    $scope.getUserAccessOnAccount = getUserAccessOnAccount;
    $scope.logout = logout;
    $scope.noAccount = false;
    $scope.$on('$routeChangeStart', function() {
      $scope.isDocs = $location.path().search('/Docs') !== -1 ? 'True' : 'False';
    });

    var portalSessionCookie = ipCookie('beaker.session.id');
    var vdccontrol = JSON.parse(localStorage.getItem('vdccontrol'));
    var jwt = vdccontrol.json_web_token;
    var vdc_id = vdccontrol.vdc_id;

    // Binding and Watch
    $scope.$watchCollection('cloudspaces', cloudspaces, true);
    $scope.$watchCollection('currentAccount.id + currentAccount.userRightsOnAccount', CurrentAccountIdAndUserRights);
    $scope.$watchCollection('currentSpace', currentSpace, true);

    // Initialization: Functions invokation logic
    checkUserAccountAccessibility();

    // Functions
    function checkUserAccountAccessibility() {
  if (portalSessionCookie || jwt) {
    if (!User.current() || User.current().api_key !== portalSessionCookie) {
      User.getPortalLoggedinUser().then(function(user) {
        var username;
        if (typeof user === 'string') {
           $scope.admin = false;
           username = user;
        } else {
           $scope.admin = user.admin;
           username = user.name;
        }
        if (username !== 'guest') {
          autoLogin(username);
        }
        $scope.loadSpaces();
      }, function(reason) {
        $scope.loginError = reason.status;
      });

    }else {
      autoLogin(User.current().username);
      $scope.loadSpaces();
    }
  }
}

    function setInitialAccount() {
      if ($scope.currentSpace) {
        $scope.currentAccount = {
          id: $scope.currentSpace.accountId,
          name: $scope.currentSpace.accountName,
          userRightsOnCloudspace: $scope.currentSpace.acl,
          userRightsOnAccountBilling: $scope.currentSpace.userRightsOnAccountBilling
        };
      }else {
        $scope.currentAccount = {id: ''};
      }
    }

    function autoLogin(username) {
      User.portalLogin(username, portalSessionCookie);
      $scope.currentUser = User.current();
      $scope.currentUser.acl = {account: 0, cloudspace: 0, machine: 0};
      var currentCloudSpace = CloudSpace.current();
      if (vdc_id && currentCloudSpace && currentCloudSpace.id != vdc_id) {
         currentCloudSpace = null;
      }
      $scope.currentSpace = currentCloudSpace;
      setInitialAccount();
    }
    function setCurrentCloudspace(space) {
      var accountId = null;
      if (space !== null && space !== undefined) {
         accountId = space.accountId;
      }
      CloudSpace.setCurrent(space);
      $scope.currentSpace = space;
      $scope.setCurrentAccount(accountId);
    }
    function checkDisabledAccount(status) {
      $scope.visibility = 'show';
      if (status === 'DISABLED') {
        _.each($scope.currentUser.acl , function(value, key) {
          $scope.currentUser.acl[key] = 1;
        });
      }
    }
    function setCurrentAccount(currentAccountId) {
      $scope.currentAccount.userRightsOnAccount = {};
      if (currentAccountId) {
        Account.get(currentAccountId).then(function(account) {
          $scope.currentAccount = account;
          $scope.currentAccount.userRightsOnAccount = account.acl;
          $scope.checkDisabledAccount(account.status);
        }, function(reason) {
          if (reason.status === 403) {
            $scope.currentUser.acl.account = 0;
            setInitialAccount();
          }else {
            $ErrorResponseAlert(reason);
          }
        });
      }
    }
    function loadSpaces() {
      if ($scope.currentUser === undefined) {
        return []; //return empty list when not logged in
      }
      return CloudSpace.list().then(function(cloudspaces) {
        $scope.cloudspaces = cloudspaces;
        return cloudspaces;
      }, function(reason) {
        $ErrorResponseAlert(reason);
      });
    }
    function invalidAccount() {
      $window.location = '/';
    }
    function cloudspaces() {
      if (!$scope.cloudspaces) {return;}

      var currentCloudSpaceFromList;
      if ($scope.currentSpace || vdc_id) {
        var searchfor = vdc_id || $scope.currentSpace.id;
        currentCloudSpaceFromList = _.find($scope.cloudspaces, function(cloudspace) {
          return cloudspace.id === searchfor;
        });
        if (vdc_id && !currentCloudSpaceFromList) {
           // when vdc_id is asked and not found dont select anything
           $scope.currentSpace = null;
           return;
        }
      }
      if (!currentCloudSpaceFromList) {
        currentCloudSpaceFromList = _.first($scope.cloudspaces);
      }
      $scope.setCurrentCloudspace(currentCloudSpaceFromList);
    }
    function getUserAccessOnAccount() {
      if ($scope.currentAccount.userRightsOnAccount) {
        var userInCurrentAccount = _.find($scope.currentAccount.userRightsOnAccount , function(acl) {
          return acl.userGroupId === $scope.currentUser.username;
        });
        $scope.currentUser.acl.account = 0;
        if (userInCurrentAccount) {
          var currentUserAccessrightOnAccount = userInCurrentAccount.right.toUpperCase();
          if (currentUserAccessrightOnAccount === 'R') {
            $scope.currentUser.acl.account = 1;
          }else if (currentUserAccessrightOnAccount.search(/R|C|X/) !== -1 &&
            currentUserAccessrightOnAccount.search(/D|U/) === -1) {
            $scope.currentUser.acl.account = 2;
          }else if (currentUserAccessrightOnAccount.search(/R|C|X|D|U/) !== -1) {
            $scope.currentUser.acl.account = 3;
          }
        }
      }
    }
    function CurrentAccountIdAndUserRights() {
      if ($scope.currentAccount && $scope.currentAccount.status !== 'DISABLED') {
        $scope.getUserAccessOnAccount();
      }
    }
    function logout() {
      User.logout();
      var uri = new URI($window.location);
      uri.filename('');
      uri.fragment('');
      $window.location = uri.toString();
    }
    function currentSpace() {
      if ($scope.currentSpace && $scope.currentUser) {
        CloudSpace.get($scope.currentSpace.id).then(function(data) {
          if ($scope.currentSpace.acl.length !== data.acl.length) {
            $scope.currentSpace.acl = data.acl;
          }
          $scope.setCurrentAccount($scope.currentSpace.accountId);
        }, function(reason) {
                if (reason.status === 403) {
                  $scope.currentUser.acl.cloudspace = 0;
                }
              });
        if ($scope.currentUser.username && $scope.currentSpace.acl) {
          var currentUserAccessright = _.find($scope.currentSpace.acl , function(acl) {
            return acl.userGroupId === $scope.currentUser.username;
          });
          if (currentUserAccessright) {
            currentUserAccessright = currentUserAccessright.right.toUpperCase();
            if (currentUserAccessright === 'R') {
              $scope.currentUser.acl.cloudspace = 1;
            }else if (currentUserAccessright.search(/R|C|X/) !== -1 && currentUserAccessright.search(/D|U/) === -1) {
              $scope.currentUser.acl.cloudspace = 2;
            }else if (currentUserAccessright.search(/R|C|X|D|U/) !== -1) {
              $scope.currentUser.acl.cloudspace = 3;
            }
          }
        }
        $scope.getUserAccessOnAccount();
      }
    }
  }
})();


text:
//
// This code was auto-generated by AFNOR StoredProcedureSystem, version 1.0
//

using System;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;

namespace Bivi.Domaine
{
    public partial class TypeRenduBlocChamps
    {

        [DataMember]
        public long ID { get; set; }

        [DataMember]
        public virtual TypeRenduBloc TypeRenduBloc { get; set; }

        [DataMember]
        public long TypeRenduBlocID { get; set; }

        [DataMember]
		[StringLength(200)]
        public string Code { get; set; }

        [DataMember]
		[StringLength(200)]
        public string Libelle { get; set; }

        [DataMember]
        public bool Hidden { get; set; }
    }
}


text:
<!DOCTYPE HTML>

<title>Source code</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="source: package: com.restfb.types.whatsapp, class: WABAOnBehalfOfComputedInfo">
<meta name="generator" content="javadoc/SourceToHTMLConverter">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

001// Generated by delombok at Tue Sep 27 22:25:18 CEST 2022
002
023package com.restfb.types.whatsapp;
024
025import com.restfb.Facebook;
026import com.restfb.types.NamedFacebookType;
027
028public class WABAOnBehalfOfComputedInfo extends NamedFacebookType {
029  @Facebook
030  private String status;
031
032  @java.lang.SuppressWarnings("all")
033  public String getStatus() {
034    return this.status;
035  }
036
037  @java.lang.SuppressWarnings("all")
038  public void setStatus(final String status) {
039    this.status = status;
040  }
041}


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

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RESTART_PACKAGES"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name="com.yxp.uninstall.listen.UninstallReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.PACKAGE_ADDED" />
                <action android:name="android.intent.action.PACKAGE_REMOVED" />
                <action android:name="android.intent.action.PACKAGE_REPLACED" />
                <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
                <data android:scheme="package" />
            </intent-filter>
        </receiver>
    </application>

</manifest>


text:
import LocaleToggle, { mapDispatchToProps } from '../index';
import { changeLocale } from '../../LanguageProvider/actions';
import LanguageProvider from '../../LanguageProvider';

import expect from 'expect';
import { shallow, mount } from 'enzyme';
import configureStore from '../../../store';
import React from 'react';
import { Provider } from 'react-redux';
import { browserHistory } from 'react-router';
import { translationMessages } from '../../../i18n';

describe('<LocaleToggle />', () => {
  let store;

  before(() => {
    store = configureStore({}, browserHistory);
  });

  it('should render the default language messages', () => {
    const renderedComponent = shallow(
      <Provider store={store}>
        <LanguageProvider messages={translationMessages}>
          <LocaleToggle />
        </LanguageProvider>
      </Provider>
    );
    expect(renderedComponent.contains(<LocaleToggle />)).toEqual(true);
  });

  it('should present the default `en` english language option', () => {
    const renderedComponent = mount(
      <Provider store={store}>
        <LanguageProvider messages={translationMessages}>
          <LocaleToggle />
        </LanguageProvider>
      </Provider>
    );
    expect(renderedComponent.contains(<option value="en">EN</option>)).toEqual(true);
  });

  describe('mapDispatchToProps', () => {
    describe('onLocaleToggle', () => {
      it('should be injected', () => {
        const dispatch = expect.createSpy();
        const result = mapDispatchToProps(dispatch);
        expect(result.onLocaleToggle).toExist();
      });

      it('should dispatch changeLocale when called', () => {
        const dispatch = expect.createSpy();
        const result = mapDispatchToProps(dispatch);
        const locale = 'de';
        const evt = { target: { value: locale } };
        result.onLocaleToggle(evt);
        expect(dispatch).toHaveBeenCalledWith(changeLocale(locale));
      });
    });
  });
});


text:
/**
 * The main app singleton used throughout the app.
 * @class core
 * @singleton
 */
var Alloy = require("alloy");

var App = {
	/**
	 * Device information
	 * @type {Object}
	 * @param {String} version The version of the OS
	 * @param {Number} versionMajor The major version of the OS
	 * @param {Number} versionMinor The minor version of the OS
	 * @param {Number} width The width of the device screen
	 * @param {Number} height The height of the device screen
	 * @param {Number} dpi The DPI of the device screen
	 * @param {String} orientation The device orientation, either "landscape" or "portrait"
	 * @param {String} statusBarOrientation A Ti.UI orientation value
	 */
	Device: {
		version: Ti.Platform.version,
		versionMajor: parseInt(Ti.Platform.version.split(".")[0], 10),
		versionMinor: parseInt(Ti.Platform.version.split(".")[1], 10),
		width: null,
		height: null,
		dpi: Ti.Platform.displayCaps.dpi,
		orientation: Ti.Gesture.orientation == Ti.UI.LANDSCAPE_LEFT || Ti.Gesture.orientation == Ti.UI.LANDSCAPE_RIGHT ? "landscape" : "portrait"
	},
	/**
	 * Sets up the app singleton and all it's child dependencies.
	 * **NOTE: This should only be fired in index controller file and only once.**
	 */
	init: function() {
		// Global system Events
		Ti.Network.addEventListener("change", App.networkChange);
		Ti.App.addEventListener("pause", App.exit);
		Ti.App.addEventListener("close", App.exit);
		Ti.App.addEventListener("resumed", App.resume);
		Ti.Gesture.addEventListener("orientationchange", App.orientationChange);

		if(OS_ANDROID) {
			Ti.Android.currentActivity.addEventListener("resume", App.resume);
		}

		// Get device dimensions
		App.getDeviceDimensions();
	},
	/**
	 * Handle cross platform way of opening a main screen.
	 *
	 * See example:
	 * 		var login = Alloy.createController("login");
	 * 		App.openScreen(login);
	 *
	 * or if you don't need the controller reference:
	 * 		App.openScreen("login");
	 *
	 * This is a simplified, app-wide navigation
	 * example which auto-adds a window to the controller.
	 * More could be added here depending on the navigation requirements.
	 * For instance, if you have a navgroup for handheld, you could open it in that
	 * for iOS and differently in Android, etc.
	 *
	 * @param {Controllers/String} _controller
	 * @param {Object} _controllerArguments The arguments for the controller (optional)
	 */
	openScreen: function(_controller, _controllerArguments) {
		var controller = null;

		if(typeof _controller === "string") {
			controller = Alloy.createController(_controller, _controllerArguments);
		} else {
			controller = _controller;
		}

		// In this example we add a window to a controller
		// opened via `openScreen`. Keeping windows out of the
		// UI architecture keep the Views flexible.
		controller.window = Ti.UI.createWindow({
			backgroundColor: Alloy.CFG.windowBackgroundColor,
			statusBarStyle: OS_IOS ? Ti.UI.iPhone.StatusBar.LIGHT_CONTENT : null,
			navBarHidden: true,
			orientationModes: [
				Ti.UI.LANDSCAPE_LEFT,
				Ti.UI.LANDSCAPE_RIGHT
			]
		});

		controller.window.add(controller.wrapper);

		// Set views for current orientation
		App.setViewsForOrientation(controller);

		// Bind orientation events for this controller instance
		App.bindOrientationEvents(controller);

		controller.window.open();
	},
	/**
	 * Helper to bind the orientation events to a controller. These get added automatically
	 * for every controller opened via {@link core#openScreen} which have a public `handleOrientation` method.
	 *
	 * **NOTE** It is VERY important this is
	 * managed right because we're adding global events. They must be removed
	 * or a leak can happen because of all the closures. We could slightly
	 * reduce the closures if we placed these in the individual controllers
	 * but then we're duplicating code. This keeps the controllers clean. Currently,
	 * this method will _add_ and _remove_ the global events, so things should go
	 * out of scope and GC'd correctly.
	 *
	 * @param {Controllers} _controller The controller to bind the orientation events
	 */
	bindOrientationEvents: function(_controller) {
		_controller.window.addEventListener("close", function() {
			if(_controller.handleOrientation) {
				Ti.App.removeEventListener("orientationChange", _controller.handleOrientation);
			}
		});

		_controller.window.addEventListener("open", function() {
			Ti.App.addEventListener("orientationChange", function(_event) {
				if(_controller.handleOrientation) {
					_controller.handleOrientation(_event);
				}

				App.setViewsForOrientation(_controller);
			});
		});
	},
	/**
	 * Update views for current orientation helper
	 *
	 * We're doing this because Alloy does not have support for
	 * orientation support in tss files yet. In order not to duplicate
	 * a ton of object properties, hardcode them, etc. we're using this method.
	 *
	 * Once Alloy has orientation support (e.g. `#myElement[orientation=landscape]`), this
	 * can be removed and the tss reworked.
	 *
	 * All that has to be done is implement the following structure in a `.tss` file:
	 * 		"#myElement": {
	 * 			landscape: { backgroundColor: "red" },
	 * 			portrait: { backgroundColor: "green" }
	 * 		}
	 *
	 * @param {Controllers} _controller
	 */
	setViewsForOrientation: function(_controller) {
		if(!App.Device.orientation) {
			return;
		}

		// Restricted the UI for portrait and landscape orientation
		if(App.Device.orientation == "portrait" || App.Device.orientation == "landscape") {
			for(var view in _controller.__views) {
				if(_controller.__views[view][App.Device.orientation] && typeof _controller.__views[view].applyProperties == "function") {
					_controller.__views[view].applyProperties(_controller.__views[view][App.Device.orientation]);
				} else if(_controller.__views[view].wrapper && _controller.__views[view].wrapper[App.Device.orientation] && typeof _controller.__views[view].applyProperties == "function") {
					_controller.__views[view].applyProperties(_controller.__views[view].wrapper[App.Device.orientation]);
				}
			}
		}
	},
	/**
	 * Global network event handler
	 * @param {Object} _event Standard Ti callback
	 */
	networkChange: function(_event) {

	},
	/**
	 * Exit event observer
	 * @param {Object} _event Standard Ti callback
	 */
	exit: function(_event) {

	},
	/**
	 * Resume event observer
	 * @param {Object} _event Standard Ti callback
	 */
	resume: function(_event) {

	},
	/**
	 * Handle the orientation change event callback
	 * @param {Object} _event Standard Ti Callback
	 */
	orientationChange: function(_event) {
		// Ignore face-up, face-down and unknown orientation
		if(_event.orientation === Titanium.UI.FACE_UP || _event.orientation === Titanium.UI.FACE_DOWN || _event.orientation === Titanium.UI.UNKNOWN) {
			return;
		}

		App.Device.orientation = _event.source.isLandscape() ? "landscape" : "portrait";

		/**
		 * Fires an event for orientation change handling throughout the app
		 * @event orientationChange
		 */
		Ti.App.fireEvent("orientationChange", {
			orientation: App.Device.orientation
		});
	},
	/**
	 * Determines the device dimensions
	 */
	getDeviceDimensions: function() {
		// Set device height and width based on orientation
		switch(App.Device.orientation) {
			case "portrait":
				App.Device.width = Ti.Platform.displayCaps.platformWidth > Ti.Platform.displayCaps.platformHeight ? Ti.Platform.displayCaps.platformHeight : Ti.Platform.displayCaps.platformWidth;
				App.Device.height = Ti.Platform.displayCaps.platformWidth > Ti.Platform.displayCaps.platformHeight ? Ti.Platform.displayCaps.platformWidth : Ti.Platform.displayCaps.platformHeight;
				break;
			case "landscape":
				App.Device.width = Ti.Platform.displayCaps.platformWidth > Ti.Platform.displayCaps.platformHeight ? Ti.Platform.displayCaps.platformWidth : Ti.Platform.displayCaps.platformHeight;
				App.Device.height = Ti.Platform.displayCaps.platformWidth > Ti.Platform.displayCaps.platformHeight ? Ti.Platform.displayCaps.platformHeight : Ti.Platform.displayCaps.platformWidth;
				break;
		}

		// Convert dimensions from DP to PX for Android
		if(OS_ANDROID) {
			App.Device.width = (App.Device.width / (App.Device.dpi / 160));
			App.Device.height = (App.Device.height / (App.Device.dpi / 160));
		}
	}
};

module.exports = App;


text:
'use strict';

var colors = require('colors');
var _ = require('lodash');

var Log = require('./lib/log').Log;
var log = new Log({
  log: '[LOG] %s',
  info: '[INFO] %s'.cyan,
  debug: '[DEBUG] %s'.magenta,
  warn: '[WARN] %s'.yellow,
  error: '[ERROR] %s'.red,
});

log.event.onAny(console.log);

var through = require('through');

log.muxer = function() {
  var muxers = {};
  var progressState = {};
  var logLevels = log.getLevels(Object.keys(log.levels), arguments);
  logLevels.forEach(function(name) {
    var muxer = muxers[name] = new log.Muxer({progressState: progressState});
    log.event.on(name, function(data) {
      muxer.write(log.levels[data.level].formatString, data.args); // allow per-muxer formatString override
    });
  });

  var inMuxer = new log.Muxer({progressState: progressState});
  function filter() {
    var filtered = through();
    filtered.logLevels = log.getLevels(logLevels, arguments);
    filtered.logLevels.forEach(function(name) {
      muxers[name].stream.pipe(filtered);
    });
    if (_.toArray(arguments).indexOf('_input') !== -1) {
      inMuxer.stream.pipe(filtered);
    }
    filtered.filter = filter;
    return filtered;
  }
  var muxed = filter();
  // muxed.pipe(inMuxer.stream);
  muxed.filter = filter;
  // // filtered._write = filtered.write;
  // muxed.write = function() {
  //   // inMuxer.stream.write.apply(inMuxer, arguments);
  // };
  return muxed;
};

log.getLevels = function(superset, subset) {
  subset = _.isArray(subset[0]) ? subset[0] : _.toArray(subset);
  var map = _.groupBy(subset, function(s) {
    return /^!/.test(s) ? 'exclude' : 'include';
  });
  var result = map.include ? _.intersection(map.include, superset) : superset;
  if (map.exclude) {
    result = _.difference(result, _.invoke(map.exclude, 'slice', 1));
  }
  return result;
};

// set up streams

/*
var logStdio;
var debugMode = 0;
if (debugMode) {
  logStdio = log.muxer();
  logStdio.filter('debug').pipe(process.stdout);
} else {
  logStdio = log.muxer('!debug');
}
logStdio.filter('_input', 'log', 'info').pipe(process.stdout);
logStdio.filter('warn', 'error').pipe(process.stderr);
console.log('log.muxer levels:', logStdio.logLevels);
// logStdio.pipe(process.stdout);

log.muxer()
  .pipe(through(function(data) {
    data = colors.stripColors(data);
    data = data.replace(/\r/g, '\n'); // only do this if you want to cat the output file
    this.queue(data);
  }))
  .pipe(require('fs').createWriteStream('tmp/out3.txt'));
*/

// simulation

var cmds = [
  log.log.bind(log, 'This is a test log message.'),
  log.info.bind(log, 'This is a test info message.'),
  log.debug.bind(log, 'This is a test debug message.'),
  log.warn.bind(log, 'This is a test warning message.'),
  log.error.bind(log, 'This is a test error message.'),
  log.log.bind(log, 'Testing log %s: %d, %j.', 'A', 123, {a: 1}),
  log.info.bind(log, 'Testing info %s: %d, %j.', 'A', 123, {a: 1}),
  log.debug.bind(log, 'Testing debug %s: %d, %j.', 'A', 123, {a: 1}),
  log.warn.bind(log, 'Testing warning %s: %d, %j.', 'A', 123, {a: 1}),
  log.error.bind(log, 'Testing error %s: %d, %j.', 'A', 123, {a: 1}),
];

var done;
var id1 = setInterval(function() {
  var cmd = cmds.shift();
  if (cmd) {
    cmd();
  } else {
    clearInterval(id1);
    done = true;
  }
}, 200);

// var p = log.log.progress('Progress...');
// var max = 33;
// var counter = 0;
// var id2 = setInterval(function() {
//   p.update(++counter, max);
//   if (counter === max) {
//     p.done('OK');
//     clearInterval(id2);
//   }
// }, 50);

// var split = require('split');
// var noise = through();
// noise.pipe(logStdio);
// // noise.pipe(process.stdout);
// var noiseCounter = 0;
// var id = setInterval(function() {
//   if (done) {
//     clearInterval(id);
//     noise.end();
//     console.log('noise total =', noiseCounter);
//   } else {
//     noiseCounter++;
//     noise.write('noise[' + noiseCounter + '] ' + (noiseCounter % 5 === 0 ? '<BR>\n' : ''));
//   }
// }, 35);

// node log2_example.js; echo ---; cat tmp/out3.txt
// node log2_example.js >/dev/null; echo ---; cat tmp/out3.txt
// node log2_example.js 2>/dev/null; echo ---; cat tmp/out3.txt


text:
DOWNLOAD=true

# This will cause the script to run in a loop so that the bot auto-restarts
# when you use the shutdown command
LOOP=true

download() {
    if [ $DOWNLOAD == true ]; then
        URL=$(curl -s https://api.github.com/repos/jagrosh/MusicBot/releases/latest \
           | grep -i browser_download_url.*\.jar \
           | sed 's/.*\(http.*\)"/\1/')
        FILENAME=$(echo $URL | sed 's/.*\/\([^\/]*\)/\1/')
        if [ -f $FILENAME ]; then
            echo "Latest version already downloaded (${FILENAME})"
        else
            curl -L $URL -o $FILENAME
        fi
    fi
}

run() {
    java -Dnogui=true -jar $(ls -t JMusicBot* | head -1)
}

while
    download
    run
    $LOOP
do
    continue
done


text:
package gov.nara.nwts.ftapp.filter;

/**
 * Default filter which accepts all files
 * @author TBrady
 *
 */
public class DefaultFileTestFilter implements FileTestFilter {

	public String getName() {
		return "All Files";
	}
	public String getContains() {
		return "";
	}
	public String getPrefix() {
		return "";
	}

	public String getExclusion() {
		return "";
	}

	public String getSuffix() {
		return "";
	}
	public boolean isRePrefix() {
		return false;
	}
	public boolean isReContains() {
		return false;
	}
	public boolean isReSuffix() {
		return false;
	}
	public boolean isReExclusion() {
		return false;
	}

	public String getShortName() {
		return getName();
	}

	public String getShortNameNormalized() {
		return getShortName().replaceAll("[\\s&]","");
	}
	public String getShortNameFormatted() {
		StringBuffer buf = new StringBuffer();
		buf.append(getShortNameNormalized());
		buf.append("                     ");
		return buf.substring(0,20);
	}
}


text:
package org.locationtech.geomesa.memory.cqengine.datastore

import java.util

import com.typesafe.scalalogging.LazyLogging
import org.geotools.data.Query
import org.geotools.data.store.{ContentDataStore, ContentEntry, ContentFeatureSource}
import org.geotools.feature.NameImpl
import org.locationtech.geomesa.memory.cqengine.GeoCQEngine
import org.opengis.feature.`type`.Name
import org.opengis.feature.simple.SimpleFeatureType

import scala.collection.JavaConversions._

class GeoCQEngineDataStore(useGeoIndex: java.lang.Boolean
                          ) extends ContentDataStore with LazyLogging {
  logger.info(s"useGeoIndex=$useGeoIndex")

  val namesToEngine = new java.util.concurrent.ConcurrentHashMap[String, GeoCQEngine]()

  override def createFeatureSource(entry: ContentEntry): ContentFeatureSource = {
    val engine = namesToEngine.get(entry.getTypeName)
    if (engine != null) {
      new GeoCQEngineFeatureStore(engine, entry, Query.ALL)
    } else {
      null
    }
  }

  override def createTypeNames(): util.List[Name] = { namesToEngine.keys().toList.map { new NameImpl(_) } }

  override def createSchema(featureType: SimpleFeatureType): Unit = {
    namesToEngine.putIfAbsent(
      featureType.getTypeName,
      new GeoCQEngine(featureType, enableGeomIndex=useGeoIndex))
  }
}

object GeoCQEngineDataStore {
  lazy val engine = new GeoCQEngineDataStore(useGeoIndex=true)
  lazy val engineNoGeoIndex = new GeoCQEngineDataStore(useGeoIndex=false)
}


text:
package com.intellij.internal.statistic.configurable;

import com.intellij.internal.statistic.StatisticsBundle;
import com.intellij.internal.statistic.StatisticsUploadAssistant;
import com.intellij.internal.statistic.connect.StatisticsService;
import com.intellij.internal.statistic.persistence.UsageStatisticsPersistenceComponent;
import com.intellij.openapi.application.ApplicationInfo;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.util.ui.UIUtil;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map;

public class StatisticsConfigurationComponent {

  private JPanel myMainPanel;
  private JLabel myTitle;
  private JCheckBox myAllowToSendUsagesCheckBox;
  private JRadioButton myDailyRadioButton;
  private JRadioButton myMonthlyRadioButton;
  private JRadioButton myWeeklyRadioButton;
  private JLabel myLabel;
  private JPanel myRadioButtonPanel;

  public StatisticsConfigurationComponent() {
    String product = ApplicationNamesInfo.getInstance().getFullProductName();
    String company = ApplicationInfo.getInstance().getCompanyName();
    myTitle.setText(StatisticsBundle.message("stats.title", product, company));
    myLabel.setText(StatisticsBundle.message("stats.config.details", company));
    myLabel.setFont(UIUtil.getLabelFont(UIUtil.FontSize.SMALL));

    myAllowToSendUsagesCheckBox.setText(StatisticsBundle.message("stats.config.allow.send.stats.text", company));
    myAllowToSendUsagesCheckBox.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        setRadioButtonsEnabled();
      }
    });

    // Let current statistics service override labels
    StatisticsService service = StatisticsUploadAssistant.getStatisticsService();
    if (service != null) {
      Map<String, String> overrides = service.getStatisticsConfigurationLabels();
      if (overrides != null) {
        String s = overrides.get(StatisticsService.TITLE);
        if (s != null) {
          myTitle.setText(s);
        }
        s = overrides.get(StatisticsService.DETAILS);
        if (s != null) {
          myLabel.setText(s);
        }
        s = overrides.get(StatisticsService.ALLOW_CHECKBOX);
        if (s != null) {
          myAllowToSendUsagesCheckBox.setText(s);
        }
      }
    }

    myTitle.setText(myTitle.getText().replace("%company%", company));
    myLabel.setText(myLabel.getText().replace("%company%", company));
    myAllowToSendUsagesCheckBox.setText(myAllowToSendUsagesCheckBox.getText().replace("%company%", company));
  }

  private void setRadioButtonsEnabled() {
    final boolean enabled = myAllowToSendUsagesCheckBox.isSelected();

    myWeeklyRadioButton.setEnabled(enabled);
    myMonthlyRadioButton.setEnabled(enabled);
    myDailyRadioButton.setEnabled(enabled);
  }

  public JPanel getJComponent() {
    return myMainPanel;
  }

  public boolean isAllowed() {
    return myAllowToSendUsagesCheckBox.isSelected();
  }

  public void reset() {
    final UsageStatisticsPersistenceComponent persistenceComponent = UsageStatisticsPersistenceComponent.getInstance();

    myAllowToSendUsagesCheckBox.setSelected(persistenceComponent.isAllowed());
    setRadioButtonsEnabled();

    final SendPeriod period = persistenceComponent.getPeriod();

    switch (period) {
      case DAILY:
        myDailyRadioButton.setSelected(true);
        break;
      case MONTHLY:
        myMonthlyRadioButton.setSelected(true);
        break;
      default:
        myWeeklyRadioButton.setSelected(true);
        break;
    }
  }

  public SendPeriod getPeriod() {
    if (myDailyRadioButton.isSelected()) return SendPeriod.DAILY;
    if (myMonthlyRadioButton.isSelected()) return SendPeriod.MONTHLY;

    return SendPeriod.WEEKLY;
  }
}


text:
__Warning: deps is in active development; don't use until 1.0 is released__

deps
=======

A general purpose dependency management tool. It is built from the unix philosophy:

> Write programs that do one thing and do it well. Write programs to
> work together. Write programs to handle text streams, because that
> is a universal interface.

The goal of deps is to do one thing and do it well.  The result of its
work will be used by your build tools of choice to build your project.
`deps` only job is to take a list of URLs and download them into a
directory; that's it.

Design
-------

All `deps` does is copy files from some remote location and stick them
in a directory in `deps/`. It does that using a file called
`deps.txt`.

The format of `deps.txt` is extremely simple:

```
deps     git://eric@themoritzfamily.com/~/eric/git/deps.git#develop
nanoweb  https://pypi.python.org/packages/source/n/nanoweb/nanoweb-1.0.tar.gz
wand-0.1 ~/projects/wand-0.1
```

As you can see it is just a list of URLs with a name.

Using this `deps.txt` file, the following directory structure will be
created:

```
deps/
     deptool/
     nanoweb/
     wand-0.1/
```

Algorithm
----------

The `deps` algorithm is to be as explicit as possible on how `deps` works:

1. Enqueue urls from ./deps.txt
2. pop a url from the queue
3. If deps/{name} does not exist, download url to deps/{name}
4. Equeue urls from deps/{name}/deps.txt
5. goto 2 until queue is empty

This algorithm has the following properties:

1. The dependancies are processed
a [breadth first](https://en.wikipedia.org/wiki/File:Animated_BFS.gif) order
2. A dependancy that comes before a duplicate dependancy takes presedence

Why
----

So, why did we choose these properties?  We had two requirements for
our dependancy management system.

First, during development of a product that is composed of multiple
packages, we needed to have a persistant copy of dependancies while
working on a feature. That is why `deps` will never clobber an already
existing dependancy in `deps/`.

Second, we needed to place the decision of version conflicts in the
hands of a parent dependancy.

If two projects have conflicting dependancies, a parent should be able
to choose a version that is compatible with both rather that crash the
build.


text:
package ru.pinkponies.server;

import ru.pinkponies.protocol.Location;

public final class Apple extends Entity {
	/**
	 * The id of the quest to which apple relates.
	 */
	private final long questId;

	public Apple(final long id, final Location location, final long questId) {
		super(id, location);
		this.questId = questId;
	}

	@Override
	public String toString() {
		return "Apple [id=" + this.getId() + ", questId=" + this.questId + ", " + this.getLocation() + "]";
	}
}


text:
'use strict';

angular.module('delbApp')
  .factory('ListService', ['$http', function($http){
    var endpoint = {
      GetListItems:'/api/v1/list.json',
      PostListItem: '/api/v1/list'
    };
    return {
      getListItems: function (returnData) {
        returnData = returnData || {};
        returnData.take = returnData.take || 10;
        returnData.skip = returnData.skip || 0;
        return $http.get(endpoint.GetListItems);
      },
      postListItem: function(title, category, price, description){
        return $http.post(endpoint.PostListItem, {
          title: title,
          category: category,
          price: price,
          description: description
        });
      }
    };
  }]);


text:
const vec3 = require('../math/vec3')
const fromPointAxisNormal = require('./fromPointAxisNormal')

/** Creates a new connector, with the connection point moved in the direction of the axis
 * @param {Number} distance the distance to extend the connector to
 * @param {connector} connector the connector to extend
 * @returns {connector} a normalized connector
 */
const extend = (distance, connector) => {
  const newpoint = vec3.add(connector.point, vec3.scale(distance, vec3.unit(connector.axis)))
  return fromPointAxisNormal(newpoint, connector.axis, connector.normal)
}

module.exports = extend


text:
TODO: Write a gem description

This is a simple API for working with the bulgarian VoiceCom AD service.

At this moment only usable with Rails.

Add this line to your application's Gemfile:

    gem 'voice_com'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install voice_com

## Usage

After installing the gem. You have to create a configuration config/voicecom_config.yml.

A template is give in the gem's repository in templates/voicecom_config.yml.

## Request

  Creating a request object:

    request = VoiceCom::Request.new request_attr

  Attribute accepted by a request object:

  smsid*   : Unique id of the sms **message

  phone*   : Phone number of the receiver

  text*    : The sort text message of the request

  op       : Mobile operator, if none given it will be determined by the phone number

  priority : 1 - height priority / 2 - lower priority

  validity : Sets the short message validity period, default 24 hours

  ** VoiceCom gem builds in an ActiveRecord instance method, with gives an unique sms id,
  created from the records 'database id column' and prefixed with the uppercase letter in the ActiveRecord Class name.

  The config file accepts and an addition value(sms_uniq_id_column). If given the 'uniq_sms_id' return the value in this column.

  Sending the message:

    request.send_message

  The method returns a response string, check VoiceCom documentation for more details.

## Response

  Creating a response object:

    response = VoiceCom::Response.new response_attr

  Attributes for creating a response object:
    :sid, :dlr, :answer, :to, :from, :ts, :smsID, :voicecom_id

  For more information see VoiceCom documentation.

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
namespace ti
{
	class IntroDialog : public Dialog
	{
		protected:
			HWND nameLabel;
			HWND versionLabel;
			HWND publisherLabel;
			HWND urlLabel;
			HWND licenseBlurb;
			HWND licenseTextBox;
			HWND installBox;
			HWND installLocationText;
			HWND installLocationButton;
			HWND startMenuCheck;
			HWND securityBlurb;
			HWND runButton;
			HWND cancelButton;

			void InstallLocationClicked();
			virtual void Initialize(HWND window);
			virtual void ButtonClicked(int id);

		public:
			IntroDialog();

	};
}
#endif


text:
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "media/gpu/chromeos/video_decoder_pipeline.h"

#include <memory>

#include "base/bind.h"
#include "base/containers/contains.h"
#include "base/memory/ptr_util.h"
#include "base/task/post_task.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "build/build_config.h"
#include "gpu/config/gpu_driver_bug_workarounds.h"
#include "media/base/async_destroy_video_decoder.h"
#include "media/base/bind_to_current_loop.h"
#include "media/base/limits.h"
#include "media/base/media_log.h"
#include "media/gpu/chromeos/dmabuf_video_frame_pool.h"
#include "media/gpu/chromeos/image_processor.h"
#include "media/gpu/chromeos/image_processor_factory.h"
#include "media/gpu/chromeos/platform_video_frame_pool.h"
#include "media/gpu/macros.h"
#include "media/media_buildflags.h"
#include "third_party/abseil-cpp/absl/types/optional.h"

#if BUILDFLAG(USE_VAAPI)
#include <drm_fourcc.h>
#include "media/gpu/vaapi/vaapi_video_decoder.h"
#elif BUILDFLAG(USE_V4L2_CODEC)
#include "media/gpu/v4l2/v4l2_video_decoder.h"
#else
#error Either VA-API or V4L2 must be used for decode acceleration on Chrome OS.
#endif

namespace media {
namespace {

using PixelLayoutCandidate = ImageProcessor::PixelLayoutCandidate;

// The number of requested frames used for the image processor should be the
// number of frames in media::Pipeline plus the current processing frame.
constexpr size_t kNumFramesForImageProcessor = limits::kMaxVideoFrames + 1;

// Preferred output formats in order of preference.
// TODO(mcasas): query the platform for its preferred formats and modifiers.
constexpr Fourcc kPreferredRenderableFourccs[] = {
    Fourcc(Fourcc::NV12),
    Fourcc(Fourcc::P010),
    // Only used for Hana (MT8173). Remove when that device reaches EOL.
    Fourcc(Fourcc::YV12),
};

// Picks the preferred compositor renderable format from |candidates|, if any.
// If |preferred_fourcc| is provided, contained in |candidates|, and considered
// renderable, it returns that. Otherwise, it goes through
// |kPreferredRenderableFourccs| until it finds one that's in |candidates|. If
// it can't find a renderable format in |candidates|, it returns absl::nullopt.
absl::optional<Fourcc> PickRenderableFourcc(
    const std::vector<Fourcc>& candidates,
    absl::optional<Fourcc> preferred_fourcc) {
  if (preferred_fourcc && base::Contains(candidates, *preferred_fourcc) &&
      base::Contains(kPreferredRenderableFourccs, *preferred_fourcc)) {
    return preferred_fourcc;
  }
  for (const auto& value : kPreferredRenderableFourccs) {
    if (base::Contains(candidates, value))
      return value;
  }
  return absl::nullopt;
}

}  //  namespace

VideoDecoderMixin::VideoDecoderMixin(
    std::unique_ptr<MediaLog> media_log,
    scoped_refptr<base::SequencedTaskRunner> decoder_task_runner,
    base::WeakPtr<VideoDecoderMixin::Client> client)
    : decoder_task_runner_(std::move(decoder_task_runner)),
      client_(std::move(client)) {}

VideoDecoderMixin::~VideoDecoderMixin() = default;

bool VideoDecoderMixin::NeedsTranscryption() {
  return false;
}

// static
std::unique_ptr<VideoDecoder> VideoDecoderPipeline::Create(
    scoped_refptr<base::SequencedTaskRunner> client_task_runner,
    std::unique_ptr<DmabufVideoFramePool> frame_pool,
    std::unique_ptr<VideoFrameConverter> frame_converter,
    std::unique_ptr<MediaLog> media_log) {
  DCHECK(client_task_runner);
  DCHECK(frame_pool);
  DCHECK(frame_converter);

  CreateDecoderFunctionCB create_decoder_function_cb =
#if BUILDFLAG(USE_VAAPI)
      base::BindOnce(&VaapiVideoDecoder::Create);
#elif BUILDFLAG(USE_V4L2_CODEC)
      base::BindOnce(&V4L2VideoDecoder::Create);
#endif

  auto* pipeline = new VideoDecoderPipeline(
      std::move(client_task_runner), std::move(frame_pool),
      std::move(frame_converter), std::move(media_log),
      std::move(create_decoder_function_cb));
  return std::make_unique<AsyncDestroyVideoDecoder<VideoDecoderPipeline>>(
      base::WrapUnique(pipeline));
}

// static
absl::optional<SupportedVideoDecoderConfigs>
VideoDecoderPipeline::GetSupportedConfigs(
    const gpu::GpuDriverBugWorkarounds& workarounds) {
  absl::optional<SupportedVideoDecoderConfigs> configs =
  // TODO(b/195769334): figure out the best way to query the supported
  // configurations when using an out-of-process video decoder.
#if BUILDFLAG(USE_VAAPI)
      VaapiVideoDecoder::GetSupportedConfigs();
#elif BUILDFLAG(USE_V4L2_CODEC)
      V4L2VideoDecoder::GetSupportedConfigs();
#endif

  if (!configs)
    return absl::nullopt;

  if (workarounds.disable_accelerated_vp8_decode) {
    base::EraseIf(configs.value(), [](const auto& config) {
      return config.profile_min >= VP8PROFILE_MIN &&
             config.profile_max <= VP8PROFILE_MAX;
    });
  }

  if (workarounds.disable_accelerated_vp9_decode) {
    base::EraseIf(configs.value(), [](const auto& config) {
      return config.profile_min >= VP9PROFILE_PROFILE0 &&
             config.profile_max <= VP9PROFILE_PROFILE0;
    });
  }

  if (workarounds.disable_accelerated_vp9_profile2_decode) {
    base::EraseIf(configs.value(), [](const auto& config) {
      return config.profile_min >= VP9PROFILE_PROFILE2 &&
             config.profile_max <= VP9PROFILE_PROFILE2;
    });
  }

  return configs;
}

VideoDecoderPipeline::VideoDecoderPipeline(
    scoped_refptr<base::SequencedTaskRunner> client_task_runner,
    std::unique_ptr<DmabufVideoFramePool> frame_pool,
    std::unique_ptr<VideoFrameConverter> frame_converter,
    std::unique_ptr<MediaLog> media_log,
    CreateDecoderFunctionCB create_decoder_function_cb)
    : client_task_runner_(std::move(client_task_runner)),
      // Note that the decoder thread is created with base::MayBlock(). This is
      // because the underlying |decoder_| may need to allocate a dummy buffer
      // to discover the most native modifier accepted by the hardware video
      // decoder; this in turn may need to open the render node, and this is the
      // operation that may block.
      decoder_task_runner_(base::ThreadPool::CreateSingleThreadTaskRunner(
          {base::WithBaseSyncPrimitives(), base::TaskPriority::USER_VISIBLE,
           base::MayBlock()},
          base::SingleThreadTaskRunnerThreadMode::DEDICATED)),
      main_frame_pool_(std::move(frame_pool)),
      frame_converter_(std::move(frame_converter)),
      media_log_(std::move(media_log)),
      create_decoder_function_cb_(std::move(create_decoder_function_cb)) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(client_sequence_checker_);
  DETACH_FROM_SEQUENCE(decoder_sequence_checker_);
  DCHECK(main_frame_pool_);
  DCHECK(frame_converter_);
  DCHECK(client_task_runner_);
  DVLOGF(2);

  decoder_weak_this_ = decoder_weak_this_factory_.GetWeakPtr();

  main_frame_pool_->set_parent_task_runner(decoder_task_runner_);
  frame_converter_->Initialize(
      decoder_task_runner_,
      base::BindRepeating(&VideoDecoderPipeline::OnFrameConverted,
                          decoder_weak_this_));
}

VideoDecoderPipeline::~VideoDecoderPipeline() {
  // We have to destroy |main_frame_pool_| and |frame_converter_| on
  // |decoder_task_runner_|, so the destructor must be called on
  // |decoder_task_runner_|.
  DCHECK_CALLED_ON_VALID_SEQUENCE(decoder_sequence_checker_);
  DVLOGF(3);

  decoder_weak_this_factory_.InvalidateWeakPtrs();

  main_frame_pool_.reset();
  frame_converter_.reset();
  decoder_.reset();
#if BUILDFLAG(IS_CHROMEOS_ASH)
  buffer_transcryptor_.reset();
#endif  // BUILDFLAG(IS_CHROMEOS_ASH)
}

// static
void VideoDecoderPipeline::DestroyAsync(
    std::unique_ptr<VideoDecoderPipeline> pipeline) {
  DVLOGF(2);
  DCHECK(pipeline);
  DCHECK_CALLED_ON_VALID_SEQUENCE(pipeline->client_sequence_checker_);

  auto* decoder_task_runner = pipeline->decoder_task_runner_.get();
  decoder_task_runner->DeleteSoon(FROM_HERE, std::move(pipeline));
}

VideoDecoderType VideoDecoderPipeline::GetDecoderType() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(client_sequence_checker_);
  // TODO(mcasas): query |decoder_| instead.
#if BUILDFLAG(USE_VAAPI)
  return VideoDecoderType::kVaapi;
#elif BUILDFLAG(USE_V4L2_CODEC)
  return VideoDecoderType::kV4L2;
#else
  return VideoDecoderType::kUnknown;
#endif
}

bool VideoDecoderPipeline::IsPlatformDecoder() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(client_sequence_checker_);

  return true;
}

int VideoDecoderPipeline::GetMaxDecodeRequests() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(client_sequence_checker_);

  // TODO(mcasas): query |decoder_| instead.
  return 4;
}

bool VideoDecoderPipeline::NeedsBitstreamConversion() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(client_sequence_checker_);

  // TODO(mcasas): also query |decoder_|.
  return needs_bitstream_conversion_;
}

bool VideoDecoderPipeline::CanReadWithoutStalling() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(client_sequence_checker_);

  // TODO(mcasas): also query |decoder_|.
  return main_frame_pool_ && !main_frame_pool_->IsExhausted();
}

void VideoDecoderPipeline::Initialize(const VideoDecoderConfig& config,
                                      bool /* low_delay */,
                                      CdmContext* cdm_context,
                                      InitCB init_cb,
                                      const OutputCB& output_cb,
                                      const WaitingCB& waiting_cb) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(client_sequence_checker_);
  VLOGF(2) << "config: " << config.AsHumanReadableString();

  if (!config.IsValidConfig()) {
    VLOGF(1) << "config is not valid";
    std::move(init_cb).Run(DecoderStatus::Codes::kUnsupportedConfig);
    return;
  }
#if BUILDFLAG(USE_CHROMEOS_PROTECTED_MEDIA)
  if (config.is_encrypted() && !cdm_context) {
    VLOGF(1) << "Encrypted streams require a CdmContext";
    std::move(init_cb).Run(DecoderStatus::Codes::kUnsupportedConfig);
    return;
  }
#else   // BUILDFLAG(USE_CHROMEOS_PROTECTED_MEDIA)
  if (config.is_encrypted() && !allow_encrypted_content_for_testing_) {
    VLOGF(1) << "Encrypted streams are not supported for this VD";
    std::move(init_cb).Run(DecoderStatus::Codes::kUnsupportedEncryptionMode);
    return;
  }
  if (cdm_context && !allow_encrypted_content_for_testing_) {
    VLOGF(1) << "cdm_context is not supported.";
    std::move(init_cb).Run(DecoderStatus::Codes::kUnsupportedEncryptionMode);
    return;
  }
#endif  // !BUILDFLAG(USE_CHROMEOS_PROTECTED_MEDIA)

  needs_bitstream_conversion_ = (config.codec() == VideoCodec::kH264) ||
                                (config.codec() == VideoCodec::kHEVC);

  decoder_task_runner_->PostTask(
      FROM_HERE,
      base::BindOnce(&VideoDecoderPipeline::InitializeTask, decoder_weak_this_,
                     config, cdm_context, std::move(init_cb),
                     std::move(output_cb), std::move(waiting_cb)));
}

void VideoDecoderPipeline::InitializeTask(const VideoDecoderConfig& config,
                                          CdmContext* cdm_context,
                                          InitCB init_cb,
                                          const OutputCB& output_cb,
                                          const WaitingCB& waiting_cb) {
  DVLOGF(3);
  DCHECK_CALLED_ON_VALID_SEQUENCE(decoder_sequence_checker_);

  client_output_cb_ = std::move(output_cb);
  waiting_cb_ = std::move(waiting_cb);

  // |decoder_| may be Initialize()d multiple times (e.g. on |config| changes)
  // but can only be created once.
  if (!decoder_ && !create_decoder_function_cb_.is_null()) {
    decoder_ =
        std::move(create_decoder_function_cb_)
            .Run(media_log_->Clone(), decoder_task_runner_, decoder_weak_this_);
  }
  // Note: |decoder_| might fail to be created, e.g. on V4L2 platforms.
  if (!decoder_) {
    OnError("|decoder_| creation failed.");
    client_task_runner_->PostTask(
        FROM_HERE,
        base::BindOnce(std::move(init_cb),
                       DecoderStatus::Codes::kFailedToCreateDecoder));
    return;
  }

  decoder_->Initialize(
      config, /* low_delay=*/false, cdm_context,
      base::BindOnce(&VideoDecoderPipeline::OnInitializeDone,
                     decoder_weak_this_, std::move(init_cb), cdm_context),
      base::BindRepeating(&VideoDecoderPipeline::OnFrameDecoded,
                          decoder_weak_this_),
      base::BindRepeating(&VideoDecoderPipeline::OnDecoderWaiting,
                          decoder_weak_this_));
}

void VideoDecoderPipeline::OnInitializeDone(InitCB init_cb,
                                            CdmContext* cdm_context,
                                            DecoderStatus status) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(decoder_sequence_checker_);
  DVLOGF(4) << "Initialization status = " << static_cast<int>(status.code());

  if (!status.is_ok()) {
    MEDIA_LOG(ERROR, media_log_)
        << "VideoDecoderPipeline |decoder_| Initialize() failed, status: "
        << static_cast<int>(status.code());
    decoder_ = nullptr;
  }
  MEDIA_LOG(INFO, media_log_)
      << "VideoDecoderPipeline |decoder_| Initialize() successful";

#if BUILDFLAG(IS_CHROMEOS_ASH)
  if (decoder_ && decoder_->NeedsTranscryption()) {
    if (!cdm_context) {
      VLOGF(1) << "CdmContext required for transcryption";
      decoder_ = nullptr;
      status = DecoderStatus::Codes::kUnsupportedEncryptionMode;
    } else {
      // We need to enable transcryption for protected content.
      buffer_transcryptor_ = std::make_unique<DecoderBufferTranscryptor>(
          cdm_context,
          base::BindRepeating(&VideoDecoderPipeline::OnBufferTranscrypted,
                              decoder_weak_this_),
          base::BindRepeating(&VideoDecoderPipeline::OnDecoderWaiting,
                              decoder_weak_this_));
    }
  } else {
    // In case this was created on a prior initialization but no longer needed.
    buffer_transcryptor_.reset();
  }
#endif  // BUILDFLAG(IS_CHROMEOS_ASH)

  client_task_runner_->PostTask(FROM_HERE,
                                base::BindOnce(std::move(init_cb), status));
}

void VideoDecoderPipeline::Reset(base::OnceClosure reset_cb) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(client_sequence_checker_);
  DVLOGF(3);

  decoder_task_runner_->PostTask(
      FROM_HERE, base::BindOnce(&VideoDecoderPipeline::ResetTask,
                                decoder_weak_this_, std::move(reset_cb)));
}

void VideoDecoderPipeline::ResetTask(base::OnceClosure reset_cb) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(decoder_sequence_checker_);
  DVLOGF(3);

  need_apply_new_resolution = false;
  decoder_->Reset(base::BindOnce(&VideoDecoderPipeline::OnResetDone,
                                 decoder_weak_this_, std::move(reset_cb)));
}

void VideoDecoderPipeline::OnResetDone(base::OnceClosure reset_cb) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(decoder_sequence_checker_);
  DVLOGF(3);

  if (image_processor_)
    image_processor_->Reset();
  frame_converter_->AbortPendingFrames();

#if BUILDFLAG(IS_CHROMEOS_ASH)
  if (buffer_transcryptor_)
    buffer_transcryptor_->Reset(DecoderStatus::Codes::kAborted);
#endif  // BUILDFLAG(IS_CHROMEOS_ASH)

  CallFlushCbIfNeeded(DecoderStatus::Codes::kAborted);

  if (need_frame_pool_rebuild_) {
    need_frame_pool_rebuild_ = false;
    if (main_frame_pool_)
      main_frame_pool_->ReleaseAllFrames();
    if (auxiliary_frame_pool_)
      auxiliary_frame_pool_->ReleaseAllFrames();
  }

  client_task_runner_->PostTask(FROM_HERE, std::move(reset_cb));
}

void VideoDecoderPipeline::Decode(scoped_refptr<DecoderBuffer> buffer,
                                  DecodeCB decode_cb) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(client_sequence_checker_);
  DVLOGF(4);

  decoder_task_runner_->PostTask(
      FROM_HERE,
      base::BindOnce(&VideoDecoderPipeline::DecodeTask, decoder_weak_this_,
                     std::move(buffer), std::move(decode_cb)));
}

void VideoDecoderPipeline::DecodeTask(scoped_refptr<DecoderBuffer> buffer,
                                      DecodeCB decode_cb) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(decoder_sequence_checker_);
  DCHECK(decoder_);
  DVLOGF(4);

  if (has_error_) {
    client_task_runner_->PostTask(
        FROM_HERE,
        base::BindOnce(std::move(decode_cb), DecoderStatus::Codes::kFailed));
    return;
  }

  const bool is_flush = buffer->end_of_stream();
#if BUILDFLAG(IS_CHROMEOS_ASH)
  if (buffer_transcryptor_) {
    buffer_transcryptor_->EnqueueBuffer(
        std::move(buffer),
        base::BindOnce(&VideoDecoderPipeline::OnDecodeDone, decoder_weak_this_,
                       is_flush, std::move(decode_cb)));
    return;
  }
#endif  // BUILDFLAG(IS_CHROMEOS_ASH)

  decoder_->Decode(
      std::move(buffer),
      base::BindOnce(&VideoDecoderPipeline::OnDecodeDone, decoder_weak_this_,
                     is_flush, std::move(decode_cb)));
}

void VideoDecoderPipeline::OnDecodeDone(bool is_flush,
                                        DecodeCB decode_cb,
                                        DecoderStatus status) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(decoder_sequence_checker_);
  DVLOGF(4) << "is_flush: " << is_flush
            << ", status: " << static_cast<int>(status.code());

  if (has_error_)
    status = DecoderStatus::Codes::kFailed;

  if (is_flush && status.is_ok()) {
    client_flush_cb_ = std::move(decode_cb);
    CallFlushCbIfNeeded(DecoderStatus::Codes::kOk);
    return;
  }

  client_task_runner_->PostTask(
      FROM_HERE, base::BindOnce(std::move(decode_cb), std::move(status)));
}

void VideoDecoderPipeline::OnFrameDecoded(scoped_refptr<VideoFrame> frame) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(decoder_sequence_checker_);
  DCHECK(frame_converter_);
  DVLOGF(4);

  if (image_processor_) {
    image_processor_->Process(
        std::move(frame),
        base::BindOnce(&VideoDecoderPipeline::OnFrameProcessed,
                       decoder_weak_this_));
  } else {
    frame_converter_->ConvertFrame(std::move(frame));
  }
}

void VideoDecoderPipeline::OnFrameProcessed(scoped_refptr<VideoFrame> frame) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(decoder_sequence_checker_);
  DCHECK(frame_converter_);
  DVLOGF(4);

  frame_converter_->ConvertFrame(std::move(frame));
}

void VideoDecoderPipeline::OnFrameConverted(scoped_refptr<VideoFrame> frame) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(decoder_sequence_checker_);
  DVLOGF(4);

  if (!frame)
    return OnError("Frame converter returns null frame.");
  if (has_error_) {
    DVLOGF(2) << "Skip returning frames after error occurs.";
    return;
  }

  // Flag that the video frame is capable of being put in an overlay.
  frame->metadata().allow_overlay = true;
  // Flag that the video frame was decoded in a power efficient way.
  frame->metadata().power_efficient = true;

  // MojoVideoDecoderService expects the |output_cb_| to be called on the client
  // task runner, even though media::VideoDecoder states frames should be output
  // without any thread jumping.
  // Note that all the decode/flush/output/reset callbacks are executed on
  // |client_task_runner_|.
  client_task_runner_->PostTask(
      FROM_HERE, base::BindOnce(client_output_cb_, std::move(frame)));

  // After outputting a frame, flush might be completed.
  CallFlushCbIfNeeded(DecoderStatus::Codes::kOk);
  CallApplyResolutionChangeIfNeeded();
}

void VideoDecoderPipeline::OnDecoderWaiting(WaitingReason reason) {
  DVLOGF(3);
  DCHECK_CALLED_ON_VALID_SEQUENCE(decoder_sequence_checker_);
  if (reason == media::WaitingReason::kDecoderStateLost)
    need_frame_pool_rebuild_ = true;

  client_task_runner_->PostTask(FROM_HERE, base::BindOnce(waiting_cb_, reason));
}

bool VideoDecoderPipeline::HasPendingFrames() const {
  DVLOGF(3);
  DCHECK_CALLED_ON_VALID_SEQUENCE(decoder_sequence_checker_);

  return frame_converter_->HasPendingFrames() ||
         (image_processor_ && image_processor_->HasPendingFrames());
}

void VideoDecoderPipeline::OnError(const std::string& msg) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(decoder_sequence_checker_);
  VLOGF(1) << msg;
  MEDIA_LOG(ERROR, media_log_) << "VideoDecoderPipeline " << msg;

  has_error_ = true;
#if BUILDFLAG(IS_CHROMEOS_ASH)
  if (buffer_transcryptor_)
    buffer_transcryptor_->Reset(DecoderStatus::Codes::kFailed);
#endif  // BUILDFLAG(IS_CHROMEOS_ASH)
  CallFlushCbIfNeeded(DecoderStatus::Codes::kFailed);
}

void VideoDecoderPipeline::CallFlushCbIfNeeded(DecoderStatus status) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(decoder_sequence_checker_);
  DVLOGF(3) << "status: " << static_cast<int>(status.code());

  if (!client_flush_cb_)
    return;

  // Flush is not completed yet.
  if (status == DecoderStatus::Codes::kOk && HasPendingFrames())
    return;

  client_task_runner_->PostTask(
      FROM_HERE, base::BindOnce(std::move(client_flush_cb_), status));
}

void VideoDecoderPipeline::PrepareChangeResolution() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(decoder_sequence_checker_);
  DVLOGF(3);
  DCHECK(!need_apply_new_resolution);

  need_apply_new_resolution = true;
  CallApplyResolutionChangeIfNeeded();
}

void VideoDecoderPipeline::CallApplyResolutionChangeIfNeeded() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(decoder_sequence_checker_);
  DVLOGF(3);

  if (need_apply_new_resolution && !HasPendingFrames()) {
    need_apply_new_resolution = false;
    decoder_->ApplyResolutionChange();
  }
}

DmabufVideoFramePool* VideoDecoderPipeline::GetVideoFramePool() const {
  DVLOGF(3);
  DCHECK_CALLED_ON_VALID_SEQUENCE(decoder_sequence_checker_);

  // TODO(andrescj): consider returning a WeakPtr instead. That way, if callers
  // store the returned pointer, they know that they should check it's valid
  // because the video frame pool can change across resolution changes if we go
  // from using an image processor to not using one (or viceversa).
  if (image_processor_)
    return auxiliary_frame_pool_.get();
  return main_frame_pool_.get();
}

CroStatus::Or<PixelLayoutCandidate>
VideoDecoderPipeline::PickDecoderOutputFormat(
    const std::vector<PixelLayoutCandidate>& candidates,
    const gfx::Rect& decoder_visible_rect,
    const gfx::Size& decoder_natural_size,
    absl::optional<gfx::Size> output_size,
    size_t num_of_pictures,
    bool use_protected,
    bool need_aux_frame_pool,
    absl::optional<DmabufVideoFramePool::CreateFrameCB> allocator) {
  DVLOGF(3);
  DCHECK_CALLED_ON_VALID_SEQUENCE(decoder_sequence_checker_);

  if (candidates.empty())
    return CroStatus::Codes::kNoDecoderOutputFormatCandidates;

  auxiliary_frame_pool_.reset();
  image_processor_.reset();

  // As long as we're not scaling, check if any of the |candidates| formats is
  // directly renderable. If so, and (VA-API-only) the modifier of buffers
  // provided by the frame pool matches the one supported by the |decoder_|, we
  // don't need an image processor.
  absl::optional<PixelLayoutCandidate> viable_candidate;
  if (!output_size || *output_size == decoder_visible_rect.size()) {
    for (const auto& preferred_fourcc : kPreferredRenderableFourccs) {
      for (const auto& candidate : candidates) {
        if (candidate.fourcc == preferred_fourcc) {
          viable_candidate = candidate;
          break;
        }
      }
      if (viable_candidate)
        break;
    }
  }

#if BUILDFLAG(IS_LINUX)
  // Linux should always use a custom allocator (to allocate buffers using
  // libva) and a PlatformVideoFramePool.
  CHECK(allocator.has_value());
  CHECK(main_frame_pool_->AsPlatformVideoFramePool());
  main_frame_pool_->AsPlatformVideoFramePool()->SetCustomFrameAllocator(
      *allocator);
#elif BUILDFLAG(IS_CHROMEOS_LACROS)
  // Lacros should always use a PlatformVideoFramePool outside of tests (because
  // it doesn't need to handle ARC++/ARCVM requests) with no custom allocator
  // (because buffers are allocated with minigbm).
  CHECK(!allocator.has_value());
  CHECK(main_frame_pool_->AsPlatformVideoFramePool() ||
        main_frame_pool_->IsFakeVideoFramePool());
#elif BUILDFLAG(IS_CHROMEOS_ASH)
  // Ash Chrome can use any type of frame pool (because it may get requests from
  // ARC++/ARCVM) but never a custom allocator.
  CHECK(!allocator.has_value());
#else
#error "Unsupported platform"
#endif

#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)
  // viable_candidate should always be set unless using L1 protected content,
  // which isn't an option on linux or lacros.
  CHECK(viable_candidate);
#endif

  if (viable_candidate) {
    CroStatus::Or<GpuBufferLayout> status_or_layout =
        main_frame_pool_->Initialize(viable_candidate->fourcc,
                                     viable_candidate->size,
                                     decoder_visible_rect, decoder_natural_size,
                                     num_of_pictures, use_protected);
    if (status_or_layout.has_error())
      return std::move(status_or_layout).error();

#if BUILDFLAG(USE_VAAPI) && BUILDFLAG(IS_CHROMEOS_ASH)
    // Linux and Lacros do not check the modifiers,
    // since they do not set any.
    const GpuBufferLayout layout(std::move(status_or_layout).value());
    if (layout.modifier() == viable_candidate->modifier) {
      return *viable_candidate;
    } else if (layout.modifier() != DRM_FORMAT_MOD_LINEAR) {
      // In theory, we could accept any |layout|.modifier(). However, the only
      // known use case for a modifier different than the one native to the
      // |decoder_| is when Android wishes to get linear decoded data. Thus, to
      // reduce the number of of moving parts that can fail, we restrict the
      // modifiers of pool buffers to be either the hardware decoder's native
      // modifier or DRM_FORMAT_MOD_LINEAR.
      DVLOGF(2) << "Unsupported modifier, " << std::hex
                << viable_candidate->modifier << ", passed in";
      return CroStatus::Codes::kFailedToCreateImageProcessor;
    }
#else
    return *viable_candidate;
#endif  // BUILDFLAG(USE_VAAPI) && BUILDFLAG(IS_CHROMEOS_ASH)
  }

  std::unique_ptr<ImageProcessor> image_processor;
  if (create_image_processor_cb_for_testing_) {
    image_processor = create_image_processor_cb_for_testing_.Run(
        candidates,
        /*input_visible_rect=*/decoder_visible_rect,
        output_size ? *output_size : decoder_visible_rect.size(),
        kNumFramesForImageProcessor);
  } else {
    image_processor = ImageProcessorFactory::CreateWithInputCandidates(
        candidates, /*input_visible_rect=*/decoder_visible_rect,
        output_size ? *output_size : decoder_visible_rect.size(),
        kNumFramesForImageProcessor, decoder_task_runner_,
        base::BindRepeating(&PickRenderableFourcc),
        BindToCurrentLoop(base::BindRepeating(&VideoDecoderPipeline::OnError,
                                              decoder_weak_this_,
                                              "ImageProcessor error")));
  }

  if (!image_processor) {
    DVLOGF(2) << "Unable to find ImageProcessor to convert format";
    // TODO(crbug/1103510): Make CreateWithInputCandidates return an Or type.
    return CroStatus::Codes::kFailedToCreateImageProcessor;
  }

  if (need_aux_frame_pool) {
    // Initialize the auxiliary frame pool with the input format of the image
    // processor. Note that we pass nullptr as the GpuMemoryBufferFactory. That
    // way, the pool will allocate buffers using minigbm directly instead of
    // going through Ozone which means it won't create DRM/KMS framebuffers for
    // those buffers. This is good because these buffers don't end up as
    // overlays anyway.
    auxiliary_frame_pool_ = std::make_unique<PlatformVideoFramePool>(
        /*gpu_memory_buffer_factory=*/nullptr);

    auxiliary_frame_pool_->set_parent_task_runner(decoder_task_runner_);
    CroStatus::Or<GpuBufferLayout> status_or_layout =
        auxiliary_frame_pool_->Initialize(
            image_processor->input_config().fourcc,
            image_processor->input_config().size, decoder_visible_rect,
            decoder_natural_size, num_of_pictures, use_protected);
    if (status_or_layout.has_error()) {
      // A PlatformVideoFramePool should never abort initialization.
      DCHECK_NE(status_or_layout.code(), CroStatus::Codes::kResetRequired);
      DVLOGF(2) << "Could not initialize the auxiliary frame pool";
      return std::move(status_or_layout).error();
    }
  }
  // Note that fourcc is specified in ImageProcessor's factory method.
  auto fourcc = image_processor->input_config().fourcc;
  auto size = image_processor->input_config().size;

  // Setup new pipeline.
  // TODO(b/203240043): Verify that if we're using the image processor for tiled
  // to linear transformation, that the created frame pool is of linear format.
  // TODO(b/203240043): Add CHECKs to verify that the image processor is being
  // created for only valid use cases. Writing to a linear output buffer, e.g.
  auto status_or_image_processor = ImageProcessorWithPool::Create(
      std::move(image_processor), main_frame_pool_.get(),
      kNumFramesForImageProcessor, use_protected, decoder_task_runner_);
  if (status_or_image_processor.has_error()) {
    DVLOGF(2) << "Unable to create ImageProcessorWithPool.";
    return std::move(status_or_image_processor).error();
  }

  image_processor_ = std::move(status_or_image_processor).value();
  // TODO(b/203240043): Currently, the modifier is not read by any callers of
  // this function. We can eventually provide it by making it available to fetch
  // through the |image_processor|.
  return PixelLayoutCandidate{fourcc, size,
                              gfx::NativePixmapHandle::kNoModifier};
}

#if BUILDFLAG(IS_CHROMEOS_ASH)
void VideoDecoderPipeline::OnBufferTranscrypted(
    scoped_refptr<DecoderBuffer> transcrypted_buffer,
    DecodeCB decode_callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(decoder_sequence_checker_);
  DCHECK(!has_error_);
  if (!transcrypted_buffer) {
    OnError("Error in buffer transcryption");
    std::move(decode_callback).Run(DecoderStatus::Codes::kFailed);
    return;
  }

  decoder_->Decode(std::move(transcrypted_buffer), std::move(decode_callback));
}
#endif  // BUILDFLAG(IS_CHROMEOS_ASH)

}  // namespace media


text:
LPE Estimator Analysis

## Links to Notebooks

* [Kabir Crash](15-09-30 Kabir Log.ipynb)

## Install Dependencies
```bash
sudo apt-get install python-pandas python-matplotlib-baselib
```

```bash
pip install px4tools
```

## Running IPython

Navigate to the git repo folder and type:
```bash
ipython notebook
```

This should launch a browser.


text:
package org.apache.asterix.lang.common.visitor;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.apache.asterix.common.exceptions.AsterixException;
import org.apache.asterix.lang.common.base.Expression;
import org.apache.asterix.lang.common.base.Expression.Kind;
import org.apache.asterix.lang.common.base.ILangExpression;
import org.apache.asterix.lang.common.clause.GroupbyClause;
import org.apache.asterix.lang.common.clause.LetClause;
import org.apache.asterix.lang.common.clause.LimitClause;
import org.apache.asterix.lang.common.clause.OrderbyClause;
import org.apache.asterix.lang.common.clause.WhereClause;
import org.apache.asterix.lang.common.expression.CallExpr;
import org.apache.asterix.lang.common.expression.FieldAccessor;
import org.apache.asterix.lang.common.expression.FieldBinding;
import org.apache.asterix.lang.common.expression.GbyVariableExpressionPair;
import org.apache.asterix.lang.common.expression.IfExpr;
import org.apache.asterix.lang.common.expression.IndexAccessor;
import org.apache.asterix.lang.common.expression.ListConstructor;
import org.apache.asterix.lang.common.expression.LiteralExpr;
import org.apache.asterix.lang.common.expression.OperatorExpr;
import org.apache.asterix.lang.common.expression.QuantifiedExpression;
import org.apache.asterix.lang.common.expression.RecordConstructor;
import org.apache.asterix.lang.common.expression.UnaryExpr;
import org.apache.asterix.lang.common.expression.VariableExpr;
import org.apache.asterix.lang.common.rewrites.LangRewritingContext;
import org.apache.asterix.lang.common.rewrites.VariableSubstitutionEnvironment;
import org.apache.asterix.lang.common.statement.FunctionDecl;
import org.apache.asterix.lang.common.statement.Query;
import org.apache.asterix.lang.common.struct.QuantifiedPair;
import org.apache.asterix.lang.common.struct.VarIdentifier;
import org.apache.asterix.lang.common.utils.VariableCloneAndSubstitutionUtil;
import org.apache.asterix.lang.common.visitor.base.AbstractQueryExpressionVisitor;
import org.apache.hyracks.algebricks.common.utils.Pair;

public class CloneAndSubstituteVariablesVisitor extends
        AbstractQueryExpressionVisitor<Pair<ILangExpression, VariableSubstitutionEnvironment>, VariableSubstitutionEnvironment> {

    private LangRewritingContext context;

    public CloneAndSubstituteVariablesVisitor(LangRewritingContext context) {
        this.context = context;
    }

    @Override
    public Pair<ILangExpression, VariableSubstitutionEnvironment> visit(LetClause lc,
            VariableSubstitutionEnvironment env) throws AsterixException {
        Pair<ILangExpression, VariableSubstitutionEnvironment> p1 = lc.getBindingExpr().accept(this, env);
        VariableExpr varExpr = lc.getVarExpr();
        VariableExpr newVe = generateNewVariable(context, varExpr);
        LetClause newLet = new LetClause(newVe, (Expression) p1.first);
        return new Pair<ILangExpression, VariableSubstitutionEnvironment>(newLet,
                VariableCloneAndSubstitutionUtil.eliminateSubstFromList(lc.getVarExpr(), env));
    }

    @Override
    public Pair<ILangExpression, VariableSubstitutionEnvironment> visit(GroupbyClause gc,
            VariableSubstitutionEnvironment env) throws AsterixException {
        VariableSubstitutionEnvironment newSubs = env;
        List<GbyVariableExpressionPair> newGbyList = VariableCloneAndSubstitutionUtil.substInVarExprPair(context,
                gc.getGbyPairList(), env, newSubs, this);
        List<GbyVariableExpressionPair> newDecorList = gc.hasDecorList() ? VariableCloneAndSubstitutionUtil
                .substInVarExprPair(context, gc.getDecorPairList(), env, newSubs, this)
                : new ArrayList<GbyVariableExpressionPair>();
        List<VariableExpr> wList = new LinkedList<VariableExpr>();
        if (gc.hasWithList()) {
            for (VariableExpr w : gc.getWithVarList()) {
                VarIdentifier newVar = context.getRewrittenVar(w.getVar().getId());
                wList.add(new VariableExpr(newVar));
            }
        }
        GroupbyClause newGroup = new GroupbyClause(newGbyList, newDecorList, wList, gc.hasHashGroupByHint());
        return new Pair<ILangExpression, VariableSubstitutionEnvironment>(newGroup, newSubs);
    }

    @Override
    public Pair<ILangExpression, VariableSubstitutionEnvironment> visit(QuantifiedExpression qe,
            VariableSubstitutionEnvironment env) throws AsterixException {
        List<QuantifiedPair> oldPairs = qe.getQuantifiedList();
        List<QuantifiedPair> newPairs = new ArrayList<QuantifiedPair>(oldPairs.size());
        VariableSubstitutionEnvironment newSubs = env;
        for (QuantifiedPair t : oldPairs) {
            VariableExpr newVar = generateNewVariable(context, t.getVarExpr());
            newSubs = VariableCloneAndSubstitutionUtil.eliminateSubstFromList(newVar, newSubs);
            Pair<ILangExpression, VariableSubstitutionEnvironment> p1 = t.getExpr().accept(this, newSubs);
            QuantifiedPair t2 = new QuantifiedPair(newVar, (Expression) p1.first);
            newPairs.add(t2);
        }
        Pair<ILangExpression, VariableSubstitutionEnvironment> p2 = qe.getSatisfiesExpr().accept(this, newSubs);
        QuantifiedExpression qe2 = new QuantifiedExpression(qe.getQuantifier(), newPairs, (Expression) p2.first);
        return new Pair<ILangExpression, VariableSubstitutionEnvironment>(qe2, newSubs);
    }

    @Override
    public Pair<ILangExpression, VariableSubstitutionEnvironment> visit(WhereClause wc,
            VariableSubstitutionEnvironment env) throws AsterixException {
        Pair<ILangExpression, VariableSubstitutionEnvironment> p1 = wc.getWhereExpr().accept(this, env);
        WhereClause newW = new WhereClause((Expression) p1.first);
        return new Pair<ILangExpression, VariableSubstitutionEnvironment>(newW, p1.second);
    }

    @Override
    public Pair<ILangExpression, VariableSubstitutionEnvironment> visit(CallExpr pf,
            VariableSubstitutionEnvironment env) throws AsterixException {
        List<Expression> exprList = VariableCloneAndSubstitutionUtil.visitAndCloneExprList(pf.getExprList(), env, this);
        CallExpr f = new CallExpr(pf.getFunctionSignature(), exprList);
        return new Pair<ILangExpression, VariableSubstitutionEnvironment>(f, env);
    }

    @Override
    public Pair<ILangExpression, VariableSubstitutionEnvironment> visit(FunctionDecl fd,
            VariableSubstitutionEnvironment env) throws AsterixException {
        List<VarIdentifier> newList = new ArrayList<VarIdentifier>(fd.getParamList().size());
        for (VarIdentifier vi : fd.getParamList()) {
            VariableExpr varExpr = new VariableExpr(vi);
            if (!env.constainsOldVar(varExpr)) {
                throw new AsterixException("Parameter " + vi + " does not appear in the substitution list.");
            }
            Expression newExpr = env.findSubstituion(varExpr);
            if (newExpr.getKind() != Kind.VARIABLE_EXPRESSION) {
                throw new AsterixException("Parameter " + vi + " cannot be substituted by a non-variable expression.");
            }
            newList.add(((VariableExpr) newExpr).getVar());
        }

        Pair<ILangExpression, VariableSubstitutionEnvironment> p1 = fd.getFuncBody().accept(this, env);
        FunctionDecl newF = new FunctionDecl(fd.getSignature(), newList, (Expression) p1.first);
        return new Pair<ILangExpression, VariableSubstitutionEnvironment>(newF, env);
    }

    @Override
    public Pair<ILangExpression, VariableSubstitutionEnvironment> visit(IfExpr ifexpr,
            VariableSubstitutionEnvironment env) throws AsterixException {
        Pair<ILangExpression, VariableSubstitutionEnvironment> p1 = ifexpr.getCondExpr().accept(this, env);
        Pair<ILangExpression, VariableSubstitutionEnvironment> p2 = ifexpr.getThenExpr().accept(this, env);
        Pair<ILangExpression, VariableSubstitutionEnvironment> p3 = ifexpr.getElseExpr().accept(this, env);
        IfExpr i = new IfExpr((Expression) p1.first, (Expression) p2.first, (Expression) p3.first);
        return new Pair<ILangExpression, VariableSubstitutionEnvironment>(i, env);
    }

    @Override
    public Pair<ILangExpression, VariableSubstitutionEnvironment> visit(LimitClause lc,
            VariableSubstitutionEnvironment env) throws AsterixException {
        Pair<ILangExpression, VariableSubstitutionEnvironment> p1 = lc.getLimitExpr().accept(this, env);
        Pair<ILangExpression, VariableSubstitutionEnvironment> p2 = null;
        Expression lcOffsetExpr = lc.getOffset();
        if (lcOffsetExpr != null) {
            p2 = lcOffsetExpr.accept(this, env);
        } else {
            p2 = new Pair<ILangExpression, VariableSubstitutionEnvironment>(null, null);
        }
        LimitClause c = new LimitClause((Expression) p1.first, (Expression) p2.first);
        return new Pair<ILangExpression, VariableSubstitutionEnvironment>(c, env);
    }

    @Override
    public Pair<ILangExpression, VariableSubstitutionEnvironment> visit(ListConstructor lc,
            VariableSubstitutionEnvironment env) throws AsterixException {
        List<Expression> oldExprList = lc.getExprList();
        List<Expression> exprs = VariableCloneAndSubstitutionUtil.visitAndCloneExprList(oldExprList, env, this);
        ListConstructor c = new ListConstructor(lc.getType(), exprs);
        return new Pair<ILangExpression, VariableSubstitutionEnvironment>(c, env);
    }

    @Override
    public Pair<ILangExpression, VariableSubstitutionEnvironment> visit(LiteralExpr l,
            VariableSubstitutionEnvironment env) throws AsterixException {
        return new Pair<ILangExpression, VariableSubstitutionEnvironment>(l, env);
    }

    @Override
    public Pair<ILangExpression, VariableSubstitutionEnvironment> visit(OperatorExpr op,
            VariableSubstitutionEnvironment env) throws AsterixException {
        List<Expression> oldExprList = op.getExprList();
        List<Expression> exprs = new ArrayList<Expression>(oldExprList.size());
        for (Expression e : oldExprList) {
            Pair<ILangExpression, VariableSubstitutionEnvironment> p1 = e.accept(this, env);
            exprs.add((Expression) p1.first);
        }
        OperatorExpr oe = new OperatorExpr(exprs, op.getExprBroadcastIdx(), op.getOpList());
        oe.setCurrentop(op.isCurrentop());
        return new Pair<ILangExpression, VariableSubstitutionEnvironment>(oe, env);
    }

    @Override
    public Pair<ILangExpression, VariableSubstitutionEnvironment> visit(OrderbyClause oc,
            VariableSubstitutionEnvironment env) throws AsterixException {
        List<Expression> exprList = VariableCloneAndSubstitutionUtil.visitAndCloneExprList(oc.getOrderbyList(), env,
                this);
        OrderbyClause oc2 = new OrderbyClause(exprList, oc.getModifierList());
        oc2.setNumFrames(oc.getNumFrames());
        oc2.setNumTuples(oc.getNumTuples());
        oc2.setRangeMap(oc.getRangeMap());
        return new Pair<ILangExpression, VariableSubstitutionEnvironment>(oc2, env);
    }

    @Override
    public Pair<ILangExpression, VariableSubstitutionEnvironment> visit(Query q, VariableSubstitutionEnvironment env)
            throws AsterixException {
        Query newQ = new Query();
        Pair<ILangExpression, VariableSubstitutionEnvironment> p1 = q.getBody().accept(this, env);
        newQ.setBody((Expression) p1.first);
        return new Pair<ILangExpression, VariableSubstitutionEnvironment>(newQ, p1.second);
    }

    @Override
    public Pair<ILangExpression, VariableSubstitutionEnvironment> visit(RecordConstructor rc,
            VariableSubstitutionEnvironment env) throws AsterixException {
        List<FieldBinding> oldFbs = rc.getFbList();
        ArrayList<FieldBinding> newFbs = new ArrayList<FieldBinding>(oldFbs.size());
        for (FieldBinding fb : oldFbs) {
            Pair<ILangExpression, VariableSubstitutionEnvironment> p1 = fb.getLeftExpr().accept(this, env);
            Pair<ILangExpression, VariableSubstitutionEnvironment> p2 = fb.getRightExpr().accept(this, env);
            FieldBinding fb2 = new FieldBinding((Expression) p1.first, (Expression) p2.first);
            newFbs.add(fb2);
        }
        RecordConstructor newRc = new RecordConstructor(newFbs);
        return new Pair<ILangExpression, VariableSubstitutionEnvironment>(newRc, env);
    }

    @Override
    public Pair<ILangExpression, VariableSubstitutionEnvironment> visit(UnaryExpr u,
            VariableSubstitutionEnvironment env) throws AsterixException {
        Pair<ILangExpression, VariableSubstitutionEnvironment> p1 = u.getExpr().accept(this, env);
        UnaryExpr newU = new UnaryExpr(u.getSign(), (Expression) p1.first);
        return new Pair<ILangExpression, VariableSubstitutionEnvironment>(newU, env);
    }

    @Override
    public Pair<ILangExpression, VariableSubstitutionEnvironment> visit(IndexAccessor ia,
            VariableSubstitutionEnvironment env) throws AsterixException {
        Pair<ILangExpression, VariableSubstitutionEnvironment> p1 = ia.getExpr().accept(this, env);
        Expression indexExpr = null;
        if (!ia.isAny()) {
            Pair<ILangExpression, VariableSubstitutionEnvironment> p2 = ia.getIndexExpr().accept(this, env);
            indexExpr = (Expression) p2.first;
        }
        IndexAccessor i = new IndexAccessor((Expression) p1.first, indexExpr);
        i.setAny(ia.isAny());
        return new Pair<ILangExpression, VariableSubstitutionEnvironment>(i, env);
    }

    @Override
    public Pair<ILangExpression, VariableSubstitutionEnvironment> visit(FieldAccessor fa,
            VariableSubstitutionEnvironment env) throws AsterixException {
        Pair<ILangExpression, VariableSubstitutionEnvironment> p = fa.getExpr().accept(this, env);
        FieldAccessor newF = new FieldAccessor((Expression) p.first, fa.getIdent());
        return new Pair<ILangExpression, VariableSubstitutionEnvironment>(newF, p.second);
    }

    @Override
    public Pair<ILangExpression, VariableSubstitutionEnvironment> visit(VariableExpr v,
            VariableSubstitutionEnvironment env) throws AsterixException {
        return new Pair<ILangExpression, VariableSubstitutionEnvironment>(rewriteVariableExpr(v, env), env);
    }

    // Replace a variable expression if the variable is to-be substituted.
    public Expression rewriteVariableExpr(VariableExpr expr, VariableSubstitutionEnvironment env) {
        if (env.constainsOldVar(expr)) {
            return env.findSubstituion(expr);
        } else {
            // it is a variable from the context
            VarIdentifier var = context.getRewrittenVar(expr.getVar().getId());
            if (var != null) {
                return new VariableExpr(var);
            }
        }
        return expr;
    }

    /**
     * Generates a new variable for an existing variable.
     *
     * @param context
     *            , the language rewriting context which keeps all the rewriting variable-int-id to variable-string-identifier mappings.
     * @param varExpr
     *            , the existing variable expression.
     * @return the new variable expression.
     */
    public VariableExpr generateNewVariable(LangRewritingContext context, VariableExpr varExpr) {
        VarIdentifier vi = varExpr.getVar();
        VarIdentifier newVar = context.mapOldId(vi.getId(), vi.getValue());
        VariableExpr newVarExpr = new VariableExpr(newVar);
        return newVarExpr;
    }

}


text:
package com.zuoxiaolong.blog.model.persistent;

import lombok.Data;

@Data
public class Contributor extends BaseModel {

    private String contributorName;

    private String personalUrl;

}


text:
export {};
//# sourceMappingURL=template-result_test.d.ts.map


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
	<title>Redirecionamento...</title>

Redirecionamento

	Se esta página não for automaticamente redirecionada em 9 segundos, clique
	aqui.


text:
package de.holisticon.emapp.handler;

import com.google.common.eventbus.Subscribe;
import com.vaadin.ui.Table;
import com.vaadin.ui.Window;
import de.holisticon.emapp.event.NewTimeTrackingRecordEvent;
import de.holisticon.emapp.model.TimeTrackingRecord;
import de.holisticon.emapp.ui.MessageBox;

public class NewTimeTrackingRecordHandler {

	private final Table view;
	private Window window;

	public NewTimeTrackingRecordHandler(Table timeTrackingRecordsTable, Window window) {
		this.window = window;
		this.view = timeTrackingRecordsTable;
	}

	@Subscribe
	public void addTimeTrackingRecord(NewTimeTrackingRecordEvent event) {
		MessageBox.showTray(window, "info", "your record has been saved");
		TimeTrackingRecord model = event.getTrackingRecord();
		view.getContainerDataSource().addItem(model);
	}
}