text:
<?php

namespace Propel\Generator\Model\Diff;

use Propel\Generator\Model\Database;
use Propel\Generator\Model\Table;

/**
 * Service class for comparing Database objects
 * Heavily inspired by Doctrine2's Migrations
 * (see http://github.com/doctrine/dbal/tree/master/lib/Doctrine/DBAL/Schema/)
 */
class DatabaseComparator
{
    /**
     * @var DatabaseDiff
     */
    protected $databaseDiff;

    /**
     * @var Database
     */
    protected $fromDatabase;

    /**
     * @var Database
     */
    protected $toDatabase;

    /**
     * Whether we should detect renamings and track it via `addRenamedTable` at the
     * DatabaseDiff object.
     *
     * @var bool
     */
    protected $withRenaming = false;

    /**
     * @var boolean
     */
    protected $removeTable = true;

    /**
     * @var array list of excluded tables
     */
    protected $excludedTables = array();

    public function __construct($databaseDiff = null)
    {
        $this->databaseDiff = (null === $databaseDiff) ? new DatabaseDiff() : $databaseDiff;
    }

    public function getDatabaseDiff()
    {
        return $this->databaseDiff;
    }

    /**
     * Sets the fromDatabase property.
     *
     * @param Database $fromDatabase
     */
    public function setFromDatabase(Database $fromDatabase)
    {
        $this->fromDatabase = $fromDatabase;
    }

    /**
     * Returns the fromDatabase property.
     *
     * @return Database
     */
    public function getFromDatabase()
    {
        return $this->fromDatabase;
    }

    /**
     * Sets the toDatabase property.
     *
     * @param Database $toDatabase
     */
    public function setToDatabase(Database $toDatabase)
    {
        $this->toDatabase = $toDatabase;
    }

    /**
     * Returns the toDatabase property.
     *
     * @return Database
     */
    public function getToDatabase()
    {
        return $this->toDatabase;
    }

    /**
     * Set true to handle removed tables or false to ignore them
     *
     * @param boolean $removeTable
     */
    public function setRemoveTable($removeTable)
    {
        $this->removeTable = $removeTable;
    }

    /**
     * @return boolean
     */
    public function getRemoveTable()
    {
        return $this->removeTable;
    }

    /**
     * Set the list of tables excluded from the comparison
     *
     * @param array $excludedTables set the list of table name
     */
    public function setExcludedTables(array $excludedTables)
    {
        $this->excludedTables = $excludedTables;
    }

    /**
     * Returns the list of tables excluded from the comparison
     *
     * @return array
     */
    public function getExcludedTables()
    {
        return $this->excludedTables;
    }

    /**
     * Returns the computed difference between two database objects.
     *
     * @param  Database             $fromDatabase
     * @param  Database             $toDatabase
     * @param  boolean              $caseInsensitive
     * @return DatabaseDiff|Boolean
     */
    public static function computeDiff(Database $fromDatabase, Database $toDatabase, $caseInsensitive = false, $withRenaming = false, $removeTable = true, $excludedTables = array())
    {
        $databaseComparator = new self();
        $databaseComparator->setFromDatabase($fromDatabase);
        $databaseComparator->setToDatabase($toDatabase);
        $databaseComparator->setWithRenaming($withRenaming);
        $databaseComparator->setRemoveTable($removeTable);
        $databaseComparator->setExcludedTables($excludedTables);

        $platform = $toDatabase->getPlatform() ?: $fromDatabase->getPlatform();

        if ($platform) {
            foreach ($fromDatabase->getTables() as $table) {
                $platform->normalizeTable($table);
            }
            foreach ($toDatabase->getTables() as $table) {
                $platform->normalizeTable($table);
            }
        }

        $differences = 0;
        $differences += $databaseComparator->compareTables($caseInsensitive);

        return ($differences > 0) ? $databaseComparator->getDatabaseDiff() : false;
    }

    /**
     * @param boolean $withRenaming
     */
    public function setWithRenaming($withRenaming)
    {
        $this->withRenaming = $withRenaming;
    }

    /**
     * @return boolean
     */
    public function getWithRenaming()
    {
        return $this->withRenaming;
    }

    /**
     * Returns the number of differences.
     *
     * Compares the tables of the fromDatabase and the toDatabase, and modifies
     * the inner databaseDiff if necessary.
     *
     * @param  boolean $caseInsensitive
     * @return integer
     */
    public function compareTables($caseInsensitive = false)
    {
        $fromDatabaseTables = $this->fromDatabase->getTables();
        $toDatabaseTables = $this->toDatabase->getTables();
        $databaseDifferences = 0;

        // check for new tables in $toDatabase
        foreach ($toDatabaseTables as $table) {
            if ($this->isTableExcluded($table)) {
                continue;
            }
            if (!$this->fromDatabase->hasTable($table->getName(), $caseInsensitive) && !$table->isSkipSql()) {
                $this->databaseDiff->addAddedTable($table->getName(), $table);
                $databaseDifferences++;
            }
        }

        // check for removed tables in $toDatabase
        if ($this->getRemoveTable()) {
            foreach ($fromDatabaseTables as $table) {
                if ($this->isTableExcluded($table)) {
                    continue;
                }
                if (!$this->toDatabase->hasTable($table->getName(), $caseInsensitive) && !$table->isSkipSql()) {
                    $this->databaseDiff->addRemovedTable($table->getName(), $table);
                    $databaseDifferences++;
                }
            }
        }

        // check for table differences
        foreach ($fromDatabaseTables as $fromTable) {
            if ($this->isTableExcluded($fromTable)) {
                continue;
            }
            if ($this->toDatabase->hasTable($fromTable->getName(), $caseInsensitive)) {
                $toTable = $this->toDatabase->getTable($fromTable->getName(), $caseInsensitive);
                $databaseDiff = TableComparator::computeDiff($fromTable, $toTable, $caseInsensitive);
                if ($databaseDiff) {
                    $this->databaseDiff->addModifiedTable($fromTable->getName(), $databaseDiff);
                    $databaseDifferences++;
                }
            }
        }

        // check for table renamings
        foreach ($this->databaseDiff->getAddedTables() as $addedTableName => $addedTable) {
            foreach ($this->databaseDiff->getRemovedTables() as $removedTableName => $removedTable) {
                if (!TableComparator::computeDiff($addedTable, $removedTable, $caseInsensitive)) {
                    // no difference except the name, that's probably a renaming
                    if ($this->getWithRenaming()) {
                        $this->databaseDiff->addRenamedTable($removedTableName, $addedTableName);
                        $this->databaseDiff->removeAddedTable($addedTableName);
                        $this->databaseDiff->removeRemovedTable($removedTableName);
                        $databaseDifferences--;
                    } else {
                        $this->databaseDiff->addPossibleRenamedTable($removedTableName, $addedTableName);
                    }
                    // skip to the next added table
                    break;
                }
            }
        }

        return $databaseDifferences;
    }

    /**
     * @param Table $table
     * @return bool
     */
    protected function isTableExcluded(Table $table)
    {
        return in_array($table->getName(), $this->excludedTables);
    }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;

namespace Blogs.EfAndSprocfForCqrs.ReadModel.QueryResults
{
    public class SingleSearchResult<T> : IEnumerable<T>
    {
        private readonly T _result;

        public SingleSearchResult()
        {
            _result = default(T);
        }

        public SingleSearchResult(T result)
        {
            if (result == null) throw new ArgumentNullException("result");

            _result = result;
        }

        public IEnumerator<T> GetEnumerator()
        {
            if (ResultWasFound)
            {
                yield return _result;
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        /// <summary>
        /// Gets a value indicating whether a result was found.
        /// </summary>
        /// <value>
        ///   <c>true</c> if a result was found; otherwise, <c>false</c>.
        /// </value>
        public bool ResultWasFound
        {
            get { return _result != null; }
        }

        /// <summary>
        /// Gets the result (providing one was found); otherwise and exception is thrown.
        /// </summary>
        /// <value>
        /// The result.
        /// </value>
        /// <exception cref="System.InvalidOperationException">
        /// No result was present. Please use 'ResultWasFound' property
        /// to check for result before calling the 'Result' function.
        /// </exception>
        public T Result
        {
            get
            {
                if (ResultWasFound) return _result;

                throw new InvalidOperationException(
                    "No result was present. Please use 'ResultWasFound' property " +
                    "to check for result before calling the 'Result' function. ");
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<vaadin-vertical-layout>
    <vaadin-text-field caption="Enter your name" _id="foo"/>
    <vaadin-button _id="bar">Say hello</vaadin-button>
</vaadin-vertical-layout>


text:
#ifndef AR_VIDEO_GSTREAMER_H
#define AR_VIDEO_GSTREAMER_H

#ifdef  __cplusplus
extern "C" {
#endif

#include <AR/config.h>
#include <AR/ar.h>

typedef struct _AR2VideoParamT AR2VideoParamT;

#ifdef  __cplusplus
}
#endif

#endif


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model common\models\User2 */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'username')->textInput(['maxlength' => 20]) ?>

    <?= $form->field($model, 'email')->textInput(['maxlength' => 100]) ?>

    <?= $form->field($model, 'password')->passwordInput(['maxlength' => 255]) ?>

    <?= $form->field($model, 'code')->textInput(['maxlength' => 25]) ?>

    <?= $form->field($model, 'name')->textInput(['maxlength' => 255]) ?>

    <?= $form->field($model, 'city_id')->textInput() ?>

    <?= $form->field($model, 'address')->textInput(['maxlength' => 255]) ?>

    <?= $form->field($model, 'phone')->textInput(['maxlength' => 20]) ?>

    <?= $form->field($model, 'description')->textInput(['maxlength' => 255]) ?>

    <?= $form->field($model, 'created')->textInput() ?>

    <?= $form->field($model, 'created_user_id')->textInput() ?>

    <?= $form->field($model, 'modified')->textInput() ?>

    <?= $form->field($model, 'enabled')->textInput() ?>

    <?= $form->field($model, 'avatar_img')->textInput(['maxlength' => 100]) ?>

    <?= $form->field($model, 'roles_id')->textInput() ?>

    <?= $form->field($model, 'saldo')->textInput() ?>

    <?= $form->field($model, 'sex')->dropDownList([ 'm' => 'M', 'f' => 'F', ], ['prompt' => '']) ?>

    <?= $form->field($model, 'nationality')->textInput(['maxlength' => 255]) ?>

    <?= $form->field($model, 'birth')->textInput() ?>

    <?= $form->field($model, 'referal_user_id')->textInput() ?>

    <?= $form->field($model, 'others')->textarea(['rows' => 6]) ?>

    <?= $form->field($model, 'modal')->textInput() ?>

    <?= $form->field($model, 'auth_key')->textInput(['maxlength' => 32]) ?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
window.SYSTEM_VERSION = new Date().getTime();
if(config.type != 'develop'){
  SYSTEM_VERSION = config.timestamp;
}
window.BASE_HOST = config.url ;
//window.BASE_URL = 'http://' + BASE_HOST + '/';
window.BASE_URL = 'http://localhost:8088/';

require.config({
  urlArgs: "bust=" + SYSTEM_VERSION,
  baseUrl: '/scripts',
  //paths
  paths: {
    'app': 'app'
    //'angular': '../lib/angular',
    //'angular-route': '../plugin/angular-route',
    //'angular-ui-router': '../plugin/angular-ui-router',
    //'angular-animate': '../plugin/angular-animate',
    //'angular-cookies': '../plugin/angular-cookies',
    //'angular-table': '../plugin/angular-table',
    //'bootstrap': '../plugin/bootstrap',
    //'ui-bootstrap': '../plugin/ui-bootstrap-tpls',
    //'ngDialog': '../plugin/ngDialog',
    //'jquery': '../lib/jquery'
  },
  shim: {
    //'app': {
    //	//deps : []
    //	deps: ['angular', 'angular-route','angular-ui-router','angular-animate','angular-cookies', 'angular-table', 'ngDialog','bootstrap','ui-bootstrap']
    //},
    //'angular-route': {
    //	deps: ['angular']
    //},
    //'angular-ui-router': {
    //	deps: ['angular']
    //},
    //'angular-animate': {
    //	deps: ['angular']
    //},
    //'angular-cookies': {
    //	deps: ['angular']
    //},
    //'angular-table': {
    //	deps: ['angular']
    //},
    //'ngDialog': {
    //	deps: ['angular']
    //},
    //'bootstrap': {
    //	deps: ['jquery']
    //},
    //'ui-bootstrap': {
    //	deps: ['jquery','bootstrap','angular']
    //}
  }
});

require(['app'],
  function (app) {
    angular.bootstrap(document, ['app']);
  }
);


text:
<!DOCTYPE html>
<meta charset="utf-8">
<title>Test for PaymentRequest in an iframe</title>
<script src="../resources/testharness.js"></script>
<script src="../resources/testharnessreport.js"></script>
<iframe src="resources/payment-request-in-iframe-nested-expect-failure.html"></iframe>


text:
module Spree
  module Admin
    class OrderVersionsController < Spree::Admin::BaseController
      def index
        if params[:order_id].present?
          @order    = Spree::Order.find_by(number: params[:order_id])
          @versions = @order.order_versions.order(id: :desc)
        end
      end

      def show
        if params[:order_id].present?
          @order    = Spree::Order.find_by(number: params[:order_id])
          @version  = @order.order_versions.find(params[:id])
        end
      end
    end
  end
end


text:
package youzi.com.sharelove;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.Toast;

import youzi.com.sharelove.modal.Config;
import youzi.com.sharelove.modal.MusicWindow;
import youzi.com.sharelove.modal.internet.Form;
import youzi.com.sharelove.modal.internet.GetRoomInfo;
import youzi.com.sharelove.modal.internet.HttpMethod;
import youzi.com.sharelove.modal.sql.sqlbase.Appinfo_DbService;
import youzi.com.sharelove.view.fragment_about;
import youzi.com.sharelove.view.fragment_listen;
import youzi.com.sharelove.view.fragment_main;
import youzi.com.sharelove.view.listenRoom;

import static android.widget.RadioGroup.*;

public class MainActivity extends AppCompatActivity implements OnClickListener {
    private SectionsPagerAdapter mSectionsPagerAdapter;
    private ViewPager mViewPager;
    private Button TestBtn;

    private ProgressDialog loadingdialog;//初始化加载

    FloatingActionButton news;
    Handler handler, startHandler;

    Animation rightOut;
    boolean flag = true;

    //自定义的弹出框类
    MusicWindow menuWindow;

    private Appinfo_DbService appinfo_dbService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        appinfo_dbService = Appinfo_DbService.getDbService_Appinfo(this);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        TestBtn = (Button) findViewById(R.id.btn);
        setSupportActionBar(toolbar);
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        mViewPager = (ViewPager) findViewById(R.id.container);
        startHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                mViewPager.setAdapter(mSectionsPagerAdapter);
            }
        };

//        startActivity(new Intent(this, listenRoom.class));
        news = (FloatingActionButton) findViewById(R.id.news);
        news.setVisibility(View.GONE);
        news.setOnClickListener(this);
        news.setScrollBarSize(20);

        TestBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                menuWindow = new MusicWindow(MainActivity.this, itemsOnClick);
                //显示窗口
                menuWindow.showAtLocation(MainActivity.this.findViewById(R.id.fragment_main), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
                if (flag) { // 第一次点击按钮生效,在消息框退出前不响应点击
                    flag = false;
                } else {
                    return;
                }

                // 显示消息框
                news.startAnimation(rightOut);
                news.setVisibility(View.VISIBLE);
            }
        });
        init();
    }

    //为弹出窗口实现监听类
    private OnClickListener itemsOnClick = new OnClickListener() {

        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                default:
                    break;
            }
        }

    };

    public void init() {
        loadingdialog = ProgressDialog.show(this, null, "程序正在初始化,请稍候...", true, false);
        loadingdialog.onStart();
        //版本初始化
        if (appinfo_dbService.getCount() <= 0) {
            initToken(this);
        } else {
//            initToken(this);
            startHandler.sendEmptyMessage(0);
            appinfo_dbService.initToken(this.getApplication());
            //故意等待
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    loadingdialog.dismiss();
                }
            }).start();
        }
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                news.setVisibility(View.INVISIBLE);
                flag = true;
                super.handleMessage(msg);
            }

        };

        rightOut = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0,
                Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF,
                0);
        rightOut.setDuration(500);

        rightOut.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                //news.startAnimation(inDown);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.news:
                Snackbar.make(mViewPager, "这是个推送消息~~~", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
                handler.sendEmptyMessage(0);
                return;
        }
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    return new fragment_main("1");
                case 1:
                    return new fragment_listen("2");
                case 2:
                    return new fragment_about();
            }
            return null;
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

    }

    public void initToken(final Activity activity) {
        Form form = new Form(Config.RegisterTokenUrl);
        new GetRoomInfo(HttpMethod.GET, form, new GetRoomInfo.SuccessCallback() {
            @Override
            public void onSuccess(String result) {
//                System.out.println("token" + GetRoomInfo.getRoomToken(result));
                appinfo_dbService.update_Token(GetRoomInfo.getRoomToken(result));
                appinfo_dbService.initToken(activity.getApplication());
                startHandler.sendEmptyMessage(0);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        loadingdialog.dismiss();
                    }
                }).start();
            }
        }, new GetRoomInfo.FailCallback() {
            @Override
            public void onFail(String result) {
                Toast.makeText(activity, "注册Token失败!-" + result, Toast.LENGTH_LONG).show();
//                finish();
            }
        });
    }
}


text:
package com.amazonaws.services.chime.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListChannelMessagesResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * The ARN of the channel containing the requested messages.
     *

     */
    private String channelArn;
    /**
     *

     * The token passed by previous API calls until all requested messages are returned.
     *

     */
    private String nextToken;
    /**
     *

     * The information about, and content of, each requested message.
     *

     */
    private java.util.List<ChannelMessageSummary> channelMessages;

    /**
     *

     * The ARN of the channel containing the requested messages.
     *

     *
     * @param channelArn
     *        The ARN of the channel containing the requested messages.
     */

    public void setChannelArn(String channelArn) {
        this.channelArn = channelArn;
    }

    /**
     *

     * The ARN of the channel containing the requested messages.
     *

     *
     * @return The ARN of the channel containing the requested messages.
     */

    public String getChannelArn() {
        return this.channelArn;
    }

    /**
     *

     * The ARN of the channel containing the requested messages.
     *

     *
     * @param channelArn
     *        The ARN of the channel containing the requested messages.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListChannelMessagesResult withChannelArn(String channelArn) {
        setChannelArn(channelArn);
        return this;
    }

    /**
     *

     * The token passed by previous API calls until all requested messages are returned.
     *

     *
     * @param nextToken
     *        The token passed by previous API calls until all requested messages are returned.
     */

    public void setNextToken(String nextToken) {
        this.nextToken = nextToken;
    }

    /**
     *

     * The token passed by previous API calls until all requested messages are returned.
     *

     *
     * @return The token passed by previous API calls until all requested messages are returned.
     */

    public String getNextToken() {
        return this.nextToken;
    }

    /**
     *

     * The token passed by previous API calls until all requested messages are returned.
     *

     *
     * @param nextToken
     *        The token passed by previous API calls until all requested messages are returned.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListChannelMessagesResult withNextToken(String nextToken) {
        setNextToken(nextToken);
        return this;
    }

    /**
     *

     * The information about, and content of, each requested message.
     *

     *
     * @return The information about, and content of, each requested message.
     */

    public java.util.List<ChannelMessageSummary> getChannelMessages() {
        return channelMessages;
    }

    /**
     *

     * The information about, and content of, each requested message.
     *

     *
     * @param channelMessages
     *        The information about, and content of, each requested message.
     */

    public void setChannelMessages(java.util.Collection<ChannelMessageSummary> channelMessages) {
        if (channelMessages == null) {
            this.channelMessages = null;
            return;
        }

        this.channelMessages = new java.util.ArrayList<ChannelMessageSummary>(channelMessages);
    }

    /**
     *

     * The information about, and content of, each requested message.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setChannelMessages(java.util.Collection)} or {@link #withChannelMessages(java.util.Collection)} if you
     * want to override the existing values.
     *

     *
     * @param channelMessages
     *        The information about, and content of, each requested message.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListChannelMessagesResult withChannelMessages(ChannelMessageSummary... channelMessages) {
        if (this.channelMessages == null) {
            setChannelMessages(new java.util.ArrayList<ChannelMessageSummary>(channelMessages.length));
        }
        for (ChannelMessageSummary ele : channelMessages) {
            this.channelMessages.add(ele);
        }
        return this;
    }

    /**
     *

     * The information about, and content of, each requested message.
     *

     *
     * @param channelMessages
     *        The information about, and content of, each requested message.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListChannelMessagesResult withChannelMessages(java.util.Collection<ChannelMessageSummary> channelMessages) {
        setChannelMessages(channelMessages);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getChannelArn() != null)
            sb.append("ChannelArn: ").append(getChannelArn()).append(",");
        if (getNextToken() != null)
            sb.append("NextToken: ").append("***Sensitive Data Redacted***").append(",");
        if (getChannelMessages() != null)
            sb.append("ChannelMessages: ").append(getChannelMessages());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof ListChannelMessagesResult == false)
            return false;
        ListChannelMessagesResult other = (ListChannelMessagesResult) obj;
        if (other.getChannelArn() == null ^ this.getChannelArn() == null)
            return false;
        if (other.getChannelArn() != null && other.getChannelArn().equals(this.getChannelArn()) == false)
            return false;
        if (other.getNextToken() == null ^ this.getNextToken() == null)
            return false;
        if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
            return false;
        if (other.getChannelMessages() == null ^ this.getChannelMessages() == null)
            return false;
        if (other.getChannelMessages() != null && other.getChannelMessages().equals(this.getChannelMessages()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getChannelArn() == null) ? 0 : getChannelArn().hashCode());
        hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
        hashCode = prime * hashCode + ((getChannelMessages() == null) ? 0 : getChannelMessages().hashCode());
        return hashCode;
    }

    @Override
    public ListChannelMessagesResult clone() {
        try {
            return (ListChannelMessagesResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
package androidx.media3.exoplayer.upstream;

import android.content.Context;
import android.os.Handler;
import androidx.annotation.Nullable;
import androidx.media3.common.C;
import androidx.media3.common.util.Assertions;
import androidx.media3.common.util.Clock;
import androidx.media3.common.util.NetworkTypeObserver;
import androidx.media3.common.util.UnstableApi;
import androidx.media3.common.util.Util;
import androidx.media3.datasource.DataSource;
import androidx.media3.datasource.DataSpec;
import androidx.media3.datasource.TransferListener;
import androidx.media3.exoplayer.upstream.BandwidthMeter.EventListener.EventDispatcher;
import com.google.common.base.Ascii;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.HashMap;
import java.util.Map;

/**
 * Estimates bandwidth by listening to data transfers.
 *
 *
The bandwidth estimate is calculated using a {@link SlidingPercentile} and is updated each
 * time a transfer ends. The initial estimate is based on the current operator's network country
 * code or the locale of the user, as well as the network connection type. This can be configured in
 * the {@link Builder}.
 */
@UnstableApi
public final class DefaultBandwidthMeter implements BandwidthMeter, TransferListener {

  /** Default initial Wifi bitrate estimate in bits per second. */
  public static final ImmutableList<Long> DEFAULT_INITIAL_BITRATE_ESTIMATES_WIFI =
      ImmutableList.of(4_800_000L, 3_100_000L, 2_100_000L, 1_500_000L, 800_000L);

  /** Default initial 2G bitrate estimates in bits per second. */
  public static final ImmutableList<Long> DEFAULT_INITIAL_BITRATE_ESTIMATES_2G =
      ImmutableList.of(1_500_000L, 1_000_000L, 730_000L, 440_000L, 170_000L);

  /** Default initial 3G bitrate estimates in bits per second. */
  public static final ImmutableList<Long> DEFAULT_INITIAL_BITRATE_ESTIMATES_3G =
      ImmutableList.of(2_200_000L, 1_400_000L, 1_100_000L, 910_000L, 620_000L);

  /** Default initial 4G bitrate estimates in bits per second. */
  public static final ImmutableList<Long> DEFAULT_INITIAL_BITRATE_ESTIMATES_4G =
      ImmutableList.of(3_000_000L, 1_900_000L, 1_400_000L, 1_000_000L, 660_000L);

  /** Default initial 5G-NSA bitrate estimates in bits per second. */
  public static final ImmutableList<Long> DEFAULT_INITIAL_BITRATE_ESTIMATES_5G_NSA =
      ImmutableList.of(6_000_000L, 4_100_000L, 3_200_000L, 1_800_000L, 1_000_000L);

  /** Default initial 5G-SA bitrate estimates in bits per second. */
  public static final ImmutableList<Long> DEFAULT_INITIAL_BITRATE_ESTIMATES_5G_SA =
      ImmutableList.of(2_800_000L, 2_400_000L, 1_600_000L, 1_100_000L, 950_000L);

  /**
   * Default initial bitrate estimate used when the device is offline or the network type cannot be
   * determined, in bits per second.
   */
  public static final long DEFAULT_INITIAL_BITRATE_ESTIMATE = 1_000_000;

  /** Default maximum weight for the sliding window. */
  public static final int DEFAULT_SLIDING_WINDOW_MAX_WEIGHT = 2000;

  /**
   * Index for the Wifi group index in the array returned by {@link
   * #getInitialBitrateCountryGroupAssignment}.
   */
  private static final int COUNTRY_GROUP_INDEX_WIFI = 0;
  /**
   * Index for the 2G group index in the array returned by {@link
   * #getInitialBitrateCountryGroupAssignment}.
   */
  private static final int COUNTRY_GROUP_INDEX_2G = 1;
  /**
   * Index for the 3G group index in the array returned by {@link
   * #getInitialBitrateCountryGroupAssignment}.
   */
  private static final int COUNTRY_GROUP_INDEX_3G = 2;
  /**
   * Index for the 4G group index in the array returned by {@link
   * #getInitialBitrateCountryGroupAssignment}.
   */
  private static final int COUNTRY_GROUP_INDEX_4G = 3;
  /**
   * Index for the 5G-NSA group index in the array returned by {@link
   * #getInitialBitrateCountryGroupAssignment}.
   */
  private static final int COUNTRY_GROUP_INDEX_5G_NSA = 4;
  /**
   * Index for the 5G-SA group index in the array returned by {@link
   * #getInitialBitrateCountryGroupAssignment}.
   */
  private static final int COUNTRY_GROUP_INDEX_5G_SA = 5;

  @Nullable private static DefaultBandwidthMeter singletonInstance;

  /** Builder for a bandwidth meter. */
  public static final class Builder {

    @Nullable private final Context context;

    private Map<Integer, Long> initialBitrateEstimates;
    private int slidingWindowMaxWeight;
    private Clock clock;
    private boolean resetOnNetworkTypeChange;

    /**
     * Creates a builder with default parameters and without listener.
     *
     * @param context A context.
     */
    public Builder(Context context) {
      // Handling of null is for backward compatibility only.
      this.context = context == null ? null : context.getApplicationContext();
      initialBitrateEstimates = getInitialBitrateEstimatesForCountry(Util.getCountryCode(context));
      slidingWindowMaxWeight = DEFAULT_SLIDING_WINDOW_MAX_WEIGHT;
      clock = Clock.DEFAULT;
      resetOnNetworkTypeChange = true;
    }

    /**
     * Sets the maximum weight for the sliding window.
     *
     * @param slidingWindowMaxWeight The maximum weight for the sliding window.
     * @return This builder.
     */
    @CanIgnoreReturnValue
    public Builder setSlidingWindowMaxWeight(int slidingWindowMaxWeight) {
      this.slidingWindowMaxWeight = slidingWindowMaxWeight;
      return this;
    }

    /**
     * Sets the initial bitrate estimate in bits per second that should be assumed when a bandwidth
     * estimate is unavailable.
     *
     * @param initialBitrateEstimate The initial bitrate estimate in bits per second.
     * @return This builder.
     */
    @CanIgnoreReturnValue
    public Builder setInitialBitrateEstimate(long initialBitrateEstimate) {
      for (Integer networkType : initialBitrateEstimates.keySet()) {
        setInitialBitrateEstimate(networkType, initialBitrateEstimate);
      }
      return this;
    }

    /**
     * Sets the initial bitrate estimate in bits per second that should be assumed when a bandwidth
     * estimate is unavailable and the current network connection is of the specified type.
     *
     * @param networkType The {@link C.NetworkType} this initial estimate is for.
     * @param initialBitrateEstimate The initial bitrate estimate in bits per second.
     * @return This builder.
     */
    @CanIgnoreReturnValue
    public Builder setInitialBitrateEstimate(
        @C.NetworkType int networkType, long initialBitrateEstimate) {
      initialBitrateEstimates.put(networkType, initialBitrateEstimate);
      return this;
    }

    /**
     * Sets the initial bitrate estimates to the default values of the specified country. The
     * initial estimates are used when a bandwidth estimate is unavailable.
     *
     * @param countryCode The ISO 3166-1 alpha-2 country code of the country whose default bitrate
     *     estimates should be used.
     * @return This builder.
     */
    @CanIgnoreReturnValue
    public Builder setInitialBitrateEstimate(String countryCode) {
      initialBitrateEstimates =
          getInitialBitrateEstimatesForCountry(Ascii.toUpperCase(countryCode));
      return this;
    }

    /**
     * Sets the clock used to estimate bandwidth from data transfers. Should only be set for testing
     * purposes.
     *
     * @param clock The clock used to estimate bandwidth from data transfers.
     * @return This builder.
     */
    @CanIgnoreReturnValue
    public Builder setClock(Clock clock) {
      this.clock = clock;
      return this;
    }

    /**
     * Sets whether to reset if the network type changes. The default value is {@code true}.
     *
     * @param resetOnNetworkTypeChange Whether to reset if the network type changes.
     * @return This builder.
     */
    @CanIgnoreReturnValue
    public Builder setResetOnNetworkTypeChange(boolean resetOnNetworkTypeChange) {
      this.resetOnNetworkTypeChange = resetOnNetworkTypeChange;
      return this;
    }

    /**
     * Builds the bandwidth meter.
     *
     * @return A bandwidth meter with the configured properties.
     */
    public DefaultBandwidthMeter build() {
      return new DefaultBandwidthMeter(
          context,
          initialBitrateEstimates,
          slidingWindowMaxWeight,
          clock,
          resetOnNetworkTypeChange);
    }

    private static Map<Integer, Long> getInitialBitrateEstimatesForCountry(String countryCode) {
      int[] groupIndices = getInitialBitrateCountryGroupAssignment(countryCode);
      Map<Integer, Long> result = new HashMap<>(/* initialCapacity= */ 8);
      result.put(C.NETWORK_TYPE_UNKNOWN, DEFAULT_INITIAL_BITRATE_ESTIMATE);
      result.put(
          C.NETWORK_TYPE_WIFI,
          DEFAULT_INITIAL_BITRATE_ESTIMATES_WIFI.get(groupIndices[COUNTRY_GROUP_INDEX_WIFI]));
      result.put(
          C.NETWORK_TYPE_2G,
          DEFAULT_INITIAL_BITRATE_ESTIMATES_2G.get(groupIndices[COUNTRY_GROUP_INDEX_2G]));
      result.put(
          C.NETWORK_TYPE_3G,
          DEFAULT_INITIAL_BITRATE_ESTIMATES_3G.get(groupIndices[COUNTRY_GROUP_INDEX_3G]));
      result.put(
          C.NETWORK_TYPE_4G,
          DEFAULT_INITIAL_BITRATE_ESTIMATES_4G.get(groupIndices[COUNTRY_GROUP_INDEX_4G]));
      result.put(
          C.NETWORK_TYPE_5G_NSA,
          DEFAULT_INITIAL_BITRATE_ESTIMATES_5G_NSA.get(groupIndices[COUNTRY_GROUP_INDEX_5G_NSA]));
      result.put(
          C.NETWORK_TYPE_5G_SA,
          DEFAULT_INITIAL_BITRATE_ESTIMATES_5G_SA.get(groupIndices[COUNTRY_GROUP_INDEX_5G_SA]));
      // Assume default Wifi speed for Ethernet to prevent using the slower fallback.
      result.put(
          C.NETWORK_TYPE_ETHERNET,
          DEFAULT_INITIAL_BITRATE_ESTIMATES_WIFI.get(groupIndices[COUNTRY_GROUP_INDEX_WIFI]));
      return result;
    }
  }

  /**
   * Returns a singleton instance of a {@link DefaultBandwidthMeter} with default configuration.
   *
   * @param context A {@link Context}.
   * @return The singleton instance.
   */
  public static synchronized DefaultBandwidthMeter getSingletonInstance(Context context) {
    if (singletonInstance == null) {
      singletonInstance = new DefaultBandwidthMeter.Builder(context).build();
    }
    return singletonInstance;
  }

  private static final int ELAPSED_MILLIS_FOR_ESTIMATE = 2000;
  private static final int BYTES_TRANSFERRED_FOR_ESTIMATE = 512 * 1024;

  private final ImmutableMap<Integer, Long> initialBitrateEstimates;
  private final EventDispatcher eventDispatcher;
  private final SlidingPercentile slidingPercentile;
  private final Clock clock;
  private final boolean resetOnNetworkTypeChange;

  private int streamCount;
  private long sampleStartTimeMs;
  private long sampleBytesTransferred;

  private @C.NetworkType int networkType;
  private long totalElapsedTimeMs;
  private long totalBytesTransferred;
  private long bitrateEstimate;
  private long lastReportedBitrateEstimate;

  private boolean networkTypeOverrideSet;
  private @C.NetworkType int networkTypeOverride;

  /**
   * @deprecated Use {@link Builder} instead.
   */
  @Deprecated
  public DefaultBandwidthMeter() {
    this(
        /* context= */ null,
        /* initialBitrateEstimates= */ ImmutableMap.of(),
        DEFAULT_SLIDING_WINDOW_MAX_WEIGHT,
        Clock.DEFAULT,
        /* resetOnNetworkTypeChange= */ false);
  }

  private DefaultBandwidthMeter(
      @Nullable Context context,
      Map<Integer, Long> initialBitrateEstimates,
      int maxWeight,
      Clock clock,
      boolean resetOnNetworkTypeChange) {
    this.initialBitrateEstimates = ImmutableMap.copyOf(initialBitrateEstimates);
    this.eventDispatcher = new EventDispatcher();
    this.slidingPercentile = new SlidingPercentile(maxWeight);
    this.clock = clock;
    this.resetOnNetworkTypeChange = resetOnNetworkTypeChange;
    if (context != null) {
      NetworkTypeObserver networkTypeObserver = NetworkTypeObserver.getInstance(context);
      networkType = networkTypeObserver.getNetworkType();
      bitrateEstimate = getInitialBitrateEstimateForNetworkType(networkType);
      networkTypeObserver.register(/* listener= */ this::onNetworkTypeChanged);
    } else {
      networkType = C.NETWORK_TYPE_UNKNOWN;
      bitrateEstimate = getInitialBitrateEstimateForNetworkType(C.NETWORK_TYPE_UNKNOWN);
    }
  }

  /**
   * Overrides the network type. Handled in the same way as if the meter had detected a change from
   * the current network type to the specified network type internally.
   *
   *
Applications should not normally call this method. It is intended for testing purposes.
   *
   * @param networkType The overriding network type.
   */
  public synchronized void setNetworkTypeOverride(@C.NetworkType int networkType) {
    networkTypeOverride = networkType;
    networkTypeOverrideSet = true;
    onNetworkTypeChanged(networkType);
  }

  @Override
  public synchronized long getBitrateEstimate() {
    return bitrateEstimate;
  }

  @Override
  public TransferListener getTransferListener() {
    return this;
  }

  @Override
  public void addEventListener(Handler eventHandler, EventListener eventListener) {
    Assertions.checkNotNull(eventHandler);
    Assertions.checkNotNull(eventListener);
    eventDispatcher.addListener(eventHandler, eventListener);
  }

  @Override
  public void removeEventListener(EventListener eventListener) {
    eventDispatcher.removeListener(eventListener);
  }

  @Override
  public void onTransferInitializing(DataSource source, DataSpec dataSpec, boolean isNetwork) {
    // Do nothing.
  }

  @Override
  public synchronized void onTransferStart(
      DataSource source, DataSpec dataSpec, boolean isNetwork) {
    if (!isTransferAtFullNetworkSpeed(dataSpec, isNetwork)) {
      return;
    }
    if (streamCount == 0) {
      sampleStartTimeMs = clock.elapsedRealtime();
    }
    streamCount++;
  }

  @Override
  public synchronized void onBytesTransferred(
      DataSource source, DataSpec dataSpec, boolean isNetwork, int bytesTransferred) {
    if (!isTransferAtFullNetworkSpeed(dataSpec, isNetwork)) {
      return;
    }
    sampleBytesTransferred += bytesTransferred;
  }

  @Override
  public synchronized void onTransferEnd(DataSource source, DataSpec dataSpec, boolean isNetwork) {
    if (!isTransferAtFullNetworkSpeed(dataSpec, isNetwork)) {
      return;
    }
    Assertions.checkState(streamCount > 0);
    long nowMs = clock.elapsedRealtime();
    int sampleElapsedTimeMs = (int) (nowMs - sampleStartTimeMs);
    totalElapsedTimeMs += sampleElapsedTimeMs;
    totalBytesTransferred += sampleBytesTransferred;
    if (sampleElapsedTimeMs > 0) {
      float bitsPerSecond = (sampleBytesTransferred * 8000f) / sampleElapsedTimeMs;
      slidingPercentile.addSample((int) Math.sqrt(sampleBytesTransferred), bitsPerSecond);
      if (totalElapsedTimeMs >= ELAPSED_MILLIS_FOR_ESTIMATE
          || totalBytesTransferred >= BYTES_TRANSFERRED_FOR_ESTIMATE) {
        bitrateEstimate = (long) slidingPercentile.getPercentile(0.5f);
      }
      maybeNotifyBandwidthSample(sampleElapsedTimeMs, sampleBytesTransferred, bitrateEstimate);
      sampleStartTimeMs = nowMs;
      sampleBytesTransferred = 0;
    } // Else any sample bytes transferred will be carried forward into the next sample.
    streamCount--;
  }

  private synchronized void onNetworkTypeChanged(@C.NetworkType int networkType) {
    if (this.networkType != C.NETWORK_TYPE_UNKNOWN && !resetOnNetworkTypeChange) {
      // Reset on network change disabled. Ignore all updates except the initial one.
      return;
    }

    if (networkTypeOverrideSet) {
      networkType = networkTypeOverride;
    }
    if (this.networkType == networkType) {
      return;
    }

    this.networkType = networkType;
    if (networkType == C.NETWORK_TYPE_OFFLINE
        || networkType == C.NETWORK_TYPE_UNKNOWN
        || networkType == C.NETWORK_TYPE_OTHER) {
      // It's better not to reset the bandwidth meter for these network types.
      return;
    }

    // Reset the bitrate estimate and report it, along with any bytes transferred.
    this.bitrateEstimate = getInitialBitrateEstimateForNetworkType(networkType);
    long nowMs = clock.elapsedRealtime();
    int sampleElapsedTimeMs = streamCount > 0 ? (int) (nowMs - sampleStartTimeMs) : 0;
    maybeNotifyBandwidthSample(sampleElapsedTimeMs, sampleBytesTransferred, bitrateEstimate);

    // Reset the remainder of the state.
    sampleStartTimeMs = nowMs;
    sampleBytesTransferred = 0;
    totalBytesTransferred = 0;
    totalElapsedTimeMs = 0;
    slidingPercentile.reset();
  }

  private void maybeNotifyBandwidthSample(
      int elapsedMs, long bytesTransferred, long bitrateEstimate) {
    if (elapsedMs == 0 && bytesTransferred == 0 && bitrateEstimate == lastReportedBitrateEstimate) {
      return;
    }
    lastReportedBitrateEstimate = bitrateEstimate;
    eventDispatcher.bandwidthSample(elapsedMs, bytesTransferred, bitrateEstimate);
  }

  private long getInitialBitrateEstimateForNetworkType(@C.NetworkType int networkType) {
    Long initialBitrateEstimate = initialBitrateEstimates.get(networkType);
    if (initialBitrateEstimate == null) {
      initialBitrateEstimate = initialBitrateEstimates.get(C.NETWORK_TYPE_UNKNOWN);
    }
    if (initialBitrateEstimate == null) {
      initialBitrateEstimate = DEFAULT_INITIAL_BITRATE_ESTIMATE;
    }
    return initialBitrateEstimate;
  }

  private static boolean isTransferAtFullNetworkSpeed(DataSpec dataSpec, boolean isNetwork) {
    return isNetwork && !dataSpec.isFlagSet(DataSpec.FLAG_MIGHT_NOT_USE_FULL_NETWORK_SPEED);
  }

  /**
   * Returns initial bitrate group assignments for a {@code country}. The initial bitrate is a list
   * of indices for [Wifi, 2G, 3G, 4G, 5G_NSA, 5G_SA].
   */
  private static int[] getInitialBitrateCountryGroupAssignment(String country) {
    switch (country) {
      case "AE":
        return new int[] {1, 4, 4, 4, 4, 0};
      case "AG":
        return new int[] {2, 4, 1, 2, 2, 2};
      case "AI":
        return new int[] {0, 2, 0, 3, 2, 2};
      case "AM":
        return new int[] {2, 3, 2, 3, 2, 2};
      case "AO":
        return new int[] {4, 4, 3, 2, 2, 2};
      case "AS":
        return new int[] {2, 2, 3, 3, 2, 2};
      case "AT":
        return new int[] {1, 0, 1, 1, 0, 0};
      case "AU":
        return new int[] {0, 1, 1, 1, 2, 0};
      case "AW":
        return new int[] {1, 3, 4, 4, 2, 2};
      case "BA":
        return new int[] {1, 2, 1, 1, 2, 2};
      case "BD":
        return new int[] {2, 1, 3, 3, 2, 2};
      case "BE":
        return new int[] {0, 1, 4, 4, 3, 2};
      case "BF":
        return new int[] {4, 3, 4, 3, 2, 2};
      case "BH":
        return new int[] {1, 2, 1, 3, 4, 2};
      case "BJ":
        return new int[] {4, 4, 3, 3, 2, 2};
      case "BO":
        return new int[] {1, 2, 3, 2, 2, 2};
      case "BS":
        return new int[] {4, 4, 2, 2, 2, 2};
      case "BT":
        return new int[] {3, 1, 3, 2, 2, 2};
      case "BW":
        return new int[] {3, 2, 1, 0, 2, 2};
      case "BY":
        return new int[] {0, 1, 2, 3, 2, 2};
      case "BZ":
        return new int[] {2, 4, 2, 1, 2, 2};
      case "CA":
        return new int[] {0, 2, 2, 2, 3, 2};
      case "CD":
        return new int[] {4, 2, 3, 2, 2, 2};
      case "CH":
        return new int[] {0, 0, 0, 1, 0, 2};
      case "CM":
        return new int[] {3, 3, 3, 3, 2, 2};
      case "CN":
        return new int[] {2, 0, 1, 1, 3, 2};
      case "CO":
        return new int[] {2, 3, 4, 3, 2, 2};
      case "CR":
        return new int[] {2, 3, 4, 4, 2, 2};
      case "CV":
        return new int[] {2, 1, 0, 0, 2, 2};
      case "BN":
      case "CW":
        return new int[] {2, 2, 0, 0, 2, 2};
      case "DE":
        return new int[] {0, 1, 2, 2, 2, 3};
      case "DK":
        return new int[] {0, 0, 3, 2, 0, 2};
      case "DO":
        return new int[] {3, 4, 4, 4, 4, 2};
      case "EC":
        return new int[] {2, 3, 2, 1, 2, 2};
      case "ET":
        return new int[] {4, 3, 3, 1, 2, 2};
      case "FI":
        return new int[] {0, 0, 0, 3, 0, 2};
      case "FJ":
        return new int[] {3, 1, 2, 2, 2, 2};
      case "FM":
        return new int[] {4, 2, 4, 1, 2, 2};
      case "FR":
        return new int[] {1, 2, 3, 1, 0, 2};
      case "GB":
        return new int[] {0, 0, 1, 1, 1, 1};
      case "GE":
        return new int[] {1, 1, 1, 2, 2, 2};
      case "BB":
      case "DM":
      case "FO":
      case "GI":
        return new int[] {0, 2, 0, 0, 2, 2};
      case "AF":
      case "GM":
        return new int[] {4, 3, 3, 4, 2, 2};
      case "GN":
        return new int[] {4, 3, 4, 2, 2, 2};
      case "GQ":
        return new int[] {4, 2, 1, 4, 2, 2};
      case "GT":
        return new int[] {2, 3, 2, 2, 2, 2};
      case "CG":
      case "EG":
      case "GW":
        return new int[] {3, 4, 3, 3, 2, 2};
      case "GY":
        return new int[] {3, 2, 2, 1, 2, 2};
      case "HK":
        return new int[] {0, 1, 2, 3, 2, 0};
      case "HU":
        return new int[] {0, 0, 0, 1, 3, 2};
      case "ID":
        return new int[] {3, 1, 2, 2, 3, 2};
      case "ES":
      case "IE":
        return new int[] {0, 1, 1, 1, 2, 2};
      case "CL":
      case "IL":
        return new int[] {1, 2, 2, 2, 3, 2};
      case "IN":
        return new int[] {1, 1, 3, 2, 3, 3};
      case "IQ":
        return new int[] {3, 2, 2, 3, 2, 2};
      case "IR":
        return new int[] {3, 0, 1, 1, 4, 1};
      case "IT":
        return new int[] {0, 0, 0, 1, 1, 2};
      case "JM":
        return new int[] {2, 4, 3, 2, 2, 2};
      case "JO":
        return new int[] {2, 1, 1, 2, 2, 2};
      case "JP":
        return new int[] {0, 1, 1, 2, 2, 4};
      case "KH":
        return new int[] {2, 1, 4, 2, 2, 2};
      case "CF":
      case "KI":
        return new int[] {4, 2, 4, 2, 2, 2};
      case "FK":
      case "KE":
      case "KP":
        return new int[] {3, 2, 2, 2, 2, 2};
      case "KR":
        return new int[] {0, 1, 1, 3, 4, 4};
      case "CY":
      case "KW":
        return new int[] {1, 0, 0, 0, 0, 2};
      case "KZ":
        return new int[] {2, 1, 2, 2, 2, 2};
      case "LA":
        return new int[] {1, 2, 1, 3, 2, 2};
      case "LB":
        return new int[] {3, 3, 2, 4, 2, 2};
      case "LK":
        return new int[] {3, 1, 3, 3, 4, 2};
      case "CI":
      case "DZ":
      case "LR":
        return new int[] {3, 4, 4, 4, 2, 2};
      case "LS":
        return new int[] {3, 3, 2, 2, 2, 2};
      case "LT":
        return new int[] {0, 0, 0, 0, 2, 2};
      case "LU":
        return new int[] {1, 0, 3, 2, 1, 4};
      case "MA":
        return new int[] {3, 3, 1, 1, 2, 2};
      case "MC":
        return new int[] {0, 2, 2, 0, 2, 2};
      case "ME":
        return new int[] {2, 0, 0, 1, 2, 2};
      case "MK":
        return new int[] {1, 0, 0, 1, 3, 2};
      case "MM":
        return new int[] {2, 4, 2, 3, 2, 2};
      case "MN":
        return new int[] {2, 0, 1, 2, 2, 2};
      case "MO":
      case "MP":
        return new int[] {0, 2, 4, 4, 2, 2};
      case "GP":
      case "MQ":
        return new int[] {2, 1, 2, 3, 2, 2};
      case "MU":
        return new int[] {3, 1, 1, 2, 2, 2};
      case "MV":
        return new int[] {3, 4, 1, 4, 2, 2};
      case "MW":
        return new int[] {4, 2, 3, 3, 2, 2};
      case "MX":
        return new int[] {2, 4, 3, 4, 2, 2};
      case "MY":
        return new int[] {1, 0, 3, 1, 3, 2};
      case "MZ":
        return new int[] {3, 1, 2, 1, 2, 2};
      case "NC":
        return new int[] {3, 3, 4, 4, 2, 2};
      case "NG":
        return new int[] {3, 4, 2, 1, 2, 2};
      case "NL":
        return new int[] {0, 2, 2, 3, 0, 3};
      case "CZ":
      case "NO":
        return new int[] {0, 0, 2, 0, 1, 2};
      case "NP":
        return new int[] {2, 2, 4, 3, 2, 2};
      case "NR":
      case "NU":
        return new int[] {4, 2, 2, 1, 2, 2};
      case "OM":
        return new int[] {2, 3, 1, 3, 4, 2};
      case "GU":
      case "PE":
        return new int[] {1, 2, 4, 4, 4, 2};
      case "CK":
      case "PF":
        return new int[] {2, 2, 2, 1, 2, 2};
      case "ML":
      case "PG":
        return new int[] {4, 3, 3, 2, 2, 2};
      case "PH":
        return new int[] {2, 1, 3, 3, 3, 0};
      case "NZ":
      case "PL":
        return new int[] {1, 1, 2, 2, 4, 2};
      case "PR":
        return new int[] {2, 0, 2, 1, 2, 1};
      case "PS":
        return new int[] {3, 4, 1, 2, 2, 2};
      case "PW":
        return new int[] {2, 2, 4, 1, 2, 2};
      case "QA":
        return new int[] {2, 4, 4, 4, 4, 2};
      case "MF":
      case "RE":
        return new int[] {1, 2, 1, 2, 2, 2};
      case "RO":
        return new int[] {0, 0, 1, 2, 1, 2};
      case "MD":
      case "RS":
        return new int[] {1, 0, 0, 0, 2, 2};
      case "RU":
        return new int[] {1, 0, 0, 0, 4, 3};
      case "RW":
        return new int[] {3, 4, 2, 0, 2, 2};
      case "SA":
        return new int[] {3, 1, 1, 1, 2, 2};
      case "SB":
        return new int[] {4, 2, 4, 3, 2, 2};
      case "SG":
        return new int[] {1, 1, 2, 2, 2, 1};
      case "AQ":
      case "ER":
      case "SH":
        return new int[] {4, 2, 2, 2, 2, 2};
      case "GR":
      case "HR":
      case "SI":
        return new int[] {1, 0, 0, 0, 1, 2};
      case "BG":
      case "MT":
      case "SK":
        return new int[] {0, 0, 0, 0, 1, 2};
      case "AX":
      case "LI":
      case "MS":
      case "PM":
      case "SM":
        return new int[] {0, 2, 2, 2, 2, 2};
      case "SN":
        return new int[] {4, 4, 4, 3, 2, 2};
      case "SR":
        return new int[] {2, 4, 3, 0, 2, 2};
      case "SS":
        return new int[] {4, 3, 2, 3, 2, 2};
      case "ST":
        return new int[] {2, 2, 1, 2, 2, 2};
      case "NI":
      case "PA":
      case "SV":
        return new int[] {2, 3, 3, 3, 2, 2};
      case "SZ":
        return new int[] {3, 3, 3, 4, 2, 2};
      case "SX":
      case "TC":
        return new int[] {1, 2, 1, 0, 2, 2};
      case "GA":
      case "TG":
        return new int[] {3, 4, 1, 0, 2, 2};
      case "TH":
        return new int[] {0, 2, 2, 3, 3, 4};
      case "TK":
        return new int[] {2, 2, 2, 4, 2, 2};
      case "CU":
      case "DJ":
      case "SY":
      case "TJ":
      case "TL":
        return new int[] {4, 3, 4, 4, 2, 2};
      case "SC":
      case "TM":
        return new int[] {4, 2, 1, 1, 2, 2};
      case "AZ":
      case "GF":
      case "LY":
      case "PK":
      case "SO":
      case "TO":
        return new int[] {3, 2, 3, 3, 2, 2};
      case "TR":
        return new int[] {1, 1, 0, 0, 2, 2};
      case "TT":
        return new int[] {1, 4, 1, 3, 2, 2};
      case "EE":
      case "IS":
      case "LV":
      case "PT":
      case "SE":
      case "TW":
        return new int[] {0, 0, 0, 0, 0, 2};
      case "TZ":
        return new int[] {3, 4, 3, 2, 2, 2};
      case "IM":
      case "UA":
        return new int[] {0, 2, 1, 1, 2, 2};
      case "SL":
      case "UG":
        return new int[] {3, 3, 4, 3, 2, 2};
      case "US":
        return new int[] {1, 0, 2, 2, 3, 1};
      case "AR":
      case "KG":
      case "TN":
      case "UY":
        return new int[] {2, 1, 1, 1, 2, 2};
      case "UZ":
        return new int[] {2, 2, 3, 4, 2, 2};
      case "BL":
      case "CX":
      case "VA":
        return new int[] {1, 2, 2, 2, 2, 2};
      case "AD":
      case "BM":
      case "BQ":
      case "GD":
      case "GL":
      case "KN":
      case "KY":
      case "LC":
      case "VC":
        return new int[] {1, 2, 0, 0, 2, 2};
      case "VG":
        return new int[] {2, 2, 1, 1, 2, 2};
      case "GG":
      case "VI":
        return new int[] {0, 2, 0, 1, 2, 2};
      case "VN":
        return new int[] {0, 3, 3, 4, 2, 2};
      case "GH":
      case "NA":
      case "VU":
        return new int[] {3, 3, 3, 2, 2, 2};
      case "IO":
      case "MH":
      case "TV":
      case "WF":
        return new int[] {4, 2, 2, 4, 2, 2};
      case "WS":
        return new int[] {3, 1, 3, 1, 2, 2};
      case "AL":
      case "XK":
        return new int[] {1, 1, 1, 1, 2, 2};
      case "BI":
      case "HT":
      case "KM":
      case "MG":
      case "NE":
      case "SD":
      case "TD":
      case "VE":
      case "YE":
        return new int[] {4, 4, 4, 4, 2, 2};
      case "JE":
      case "YT":
        return new int[] {4, 2, 2, 3, 2, 2};
      case "ZA":
        return new int[] {3, 2, 2, 1, 1, 2};
      case "ZM":
        return new int[] {3, 3, 4, 2, 2, 2};
      case "MR":
      case "ZW":
        return new int[] {4, 2, 4, 4, 2, 2};
      default:
        return new int[] {2, 2, 2, 2, 2, 2};
    }
  }
}


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>simpleEventObjectDemo </title>
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">

		<button>click me</button>

		<input type="text" placeholder="write in me">


text:
package goja.mvc.render.ftl.shiro.permission;

import goja.mvc.render.ftl.shiro.auth.SecureTag;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModelException;

import java.io.IOException;
import java.util.Map;

/**
 * <p> . </p>
 *
 * @author poplar.yfyang
 * @version 1.0 2012-10-27 10:37 AM
 * @since JDK 1.5
 */
public abstract class PermissionTag extends SecureTag {

    String getName(Map params) {
        return getParam(params, "name");
    }

    @Override
    protected void verifyParameters(Map params) throws TemplateModelException {
        String permission = getName(params);

        if (permission == null || permission.length() == 0) {
            throw new TemplateModelException("The 'name' tag attribute must be set.");
        }
    }

    @Override
    public void render(Environment env, Map params, TemplateDirectiveBody body) throws IOException, TemplateException {
        String p = getName(params);

        boolean show = showTagBody(p);
        if (show) {
            renderBody(env, body);
        }
    }

    protected boolean isPermitted(String p) {
        return getSubject() != null && getSubject().isPermitted(p);
    }

    protected abstract boolean showTagBody(String p);
}


text:
package configuration;

import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

import static org.junit.Assert.assertEquals;

/**
 * Configuration Unit test
 *
 * David Maignan <davidmaignan@gmail.com>
 */
public class ConfigurationTest {
    Configuration configConfiguration;

    @Before
    public void setUp() throws IOException{
        configConfiguration = new Configuration();
    }

    @Test(timeout = 1000)
    public void testJDrivePathExists() throws Exception{
        Configuration configConfiguration = new Configuration();

        assertEquals("/Test/Path", configConfiguration.getProperty("rootFolder"));
    }

    @Test(timeout = 1000)
    public void testNoPropertyFound() throws Exception {
        Configuration configConfiguration = new Configuration();

        assertEquals(null, configConfiguration.getProperty("mockProperty"));
    }

    @Test(timeout = 1000)
    public void testDBNameExists() throws Exception {
        Configuration configConfiguration = new Configuration();

        assertEquals("db_test", configConfiguration.getProperty("dbName"));
    }
}


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports System.Collections.Immutable
Imports Microsoft.VisualStudio.Shell.TableControl
Imports Microsoft.VisualStudio.Shell.TableManager

Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Diagnostics
    Friend Class TestTableManagerProvider
        Implements ITableManagerProvider

        Public Function GetTableManager(identifier As String) As ITableManager Implements ITableManagerProvider.GetTableManager
            Return New TestTableManager(identifier)
        End Function

        Public Class TestTableManager
            Implements ITableManager

            Private ReadOnly _identifier As String
            Private ReadOnly _sources As Dictionary(Of ITableDataSource, String())
            Private ReadOnly _sinks As Dictionary(Of ITableDataSink, IDisposable)

            Public Sub New(identifier As String)
                Me._identifier = identifier
                Me._sources = New Dictionary(Of ITableDataSource, String())()
                Me._sinks = New Dictionary(Of ITableDataSink, IDisposable)()
            End Sub

            Public ReadOnly Property Identifier As String Implements ITableManager.Identifier
                Get
                    Return _identifier
                End Get
            End Property

            Public ReadOnly Property Sources As IReadOnlyList(Of ITableDataSource) Implements ITableManager.Sources
                Get
                    Return _sources.Keys.ToImmutableArray()
                End Get
            End Property

            Public Event SourcesChanged As EventHandler Implements ITableManager.SourcesChanged

            Public Function AddSource(source As ITableDataSource, ParamArray columns() As String) As Boolean Implements ITableManager.AddSource
                _sources.Add(source, columns)

                Dim sink = New TestSink()
                Dim subscription = source.Subscribe(sink)

                _sinks.Add(sink, subscription)

                Return True
            End Function

            Public Function AddSource(source As ITableDataSource, columns As IReadOnlyCollection(Of String)) As Boolean Implements ITableManager.AddSource
                Return AddSource(source, columns.ToArray())
            End Function

            Public Function GetColumnsForSources(sources As IEnumerable(Of ITableDataSource)) As IReadOnlyList(Of String) Implements ITableManager.GetColumnsForSources
                Dim list = New List(Of String)

                For Each source In _sources.Keys
                    Dim columns As String() = Nothing
                    If _sources.TryGetValue(source, columns) Then
                        list.AddRange(columns)
                    End If
                Next

                Return list
            End Function

            Public Function RemoveSource(source As ITableDataSource) As Boolean Implements ITableManager.RemoveSource
                Return _sources.Remove(source)
            End Function

            Public ReadOnly Property Sinks_TestOnly As IEnumerable(Of KeyValuePair(Of ITableDataSink, IDisposable))
                Get
                    Return _sinks
                End Get
            End Property

            Public Class TestSink
                Implements ITableDataSink

                Public ReadOnly Entries As HashSet(Of ITableEntriesSnapshotFactory)

                Public Sub New()
                    Me.Entries = New HashSet(Of ITableEntriesSnapshotFactory)()
                End Sub

                Public Sub AddFactory(newFactory As ITableEntriesSnapshotFactory, Optional removeEverything As Boolean = False) Implements ITableDataSink.AddFactory
                    Me.Entries.Add(newFactory)
                End Sub

                Public Sub RemoveFactory(oldFactory As ITableEntriesSnapshotFactory) Implements ITableDataSink.RemoveFactory
                    Me.Entries.Remove(oldFactory)
                End Sub

                Public Sub ReplaceFactory(oldFactory As ITableEntriesSnapshotFactory, newFactory As ITableEntriesSnapshotFactory) Implements ITableDataSink.ReplaceFactory
                    Me.Entries.Remove(oldFactory)
                    Me.Entries.Add(newFactory)
                End Sub

                Public Sub FactorySnapshotChanged(factory As ITableEntriesSnapshotFactory) Implements ITableDataSink.FactorySnapshotChanged
                End Sub

                Public Sub AddEntries(newEntries As IReadOnlyList(Of ITableEntry), Optional removeEverything As Boolean = False) Implements ITableDataSink.AddEntries
                    Throw New NotImplementedException()
                End Sub

                Public Sub AddSnapshot(newSnapshot As ITableEntriesSnapshot, Optional removeEverything As Boolean = False) Implements ITableDataSink.AddSnapshot
                    Throw New NotImplementedException()
                End Sub

                Public Sub RemoveEntries(oldEntries As IReadOnlyList(Of ITableEntry)) Implements ITableDataSink.RemoveEntries
                    Throw New NotImplementedException()
                End Sub

                Public Sub RemoveSnapshot(oldSnapshot As ITableEntriesSnapshot) Implements ITableDataSink.RemoveSnapshot
                    Throw New NotImplementedException()
                End Sub

                Public Sub ReplaceEntries(oldEntries As IReadOnlyList(Of ITableEntry), newEntries As IReadOnlyList(Of ITableEntry)) Implements ITableDataSink.ReplaceEntries
                    Throw New NotImplementedException()
                End Sub

                Public Sub ReplaceSnapshot(oldSnapshot As ITableEntriesSnapshot, newSnapshot As ITableEntriesSnapshot) Implements ITableDataSink.ReplaceSnapshot
                    Throw New NotImplementedException()
                End Sub

                Public Sub RemoveAllEntries() Implements ITableDataSink.RemoveAllEntries
                    Throw New NotImplementedException()
                End Sub

                Public Sub RemoveAllSnapshots() Implements ITableDataSink.RemoveAllSnapshots
                    Throw New NotImplementedException()
                End Sub

                Public Sub RemoveAllFactories() Implements ITableDataSink.RemoveAllFactories
                    Throw New NotImplementedException()
                End Sub

                Public Property IsStable As Boolean Implements ITableDataSink.IsStable
                    Get
                        Return True
                    End Get
                    Set(value As Boolean)
                    End Set
                End Property
            End Class
        End Class
    End Class
End Namespace


text:
package org.jetbrains.plugins.groovy.lang.psi.typeEnhancers;

import com.intellij.psi.PsiArrayType;
import com.intellij.psi.PsiType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil;

import static org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.isCompileStatic;

public class GrContainerConverter extends GrTypeConverter {
  @Override
  public boolean isAllowedInMethodCall() {
    return false;
  }

  @Nullable
  @Override
  public Boolean isConvertible(@NotNull PsiType lType, @NotNull PsiType rType, @NotNull GroovyPsiElement context) {
    if (isCompileStatic(context)) return null;
    if (lType instanceof PsiArrayType) {
      PsiType lComponentType = ((PsiArrayType)lType).getComponentType();
      PsiType rComponentType = ClosureParameterEnhancer.findTypeForIteration(rType, context);
      if (rComponentType != null && TypesUtil.isAssignable(lComponentType, rComponentType, context)) {
        return Boolean.TRUE;
      }
    }

    return null;
  }
}


text:
/************************************************************************************//**
// Copyright (c) 2006-2015 Advanced Micro Devices, Inc. All rights reserved.
/// \author AMD Developer Tools Team
/// \file
****************************************************************************************/
#include "w_cpipeline_pch.h"
#include "JRTCommon.h"
#include "JRTCore.h"
#include "JRTMesh.h"

#include "JRTKDTree.h"
#include "JRTKDTreeBuilder.h"
#include "JRTHeuristicKDTreeBuilder.h"
#include "JRTH2KDTreeBuilder.h"

JRTCore::JRTCore() : m_pTree(NULL), m_pHitArray(new TootleRayHit[5]), m_nArraySize(5)
{

}

JRTCore::~JRTCore()
{
    JRT_SAFE_DELETE(m_pTree);
    JRT_SAFE_DELETE_ARRAY(m_pHitArray);
}

JRTCore* JRTCore::Build(const std::vector<JRTMesh*>& rMeshes)
{
    JRTCore* pCaster = new JRTCore();

    if (rMeshes.size() == 0)
    {
        pCaster->m_pTree = NULL;
        return pCaster;
    }

    // build KD tree
    JRTHeuristicKDTreeBuilder builder;
    JRTKDTree* pTree = builder.BuildTree(rMeshes);

    if (!pTree)
    {
        delete pCaster;
        return NULL;
    }

    pCaster->m_pTree = pTree;

    return pCaster;
}

int SortTootleHit(const void* h1, const void* h2)
{
    const TootleRayHit* ph1 = (const TootleRayHit*) h1;
    const TootleRayHit* ph2 = (const TootleRayHit*) h2;
    return ph1->t >= ph2->t;
}

/// \param rOrigin  The ray origin
/// \param rDirection The ray direction
/// \param ppHitArray  A pointer that will be set to point to an array of hits.  The caller should NOT delete the returned array
/// \param pHitCount   A pointer that will receive the number of hits in the returned array.
/// \return Returns false if out of memory, true otherwise.
bool JRTCore::FindAllHits(const Vec3f& rOrigin, const Vec3f& rDirection, TootleRayHit** ppHitArray, UINT* pHitCount)
{
    if (!m_pTree)
    {
        *ppHitArray = NULL;
        *pHitCount = 0;
    }

    UINT nHits = m_pTree->FindAllHits(rOrigin, rDirection, &m_pHitArray, &m_nArraySize);

    if (nHits == 0 || nHits == JRTKDTree::OUT_OF_MEMORY)
    {
        *ppHitArray = NULL;
        *pHitCount = 0;
    }

    if (nHits == JRTKDTree::OUT_OF_MEMORY)
    {
        return false;
    }

#ifdef DEBUG

    // verify that there are no duplicates, just a test
    for (UINT i = 0; i < nHits; i++)
    {
        for (UINT j = i + 1; j < nHits; j++)
        {
            JRT_ASSERT(m_pHitArray[i].nFaceID != m_pHitArray[j].nFaceID);
        }
    }

#endif

    // sort hits by distance
    qsort(m_pHitArray, nHits, sizeof(TootleRayHit), &SortTootleHit);
    *ppHitArray = m_pHitArray;
    *pHitCount = nHits;

    return true;
}

void JRTCore::CullBackfaces(const Vec3f& rViewDir, bool bCullCCW)
{
    m_pTree->CullBackfaces(rViewDir, bCullCCW);
}

bool JRTCore::GetSceneBBHit(const Vec3f& rOrigin, const Vec3f& rDirection, Vec3f* pHitPt)
{
    const JRTBoundingBox& rBB = m_pTree->GetSceneBounds();
    float fTMin, fTMax;

    if (!rBB.RayHit(rOrigin, rDirection, &fTMin, &fTMax))
    {
        return false;
    }

    if (fTMax < 0.0f)
    {
        return false;
    }

    *pHitPt  = rOrigin + rDirection * fTMax;
    return true;
}

const JRTBoundingBox& JRTCore::GetSceneBB() const
{
    return m_pTree->GetSceneBounds();
}


text:
package com.webstersmalley.countdown.numbers;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import static org.junit.Assert.assertEquals;

public class NumbersSolverTest {

    @Test
    public void numbersSolverSinglePermutationTest() {
        List<Integer> input = new ArrayList<Integer>();
        input.add(25);
        input.add(4);
        input.add(1);

        NumbersSolver solver = new NumbersSolver();
        Set<Node> nodes = solver.getNodes(input);

        assertEquals(17, nodes.size());

    }

    @Test
    public void testPermuter() {
        NumbersSolver solver = new NumbersSolver();
        List<Integer> numbers = new ArrayList<>();
        numbers.add(9);
        numbers.add(8);
        numbers.add(50);
    }

    @Test
    public void numbersSolverNotUsingAllNumbersTest() {

        NumbersBean bean = new NumbersBean("75,50,8,3,9,8,979");
        NumbersSolver solver = new NumbersSolver();
        List<NumbersSolution> solutions = solver.solve(bean, 0);
        assertEquals(1, solutions.size());
    }

    @Test
    public void numbersSolverTest() {
        NumbersBean bean = new NumbersBean("1,25,4,101");

        NumbersSolver solver = new NumbersSolver();
        List<NumbersSolution> solutions = solver.solve(bean, 0);

        assertEquals(1, solutions.size());

    }

}


text:
package testtime

import (
	"fmt"
	"os"
	"strconv"
	"time"
)

var (
	// X is the multiplier from the TEST_TIME_SCALE environment variable.
	X = 1.0
	// Millisecond is a millisecond dilated into test time by TEST_TIME_SCALE.
	Millisecond = time.Millisecond
	// Second is a second dilated into test time by TEST_TIME_SCALE.
	Second = time.Second
)

func init() {
	if v := os.Getenv("TEST_TIME_SCALE"); v != "" {
		fv, err := strconv.ParseFloat(v, 64)
		if err != nil {
			panic(err)
		}
		X = fv
		fmt.Fprintln(os.Stderr, "Scaling test time by factor", X)
	}

	Millisecond = Scale(time.Millisecond)
	Second = Scale(time.Second)
}

// Scale returns the timeout multiplied by any set multiplier.
func Scale(timeout time.Duration) time.Duration {
	return time.Duration(X * float64(timeout))
}

// Sleep sleeps the given duration in test time scale.
func Sleep(duration time.Duration) {
	time.Sleep(Scale(duration))
}


text:
import { combineReducers } from 'redux'
import { OPEN_MENU, CLOSE_MENU, CLICK_MENU, LOAD_LEFT_MENU, HOVER_MENU } from 'actions/frame/left-menu.js'

function selectedIndex( state = [] , action ){
	if( action.type === CLICK_MENU )
		return action.selected;
	return state;
}

function leftMenuList( state = {} , action ){
	if( action.type === LOAD_LEFT_MENU )
		return action.menuList;
	return state;
}

function status( state = 1 , action ){
	switch( action.type ){
		case OPEN_MENU :
			return 1;
		case CLOSE_MENU :
			return 0;
		default:
			return state;
	}
}
function hover( state = [] , action ){
	if( action.type === HOVER_MENU )
		return action.coord;
	return state;

}
export default combineReducers({
	selectedIndex,
	leftMenuList,
	status,
	hover
});


text:
"""
2014 March 27
Shane Bussmann

Generate input files for SExtractor and run it.
"""

from astropy.table import Table
from astropy.io import fits
import os
import numpy

filterlist = ['u', 'g', 'r', 'i', 'z', 'Y', 'J', 'H', 'Ks']
nfilters = len(filterlist)

targetlistloc = 'targetlist.dat'
targetlist = Table.read(targetlistloc, format='ascii')
ntargets = len(targetlist)

fitsdir = 'fitscutouts'
os.chdir(fitsdir)

for itarg in range(ntargets):

    # get the target name from the filename
    dataname = targetlist['dataname'][itarg]
    iauname = targetlist['iauname'][itarg]

    counter = 0
    for ifilt in filterlist:

        # load the appropriate optical image
        imloc = dataname + '_' + ifilt + '_cut.fits'
        if not os.path.exists(imloc):
            continue
        header = fits.getheader(imloc)

        # estimate the photometric zeropoint of the data
        gemzero = [24.91, 28.33, 28.33, 27.93, 26.84]
        gemcolors = [0.38, 0.18, 0.1, 0.08, 0.05]
        headerkeys = header.keys()
        cautionflag = 1
        #if headerkeys.count('AIRMASS') > 0:
        #    gain = header['GAIN']
        #    exptime = header['EXPTIME']
        #    airmass = header['AIRMASS']
        #    zpt = gemzero[counter] - 2.5 * numpy.log10(gain / exptime) - \
        #        gemcolors[counter] * (airmass - 1.0)
        #    cautionflag = 0
        if headerkeys.count('PHOTZP') > 0:
            zpt = header['PHOTZP']
            cautionflag = 0
        if headerkeys.count('MAGZPT') > 0:
            zpt = header['MAGZPT']
            cautionflag = 0
        if cautionflag:
            # go back to Gemini reduction directory to get needed header info
            dataloc = '/Users/rbussman/Data/Gemini-South/'
            oldimloc = dataloc + dataname + '_' + ifilt + '.fits'
            oldheader = fits.getheader(oldimloc)
            gain = oldheader['GAIN']
            exptime = oldheader['EXPTIME']
            airmass = oldheader['AIRMASS']
            zpt = gemzero[counter] - 2.5 * numpy.log10(gain / exptime) - \
                gemcolors[counter] * (airmass - 1.0)
            cautionflag = 0

        string0 = ' -MAG_ZEROPOINT ' + str(zpt)

        catalogname = dataname + '_' + ifilt + '_cut.cat'
        string1 = ' -CATALOG_NAME ' + catalogname
        segname = dataname + '_' + ifilt + '_seg.fits'
        string2 = ' -CHECKIMAGE_NAME ' + segname

        stringfinal = ' ' + imloc

        cmd = 'sex' + string0 + string1 + string2 + stringfinal
        print cmd
        os.system(cmd)

        counter += 1


text:
package org.thebigjc.hackreduce;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.hackreduce.mappers.StockExchangeMapper;
import org.hackreduce.models.StockExchangeRecord;

/**
 * This MapReduce job will read the NASDAQ or NYSE daily prices dataset and output the highest market caps
 * obtained by each Stock symbol.
 *
 */
public class StockCrossJoin extends Configured implements Tool {

	public enum Count {
		DATES
	}

	public static class StockCrossJoinMapper extends StockExchangeMapper<Text, Text> {

		@Override
		protected void map(StockExchangeRecord record, Context context) throws IOException, InterruptedException {
			String dateStr = record.getDateString();
			context.write(new Text(dateStr), new Text(record.toString()));
		}
	}

	public static class StockCrossJoinReducer extends Reducer<Text, Text, Text, Text> {
		@Override
		protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
			context.getCounter(Count.DATES).increment(1);

			// Let's hope there aren't too many stocks!
			ArrayList<StockExchangeRecord> sres = new ArrayList<StockExchangeRecord>();
			for (Text row : values) {
				StockExchangeRecord curS = new StockExchangeRecord(row);

				for (StockExchangeRecord sre: sres) {
					String s1 = sre.getStockSymbol();
					String s2 = curS.getStockSymbol();
					double d1 = sre.getStockPriceClose();
					double d2 = curS.getStockPriceClose();

					if (s1.compareTo(s2) < 0)
						writePair(key, context, s1, s2, d1, d2);
					else
						writePair(key, context, s2, s1, d2, d1);
				}

				sres.add(curS);
			}
		}

		private void writePair(Text date, Context context, String s1, String s2,
				double d1, double d2) throws IOException, InterruptedException {
			context.write(new Text(s1 + "|" + s2 + "|" + date), new Text(d1 + "|" + d2));
		}

	}

	@Override
	public int run(String[] args) throws Exception {
        Configuration conf = getConf();

        if (args.length != 2) {
        	System.err.println("Usage: " + getClass().getName() + " <input> <output>");
        	System.exit(2);
        }

        // Creating the MapReduce job (configuration) object
        Job job = new Job(conf);
        job.setJarByClass(getClass());
        job.setJobName(getClass().getName());

        // Tell the job which Mapper and Reducer to use (classes defined above)
        job.setMapperClass(StockCrossJoinMapper.class);
		job.setReducerClass(StockCrossJoinReducer.class);

		// Configure the job to accept the NASDAQ/NYSE data as input
		StockExchangeMapper.configureJob(job);

		// This is what the Mapper will be outputting to the Reducer
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(Text.class);

		// This is what the Reducer will be outputting
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(Text.class);

		// Setting the input folder of the job
		FileInputFormat.addInputPath(job, new Path(args[0]));

		// Preparing the output folder by first deleting it if it exists
        Path output = new Path(args[1]);
        FileSystem.get(conf).delete(output, true);
	    FileOutputFormat.setOutputPath(job, output);

		return job.waitForCompletion(true) ? 0 : 1;
	}

	public static void main(String[] args) throws Exception {
		int result = ToolRunner.run(new Configuration(), new StockCrossJoin(), args);
		System.exit(result);
	}

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Boletinus solidipes Peck

### Remarks
null


text:
import collections
import uuid

import mock
import webob

from ooi.api import helpers
from ooi.api import network_link as network_link_api
from ooi import exception
from ooi.occi.core import collection
from ooi.occi.infrastructure import compute
from ooi.occi.infrastructure import network
from ooi.occi.infrastructure import network_link
from ooi.openstack import network as os_network
from ooi.tests import base
from ooi.tests import fakes

class TestNetworkLinkController(base.TestController):
    def setUp(self):
        super(TestNetworkLinkController, self).setUp()
        self.controller = network_link_api.Controller(mock.MagicMock(), None)

    def _build_req(self, tenant_id, path="/whatever", **kwargs):
        m = mock.MagicMock()
        m.user.project_id = tenant_id
        environ = {"keystone.token_auth": m}

        kwargs["base_url"] = self.application_url

        return webob.Request.blank(path, environ=environ, **kwargs)

    @mock.patch.object(helpers.OpenStackHelper, "get_floating_ips")
    def test_index(self, mock_floating_ips):
        for tenant in fakes.tenants.values():
            ips = fakes.floating_ips[tenant["id"]]
            mock_floating_ips.return_value = ips
            ret = self.controller.index(None)
            self.assertIsInstance(ret, collection.Collection)
            if tenant["name"] == "baz":
                for idx, ip in enumerate(ips):
                    if ip["instance_id"]:
                        self.assertIsInstance(ret.resources[idx],
                                              os_network.OSNetworkInterface)
            else:
                self.assertEqual([], ret.resources)
            mock_floating_ips.assert_called_with(None)

    @mock.patch.object(network_link_api.Controller, "_get_interface_from_id")
    def test_delete_invalid(self, mock_get):
        class FakeNetworkLink(object):
            target = collections.namedtuple("Target", ["id"])("fixed")

        server_id = uuid.uuid4().hex
        server_addr = "192.168.253.1"
        link_id = "%s_%s" % (server_id, server_addr)
        mock_get.return_value = FakeNetworkLink()
        self.assertRaises(exception.Invalid,
                          self.controller.delete, None, link_id)
        mock_get.assert_called_with(None, link_id)

    @mock.patch.object(helpers.OpenStackHelper, "release_floating_ip")
    @mock.patch.object(helpers.OpenStackHelper, "remove_floating_ip")
    @mock.patch.object(network_link_api.Controller, "_get_interface_from_id")
    def test_delete(self, mock_get, mock_remove, mock_release):
        class FakeNetworkLink(object):
            target = collections.namedtuple("Target", ["id"])("floating")
            source = collections.namedtuple("Source", ["id"])(uuid.uuid4().hex)
            address = "192.168.253.1"
            id = "%s_%s" % (source.id, address)
            ip_id = "foo"

        link = FakeNetworkLink()
        mock_get.return_value = link
        mock_release.return_value = None
        mock_remove.return_value = None

        ret = self.controller.delete(None, link.id)
        self.assertEqual([], ret)

        mock_get.assert_called_with(None, link.id)
        mock_remove.assert_called_with(None, link.source.id, link.address)
        mock_release.assert_called_with(None, link.ip_id)

    @mock.patch.object(network_link_api.Controller, "_get_interface_from_id")
    def test_show(self, mock_get):
        mock_get.return_value = "foo"

        ret = self.controller.show(None, "bar")
        self.assertEqual(["foo"], ret)
        mock_get.assert_called_with(None, "bar")

    def test_get_interface_from_id_invalid(self):
        self.assertRaises(exception.LinkNotFound,
                          self.controller._get_interface_from_id,
                          None,
                          "foobarbaz")

    @mock.patch.object(helpers.OpenStackHelper, "get_server")
    def test_get_interface_from_id_invalid_no_matching_server(self, mock_get):
        mock_get.return_value = {"addresses": {"foo": [{"addr": "1.1.1.2"}]}}

        self.assertRaises(exception.LinkNotFound,
                          self.controller._get_interface_from_id,
                          None,
                          "%s_1.1.1.1" % uuid.uuid4().hex)

    @mock.patch.object(network_link_api.Controller, "_build_os_net_iface")
    @mock.patch.object(helpers.OpenStackHelper, "get_server")
    def test_get_interface_from_id(self, mock_get_server, mock_build_iface):
        class FakeNetworkLink(object):
            pass
        fake_link = FakeNetworkLink()
        server_id = uuid.uuid4().hex
        server_addr = "1.1.1.1"
        link_id = "%s_%s" % (server_id, server_addr)
        mock_get_server.return_value = {"addresses": {"foo": [
            {"addr": server_addr}]}}
        mock_build_iface.return_value = fake_link

        ret = self.controller._get_interface_from_id(None, link_id)

        self.assertEqual(fake_link, ret)
        mock_get_server.assert_called_with(None, server_id)
        mock_build_iface.assert_called_with(None, server_id,
                                            {"addr": server_addr})

    def test_build_os_net_iface_fixed(self):
        addr = {"addr": "1.1.1.1",
                "OS-EXT-IPS:type": "fixed",
                "OS-EXT-IPS-MAC:mac_addr": "1234"}
        ret = self.controller._build_os_net_iface(None, uuid.uuid4().hex, addr)
        self.assertIsInstance(ret, os_network.OSNetworkInterface)
        self.assertIsInstance(ret.source, compute.ComputeResource)
        self.assertIsInstance(ret.target, network.NetworkResource)
        self.assertEqual(ret.target.id, "fixed")
        self.assertIsInstance(ret.ip_id, type(None))
        self.assertEqual(1, len(ret.mixins))
        self.assertIn(network_link.ip_network_interface, ret.mixins)

    @mock.patch.object(helpers.OpenStackHelper, "get_floating_ips")
    def test_build_os_net_iface(self, mock_floating_ips):
        ips = fakes.floating_ips[fakes.tenants["baz"]["id"]]
        for ip in ips:
            addr = {"addr": ip["ip"],
                    "OS-EXT-IPS:type": "floating",
                    "OS-EXT-IPS-MAC:mac_addr": "1234"}
            mock_floating_ips.return_value = ips

            ret = self.controller._build_os_net_iface(
                None, uuid.uuid4().hex, addr)
            self.assertIsInstance(ret, os_network.OSNetworkInterface)
            self.assertIsInstance(ret.target, network.NetworkResource)
            self.assertEqual(ret.target.id, "floating")
            self.assertIsInstance(ret.source, compute.ComputeResource)
            self.assertEqual(ret.ip_id, ip["id"])
            self.assertEqual(2, len(ret.mixins))
            self.assertIn(network_link.ip_network_interface, ret.mixins)
            for m in ret.mixins:
                if isinstance(m, os_network.OSFloatingIPPool):
                    has_pool = True
                    break
            self.assertTrue(has_pool)

    @mock.patch.object(helpers.OpenStackHelper, "get_floating_ips")
    def test_build_os_net_iface_ip_invalid(self, mock_floating_ips):
        addr = {"addr": "1.1.1.1",
                "OS-EXT-IPS:type": "floating",
                "OS-EXT-IPS-MAC:mac_addr": "1234"}
        for tenant in fakes.tenants.values():
            ips = fakes.floating_ips[tenant["id"]]
            mock_floating_ips.return_value = ips
            self.assertRaises(exception.NetworkNotFound,
                              self.controller._build_os_net_iface,
                              None,
                              uuid.uuid4().hex,
                              addr)

    @mock.patch("ooi.occi.validator.Validator")
    def test_create_invalid(self, mock_validator):
        tenant = fakes.tenants["foo"]
        req = self._build_req(tenant["id"])
        net_id = "fixed"
        server_id = uuid.uuid4().hex
        obj = {
            "attributes": {
                "occi.core.target": net_id,
                "occi.core.source": server_id,
            }
        }

        req.get_parser = mock.MagicMock()
        req.get_parser.return_value.return_value.parse.return_value = obj
        mock_validator.validate.return_value = True
        self.assertRaises(exception.Invalid,
                          self.controller.create, req, None)

    @mock.patch("ooi.api.helpers.get_id_with_kind")
    @mock.patch("ooi.occi.validator.Validator")
    def test_create_invalid_ids(self, mock_validator, mock_get_id):
        tenant = fakes.tenants["foo"]
        req = self._build_req(tenant["id"])
        net_id = "foobarbaz"
        server_id = uuid.uuid4().hex
        obj = {
            "attributes": {
                "occi.core.target": net_id,
                "occi.core.source": server_id,
            }
        }

        req.get_parser = mock.MagicMock()
        mock_get_id.side_effect = exception.Invalid()
        req.get_parser.return_value.return_value.parse.return_value = obj
        mock_validator.validate.return_value = True
        self.assertRaises(exception.Invalid,
                          self.controller.create, req, None)

    @mock.patch("ooi.api.helpers.get_id_with_kind")
    @mock.patch("ooi.occi.validator.Validator")
    def test_create_fixed(self, mock_validator, mock_get_id):
        tenant = fakes.tenants["foo"]
        req = self._build_req(tenant["id"])
        obj = {
            "attributes": {
                "occi.core.target": "foo",
                "occi.core.source": "bar",
            }
        }

        req.get_parser = mock.MagicMock()
        mock_get_id.side_effect = [('', "fixed"), ('', '')]
        req.get_parser.return_value.return_value.parse.return_value = obj
        mock_validator.validate.return_value = True
        self.assertRaises(exception.Invalid,
                          self.controller.create, req, None)

    @mock.patch("ooi.api.helpers.get_id_with_kind")
    @mock.patch("ooi.occi.validator.Validator")
    def test_create_nonfloating(self, mock_validator, mock_get_id):
        tenant = fakes.tenants["foo"]
        req = self._build_req(tenant["id"])
        obj = {
            "attributes": {
                "occi.core.target": "foo",
                "occi.core.source": "bar",
            }
        }

        req.get_parser = mock.MagicMock()
        mock_get_id.side_effect = [("", "foo"), ("", "")]
        req.get_parser.return_value.return_value.parse.return_value = obj
        mock_validator.validate.return_value = True
        self.assertRaises(exception.NetworkNotFound,
                          self.controller.create, req, None)

    @mock.patch.object(helpers.OpenStackHelper, "associate_floating_ip")
    @mock.patch.object(helpers.OpenStackHelper, "allocate_floating_ip")
    @mock.patch("ooi.api.helpers.get_id_with_kind")
    @mock.patch("ooi.occi.validator.Validator")
    def test_create_no_pool(self, mock_validator, mock_get_id, mock_allocate,
                            mock_associate):
        tenant = fakes.tenants["foo"]
        req = self._build_req(tenant["id"])
        net_id = "floating"
        server_id = uuid.uuid4().hex
        obj = {
            "attributes": {
                "occi.core.target": net_id,
                "occi.core.source": server_id,
            },
            "schemes": {
            }
        }
        ips = fakes.floating_ips[fakes.tenants["baz"]["id"]]

        for ip in ips:
            req.get_parser = mock.MagicMock()
            req.get_parser.return_value.return_value.parse.return_value = obj
            mock_validator.validate.return_value = True
            mock_allocate.return_value = ip
            mock_associate.return_value = None
            mock_get_id.side_effect = [('', net_id), ('', server_id)]

            ret = self.controller.create(req, None)
            link = ret.resources.pop()
            self.assertIsInstance(link, os_network.OSNetworkInterface)
            self.assertIsInstance(link.source, compute.ComputeResource)
            self.assertIsInstance(link.target, network.NetworkResource)
            self.assertEqual(net_id, link.target.id)
            self.assertEqual(server_id, link.source.id)

            mock_allocate.assert_called_with(mock.ANY, None)
            mock_associate.assert_called_with(mock.ANY, server_id, ip["ip"])

    @mock.patch.object(helpers.OpenStackHelper, "associate_floating_ip")
    @mock.patch.object(helpers.OpenStackHelper, "allocate_floating_ip")
    @mock.patch("ooi.api.helpers.get_id_with_kind")
    @mock.patch("ooi.occi.validator.Validator")
    def test_create_with_pool(self, mock_validator, mock_get_id, mock_allocate,
                              mock_associate):
        tenant = fakes.tenants["foo"]
        req = self._build_req(tenant["id"])
        net_id = "floating"
        server_id = uuid.uuid4().hex
        pool_name = "public"
        obj = {
            "attributes": {
                "occi.core.target": net_id,
                "occi.core.source": server_id,
            },
            "schemes": {
                os_network.OSFloatingIPPool.scheme: [pool_name],
            }
        }
        ips = fakes.floating_ips[fakes.tenants["baz"]["id"]]

        for ip in ips:
            req.get_parser = mock.MagicMock()
            req.get_parser.return_value.return_value.parse.return_value = obj
            mock_validator.validate.return_value = True
            mock_allocate.return_value = ip
            mock_associate.return_value = None
            mock_get_id.side_effect = [('', net_id), ('', server_id)]

            ret = self.controller.create(req, None)
            link = ret.resources.pop()
            self.assertIsInstance(link, os_network.OSNetworkInterface)
            self.assertIsInstance(link.source, compute.ComputeResource)
            self.assertIsInstance(link.target, network.NetworkResource)
            self.assertEqual(net_id, link.target.id)
            self.assertEqual(server_id, link.source.id)

            mock_allocate.assert_called_with(mock.ANY, pool_name)
            mock_associate.assert_called_with(mock.ANY, server_id, ip["ip"])


text:
<?php

include_once 'check_access_permissions.php';
mustHaveAnyOfTheseRoles( array( 'AWS_ADMIN', 'BOOKMYVENUE_ADMIN' ) );

include_once 'header.php';
include_once 'database.php';
include_once 'mail.php';
include_once 'tohtml.php';

if( ! $_POST[ 'response' ] )
{
    // Go back to previous page.
    goToPage( "admin_acad.php", 0 );
    exit;
}
else if( $_POST[ 'response' ] == 'submit' )
{
    $res = updateTable( 'talks', 'id'
                , 'class,host,coordinator,title,description'
                , $_POST
            );
    if( $res )
    {
        echo printInfo( 'Successfully updated entry' );

        // TODO: Update the request or event associated with this entry as well.
        $externalId = getTalkExternalId( $_POST );

        $talk = getTableEntry( 'talks', 'id', $_POST );
        assert( $talk );

        $success = true;

        $event = getEventsOfTalkId( $_POST[ 'id' ] );
        $request = getBookingRequestOfTalkId( $_POST[ 'id' ] );

        if( $event )
        {
            echo printInfo( "Updating event related to this talk" );
            $event[ 'title' ] = talkToEventTitle( $talk );
            $event[ 'description' ] = $talk[ 'description' ];
            $res = updateTable( 'events', 'gid,eid', 'title,description', $event );
            if( $res )
                echo printInfo( "... Updated successfully" );
            else
                $success = false;
        }
        else if( $request )
        {
            echo printInfo( "Updating booking request related to this talk" );
            $request[ 'title' ] = talkToEventTitle( $talk );
            $request[ 'description' ] = $talk[ 'description' ];
            $res = updateTable( 'bookmyvenue_requests', 'gid,eid'
                , 'title,description', $request );
            if( $res )
                echo printInfo( "... Updated successfully" );
            else
                $success = false;
        }

        if( $success )
        {
            echo goToPage( 'admin_acad_manages_talks.php' , 0 );
            exit;
        }
    }
    else
        echo printWarning( "Failed to update the talk " );
}
else
    echo printInfo( "Unknown operation " . $_POST[ 'response' ] );

echo goBackToPageLink( 'admin_acad_manages_talks.php', "Go back" );
exit;

?>