text:
<?php

namespace app\models;

use Yii;

use app\models\general\GeneralLabel;
use app\models\general\GeneralMessage;

/**
 * This is the model class for table "tbl_mesyuarat_senarai_nama_hadir".
 *
 * @property integer $senarai_nama_hadir_id
 * @property integer $mesyuarat_id
 * @property string $nama
 * @property integer $kehadiran
 */
class MesyuaratSenaraiNamaHadir extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'tbl_mesyuarat_senarai_nama_hadir';
    }

    public function behaviors()
    {
        return [
            'bedezign\yii2\audit\AuditTrailBehavior',
            [
                'class' => \yii\behaviors\BlameableBehavior::className(),
                'createdByAttribute' => 'created_by',
                'updatedByAttribute' => 'updated_by',
            ],
            [
                'class' => \yii\behaviors\TimestampBehavior::className(),
                'createdAtAttribute' => 'created',
                'updatedAtAttribute' => 'updated',
                'value' => new \yii\db\Expression('NOW()'),
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['nama', 'status', 'no_tel', 'jawatan', 'organisasi', 'kehadiran'], 'required', 'skipOnEmpty' => true, 'message' => GeneralMessage::yii_validation_required],
            [['mesyuarat_id', 'kehadiran'], 'integer', 'message' => GeneralMessage::yii_validation_integer],
            [['no_tel'], 'integer', 'message' => GeneralMessage::yii_validation_integer],
            [['no_tel'], 'string', 'max' => 14, 'tooLong' => GeneralMessage::yii_validation_string_max],
            [['emel'], 'email', 'message' => GeneralMessage::yii_validation_email],
            [['nama'], 'string', 'max' => 100, 'tooLong' => GeneralMessage::yii_validation_string_max],
            [['nama', 'jawatan','organisasi','emel'], function ($attribute, $params) {
                if (!\common\models\general\GeneralFunction::validateXSS($this->$attribute)) {
                    $this->addError($attribute, GeneralMessage::yii_validation_xss);
                }
            }],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'senarai_nama_hadir_id' => GeneralLabel::senarai_nama_hadir_id,
            'mesyuarat_id' => GeneralLabel::mesyuarat_id,
            'nama' => GeneralLabel::nama,
            'status' => GeneralLabel::status,
            'jawatan' => GeneralLabel::jawatan,
            'organisasi' => GeneralLabel::organisasi,
            'no_tel' => GeneralLabel::no_tel,
            'emel' => GeneralLabel::emel,
            'kehadiran' => GeneralLabel::kehadiran,

        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getRefKelulusan(){
        return $this->hasOne(RefKelulusan::className(), ['id' => 'kehadiran']);
    }
}


text:
package com.jivesoftware.example.jive.authentication.events;

/**
 * Created by mark.schisler on 8/28/14.
 */
public class JiveLoginPressed {
    public final String username;
    public final String password;
    public final String endpoint;

    public JiveLoginPressed(String endpoint, String username, String password) {
        this.username = username;
        this.password = password;
        this.endpoint = endpoint;
    }
}

redpajama_set_name: RedPajamaGithub


text:
module Facility::Addon
  module Image
    extend ActiveSupport::Concern
    extend SS::Addon

    included do
      belongs_to :image, class_name: "SS::File"
      permit_params :image_id

      before_save :save_image
      after_destroy :destroy_image
    end

    def save_image
      return true unless image_id_changed?
      image.update_attributes(site_id: site_id, model: "facility/file", state: "public") if image

      if image_id_was
        file = SS::File.where(id: image_id_was).first
        file.destroy if file
      end
    end

    def destroy_image
      image.destroy if image
    end
  end
end


text:
<?php

namespace My\PowersBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class MyPowersBundle extends Bundle
{
}


text:
import atheris
import sys
with atheris.instrument_imports():
    from smart_open.utils import *

def TestInput(data):
    if len(data) < 10:
       return

    fdp = atheris.FuzzedDataProvider(data)

    #Fuzz clamp
    clamp(
        fdp.ConsumeInt(10),
        fdp.ConsumeInt(10),
        None if fdp.ConsumeBool() else fdp.ConsumeInt(10)
    )

    #Fuzz check_kwargs
    kwargs = {}
    for i in range(1,fdp.ConsumeIntInRange(1,10)):
        kwargs[fdp.ConsumeString(5)]=fdp.ConsumeString(10)
    try:
        check_kwargs(fdp.ConsumeString(10),kwargs)
    except TypeError as e:
        if "is not a callable object" not in str(e):
            raise e

    #Fuzz make_range_string
    try:
        make_range_string(
            None if fdp.ConsumeBool() else fdp.ConsumeInt(10),
            None if fdp.ConsumeBool() else fdp.ConsumeInt(10)
        )
    except ValueError as e:
        if "make_range_string requires either a stop or start value" not in str(e):
            raise e

    #Fuzz content_range
    content_range = "%s %d-%d/%d"%(
        fdp.ConsumeString(10),
        fdp.ConsumeInt(10),
        fdp.ConsumeInt(10),
        fdp.ConsumeInt(10)
    )
    try:
       parse_content_range(content_range)
    except ValueError as e:
        error_list = [
            "invalid literal for int() with base 10",
            "not enough values to unpack"
        ]
        expected_error = False
        for error in error_list:
            if error in str(e):
                expected_error = True
        if not expected_error:
            raise e

    #Fuzz safe_urlsplit
    try:
        safe_urlsplit(fdp.ConsumeString(100))
    except ValueError as e:
        if "Invalid IPv6 URL" not in str(e):
             raise e
def main():
    atheris.Setup(sys.argv, TestInput, enable_python_coverage=True)
    atheris.instrument_all()
    atheris.Fuzz()

if __name__ == "__main__":
  main()


text:
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using System.Threading;
using log4net;

namespace System.IO.FS
{
	internal sealed class FilesystemWatcher
		: IFilesystemWatcher
	{
		private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

		private readonly Dictionary<string, IFileInfo> _filesByPath;
		private readonly FilesystemWatchdog _filesystemWatchdog;
		private readonly Filesystem _filesystem;
		private readonly IPeriodicTask _task;
		private readonly ITaskScheduler _taskScheduler;
		private readonly SearchOption _searchOption;
		private readonly object _syncRoot;
		private readonly string _searchPattern;

		private IReadOnlyList<IFileInfo> _files;
		private string _path;

		public FilesystemWatcher(FilesystemWatchdog filesystemWatchdog,
		                         Filesystem filesystem,
		                         ITaskScheduler taskScheduler,
		                         TimeSpan maximumLatency,
		                         string path,
		                         string searchPattern,
		                         SearchOption searchOption)
		{
			_filesystemWatchdog = filesystemWatchdog;
			_filesystem = filesystem;
			_taskScheduler = taskScheduler;

			_syncRoot = new object();

			_path = path;
			_searchPattern = searchPattern;
			_searchOption = searchOption;
			_filesByPath = new Dictionary<string, IFileInfo>();
			_files = new IFileInfo[0];

			_task = _taskScheduler.StartPeriodic(Update, maximumLatency, $"FilesystemWatcher({path})");
		}

		#region Implementation of IDisposable

		public void Dispose()
		{
			_taskScheduler.StopPeriodic(_task);
			_filesystemWatchdog.StopDirectoryWatch(this);
		}

		#endregion

		private void Update()
		{
			EnumerateOnce();
		}

		private void EnumerateOnce()
		{
			var filePaths = EnumerateFiles();
			Synchronize(filePaths);
		}

		[Pure]
		private IReadOnlyList<string> EnumerateFiles()
		{
			try
			{
				return _filesystem.EnumerateFiles(_path,
				                                  _searchPattern,
				                                  _searchOption,
				                                  tolerateNonExistantPath: true);
			}
			catch (IOException e)
			{
				Log.DebugFormat("Caught exception: {0}", e);
				return new string[0];
			}
			catch (Exception e)
			{
				Log.ErrorFormat("Caught unexpected exception: {0}", e);
				return new string[0];
			}
		}

		private void Synchronize(IReadOnlyList<string> filePaths)
		{
			bool changed = false;

			lock (_syncRoot)
			{
				foreach (var path in filePaths)
				{
					if (!_filesByPath.ContainsKey(path))
					{
						_filesByPath.Add(path, _filesystem.GetFileInfo(path));
						changed = true;
					}
				}

				foreach (var path in _filesByPath.Keys.ToList())
				{
					if (!filePaths.Contains(path))
					{
						_filesByPath.Remove(path);
						changed = true;
					}
				}

				if (changed)
				{
					_files = _filesByPath.Values.ToList();
				}
			}

			if (changed)
				EmitChanged();
		}

		private void EmitChanged()
		{
			try
			{
				Changed?.Invoke();
			}
			catch (Exception e)
			{
				Log.ErrorFormat("Caught unexpected exception: {0}", e);
			}
		}

		#region Implementation of IFilesystemWatcher

		public IEnumerable<IFileInfo> Files
		{
			get { return _files; }
		}

		public string Path
		{
			get { return _path; }
			set
			{
				_path = value;
				EnumerateOnce();
			}
		}

#pragma warning disable 67
		public event Action Changed;
#pragma warning restore 67

		#endregion
	}
}


text:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Class Audit_model.
 *
 * Model to help interact with audits table in database.
 */
class Audit_model extends CI_Model
{
    /**
     * @var string
     */
    private $table;

    /**
     * Audit_model constructor.
     */
    function __construct()
    {
        parent::__construct();
        $this->table = 'audits';
    }

    /**
     * Retrieve the registration and login history of the user from the database table
     * based on the given id of user.
     *
     * @param $idUser
     * @param int $currentPage
     * @param int $resultsPerPage
     * @return array
     */
    function get_audit_by_id_user($idUser, $currentPage = 0, $resultsPerPage = 0)
    {
        $offset = 0;
        $limit = $resultsPerPage;
        if ($currentPage && $resultsPerPage) {
            if ($currentPage >= 1) {
                $offset = $currentPage * $resultsPerPage;
            }
        }

        $this->db->where('id_user', $idUser);
        $this->db->order_by('id_audit', 'desc');

        if ($offset && $limit) {
            $this->db->limit($offset, $limit);
        } else if ($limit) {
            $this->db->limit($limit);
        }

        $query = $this->db->get($this->table);

        return $query->result();
    }

    /**
     * Counts the number of rows in the database table for both registration and login history of the
     * user based on the given id of user.
     *
     * @param $idUser
     * @return int
     */
    function get_audit_count_by_id_user($idUser)
    {
        $this->db->from($this->table);
        $this->db->where('id_user', $idUser);
        $count = $this->db->count_all_results();

        return $count;
    }

    /**
     * Store the audit information in the database table as is.
     *
     * @param $data
     * @return bool
     */
    function save_audit($data)
    {
        return $this->db->insert($this->table, $data);
    }
}


text:
package org.neo4j.driver.internal;

import java.util.Collection;
import java.util.Map;

import org.neo4j.driver.Entity;
import org.neo4j.driver.Identity;
import org.neo4j.driver.Value;

public abstract class SimpleEntity implements Entity
{
    private final Identity id;
    private final Map<String,Value> properties;

    public SimpleEntity( Identity id, Map<String,Value> properties )
    {
        this.id = id;
        this.properties = properties;
    }

    @Override
    public Identity identity()
    {
        return id;
    }

    @Override
    public Collection<String> propertyKeys()
    {
        return properties.keySet();
    }

    @Override
    public Value property( String key )
    {
        return properties.get( key );
    }

    @Override
    public int propertyCount()
    {
        return properties.size();
    }

    @Override
    public boolean equals( Object o )
    {
        if ( this == o )
        {
            return true;
        }
        if ( o == null || getClass() != o.getClass() )
        {
            return false;
        }

        SimpleEntity that = (SimpleEntity) o;

        return id.equals( that.id );

    }

    @Override
    public int hashCode()
    {
        return id.hashCode();
    }

    @Override
    public String toString()
    {
        return "Entity{" +
               "id=" + id +
               ", properties=" + properties +
               '}';
    }
}


text:
<project xmlns:ivy="antlib:org.apache.ivy.ant" basedir="." name="common-lib" default="build">
	<property file="build.properties"/>
	<property file="../branch.properties"/>
    <property file="${build-infrastructure.dir}/common.properties" />

	<import file="${build-infrastructure.dir}/build-common.xml"/>
</project>


text:
<?php

namespace Google\Service\Dfareporting;

class CreativeGroup extends \Google\Model
{
  /**
   * @var string
   */
  public $accountId;
  /**
   * @var string
   */
  public $advertiserId;
  protected $advertiserIdDimensionValueType = DimensionValue::class;
  protected $advertiserIdDimensionValueDataType = '';
  /**
   * @var int
   */
  public $groupNumber;
  /**
   * @var string
   */
  public $id;
  /**
   * @var string
   */
  public $kind;
  /**
   * @var string
   */
  public $name;
  /**
   * @var string
   */
  public $subaccountId;

  /**
   * @param string
   */
  public function setAccountId($accountId)
  {
    $this->accountId = $accountId;
  }
  /**
   * @return string
   */
  public function getAccountId()
  {
    return $this->accountId;
  }
  /**
   * @param string
   */
  public function setAdvertiserId($advertiserId)
  {
    $this->advertiserId = $advertiserId;
  }
  /**
   * @return string
   */
  public function getAdvertiserId()
  {
    return $this->advertiserId;
  }
  /**
   * @param DimensionValue
   */
  public function setAdvertiserIdDimensionValue(DimensionValue $advertiserIdDimensionValue)
  {
    $this->advertiserIdDimensionValue = $advertiserIdDimensionValue;
  }
  /**
   * @return DimensionValue
   */
  public function getAdvertiserIdDimensionValue()
  {
    return $this->advertiserIdDimensionValue;
  }
  /**
   * @param int
   */
  public function setGroupNumber($groupNumber)
  {
    $this->groupNumber = $groupNumber;
  }
  /**
   * @return int
   */
  public function getGroupNumber()
  {
    return $this->groupNumber;
  }
  /**
   * @param string
   */
  public function setId($id)
  {
    $this->id = $id;
  }
  /**
   * @return string
   */
  public function getId()
  {
    return $this->id;
  }
  /**
   * @param string
   */
  public function setKind($kind)
  {
    $this->kind = $kind;
  }
  /**
   * @return string
   */
  public function getKind()
  {
    return $this->kind;
  }
  /**
   * @param string
   */
  public function setName($name)
  {
    $this->name = $name;
  }
  /**
   * @return string
   */
  public function getName()
  {
    return $this->name;
  }
  /**
   * @param string
   */
  public function setSubaccountId($subaccountId)
  {
    $this->subaccountId = $subaccountId;
  }
  /**
   * @return string
   */
  public function getSubaccountId()
  {
    return $this->subaccountId;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(CreativeGroup::class, 'Google_Service_Dfareporting_CreativeGroup');


text:
<?php if (!wfConfig::get('isPaid')) { ?>

Scan Scheduling is only available to Premium Members

Premium users can increase their WordPress protection by controlling scan frequency up to once per hour. Premium also allows you to control when Wordfence initiates a scan, selecting optimal times that don't interfere with high-traffic or optimal usage of your site.

Upgrade today:

Receive real-time Firewall and Scan engine rule updates for protection as threats emerge

Other advanced features like IP reputation monitoring, an advanced comment spam filter, country blocking and cell phone sign-in give you the best protection available

Access to Premium Support

Discounts of up to 90% available for multiyear and multi-license purchases

Get Premium

<?php } ?>

			<div class="wf-card wf-card-left<?php echo (wfScan::isAutoScanSchedule() ? ' active' : ''); ?>" data-mode="auto">

							Let Wordfence automatically schedule scans (recommended)

							<?php if (wfScan::isAutoScanSchedule()) : ?>
								<?php echo wordfence::getNextScanStartTime(); ?>
							<?php endif; ?>

						<div class="wf-card-action-checkbox<?php echo (wfScan::isAutoScanSchedule() ? ' checked' : ''); ?>">

			<div class="wf-card wf-card-left<?php echo (wfScan::isManualScanSchedule() ? ' active' : ''); ?><?php if (!wfConfig::get('isPaid')) { echo ' disabled'; } ?>" data-mode="manual">

							Manually schedule scans<?php if (!wfConfig::get('isPaid')) { echo ' (Premium Members Only)'; } ?>

							<?php if (wfScan::isManualScanSchedule()) : ?>
								<?php echo wordfence::getNextScanStartTime(); ?>
							<?php endif; ?>

						<div class="wf-card-action-checkbox<?php echo (wfScan::isManualScanSchedule() ? ' checked' : ''); ?>">

							Shortcuts

							Shortcuts

								<button type="button" class="wf-btn wf-btn-primary scan-shortcut" data-shortcut="onceDaily">Once per day</button> <button type="button" class="wf-btn wf-btn-primary scan-shortcut" data-shortcut="twiceDaily">Twice per day</button> <button type="button" class="wf-btn wf-btn-primary scan-shortcut" data-shortcut="weekends">Weekends</button> <button type="button" class="wf-btn wf-btn-primary scan-shortcut" data-shortcut="oddDaysWE">Odd days and weekends</button> <button type="button" class="wf-btn wf-btn-primary scan-shortcut" data-shortcut="every6hours">Every 6 hours</button>

						<?php
						$daysOfWeek = array(
							array(1, 'Monday'),
							array(2, 'Tuesday'),
							array(3, 'Wednesday'),
							array(4, 'Thursday'),
							array(5, 'Friday'),
							array(6, 'Saturday'),
							array(0, 'Sunday')
						);
						$sched = wfConfig::get_ser('scanSched', array());
						foreach ($daysOfWeek as $d) :
							list($dayNumber, $dayName) = $d;
							?>

								<?php echo $dayName; ?>

							<tr class="schedule-day" data-day="<?php echo $dayNumber; ?>">
								<?php echo $dayName; ?>

AM

AM

											<?php
											for ($h = 0; $h < 12; $h++) {
												$active = (isset($sched[$dayNumber]) && $sched[$dayNumber][$h] ? ' active' : '');
												echo '
' . str_pad($h, 2, '0', STR_PAD_LEFT) . '
';
											}
											?>

PM

PM

											<?php
											for ($i = 0; $i < 12; $i++) {
												$h = $i;
												if ($h == 0) { $h = 12; }
												$active = (isset($sched[$dayNumber]) && $sched[$dayNumber][$i + 12] ? ' active' : '');
												echo '
' . str_pad($h, 2, '0', STR_PAD_LEFT) . '
';
											}
											?>

						<?php endforeach; ?>


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Armeria documentation service</title>
  <link href="assets/css/vendor/bootstrap-3.3.5.min.css" rel="stylesheet">
  <link href="assets/css/vendor/highlight-jsononly-github-8.9.1.min.css" rel="stylesheet">
  <link href="assets/css/armeria.css" rel="stylesheet">

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar"
              aria-expanded="false" aria-controls="navbar">
        Toggle navigation

      </button>
      Armeria documentation service

Welcome to the Armeria documentation service

          This page provides the information about the RPC services and its related data types in this server.

Please start to navigate via the sidebar on the left or the menu button on the top right.


text:
<?php
namespace ide\formats\form;

use ide\editors\value\ElementPropertyEditor;
use ide\editors\value\SimpleTextPropertyEditor;
use php\io\File;
use InvalidArgumentException;
use php\lib\Items;
use php\lib\Str;
use php\xml\DomDocument;
use php\xml\DomElement;
use php\xml\XmlProcessor;
use php\io\Stream;

/**
 * Class FormElementConfig
 * @package ide\formats\form
 */
class FormElementConfig
{
    /**
     * @var FormElementConfig[]
     */
    protected static $cache = [];

    /**
     * @var DomDocument
     */
    protected $document;

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

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

    /**
     * @var FormElementConfig
     */
    protected $parent;

    /********* ... *********/

    /**
     * @var array
     */
    protected $initProperties = [];

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

    /**
     * @var array
     */
    protected $properties = [];

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

    /**
     * @var array
     */
    protected $propertyGroups = [];

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

    /**
     * @var array
     */
    protected $eventTypes = [];

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

    /**
     * FormElementConfig constructor.
     *
     * @param $type
     */
    protected function __construct($type)
    {
        if (!Str::contains($type, '\\')) {
            $type = __NAMESPACE__ . '\\elements\\' . $type;
        }

        $file = 'res://' . Str::replace($type, '\\', '/') . '.xml';

        if (!Stream::exists($file)) {
            throw new InvalidArgumentException("XmlFileName($file) file is not exists");
        }

        $this->filename = $type;

        Stream::tryAccess($file, function (Stream $stream) {
            $processor = new XmlProcessor();
            $this->document = $processor->parse($stream);

            $this->readDocument();
        });
    }

    /**
     * @param $type
     *
     * @return FormElementConfig|null null if not exists
     */
    public static function of($type)
    {
        if ($instance = self::$cache[$type]) {
            return $instance;
        }

        try {
            return self::$cache[$type] = new FormElementConfig($type);
        } catch (InvalidArgumentException $e) {
            return null;
        }
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @return string
     */
    public function getFilename()
    {
        return $this->filename;
    }

    /**
     * @return bool
     */
    public function hasParent()
    {
        return !!$this->parent;
    }

    /**
     * @return FormElementConfig
     */
    public function getParent()
    {
        return $this->parent;
    }

    /**
     * @return array [code, value, virtual: bool]
     */
    public function getInitProperties()
    {
        return $this->allInitProperties;
    }

    /**
     * @return array [code, name, group, editor: object]
     */
    public function getProperties()
    {
        return $this->allProperties;
    }

    /**
     * @return array [code, title]
     */
    public function getPropertyGroups()
    {
        return $this->allPropertyGroups;
    }

    public function getEventTypes()
    {
        return $this->allEventTypes;
    }

    protected function readDocument()
    {
        $extends = $this->document->get('/element/@extends');

        // extends.
        if ($extends) {
            $this->parent = FormElementConfig::of($extends);

            if ($this->parent == null) {
                throw new \Exception("Unable to find the 'extends' config of - $extends");
            }
        }

        $this->readInitPropertiesFromDocument();
        $this->readPropertiesFromDocument();
        $this->readEventTypesFromDocument();

        $this->processParents();
    }

    protected function processParents()
    {
        $tree = [$this];
        $one = $this;

        while ($one->parent) {
            $tree[] = $one->parent;
            $one = $one->parent;
        }

        $eventTypes = [];

        /** @var FormElementConfig $one */
        foreach ($tree as $one) {
            foreach ($one->eventTypes as $code => $eventType) {
                $eventTypes[$code] = $eventType;
            }
        }

        $tree = Items::reverse($tree);

        $initProperties = [];

        /** @var FormElementConfig $one */
        foreach ($tree as $one) {
            foreach ($one->initProperties as $code => $property) {
                $initProperties[$code] = $property;
            }
        }

        $properties = [];

        foreach ($tree as $one) {
            foreach ($one->properties as $code => $property) {
                $properties[$code] = $property;
            }
        }

        $propertyGroups = [];

        foreach ($tree as $one) {
            foreach ($one->propertyGroups as $code => $group) {
                $propertyGroups[$code] = $group;
            }
        }

        $this->allInitProperties = $initProperties;
        $this->allProperties = $properties;
        $this->allPropertyGroups = $propertyGroups;
        $this->allEventTypes = $eventTypes;
    }

    protected function readInitPropertiesFromDocument()
    {
        // init properties
        foreach ($this->document->findAll('/element/init/property') as $property) {
            $code = $property->getAttribute('code');

            if (!$code) {
                throw new \Exception("Init property must have the 'code' value");
            }

            $this->initProperties[$code] = [
                'code'    => $code,
                'value'   => $property->getAttribute('value'),
                'virtual' => (bool)$property->getAttribute('virtual'),
            ];
        }
    }

    protected function readPropertiesFromDocument()
    {
        /** @var DomElement $groupProperties */
        foreach ($this->document->findAll('/element/properties') as $groupProperties) {
            $group = 'general';

            if ($groupProperties->hasAttribute('group')) {
                $group = $groupProperties->getAttribute('group');

                $this->propertyGroups[$group] = [
                    'code'  => $group,
                    'title' => $groupProperties->getAttribute('title'),
                ];
            }

            foreach ($groupProperties->findAll('property') as $property) {
                $code = $property->getAttribute('code');
                $name = $property->getAttribute('name');

                $editorFactory = function () use ($property) {
                    if ($property->hasAttribute('editor')) {
                        if ($property->getAttribute('editor') == 'none') {
                            $editor = null;
                        } else {
                            $editor = ElementPropertyEditor::getByCode($property->getAttribute('editor'))->unserialize($property);
                        }
                    } else {
                        $editor = (new SimpleTextPropertyEditor())->unserialize($property);
                    }

                    if ($editor) {
                        if ($property->getAttribute('virtual')) {
                            $editor->setAsDataProperty();
                        }

                        if ($property->getAttribute('css')) {
                            $editor->setAsCssProperty();
                        }

                        if ($property->getAttribute('formConfig')) {
                            $editor->setAsFormConfigProperty($property->getAttribute('defaultValue'));
                        }

                        $editor->setTooltip($property->getAttribute('tooltip'));
                    }

                    return $editor;
                };

                if (!$group) {
                    $group = 'general';
                }

                $this->properties[$code] = [
                    'code'          => $code,
                    'group'         => $group,
                    'name'          => $name,
                    'editorFactory' => $editorFactory,
                ];
            }
        }
    }

    protected function readEventTypesFromDocument()
    {
        /** @var DomElement $eventType */
        foreach ($this->document->findAll("/element/eventTypes/eventType") as $eventType) {
            $code = $eventType->getAttribute('code');
            $name = $eventType->getAttribute('name');
            $description = $eventType->getAttribute('description');

            $icon = $eventType->getAttribute('icon');
            $kind = $eventType->getAttribute('kind');

            $kind = "ide\\formats\\form\\event\\{$kind}Kind";

            $kind = new $kind();

            $this->eventTypes[$code] = [
                'code'        => $code,
                'name'        => $name,
                'description' => $description,
                'icon'        => $icon,
                'kind'        => $kind,
            ];
        }
    }
}


text:
package set

import (
	"encoding/json"
	"fmt"
	"io"
	"os"
	"strings"

	"github.com/spf13/cobra"
	kapi "k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/kubectl"
	kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
	"k8s.io/kubernetes/pkg/kubectl/resource"
	"k8s.io/kubernetes/pkg/util/strategicpatch"

	cmdutil "github.com/openshift/origin/pkg/cmd/util"
	"github.com/openshift/origin/pkg/cmd/util/clientcmd"
)

const (
	envLong = `
Update environment variables on a pod template or a build config

List environment variable definitions in one or more pods, pod templates or build
configuration.
Add, update, or remove container environment variable definitions in one or
more pod templates (within replication controllers or deployment configurations) or
build configurations.
View or modify the environment variable definitions on all containers in the
specified pods or pod templates, or just those that match a wildcard.

If "--env -" is passed, environment variables can be read from STDIN using the standard env
syntax.`

	envExample = `  # Update deployment 'registry' with a new environment variable
  $ %[1]s env dc/registry STORAGE_DIR=/local

  # List the environment variables defined on a build config 'sample-build'
  $ %[1]s env bc/sample-build --list

  # List the environment variables defined on all pods
  $ %[1]s env pods --all --list

  # Output modified build config in YAML, and does not alter the object on the server
  $ %[1]s env bc/sample-build STORAGE_DIR=/data -o yaml

  # Update all containers in all replication controllers in the project to have ENV=prod
  $ %[1]s env rc --all ENV=prod

  # Remove the environment variable ENV from container 'c1' in all deployment configs
  $ %[1]s env dc --all --containers="c1" ENV-

  # Remove the environment variable ENV from a deployment config definition on disk and
  # update the deployment config on the server
  $ %[1]s env -f dc.json ENV-

  # Set some of the local shell environment into a deployment config on the server
  $ env | grep RAILS_ | %[1]s env -e - dc/registry`
)

// NewCmdEnv implements the OpenShift cli env command
func NewCmdEnv(fullName string, f *clientcmd.Factory, in io.Reader, out io.Writer) *cobra.Command {
	var filenames []string
	var env []string
	cmd := &cobra.Command{
		Use:     "env RESOURCE/NAME KEY_1=VAL_1 ... KEY_N=VAL_N",
		Short:   "Update environment variables on a pod template",
		Long:    envLong,
		Example: fmt.Sprintf(envExample, fullName),
		Run: func(cmd *cobra.Command, args []string) {
			err := RunEnv(f, in, out, cmd, args, env, filenames)
			if err == cmdutil.ErrExit {
				os.Exit(1)
			}
			kcmdutil.CheckErr(err)
		},
	}
	cmd.Flags().StringP("containers", "c", "*", "The names of containers in the selected pod templates to change - may use wildcards")
	cmd.Flags().StringSliceVarP(&env, "env", "e", env, "Specify key value pairs of environment variables to set into each container.")
	cmd.Flags().Bool("list", false, "Display the environment and any changes in the standard format")
	cmd.Flags().StringP("selector", "l", "", "Selector (label query) to filter on")
	cmd.Flags().Bool("all", false, "Select all resources in the namespace of the specified resource types")
	cmd.Flags().StringSliceVarP(&filenames, "filename", "f", filenames, "Filename, directory, or URL to file to use to edit the resource.")
	cmd.Flags().Bool("overwrite", true, "If true, allow environment to be overwritten, otherwise reject updates that overwrite existing environment.")
	cmd.Flags().String("resource-version", "", "If non-empty, the labels update will only succeed if this is the current resource-version for the object. Only valid when specifying a single resource.")
	cmd.Flags().StringP("output", "o", "", "Display the changed objects instead of updating them. One of: json|yaml.")
	cmd.Flags().String("output-version", "", "Output the changed objects with the given version (default api-version).")

	cmd.MarkFlagFilename("filename", "yaml", "yml", "json")

	return cmd
}

func validateNoOverwrites(meta *kapi.ObjectMeta, labels map[string]string) error {
	for key := range labels {
		if value, found := meta.Labels[key]; found {
			return fmt.Errorf("'%s' already has a value (%s), and --overwrite is false", key, value)
		}
	}
	return nil
}

// RunEnv contains all the necessary functionality for the OpenShift cli env command
// TODO: refactor to share the common "patch resource" pattern of probe
func RunEnv(f *clientcmd.Factory, in io.Reader, out io.Writer, cmd *cobra.Command, args []string, envParams, filenames []string) error {
	resources, envArgs, ok := cmdutil.SplitEnvironmentFromResources(args)
	if !ok {
		return kcmdutil.UsageError(cmd, "all resources must be specified before environment changes: %s", strings.Join(args, " "))
	}
	if len(filenames) == 0 && len(resources) < 1 {
		return kcmdutil.UsageError(cmd, "one or more resources must be specified as <resource> <name> or <resource>/<name>")
	}

	containerMatch := kcmdutil.GetFlagString(cmd, "containers")
	list := kcmdutil.GetFlagBool(cmd, "list")
	selector := kcmdutil.GetFlagString(cmd, "selector")
	all := kcmdutil.GetFlagBool(cmd, "all")
	//overwrite := kcmdutil.GetFlagBool(cmd, "overwrite")
	resourceVersion := kcmdutil.GetFlagString(cmd, "resource-version")
	outputFormat := kcmdutil.GetFlagString(cmd, "output")

	if list && len(outputFormat) > 0 {
		return kcmdutil.UsageError(cmd, "--list and --output may not be specified together")
	}

	clientConfig, err := f.ClientConfig()
	if err != nil {
		return err
	}

	cmdNamespace, explicit, err := f.DefaultNamespace()
	if err != nil {
		return err
	}

	env, remove, err := cmdutil.ParseEnv(append(envParams, envArgs...), in)
	if err != nil {
		return err
	}

	mapper, typer := f.Object(false)
	b := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), kapi.Codecs.UniversalDecoder()).
		ContinueOnError().
		NamespaceParam(cmdNamespace).DefaultNamespace().
		FilenameParam(explicit, false, filenames...).
		SelectorParam(selector).
		ResourceTypeOrNameArgs(all, resources...).
		Flatten()

	one := false
	infos, err := b.Do().IntoSingular(&one).Infos()
	if err != nil {
		return err
	}

	// only apply resource version locking on a single resource
	if !one && len(resourceVersion) > 0 {
		return kcmdutil.UsageError(cmd, "--resource-version may only be used with a single resource")
	}
	// Keep a copy of the original objects prior to updating their environment.
	// Used in constructing the patch(es) that will be applied in the server.
	oldObjects, err := resource.AsVersionedObjects(infos, clientConfig.GroupVersion.String(), kapi.Codecs.LegacyCodec(*clientConfig.GroupVersion))
	if err != nil {
		return err
	}
	if len(oldObjects) != len(infos) {
		return fmt.Errorf("could not convert all objects to API version %q", clientConfig.GroupVersion)
	}
	oldData := make([][]byte, len(infos))
	for i := range oldObjects {
		old, err := json.Marshal(oldObjects[i])
		if err != nil {
			return err
		}
		oldData[i] = old
	}

	skipped := 0
	for _, info := range infos {
		ok, err := f.UpdatePodSpecForObject(info.Object, func(spec *kapi.PodSpec) error {
			containers, _ := selectContainers(spec.Containers, containerMatch)
			if len(containers) == 0 {
				fmt.Fprintf(cmd.Out(), "warning: %s/%s does not have any containers matching %q\n", info.Mapping.Resource, info.Name, containerMatch)
				return nil
			}
			for _, c := range containers {
				c.Env = updateEnv(c.Env, env, remove)

				if list {
					fmt.Fprintf(out, "# %s %s, container %s\n", info.Mapping.Resource, info.Name, c.Name)
					for _, env := range c.Env {
						// if env.ValueFrom != nil && env.ValueFrom.FieldRef != nil {
						// 	fmt.Fprintf(cmd.Out(), "%s= # calculated from pod %s %s\n", env.Name, env.ValueFrom.FieldRef.FieldPath, env.ValueFrom.FieldRef.APIVersion)
						// 	continue
						// }
						fmt.Fprintf(out, "%s=%s\n", env.Name, env.Value)

					}
				}
			}
			return nil
		})
		if !ok {
			// This is a fallback function for objects that don't have pod spec.
			ok, err = f.UpdateObjectEnvironment(info.Object, func(vars *[]kapi.EnvVar) error {
				if vars == nil {
					return fmt.Errorf("no environment variables provided")
				}
				*vars = updateEnv(*vars, env, remove)
				if list {
					fmt.Fprintf(out, "# %s %s\n", info.Mapping.Resource, info.Name)
					for _, env := range *vars {
						fmt.Fprintf(out, "%s=%s\n", env.Name, env.Value)
					}
				}
				return nil
			})
			if !ok {
				skipped++
				continue
			}
		}
		if err != nil {
			fmt.Fprintf(cmd.Out(), "error: %s/%s %v\n", info.Mapping.Resource, info.Name, err)
			continue
		}
	}
	if one && skipped == len(infos) {
		return fmt.Errorf("%s/%s is not a pod or does not have a pod template", infos[0].Mapping.Resource, infos[0].Name)
	}

	if list {
		return nil
	}

	if len(outputFormat) != 0 {
		outputVersion, err := kcmdutil.OutputVersion(cmd, clientConfig.GroupVersion)
		if err != nil {
			return err
		}
		objects, err := resource.AsVersionedObjects(infos, outputVersion.String(), kapi.Codecs.LegacyCodec(outputVersion))
		if err != nil {
			return err
		}
		if len(objects) != len(infos) {
			return fmt.Errorf("could not convert all objects to API version %q", outputVersion)
		}
		p, _, err := kubectl.GetPrinter(outputFormat, "")
		if err != nil {
			return err
		}
		for _, object := range objects {
			if err := p.PrintObj(object, out); err != nil {
				return err
			}
		}
		return nil
	}

	objects, err := resource.AsVersionedObjects(infos, clientConfig.GroupVersion.String(), kapi.Codecs.LegacyCodec(*clientConfig.GroupVersion))
	if err != nil {
		return err
	}
	if len(objects) != len(infos) {
		return fmt.Errorf("could not convert all objects to API version %q", clientConfig.GroupVersion)
	}

	failed := false
	for i, info := range infos {
		newData, err := json.Marshal(objects[i])
		if err != nil {
			return err
		}
		patchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData[i], newData, objects[i])
		if err != nil {
			return err
		}
		obj, err := resource.NewHelper(info.Client, info.Mapping).Patch(info.Namespace, info.Name, kapi.StrategicMergePatchType, patchBytes)
		if err != nil {
			handlePodUpdateError(cmd.Out(), err, "environment variables")
			failed = true
			continue
		}
		info.Refresh(obj, true)

		shortOutput := kcmdutil.GetFlagString(cmd, "output") == "name"
		kcmdutil.PrintSuccess(mapper, shortOutput, out, info.Mapping.Resource, info.Name, "updated")
	}
	if failed {
		return cmdutil.ErrExit
	}
	return nil
}


text:
StatisticsWindow::StatisticsWindow(const PatternViewMap &patterns, QWidget *parent):QDialog(parent)
{
    table = new QTableWidget(this);
    QHBoxLayout* l = new QHBoxLayout(this);
    setModal(true);
    table->setColumnCount(4);
    setWindowTitle("Statistics");
    table->setRowCount(patterns.keys().length());
    QStringList header;
    header<<"Имя"<<"Отрезков"<<"Сопоставлений" << "Вариантов";
    table->setHorizontalHeaderLabels(header);
    table->verticalHeader()->hide();
    table->setEditTriggers(QAbstractItemView::NoEditTriggers);
    table->setContentsMargins(5,5,5,5);
    l->addWidget(table);
    setLayout(l);
    fillTable(patterns);

    resizeToFit();
}

StatisticsWindow::StatisticsWindow(QSharedPointer<utility::IntervalViewMap> data, QWidget *parent):QDialog(parent)
{
    table = new QTableWidget(this);
    table->setSelectionBehavior(QAbstractItemView::SelectRows);
    QHBoxLayout* l = new QHBoxLayout(this);
    l->setStretch(0,1);
    setModal(true);
    table->setColumnCount(4);
    setWindowTitle("Статистика сопоставлений");
    QStringList header;
    header<<"Имя"<<"Отрезков"<<"Сопоставлений" << "Вариантов";
    table->setHorizontalHeaderLabels(header);
    table->horizontalHeader()->setStretchLastSection(true);
    table->verticalHeader()->hide();
    table->setEditTriggers(QAbstractItemView::NoEditTriggers);
    table->setContentsMargins(5,5,5,5);
    table->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
    l->addWidget(table);
    setLayout(l);
    fillTable(data);

}

void StatisticsWindow::resizeEvent(QResizeEvent *e)
{
    QDialog::resizeEvent(e);
}

void StatisticsWindow::fillTable(const PatternViewMap &patterns)
{
    QStringList keys = patterns.keys();
    for(int i = 0; i < keys.length();++i){
        table->setItem(i,0,new QTableWidgetItem(keys[i]));
        table->setItem(i,1,new QTableWidgetItem(QString::number(patterns[keys[i]].length())));
        table->setItem(i,2,new QTableWidgetItem(QString::number(patterns[keys[i]].length())));
        table->setItem(i,3,new QTableWidgetItem(QString::number(countVariants(patterns[keys[i]]))));
    }
}

void StatisticsWindow::fillTable(QSharedPointer<utility::IntervalViewMap> data)
{
    QMap<QString,PatternStats> result;
    int segments = 0;
    int matches = 0;
    int variants = 0;
    for(utility::IntervalViewMap::iterator it = data->begin();it != data->end();++it){
        utility::IntervalMatch m = it->value;
        for(int i = 0 ;i <m.patterns.size();++i){
            if(result.contains(m.patterns[i])){
                result[m.patterns[i]].segments++;
                result[m.patterns[i]].variants+=m.variants[i];
            }else {
                result[m.patterns[i]] = {1,m.variants[i]};
            }

            variants+=m.variants[i];
        }
        segments++;
        matches+=m.patterns.size();
    }
    int i = 0;
    table->setRowCount(result.size()+1);
    for(const QString&val:result.keys()){
        table->setItem(i,0,new QTableWidgetItem(val));
        PatternStats stats = result[val];
        table->setItem(i,1,new QTableWidgetItem(QString::number(stats.segments)));
        table->setItem(i,2,new QTableWidgetItem(QString::number(stats.segments)));
        table->setItem(i,3,new QTableWidgetItem(QString::number(stats.variants)));
        i++;
    }
    table->setItem(i,0,new QTableWidgetItem("Всего"));
    table->setItem(i,1,new QTableWidgetItem(QString::number(segments)));
    table->setItem(i,2,new QTableWidgetItem(QString::number(matches)));
    table->setItem(i,3,new QTableWidgetItem(QString::number(variants)));
    table->resizeRowsToContents();
    table->resizeColumnsToContents();
}

int StatisticsWindow::countVariants(const QVector<PatternCompiler::MatchRepr> &vect)
{
    int sum = 0;
    for(int i = 0 ; i< vect.size();++i){
        sum+= vect[i].variants;
    }
    return sum;
}

void StatisticsWindow::resizeToFit()
{

    table->resizeColumnsToContents();
    table->resizeRowsToContents();
    int w = table->horizontalHeader()->width()+4;
    for (int i = 0; i < table->columnCount(); i++){
        w += table->columnWidth(i);
    }
    int h = table->verticalHeader()->height()+4;
    for (int i = 0; i < table->rowCount(); i++){
       h += table->rowHeight(i);
    }
    resize(w,h);
}


text:
package org.finos.waltz.jobs.generators;

import org.finos.waltz.common.RandomUtilities;
import org.finos.waltz.model.EntityKind;
import org.finos.waltz.model.physical_specification.DataFormatKind;
import org.finos.waltz.schema.tables.records.PhysicalSpecificationRecord;
import org.jooq.DSLContext;
import org.springframework.context.ApplicationContext;

import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static org.finos.waltz.common.DateTimeUtilities.nowUtcTimestamp;
import static org.finos.waltz.common.RandomUtilities.randomPick;
import static org.finos.waltz.schema.tables.PhysicalSpecification.PHYSICAL_SPECIFICATION;
import static org.jooq.lambda.tuple.Tuple.tuple;

public class PhysicalSpecificationGenerator implements SampleDataGenerator {

    private static final Random rnd = RandomUtilities.getRandom();

    private static String[] names = {
            "trade",
            "report",
            "risk",
            "ratings",
            "eod",
            "intra-day",
            "yyymmdd",
            "finance",
            "accounting",
            "balance",
            "agg",
            "holdings",
            "accruals",
            "debit",
            "credit",
            "currency",
            "regulatory",
            "transactions",
            "transfers",
            "exchange",
            "summary",
            "daily",
            "position",
            "settlement",
            "confirms",
            "confirmation"
    };

    private static String[] extensions = {
            "xls",
            "txt",
            "csv",
            "tsv",
            "psv",
            "md",
            "bin",
            "xml",
            "json",
            "yaml",
            "yml",
            "pdf",
            "rtf",
            "doc"
    };

    private static String mkName(Integer i) {

        return new StringBuilder()
                .append(randomPick(names))
                .append("-")
                .append(randomPick(names))
                .append("-")
                .append(i)
                .append(".")
                .append(randomPick(extensions))
                .toString();
    }

    @Override
    public Map<String, Integer> create(ApplicationContext ctx) {
        DSLContext dsl = getDsl(ctx);

        List<Long> appIds = getAppIds(dsl);

        List<PhysicalSpecificationRecord> records = appIds
                .stream()
                .flatMap(appId -> IntStream
                        .range(0, rnd.nextInt(4))
                        .mapToObj(i -> tuple(appId, i)))
                .map(t -> {
                    String name = mkName(t.v2);
                    PhysicalSpecificationRecord record = dsl.newRecord(PHYSICAL_SPECIFICATION);
                    record.setOwningEntityId(t.v1);
                    record.setOwningEntityKind(EntityKind.APPLICATION.name());
                    record.setFormat(randomPick(DataFormatKind.values()).name());
                    record.setProvenance(SAMPLE_DATA_PROVENANCE);
                    record.setDescription("Desc "+ name + " " + t.v2);
                    record.setName(name);
                    record.setExternalId("ext-" + t.v1 + "." + t.v2);
                    record.setLastUpdatedBy("admin");
                    record.setCreatedBy("admin");
                    record.setCreatedAt(nowUtcTimestamp());
                    return record;
                })
                .collect(Collectors.toList());

        log("---saving: "+records.size());
        dsl.batchInsert(records).execute();
        log("---done");
        return null;
    }

    @Override
    public boolean remove(ApplicationContext ctx) {
        DSLContext dsl = getDsl(ctx);

        log("---deleting old demo records");
        dsl.deleteFrom(PHYSICAL_SPECIFICATION)
                .where(PHYSICAL_SPECIFICATION.PROVENANCE.eq(SAMPLE_DATA_PROVENANCE))
                .execute();
        return false;
    }
}


text:
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ATPTennisStat.ConsoleClient.Core.Contracts;
using Bytes2you.Validation;
using ATPTennisStat.PostgreSqlData;
using System;

namespace ATPTennisStat.ConsoleClient.Core.Commands.TicketCommands
{
    public class BuyTicketsCommand : ICommand
    {
        protected readonly IPostgresDataProvider dp;
        private IWriter writer;

        public BuyTicketsCommand(IPostgresDataProvider dp, IWriter writer)
        {
            if (dp == null)
            {
                throw new ArgumentNullException("Data provider cannot be null!");
            }

            if (writer == null)
            {
                throw new ArgumentNullException("Writer cannot be null!");
            }

            this.dp = dp;
            this.writer = writer;
        }

        public string Execute()
        {
            throw new ArgumentException("You need to pass a parameter to this command");
        }

        public string Execute(IList<string> parameters)
        {

            if (parameters.Count == 0)
            {
                return this.Execute();
            }

            else
            {
                this.writer.Clear();

                var result = new StringBuilder();
                int ticketId = -1;

                int.TryParse(parameters[0], out ticketId);
                Guard.WhenArgument(ticketId, "Incorrect event Id!").IsLessThan(0).Throw();

                var currentTickets = dp.Tickets.GetAllQuerable()
                                    .Where(t => t.Id == ticketId)
                                    .FirstOrDefault();

                if (currentTickets != null)
                {
                    var tennisEventName = dp.TennisEvents.GetAllQuerable()
                                            .Where(te => te.Id == currentTickets.TennisEventId)
                                            .Select(te => te.Name)
                                            .FirstOrDefault();

                    currentTickets.Number--;
                    dp.UnitOfWork.Finished();
                    result.AppendLine($"Successfully bought ticket for {tennisEventName}!");
                }
                else
                {
                    result.AppendLine($"Sorry no tickets with this Id: {ticketId} were found!");
                }

                result.AppendLine("[menu] [alle] [allt] [buyt (id)]");
                return result.ToString();
            }

        }
    }
}


text:
require 'test_helper'

class StaticPagesControllerTest < ActionController::TestCase
  test "should get home" do
    get :home
    assert_response :success
    assert_select "title", "Quiz | Do I Need a PLB?"
  end

  test "should get whowhy" do
    get :whowhy
    assert_response :success
    assert_select "title", "Who Made This | Do I Need a PLB?"
  end

  test "should get satnetworks" do
    get :satnetworks
    assert_response :success
    assert_select "title", "Satellite Networks | Do I Need a PLB?"
  end

  test "should get rescues" do
    get :rescues
    assert_response :success
    assert_select "title", "Rescues | Do I Need a PLB?"
  end

  test "should get comptable" do
    get :comptable
    assert_response :success
    assert_select "title", "Comparison Table | Do I Need a PLB?"
  end

end


text:
function sym(...args) {
  function dedup(array) {
    return array.filter((el, i, arr) => arr.indexOf(el) === i);
  }
  function diffArray(arr1, arr2) {
    return arr1.concat(dedup(arr2)).filter((el, i, arr) => arr.indexOf(el) === arr.lastIndexOf(el));
  }
  return args.reduce(diffArray, []).sort();
}

module.exports = sym;


text:
from .rsync import Rsync
from . import snaplog
from .snaplog import dt_tolocal as dt2lo
import shutil
import json

AUTO_LABELS = {
    "hour" : lambda l,n : dt2lo(l.dt).date() == dt2lo(n.dt).date() and\
                          dt2lo(l.dt).hour == dt2lo(n.dt).hour,
    "day" : lambda l,n : dt2lo(l.dt).date() == dt2lo(n.dt).date(),
    "week" : lambda l,n : dt2lo(l.dt).isocalendar()[:2] == dt2lo(n.dt).isocalendar()[:2],
    "month" : lambda l,n : dt2lo(l.dt).year == dt2lo(n.dt).year and\
                           dt2lo(l.dt).month == dt2lo(n.dt).month,
}
DEFAULT_AUTO_LABELS = ["day","hour"]

class SnapManager(object):
    @staticmethod
    def from_json(filename):
        configs = json.load(open(filename,"r"))

        return SnapManager(configs["snaplog_file"],
                           configs["source_path"],
                           configs["backup_path"],
                           configs["limits"] if "limits" in configs else {},
                           configs["auto_labels"] if "auto_labels" in configs else None,
                           configs)

    # TODO : better __init__ function
    def __init__(self,snaplog_file,source_path,backup_path,limits,auto_labels=None,configs={}):
        self.snaplog_file = snaplog_file
        self.source_path = source_path if isinstance(source_path,list) else [source_path]
        self.backup_path = backup_path
        self.logs = snaplog.Snaplogs(self.snaplog_file)

        self.limits = limits
        self.configs = configs

        if auto_labels== None:
            self.auto_labels = set(DEFAULT_AUTO_LABELS)
        else:
            self.auto_labels = set(auto_labels)

        # configs:check-path
        if "check-path" in self.configs:
            check_path = self.configs["check-path"]
            if isinstance(check_path,list):
                self.check_path = check_path
            else:
                self.check_path = [check_path]
        else:
            self.check_path = None

    def snapshot(self,labels=["node"],auto_write=True):
        prev = self.logs.get_latest("")
        prev_path = prev.path if prev!=None else None
        dt = snaplog.Snaplog.now()
        path = self.backup_path + snaplog.dt_logstr(dt)

        for sp in self.source_path:
            r = Rsync(sp,path,link_dest=prev_path)
            print r.cmd
            r.execute()

        log = snaplog.Snaplog(path,dt,labels)
        self.auto_label(log)
        self.logs.add(log)
        print log

        self.limit_check()
        if auto_write: self.logs.write(self.snaplog_file)
        return log

    def limit_check(self):
        """ check limits after take a snapshot """
        for k,v in self.limits.items():
            if self.logs.count(k) > v:
                removed_log = self.logs.get(k)[0]
                removed_log.labels.remove(k)

                if self.remove(removed_log,check_label=True):
                    print "Remove : "+removed_log.path

    def remove(self,log,check_label=False,rmtree=True):
        """ when check_label and log.labels is not empty ,do nothing """
        if check_label and len(log.labels) != 0:
            return False

        self.logs.remove(log)
        if rmtree:
            shutil.rmtree(log.path)
        return True

    def auto_label(self,log):
        """ label a log automatically with pre-defined condition """
        for label,autolabel in AUTO_LABELS.items():
            if not label in self.auto_labels:
                continue

            latest = self.logs.get_latest(label)

            # check whether the previous log with the same label should be remove
            if latest!=None and latest.dt<=log.dt and autolabel(latest,log):
                unlabel_log = latest
                unlabel_log.labels.remove(label)

                if self.remove(unlabel_log,check_label=True):
                    print "Remove : "+unlabel_log.path

            log.labels.add(label)


text:
{-# LANGUAGE ScopedTypeVariables #-}
module Tct.Trs.Encoding.Interpretation
  where

import Data.Maybe (fromMaybe)
import           Control.Monad                      (liftM)
import qualified Data.Foldable                      as F
import qualified Data.Map.Strict                    as M
import           Data.Monoid                        ((<>))
import qualified Data.Traversable                   as F

import qualified Data.Rewriting.Rule                as R
import           Data.Rewriting.Term                (Term (..))

import qualified Tct.Core.Data as T
import qualified Tct.Core.Common.Pretty             as PP
import qualified Tct.Core.Common.Xml                as Xml

import           Tct.Common.SMT                     as SMT (zero, (.&&), (.=>), (.>))
import qualified Tct.Common.SMT                     as SMT

import           Tct.Trs.Data
import qualified Tct.Trs.Data.Problem               as Prob
import qualified Tct.Trs.Data.RuleSelector          as RS
import qualified Tct.Trs.Data.Signature             as Sig
import qualified Tct.Trs.Data.Rules                 as RS
import qualified Tct.Trs.Encoding.ArgumentFiltering as AFEnc
import qualified Tct.Trs.Encoding.UsablePositions   as UPEnc
import qualified Tct.Trs.Encoding.UsableRules       as UREnc

-- | @interpret fun var term@ interprets @term@.
interpretTerm :: (fun -> [a] -> a) -> (var -> a) -> Term fun var -> a
interpretTerm ifun ivar (Fun f ts) = ifun f (interpretTerm ifun ivar `fmap` ts)
interpretTerm _    ivar (Var a)    = ivar a

newtype Interpretation f a = Interpretation { interpretations :: M.Map f a }
  deriving (Show, Functor, F.Foldable, F.Traversable)

instance (SMT.Decode m c a) => SMT.Decode m (Interpretation fun c) (Interpretation fun a) where
  decode (Interpretation m) = Interpretation `liftM` F.traverse SMT.decode m

-- instance (Applicative m, Monad m) => SMT.Decode m (UPEnc.UsablePositions f) (UPEnc.UsablePositions f) where
--   decode = return

instance (PP.Pretty f, PP.Pretty c)  => PP.Pretty (Interpretation f c) where
  pretty pint = PP.table [(PP.AlignRight, as), (PP.AlignLeft, bs), (PP.AlignLeft,cs)]
    where
      (as,bs,cs) = unzip3 $ map k (M.toList $ interpretations pint)
      k (f,p)    = (PP.text "p" <> PP.parens (PP.pretty f), PP.text " = ", PP.pretty p)

-- | Indicates wether strict oriented rules should be shifted to the weak components or wether all strict rules should be oriented strictly.
-- In the latter case the complexity problem is already solved.
-- @All = Just (selAny selStricts)@ but the encoding is cheaper
data Shift = Shift (ExpressionSelector F V) | All
  deriving Show

-- FIXME: MS: clean up proof construction; usable args returns empty if not set instead of all
data InterpretationProof a b = InterpretationProof
  { sig_       :: Signature F
  , inter_     :: Interpretation F a
  , uargs_     :: UPEnc.UsablePositions F
  , ufuns_     :: Maybe (Symbols F)
  , useURules_ :: Bool
  , shift_     :: Shift
  , strictDPs_ :: [(R.Rule F V, (b, b))]
  , strictTrs_ :: [(R.Rule F V, (b, b))]
  , weakDPs_   :: [(R.Rule F V, (b, b))]
  , weakTrs_   :: [(R.Rule F V, (b, b))]
  } deriving Show

instance Monad m => SMT.Decode m (InterpretationProof a b) (InterpretationProof a b) where
  decode = return

-- MS: formally this is not so nice as in tct2; some extra work would be necessary
-- on the other hand we now have an abstract orient function for interpretations
-- see Tct.RS.Method.Poly.NaturalPI for an example
class AbstractInterpretation i where
  type (A i) :: *
  type (B i) :: *
  type (C i) :: *

  encode      :: i -> A i -> SMT.SmtSolverSt Int (B i)

  setMonotone :: i -> B i -> [Int] -> SMT.Formula Int
  setInFilter :: i -> B i -> (Int -> SMT.Formula Int) -> SMT.Formula Int

  interpret   :: i -> Interpretation F (B i) -> R.Term F V -> C i

  addConstant :: i -> C i -> SMT.IExpr Int -> C i
  gte         :: i -> C i -> C i -> SMT.Formula Int

type ForceAny = [R.Rule F V] -> SMT.Formula Int

orient :: AbstractInterpretation i => i
  -> Trs
  -> Interpretation F (A i)
  -> Shift
  -> Bool -- TODO: MS: Use Types
  -> Bool
  -> SMT.SmtSolverSt Int (InterpretationProof () (), Interpretation F (B i), Maybe (UREnc.UsableEncoder F Int))
orient inter prob absi mselector useUP useUR = do
  SMT.setLogic SMT.QF_NIA

  -- encode abstract interpretation
  ebsi <- F.mapM (encode inter) absi

  let
    usablePositions = UPEnc.usableArgsWhereApplicable prob (Prob.isDTProblem prob) useUP
    monotoneConstraints =
      SMT.bigAnd [ setMonotone inter (interpretations ebsi `find` f) is | (f,is)  <- UPEnc.usablePositions usablePositions ]
        where find m f = error ("Interpretation.monotonConstraints: not found:" ++ show f) `fromMaybe` M.lookup f m

  -- encode usable rules modulo argument filtering
  usenc <- if allowUR then Just `liftM` UREnc.usableEncoder prob else return Nothing
  ifenc <- if allowAF then Just `liftM` AFEnc.inFilterEncoder prob else return Nothing

  let
    usable r = case usenc of
      Nothing -> SMT.top
      Just us -> UREnc.usable us r
    inFilter f i = case ifenc of
      Nothing -> SMT.top
      Just af -> AFEnc.inFilter af f i

    usableRulesConstraints
      | allowUR   = UREnc.validUsableRules trs usable inFilter
      | otherwise = SMT.top

    filteringConstraints
      | allowAF   = SMT.bigAnd $ k `M.mapWithKey` interpretations ebsi
      | otherwise = SMT.top
      where k f fi = setInFilter inter fi (inFilter f)

  -- encode strict vars
  strictVarEncoder <- M.fromList `fmap` F.mapM (\r -> SMT.nvarM' >>= \v -> return (r,v)) rules

  let
    find f = error "Interpretation.strictVar: not found" `fromMaybe` M.lookup f strictVarEncoder
    strict = find

    interpretf = interpret inter ebsi
    (.>=.) = gte inter
    (.+.)  = addConstant inter

    wOrderConstraints = SMT.bigAnd [ usable r .=> wOrder r | r <- wrules ]
      where wOrder r = interpretf (R.lhs r) .>=. interpretf (R.rhs r)
    sOrderConstraints = SMT.bigAnd [ usable r .=> sOrder r | r <- srules ]
      where sOrder r = interpretf (R.lhs r) .>=. (interpretf (R.rhs r) .+. strict r)

    forceAny rs
      | null rs   = SMT.bot
      | otherwise = SMT.bigOr [ usable r .&& strict r .> zero | r <- rs ]
    rulesConstraints = forceAny srules .&& forceSel
      where
        forceSel = case mselector of
          All       -> SMT.bigAnd [ usable r .=> strict r .> zero | r <- srules ]
          Shift sel -> orientSelected (RS.rsSelect sel prob)

    orientSelected (RS.SelectDP r)  = strict r .> zero
    orientSelected (RS.SelectTrs r) = strict r .> zero
    orientSelected (RS.BigAnd es)   = SMT.bigAnd (orientSelected `fmap` es)
    orientSelected (RS.BigOr es)    = SMT.bigOr (orientSelected `fmap` es)

  SMT.assert wOrderConstraints
  SMT.assert sOrderConstraints
  SMT.assert rulesConstraints
  SMT.assert monotoneConstraints
  SMT.assert usableRulesConstraints
  SMT.assert filteringConstraints

  return (proof usablePositions, ebsi, usenc)

  where
    trs    = Prob.allComponents prob
    rules  = RS.toList trs
    srules = RS.toList (Prob.strictComponents prob)
    wrules = RS.toList (Prob.weakComponents prob)

    allowUR = useUR && Prob.isRCProblem prob && Prob.isInnermostProblem prob
    allowAF = allowUR

    proof uposs = InterpretationProof
      { sig_       = Prob.signature prob
      , inter_     = Interpretation M.empty
      , uargs_     = uposs
      , ufuns_     = Nothing
      , useURules_ = allowUR
      , shift_     = mselector
      , strictDPs_ = []
      , strictTrs_ = []
      , weakDPs_   = []
      , weakTrs_   = [] }

-- toTree :: (T.Processor p, T.In p ~ T.Out p) => p -> T.In p -> T.Result p -> T.ProofTree (T.Out p)
-- toTree p prob (T.Fail po)                 = T.NoProgress (T.ProofNode p prob po) (T.Open prob)
-- toTree p prob (T.Success probs po certfn) = T.Progress (T.ProofNode p prob po) certfn (T.Open `fmap` probs)

newProblem :: Trs -> InterpretationProof a b -> T.Optional T.Id Trs
newProblem prob proof = case shift_ proof of
  All     -> T.Null
  Shift _ -> T.Opt . T.Id $ newProblem' prob proof

newProblem' :: Problem F V -> InterpretationProof a b -> Problem F V
newProblem' prob proof = Prob.sanitiseDPGraph $  prob
    { Prob.strictDPs = Prob.strictDPs prob `RS.difference` sDPs
    , Prob.strictTrs = Prob.strictTrs prob `RS.difference` sTrs
    , Prob.weakDPs   = Prob.weakDPs prob `RS.union` sDPs
    , Prob.weakTrs   = Prob.weakTrs prob `RS.union` sTrs }
  where
    rules = RS.fromList . fst . unzip
    sDPs = rules (strictDPs_ proof)
    sTrs = rules (strictTrs_ proof)

instance (PP.Pretty a, PP.Pretty b) => PP.Pretty (InterpretationProof a b) where
  pretty proof = PP.vcat
    [ if uargs_ proof /= UPEnc.fullWithSignature (sig_ proof)
        then PP.vcat
          [ PP.text "The following argument positions are considered usable:"
          , PP.indent 2 $ PP.pretty (uargs_ proof)
          , PP.empty ]
        else PP.empty
    , PP.text "Following symbols are considered usable:"
    , PP.indent 2 $ maybe (PP.text "all") PP.set' (ufuns_ proof)
    , PP.text "TcT has computed the following interpretation:"
    , PP.indent 2 (PP.pretty (inter_ proof))
    , PP.empty
    , PP.text "Following rules are strictly oriented:"
    , ppproof (PP.text " > ") (strictDPs_ proof ++ strictTrs_ proof)
    , PP.text ""
    , PP.text "Following rules are (at-least) weakly oriented:"
    , ppproof (PP.text " >= ") (weakDPs_ proof ++ weakTrs_ proof) ]
    where
      ppproof ppOrd rs = PP.table [(PP.AlignRight, as), (PP.AlignLeft, bs), (PP.AlignLeft, cs)]
        where
          (as,bs,cs) = unzip3 $ concatMap ppRule rs
          ppRule (R.Rule l r,(lhs,rhs)) =
            [ (PP.pretty l, PP.text " = ", PP.pretty lhs)
            , (PP.empty   , ppOrd        , PP.pretty rhs)
            , (PP.empty   , PP.text " = ", PP.pretty r)
            , (PP.empty   , PP.empty     , PP.empty) ]

xmlProof :: Xml.Xml a => InterpretationProof a b -> Xml.XmlContent -> Xml.XmlContent
xmlProof proof itype =
  Xml.elt "ruleShifting"
    [ orderingConstraintProof
    , Xml.elt "trs" [Xml.toXml $ RS.fromList trs]          -- strict part
    -- ceta complains if usableRules are set for non-innermost; even if all rules are given
    , if useURules_ proof
        then Xml.elt "usableRules" [Xml.toXml $ RS.fromList usr] -- usable part
        else Xml.empty
    -- akin to tct2 we allow interpretations to be the base case of our proof
    -- though ceTA requires to use ruleShifting; in this case we append the proof for the empty problem
    , case shift_ proof of
        -- Tct.Core.Processor.Empty.toXml Emptyproblem == </closed>, but toXml is not used in practice
        All     -> Xml.elt "complexityProof" [Xml.elt "rIsEmpty" []]
        Shift _ -> Xml.empty
    ]
    where
      orderingConstraintProof =
        Xml.elt "orderingConstraintProof"
          [ Xml.elt "redPair" [Xml.elt "interpretation" (itype :xinters)]]
      xinters = map xinter . M.toList . interpretations $ inter_ proof
      xinter (f,p) = Xml.elt "interpret"
        [ Xml.toXml f
        , Xml.elt "arity" [Xml.int $ sig_ proof `Sig.arity` f]
        , Xml.toXml p ]
        -- , Xml.elt "polynomial" [Xml.toXml p]]
      trs = map fst $ strictTrs_ proof ++ strictDPs_ proof
      usr = (trs ++) . map fst $ weakTrs_ proof ++ weakDPs_ proof


text:
from google.cloud import bigquery_datatransfer_v1

def sample_start_manual_transfer_runs():
    # Create a client
    client = bigquery_datatransfer_v1.DataTransferServiceClient()

    # Initialize request argument(s)
    request = bigquery_datatransfer_v1.StartManualTransferRunsRequest(
    )

    # Make the request
    response = client.start_manual_transfer_runs(request=request)

    # Handle the response
    print(response)

# [END bigquerydatatransfer_v1_generated_DataTransferService_StartManualTransferRuns_sync]


text:
import { EOL } from "os";
import * as path from "path";
import { TARGET_FRAMEWORK_IDENTIFIERS } from "../../constants";
import { cache } from "../../decorators";

export abstract class ProjectBase implements Project.IProjectBase {
	private static VALID_CONFIGURATION_CHARACTERS_REGEX = "[-_A-Za-z0-9]";
	private static CONFIGURATION_FROM_FILE_NAME_REGEX = new RegExp(`^[.](${ProjectBase.VALID_CONFIGURATION_CHARACTERS_REGEX}+?)[.]abproject$`, "i");
	private static ANDROID_MANIFEST_NAME = "AndroidManifest.xml";
	private static APP_IDENTIFIER_PLACEHOLDER = "$AppIdentifier$";

	public configurationSpecificData: IDictionary<Project.IData>;

	protected _shouldSaveProject = false;
	protected _projectData: Project.IData;

	private _hasBuildConfigurations = false;

	constructor(protected $cordovaProjectCapabilities: Project.ICapabilities,
		protected $errors: IErrors,
		protected $fs: IFileSystem,
		protected $logger: ILogger,
		protected $nativeScriptProjectCapabilities: Project.ICapabilities,
		protected $options: ICommonOptions,
		protected $projectConstants: Project.IConstants,
		protected $staticConfig: Config.IStaticConfig) {
		this.configurationSpecificData = Object.create(null);
	}

	// This property is purposely written as two separate methods so that only get/set can be overriden
	protected getShouldSaveProject(): boolean {
		return this._shouldSaveProject;
	}

	protected setShouldSaveProject(shouldSaveProject: boolean) {
		this._shouldSaveProject = shouldSaveProject;
	}

	public get projectData(): Project.IData {
		this.readProjectData();
		return this._projectData;
	}

	public set projectData(projectData: Project.IData) {
		this._projectData = projectData;
	}

	public projectDir: string;
	public getProjectDir(): string {
		return this.projectDir;
	}

	public get capabilities(): Project.ICapabilities {
		const projectData = this.projectData;
		if (projectData) {
			if (projectData.Framework && projectData.Framework.toLowerCase() === TARGET_FRAMEWORK_IDENTIFIERS.NativeScript.toLowerCase()) {
				return this.$nativeScriptProjectCapabilities;
			} else if (projectData.Framework && projectData.Framework.toLowerCase() === TARGET_FRAMEWORK_IDENTIFIERS.Cordova.toLowerCase()) {
				return this.$cordovaProjectCapabilities;
			}
		}

		return null;
	}

	public get hasBuildConfigurations(): boolean {
		return this._hasBuildConfigurations;
	}

	public get projectInformation(): Project.IProjectInformation {
		return {
			projectData: this.projectData,
			configurationSpecificData: this.configurationSpecificData,
			hasBuildConfigurations: this.hasBuildConfigurations,
			configurations: _.keys(this.configurationSpecificData)
		};
	}

	@cache()
	public getAppIdentifierForPlatform(platform?: string): string {
		let platformSpecificAppIdentifier = this.projectData.AppIdentifier;

		if (platform &&
			platform.toLowerCase() === this.$projectConstants.ANDROID_PLATFORM_NAME.toLowerCase() &&
			this.projectData.Framework === TARGET_FRAMEWORK_IDENTIFIERS.Cordova) {
			const pathToAndroidResources = path.join(this.projectDir, this.$staticConfig.APP_RESOURCES_DIR_NAME, this.$projectConstants.ANDROID_PLATFORM_NAME);

			const pathToAndroidManifest = path.join(pathToAndroidResources, ProjectBase.ANDROID_MANIFEST_NAME);
			const appIdentifierInAndroidManifest = this.getAppIdentifierFromConfigFile(pathToAndroidManifest, /package\s*=\s*"(\S*)"/);

			if (appIdentifierInAndroidManifest && appIdentifierInAndroidManifest !== ProjectBase.APP_IDENTIFIER_PLACEHOLDER) {
				platformSpecificAppIdentifier = appIdentifierInAndroidManifest;
			}
		}

		return platformSpecificAppIdentifier;
	}

	protected abstract validate(): void;
	protected abstract saveProjectIfNeeded(): void;

	protected readProjectData(): void {
		const projectDir = this.getProjectDir();
		this.setShouldSaveProject(false);
		if (projectDir) {
			const projectFilePath = path.join(projectDir, this.$projectConstants.PROJECT_FILE);
			try {
				this.projectData = this.getProjectData(projectFilePath);
				this.validate();

				_.each(this.$fs.enumerateFilesInDirectorySync(projectDir), (configProjectFile: string) => {
					const configMatch = path.basename(configProjectFile).match(ProjectBase.CONFIGURATION_FROM_FILE_NAME_REGEX);
					if (configMatch && configMatch.length > 1) {
						const configurationName = configMatch[1];
						const configProjectContent = this.$fs.readJson(configProjectFile),
							configurationLowerCase = configurationName.toLowerCase();
						this.configurationSpecificData[configurationLowerCase] = <any>_.merge(_.cloneDeep(this._projectData), configProjectContent);
						this._hasBuildConfigurations = true;
					}
				});
			} catch (err) {
				if (err.message === "FUTURE_PROJECT_VER") {
					this.$errors.failWithoutHelp("This project is created by a newer version of AppBuilder. Upgrade AppBuilder CLI to work with it.");
				}

				this.$errors.failWithoutHelp("The project file %s is corrupted." + EOL +
					"Consider restoring an earlier version from your source control or backup." + EOL +
					"To create a new one with the default settings, delete this file and run $ appbuilder init hybrid." + EOL +
					"Additional technical information: %s", projectFilePath, err.toString());
			}

			this.saveProjectIfNeeded();
		}
	}

	private getProjectData(projectFilePath: string): Project.IData {
		const data = this.$fs.readJson(projectFilePath);
		if (data.projectVersion && data.projectVersion.toString() !== "1") {
			this.$errors.fail("FUTURE_PROJECT_VER");
		}

		if (!_.has(data, "Framework")) {
			if (_.has(data, "projectType")) {
				data["Framework"] = data["projectType"];
				delete data["projectType"];
			} else {
				data["Framework"] = TARGET_FRAMEWORK_IDENTIFIERS.Cordova;
			}

			this.setShouldSaveProject(true);
		}

		return data;
	}

	private getAppIdentifierFromConfigFile(pathToConfigFile: string, regExp: RegExp): string {
		if (this.$fs.exists(pathToConfigFile)) {
			const fileContent = this.$fs.readText(pathToConfigFile);

			const matches = fileContent.match(regExp);

			if (matches && matches[1]) {
				return matches[1];
			}
		}

		return null;
	}
}


text:
/**
 * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
 */
package net.sourceforge.pmd.cpd;

/**
 * Implements the Go Language
 *
 * @author oinume@gmail.com
 */
public class GoLanguage extends AbstractLanguage {

    /**
     * Creates a new instance of {@link GoLanguage}
     */
    public GoLanguage() {
        super("Go", "go", new GoTokenizer(), ".go");
    }
}


text:
import { Component, OnInit, Input } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'stbui-github-button',
  templateUrl: './github-button.component.html',
  styleUrls: ['./github-button.component.scss']
})
export class GithubButtonComponent implements OnInit {
  private _type;
  @Input()
  set type(value) {
    this._type = value.split('|');
  }
  get type() {
    if (!this._type) {
      this._type = 'link|watch|star|issue|fork|download';
      this._type = this._type.split('|');
    }
    return this._type;
  }

  @Input() user: string = 'stbui';
  @Input() repo: string = 'angular-material-app';

  readonly baseApi: string = 'https://api.github.com/repos';
  readonly baseUrl: string = 'https://github.com';
  repository: object = {
    subscribers_count: 0,
    stargazers_count: 0,
    forks_count: 0,
    open_issues_count: 0
  };

  constructor(private http: HttpClient) {}

  ngOnInit() {
    const url = `${this.baseApi}/${this.user}/${this.repo}`;
    this.http.get(url).subscribe(res => {
      this.repository = res;
    });
  }

  getGithubUrl() {
    const url = `${this.baseUrl}/${this.user}/${this.repo}`;

    return {
      base: url,
      watch: `${url}/watchers`,
      star: `${url}/stargazers`,
      fork: `${url}/network`,
      issue: `${url}/issues`,
      download: `${url}/archive/master.zip`
    };
  }
}


text:
@interface ZYCNavigationController : UINavigationController

@end


text:
package com.example.framework.requests;

import com.example.framework.CustomServiceRequest;

public abstract class BodyRequest<TBody, TResult> extends CustomServiceRequest<TResult> {
	public TBody body;
}


text:
# Sortable
Sortable is a minimalist JavaScript library for reorderable drag-and-drop lists.

Demo: http://rubaxa.github.io/Sortable/

## Features

 * Supports touch devices and [modern](http://caniuse.com/#search=drag) browsers (including IE9)
 * Can drag from one list to another or within the same list
 * CSS animation when moving items
 * Supports drag handles *and selectable text* (better than voidberg's html5sortable)
 * Smart auto-scrolling
 * Built using native HTML5 drag and drop API
 * Supports [Meteor](meteor/README.md), [AngularJS](#ng), [React](#react) and [Polymer](#polymer)
 * Supports any CSS library, e.g. [Bootstrap](#bs)
 * Simple API
 * [CDN](#cdn)
 * No jQuery (but there is [support](#jq))

### Articles
 * [Sortable v1.0 — New capabilities](https://github.com/RubaXa/Sortable/wiki/Sortable-v1.0-—-New-capabilities/) (December 22, 2014)
 * [Sorting with the help of HTML5 Drag'n'Drop API](https://github.com/RubaXa/Sortable/wiki/Sorting-with-the-help-of-HTML5-Drag'n'Drop-API/) (December 23, 2013)

### Usage
```html
<ul id="items">
	<li>item 1</li>
	<li>item 2</li>
	<li>item 3</li>
</ul>
```

```js
var el = document.getElementById('items');
var sortable = Sortable.create(el);
```

You can use any element for the list and its elements, not just `ul`/`li`. Here is an [example with `div`s](http://jsbin.com/luxero/2/edit?html,js,output).

---

### Options
```js
var sortable = new Sortable(el, {
	group: "name",  // or { name: "...", pull: [true, false, clone], put: [true, false, array] }
	sort: true,  // sorting inside list
	delay: 0, // time in milliseconds to define when the sorting should start
	disabled: false, // Disables the sortable if set to true.
	store: null,  // @see Store
	animation: 150,  // ms, animation speed moving items when sorting, `0` — without animation
	handle: ".my-handle",  // Drag handle selector within list items
	filter: ".ignore-elements",  // Selectors that do not lead to dragging (String or Function)
	draggable: ".item",  // Specifies which items inside the element should be sortable
	ghostClass: "sortable-ghost",  // Class name for the drop placeholder
	chosenClass: "sortable-chosen",  // Class name for the chosen item
	dataIdAttr: 'data-id',

	forceFallback: false,  // ignore the HTML5 DnD behaviour and force the fallback to kick in
	fallbackClass: "sortable-fallback"  // Class name for the cloned DOM Element when using forceFallback
	fallbackOnBody: false  // Appends the cloned DOM Element into the Document's Body

	scroll: true, // or HTMLElement
	scrollSensitivity: 30, // px, how near the mouse must be to an edge to start scrolling.
	scrollSpeed: 10, // px

	setData: function (dataTransfer, dragEl) {
		dataTransfer.setData('Text', dragEl.textContent);
	},

	// dragging started
	onStart: function (/**Event*/evt) {
		evt.oldIndex;  // element index within parent
	},

	// dragging ended
	onEnd: function (/**Event*/evt) {
		evt.oldIndex;  // element's old index within parent
		evt.newIndex;  // element's new index within parent
	},

	// Element is dropped into the list from another list
	onAdd: function (/**Event*/evt) {
		var itemEl = evt.item;  // dragged HTMLElement
		evt.from;  // previous list
		// + indexes from onEnd
	},

	// Changed sorting within list
	onUpdate: function (/**Event*/evt) {
		var itemEl = evt.item;  // dragged HTMLElement
		// + indexes from onEnd
	},

	// Called by any change to the list (add / update / remove)
	onSort: function (/**Event*/evt) {
		// same properties as onUpdate
	},

	// Element is removed from the list into another list
	onRemove: function (/**Event*/evt) {
		// same properties as onUpdate
	},

	// Attempt to drag a filtered element
	onFilter: function (/**Event*/evt) {
		var itemEl = evt.item;  // HTMLElement receiving the `mousedown|tapstart` event.
	},

	// Event when you move an item in the list or between lists
	onMove: function (/**Event*/evt) {
		// Example: http://jsbin.com/tuyafe/1/edit?js,output
		evt.dragged; // dragged HTMLElement
		evt.draggedRect; // TextRectangle {left, top, right и bottom}
		evt.related; // HTMLElement on which have guided
		evt.relatedRect; // TextRectangle
		// return false; — for cancel
	}
});
```

---

#### `group` option
To drag elements from one list into another, both lists must have the same `group` value.
You can also define whether lists can give away, give and keep a copy (`clone`), and receive elements.

 * name: `String` — group name
 * pull: `true|false|'clone'` — ability to move from the list. `clone` — copy the item, rather than move.
 * put: `true|false|["foo", "bar"]` — whether elements can be added from other lists, or an array of group names from which elements can be taken. Demo: http://jsbin.com/naduvo/2/edit?html,js,output

---

#### `sort` option
Sorting inside list.

Demo: http://jsbin.com/xizeh/2/edit?html,js,output

---

#### `delay` option
Time in milliseconds to define when the sorting should start.

Demo: http://jsbin.com/xizeh/4/edit?html,js,output

---

#### `disabled` options
Disables the sortable if set to `true`.

Demo: http://jsbin.com/xiloqu/1/edit?html,js,output

```js
var sortable = Sortable.create(list);

document.getElementById("switcher").onclick = function () {
	var state = sortable.option("disabled"); // get

	sortable.option("disabled", !state); // set
};
```

---

#### `handle` option
To make list items draggable, Sortable disables text selection by the user.
That's not always desirable. To allow text selection, define a drag handler,
which is an area of every list element that allows it to be dragged around.

Demo: http://jsbin.com/newize/1/edit?html,js,output

```js
Sortable.create(el, {
	handle: ".my-handle"
});
```

```html
<ul>
	<li><span class="my-handle">::</span> list item text one
	<li><span class="my-handle">::</span> list item text two
</ul>
```

```css
.my-handle {
	cursor: move;
	cursor: -webkit-grabbing;
}
```

---

#### `filter` option

```js
Sortable.create(list, {
	filter: ".js-remove, .js-edit",
	onFilter: function (evt) {
		var item = evt.item,
			ctrl = evt.target;

		if (Sortable.utils.is(ctrl, ".js-remove")) {  // Click on remove button
			item.parentNode.removeChild(item); // remove sortable item
		}
		else if (Sortable.utils.is(ctrl, ".js-edit")) {  // Click on edit link
			// ...
		}
	}
})
```

---

#### `ghostClass` option
Class name for the drop placeholder (default `sortable-ghost`).

Demo: http://jsbin.com/hunifu/1/edit?css,js,output

```css
.ghost {
  opacity: 0.4;
}
```

```js
Sortable.create(list, {
  ghostClass: "ghost"
});
```

---

#### `chosenClass` option
Class name for the chosen item  (default `sortable-chosen`).

Demo: http://jsbin.com/hunifu/edit?html,css,js,output

```css
.chosen {
  color: #fff;
  background-color: #c00;
}
```

```js
Sortable.create(list, {
  delay: 500,
  chosenClass: "chosen"
});
```

---

#### `forceFallback` option
If set to `true`, the Fallback for non HTML5 Browser will be used, even if we are using an HTML5 Browser.
This gives us the possiblity to test the behaviour for older Browsers even in newer Browser, or make the Drag 'n Drop feel more consistent between Desktop , Mobile and old Browsers.

On top of that, the Fallback always generates a copy of that DOM Element and appends the class `fallbackClass` definied in the options. This behaviour controls the look of this 'dragged' Element.

Demo: http://jsbin.com/pucurizace/edit?html,css,js,output

---

#### `scroll` option
If set to `true`, the page (or sortable-area) scrolls when coming to an edge.

Demo:
 - `window`: http://jsbin.com/boqugumiqi/1/edit?html,js,output
 - `overflow: hidden`: http://jsbin.com/kohamakiwi/1/edit?html,js,output

---

#### `scrollSensitivity` option
Defines how near the mouse must be to an edge to start scrolling.

---

#### `scrollSpeed` option
The speed at which the window should scroll once the mouse pointer gets within the `scrollSensitivity` distance.

---

### Support AngularJS
Include [ng-sortable.js](ng-sortable.js)

Demo: http://jsbin.com/naduvo/1/edit?html,js,output

```html
<div ng-app="myApp" ng-controller="demo">
	<ul ng-sortable>
		<li ng-repeat="item in items">{{item}}</li>
	</ul>

	<ul ng-sortable="{ group: 'foobar' }">
		<li ng-repeat="item in foo">{{item}}</li>
	</ul>

	<ul ng-sortable="barConfig">
		<li ng-repeat="item in bar">{{item}}</li>
	</ul>
</div>
```

```js
angular.module('myApp', ['ng-sortable'])
	.controller('demo', ['$scope', function ($scope) {
		$scope.items = ['item 1', 'item 2'];
		$scope.foo = ['foo 1', '..'];
		$scope.bar = ['bar 1', '..'];
		$scope.barConfig = {
			group: 'foobar',
			animation: 150,
			onSort: function (/** ngSortEvent */evt){
				// @see https://github.com/RubaXa/Sortable/blob/master/ng-sortable.js#L18-L24
			}
		};
	}]);
```

---

### Support React
Include [react-sortable-mixin.js](react-sortable-mixin.js).
See [more options](react-sortable-mixin.js#L26).

```jsx
var SortableList = React.createClass({
	mixins: [SortableMixin],

	getInitialState: function() {
		return {
			items: ['Mixin', 'Sortable']
		};
	},

	handleSort: function (/** Event */evt) { /*..*/ },

	render: function() {
		return <ul>{
			this.state.items.map(function (text) {
				return <li>{text}</li>
			})
		}</ul>
	}
});

React.render(<SortableList />, document.body);

//
// Groups
//
var AllUsers = React.createClass({
	mixins: [SortableMixin],

	sortableOptions: {
		ref: "user",
		group: "shared",
		model: "users"
	},

	getInitialState: function() {
		return { users: ['Abbi', 'Adela', 'Bud', 'Cate', 'Davis', 'Eric']; };
	},

	render: function() {
		return (
			<h1>Users</h1>
			<ul ref="user">{
				this.state.users.map(function (text) {
					return <li>{text}</li>
				})
			}</ul>
		);
	}
});

var ApprovedUsers = React.createClass({
	mixins: [SortableMixin],
	sortableOptions: { group: "shared" },

	getInitialState: function() {
		return { items: ['Hal', 'Judy']; };
	},

	render: function() {
		return <ul>{
			this.state.items.map(function (text) {
				return <li>{text}</li>
			})
		}</ul>
	}
});

React.render(<div>
	<AllUsers/>
	<hr/>
	<ApprovedUsers/>
</div>, document.body);
```

---

### Support KnockoutJS
Include [knockout-sortable.js](knockout-sortable.js)

```html
<div data-bind="sortable: {foreach: yourObservableArray, options: {/* sortable options here */}}">
	<!-- optional item template here -->
</div>

<div data-bind="draggable: {foreach: yourObservableArray, options: {/* sortable options here */}}">
	<!-- optional item template here -->
</div>
```

Using this bindingHandler sorts the observableArray when the user sorts the HTMLElements.

The sortable/draggable bindingHandlers supports the same syntax as Knockouts built in [template](http://knockoutjs.com/documentation/template-binding.html) binding except for the `data` option, meaning that you could supply the name of a template or specify a separate templateEngine. The difference between the sortable and draggable handlers is that the draggable has the sortable `group` option set to `{pull:'clone',put: false}` and the `sort` option set to false by default (overridable).

Other attributes are:
*	options: an object that contains settings for the underlaying sortable, ie `group`,`handle`, events etc.
*	collection: if your `foreach` array is a computed then you would supply the underlaying observableArray that you would like to sort here.

---

### Support Polymer
```html

<link rel="import" href="bower_components/Sortable/Sortable-js.html">

<sortable-js handle=".handle">
  <template is="dom-repeat" items={{names}}>
    <div>{{item}}</div>
  </template>
<sortable-js>
```

### Method

##### option(name:`String`[, value:`*`]):`*`
Get or set the option.

##### closest(el:`String`[, selector:`HTMLElement`]):`HTMLElement|null`
For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

##### toArray():`String[]`
Serializes the sortable's item `data-id`'s (`dataIdAttr` option) into an array of string.

##### sort(order:`String[]`)
Sorts the elements according to the array.

```js
var order = sortable.toArray();
sortable.sort(order.reverse()); // apply
```

##### save()
Save the current sorting (see [store](#store))

##### destroy()
Removes the sortable functionality completely.

---

### Store
Saving and restoring of the sort.

```html
<ul>
	<li data-id="1">order</li>
	<li data-id="2">save</li>
	<li data-id="3">restore</li>
</ul>
```

```js
Sortable.create(el, {
	group: "localStorage-example",
	store: {
		/**
		 * Get the order of elements. Called once during initialization.
		 * @param   {Sortable}  sortable
		 * @returns {Array}
		 */
		get: function (sortable) {
			var order = localStorage.getItem(sortable.options.group);
			return order ? order.split('|') : [];
		},

		/**
		 * Save the order of elements. Called onEnd (when the item is dropped).
		 * @param {Sortable}  sortable
		 */
		set: function (sortable) {
			var order = sortable.toArray();
			localStorage.setItem(sortable.options.group, order.join('|'));
		}
	}
})
```

---

### Bootstrap
Demo: http://jsbin.com/luxero/2/edit?html,js,output

```html
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"/>

<!-- Latest Sortable -->
<script src="http://rubaxa.github.io/Sortable/Sortable.js"></script>

<!-- Simple List -->
<ul id="simpleList" class="list-group">
	<li class="list-group-item">This is <a href="http://rubaxa.github.io/Sortable/">Sortable</a></li>
	<li class="list-group-item">It works with Bootstrap...</li>
	<li class="list-group-item">...out of the box.</li>
	<li class="list-group-item">It has support for touch devices.</li>
	<li class="list-group-item">Just drag some elements around.</li>
</ul>

<script>
    // Simple list
    Sortable.create(simpleList, { /* options */ });
</script>
```

---

### Static methods & properties

##### Sortable.create(el:`HTMLElement`[, options:`Object`]):`Sortable`
Create new instance.

---

##### Sortable.active:`Sortable`
Link to the active instance.

---

##### Sortable.utils
* on(el`:HTMLElement`, event`:String`, fn`:Function`) — attach an event handler function
* off(el`:HTMLElement`, event`:String`, fn`:Function`) — remove an event handler
* css(el`:HTMLElement`)`:Object` — get the values of all the CSS properties
* css(el`:HTMLElement`, prop`:String`)`:Mixed` — get the value of style properties
* css(el`:HTMLElement`, prop`:String`, value`:String`) — set one CSS properties
* css(el`:HTMLElement`, props`:Object`) — set more CSS properties
* find(ctx`:HTMLElement`, tagName`:String`[, iterator`:Function`])`:Array` — get elements by tag name
* bind(ctx`:Mixed`, fn`:Function`)`:Function` — Takes a function and returns a new one that will always have a particular context
* is(el`:HTMLElement`, selector`:String`)`:Boolean` — check the current matched set of elements against a selector
* closest(el`:HTMLElement`, selector`:String`[, ctx`:HTMLElement`])`:HTMLElement|Null` — for each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree
* toggleClass(el`:HTMLElement`, name`:String`, state`:Boolean`) — add or remove one classes from each element

---

### CDN

```html
<!-- CDNJS :: Sortable (https://cdnjs.com/) -->
<script src="//cdnjs.cloudflare.com/ajax/libs/Sortable/1.4.1-rc1/Sortable.min.js"></script>

<!-- jsDelivr :: Sortable (http://www.jsdelivr.com/) -->
<script src="//cdn.jsdelivr.net/sortable/1.4.1-rc1/Sortable.min.js"></script>

<!-- jsDelivr :: Sortable :: Latest (http://www.jsdelivr.com/) -->
<script src="//cdn.jsdelivr.net/sortable/latest/Sortable.min.js"></script>
```

---

### jQuery compatibility
To assemble plugin for jQuery, perform the following steps:

```bash
  cd Sortable
  npm install
  grunt jquery
```

Now you can use `jquery.fn.sortable.js`:

(or `jquery.fn.sortable.min.js` if you run `grunt jquery:min`)

```js
  $("#list").sortable({ /* options */ }); // init

  $("#list").sortable("widget"); // get Sortable instance

  $("#list").sortable("destroy"); // destroy Sortable instance

  $("#list").sortable("{method-name}"); // call an instance method

  $("#list").sortable("{method-name}", "foo", "bar"); // call an instance method with parameters
```

And `grunt jquery:mySortableFunc` → `jquery.fn.mySortableFunc.js`

---

### Contributing (Issue/PR)

Please, [read this](CONTRIBUTING.md).

---

## MIT LICENSE
Copyright 2013-2015 Lebedev Konstantin <ibnRubaXa@gmail.com>
http://rubaxa.github.io/Sortable/

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
module Hammer
  module Component
    module Developer

      class Inspection::Hash < Inspection::Object

        def unpack
          @components = obj.to_a.flatten(1).map do |value|
            inspector value
          end
        end

      end
    end
  end
end


text:
    {{#each this.categories}}

        {{#each subCategories}}

{{this.name}}

        {{/each}}

    {{/each}}

    {{#each this.categories}}

        {{#each subCategories}}

{{this.name}}

        {{/each}}

    {{/each}}

             StructurAlgo
            menu

                {{#each categories}}

                    {{name}}arrow_drop_down

                {{/each}}

file_download

settings

                {{#if info}}

info

                {{/if}}

                {{#each categories}}

                    {{name}}arrow_drop_down

                {{/each}}

file_download

settings

                {{#if info}}

info

                {{/if}}

Settings

            <form action="#">

                        Load
                        <input type="file" id="file-input" accept="json">

                        <input class="file-path validate" type="text" placeholder="Upload datastructure JSON file">

                    <select id="font-size-select">
                        <option value="10">10</option>
                        <option value="12" selected>12</option>
                        <option value="14">14</option>
                        <option value="16">16</option>
                        <option value="18">18</option>
                        <option value="20">20</option>
                        <option value="22">22</option>
                        <option value="24">24</option>
                    </select>
                    Font Size

            </form>

            Close

Controls

                {{info}}

            Close


text:
package v2

import (
	"os"
	"testing"

	"github.com/rackspace/gophercloud/rackspace/identity/v2/tokens"
	th "github.com/rackspace/gophercloud/testhelper"
)

func TestTokenAuth(t *testing.T) {
	authedClient := createClient(t, true)
	token := authedClient.TokenID

	tenantID := os.Getenv("RS_TENANT_ID")
	if tenantID == "" {
		t.Skip("You must set RS_TENANT_ID environment variable to run this test")
	}

	authOpts := tokens.AuthOptions{}
	authOpts.TenantID = tenantID
	authOpts.TokenID = token

	_, err := tokens.Create(authedClient, authOpts).ExtractToken()
	th.AssertNoErr(t, err)
}


text:
package com.tierline.scala.activemodel

import com.tierline.scala.activemodel.singletenant.domain.Cart
import org.scalatest.FunSuite
import com.tierline.scala.activemodel.util.Companion

class UtilsTest extends FunSuite {

  test("Get Companion object from class manifest") {
    assert(Companion.of[Cart].isDefined)
  }
}


text:
require 'spec_helper'

describe ActsAsTaggableOn::Utils do
  describe "like_operator" do
    before(:each) do
      clean_database!
      TaggableModel.acts_as_taggable_on(:tags, :languages, :skills, :needs, :offerings)
      @taggable = TaggableModel.new(:name => "Bob Jones")
    end

    it "should return 'ILIKE' when the adapter is PostgreSQL" do
      TaggableModel.connection.stub(:adapter_name).and_return("PostgreSQL")
      TaggableModel.send(:like_operator).should == "ILIKE"
    end

    it "should return 'LIKE' when the adapter is not PostgreSQL" do
      TaggableModel.connection.stub(:adapter_name).and_return("MySQL")
      TaggableModel.send(:like_operator).should == "LIKE"
    end
  end
end