text:
<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Form_model extends CI_Model
{

    public $table = 'form';
    public $id = 'id_form';
    public $order = 'DESC';

    function __construct()
    {
        parent::__construct();
    }

    // get all
    function get_all()
    {
        $this->db->order_by($this->id, $this->order);
        return $this->db->get($this->table)->result();
    }

    // get total rows
    function total_rows($q = NULL) {
        $this->db->like('id_form', $q);
	$this->db->or_like('id_user', $q);
	$this->db->or_like('date', $q);
	$this->db->or_like('information', $q);
	$this->db->or_like('information_kabid', $q);
	$this->db->or_like('information_TU', $q);
	$this->db->or_like('information_PPK', $q);
	$this->db->or_like('date_needs', $q);
	$this->db->or_like('that', $q);
	$this->db->or_like('read_status_Ketua', $q);
	$this->db->or_like('read_status_TU', $q);
	$this->db->or_like('read_status_PPK', $q);
	$this->db->or_like('status_submit', $q);
	$this->db->or_like('id_budget', $q);
	$this->db->or_like('name_activity', $q);
	$this->db->from($this->table);
        return $this->db->count_all_results();
    }

    // get data with limit and search
    function get_limit_data($limit, $start = 0, $q = NULL) {
        $this->db->order_by($this->id, $this->order);
        $this->db->like('id_form', $q);
	$this->db->or_like('id_user', $q);
	$this->db->or_like('date', $q);
	$this->db->or_like('information', $q);
	$this->db->or_like('information_kabid', $q);
	$this->db->or_like('information_TU', $q);
	$this->db->or_like('information_PPK', $q);
	$this->db->or_like('date_needs', $q);
	$this->db->or_like('that', $q);
	$this->db->or_like('read_status_Ketua', $q);
	$this->db->or_like('read_status_TU', $q);
	$this->db->or_like('read_status_PPK', $q);
	$this->db->or_like('status_submit', $q);
	$this->db->or_like('id_budget', $q);
	$this->db->or_like('name_activity', $q);
	$this->db->limit($limit, $start);
        return $this->db->get($this->table)->result();
    }

    // insert data
    function insert($data)
    {
        $this->db->insert($this->table, $data);
    }

    // update data
    function update($id, $data)
    {
        $this->db->where($this->id, $id);
        $this->db->update($this->table, $data);
    }

    // delete data
    function delete($id)
    {
        $this->db->where($this->id, $id);
        $this->db->delete($this->table);
    }

     function get_all_detail()
    {
        return $this->db->query('select * from user_akun a, form b, source_budget c where a.id_user = b.id_user and c.id_budget = b.id_budget ORDER BY `date` DESC')->result();
    }

    function get_all_form_detail()
    {
        return $this->db->query('select * from user_akun a, form b, tracking c, status_tracking d where a.id_user = b.id_user and c.id_form = b.id_form and c.id_status_tracking = d.id_status_tracking and b.status_submit=1 ORDER BY `date` DESC')->result();
    }

    function get_all_form_detail_like($like)
    {
        return $this->db->query('select * from user_akun a, form b, tracking c, status_tracking d where a.id_user = b.id_user and c.id_form = b.id_form and c.id_status_tracking = d.id_status_tracking and b.status_submit=1 and (b.date like "%'.$like.'%" or a.name like "%'.$like.'%" or b.name_activity like "%'.$like.'%") ORDER BY `date` DESC')->result();
    }

    function get_all_detail_like($like)
    {
        return $this->db->query('select * from user_akun a, form b where a.id_user = b.id_user and (b.date like "%'.$like.'%" or a.name like "%'.$like.'%" or b.name_activity like "%'.$like.'%") ORDER BY `date` DESC')->result();
    }

    // get data by id
    function get_by_id($id)
    {
        return $this->db->query('select * from user_akun a, form b, tracking c, status_tracking d, source_budget e where a.id_user = b.id_user and c.id_form = b.id_form and c.id_status_tracking = d.id_status_tracking and b.status_submit=1 and b.id_budget=e.id_budget and b.id_form ='.$id)->row();
    }

    function get_by_id_new($id)
    {
        $this->db->where($this->id, $id);
        return $this->db->get($this->table)->row();
    }

    //get by id user
    function get_by_user($id)
    {
        return $this->db->query('select * from user_akun a, form b, tracking c, status_tracking d where a.id_user = b.id_user and c.id_form = b.id_form and c.id_status_tracking = d.id_status_tracking and b.status_submit=1 and b.id_user ='.$id.' ORDER BY `date` DESC')->result();
    }

    function get_by_user_like($id,$like)
    {
        return $this->db->query('select * from user_akun a, form b, tracking c, status_tracking d where a.id_user = b.id_user and c.id_form = b.id_form and c.id_status_tracking = d.id_status_tracking and b.status_submit=1 and b.id_user ='.$id.' and (b.date like "%'.$like.'%" or a.name like "%'.$like.'%" or b.name_activity like "%'.$like.'%") ORDER BY `date` DESC')->result();
    }

    function get_by_user_div($id)
    {
        return $this->db->query('SELECT * FROM `form` JOIN `user_akun` JOIN `tracking` JOIN `status_tracking` ON `form`.`id_user` = `user_akun`.`id_user` and `tracking`.`id_form` = `form`.`id_form` and `tracking`.`id_status_tracking` = `status_tracking`.`id_status_tracking` WHERE `form`.`status_submit`=1 and `user_akun`.`id_division` ='.$id.' ORDER BY `read_status_Ketua` ASC, `status_tracking`.`id_status_tracking` DESC,  `date` DESC')->result();
    }

    function get_by_user_div_like($id,$like)
    {
        return $this->db->query('SELECT * FROM `form` JOIN `user_akun` JOIN `tracking` JOIN `status_tracking` ON `form`.`id_user` = `user_akun`.`id_user` and `tracking`.`id_form` = `form`.`id_form` and `tracking`.`id_status_tracking` = `status_tracking`.`id_status_tracking` WHERE `form`.`status_submit`=1 and `user_akun`.`id_division` ='.$id.' and (form.date like "%'.$like.'%" or user_akun.name like "%'.$like.'%" or form.name_activity like "%'.$like.'%") ORDER BY `read_status_Ketua` ASC, `date` DESC')->result();
    }

    function get_by_user_acc_TU()
    {
        return $this->db->query('select * from user_akun a, form b, tracking c, status_tracking d, tracking_history e where a.id_user = b.id_user and c.id_form = b.id_form and c.id_status_tracking = d.id_status_tracking and b.status_submit=1 and e.id_tracking=c.id_tracking and (c.id_status_tracking =1 or c.id_status_tracking =11 or c.id_status_tracking =12 or c.id_status_tracking =2 or c.id_status_tracking =3 or c.id_status_tracking =13 or c.id_status_tracking =6
            or c.id_status_tracking =5 or c.id_status_tracking =13 or c.id_status_tracking =14) GROUP BY `b`.`id_form` ORDER BY `read_status_TU` ASC, `date` DESC')->result();
    }

    function get_by_user_acc_TU_like($like)
    {
        return $this->db->query('select * from user_akun a, form b, tracking c, status_tracking d, tracking_history e where a.id_user = b.id_user and c.id_form = b.id_form and c.id_status_tracking = d.id_status_tracking and b.status_submit=1 and e.id_tracking=c.id_tracking and (c.id_status_tracking =1 or c.id_status_tracking =11 or c.id_status_tracking =12 or c.id_status_tracking =2 or c.id_status_tracking =3 or c.id_status_tracking =13 or c.id_status_tracking =6
            or c.id_status_tracking =5 or c.id_status_tracking =13 or c.id_status_tracking =14) and (b.date like "%'.$like.'%" or a.name like "%'.$like.'%" or b.name_activity like "%'.$like.'%") GROUP BY `b`.`id_form` ORDER BY `read_status_TU` ASC, `date` DESC')->result();
    }

    function get_by_user_acc_PPKRM()
    {
        return $this->db->query('select * from user_akun a, form b, tracking c, status_tracking d, tracking_history e where a.id_user = b.id_user and c.id_form = b.id_form and c.id_status_tracking = d.id_status_tracking and e.id_tracking=c.id_tracking and b.status_submit=1 and b.id_budget=2 and (c.id_status_tracking =12 or c.id_status_tracking =2 or c.id_status_tracking =3 or c.id_status_tracking =14 or c.id_status_tracking =6
            or c.id_status_tracking =5) GROUP BY `b`.`id_form` ORDER BY `read_status_PPK` ASC, `date` DESC')->result();
    }

    function get_by_user_acc_PPKRM_like($like)
    {
        return $this->db->query('select * from user_akun a, form b, tracking c, status_tracking d, tracking_history e where a.id_user = b.id_user and c.id_form = b.id_form and c.id_status_tracking = d.id_status_tracking and e.id_tracking=c.id_tracking and b.status_submit=1 and b.id_budget=2 and (c.id_status_tracking =12 or c.id_status_tracking =2 or c.id_status_tracking =3 or c.id_status_tracking =14 or c.id_status_tracking =6
            or c.id_status_tracking =5) and (b.date like "%'.$like.'%" or a.name like "%'.$like.'%" or b.name_activity like "%'.$like.'%") GROUP BY `b`.`id_form` ORDER BY `read_status_PPK` ASC, `date` DESC')->result();
    }

    function get_by_user_acc_PPKBLU()
    {
        return $this->db->query('select * from user_akun a, form b, tracking c, status_tracking d, tracking_history e where a.id_user = b.id_user and c.id_form = b.id_form and c.id_status_tracking = d.id_status_tracking and e.id_tracking=c.id_tracking and b.status_submit=1 and b.id_budget=1 and (c.id_status_tracking =12 or c.id_status_tracking =2 or c.id_status_tracking =3 or c.id_status_tracking =14 or c.id_status_tracking =6
            or c.id_status_tracking =5) GROUP BY `b`.`id_form` ORDER BY `read_status_PPK` ASC, `date` DESC')->result();
    }

    function get_by_user_acc_PPKBLU_like($like)
    {
        return $this->db->query('select * from user_akun a, form b, tracking c, status_tracking d, tracking_history e where a.id_user = b.id_user and c.id_form = b.id_form and c.id_status_tracking = d.id_status_tracking and e.id_tracking=c.id_tracking and b.status_submit=1 and b.id_budget=1 and (c.id_status_tracking =12 or c.id_status_tracking =2 or c.id_status_tracking =3 or c.id_status_tracking =14 or c.id_status_tracking =6
            or c.id_status_tracking =5) and (b.date like "%'.$like.'%" or a.name like "%'.$like.'%" or b.name_activity like "%'.$like.'%") GROUP BY `b`.`id_form` ORDER BY `read_status_PPK` ASC, `date` DESC')->result();
    }

     function get_by_user_pengadaan()
    {
        return $this->db->query('select * from user_akun a, form b, tracking c, status_tracking d, tracking_history e where a.id_user = b.id_user and c.id_form = b.id_form and c.id_status_tracking = d.id_status_tracking and e.id_tracking=c.id_tracking and b.status_submit=1 and (c.id_status_tracking =3 or c.id_status_tracking =5 or c.id_status_tracking =6) GROUP BY `b`.`id_form` ORDER BY `read_status_Pengadaan` ASC, c.id_tracking DESC,`date` DESC')->result();
    }

    function get_by_user_pengadaan_like($like)
    {
        return $this->db->query('select * from user_akun a, form b, tracking c, status_tracking d, tracking_history e where a.id_user = b.id_user and c.id_form = b.id_form and c.id_status_tracking = d.id_status_tracking and e.id_tracking=c.id_tracking and b.status_submit=1 and (c.id_status_tracking =3 or c.id_status_tracking =5 or c.id_status_tracking =6) and (b.date like "%'.$like.'%" or a.name like "%'.$like.'%" or b.name_activity like "%'.$like.'%") GROUP BY `b`.`id_form` ORDER BY `date` DESC')->result();
    }

    //get by id user
    function get_by_user_now($id)
    {
        $this->db->where('id_user', $id);
        $this->db->order_by('id_form','desc');
        $this->db->limit(1);
        return $this->db->get($this->table)->row();
    }

    function delete_useless_form()
    {
        $this->db->where('status_submit', "0");
        $temp = $this->db->get($this->table)->result();
        $this->delete_child($temp);

        $this->db->where('status_submit', "0");
        $this->db->delete($this->table);
    }

    function delete_child($temp){
        foreach ($temp as $x) {
            $this->db->where('id_form', $x->id_form);
            $this->db->delete('form_content');
        }
    }

}


text:
var Mks50Patch = require('./mks50patch.js')
var assert = require('assert')

var patch = new Mks50Patch()

// Get parameter as a sanity check

assert.equal(patch.get('VCF FREQ').label, 'VCF Cutoff')

redpajama_set_name: RedPajamaGithub


text:
/*
 * seed.cc
 *
 *  Created on: Mar 3, 2017
 *      Author: isovic
 */

#include "seed.h"

namespace is {

Seed::Seed() {
  // TODO Auto-generated constructor stub

}

Seed::~Seed() {
  // TODO Auto-generated destructor stub
}

} /* namespace is */


text:
<?php

namespace Thapp\IocConf;

use Illuminate\Container\Container;

/**
 * Class: IocResolver
 *
 * @implements ResolverInterface
 *
 * @package
 * @version
 * @author Thomas Appel <mail@thomas-appel.com>
 * @license MIT
 */
class IocResolver implements ResolverInterface
{

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

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

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

    /**
     * setters
     *
     * @var array
     */
    protected $setters;

    /**
     * arguments
     *
     * @var array
     */
    protected $arguments;

    /**
     * __construct
     *
     * @param mixed $
     * @access public
     */
    public function __construct(\SimpleXMLElement $entity, $attributes)
    {
        extract($attributes);

        $this->id    = $id;
        $this->class = $class;
        $this->scope = $scope;

        $this->setters   = $this->getEntitySetters($entity);
        $this->arguments = $this->getEntityArguments($entity);
    }

    /**
     * get the arguments array from an entity node
     *
     * @param \SimpleXMLElement $entity the entity node
     * @access protected
     * @return array
     */
    protected function getEntityArguments(\Thapp\XmlConf\SimpleXmlConfigInterface $entity)
    {
        $arguments  = array();

        foreach ($entity->argument as $argument) {
            $arguments[] = array($argument->get('id'), $argument->get('class'));
        }

        return $arguments;
    }

    /**
     * get the setters array from an entity node
     *
     * @param \SimpleXMLElement $entity the entity node
     * @access protected
     * @return array
     */
    protected function getEntitySetters(\Thapp\XmlConf\SimpleXmlConfigInterface $entity)
    {
        $setters = array();

        foreach ($entity->call as $call) {
            $arguments  = $this->getEntityArguments($call);
            $setters[$call->get('method')] = $arguments;
        }

        return $setters;
    }

    /**
     * resolve the callback data array
     *
     * @access public
     * @return array
     */
    public function resolve()
    {
        return array(
            'id'       => $this->id,
            'class'    => $this->class,
            'scope'    => $this->scope,
            'resolver' => $this
        );
    }

    /**
     * make
     *
     * @access public
     * @return mixed
     */
    public function make()
    {
        $me = $this;

        return function (Container $app) use ($me)
        {
            return $this->runFactory($app);
        };
    }

    /**
     * execute the classfactory callback
     *
     * @param \Illuminate\Container\Container $app the IoC container
     * @access protected
     * @return mixed normaly returns an object instance
     */
    protected function runFactory(Container $app)
    {
        $args = array();

        if (count($this->arguments) > 0) {
            foreach ($this->arguments as $argument) {
                $args[] = $this->resolveArgument($app, $argument[0], $argument[1]);
            }
        }

        // if no id is given, we cannot resolve the instance directly
        // from the container. Instead, we create a new Instance.
        if (0 === strlen($this->id)) {
            $instance = new \ReflectionClass($this->class);
            $instance = count($args) ? $instance->newInstanceArgs($args) : $instance->newInstance();
        } else {
            $instance = $app->make($this->class, count($args) ? $args : null);
        }

        if (count($this->setters) > 0) {
            foreach ($this->setters as $method => $arguments) {
                $args[] = $this->resolveSetter($app, $instance, $method, $arguments);
            }
        }
        return $instance;
    }

    /**
     * resolve required arguments
     *
     * @param \Illuminate\Container\Container $app the IoC container
     * @param string $id bound id
     * @param string $class classname
     * @access protected
     * @return mixed
     */
    protected function resolveArgument(Container $app, $id, $class)
    {
        return $app->make((0 === strlen($id) || $id === $class) ? $class : $id);
    }

    /**
     * resolve required setters
     *
     * @param \Illuminate\Container\Container $app the IoC container
     * @param object $instance the class instance
     * @param array $arguments setter arguments
     * @param string $method setter mathod name
     * @access protected
     * @return void
     */
    protected function resolveSetter(Container $app, $instance, $method, $arguments)
    {
        list($id, $class) = current($arguments);

        $result = $this->resolveArgument($app, $id, $class);
        return call_user_func_array(array($instance, $method), array($result));
    }

}


text:
var adam = {
	name: "Adam Sandler",
	age: 47,
	favourite_movie: "The Wedding Singer",
	quote: "That's your home! Are you too good for your home?!"
}
	console.log("Client: " + adam.name + " He is " + adam.age + " years old. His favourite quote is " + adam.quote + ". Have you seen my favourite movie: " +adam.favourite_movie);

var kristen = {
	name: "Kristen Bell",
	age: 33,
	quote: "Do you wanna build a snowman?",
	showAge: function(){
		console.log(this.age);
	}
}

var jim = {
	name: "Jim Carrey",
	age: 57,
	children: adam,
	quote: "...So you're telling me there's a chance? YEAH!",
	showQuote: function(){
		console.log(this.quote);
	}
}

jim.showQuote()

function Client(name, age, quote) {
	this.name = name,
	this.age = age,
	this.quote = quote
 }

var shooterMcGavin = new Client("Shooter McGavin", 48, "Just stay out of my way... or you'll pay. Listen to what I say.");
shooterMcGavin.constructor === Client;
shooterMcGavin.age === 48;
shooterMcGavin.quote === "Just stay out of my way... or you'll pay. Listen to what I say.";

// //Just like your clients, JavaScript Objects are capable of some awesome stuff!
// Not only can they hold simple information like strings and integers,
// but properties can also store functions! Pick any of the client objects you created,
// and assign it a property called showQuote that stores a function that will display
// that client's quote. Test your code!


text:
#ifndef __CS_143__FlowEvent__
#define __CS_143__FlowEvent__

class Host;

#include "../EventGenerators/EventGenerator.h"
#include "Event.h"
#include "Packet.h"
#include "../EventGenerators/Flow.h"
#include <string>

class FlowEvent : public Event {
public:
    FlowEvent(std::shared_ptr<Flow> flowobj,
              std::string dest,
              std::string src,
              float ts);

    int data_size;
    std::shared_ptr<Flow> floww;

    virtual std::string printEvent() override;
    virtual std::string getType() override;
};

#endif /* defined(__CS_143__FlowEvent__) */


text:
def PNG_CheckText(text, can_be_empty = False, max_size = None, \
    no_extra_spaces = True, utf_8 = False, newlines = False, \
    is_keyword = False):
  string = text.value;
  if not can_be_empty and len(string) == 0:
    name.warnings.append('expected at least one character');
  elif max_size is not None and len(string) > max_size:
    name.warnings.append('expected at most 79 characters');
  illegal_charcodes = set();
  if utf_8:
    try:
      string = string.decode('utf-8', 'strict');
    except Exception, e:
      text.warnings.append('utf-8 decoding error: %s' % e);
      string = '';
  for char in string:
    charcode = ord(char);
    if not newlines:
      if charcode == 0x0A:
        illegal_charcodes.add(charcode);
    elif (charcode < 0x20 and charcode != 0x0A) \
        or (charcode > 0x7E and charcode < 0xA1):
      illegal_charcodes.add(charcode);

  if illegal_charcodes:
    illegal_chars = ['%02X' % charcode for charcode in illegal_charcodes if 1];
    text.warnings.append( \
        'string contains illegal characters: %s' % ', '.join(illegal_chars));

  if no_extra_spaces and ' ' in [string[0], string[-1]]:
    text.warnings.append('string must not start or end with a space');

  if is_keyword and string not in [
      'Title', 'Author', 'Description', 'Copyright', 'Creation Time',
      'Software', 'Disclaimer', 'Warning', 'Source', 'Comment']:
    text.warnings.append('unknown keyword');


text:
/**
 *
 */
package fr.lithie.matchup.views.panels;

import javax.swing.JPanel;
import java.awt.GridBagLayout;
import javax.swing.JLabel;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.metal.MetalBorders.TextFieldBorder;

import fr.lithie.matchup.views.base.IVisibility;

import java.awt.Insets;

/**
 * @author Audrey
 *
 */

public class PanelField extends JPanel implements IVisibility {
	private JLabel label;
	private JTextField input;

	/**
	 * @return the label
	 */
	public JLabel getLabel() {
		return label;
	}

	/**
	 * @return the input
	 */
	public JTextField getInput() {
		return input;
	}

	/**
	 * Create the panel.
	 */
	public PanelField(String label) {
		super();
//		if (!label.isEmpty()) {
			GridBagLayout gridBagLayout = new GridBagLayout();
			gridBagLayout.columnWidths = new int[] { 1, 0, 5, 0, 1, 0 };
			gridBagLayout.rowHeights = new int[] { 1, 0, 1, 0 };
			gridBagLayout.columnWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE };
			gridBagLayout.rowWeights = new double[] { 0.0, 0.0, 0.0, Double.MIN_VALUE };
			setLayout(gridBagLayout);

			this.label = new JLabel(label);
			GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
			gbc_lblNewLabel.anchor = GridBagConstraints.WEST;
			gbc_lblNewLabel.insets = new Insets(0, 0, 1, 1);
			gbc_lblNewLabel.gridx = 1;
			gbc_lblNewLabel.gridy = 1;
			add(this.label, gbc_lblNewLabel);

			input = new JTextField();
			GridBagConstraints gbc_textField = new GridBagConstraints();
			gbc_textField.fill = GridBagConstraints.HORIZONTAL;
			input.setMinimumSize(new Dimension(70, 20));
			gbc_textField.insets = new Insets(0, 0, 1, 1);
			gbc_textField.gridx = 3;
			gbc_textField.gridy = 1;
			add(input, gbc_textField);
//		}
	}

	/* (non-Javadoc)
	 * @see fr.yas.matchup.views.IVisibility#setMode(boolean)
	 */
	@Override
	public void setMode(boolean b) {
		this.getInput().setEditable(b);
		if(b)
			this.getInput().setBorder(new TextFieldBorder());
		else
			this.getInput().setBorder(new EmptyBorder(0, 0, 0, 0));

	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
  <fixed facet="php.component"/>
  <fixed facet="php.core.component"/>
  <installed facet="php.core.component" version="1"/>
  <installed facet="php.component" version="5.6"/>
  <installed facet="wst.jsdt.web" version="1.0"/>
</faceted-project>


text:
#include "src/core/lib/gprpp/ref_counted.h"

#include <memory>
#include <new>
#include <set>
#include <type_traits>

#include "gmock/gmock.h"
#include "gtest/gtest.h"

#include "test/core/util/test_config.h"

namespace grpc_core {
namespace testing {
namespace {

class Foo : public RefCounted<Foo> {
 public:
  Foo() {
    static_assert(std::has_virtual_destructor<Foo>::value,
                  "PolymorphicRefCount doesn't have a virtual dtor");
  }
};

TEST(RefCounted, Basic) {
  Foo* foo = new Foo();
  foo->Unref();
}

TEST(RefCounted, ExtraRef) {
  Foo* foo = new Foo();
  RefCountedPtr<Foo> foop = foo->Ref();
  foop.release();
  foo->Unref();
  foo->Unref();
}

class Value : public RefCounted<Value, PolymorphicRefCount, kUnrefNoDelete> {
 public:
  Value(int value, std::set<std::unique_ptr<Value>>* registry) : value_(value) {
    registry->emplace(this);
  }

  int value() const { return value_; }

 private:
  int value_;
};

void GarbageCollectRegistry(std::set<std::unique_ptr<Value>>* registry) {
  for (auto it = registry->begin(); it != registry->end();) {
    RefCountedPtr<Value> v = (*it)->RefIfNonZero();
    // Check if the object has any refs remaining.
    if (v != nullptr) {
      // It has refs remaining, so we do not delete it.
      ++it;
    } else {
      // No refs remaining, so remove it from the registry.
      it = registry->erase(it);
    }
  }
}

TEST(RefCounted, NoDeleteUponUnref) {
  std::set<std::unique_ptr<Value>> registry;
  // Add two objects to the registry.
  auto v1 = MakeRefCounted<Value>(1, &registry);
  auto v2 = MakeRefCounted<Value>(2, &registry);
  EXPECT_THAT(registry,
              ::testing::UnorderedElementsAre(
                  ::testing::Pointee(::testing::Property(&Value::value, 1)),
                  ::testing::Pointee(::testing::Property(&Value::value, 2))));
  // Running garbage collection should not delete anything, since both
  // entries still have refs.
  GarbageCollectRegistry(&registry);
  EXPECT_THAT(registry,
              ::testing::UnorderedElementsAre(
                  ::testing::Pointee(::testing::Property(&Value::value, 1)),
                  ::testing::Pointee(::testing::Property(&Value::value, 2))));
  // Unref v2 and run GC to remove it.
  v2.reset();
  GarbageCollectRegistry(&registry);
  EXPECT_THAT(registry, ::testing::UnorderedElementsAre(::testing::Pointee(
                            ::testing::Property(&Value::value, 1))));
  // Now unref v1 and run GC again.
  v1.reset();
  GarbageCollectRegistry(&registry);
  EXPECT_THAT(registry, ::testing::UnorderedElementsAre());
}

class ValueInExternalAllocation
    : public RefCounted<ValueInExternalAllocation, PolymorphicRefCount,
                        kUnrefCallDtor> {
 public:
  explicit ValueInExternalAllocation(int value) : value_(value) {}

  int value() const { return value_; }

 private:
  int value_;
};

TEST(RefCounted, CallDtorUponUnref) {
  std::aligned_storage<sizeof(ValueInExternalAllocation),
                       alignof(ValueInExternalAllocation)>::type storage;
  RefCountedPtr<ValueInExternalAllocation> value(
      new (&storage) ValueInExternalAllocation(5));
  EXPECT_EQ(value->value(), 5);
}

class FooNonPolymorphic
    : public RefCounted<FooNonPolymorphic, NonPolymorphicRefCount> {
 public:
  FooNonPolymorphic() {
    static_assert(!std::has_virtual_destructor<FooNonPolymorphic>::value,
                  "NonPolymorphicRefCount has a virtual dtor");
  }
};

TEST(RefCountedNonPolymorphic, Basic) {
  FooNonPolymorphic* foo = new FooNonPolymorphic();
  foo->Unref();
}

TEST(RefCountedNonPolymorphic, ExtraRef) {
  FooNonPolymorphic* foo = new FooNonPolymorphic();
  RefCountedPtr<FooNonPolymorphic> foop = foo->Ref();
  foop.release();
  foo->Unref();
  foo->Unref();
}

class FooWithTracing : public RefCounted<FooWithTracing> {
 public:
  FooWithTracing() : RefCounted("Foo") {}
};

TEST(RefCountedWithTracing, Basic) {
  FooWithTracing* foo = new FooWithTracing();
  RefCountedPtr<FooWithTracing> foop = foo->Ref(DEBUG_LOCATION, "extra_ref");
  foop.release();
  foo->Unref(DEBUG_LOCATION, "extra_ref");
  // Can use the no-argument methods, too.
  foop = foo->Ref();
  foop.release();
  foo->Unref();
  foo->Unref(DEBUG_LOCATION, "original_ref");
}

class FooNonPolymorphicWithTracing
    : public RefCounted<FooNonPolymorphicWithTracing, NonPolymorphicRefCount> {
 public:
  FooNonPolymorphicWithTracing() : RefCounted("FooNonPolymorphicWithTracing") {}
};

TEST(RefCountedNonPolymorphicWithTracing, Basic) {
  FooNonPolymorphicWithTracing* foo = new FooNonPolymorphicWithTracing();
  RefCountedPtr<FooNonPolymorphicWithTracing> foop =
      foo->Ref(DEBUG_LOCATION, "extra_ref");
  foop.release();
  foo->Unref(DEBUG_LOCATION, "extra_ref");
  // Can use the no-argument methods, too.
  foop = foo->Ref();
  foop.release();
  foo->Unref();
  foo->Unref(DEBUG_LOCATION, "original_ref");
}

}  // namespace
}  // namespace testing
}  // namespace grpc_core

int main(int argc, char** argv) {
  grpc::testing::TestEnvironment env(&argc, argv);
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using EventStore.Core.Data;
using EventStore.Projections.Core.Messages;

namespace EventStore.Projections.Core.Services.Processing
{
    public class PreTaggedPositionTagger : PositionTagger
    {
        private readonly CheckpointTag _zeroCheckpointTag;

        public PreTaggedPositionTagger(int phase, CheckpointTag zeroCheckpointTag)
            : base(phase)
        {
            _zeroCheckpointTag = zeroCheckpointTag;
        }

        public override bool IsMessageAfterCheckpointTag(
            CheckpointTag previous, ReaderSubscriptionMessage.CommittedEventDistributed committedEvent)
        {
            if (committedEvent.PreTagged == null)
                throw new ArgumentException("committedEvent.PreTagged == null", "committedEvent");
            if (previous.Phase < Phase)
                return true;

            return committedEvent.PreTagged > previous;
        }

        public override CheckpointTag MakeCheckpointTag(
            CheckpointTag previous, ReaderSubscriptionMessage.CommittedEventDistributed committedEvent)
        {
            if (committedEvent.PreTagged == null)
                throw new ArgumentException("committedEvent.PreTagged == null", "committedEvent");

            if (previous.Phase != Phase)
                throw new ArgumentException(
                    string.Format("Invalid checkpoint tag phase.  Expected: {0} Was: {1}", Phase, previous.Phase));

            return committedEvent.PreTagged;
        }

        public override CheckpointTag MakeCheckpointTag(CheckpointTag previous, ReaderSubscriptionMessage.EventReaderPartitionEof partitionEof)
        {
            if (partitionEof.PreTagged == null)
                throw new ArgumentException("committedEvent.PreTagged == null", "committedEvent");

            if (previous.Phase != Phase)
                throw new ArgumentException(
                    string.Format("Invalid checkpoint tag phase.  Expected: {0} Was: {1}", Phase, previous.Phase));

            return partitionEof.PreTagged;
        }

        public override CheckpointTag MakeCheckpointTag(
            CheckpointTag previous, ReaderSubscriptionMessage.EventReaderPartitionDeleted partitionDeleted)
        {
            if (partitionDeleted.PreTagged == null)
                throw new ArgumentException("committedEvent.PreTagged == null", "committedEvent");

            if (previous.Phase != Phase)
                throw new ArgumentException(
                    string.Format("Invalid checkpoint tag phase.  Expected: {0} Was: {1}", Phase, previous.Phase));

            return partitionDeleted.PreTagged;
        }

        public override CheckpointTag MakeZeroCheckpointTag()
        {
            return _zeroCheckpointTag;
        }

        public override bool IsCompatible(CheckpointTag checkpointTag)
        {
            return true; //TODO: implement properly
        }

        public override CheckpointTag AdjustTag(CheckpointTag tag)
        {
            if (tag.Phase < Phase)
                return tag;
            if (tag.Phase > Phase)
                throw new ArgumentException(
                    string.Format("Invalid checkpoint tag phase.  Expected less or equal to: {0} Was: {1}", Phase, tag.Phase), "tag");

            return tag;
        }
    }
}


text:
import SeqEmitter from "seq-emitter";
import MMLIterator from "mml-iterator";
import reverseOctave from "./reverseOctave";
import stripComments from "strip-comments";

export default class MMLEmitter extends SeqEmitter {
  constructor(source, config = {}) {
    if (config.reverseOctave) {
      source = reverseOctave(source);
    }

    let MMLIteratorClass = config.MMLIterator || MMLIterator;
    let tracks = stripComments(source).split(";");

    tracks = tracks.filter(source => !!source.trim());
    tracks = tracks.map(track => new MMLIteratorClass(track, config));

    super(tracks, config);
  }
}


text:
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * Validation callback.
 *
 * @package PhpMyAdmin-Setup
 */

/**
 * Core libraries.
 */
require './lib/common.inc.php';

$validators = array();
require './libraries/config/validate.lib.php';

header('Content-type: application/json');

$ids = isset($_POST['id']) ? $_POST['id'] : null;
$vids = explode(',', $ids);
$vals = isset($_POST['values']) ? $_POST['values'] : null;
$values = json_decode($vals);
if (!($values instanceof stdClass)) {
    PMA_fatalError(__('Wrong data'));
}
$values = (array)$values;
$result = PMA_config_validate($vids, $values, true);
if ($result === false) {
    $result = 'Wrong data or no validation for ' . $vids;
}
echo $result !== true ? json_encode($result) : '';
?>


text:
import 'mocha';
import { expect } from 'chai';

import { getExecOutput, ExecOptions } from '@actions/exec';

const { TEST_ACCOUNT, TEST_PROJECT_ID, TEST_COMPONENTS } = process.env;

describe('#run', function () {
  it('has the correct account', async function () {
    if (!TEST_ACCOUNT) this.skip();

    const raw = await gcloudRun([
      '--quiet',
      'auth',
      'list',
      '--filter',
      'status:ACTIVE',
      '--format',
      'json',
    ]);
    const parsed = JSON.parse(raw)[0]?.['account'] || '(unset)';
    expect(parsed).to.eql(TEST_ACCOUNT.trim());
  });

  it('has the correct project_id', async function () {
    if (!TEST_PROJECT_ID) this.skip();

    const raw = await gcloudRun(['--quiet', 'config', 'list', 'core/project', '--format', 'json']);
    const parsed = JSON.parse(raw)['core']?.['project'] || '(unset)';

    expect(parsed.trim()).to.eql(TEST_PROJECT_ID.trim());
  });

  it('includes the given components', async function () {
    if (!TEST_COMPONENTS) this.skip();

    const raw = await gcloudRun([
      '--quiet',
      'components',
      'list',
      '--only-local-state',
      '--format',
      'json',
    ]);
    const parsed = JSON.parse(raw).map((entry: Record<string, any>) => entry['id']);

    const members = TEST_COMPONENTS.split(',').map((component) => component.trim());
    expect(parsed).to.include.all.members(members);
  });
});

async function gcloudRun(cmd: string[], options?: ExecOptions): Promise<string> {
  // A workaround for https://github.com/actions/toolkit/issues/229
  let toolCommand = 'gcloud';
  if (process.platform == 'win32') {
    toolCommand = 'gcloud.cmd';
  }

  const opts = Object.assign({}, { silent: true, ignoreReturnCode: true }, options);
  const commandString = `${toolCommand} ${cmd.join(' ')}`;

  const result = await getExecOutput(toolCommand, cmd, opts);
  if (result.exitCode !== 0) {
    const errMsg = result.stderr || `command exited ${result.exitCode}, but stderr had no output`;
    throw new Error(`failed to execute command \`${commandString}\`: ${errMsg}`);
  }
  return result.stdout;
}


text:
auto register routes for hapi

[![Dependency Status](https://david-dm.org/keviswang/hapi-auto-router.svg)](https://david-dm.org/keviswang/hapi-auto-router)
[![devDependency Status](https://david-dm.org/keviswang/hapi-auto-router/dev-status.svg?theme=shields.io)](https://david-dm.org/keviswang/hapi-auto-router#info=devDependencies)
[![Build Status](https://travis-ci.org/keviswang/hapi-auto-router.svg?branch=master)](https://travis-ci.org/keviswang/hapi-auto-router)

## Install

```bash
$ npm install hapi-auto-router
```

## Usage

```bash
$ echo "details coming soon"
```

## License

MIT


text:
@interface AuthEventHandler : ProtobufEventHandler
{
    struct ec_key_st *ecdh_key;
    unsigned int ct1;
}

- (_Bool)OnProtocolEncryptPack:(id)arg1 OutBuf:(struct AutoBuffer *)arg2 uin:(unsigned int)arg3;
- (_Bool)OnProtocolManualAuthEncryptPack:(id)arg1 OutBuf:(struct AutoBuffer *)arg2 uin:(unsigned int)arg3;
- (_Bool)OnProtocolAutoAuthEncryptPack:(id)arg1 OutBuf:(struct AutoBuffer *)arg2 uin:(unsigned int)arg3;
- (_Bool)OnProtocolHasCustomEncryptPack:(id)arg1;
- (void)OnProtocolConnectFail:(id)arg1;
- (void)OnProtocolResponse:(id)arg1 shouldContinue:(_Bool *)arg2;
- (void)changeForMessage:(id)arg1;
- (void)OnProtocolStart:(id)arg1 shouldContinue:(_Bool *)arg2;
- (void)dealloc;
- (id)init;

@end


text:
package org.postgresql.jdbc2.optional;

import org.postgresql.ds.PGSimpleDataSource;

public class SimpleDataSource extends PGSimpleDataSource
{
}


text:
/**
 * Created by john on 9/12/15.
 */

/// <reference path="../_app.ts" />

module app.controllers {
    'use strict';

    export class HomeController {
		constructor() {}
	}
}


text:
package org.naishadhparmar.customcalendar;

import android.app.DatePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.support.design.widget.Snackbar;

import org.naishadhparmar.zcustomcalendar.CustomCalendar;
import org.naishadhparmar.zcustomcalendar.OnDateSelectedListener;
import org.naishadhparmar.zcustomcalendar.OnNavigationButtonClickedListener;
import org.naishadhparmar.zcustomcalendar.Property;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class ActivityMain extends AppCompatActivity implements OnNavigationButtonClickedListener{

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		final CustomCalendar customCalendar = (CustomCalendar) findViewById(R.id.custom_calendar);

		HashMap<Object, Property> mapDescToProp = new HashMap<>();

		Property propDefault = new Property();
		propDefault.layoutResource = R.layout.default_view;
		propDefault.dateTextViewResource = R.id.default_datetextview;
		mapDescToProp.put("default", propDefault);

		Property propUnavailable = new Property();
		propUnavailable.layoutResource = R.layout.unavailable_view;
		//You can leave the text view field blank. Custom calendar won't try to set a date on such views
		propUnavailable.enable = false;
		mapDescToProp.put("unavailable", propUnavailable);

		Property propHoliday = new Property();
		propHoliday.layoutResource = R.layout.holiday_view;
		propHoliday.dateTextViewResource = R.id.holiday_datetextview;
		mapDescToProp.put("holiday", propHoliday);

		customCalendar.setMapDescToProp(mapDescToProp);

		HashMap<Integer, Object> mapDateToDesc = new HashMap<>();
		Calendar calendar = Calendar.getInstance();
		mapDateToDesc.put(2, "unavailable");
		mapDateToDesc.put(5, "holiday");
		mapDateToDesc.put(10, "default"); //You don't need to explicitly mention "default" description dates.
		mapDateToDesc.put(11, "unavailable");
		mapDateToDesc.put(19, "holiday");
		mapDateToDesc.put(20, "holiday");
		mapDateToDesc.put(24, "unavailable");

		customCalendar.setOnNavigationButtonClickedListener(CustomCalendar.PREVIOUS, this);
		customCalendar.setOnNavigationButtonClickedListener(CustomCalendar.NEXT, this);
		customCalendar.setDate(calendar, mapDateToDesc);
		customCalendar.setOnDateSelectedListener(new OnDateSelectedListener() {
			@Override
			public void onDateSelected(View view, Calendar selectedDate, Object desc) {
				Snackbar.make(customCalendar, selectedDate.get(Calendar.DAY_OF_MONTH) + " selected", Snackbar.LENGTH_LONG).show();
			}
		});
	}

	@Override
	public Map<Integer, Object>[] onNavigationButtonClicked(int whichButton, Calendar newMonth) {
		Map<Integer, Object>[] arr = new Map[2];
		switch(newMonth.get(Calendar.MONTH)) {
			case Calendar.AUGUST:
				arr[0] = new HashMap<>(); //This is the map linking a date to its description
				arr[0].put(3, "unavailable");
				arr[0].put(6, "holiday");
				arr[0].put(21, "unavailable");
				arr[0].put(24, "holiday");
				arr[1] = null; //Optional: This is the map linking a date to its tag.
				break;
			case Calendar.JUNE:
				arr[0] = new HashMap<>();
				arr[0].put(5, "unavailable");
				arr[0].put(10, "holiday");
				arr[0].put(19, "holiday");
				break;
		}
		return arr;
	}
}


text: This is a test program for "zinnia" and "shwr", written with QT.


text:
namespace DAVA
{
namespace PlatformApi
{
namespace Win32
{
void SetWindowIcon(Window* targetWindow, int32 iconResourceId)
{
    using namespace DAVA::Private;
    WindowImpl* wb = EngineBackend::GetWindowImpl(targetWindow);
    wb->SetIcon(MAKEINTRESOURCEW(iconResourceId));
}

void SetWindowCursor(Window* targetWindow, HCURSOR hcursor)
{
    using namespace DAVA::Private;
    WindowImpl* wb = EngineBackend::GetWindowImpl(targetWindow);
    wb->SetCursor(hcursor);
}

} // namespace Win32
} // namespace PlatformApi
} // namespace DAVA

#endif // __DAVAENGINE_WIN32__


text:
require 'puppet/parameter/boolean'
require_relative '../pacemaker/options'
require_relative '../pacemaker/type'

Puppet::Type.newtype(:pcmk_colocation) do
  desc %q(Type for manipulating corosync/pacemaker colocation.  Colocation
      is the grouping together of a set of primitives so that they travel
      together when one of them fails.  For instance, if a web server vhost
      is colocated with a specific ip address and the web server software
      crashes, the ip address with migrate to the new host with the vhost.

      More information on Corosync/Pacemaker colocation can be found here:

      * http://www.clusterlabs.org/doc/en-US/Pacemaker/1.1/html/Clusters_from_Scratch/_ensuring_resources_run_on_the_same_host.html)

  include Pacemaker::Options
  include Pacemaker::Type

  ensurable

  newparam(:name) do
    desc %q(Identifier of the colocation entry. This value needs to be unique
        across the entire Corosync/Pacemaker configuration since it doesn't have
        the concept of name spaces per type.)
    isnamevar
  end

  newparam(:debug, :boolean => true, :parent => Puppet::Parameter::Boolean) do
    desc %q(Don't actually make changes)
    defaultto false
  end

  newproperty(:first) do
    desc %q(First Corosync primitive.)
  end

  newproperty(:second) do
    desc %q(Second Corosync primitive.)
  end

  newproperty(:score) do
    desc %q(The priority of this colocation.  Primitives can be a part of
        multiple colocation groups and so there is a way to control which
        primitives get priority when forcing the move of other primitives.
        This value can be an integer but is often defined as the string
        INFINITY.)

    defaultto 'INFINITY'

    validate do |value|
      break if %w(inf INFINITY -inf -INFINITY).include? value
      break if value.to_i.to_s == value
      fail 'Score parameter is invalid, should be +/- INFINITY(or inf) or Integer'
    end

    munge do |value|
      value.gsub 'inf', 'INFINITY'
    end

    isrequired
  end

  autorequire(:service) do
    ['corosync']
  end

  autorequire(:pcmk_resource) do
    resources = []
    next resources unless self[:ensure] == :present
    resources << primitive_base_name(self[:first]) if self[:first]
    resources << primitive_base_name(self[:second]) if self[:second]
    debug "Autorequire pcmk_resources: #{resources.join ', '}" if resources.any?
    resources
  end

  if respond_to? :autobefore
    autobefore(:pcmk_resource) do
      resources = []
      next resources unless self[:ensure] == :absent
      resources << primitive_base_name(self[:first]) if self[:first]
      resources << primitive_base_name(self[:second]) if self[:second]
      debug "Autobefore pcmk_resources: #{resources.join ', '}" if resources.any?
      resources
    end
  end

end


text:
function fighandle=tilefig(varargin)
% fighandle = tilefig(figs,figname,extend,layout)  TILE 1 or more FIGures.
% Tiles the screen for existing figures starting at the top left hand corner.
%   Examples:
%           tilefig, tilefig([1,2,3],'Title',1+i), tilefig('Title'),
%           figh=tilefig([2:12]); figh=tilefig([3,4],i); tilefig(5,-1,[2,3])
%   "fighandle" is an output array of handle numbers for the figures.
%   "figs" (first numeric input) is a vector of handles of the figures to be tiled.
%       Default value is 0 which tiles all open figures.
%   "figname" (any argument position) is an optional string for each figure's name.
%       If not specified then figure names are retained, to erase names use ' '.
%   "extend" (second numeric input)is a complex number specifying how figures
%       are to be created on the extended desktop.
%       Examples: +1/-1 is one screen to the right/left,
%                 0 is the primary screen (default),
%                 +i is one screen up,
%                 -1-0.5i is half a screen down and to the left, etc...
%   "layout" (third numeric input) is a vector (rows,columns) specifying the
%       screen layout or a single number specifying the aspect ratio.
%       If not specified then the optimal layout will be determined.
%       If the specified layout only creates one row, then the figure
%       height is chosen to maintain the default aspect ratio.
%       The aspect ratio is the minimum horizontal/vertical figure size.
% NOTES:
% Figures are tiled in the order they are specified in "figs".
% The figures are numbered within this group of figures and not by their
%   figure handle.
% The figures are accessible by their handles. Thus "figure(fighandle(4))"
%   will make the 4th figure from this group of figures the current figure.
% To delete the entire group of figures use "close(fighandle)".

%   Copyright 2006 Mirtech, Inc.
%   created 09/18/2006  by Mirko Hrovat on Matlab Ver. 7.2
%   Mirtech, Inc.       email: mhrovat@email.com
%   Inspired by "Tilefigs" by Charles Plum
% More notes:
% Will work with docked figures, will ignore modal figures.
% Extended monitors must have the same resolution as the primary monitor.
% The size and layout of the figures is determined by the aspect ratio and
%   the number of figure columns.
% For a large number of figures, the menubar and toolbar are removed to
%   increase figure space.
% Default properties for this group of figures may be coded into the code
%   below. The following properties are currently set.
%        'Units','pixels', ...
%        'NumberTitle','off',...
%        'MenuBar',menbar,...       (depends on number of figures)
%        'ToolBar',tbar             (depends on number of figures)

% --------- Key Constants -----------
% To allow for user or OS borders set the appropriate value in pixels.
% For example one might want to set the bottomborder for the taskbar.
topborder       =0;
bottomborder    =0;
rightborder     =0;
leftborder      =0;
% Border properties for figures - Adjust if needed.
% determined by the difference between OuterPosition and Position values.
% GETFIGDIM can return these values for your system.
figureborder    =5;     %#ok
titleheight     =26;
menbarheight    =21;
toolbarheight   =27;
minfigwidth     =125;
% Set the default aspect ratio (minimum horizontal/vertical size of the figure).
def_aspect      =1.1;

menbarlimit     =3;     % no menubar if numrows > menbarlimit
toolbarlimit    =3;     % no toolbar if numrows > toolbarlimit
maxnumrows      =6;     % maximum number of figure rows to create
% ----------------------------------

extend=[];
figs=[];
ftitle=[];
layout=[];
getname=1;
if nargin~=0,
    count=0;
    for n=1:length(varargin),
        arg=varargin{n};
        if isnumeric(arg),      % note "empty" is also considered to be numeric!
            count=count+1;
            switch count
                case 1
                    figs=arg;
                case 2
                    extend=arg;
                case 3
                    layout=arg;
            end  % switch count
        elseif ischar(arg),
            ftitle=arg;
            getname=0;
        end  % if ~isempty
    end  % for
end  % if nargin
if isempty(figs),       figs=0;     end
if isempty(ftitle),     ftitle='';  end
if isempty(extend),     extend=0;   end
if isempty(layout)||numel(layout)==2,
    aspect=def_aspect;
elseif numel(layout)==1,
    aspect=layout;
    layout=[];
else
    error ('  Layout cannot have more than 2 elements!')
end

% alternative methods to find all of the figures.
% Second method should be more foolproof.
% allhands=get(0,'Children');
allhands=findobj('Type','figure');
% Note that figures without visible handles will not be tiled.
if figs==0,
    figs=sort(allhands);
else
    [tmp,indx]=intersect(figs,allhands);    %#ok  only tile figures that do exist
    figs=figs(sort(indx));                  % this keeps the order of the figures
end
numfigs=numel(figs);
% Check WindowStyle property on figures
m=0;
for n=1:numfigs,
    m=m+1;
    winstyle=get(figs(m),'WindowStyle');
    if strcmpi(winstyle,'modal'),           % Cannot maximize this figure.
        figs(m)=[];
        m=m-1;
    elseif strcmpi(winstyle,'docked'),      % Docked figures need to be undocked.
        set(figs(m),'WindowStyle','normal');
        drawnow
    end
end
numfigs=numel(figs);

% Get screen dimensions. Note that multiple monitors are assumed to have
% the same resolution.
set(0,'Units','pixels');
scnsize=get(0,'ScreenSize');
scnwidth=scnsize(3)-leftborder-rightborder;
scnheight=scnsize(4)-topborder-bottomborder;

% Try to determine the best layout for the number of figures.
% Calculate the number of figure columns for different number of rows
% based upon the screen size to maintain square figures
numfigcols=zeros(1,maxnumrows);
for n=2:maxnumrows,
    barheight=((menbarlimit-n)>=0)*menbarheight+((toolbarlimit-n)>=0)*toolbarheight;
    numfigcols(n)=fix(scnwidth/((scnheight/n - barheight-titleheight)*aspect));
% Note that the figure size is created with a minimum aspect ratio.
end
% For one row of figures use the same size figure as for two rows.
numfigcols(1)=numfigcols(2);
maxnumfigs=(1:maxnumrows).*numfigcols;

% Calculate offsets for multiple monitors.
offx=scnsize(3)*real(extend)+leftborder;
offy=scnsize(4)*imag(extend)+bottomborder;

% Determine layout from numfigs
if isempty(layout),
    % Determine a layout (figrows,figcols) for numfigs figures.
    figrows=1;
    while numfigs>maxnumfigs(figrows);
        figrows=figrows+1;
        if figrows>maxnumrows,
            error ('  Too many figures are requested! Maximum is %3.0f',maxnumfigs(maxnumrows))
        end
    end
    figcols=numfigcols(figrows);
else
    figrows=layout(1);
    figcols=layout(2);
    if figrows>maxnumrows,
        error ('  Too many figure rows! Maximum is %3.0f',maxnumrows)
    end
end     % isempty(layout)

% For a large number of figures, the menu and tool bars are turned off to
% conserve space.
if figrows > toolbarlimit,
    tbar='none';
else
    tbar='figure';
end
if figrows > menbarlimit,
    menbar='none';
else
    menbar='figure';
end

figwidth=scnwidth/figcols;
if figwidth < minfigwidth
    figcols=fix(scnwidth/minfigwidth);
    figrows=ceil(numfigs/figcols);
    if figrows>maxnumrows,
        error ('  Too many figure rows! Maximum is %3.0f',maxnumrows)
    end
    figwidth=scnwidth/figcols;
end

% For a single row of figures calculate height based upon aspect ratio.
if figrows==1,
    figheight=figwidth/aspect + menbarheight + toolbarheight + titleheight;
    figrows=scnheight/figheight;    % It's ok if figrows is not integer.
else
    figheight=scnheight/figrows;
end

% Now move the individual figures.
% Note that the OuterPosition property is preferable to the Position property
% for setting the figure positions.
for n=numfigs:-1:1,
    r=fix((n-1)/figcols)+1;     % calculate row number
    c=mod(n-1,figcols)+1;       % calculate column number
    pos=[offx+(c-1)*figwidth+1,offy+(figrows-r)*figheight+1,figwidth,figheight];
    if getname,
        ftitle = get(figs(n),'Name');
        % remove #xx if it exists
        if ~isempty(ftitle) && ftitle(1)=='#',
            [tmp,ftitle]=strtok(ftitle);    %#ok
            ftitle=strtrim(ftitle);
        end
    end
    if numfigs==1,
        figtitle=ftitle;
    else
        figtitle=['#',int2str(n),'  ',ftitle];
    end
    % Move figure and modify properties as needed.
    set(figs(n),'Name',figtitle,...
        'Units','pixels', ...
        'OuterPosition',pos,...
        'NumberTitle','off',...
        'MenuBar',menbar,...
        'ToolBar',tbar);
    figure(figs(n))             % bring figure to front.
end

if nargout==1,
    fighandle=figs;
end