text:
from __future__ import absolute_import

from six.moves import BaseHTTPServer
import logging
import os
import pyqrcode
import socket
from socket import gethostname, gethostbyname
import time
from six.moves.urllib import parse as urlparse
import webbrowser

from .phone_sensor import SENSOR_PAGE_HTML

logger = logging.getLogger("pebble_tool.util.browser")

class BrowserController(object):
    def __init__(self):
        self.port = None

    def open_config_page(self, url, callback):
        self.port = port = self._choose_port()
        url = self.url_append_params(url, {'return_to': 'http://localhost:{}/close?'.format(port)})
        webbrowser.open_new(url)
        self.serve_page(port, callback)

    def serve_page(self, port, callback):
        # This is an array so AppConfigHandler doesn't create an instance variable when trying to set the state to False
        running = [True]

        class AppConfigHandler(BaseHTTPServer.BaseHTTPRequestHandler):
            def do_GET(self):
                path, query = self.path.split('?', 1)
                if path == '/close':
                    self.send_response(200)
                    self.end_headers()
                    self.wfile.write("OK")
                    running[0] = False
                    callback(query)
                else:
                    self.send_response(404)
                    self.end_headers()
                    self.wfile.write("Not Found")

        server = BaseHTTPServer.HTTPServer(('', port), AppConfigHandler)
        while running[0]:
            server.handle_request()

    def url_append_params(self, url, params):
        parsed = urlparse.urlparse(url, "http")
        query = parsed.query
        if parsed.query != '':
            query += '&'

        encoded_params = urlparse.urlencode(params)
        query += encoded_params
        return urlparse.urlunparse((parsed.scheme, parsed.netloc, parsed.path, parsed.params, query, parsed.fragment))

    def serve_sensor_page(self, pypkjs_port, port=None):
        self.port = port or self._choose_port()

        class SensorPageHandler(BaseHTTPServer.BaseHTTPRequestHandler):
            PERMITTED_PATHS = {'static/js/backbone-min.js',
                               'static/js/backbone-min.map',
                               'static/js/propeller.min.js',
                               'static/js/sensors.js',
                               'static/js/underscore-min.js',
                               'static/js/underscore-min.map',
                               'static/js/websocket.js',
                               'static/compass-arrow.png',
                               'static/compass-rose.png',
                               'static/stylesheets/normalize.min.css',
                               'static/stylesheets/sensors.css'}

            def do_HEAD(self):
                self.send_response(200)
                self.end_headers()

            def do_GET(self):
                requested_file = self.path.rsplit('/', 1)[1]
                file_path = self.path.lstrip('/')
                if requested_file == '':
                    self.send_response(200)
                    self.send_header('Content-type', 'text/html')
                    self.end_headers()
                    self.wfile.write(SENSOR_PAGE_HTML.format(websocket_host="'{}'".format(gethostbyname(gethostname())),
                                                             websocket_port="'{}'".format(pypkjs_port)))
                elif file_path in self.PERMITTED_PATHS:
                    try:
                        file_contents = open(os.path.join(os.path.dirname(os.path.realpath(__file__)), file_path))
                        self.send_response(200)
                        self.end_headers()
                        self.wfile.write(file_contents.read())
                    except IOError:
                        self.send_response(404)
                        self.end_headers()
                        self.wfile.write("Not Found")
                else:
                    self.send_response(403)
                    self.end_headers()
                    self.wfile.write("Forbidden")

            def log_request(self, code='-', size='-'):
                logger.debug("{} - - [{}] '{}' {} {}".format(self.client_address[0], self.log_date_time_string(),
                                                               self.requestline, code, size))

        server = BaseHTTPServer.HTTPServer(('', self.port), SensorPageHandler)
        url = "http://{}:{}".format(gethostbyname(gethostname()), server.server_port)
        url_code = pyqrcode.create(url)
        print(url_code.terminal(quiet_zone=1))
        print("=======================================================================================================")
        print("Please scan the QR code or enter the following URL in your mobile browser:\n{}".format(url))
        print("=======================================================================================================")
        print("\nUse Ctrl-C to stop sending sensor data to the emulator.\n")
        try:
            server.serve_forever()
        except KeyboardInterrupt:
            print("Stopping...")
            server.server_close()
            time.sleep(2) # Wait for WS connection to die between phone/QEMU

    def _choose_port(self):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind(('localhost', 0))
        addr, port = s.getsockname()
        s.close()
        return port


text:
<?php
/**
 * Displays the searchform of the theme.
 *
 * @package Theme Horse
 * @subpackage Ambition
 * @since Ambition 1.0
 */
?>
	<form action="<?php echo esc_url( home_url( '/' ) ); ?>" method="get" class="searchform clearfix">
		<label class="assistive-text"> <?php _e( 'Search', 'ambition' ); ?> </label>
		<input type="search" placeholder="<?php esc_attr_e( 'Search', 'ambition' ); ?>" class="s field" name="s">
		<input type="submit" value="<?php esc_attr_e( 'Search', 'ambition' ); ?>" class="search-submit">
	</form><!-- .search-form -->

redpajama_set_name: RedPajamaGithub


text:
snippets
=======

bits of reusable code i wanna keep around

grading_scripts contains stuff I use to help move assignment grading more quickly in the class I TA


text:
cd ../diishf
rm outfile
# set up the Gaussian environment
mkdir workdir
cd workdir >> outfile 2>&1
echo "---------------------------------" >> ../outfile 2>&1
echo "Failure Test: no input to program" >> ../outfile 2>&1
echo "---------------------------------" >> ../outfile 2>&1
./diishf >> ../outfile
echo "Finished with tests designed to fail">> ../outfile
echo "-------------" >> ../outfile 2>&1
echo "MatFile test">> ../outfile
echo "-------------" >> ../outfile 2>&1
cp ../../data/MatrixFile/ch4_rhf.mat . >> ../outfile
../diishf -f ch4_rhf.mat >> ../outfile
cd ..
rm -r workdir

sed -e 'sZ-0.000000Z 0.000000Zg' < outfile > outfile_tmp
mv outfile_tmp outfile

diff -b -B outfile OUTPUT/out

exit


text:
package codes.soloware.couchpotato.server.sound.javax;

import javax.sound.sampled.FloatControl;

import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
 * A set of test cases for the {@link FloatControlAdapter} class.
 */
@RunWith(MockitoJUnitRunner.StrictStubs.class)
public class FloatControlAdapterTest
{
	private static final float mockVolumeValue=0.5f;
	private static final float errorTolerance=0.0001f;
	private FloatControl mockControl;
	private FloatControlAdapter testee;

	@Before
	public void setup()
	{
		mockControl=Mockito.mock(FloatControl.class);
		Mockito.when(mockControl.getType()).thenReturn(FloatControl.Type.VOLUME);

		testee=new FloatControlAdapter(mockControl);
	}

	@Test
	@SuppressWarnings("boxing")
	public void getMaximumVolume()
	{
		Mockito.when(mockControl.getMaximum()).thenReturn(mockVolumeValue);
		Assert.assertEquals(mockVolumeValue, testee.getMaximumVolume(), errorTolerance);
	}

	@Test
	@SuppressWarnings("boxing")
	public void getMinimumVolume()
	{
		Mockito.when(mockControl.getMinimum()).thenReturn(mockVolumeValue);
		Assert.assertEquals(mockVolumeValue, testee.getMinimumVolume(), errorTolerance);
	}

	@Test
	@SuppressWarnings("boxing")
	public void getVolume()
	{
		Mockito.when(mockControl.getValue()).thenReturn(mockVolumeValue);
		Assert.assertEquals(mockVolumeValue, testee.getVolume(), errorTolerance);
	}

	@Test
	public void setVolume()
	{
		testee.setVolume(mockVolumeValue);
		Mockito.verify(mockControl).setValue(mockVolumeValue);
	}
}


text:
require 'testor/commands/bundle'

module Testor
  class Command

    class Spec < Bundle

      def run

        if print_matrix?
          puts  "\nh2. %s\n\n"   % repo.name
          puts  '| RUBY  | %s |' % env.adapters(repo).join(' | ')
        end

        super do |ruby|

          print '| %s |' % ruby if print_matrix?

          if block_given?

            yield ruby

          else

            execute

            if print_matrix?
              print ' %s |' % [ status ]
            end

          end

        end

      end

      def bundle_command
        if env.command_options
          "exec spec #{env.command_options.join(' ')}"
        else
          'exec rake spec'
        end
      end

      def action
        "#{super} Testing"
      end

      def print_matrix?
        executable? && !verbose? && !pretend?
      end

      def suppress_log?
        !executable? || print_matrix?
      end

      def skip?
        target_revision && !clean?
      end

      def target_revision
        env.options[:revision]
      end

      def clean?
        %x[git status] =~ /working directory clean/
      end

    end # class Spec

  end # class Command
end # module Testor


text:
package org.develnext.jphp.core.tokenizer.token.stmt;

import org.develnext.jphp.core.tokenizer.TokenType;
import org.develnext.jphp.core.tokenizer.TokenMeta;

public class ArrayStmtToken extends StmtToken {
    public ArrayStmtToken(TokenMeta meta) {
        super(meta, TokenType.T_ARRAY);
    }
}


text:
<?php

abstract class RokCommon_Form_AbstractItem implements RokCommon_Form_IItem
{
	/**
	 * @var RokCommon_Service_Container
	 */
	protected $container;

	/**
	 * The JForm object of the form attached to the form field.
	 *
	 * @var        object
	 * @since    1.6
	 */
	protected $form;

	/**
	 * The form control prefix for field names from the JForm object attached to the form field.
	 *
	 * @var        string
	 * @since    1.6
	 */
	protected $formControl;

	/**
	 * The hidden state for the form field.
	 *
	 * @var        boolean
	 * @since    1.6
	 */
	protected $hidden = false;

	/**
	 * True to translate the field label string.
	 * True to translate the field label string.
	 *
	 * @var        boolean
	 * @since    1.6
	 */
	protected $translateLabel = true;

	/**
	 * True to translate the field description string.
	 *
	 * @var        boolean
	 * @since    1.6
	 */
	protected $translateDescription = true;

	/**
	 * The JXMLElement object of the <field /> XML element that describes the form field.
	 *
	 * @var        object
	 * @since    1.6
	 */
	protected $element;

	/**
	 * The document id for the form field.
	 *
	 * @var        string
	 * @since    1.6
	 */
	protected $id;

	/**
	 * The input for the form field.
	 *
	 * @var        string
	 * @since    1.6
	 */
	protected $input;

	/**
	 * The label for the form field.
	 *
	 * @var        string
	 * @since    1.6
	 */
	protected $label;

	/**
	 * The name of the form field.
	 *
	 * @var        string
	 * @since    1.6
	 */
	protected $name;

	/**
	 * The name of the field.
	 *
	 * @var        string
	 * @since    1.6
	 */
	protected $fieldname;

	/**
	 * The group of the field.
	 *
	 * @var        string
	 * @since    1.6
	 */
	protected $group;

	/**
	 * The form field type.
	 *
	 * @var        string
	 * @since    1.6
	 */
	protected $type;

	protected $basetype;

	/**
	 * The value of the form field.
	 *
	 * @var        mixed
	 * @since    1.6
	 */
	protected $value;

	/**
	 * @var string
	 */
	protected $panel_position = 'left';

	/**
	 * @var bool
	 */
	protected $show_label = true;

	/**
	 * @var mixed
	 */
	protected $base_value;

	/**
	 * @var bool
	 */
	protected $customized = false;

	/**
	 * @var bool
	 */
	protected $setinoverride = true;

	/**
	 * @var string
	 */
	protected $class;

	/**
	 * @var bool
	 */
	protected $detached;

	/**
	 * @var mixed
	 */
	protected $default;

	protected $assets_content;

	/**
	 * Method to instantiate the form field object.
	 *
	 * @param    object    $form    The form to attach to the form field object.
	 *
	 * @return    void
	 * @since    1.6
	 */
	public function __construct(RokCommon_Form $form = null)
	{
		$this->container = RokCommon_Service::getContainer();

		// If there is a form passed into the constructor set the form and form control properties.
		if ($form instanceof RokCommon_Form) {
			$this->form        = $form;
			$this->formControl = $form->getFormControl();
		}
	}

	/**
	 * @param  $name
	 * @param  $value
	 *
	 * @return void
	 */
	public function __set($name, $value)
	{
		if (property_exists($this, $name)) {
			$this->$name = $value;
		}
	}

	/**
	 * Method to get the field title.
	 *
	 * @return  string  The field title.
	 * @since   11.1
	 */
	public function getTitle()
	{
		// Initialise variables.
		$title = '';

		if ($this->hidden) {

			return $title;
		}

		// Get the label text from the XML element, defaulting to the element name.
		$title = $this->element['label'] ? (string)$this->element['label'] : (string)$this->element['name'];
		$title = $this->translateLabel ? JText::_($title) : $title;

		return $title;
	}

	/**
	 * Method to get the field label markup.
	 *
	 * @return    string    The field label markup.
	 * @since    1.6
	 */
	public function getLabel()
	{
		// Initialise variables.
		$label = '';

		if ($this->hidden) {
			return $label;
		}

		// Get the label text from the XML element, defaulting to the element name.
		$text = $this->element['label'] ? (string)$this->element['label'] : (string)$this->element['name'];
		$text = $this->translateLabel ? JText::_($text) : $text;

		// Build the class for the label.
		$class = !empty($this->description) ? 'hasTip' : '';
		$class = $this->required == true ? $class . ' required' : $class;

		// Add the opening label tag and main attributes attributes.
		$label .= '<label id="' . $this->id . '-lbl" for="' . $this->id . '" class="' . $class . '"';

		// If a description is specified, use it to build a tooltip.
		if (!empty($this->description)) {
			$label .= ' title="' . htmlspecialchars(trim($text, ':') . '::' . ($this->translateDescription ? JText::_($this->description) : $this->description), ENT_COMPAT, 'UTF-8') . '"';
		}

		// Add the label text and closing tag.
		$label .= '>' . $text . '</label>';

		return $label;
	}

	/**
	 * Method to attach a JForm object to the field.
	 *
	 * @param \RokCommon_Form $form The JForm object to attach to the form field.
	 *
	 * @return    object    The form field object so that the method can be used in a chain.
	 * @since    1.6
	 */
	public function setForm(RokCommon_Form $form)
	{
		$this->form        = $form;
		$this->formControl = $form->getFormControl();

		return $this;
	}

	/**
	 * Method to get the name used for the field input tag.
	 *
	 * @param   string  $fieldName  The field element name.
	 *
	 * @return  string  The name to be used for the field input tag.
	 *
	 * @since   11.1
	 */
	public function getName($fieldName)
	{
		/** @var $namehandler RokCommon_Form_IItemNameHandler */
		$namehandler = $this->container->getService('form.namehandler');

		return $namehandler->getName($fieldName, $this->group, $this->formControl, false);
	}

	/**
	 * Method to get the id used for the field input tag.
	 *
	 * @param    string    $fieldId      The field element id.
	 * @param    string    $fieldName    The field element name.
	 *
	 * @return    string    The id to be used for the field input tag.
	 * @since    1.6
	 */
	public function getId($fieldId, $fieldName)
	{
		/** @var $namehandler RokCommon_Form_IItemNameHandler */
		$namehandler = $this->container->getService('form.namehandler');

		return $namehandler->getId($fieldName, $fieldId, $this->group, $this->formControl, false);
	}

	/**
	 * Method to get certain otherwise inaccessible properties from the form field object.
	 *
	 * @param    string    $name    The property name for which to the the value.
	 *
	 * @return    mixed|null    The property value or null.
	 * @since    1.6
	 */
	public function __get($name)
	{

		switch ($name) {
			case 'input':
				// If the input hasn't yet been generated, generate it.
				if (empty($this->input)) {
					$this->input = $this->getInput();
				}
				return $this->input;
				break;

			case 'label':
				// If the label hasn't yet been generated, generate it.
				if (empty($this->label)) {
					$this->label = $this->getLabel();
				}
				return $this->label;
				break;
			case 'title':
				return $this->getTitle();
				break;
			default :
				if (property_exists($this, $name) && isset($this->$name)) {
					return $this->$name;
				} elseif (method_exists($this, 'get' . ucfirst($name))) {
					return call_user_func(array($this, 'get' . ucfirst($name)));
				} elseif (property_exists($this, $name)) {
					return $this->$name;
				} elseif (isset($this->element[$name])) {
					return (string)$this->element[$name];
				} else {
					return null;
				}
				break;
		}
	}

	/**
	 * Method to attach a JForm object to the field.
	 *
	 * @param    object    $element      The JXMLElement object representing the <field /> tag for the
	 *                                   form field object.
	 * @param    mixed     $value        The form field default value for display.
	 * @param    string    $group        The field name group control value. This acts as as an array
	 *                                   container for the field. For example if the field has name="foo"
	 *                                   and the group value is set to "bar" then the full field name
	 *                                   would end up being "bar[foo]".
	 *
	 * @return    boolean    True on success.
	 * @since    1.6
	 */
	public function setup(& $element, $value, $group = null)
	{
		global $gantry;

		// Make sure there is a valid JFormField XML element.
		if (!($element instanceof RokCommon_XMLElement)) {
			return false;
		}

		// Reset the input and label values.
		$this->input = null;
		$this->label = null;

		// Set the xml element object.
		$this->element = $element;

		// Get some important attributes from the form field element.
		$class               = (string)$element['class'];
		$id                  = (string)$element['id'];
		$name                = (string)$element['name'];
		$type                = (string)$element['type'];
		$panel_position      = (string)$element['panel_position'];
		$this->show_label    = ((string)$element['show_label'] == 'false') ? false : true;
		$this->setinoverride = ((string)$element['setinoverride'] == 'false') ? false : true;
		$default             = (string)$element['default'];

//        if (!empty($name)) {
//            if (empty($group)) {
//                $gantry_name = $name;
//            } else {
//                $groups = explode('.', $group);
//                if (count($groups > 0)) {
//                    //array_shift($groups);
//                    $groups[]    = $name;
//                    $gantry_name = implode('-', $groups);
//                }
//            }
//	        // TODO set this up to get for Default not for RokCommon param value
//            //$this->base_value = $gantry->get($gantry_name, null);
//        }

		// Set the field description text.
		$this->description = (string)$element['description'];

		// Set the visibility.
		$this->hidden = ((string)$element['type'] == 'hidden' || (string)$element['hidden'] == 'true');

		// Determine whether to translate the field label and/or description.
		$this->translateLabel       = !((string)$this->element['translate_label'] == 'false' || (string)$this->element['translate_label'] == '0');
		$this->translateDescription = !((string)$this->element['translate_description'] == 'false' || (string)$this->element['translate_description'] == '0');

		// Set the group of the field.
		$this->group = $group;

		// Set the field name and id.
		$this->fieldname = $name;
		$this->name      = $this->getName($name, $group);
		$this->id        = $this->getId($id, $name, $group);
		$this->type      = $type;

		$this->class = $class;

		if ($panel_position != null) $this->panel_position = $panel_position;

		// Set the field default value.
		$this->value = $value;
		if (null != $this->default && $this->default != $this->value) $this->customized = true;
		return true;
	}

	/**
	 * @static
	 * @return void
	 */
	public static function initialize()
	{

	}

	/**
	 * @static
	 * @return void
	 */
	public static function finalize()
	{

	}

	/**
	 * @param  $callback
	 *
	 * @return mixed
	 */
	public function render($callback)
	{
		return call_user_func_array($callback, array($this));
	}
}


text:
package wang.relish.colorpicker;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;

import java.util.Locale;

/**
 * 取色器对话框
 *
 * @author Relish Wang
 * @since 2017/08/02
 */
public class ColorPickerDialog extends Dialog implements ColorPickerView.OnColorChangedListener,
        View.OnClickListener, TextView.OnEditorActionListener {

    private ColorPickerView mColorPicker;

    private View mOldColor;
    private View mNewColor;

    private View mHexLayout;
    private EditText mEtHex;
    private boolean mHexValueEnabled = false;
    private ColorStateList mHexDefaultTextColor;

    private OnColorPickedListener mListener;

    public interface OnColorPickedListener {
        void onColorPicked(int color);
    }

    private ColorPickerDialog(Context context, int initialColor) {
        super(context);
        setUp(initialColor);
    }

    private void setUp(int color) {
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        @SuppressLint("InflateParams") View layout = inflater.inflate(R.layout.dialog_color_picker, null);
        setContentView(layout);

        mColorPicker = (ColorPickerView) layout.findViewById(R.id.color_picker_view);
        mOldColor = layout.findViewById(R.id.old_color_panel);
        mNewColor = layout.findViewById(R.id.new_color_panel);

        mHexLayout = layout.findViewById(R.id.hex_layout);
        mEtHex = (EditText) layout.findViewById(R.id.et_hex);
        mEtHex.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
        mHexDefaultTextColor = mEtHex.getTextColors();

        //当点击软键盘上的【完成】按钮时触发监听
        mEtHex.setOnEditorActionListener(this);

        int padding = Math.round(mColorPicker.getDrawingOffset());
        layout.findViewById(R.id.preview_layout).setPadding(padding, 0, padding, 0);

        View mBtnCancel = layout.findViewById(R.id.tv_cancel);
        View mBtnConfirm = layout.findViewById(R.id.tv_confirm);
        mBtnCancel.setOnClickListener(this);
        mBtnConfirm.setOnClickListener(this);

        mColorPicker.setOnColorChangedListener(this);
        mOldColor.setBackgroundColor(color); // 颜色预览色板上显示旧颜色
        mColorPicker.setColor(color, true); // 为ColorPickerView设置初始颜色
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            String hexVal = mEtHex.getText().toString();
            if (hexVal.length() >= 0 || hexVal.length() < 7) {
                try {
                    int c = Utils.convertToColorInt(hexVal);
                    mColorPicker.setColor(c, true);
                    mEtHex.setTextColor(mHexDefaultTextColor);
                } catch (IllegalArgumentException e) {
                    mEtHex.setTextColor(Color.RED);
                }
            } else {
                mEtHex.setTextColor(Color.RED);
            }
            return true;
        }
        return false;
    }

    @Override
    public void onColorChanged(int color) {
        mNewColor.setBackgroundColor(color);
        if (mHexValueEnabled) updateHexValue(color);
    }

    public void setHexValueEnabled(boolean enable) {
        mHexValueEnabled = enable;
        if (enable) {
            mHexLayout.setVisibility(View.VISIBLE);
            updateHexLengthFilter();
            updateHexValue(getColor());
        } else
            mHexLayout.setVisibility(View.GONE);
    }

    public boolean getHexValueEnabled() {
        return mHexValueEnabled;
    }

    private void updateHexLengthFilter() {
        mEtHex.setFilters(new InputFilter[]{new InputFilter.LengthFilter(7)});
    }

    private void updateHexValue(int color) {
        mEtHex.setText(Utils.convertToRGB(color).toUpperCase(Locale.getDefault()));
        mEtHex.setTextColor(mHexDefaultTextColor);
    }

    /**
     * 设置颜色改变的监听器
     *
     * @param listener 颜色改变监听器
     */
    public void setOnColorChangedListener(OnColorPickedListener listener) {
        mListener = listener;
    }

    public int getColor() {
        return mColorPicker.getColor();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_confirm) {
            if (mListener != null) {
                mListener.onColorPicked(((ColorDrawable) mNewColor.getBackground()).getColor());
            }
        }
        dismiss();
    }

    @NonNull
    @Override
    public Bundle onSaveInstanceState() {
        Bundle state = super.onSaveInstanceState();
        state.putInt("old_color", ((ColorDrawable) mOldColor.getBackground()).getColor());
        state.putInt("new_color", ((ColorDrawable) mNewColor.getBackground()).getColor());
        return state;
    }

    @Override
    public void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        mOldColor.setBackgroundColor(savedInstanceState.getInt("old_color"));
        mColorPicker.setColor(savedInstanceState.getInt("new_color"), true);
    }

    public static class Builder {
        private Context context;
        private int initColor;
        private boolean hexValueEnabled;
        private OnColorPickedListener listener;

        public Builder(Context context, int initColor) {
            this.context = context;
            this.initColor = initColor;
            this.hexValueEnabled = false;
        }

        public Builder setHexValueEnabled(boolean hexValueEnabled) {
            this.hexValueEnabled = hexValueEnabled;
            return this;
        }

        public Builder setOnColorPickedListener(OnColorPickedListener listener) {
            this.listener = listener;
            return this;
        }

        public ColorPickerDialog build() {
            ColorPickerDialog dialog = new ColorPickerDialog(context, initColor);
            dialog.setHexValueEnabled(hexValueEnabled);
            dialog.setOnColorChangedListener(listener);
            return dialog;
        }
    }
}


text:
import { Main } from "./imports/server-main/main";
import './methods/quiz.methods';

const mainInstance = new Main();
mainInstance.start();


text:
package com.elastisys.scale.cloudpool.commons.scaledown.strategies;

import static com.elastisys.scale.commons.util.precond.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;

import java.util.Collection;
import java.util.Comparator;

import com.elastisys.scale.cloudpool.api.types.Machine;
import com.elastisys.scale.cloudpool.commons.scaledown.VictimSelectionStrategy;

/**
 * A {@link VictimSelectionStrategy} that selects the most recently created
 * instance for termination.
 *
 *
 */
public enum NewestMachineVictimSelectionStrategy implements VictimSelectionStrategy {

    /** The single instance of this class. */
    INSTANCE;

    @Override
    public Machine selectVictim(Collection<Machine> candidates) throws IllegalArgumentException {
        requireNonNull(candidates, "null candidate set");
        checkArgument(!candidates.isEmpty(), "empty candidate set");

        return Machine.sort(candidates, new NewestFirstOrder()).get(0);
    }

    /**
     * {@link Comparator} that orders {@link Machine} instances in order of
     * increasing age (youngest instance first). A null requestTime
     * is considered youngest (rationale: a very recently requested machine may
     * not have had all metadata initialized). In case no request time is set or
     * they are equal, a comparison is made on the {@link Machine} id.
     */
    public class NewestFirstOrder implements Comparator<Machine> {
        @Override
        public int compare(Machine m1, Machine m2) {

            Comparator<Machine> launchTimeComparator = Comparator.comparing(Machine::getLaunchTime,
                    Comparator.nullsFirst(Comparator.reverseOrder()));

            Comparator<Machine> idComparator = Comparator.comparing(Machine::getId, Comparator.reverseOrder());
            return launchTimeComparator.thenComparing(idComparator).compare(m1, m2);
        }
    }

}


text:
/*	$NetBSD: tpmvar.h,v 1.3 2012/10/27 17:18:23 chs Exp $	*/
/*
 * Copyright (c) 2008, 2009 Michael Shalayeff
 * Copyright (c) 2009, 2010 Hans-Jörg Höxer
 * All rights reserved.
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER IN
 * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
 * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

struct tpm_softc {
	device_t sc_dev;
	void *sc_ih;

	int	(*sc_init)(struct tpm_softc *, int, const char *);
	int	(*sc_start)(struct tpm_softc *, int);
	int	(*sc_read)(struct tpm_softc *, void *, size_t, size_t *, int);
	int	(*sc_write)(struct tpm_softc *, const void *, size_t);
	int	(*sc_end)(struct tpm_softc *, int, int);

	bus_space_tag_t sc_bt, sc_batm;
	bus_space_handle_t sc_bh, sc_bahm;

	u_int32_t sc_devid;
	u_int32_t sc_rev;
	u_int32_t sc_stat;
	u_int32_t sc_capabilities;

	int sc_flags;
#define	TPM_OPEN	0x0001

	int	 sc_vector;
};

int tpm_intr(void *);

bool tpm_suspend(device_t, const pmf_qual_t *);
bool tpm_resume(device_t, const pmf_qual_t *);

int tpm_tis12_probe(bus_space_tag_t, bus_space_handle_t);
int tpm_tis12_init(struct tpm_softc *, int, const char *);
int tpm_tis12_start(struct tpm_softc *, int);
int tpm_tis12_read(struct tpm_softc *, void *, size_t, size_t *, int);
int tpm_tis12_write(struct tpm_softc *, const void *, size_t);
int tpm_tis12_end(struct tpm_softc *, int, int);

int tpm_legacy_probe(bus_space_tag_t, bus_addr_t);
int tpm_legacy_init(struct tpm_softc *, int, const char *);
int tpm_legacy_start(struct tpm_softc *, int);
int tpm_legacy_read(struct tpm_softc *, void *, size_t, size_t *, int);
int tpm_legacy_write(struct tpm_softc *, const void *, size_t);
int tpm_legacy_end(struct tpm_softc *, int, int);


text:
(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['jquery', '../slick.core'], factory);
  } else {
    // Browser globals
    root.Slick.CheckboxSelectColumn = factory(root.jQuery, root.Slick);
  }
}(this, function ($, Slick) {

  function CheckboxSelectColumn(options) {
    var _grid;
    var _self = this;
    var _handler = new Slick.EventHandler();
    var _selectedRowsLookup = {};
    var _defaults = {
      columnId: "_checkbox_selector",
      cssClass: null,
      toolTip: "Select/Deselect All",
      width: 30
    };

    var _options = $.extend(true, {}, _defaults, options);

    function init(grid) {
      _grid = grid;
      _handler
        .subscribe(_grid.onSelectedRowsChanged, handleSelectedRowsChanged)
        .subscribe(_grid.onClick, handleClick)
        .subscribe(_grid.onHeaderClick, handleHeaderClick)
        .subscribe(_grid.onKeyDown, handleKeyDown);
    }

    function destroy() {
      _handler.unsubscribeAll();
    }

    function handleSelectedRowsChanged(e, args) {
      var selectedRows = _grid.getSelectedRows();
      var lookup = {}, row, i;
      for (i = 0; i < selectedRows.length; i++) {
        row = selectedRows[i];
        lookup[row] = true;
        if (lookup[row] !== _selectedRowsLookup[row]) {
          _grid.invalidateRow(row);
          delete _selectedRowsLookup[row];
        }
      }
      for (i in _selectedRowsLookup) {
        _grid.invalidateRow(i);
      }
      _selectedRowsLookup = lookup;
      _grid.render();

      if (selectedRows.length && selectedRows.length == _grid.getDataLength()) {
        _grid.updateColumnHeader(_options.columnId, "<input type='checkbox' checked='checked'>", _options.toolTip);
      } else {
        _grid.updateColumnHeader(_options.columnId, "<input type='checkbox'>", _options.toolTip);
      }
    }

    function handleKeyDown(e, args) {
      if (e.which == 32) {
        if (_grid.getColumns()[args.cell].id === _options.columnId) {
          // if editing, try to commit
          if (!_grid.getEditorLock().isActive() || _grid.getEditorLock().commitCurrentEdit()) {
            toggleRowSelection(args.row);
          }
          e.preventDefault();
          e.stopImmediatePropagation();
        }
      }
    }

    function handleClick(e, args) {
      // clicking on a row select checkbox
      if (_grid.getColumns()[args.cell].id === _options.columnId && $(e.target).is(":checkbox")) {
        // if editing, try to commit
        if (_grid.getEditorLock().isActive() && !_grid.getEditorLock().commitCurrentEdit()) {
          e.preventDefault();
          e.stopImmediatePropagation();
          return;
        }

        toggleRowSelection(args.row);
        e.stopPropagation();
        e.stopImmediatePropagation();
      }
    }

    function toggleRowSelection(row) {
      if (_selectedRowsLookup[row]) {
        _grid.setSelectedRows($.grep(_grid.getSelectedRows(), function (n) {
          return n != row
        }));
      } else {
        _grid.setSelectedRows(_grid.getSelectedRows().concat(row));
      }
    }

    function handleHeaderClick(e, args) {
      if (args.column.id == _options.columnId && $(e.target).is(":checkbox")) {
        // if editing, try to commit
        if (_grid.getEditorLock().isActive() && !_grid.getEditorLock().commitCurrentEdit()) {
          e.preventDefault();
          e.stopImmediatePropagation();
          return;
        }

        if ($(e.target).is(":checked")) {
          var rows = [];
          for (var i = 0; i < _grid.getDataLength(); i++) {
            rows.push(i);
          }
          _grid.setSelectedRows(rows);
        } else {
          _grid.setSelectedRows([]);
        }
        e.stopPropagation();
        e.stopImmediatePropagation();
      }
    }

    function getColumnDefinition() {
      return {
        id: _options.columnId,
        name: "<input type='checkbox'>",
        toolTip: _options.toolTip,
        field: "sel",
        width: _options.width,
        resizable: false,
        sortable: false,
        cssClass: _options.cssClass,
        formatter: checkboxSelectionFormatter
      };
    }

    function checkboxSelectionFormatter(row, cell, value, columnDef, dataContext) {
      if (dataContext) {
        return _selectedRowsLookup[row]
            ? "<input type='checkbox' checked='checked'>"
            : "<input type='checkbox'>";
      }
      return null;
    }

    $.extend(this, {
      "init": init,
      "destroy": destroy,

      "getColumnDefinition": getColumnDefinition
    });
  }

  return CheckboxSelectColumn;

}));


text:
// Copyright 2021 Cloud Native Foundation.
// Licensed under the Apache 2.0 license.
// See LICENSE file in the project root for full license information.

using System;
using Xunit;

namespace CloudNative.CloudEvents.UnitTests
{
    public class CloudEventAttributeTest
    {
        [Theory]
        [InlineData("")]
        [InlineData("UPPER")]
        [InlineData("punct-uation")]
        [InlineData("under_scope")]
        public void CreateExtension_InvalidName(string name)
        {
            var exception = Assert.Throws<ArgumentException>(() => CloudEventAttribute.CreateExtension(name, CloudEventAttributeType.String));
            if (!string.IsNullOrEmpty(name))
            {
                Assert.Contains($"'{name}'", exception.Message);
            }
        }

        [Theory]
        [InlineData("simple")]
        [InlineData("longnamethatwouldnotberecommendedbutisstillvalidsoweshouldnotthrow")]
        public void CreateExtension_ValidName(string name)
        {
            var attr = CloudEventAttribute.CreateExtension(name, CloudEventAttributeType.Uri);
            Assert.Equal(name, attr.Name);
        }

        [Fact]
        public void Properties_ExtensionAttribute()
        {
            var attr = CloudEventAttribute.CreateExtension("test", CloudEventAttributeType.Uri);
            Assert.Equal("test", attr.Name);
            Assert.Equal("test", attr.ToString());
            Assert.Equal(CloudEventAttributeType.Uri, attr.Type);
            Assert.False(attr.IsRequired);
            Assert.True(attr.IsExtension);
        }

        [Fact]
        public void Properties_RequiredAttribute()
        {
            var attr = CloudEventsSpecVersion.V1_0.IdAttribute;
            Assert.Equal("id", attr.Name);
            Assert.Equal("id", attr.ToString());
            Assert.Equal(CloudEventAttributeType.String, attr.Type);
            Assert.True(attr.IsRequired);
            Assert.False(attr.IsExtension);
        }

        [Fact]
        public void Properties_OptionalAttribute()
        {
            var attr = CloudEventsSpecVersion.V1_0.TimeAttribute;
            Assert.Equal("time", attr.Name);
            Assert.Equal("time", attr.ToString());
            Assert.Equal(CloudEventAttributeType.Timestamp, attr.Type);
            Assert.False(attr.IsRequired);
            Assert.False(attr.IsExtension);
        }

        [Fact]
        public void CreateExtension_NullName() =>
            Assert.Throws<ArgumentNullException>(() => CloudEventAttribute.CreateExtension(null!, CloudEventAttributeType.String));

        [Fact]
        public void CreateExtension_NullType() =>
            Assert.Throws<ArgumentNullException>(() => CloudEventAttribute.CreateExtension("name", null!));

        [Fact]
        public void CreateExtension_SpecVersionName() =>
            Assert.Throws<ArgumentException>(() =>
                CloudEventAttribute.CreateExtension(CloudEventsSpecVersion.SpecVersionAttributeName, CloudEventAttributeType.String));

        [Fact]
        public void CreateExtension_DataName() =>
            Assert.Throws<ArgumentException>(() =>
                CloudEventAttribute.CreateExtension("data", CloudEventAttributeType.String));

        [Fact]
        public void Validate_NoValidator_Valid()
        {
            var attr = CloudEventAttribute.CreateExtension("ext", CloudEventAttributeType.Integer, validator: null);
            attr.Validate(10);
        }

        [Fact]
        public void Validate_NoValidator_InvalidType()
        {
            var attr = CloudEventAttribute.CreateExtension("ext", CloudEventAttributeType.Integer, validator: null);
            Assert.Throws<ArgumentException>(() => attr.Validate(10L));
        }

        [Fact]
        public void Validate_WithValidator_Valid()
        {
            var attr = CloudEventAttribute.CreateExtension("ext", CloudEventAttributeType.Integer, ValidateNonNegative);
            attr.Validate(10);

        }

        [Fact]
        public void Validate_WithValidator_InvalidType()
        {
            var attr = CloudEventAttribute.CreateExtension("ext", CloudEventAttributeType.Integer, ValidateNonNegative);
            Assert.Throws<ArgumentException>(() => attr.Validate(10L));
        }

        [Fact]
        public void Validate_WithValidator_InvalidValue()
        {
            var attr = CloudEventAttribute.CreateExtension("ext", CloudEventAttributeType.Integer, ValidateNonNegative);
            var exception = Assert.Throws<ArgumentException>(() => attr.Validate(-5));
            Assert.Contains("Custom validation message", exception.Message);
            Assert.IsType<Exception>(exception.InnerException);
            Assert.Equal("Custom validation message", exception.InnerException!.Message);
        }

        [Fact]
        public void Parse_Valid()
        {
            var attr = CloudEventAttribute.CreateExtension("ext", CloudEventAttributeType.Integer, ValidateNonNegative);
            Assert.Equal(10, attr.Parse("10"));
        }

        [Fact]
        public void Parse_Invalid()
        {
            var attr = CloudEventAttribute.CreateExtension("ext", CloudEventAttributeType.Integer, ValidateNonNegative);
            Assert.Throws<ArgumentException>(() => attr.Parse("-5"));
        }

        [Fact]
        public void Format_Valid()
        {
            var attr = CloudEventAttribute.CreateExtension("ext", CloudEventAttributeType.Integer, ValidateNonNegative);
            Assert.Equal("10", attr.Format(10));
        }

        [Fact]
        public void Format_Invalid()
        {
            var attr = CloudEventAttribute.CreateExtension("ext", CloudEventAttributeType.Integer, ValidateNonNegative);
            Assert.Throws<ArgumentException>(() => attr.Format(-5));
        }

        private void ValidateNonNegative(object value)
        {
            if ((int)value < 0)
            {
                throw new Exception("Custom validation message");
            }
        }
    }
}


text:
<md-button ng-if="$ctrl.hasErrors()" class="md-fab md-fab-bottom-right md-primary md-mini" ng-click="$ctrl.openErrorLog()">
    <md-icon>assignment late</md-icon>
</md-button>


text:
<!-- 暂时用不上 -->
@if(Session::has('flash_message'))
	<div class="alert alert-success {{ Session::has('flash_message_important') ? 'alert-imoprtant' : '' }}">
		@if(Session::has('flash_message_important'))
			<button type="button" class="close" data-dismiss="alert" aria-hidden="true"> × </button>
		@endif
		{{ session('flash_message') }}
	</div>
@endif


text:
<?php
/**
 * This file is part of the DVSA MOT API project.
 *
 * @link https://gitlab.motdev.org.uk/mot/mot
 */

namespace DvsaMotApi\Service;

use DvsaCommon\Auth\MotAuthorisationServiceInterface;
use DvsaCommon\Auth\PermissionInSystem;
use DvsaCommon\Constants\OdometerReadingResultType;
use DvsaCommon\Constants\ReasonForRejection;
use DvsaCommon\Enum\MotTestStatusName;
use DvsaCommon\Enum\MotTestTypeCode;
use DvsaEntities\Entity\MotTest;

class MotTestStatusService
{
    /**
     * @var MotAuthorisationServiceInterface
     */
    private $authorisationService;

    /**
     * MotTestStatusService constructor.
     *
     * @param MotAuthorisationServiceInterface $authorisationService
     */
    public function __construct(MotAuthorisationServiceInterface $authorisationService)
    {
        $this->authorisationService = $authorisationService;
    }

    /**
     * @param MotTest $motTest
     *
     * @return bool
     */
    public function isIncomplete(MotTest $motTest)
    {
        $hasBrakeTestResult = $motTest->hasBrakeTestResults();
        $canTestWithoutBrakeTests = $this->authorisationService->isGranted(PermissionInSystem::TEST_WITHOUT_BRAKE_TESTS);
        $hasUnrepairedBrakePerformanceNotTestedRfr = $this->hasUnrepairedBrakePerformanceNotTestedRfr($motTest);

        $hasOriginalBrakeTestPassing = $motTest->getMotTestType()->getCode() === MotTestTypeCode::RE_TEST
            && $motTest->getMotTestIdOriginal()->getBrakeTestGeneralPass();

        $isBrakeTestOk = $hasBrakeTestResult || $hasUnrepairedBrakePerformanceNotTestedRfr || $canTestWithoutBrakeTests
            || $hasOriginalBrakeTestPassing;

        return !$this->hasOdometer($motTest) || !$isBrakeTestOk;
    }

    /**
     * @param MotTest $motTest
     *
     * @return bool
     */
    public function hasUnrepairedBrakePerformanceNotTestedRfr(MotTest $motTest)
    {
        $motRfrs = $motTest->getMotTestReasonForRejections();
        foreach ($motRfrs as $rfr) {
            if ($rfr->getReasonForRejection() === null) {
                continue; // TODO solve 'Manual Advisory' Test RFRs which doesn't have linked RFR
            }
            $rfrId = $rfr->getReasonForRejection()->getRfrId();
            if (in_array($rfrId, ReasonForRejection::BRAKE_PERFORMANCE_NOT_TESTED_RFR_IDS) && !$rfr->isMarkedAsRepaired()) {
                return true;
            }
        }

        return false;
    }

    /**
     * @param MotTest $motTest
     *
     * @return string
     */
    public function getMotTestPendingStatus(MotTest $motTest)
    {
        if ($this->isIncomplete($motTest)) {
            return MotTestService::PENDING_INCOMPLETE_STATUS;
        }

        return $motTest->hasFailures() ? MotTestStatusName::FAILED : MotTestStatusName::PASSED;
    }

    private function hasOdometer(MotTest $motTest)
    {
        $hasOdometerValue = !is_null($motTest->getOdometerValue());
        $hasOdometerUnit = !is_null($motTest->getOdometerUnit());
        $hasOdometerResultType = !is_null($motTest->getOdometerResultType()) &&
            OdometerReadingResultType::OK != $motTest->getOdometerResultType();

        return ($hasOdometerValue && $hasOdometerUnit) xor $hasOdometerResultType;
    }
}


text:
====================
Product Introduction
====================

.. toctree::
   :maxdepth: 1

   identity-and-access-management.md
   iam-features.md
   identity-management.md
   permission-management.md
   personal-data-protection-mechanism.md


text:
#ifndef TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_PROCESS_BROADCAST_SHAPES_H_
#define TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_PROCESS_BROADCAST_SHAPES_H_

#include <algorithm>

#include "tensorflow/lite/kernels/internal/types.h"

namespace tflite {

namespace reference_ops {

// Consolidates dimensions in broadcast inputs, checks for five-fold pattern.
//
// For example, if sequence of dimensions of one input is
// ..., 1, 3, 1, 7, 9, 5,... and the other is ..., 2, 3, 1, 7, 1, 1, ...
// we can consolidate these as
// ..., 1, 3*7, 9*5, ... and 2, 3*7, 1.
//
// The category is updated in the less-frequent case of shapes that are
// not suited to a fivefold-loop broadcast.
//
// Falls back to generic pattern when it does not know how to process properly.
//
// Returns true iff there is some sort of broadcast, which includes five-fold
// patterns and falling back to generic broadcast.
inline bool ProcessBroadcastShapes(const RuntimeShape& shape0,
                                   const RuntimeShape& shape1,
                                   tflite::ArithmeticParams* params) {
  const int dims_count =
      std::max(shape0.DimensionsCount(), shape1.DimensionsCount());

  params->broadcast_category = BroadcastableOpCategory::kGenericBroadcast;
  RuntimeShape scalar_shape(dims_count, 1);

  auto extended_shape0 = RuntimeShape::ExtendedShape(dims_count, shape0);
  auto extended_shape1 = RuntimeShape::ExtendedShape(dims_count, shape1);

  // Check for "exact" match, implicitly accepting any scalar shapes.
  if (extended_shape0 == extended_shape1) {
    params->broadcast_category = BroadcastableOpCategory::kNonBroadcast;
    return false;
  }

  for (int i = dims_count - 1; i >= 0; --i) {
    if (extended_shape0.Dims(i) == extended_shape1.Dims(i)) {
      continue;
    } else if (extended_shape0.Dims(i) == 1) {
      params->broadcast_category =
          BroadcastableOpCategory::kFirstInputBroadcastsFast;
      break;
    } else if (extended_shape1.Dims(i) == 1) {
      params->broadcast_category =
          BroadcastableOpCategory::kSecondInputBroadcastsFast;
      break;
    } else {
      // This case is erroneous: there is a dimension that does not match and
      // is not a broadcast from one shape to the other.
      params->broadcast_category = BroadcastableOpCategory::kGenericBroadcast;
      return true;
    }
  }

  if (params->broadcast_category !=
          BroadcastableOpCategory::kFirstInputBroadcastsFast &&
      params->broadcast_category !=
          BroadcastableOpCategory::kSecondInputBroadcastsFast) {
    // This is unreachable because at least one else clause in the above loop
    // must be reached.
    TFLITE_DCHECK(false);
    params->broadcast_category = BroadcastableOpCategory::kNonBroadcast;
    return false;
  }

  // From this point it is assumed contractually that corresponding dimensions
  // in shape0 and shape1 are either (a) equal or (b) one or other equals 1.
  const bool swap_inputs = params->broadcast_category ==
                           BroadcastableOpCategory::kSecondInputBroadcastsFast;
  const RuntimeShape* shape_a =
      swap_inputs ? &extended_shape1 : &extended_shape0;
  const RuntimeShape* shape_b =
      swap_inputs ? &extended_shape0 : &extended_shape1;

  int i = dims_count - 1;
  params->broadcast_shape[0] = 1;
  params->broadcast_shape[1] = 1;
  params->broadcast_shape[2] = 1;
  params->broadcast_shape[3] = 1;
  params->broadcast_shape[4] = 1;
  // y_0 is greedy: include dims if both or neither equal 1: in other words,
  // test for equality rather than (shape_a->Dims(i) != 1).
  while (i >= 0 && shape_a->Dims(i) == shape_b->Dims(i)) {
    params->broadcast_shape[4] *= shape_b->Dims(i);
    --i;
  }
  // Here either input_a or input_b has dim of 1 (if i >= 0).  If it is input_b
  // that has the unit dimension, the next two loops are not entered.
  while (i >= 0 && shape_a->Dims(i) == 1) {
    params->broadcast_shape[3] *= shape_b->Dims(i);
    --i;
  }
  while (i >= 0 && shape_a->Dims(i) == shape_b->Dims(i)) {
    params->broadcast_shape[2] *= shape_a->Dims(i);
    --i;
  }
  // Here either input_a or input_b has dim of 1 (if i >= 0).
  while (i >= 0 && shape_b->Dims(i) == 1) {
    params->broadcast_shape[1] *= shape_a->Dims(i);
    --i;
  }
  while (i >= 0 && shape_a->Dims(i) == shape_b->Dims(i)) {
    params->broadcast_shape[0] *= shape_b->Dims(i);
    --i;
  }

  // Rarer case is when the broadcast dimensions cannot be handled by a fivefold
  // loop.
  if (i >= 0) {
    params->broadcast_category = BroadcastableOpCategory::kGenericBroadcast;
  }
  return true;
}

}  // namespace reference_ops
}  // namespace tflite

#endif  // TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_PROCESS_BROADCAST_SHAPES_H_


text:
var baseIteratee = require('./_baseIteratee'),
    createInverter = require('./_createInverter');

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * This method is like `_.invert` except that the inverted object is generated
 * from the results of running each element of `object` thru `iteratee`. The
 * corresponding inverted value of each inverted key is an array of keys
 * responsible for generating the inverted value. The iteratee is invoked
 * with one argument: (value).
 *
 * @static
 * @memberOf _
 * @since 4.1.0
 * @category Object
 * @param {Object} object The object to invert.
 * @param {Array|Function|Object|string} [iteratee=_.identity]
 *  The iteratee invoked per element.
 * @returns {Object} Returns the new inverted object.
 * @example
 *
 * var object = { 'a': 1, 'b': 2, 'c': 1 };
 *
 * _.invertBy(object);
 * // => { '1': ['a', 'c'], '2': ['b'] }
 *
 * _.invertBy(object, function(value) {
 *   return 'group' + value;
 * });
 * // => { 'group1': ['a', 'c'], 'group2': ['b'] }
 */
var invertBy = createInverter(function(result, value, key) {
  if (hasOwnProperty.call(result, value)) {
    result[value].push(key);
  } else {
    result[value] = [key];
  }
}, baseIteratee);

module.exports = invertBy;


text:
using namespace arangodb;
using namespace arangodb::basics;

std::string GeneralRequest::translateMethod(RequestType method) {
  switch (method) {
    case RequestType::DELETE_REQ:
      return "DELETE";

    case RequestType::GET:
      return "GET";

    case RequestType::HEAD:
      return "HEAD";

    case RequestType::OPTIONS:
      return "OPTIONS";

    case RequestType::PATCH:
      return "PATCH";

    case RequestType::POST:
      return "POST";

    case RequestType::PUT:
      return "PUT";

    case RequestType::ILLEGAL:
      LOG_TOPIC("62a53", WARN, arangodb::Logger::FIXME)
          << "illegal http request method encountered in switch";
      return "UNKNOWN";
  }

  return "UNKNOWN";  // in order please MSVC
}

namespace  {
rest::RequestType translateMethod(VPackStringRef const& methodString) {
  if (methodString == "DELETE") {
    return RequestType::DELETE_REQ;
  } else if (methodString == "GET") {
    return RequestType::GET;
  } else if (methodString == "HEAD") {
    return RequestType::HEAD;
  } else if (methodString == "OPTIONS") {
    return RequestType::OPTIONS;
  } else if (methodString == "PATCH") {
    return RequestType::PATCH;
  } else if (methodString == "POST") {
    return RequestType::POST;
  } else if (methodString == "PUT") {
    return RequestType::PUT;
  }
  return RequestType::ILLEGAL;
}
}

rest::RequestType GeneralRequest::translateMethod(VPackStringRef const& method) {
  auto ret = ::translateMethod(method);
  if (RequestType::ILLEGAL == ret) {
    std::string const methodString = StringUtils::toupper(method.toString());
    return ::translateMethod(VPackStringRef(methodString));
  }
  return ret;
}

void GeneralRequest::appendMethod(RequestType method, StringBuffer* buffer) {
  // append RequestType as string value to given String buffer
  buffer->appendText(translateMethod(method));
  buffer->appendChar(' ');
}

rest::RequestType GeneralRequest::findRequestType(char const* ptr, size_t const length) {
  switch (length) {
    case 3:
      if (ptr[0] == 'g' && ptr[1] == 'e' && ptr[2] == 't') {
        return RequestType::GET;
      }
      if (ptr[0] == 'p' && ptr[1] == 'u' && ptr[2] == 't') {
        return RequestType::PUT;
      }
      break;

    case 4:
      if (ptr[0] == 'p' && ptr[1] == 'o' && ptr[2] == 's' && ptr[3] == 't') {
        return RequestType::POST;
      }
      if (ptr[0] == 'h' && ptr[1] == 'e' && ptr[2] == 'a' && ptr[3] == 'd') {
        return RequestType::HEAD;
      }
      break;

    case 5:
      if (ptr[0] == 'p' && ptr[1] == 'a' && ptr[2] == 't' && ptr[3] == 'c' && ptr[4] == 'h') {
        return RequestType::PATCH;
      }
      break;

    case 6:
      if (ptr[0] == 'd' && ptr[1] == 'e' && ptr[2] == 'l' && ptr[3] == 'e' &&
          ptr[4] == 't' && ptr[5] == 'e') {
        return RequestType::DELETE_REQ;
      }
      break;

    case 7:
      if (ptr[0] == 'o' && ptr[1] == 'p' && ptr[2] == 't' && ptr[3] == 'i' &&
          ptr[4] == 'o' && ptr[5] == 'n' && ptr[6] == 's') {
        return RequestType::OPTIONS;
      }
      break;
  }

  return RequestType::ILLEGAL;
}

GeneralRequest::~GeneralRequest() {
  // only delete if we are the owner of the context
  if (_requestContext != nullptr && _isRequestContextOwner) {
    delete _requestContext;
  }
}

void GeneralRequest::setRequestContext(RequestContext* requestContext, bool isRequestContextOwner) {
  TRI_ASSERT(requestContext != nullptr);

  if (_requestContext) {
    // if we have a shared context, we should not have got here
    TRI_ASSERT(isRequestContextOwner);

    // delete any previous context
    TRI_ASSERT(false);
    delete _requestContext;
  }

  _requestContext = requestContext;
  _isRequestContextOwner = isRequestContextOwner;
}

void GeneralRequest::addSuffix(std::string part) {
  // part will not be URL-decoded here!
  _suffixes.emplace_back(std::move(part));
}

std::vector<std::string> GeneralRequest::decodedSuffixes() const {
  std::vector<std::string> result;
  result.reserve(_suffixes.size());

  for (auto const& it : _suffixes) {
    result.emplace_back(StringUtils::urlDecodePath(it));
  }
  return result;
}

std::string const& GeneralRequest::header(std::string const& key, bool& found) const {
  auto it = _headers.find(key);
  if (it == _headers.end()) {
    found = false;
    return StaticStrings::Empty;
  }

  found = true;
  return it->second;
}

std::string const& GeneralRequest::header(std::string const& key) const {
  bool unused = true;
  return header(key, unused);
}

std::string const& GeneralRequest::value(std::string const& key, bool& found) const {
  if (!_values.empty()) {
    auto it = _values.find(key);

    if (it != _values.end()) {
      found = true;
      return it->second;
    }
  }

  found = false;
  return StaticStrings::Empty;
}

std::string const& GeneralRequest::value(std::string const& key) const {
  bool unused = true;
  return value(key, unused);
}

std::map<std::string, std::string> GeneralRequest::parameters() const {
  std::map<std::string, std::string> parameters {};
  for (auto const& paramPair : values()) {
    parameters.try_emplace(paramPair.first, paramPair.second);
  }
  return parameters;
}

// needs to be here because of a gcc bug with templates and namespaces
// https://stackoverflow.com/a/25594741/1473569
namespace arangodb {
template <>
bool GeneralRequest::parsedValue(std::string const& key, bool valueNotFound) {
  bool found = false;
  std::string const& val = this->value(key, found);
  if (found) {
    return StringUtils::boolean(val);
  }
  return valueNotFound;
}

template <>
uint64_t GeneralRequest::parsedValue(std::string const& key, uint64_t valueNotFound) {
  bool found = false;
  std::string const& val = this->value(key, found);
  if (found) {
    return StringUtils::uint64(val);
  }
  return valueNotFound;
}

template <>
double GeneralRequest::parsedValue(std::string const& key, double valueNotFound) {
  bool found = false;
  std::string const& val = this->value(key, found);
  if (found) {
    return StringUtils::doubleDecimal(val);
  }
  return valueNotFound;
}

std::shared_ptr<VPackBuilder> GeneralRequest::toVelocyPackBuilderPtr(bool strictValidation) {
  return std::make_shared<VPackBuilder>(payload(strictValidation));
}

/// @brief get VelocyPack options for validation. effectively turns off
/// validation if strictValidation is false. This optimization can be used for
/// internal requests
arangodb::velocypack::Options const* GeneralRequest::validationOptions(bool strictValidation) {
  if (strictValidation) {
    return &basics::VelocyPackHelper::strictRequestValidationOptions;
  }
  return &basics::VelocyPackHelper::looseRequestValidationOptions;
}

}  // namespace arangodb


text:
import { createReadStream, createWriteStream } from 'fs';
import * as br from 'iltorb';

const opts: br.BrotliEncodeParams = {
    disable_literal_context_modeling: false,
    lgblock: 0,
    lgwin: 22,
    mode: 0,
    quality: 11,
    size_hint: 0
};

const onCompress = (err1: Error | null | undefined, compressed: Buffer) => {
    br.decompress(compressed, (err2: Error | null | undefined, decompressed: Buffer) => {
        console.log(decompressed.toString());
    });
};

br.compress(Buffer.from('foo', 'utf8'), onCompress);

br.compress(Buffer.from('foo', 'utf8'), opts, onCompress);

br
    .compress(Buffer.from('foobar'))
    .then(compressedData => {
        br.decompress(compressedData).then(data => {
            console.log(data.equals(Buffer.from('foobar')));
        });
    });

const stream = br.compressStream();
stream.flush();

createReadStream(__filename)
    .pipe(stream)
    .pipe(createWriteStream('foo.ts'));

createReadStream(__dirname)
    .pipe(br.compressStream(opts))
    .pipe(createWriteStream('bar.ts'));

createReadStream('bar.ts')
    .pipe(br.decompressStream())
    .pipe(createWriteStream('qux.ts'));

br.decompressSync(br.compressSync(Buffer.from('foo', 'utf8')));
br.decompressSync(br.compressSync(Buffer.from('foo', 'utf8'), opts));


text:
using System.Collections.Generic;
using System.Linq;
using Flunet.Automata;
using Flunet.Automata.Interfaces;
using Flunet.Automata.Language;

namespace Flunet.Extensions
{
    /// <summary>
    /// Provides extension methods for <see cref="IAutomata{T}"/>.
    /// </summary>
    public static class AutomataExtensions
    {
        public static void ReadWord<T>(this IAutomata<T> automata, IEnumerable<T> word)
        {
            foreach (T symbol in word)
            {
                automata.Read(symbol);
            }
        }

        public static void AddRange<T>(this IExtendableDeterministicAutomata<T> source, IEnumerable<IAutomataState<T>> range)
        {
            foreach (var currentState in range)
            {
                if (!source.Contains(currentState))
                {
                    source.Add(currentState);
                }
            }
        }

        public static void AddRange<T>(this IExtendableAutomataState<T> source, IEnumerable<KeyValuePair<T, IAutomataState<T>>> range)
        {
            foreach (var currentState in range)
            {
                if (!source.Contains(currentState))
                {
                    source.Add(currentState.Key, currentState.Value);
                }
            }
        }

        public static IExtendableAutomataState<T> AddState<T>(this IExtendableDeterministicAutomata<T> automata, string id, bool isValid)
        {
            var result = new AutomataState<T>(id, isValid, automata.Comparer);

            automata.Add(result);

            return result;
        }

        public static bool IsReachableFrom<T>(this IAutomataState<T> source, IAutomataState<T> from)
        {
            return AutomataUnaryOperations.IsReachableFrom(source, from);
        }

        public static IExtendableDeterministicAutomata<T> WithoutRedundantStates<T>(this IDeterministicAutomata<T> source)
        {
            return AutomataUnaryOperations.ClearRedundantStates(source);
        }

        public static IExtendableDeterministicAutomata<T> Union<T>(this IDeterministicAutomata<T> source, IDeterministicAutomata<T> other)
        {
            return AutomataBinaryOperations.GetUnion(source.WithoutRedundantStates(), other.WithoutRedundantStates(), source.Comparer).WithoutRedundantStates();
        }

        public static IExtendableDeterministicAutomata<T> Intersect<T>(this IDeterministicAutomata<T> source, IDeterministicAutomata<T> other)
        {
            return AutomataBinaryOperations.GetIntersection(source.WithoutRedundantStates(), other.WithoutRedundantStates(), source.Comparer).WithoutRedundantStates();
        }

        public static IExtendableDeterministicAutomata<T> Not<T>(this IDeterministicAutomata<T> source)
        {
            return AutomataUnaryOperations.GetNot(source, source.Comparer);
        }
    }
}


text:
/*
 * Architecture-specific context switch
 */

/*
 * Copyright (c) 2015, ETH Zurich.
 * All rights reserved.
 *
 * This file is distributed under the terms in the attached LICENSE file.
 * If you do not find this file, copies can be found by writing to:
 * ETH Zurich D-INFK, Universitaetstrasse 6, CH-8092 Zurich. Attn: Systems Group.
 */

#include <kernel.h>
#include <dispatch.h>
#include <paging_kernel_arch.h>

/**
 * \brief Switch context to 'dcb'.
 *
 * Switch to the dispatcher pointed to by 'dcb'. Sets 'dcb_current'.
 *
 * \param dcb        Pointer to dispatcher to which to switch context.
 */
void
context_switch(struct dcb *dcb) {
    struct dispatcher_shared_generic *disp =
        get_dispatcher_shared_generic(dcb->disp);

    assert(dcb != NULL);
    assert(dcb->vspace != 0);

    // VM guests do not have a user space dispatcher
    if (!dcb->is_vm_guest) {
        assert(dcb->disp != 0);
    }

    fpu_lazy_top(dcb);

    paging_context_switch(dcb->vspace);
    context_switch_counter++;

    if (!dcb->is_vm_guest) {
        assert(dcb->disp_cte.cap.type == ObjType_Frame);

        fpu_lazy_bottom(dcb);

        /*
         * The name of the function is somewhat misleading. we need an unused
         * user register that always stores the pointer to the current
         * dispatcher. most ABIs define a register for thread-local storage,
         * and we have been abusing that on x64 for the dispatcher pointer
         * --arch_set_thread_ register sets this pointer.  Obviously this
         * needs to change to support thread-local storage using a standard
         * ABI, so we will have to figure out how to get to the dispatcher
         * from something like a thread-local variable.  The reason that this
         * is in the switch path and not in resume/execute is that on x86_64
         * loading the thread register (fs) is stupidly expensive, so we avoid
         * doing it unless we switch contexts -- presumably that could be a
         * local optimisation in the x86_64 dispatch paths rather than the
         * generic context_switch path/
         */
        arch_set_thread_register(disp->udisp);
    }
}


text:
class CPDF_Form;

class CPDF_FormObject final : public CPDF_PageObject {
 public:
  CPDF_FormObject(int32_t content_stream,
                  std::unique_ptr<CPDF_Form> pForm,
                  const CFX_Matrix& matrix);
  ~CPDF_FormObject() override;

  // CPDF_PageObject:
  Type GetType() const override;
  void Transform(const CFX_Matrix& matrix) override;
  bool IsForm() const override;
  CPDF_FormObject* AsForm() override;
  const CPDF_FormObject* AsForm() const override;

  void CalcBoundingBox();
  const CPDF_Form* form() const { return m_pForm.get(); }
  const CFX_Matrix& form_matrix() const { return m_FormMatrix; }

 private:
  std::unique_ptr<CPDF_Form> const m_pForm;
  CFX_Matrix m_FormMatrix;
};

#endif  // CORE_FPDFAPI_PAGE_CPDF_FORMOBJECT_H_


text:
from datetime import datetime
from datetime import timedelta

from mistral.openstack.common import timeutils

from mistral.services import scheduler as s
from mistral.tests import base as test_base

SAMPLE_TRIGGER = {
    "id": "123",
    "name": "test_trigger",
    "patter": "* *",
    "next_execution_time": timeutils.utcnow(),
    "workbook_name": "My workbook"
}

class SchedulerTest(test_base.DbTestCase):
    def setUp(self):
        super(SchedulerTest, self).setUp()
        self.wb_name = "My workbook"

    def test_trigger_create_and_update(self):
        base = datetime(2010, 8, 25)
        next_trigger = datetime(2010, 8, 25, 0, 5)
        trigger = s.create_trigger("test", "*/5 * * * *", self.wb_name, base)
        self.assertEqual(trigger['next_execution_time'], next_trigger)

        trigger = s.set_next_execution_time(trigger)
        next_trigger = datetime(2010, 8, 25, 0, 10)
        self.assertEqual(trigger['next_execution_time'], next_trigger)

    def test_get_trigger_in_correct_orders(self):
        base = datetime(2010, 8, 25)
        s.create_trigger("test1", "*/5 * * * *", self.wb_name, base)
        base = datetime(2010, 8, 22)
        s.create_trigger("test2", "*/5 * * * *", self.wb_name, base)
        base = datetime(2010, 9, 21)
        s.create_trigger("test3", "*/5 * * * *", self.wb_name, base)
        base = datetime.now() + timedelta(0, 50)
        s.create_trigger("test4", "*/5 * * * *", self.wb_name, base)
        triggersName = [e['name'] for e in s.get_next_triggers()]

        self.assertEqual(triggersName, ["test2", "test1", "test3"])


text:
using System.Runtime.InteropServices;

namespace GraduatedCylinder;

[StructLayout(LayoutKind.Sequential)]
public readonly struct ThreeD<TDimension>
{

    public ThreeD(TDimension x, TDimension y, TDimension z) {
        X = x;
        Y = y;
        Z = z;
    }

    public TDimension X { get; }

    public TDimension Y { get; }

    public TDimension Z { get; }

}


text:
package org.vromero.gist.mojo;

import org.apache.maven.plugins.annotations.Parameter;

import java.io.File;

public class SnippetFile {

	@Parameter(required = true )
	private File location;

	@Parameter(required = false )
	private String snippetId;

	@Parameter(required = true )
	private String gistFileName;

	public File getLocation() {
		return location;
	}

	public void setLocation(File location) {
		this.location = location;
	}

	public String getSnippetId() {
		return snippetId;
	}

	public void setSnippetId(String snippetId) {
		this.snippetId = snippetId;
	}

	public String getGistFileName() {
		return gistFileName;
	}

	public void setGistFileName(String gistFileName) {
		this.gistFileName = gistFileName;
	}

}


text:
package ie.lero.evoting.scenario;

import junit.framework.TestCase;
import election.tally.BallotCounting;
import election.tally.Constituency;

public class CountContinuingCandidatesEventK extends TestCase {

  public void testEvent() {
    final BallotCounting ballotCounting = new BallotCounting();
    final Constituency constituency = new Constituency();
    constituency.setNumberOfSeats(3, 3);
    constituency.setNumberOfCandidates(4);
    // TODO precondition not established
    ballotCounting.setup(constituency); //@ nowarn;
    //@ assert (4 == ballotCounting.getContinuingCandidates());
  }
}


text:
package org.jetbrains.plugins.scala
package lang
package psi
package api
package toplevel

import org.jetbrains.plugins.scala.lang.psi.api.toplevel.typedef.ScMember

/**
* @author Alexander Podkhalyuzin
* Date: 22.02.2008
*/

trait ScEarlyDefinitions extends ScalaPsiElement {
  def members: Seq[ScMember]
}


text:
extern crate gl;
extern crate glfw;
extern crate time;
extern crate rand;

use gl::types::*;
use glfw::Context;
use rand::Rng;
use std::mem;
use std::ptr;
use std::str;
use std::iter::repeat;

mod actor;
mod actor_manager;
mod spaceship;
mod spaceship_agent;
mod bullet;
mod asteroid;
mod kamikaze;
mod explosion;
mod token;
mod game;
mod background;
mod messages;

// Shader sources
// vertex shader
static VS_SRC: &'static str =
   "#version 150\n\
    in vec4 shape;\n\
    uniform vec3 position;\n\
    uniform vec2 camera;\n\
    uniform float z;\n\
    void main() {\n\
        float x = shape[0];\n\
        float y = shape[1];\n\
        float x_pos = position[0];\n\
        float y_pos = position[1];\n\
        float angle = position[2];\n\
        float c_x   = camera[0];\n\
        float c_y   = camera[1];\n\
        float xx = (x * cos(angle) + y * sin(angle)) + x_pos - c_x;\n\
        float yy = (-x * sin(angle) + y * cos(angle)) + y_pos - c_y;\n\
        gl_Position = vec4(xx, yy, 0.0, z);\n\
    }";

// fragment shader
static FS_SRC: &'static str =
   "#version 150\n\
    out vec4 out_color;\n\
    uniform vec3 color;\n\
    void main() {\n\
       out_color = vec4(color, 0.8);\n\
    }";

fn compile_shader(src: &str, ty: GLenum) -> GLuint {
    unsafe {
        let shader = gl::CreateShader(ty);

        // Attempt to compile the shader
        glfw::with_c_str(src, |ptr| gl::ShaderSource(shader, 1, &ptr, ptr::null()));
        gl::CompileShader(shader);

        // Get the compile status
        let mut status = gl::FALSE as GLint;
        gl::GetShaderiv(shader, gl::COMPILE_STATUS, &mut status);

        // Fail on error
        if status != (gl::TRUE as GLint) {
            let mut len = 0;
            gl::GetShaderiv(shader, gl::INFO_LOG_LENGTH, &mut len);
            let mut buf:Vec<u8> = repeat(0u8).take(len as usize -1).collect();  // subtract 1 to skip the trailing null character
            gl::GetShaderInfoLog(shader, len, ptr::null_mut(), buf.as_mut_ptr() as *mut GLchar);
            panic!("{:?}", str::from_utf8(&buf[..]));
        }
        shader
    }
}

fn link_program(vs: GLuint, fs: GLuint) -> GLuint {
    unsafe {
        let program = gl::CreateProgram();
        gl::AttachShader(program, vs);
        gl::AttachShader(program, fs);
        gl::LinkProgram(program);

        // Get the link status
        let mut status = gl::FALSE as GLint;
        gl::GetProgramiv(program, gl::LINK_STATUS, &mut status);

        // Fail on error
        if status != (gl::TRUE as GLint) {
            let mut len: GLint = 0;
            gl::GetProgramiv(program, gl::INFO_LOG_LENGTH, &mut len);
            let mut buf:Vec<u8> = repeat(0u8).take(len as usize - 1).collect();     // subtract 1 to skip the trailing null character
            gl::GetProgramInfoLog(program, len, ptr::null_mut(), buf.as_mut_ptr() as *mut GLchar);
            panic!("{:?}", str::from_utf8(&buf[..]));
        }
        program
    }
}

fn main() {
    let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap();

    // Choose a GL profile that is compatible with OS X 10.7+
    glfw.window_hint(glfw::WindowHint::ContextVersion(3, 2));
    glfw.window_hint(glfw::WindowHint::OpenGlForwardCompat(true));
    glfw.window_hint(glfw::WindowHint::OpenGlProfile(glfw::OpenGlProfileHint::Core));

    let (mut window, events) = glfw.create_window(800, 600, "rusteroids", glfw::WindowMode::Windowed)
        .expect("Failed to create GLFW window.");

    window.set_key_polling(true);

    // It is essential to make the context current before calling `gl::load_with`.
    window.make_current();

    // Load the OpenGL function pointers
//    gl::load_with(|s| glfw.get_proc_address(s));
    gl::load_with(|s| window.get_proc_address(s));

    // Create GLSL shaders
    let vs = compile_shader(VS_SRC, gl::VERTEX_SHADER);
    let fs = compile_shader(FS_SRC, gl::FRAGMENT_SHADER);
    let program = link_program(vs, fs);

    let mut vao = 0;
    let mut vbo = 0;
    let loc;
    let cam;
    let color;
    let z;

    unsafe {
        // Create Vertex Array Object
        gl::GenVertexArrays(1, &mut vao);
        gl::BindVertexArray(vao);

        // Create a Vertex Buffer Object and copy the vertex data to it
        gl::GenBuffers(1, &mut vbo);
        gl::BindBuffer(gl::ARRAY_BUFFER, vbo);

        // Use shader program
        gl::UseProgram(program);
        glfw::with_c_str("out_color", |ptr| gl::BindFragDataLocation(program, 0, ptr));

        // Specify the layout of the vertex data
        let pos_attr = glfw::with_c_str("shape",|ptr| gl::GetAttribLocation(program, ptr));
        gl::EnableVertexAttribArray(pos_attr as GLuint);
        gl::VertexAttribPointer(pos_attr as GLuint,     // must match the layout in the shader.
                                2,                      // size
                                gl::FLOAT,              // type
                                gl::FALSE as GLboolean, // normalized?
                                0,                      // stride
                                ptr::null());           // array buffer offset

        loc = glfw::with_c_str("position",|ptr| gl::GetUniformLocation(program, ptr));
        cam = glfw::with_c_str("camera",|ptr| gl::GetUniformLocation(program, ptr));
        color = glfw::with_c_str("color",|ptr| gl::GetUniformLocation(program, ptr));
        z = glfw::with_c_str("z",|ptr| gl::GetUniformLocation(program, ptr));
    }

    let output_on = false;
    let global_time = time::get_time();
    let mut t = time::get_time();
    let mut inner_t = time::get_time();
    let fr:i32 = 100000000 / 60;

    // camera position
    let mut cam_pos = (0.0, 0.0);
    let mut game = game::Game::new();

    let mut reset_countdown:usize = 3;
    let mut actors = actor_manager::ActorManager::new();
    actors.restart();

    let mut background = background::Background::new();
    background.generate(cam_pos.clone());

    while !window.should_close() {

        // Poll events
        glfw.poll_events();

        let mut messages = vec!();

        for event in glfw::flush_messages(&events) {
            handle_window_event(&mut window, event, &mut messages);
        }

        let t2 = time::get_time();

        //////////////////////////////////////
        //
        //     INNER LOOP
        //
        //////////////////////////////////////

        // switch to 1 frame a second
        //let fr = 1000000000;

        if t2.nsec - fr > t.nsec || t2.sec > t.sec {

            t = t2;

            calculate_collisions(&actors, &mut messages);

            let mut output_messages = vec!();
            actors.update(messages, &mut output_messages);

            cam_pos = get_camera(&actors, cam_pos.clone());

            draw_scene(&actors, loc, cam, color, z, cam_pos.clone(), &mut window, &background);

            actors.process_messages(&mut output_messages);
            game.process_messages(output_messages);

            generate_actors(&mut actors, cam_pos.clone(), game.max_players());
            background.cleanup(cam_pos.clone());
            background.offscreen_generate(cam_pos.clone());

            window.set_title(&format!("rusteroids - score [{}] - highscore [{}]", game.score, game.highscore)[..]);

            // every second
            let t3 = time::get_time();
            if t3.sec > inner_t.sec {
                inner_t = t3;

                if output_on {
                    println!("::  {}s  ::::::::::::::::::::::::::::::", t3.sec - global_time.sec);
                    for actor in actors.get().iter(){
                        if actor.id == 1 {
                            println!("> x  :: {}", actor.x);
                            println!("> y  :: {}", actor.y);
                        }

                        if actor.collision_type == actor::CollisionType::Collect {
                            println!("-- collect --");
                            println!("> x  :: {}", actor.x);
                            println!("> y  :: {}", actor.y);
                        }
                    }

                    println!(":: SCORE : {}", game.score);
                    println!(":: HIGHSCORE : {}", game.highscore);

                    println!(":::::::::::::::::::::::::::::::::::::::\n");
                }

                if check_restart(&actors){

                    if reset_countdown > 0 {
                        reset_countdown -= 1;
                    } else {
                        restart(&mut actors, &mut game);
                        reset_countdown = 3;
                    }
                }

            }

        }

        //////////////////////////////////////
        //
        // END OF INNER LOOP
        //
        ///////////////////////////////////////

        //window.set_should_close(true);

    }

    unsafe {
        // Cleanup
        gl::DeleteProgram(program);
        gl::DeleteShader(fs);
        gl::DeleteShader(vs);
        gl::DeleteBuffers(1, &vbo);
        gl::DeleteVertexArrays(1, &vao);
    }
}

fn generate_actors(actors: &mut actor_manager::ActorManager, (cx, cy): (f32, f32), max_actors: usize){

    let min_x = cx as i32 - 4000;
    let max_x = cx as i32 + 4000;
    let min_y = cy as i32 - 4000;
    let max_y = cy as i32 + 4000;
    let min_distance = 2600 * 2600; // square instead of sqrt on distance

    while actors.get().len() < max_actors {
        let x = rand::thread_rng().gen_range(min_x, max_x);
        let y = rand::thread_rng().gen_range(min_y, max_y);

        let x_dis = x - cx as i32;
        let y_dis = y - cy as i32;
        let distance = x_dis * x_dis + y_dis * y_dis;

        if distance > min_distance {
            let rand = rand::thread_rng().gen_range(0u32, 100);
            match rand {
                0...75  => actors.new_asteroid(x, y),
                76...82 => actors.new_spaceship(x, y),
                83...85 => actors.new_kamikaze(x, y, (cx, cy)),
                _      => ()
            }
        }
    }
}

fn check_restart(actors: &actor_manager::ActorManager) -> bool{
    let mut player_exists = false;
    for actor in actors.get().iter(){
        if actor.id == 1 {
            player_exists = true;
            break;
        }
    }
    !player_exists
}

fn restart(actors: &mut actor_manager::ActorManager, game: &mut game::Game){
    game.restart();
    actors.restart();
}

fn calculate_collisions(actor_manager: &actor_manager::ActorManager, messages: &mut Vec<(i32, messages::PlayerInstructions)>){

    let actors = actor_manager.get();

    for a1 in actors.iter(){

        // todo - if we count the top iter(), we can slice this one
        //      - to only match remaining actors
        //      - would then need to push a2.id messages on collision

        let actors2 = actor_manager.get();

        for a2 in actors2.iter(){

            if     a1.id    == 0
                || a2.id    == 0
                || a1.id    == a2.id
                || a1.id    == a2.parent
                || a2.id    == a1.parent
                || a1.collision_type == actor::CollisionType::Ignore
                || a2.collision_type == actor::CollisionType::Ignore {
                continue;
            }

            if (a1.x - a2.x).abs() as usize > 1000 || (a1.y - a2.y).abs() as usize > 1000 {
                continue;
            }

            if a1.x + a1.width > a2.x - a2.width && a1.x - a1.width < a2.x + a2.width
              && a1.y + a1.height > a2.y - a2.height && a1.y - a1.height < a2.y + a2.height {

                // within bounding box - pixel perfect that shit
                // ...

                match a2.collision_type{
                    actor::CollisionType::Collide => messages.push((a1.id,
                        messages::PlayerInstructions::Collide)),
                    actor::CollisionType::Collect => messages.push((a1.id,
                    messages::PlayerInstructions::Collect)),
                    _              => ()
                }

            }
        }
    }

}

fn handle_window_event(window: &mut glfw::Window, (_/*time*/, event): (f64, glfw::WindowEvent), messages : &mut Vec<(i32, messages::PlayerInstructions)>) {
    match event {
        // glfw::PosEvent(x, y)                => window.set_title(format!("Time: {}, Window pos: ({}, {})", time, x, y).as_slice()),
        // glfw::SizeEvent(w, h)               => window.set_title(format!("Time: {}, Window size: ({}, {})", time, w, h).as_slice()),
        // glfw::CloseEvent                    => println!("Time: {}, Window close requested.", time),
        // glfw::RefreshEvent                  => println!("Time: {}, Window refresh callback triggered.", time),
        // glfw::FocusEvent(true)              => println!("Time: {}, Window focus gained.", time),
        // glfw::FocusEvent(false)             => println!("Time: {}, Window focus lost.", time),
        // glfw::IconifyEvent(true)            => println!("Time: {}, Window was minimised", time),
        // glfw::IconifyEvent(false)           => println!("Time: {}, Window was maximised.", time),
        // glfw::FramebufferSizeEvent(w, h)    => println!("Time: {}, Framebuffer size: ({}, {})", time, w, h),
        // glfw::CharEvent(character)          => println!("Time: {}, Character: {}", time, character),
        // glfw::MouseButtonEvent(btn, action, mods) => println!("Time: {}, Button: {}, Action: {}, Modifiers: [{}]", time, glfw::DebugAliases(btn), action, mods),
        // glfw::CursorPosEvent(xpos, ypos)    => window.set_title(format!("Time: {}, Cursor position: ({}, {})", time, xpos, ypos).as_slice()),
        // glfw::CursorEnterEvent(true)        => println!("Time: {}, Cursor entered window.", time),
        // glfw::CursorEnterEvent(false)       => println!("Time: {}, Cursor left window.", time),
        // glfw::ScrollEvent(x, y)             => window.set_title(format!("Time: {}, Scroll offset: ({}, {})", time, x, y).as_slice()),
        glfw::WindowEvent::Key(key, /* scancode */ _, action, /* mods */ _ ) => {
            // println!("Time: {}, Key: {}, ScanCode: {}, Action: {}, Modifiers: [{}]", time, key, scancode, action, mods);
            match (key, action) {
                (glfw::Key::Escape, glfw::Action::Press) => window.set_should_close(true),
                (glfw::Key::Up, glfw::Action::Press) => messages.push((1, messages::PlayerInstructions::BeginIncreaseThrottle)),
                (glfw::Key::Down, glfw::Action::Press) => messages.push((1, messages::PlayerInstructions::BeginDecreaseThrottle)),
                (glfw::Key::Up, glfw::Action::Release) => messages.push((1, messages::PlayerInstructions::StopIncreaseThrottle)),
                (glfw::Key::Down, glfw::Action::Release) => messages.push((1, messages::PlayerInstructions::StopDecreaseThrottle)),
                (glfw::Key::Right, glfw::Action::Press) => messages.push((1, messages::PlayerInstructions::BeginRotateRight)),
                (glfw::Key::Left, glfw::Action::Press) => messages.push((1, messages::PlayerInstructions::BeginRotateLeft)),
                (glfw::Key::Right, glfw::Action::Release) => messages.push((1, messages::PlayerInstructions::StopRotateRight)),
                (glfw::Key::Left, glfw::Action::Release) => messages.push((1, messages::PlayerInstructions::StopRotateLeft)),
                (glfw::Key::Space, glfw::Action::Release) => messages.push((1, messages::PlayerInstructions::Fire)),
                (glfw::Key::LeftShift, glfw::Action::Press) => messages.push((1, messages::PlayerInstructions::ShieldUp)),
                (glfw::Key::LeftShift, glfw::Action::Release) => messages.push((1, messages::PlayerInstructions::ShieldDown)),
                // (glfw::KeyR, glfw::Press) => {
                //     // Resize should cause the window to "refresh"
                //     let (window_width, window_height) = window.get_size();
                //     window.set_size(window_width + 1, window_height);
                //     window.set_size(window_width, window_height);
                // }
                _ => {}
            }
        },

        _ => ()
    }
}

fn get_camera(actor_manager:&actor_manager::ActorManager, (cx, cy):(f32,f32)) -> (f32, f32){
    let actors = actor_manager.get();
    for v in actors.iter() {
        if v.id == 1 {
            return (v.x, v.y);
        }
    }

    (cx, cy)
}

fn draw_scene(actor_manager:&actor_manager::ActorManager,
        loc:i32,
        cam:i32,
        color:i32,
        z: i32,
        (cx, cy):(f32, f32),
        window: &mut glfw::Window,
        background: &background::Background){

    let actors = actor_manager.get();
    let bg = background.get();

    unsafe {
        gl::ClearColor(0.1, 0.1, 0.2, 1.0);
        gl::Clear(gl::COLOR_BUFFER_BIT);
    }
    for st in bg.iter(){
        draw(&st.shape, loc, cam, color, z, st.x, st.y, 0.0, cx, cy, &st.color, 1.9);
    }

    let mut meter = 0.0;
    for v in actors.iter() {
        if v.id == 1 {
            meter = v.meter;
        }

        draw_actor(v, loc, cam, color, z, cx, cy);
    }

    let collectables = actor_manager.get_collectables();

    draw_hud(loc, cam, color, z, (cx, cy), collectables, meter);

    window.swap_buffers();
}

fn draw_actor(p: &actor::ActorView, loc:i32, cam:i32, color:i32, z:i32, cx: f32, cy: f32){

    draw(&p.shape, loc, cam, color, z, p.x, p.y, p.rotation, cx, cy, &p.color, 1.0);
    if p.show_secondary {
        match (p.secondary_shape.clone(), p.secondary_color.clone()) {
            (Some(shape), Some(second_color)) => draw(&shape, loc, cam, color, z, p.x, p.y, p.rotation, cx, cy, &second_color, 1.0),
            _                        => ()
        }

    }
}

fn draw_hud(loc:i32, cam:i32, color:i32, z:i32, (cx, cy) : (f32, f32), collectables : Vec<actor::ActorView>, meter: f32){
    let v = vec!(
        0.0, 0.0,
        0.04, -0.04,
        0.0, -0.02,

        0.0, -0.02,
        -0.04, -0.04,
        0.0, 0.0
    );

    let col = vec!(
        0.9, 0.9, 0.4
    );

    for token in collectables.iter(){
        let dx = token.x - cx;
        let dy = token.y - cy;
        let rotation = dx.atan2(dy);

        let player_distance = (dx * dx + dy * dy).sqrt() as i32;

        let dx = rotation.sin();
        let dy = rotation.cos();

        let mut distance = 1800;

        while distance > player_distance - 100 {
            distance -= 5;
        }

        let x = dx * (distance as f32);
        let y = dy * (distance as f32);

        draw(&v, loc, cam, color, z, x, y, rotation, 0.0, 0.0, &col, 1.0);
    }

    let m = meter/5.0;
    let h = 0.02;
    let v = vec!(
        0.0, 0.0,
        0.0, -h,
        m, 0.0,

        m, 0.0,
        m, -h,
        0.0, -h
    );

    let col = vec!(0.4, 0.6, 0.2);

    draw(&v, loc, cam, color, z, 1500.0, -1850.0, 0.0, 0.0, 0.0, &col, 1.0);

}

fn draw(v: &Vec<f32>, loc:i32, cam:i32, color:i32, z:i32, x:f32, y:f32, rotation:f32, cx:f32, cy:f32, col:&Vec<f32>, z_val:f32){
    unsafe{

        gl::BufferData(gl::ARRAY_BUFFER,
               (v.len() * mem::size_of::<GLfloat>()) as GLsizeiptr,
               mem::transmute(&v[0]),
               gl::DYNAMIC_DRAW); // STATIC | DYNAMIC | STREAM

        gl::Uniform3f(loc, x / 2000.0, y / 2000.0, rotation);
        gl::Uniform2f(cam, cx / 2000.0, cy / 2000.0);
        gl::Uniform3f(color, col[0], col[1], col[2]);
        gl::Uniform1f(z, z_val);

        // LINE_LOOP / TRIANGLES
        gl::DrawArrays(gl::TRIANGLES, 0, v.len() as i32 / 2);
    }
}


text:
class User < ActiveRecord::Base

  acts_as_token_authenticatable

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  before_save :ensure_authentication_token

  has_and_belongs_to_many :entries

  def add_entry_to_bookmarks!(user, entry)
    @user.entries << @entry
  end

  def remove_entry_from_bookmarks!(user, entry)
    @user.entries.destroy(@entry.id)
  end

end


text:
package cn.sh.sis.assistand.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Properties;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

/**
 * 本地存储数据管理类
 *
 * @author zhoujian
 *
 */
public class LocalFileHepler {
	/** sdk */
	public static File sdk = Environment.getExternalStorageDirectory();

	/**
	 * 本地保存数据
	 *
	 * @param context
	 * @param file
	 *            路径
	 * @param object
	 *            对象
	 * @return
	 */
	public static String saveDataToLocate(Context context, String file,
			Object object) {
		String res = null;
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;
		try {
			fos = context.openFileOutput(file, Activity.MODE_PRIVATE);
			oos = new ObjectOutputStream(fos);
			oos.writeObject(object);
			System.out.println(fos + "fos");
			System.out.println(oos + "oos");
		} catch (FileNotFoundException e) {
			res = "没有找到文件";
			e.printStackTrace();
		} catch (IOException e) {
			res = "没有数据";
			e.printStackTrace();
		} finally {
			try {
				oos.close();
				fos.close();
				res = "保存成功";
			} catch (IOException e) {
				res = "没有数据";
				e.printStackTrace();
			}
		}
		return res;
	}

	/**
	 * 本地读取数据
	 *
	 * @param context
	 * @param file
	 *            路径
	 * @return
	 */
	public static Object loadDataFromLocate(Context context, String file) {
		Object obj = null;
		FileInputStream fis = null;
		ObjectInputStream ois = null;
		try {
			fis = context.openFileInput(file);
			ois = new ObjectInputStream(fis);
			obj = ois.readObject();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				ois.close();
				fis.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return obj;
	}

	/**
	 * 清除缓存数据
	 *
	 * @param context
	 * @param file
	 *            路径
	 */
	public static void cleanDateFromLocate(Context context, String file) {
		context.deleteFile(file);
	}

	/**
	 * 存数据
	 *
	 * @param context
	 * @param file
	 * @param key
	 * @return
	 */
	public static Object load(Context context, String file, String key) {
		/* 构建Properties对对象 */
		Properties properties = new Properties();
		try {
			/* 开发文件 */
			FileInputStream stream = context.openFileInput(file);
			/* 读取文件内容 */
			properties.load(stream);
		} catch (FileNotFoundException e) {
			return null;
		} catch (IOException e) {
			return null;
		}
		/* 取得数据 */
		return properties.get(key);
	}

	/**
	 * 取数据
	 *
	 * @param context
	 * @param file
	 * @param key
	 * @param value
	 * @return
	 */

	@SuppressLint("WorldWriteableFiles")
	public static boolean save(Context context, String file, String key,
			String value) {
		Properties properties = new Properties();

		/* 将数据打包成Properties */
		properties.put(key, value);
		try {
			FileOutputStream stream = context.openFileOutput(file,
					Context.MODE_APPEND);

			/* 将打包好的数据写入文件中 */
			properties.store(stream, "");
		} catch (FileNotFoundException e) {
			return false;
		} catch (IOException e) {
			return false;
		}

		return true;
	}

	/**
	 * 本地保存数据
	 *
	 * @param context
	 * @param file
	 *            路径
	 * @param object
	 *            对象
	 * @return
	 */
	public static String saveDataToLocateBitmap(Context context, String file,
			Bitmap bm) {
		String res = null;
		FileOutputStream fos = null;
		try {
			fos = context.openFileOutput(file, Activity.MODE_PRIVATE);
			fos.write(BitmapToBytes(bm));
			System.out.println(fos + "fos");
		} catch (FileNotFoundException e) {
			res = "没有找到文件";
			e.printStackTrace();
		} catch (IOException e) {
			res = "没有数据";
			e.printStackTrace();
		} finally {
			try {
				fos.close();
				res = "保存成功";
			} catch (IOException e) {
				res = "没有数据";
				e.printStackTrace();
			}
		}
		return res;
	}

	/**
	 * 本地读取数据
	 *
	 * @param context
	 * @param file
	 *            路径
	 * @return
	 */
	public static Bitmap loadDataFromLocateBitmap(Context context, String file) {
		Bitmap obj = null;
		FileInputStream fis = null;
		try {
			fis = context.openFileInput(file);
			obj = getPicFromBytes(readStream(fis), null);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				fis.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return obj;
	}

	/**
	 * @param 将字节数组转换为Bitmap对象
	 * @param bytes
	 *            字节数组
	 * @param opts
	 *            变换参数
	 * @return Bitmap Bitmap对象
	 */
	public static Bitmap getPicFromBytes(byte[] bytes,
			BitmapFactory.Options opts) {
		if (bytes != null)
			if (opts != null)
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length,
						opts);
			else
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
		return null;
	}

	/**
	 * 把Bitmap转Byte
	 */
	public static byte[] BitmapToBytes(Bitmap bm) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
		return baos.toByteArray();
	}

	/**
	 * @param 将图片内容解析成字节数组
	 * @param inStream
	 *            输入流
	 * @return 字节数组
	 */
	private static byte[] readStream(InputStream inStream) throws Exception {
		byte[] buffer = new byte[1024];
		int len = -1;
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		byte[] data = outStream.toByteArray();
		outStream.close();
		inStream.close();
		return data;
	}
}


text:
package main

import (
	"k8s.io/kops/upup/tools/generators/pkg/codegen"
)

func main() {
	generator := &FitaskGenerator{}
	codegen.RunGenerator("fitask", generator)
}


text:
package org.delta.spring.holder;

import org.delta.security.IUser;
import org.delta.security.SessionUtil;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Servlet 上下文数据获取
 *

 * User: Jeff
 *

 * Date: 12-11-16 上午9:23
 */
public class AppContextHolder {
    private Logger log = Logger.getLogger(AppContextHolder.class);

    public static ApplicationContext getApplicationContext() {
        ServletContext context = getServletContext();
        if (context == null) {

        }
        return WebApplicationContextUtils.getRequiredWebApplicationContext(context);
    }

    public static ServletContext getServletContext() {
        //TODO 通过 seesion 获取 ServletContext 不合理,很有可能 seesion 是空的
        HttpSession session = getSession();
        if (session != null) {
            return session.getServletContext();
        }
        return null;
    }

    public static HttpSession getSession() {
        HttpServletRequest request = getServletRequest();
        if (request != null) {
            return request.getSession();
        }
        return null;
    }

    public static HttpServletRequest getServletRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        if (requestAttributes instanceof ServletRequestAttributes) {
            return ((ServletRequestAttributes) requestAttributes).getRequest();
        }

        //throw new RuntimeException(" 通过 requestAttributes 无法获取 HttpServletRequest , 必须设置  ");
        return null;
    }

    public static IUser getLoginUser() {
        HttpSession session = AppContextHolder.getSession();
        if (session != null) {
            Object user = session.getAttribute(SessionUtil.USER_KEY);
            if (user != null && user instanceof IUser) {
                return (IUser) user;
            }
        }
        return null;
    }
}