text:
<?php

namespace mako\database\midgard;

use DateTimeInterface;
use JsonSerializable;
use RuntimeException;

use mako\application\Application;
use mako\chrono\Time;
use mako\database\ConnectionManager;
use mako\database\connections\Connection;
use mako\database\midgard\Query;
use mako\database\midgard\relations\BelongsTo;
use mako\database\midgard\relations\HasMany;
use mako\database\midgard\relations\HasManyPolymorphic;
use mako\database\midgard\relations\HasOne;
use mako\database\midgard\relations\HasOnePolymorphic;
use mako\database\midgard\relations\ManyToMany;
use mako\utility\Str;
use mako\utility\UUID;
use mako\syringe\ClassInspector;

/**
 * ORM.
 *
 * @author Frederic G. Østby
 */
abstract class ORM implements JsonSerializable
{
	/**
	 * Incrementing primary key.
	 *
	 * @var int
	 */
	const PRIMARY_KEY_TYPE_INCREMENTING = 1000;

	/**
	 * UUID primary key.
	 *
	 * @var int
	 */
	const PRIMARY_KEY_TYPE_UUID = 1001;

	/**
	 * Custom primary key.
	 *
	 * @var int
	 */
	const PRIMARY_KEY_TYPE_CUSTOM = 1002;

	/**
	 * No primary key.
	 *
	 * @var int
	 */
	const PRIMARY_KEY_TYPE_NONE = 1003;

	/**
	 * Connection name to use for the model.
	 *
	 * @var string
	 */
	protected $connectionName = null;

	/**
	 * Connection manager instance.
	 *
	 * @var \mako\database\ConnectionManager
	 */
	protected static $connectionManager = null;

	/**
	 * ORM query builder hooks.
	 *
	 * @var array
	 */
	protected static $traitHooks = [];

	/**
	 * Trait casts.
	 *
	 * @var array
	 */
	protected static $traitCasts = [];

	/**
	 * Table name.
	 *
	 * @var string
	 */
	protected $tableName = null;

	/**
	 * Foreign key name.
	 *
	 * @var string
	 */
	protected $foreignKeyName = null;

	/**
	 * Primary key.
	 *
	 * @var string
	 */
	protected $primaryKey = 'id';

	/**
	 * Does this table have an auto increment primary index?
	 *
	 * @var bool
	 */
	protected $primaryKeyType = ORM::PRIMARY_KEY_TYPE_INCREMENTING;

	/**
	 * Has the record been loaded from/saved to a database?
	 *
	 * @var bool
	 */
	protected $exists = false;

	/**
	 * Column values.
	 *
	 * @var array
	 */
	protected $columns = [];

	/**
	 * Original column values.
	 *
	 * @var array
	 */
	protected $original = [];

	/**
	 * Relations to eager load.
	 *
	 * @var array
	 */
	protected $including = [];

	/**
	 * Related records.
	 *
	 * @var array
	 */
	protected $related = [];

	/**
	 * Columns that should be casted to a specific type.
	 *
	 * @var array
	 */
	protected $cast = [];

	/**
	 * Columns that can be set through mass assignment.
	 *
	 * @var array
	 */
	protected $assignable = [];

	/**
	 * Columns and relations that are excluded from the array and json representations of the record.
	 *
	 * @var array
	 */
	protected $protected = [];

	/**
	 * Date format used when returning array and json representations of the record.
	 *
	 * @var string
	 */
	protected $dateOutputFormat = 'Y-m-d H:i:s';

	/**
	 * Constructor.
	 *
	 * @param array $columns   Column values
	 * @param bool  $raw       Set raw values?
	 * @param bool  $whitelist Remove columns that are not in the whitelist?
	 * @param bool  $exists    Does the record come from a database?
	 */
	public function __construct(array $columns = [], bool $raw = false, bool $whitelist = true, bool $exists = false)
	{
		$this->registerTraits();

		$this->assign($columns, $raw, $whitelist);

		if($exists)
		{
			$this->exists = true;

			$this->synchronize();
		}
	}

	/**
	 * Making sure that cloning returns a "fresh copy" of the record.
	 *
	 */
	public function __clone()
	{
		if($this->exists)
		{
			$this->exists   = false;
			$this->original = [];
			$this->related  = [];

			unset($this->columns[$this->primaryKey]);
		}
	}

	/**
	 * Set the connection manager.
	 *
	 * @param \mako\database\ConnectionManager $connectionManager Connection manager instance
	 */
	public static function setConnectionManager(ConnectionManager $connectionManager)
	{
		static::$connectionManager = $connectionManager;
	}

	/**
	 * Returns the connection of the model.
	 *
	 * @return \mako\database\connections\Connection
	 */
	public function getConnection(): Connection
	{
		if(empty(static::$connectionManager))
		{
			static::$connectionManager = Application::instance()->getContainer()->get('database');
		}

		return static::$connectionManager->connection($this->connectionName);
	}

	/**
	 * Has the record been loaded from/saved to a database?
	 *
	 * @return bool
	 */
	public function exists(): bool
	{
		return $this->exists;
	}

	/**
	 * Synchronizes the original values with the modified values.
	 */
	public function synchronize()
	{
		$this->original = $this->columns;
	}

	/**
	 * Gets the date format from the query builder compiler.
	 *
	 * @return string
	 */
	protected function getDateFormat(): string
	{
		static $dateFormat;

		if($dateFormat === null)
		{
			$dateFormat = $this->builder()->getCompiler()->getDateFormat();
		}

		return $dateFormat;
	}

	/**
	 * Registers traits.
	 */
	protected function registerTraits()
	{
		if(!isset(static::$traitHooks[static::class]))
		{
			static::$traitHooks[static::class] = [];
			static::$traitCasts[static::class] = [];

			foreach(ClassInspector::getTraits(static::class) as $trait)
			{
				if(method_exists($this, $getter = 'get' . $this->getClassShortName($trait) . 'Hooks'))
				{
					static::$traitHooks[static::class] = array_merge_recursive(static::$traitHooks[static::class], $this->$getter());
				}

				if(method_exists($this, $getter = 'get' . $this->getClassShortName($trait) . 'Casts'))
				{
					static::$traitCasts[static::class] += $this->$getter();
				}
			}
		}

		$this->cast += static::$traitCasts[static::class];
	}

	/**
	 * Binds the hooks to the current instance of "$this".
	 *
	 * @param  array $hooks Array of hooks
	 * @return array
	 */
	protected function bindHooks(array $hooks): array
	{
		$bound = [];

		foreach($hooks as $hook)
		{
			$bound[] = $hook->bindTo($this);
		}

		return $bound;
	}

	/**
	 * Returns hooks for the chosen event.
	 *
	 * @param  string $event Event name
	 * @return array
	 */
	public function getHooks(string $event): array
	{
		return isset(static::$traitHooks[static::class][$event]) ? $this->bindHooks(static::$traitHooks[static::class][$event]) : [];
	}

	/**
	 * Returns the short name of a class.
	 *
	 * @param  string $className Class name
	 * @return string
	 */
	protected function getClassShortName(string $className = null): string
	{
		$class = $className ?? static::class;

		$pos = strrpos($class, '\\');

		if($pos === false)
		{
			return $class;
		}

		return substr($class, $pos + 1);
	}

	/**
	 * Returns the table name of the model.
	 *
	 * @return string
	 */
	public function getTable(): string
	{
		if(empty($this->tableName))
		{
			$this->tableName = Str::pluralize(Str::camel2underscored($this->getClassShortName()));
		}

		return $this->tableName;
	}

	/**
	 * Returns the primary key of the table.
	 *
	 * @return string
	 */
	public function getPrimaryKey(): string
	{
		return $this->primaryKey;
	}

	/**
	 * Returns the primary key type.
	 *
	 * @return int
	 */
	public function getPrimaryKeyType(): int
	{
		return $this->primaryKeyType;
	}

	/**
	 * Returns the primary key value.
	 *
	 * @return mixed
	 */
	public function getPrimaryKeyValue()
	{
		return $this->columns[$this->primaryKey];
	}

	/**
	 * Returns the foreign key of the table.
	 *
	 * @return string
	 */
	public function getForeignKey(): string
	{
		if(empty($this->foreignKeyName))
		{
			$this->foreignKeyName = Str::camel2underscored($this->getClassShortName()) . '_id';
		}

		return $this->foreignKeyName;
	}

	/**
	 * Returns the namespaced class name of the model.
	 *
	 * @return string
	 */
	public function getClass(): string
	{
		return '\\' . static::class;
	}

	/**
	 * Sets the relations to eager load.
	 *
	 * @param array $includes Relations to eager load
	 */
	public function setIncludes(array $includes)
	{
		$this->including = $includes;
	}

	/**
	 * Returns the relations to eager load.
	 *
	 * @return array
	 */
	public function getIncludes(): array
	{
		return $this->including;
	}

	/**
	 * Sets eagerly loaded related records.
	 *
	 * @param string $relation Relation name
	 * @param mixed  $related  Related record(s)
	 */
	public function setRelated(string $relation, $related)
	{
		$this->related[$relation] = $related;
	}

	/**
	 * Returns the related records array.
	 *
	 * @return array
	 */
	public function getRelated(): array
	{
		return $this->related;
	}

	/**
	 * Cast value to the appropriate type.
	 *
	 * @param  string $name  Column name
	 * @param  mixed  $value Column value
	 * @return mixed
	 */
	protected function cast(string $name, $value)
	{
		if(isset($this->cast[$name]) && $value !== null)
		{
			switch($this->cast[$name])
			{
				case 'int':
					return (int) $value;
				case 'float':
					return (float) $value;
				case 'bool':
					return $value === 'f' ? false : (bool) $value;
				case 'date':
					return ($value instanceof DateTimeInterface) ? $value : Time::createFromFormat($this->getDateFormat(), $value);
				case 'string':
					return (string) $value;
				default:
					throw new RuntimeException(vsprintf('Unsupported type [ %s ].', [$this->cast[$name]]));
			}
		}

		return $value;
	}

	/**
	 * Sets a raw column value.
	 *
	 * @param string $name  Column name
	 * @param mixed  $value Column value
	 */
	public function setRawColumnValue(string $name, $value)
	{
		$this->columns[$name] = $this->cast($name, $value);
	}

	/**
	 * Sets a column value.
	 *
	 * @param string $name  Column name
	 * @param mixed  $value Column value
	 */
	public function setColumnValue(string $name, $value)
	{
		$value = $this->cast($name, $value);

		if(method_exists($this, $name . 'Mutator'))
		{
			$this->columns[$name] = $this->{$name . 'Mutator'}($value);
		}
		else
		{
			$this->columns[$name] = $value;
		}
	}

	/**
	 * Gets a raw column value.
	 *
	 * @param  string $name Column name
	 * @return mixed
	 */
	public function getRawColumnValue(string $name)
	{
		return $this->columns[$name];
	}

	/**
	 * Returns a column value.
	 *
	 * @param  string $name Column name
	 * @return mixed
	 */
	public function getColumnValue(string $name)
	{
		if(method_exists($this, $name . 'Accessor'))
		{
			return $this->{$name . 'Accessor'}($this->columns[$name]);
		}

		return $this->columns[$name];
	}

	/**
	 * Returns TRUE if it's probable that $name is a relation and FALSE if not.
	 *
	 * @param  string $name Relation name
	 * @return bool
	 */
	protected function isRelation(string $name): bool
	{
		return method_exists(self::class, $name) === false && method_exists($this, $name);
	}

	/**
	 * Gets a column value or relation.
	 *
	 * @param  string $name Column name
	 * @return mixed
	 */
	public function getValue(string $name)
	{
		if(array_key_exists($name, $this->columns))
		{
			// It's a database column

			return $this->getColumnValue($name);
		}
		elseif(array_key_exists($name, $this->related))
		{
			// The column is a cached or eagerly loaded relation

			return $this->related[$name];
		}
		elseif($this->isRelation($name))
		{
			// The column is a relation. Lazy load the records and cache them

			return $this->related[$name] = $this->{$name}()->getRelated();
		}
		else
		{
			throw new RuntimeException(vsprintf('Unknown column or relation [ %s ].', [$name]));
		}
	}

	/**
	 * Returns the columns array.
	 *
	 * @return array
	 */
	public function getRawColumnValues(): array
	{
		return $this->columns;
	}

	/**
	 * Sets column values.
	 *
	 * @param array $columns Column values
	 * @param bool  $raw     Set raw values?
	 */
	protected function setColumValues(array $columns, bool $raw)
	{
		if($raw)
		{
			if(empty($this->cast))
			{
				$this->columns = $columns;
			}
			else
			{
				foreach($columns as $column => $value)
				{
					$this->setRawColumnValue($column, $value);
				}
			}
		}
		else
		{
			foreach($columns as $column => $value)
			{
				$this->setColumnValue($column, $value);
			}
		}
	}

	/**
	 * Assigns the column values to the model.
	 *
	 * @param  array                      $columns   Column values
	 * @param  bool                       $raw       Set raw values?
	 * @param  bool                       $whitelist Remove columns that are not in the whitelist?
	 * @return \mako\database\midgard\ORM
	 */
	public function assign(array $columns, bool $raw = false, bool $whitelist = true): ORM
	{
		// Remove columns that are not in the whitelist

		if($whitelist && !empty($this->assignable))
		{
			$columns = array_intersect_key($columns, array_flip($this->assignable));
		}

		// Remove the primary key if the model has already beed loaded

		if($this->exists && isset($columns[$this->primaryKey]))
		{
			unset($columns[$this->primaryKey]);
		}

		// Set column values

		$this->setColumValues($columns, $raw);

		return $this;
	}

	/**
	 * Set column value using overloading.
	 *
	 * @param string $name  Column name
	 * @param mixed  $value Column value
	 */
	public function __set(string $name, $value)
	{
		$this->setColumnValue($name, $value);
	}

	/**
	 * Get column value or relation using overloading.
	 *
	 * @param  string $name Column name
	 * @return mixed
	 */
	public function __get(string $name)
	{
		return $this->getValue($name);
	}

	/**
	 * Checks if a column or relation is set using overloading.
	 *
	 * @param  string $name Column name
	 * @return bool
	 */
	public function __isset(string $name)
	{
		return isset($this->columns[$name]) || isset($this->related[$name]) || ($this->isRelation($name) && $this->$name && isset($this->related[$name]));
	}

	/**
	 * Unset column value or relation using overloading.
	 *
	 * @param string $name Column name
	 */
	public function __unset(string $name)
	{
		unset($this->columns[$name], $this->related[$name]);
	}

	/**
	 * Returns a query builder instance.
	 *
	 * @return \mako\database\midgard\Query
	 */
	public function builder(): Query
	{
		return new Query($this->getConnection(), $this);
	}

	/**
	 * Returns a record using the value of its primary key.
	 *
	 * @param  mixed                           $id      Primary key
	 * @param  array                           $columns Columns to select
	 * @return \mako\database\midgard\ORM|bool
	 */
	public static function get($id, array $columns = [])
	{
		return (new static)->builder()->get($id, $columns);
	}

	/**
	 * Creates a new record and returns the model.
	 *
	 * @param  array                      $columns   Column values
	 * @param  bool                       $raw       Set raw values?
	 * @param  bool                       $whitelist Remove columns that are not in the whitelist?
	 * @return \mako\database\midgard\ORM
	 */
	public static function create(array $columns, bool $raw = false, bool $whitelist = true): ORM
	{
		$model = new static($columns, $raw, $whitelist);

		$model->save();

		return $model;
	}

	/**
	 * Returns a HasOne relation.
	 *
	 * @param  string                                  $model      Related model
	 * @param  string|null                             $foreignKey Foreign key name
	 * @return \mako\database\midgard\relations\HasOne
	 */
	protected function hasOne(string $model, string $foreignKey = null): HasOne
	{
		$related = new $model;

		return new HasOne($related->getConnection(), $this, $related, $foreignKey);
	}

	/**
	 * Returns a HasOnePolymorphic relation.
	 *
	 * @param  string                                              $model           Related model
	 * @param  string                                              $polymorphicType Polymorphic type
	 * @return \mako\database\midgard\relations\HasManyPolymorphic
	 */
	protected function hasOnePolymorphic(string $model, string $polymorphicType): HasOnePolymorphic
	{
		$related = new $model;

		return new HasOnePolymorphic($related->getConnection(), $this, $related, $polymorphicType);
	}

	/**
	 * Returns a HasMany relation.
	 *
	 * @param  string                                   $model      Related model
	 * @param  string|null                              $foreignKey Foreign key name
	 * @return \mako\database\midgard\relations\HasMany
	 */
	protected function hasMany(string $model, string $foreignKey = null): HasMany
	{
		$related = new $model;

		return new HasMany($related->getConnection(), $this, $related, $foreignKey);
	}

	/**
	 * Returns a HasManyPolymorphic relation.
	 *
	 * @param  string                                              $model           Related model
	 * @param  string                                              $polymorphicType Polymorphic type
	 * @return \mako\database\midgard\relations\HasManyPolymorphic
	 */
	protected function hasManyPolymorphic(string $model, string $polymorphicType): HasManyPolymorphic
	{
		$related = new $model;

		return new HasManyPolymorphic($related->getConnection(), $this, $related, $polymorphicType);
	}

	/**
	 * Returns a ManyToMany relation.
	 *
	 * @param  string                                      $model         Related model
	 * @param  string|null                                 $foreignKey    Foreign key name
	 * @param  string|null                                 $junctionTable Junction table name
	 * @param  string|null                                 $junctionKey   Junction key name
	 * @return \mako\database\midgard\relations\ManyToMany
	 */
	protected function manyToMany(string $model, string $foreignKey = null, string $junctionTable = null, string $junctionKey = null): ManyToMany
	{
		$related = new $model;

		return new ManyToMany($related->getConnection(), $this, $related, $foreignKey, $junctionTable, $junctionKey);
	}

	/**
	 * Returns a BelongsTo relation.
	 *
	 * @param  string                                     $model      Related model
	 * @param  string|null                                $foreignKey Foreign key name
	 * @return \mako\database\midgard\relations\BelongsTo
	 */
	protected function belongsTo(string $model, string $foreignKey = null): BelongsTo
	{
		$related = new $model;

		return new BelongsTo($related->getConnection(), $this, $related, $foreignKey);
	}

	/**
	 * Has the record been modified?
	 *
	 * @return bool
	 */
	public function isModified(): bool
	{
		return count($this->getModified()) > 0;
	}

	/**
	 * Returns the modified column values of the record.
	 *
	 * @return array
	 */
	public function getModified(): array
	{
		$modified = [];

		foreach($this->columns as $key => $value)
		{
			if(!array_key_exists($key, $this->original) || $this->original[$key] !== $value)
			{
				$modified[$key] = $value;
			}
		}

		return $modified;
	}

	/**
	 * Generates a primary key.
	 *
	 * @return mixed
	 */
	protected function generatePrimaryKey()
	{
		throw new RuntimeException(vsprintf('The [ %s::generatePrimaryKey() ] method must be implemented.', [static::class]));
	}

	/**
	 * Inserts a new record into the database.
	 *
	 * @param \mako\database\midgard\Query $query Query builder
	 */
	protected function insertRecord(Query $query)
	{
		if($this->primaryKeyType === static::PRIMARY_KEY_TYPE_INCREMENTING)
		{
			$this->columns[$this->primaryKey] = $query->insertAndGetId($this->columns, $this->primaryKey);
		}
		else
		{
			switch($this->primaryKeyType)
			{
				case static::PRIMARY_KEY_TYPE_UUID:
					$this->columns[$this->primaryKey] = UUID::v4();
					break;
				case static::PRIMARY_KEY_TYPE_CUSTOM:
					$this->columns[$this->primaryKey] = $this->generatePrimaryKey();
					break;
			}

			$query->insert($this->columns);
		}
	}

	/**
	 * Updates an existing record.
	 *
	 * @param  \mako\database\midgard\Query $query Query builder
	 * @return bool
	 */
	protected function updateRecord(Query $query): bool
	{
		$query->where($this->primaryKey, '=', $this->columns[$this->primaryKey]);

		return (bool) $query->update($this->getModified());
	}

	/**
	 * Saves the record to the database.
	 *
	 * @return bool
	 */
	public function save(): bool
	{
		$success = true;

		if(!$this->exists)
		{
			// This is a new record so we need to insert it into the database.

			$this->insertRecord($this->builder());

			$this->exists = true;
		}
		elseif($this->isModified())
		{
			// This record exists and is modified so all we have to do is update it.

			$success = $this->updateRecord($this->builder());
		}

		if($success)
		{
			// Sync up if save was successful

			$this->synchronize();
		}

		return $success;
	}

	/**
	 * Deletes a record from the database.
	 *
	 * @param  \mako\database\midgard\Query $query Query builder
	 * @return bool
	 */
	protected function deleteRecord(Query $query): bool
	{
		return (bool) $query->where($this->primaryKey, '=', $this->columns[$this->primaryKey])->delete();
	}

	/**
	 * Deletes a record from the database.
	 *
	 * @return bool
	 */
	public function delete(): bool
	{
		if($this->exists)
		{
			$deleted = $this->deleteRecord($this->builder());

			if($deleted)
			{
				$this->exists   = false;
				$this->original = [];
				$this->related  = [];
			}

			return $deleted;
		}

		return false;
	}

	/**
	 * Excludes the chosen columns and relations from array and json representations of the record.
	 * You expose all fields by passing FALSE.
	 *
	 * @param  string|array|bool          $column Column or relation to hide from the
	 * @return \mako\database\midgard\ORM
	 */
	public function protect($column): ORM
	{
		if($column === false)
		{
			$this->protected = [];
		}
		else
		{
			$this->protected = array_unique(array_merge($this->protected, (array) $column));
		}

		return $this;
	}

	/**
	 * Exposes the chosen columns and relations in the array and json representations of the record.
	 * You can expose all fields by passing TRUE.
	 *
	 * @param  string|array|bool          $column Column or relation to hide from the
	 * @return \mako\database\midgard\ORM
	 */
	public function expose($column): ORM
	{
		if($column === true)
		{
			$this->protected = [];
		}
		else
		{
			$this->protected = array_diff($this->protected, (array) $column);
		}

		return $this;
	}

	/**
	 * Returns an array representation of the record.
	 *
	 * @return array
	 */
	public function toArray(): array
	{
		$columns = $this->columns;

		// Removes protected columns from the array

		if(!empty($this->protected))
		{
			$columns = array_diff_key($columns, array_flip($this->protected));
		}

		// Mutate column values if needed

		foreach($columns as $name => $value)
		{
			$value = $this->getColumnValue($name);

			if($value instanceof DateTimeInterface)
			{
				$value = $value->format($this->dateOutputFormat);
			}

			$columns[$name] = $value;
		}

		// Merge in related records

		foreach($this->related as $relation => $related)
		{
			if(in_array($relation, $this->protected))
			{
				continue;
			}

			$columns += [$relation => ($related === false ? $related : $related->toArray())];
		}

		// Returns array representation of the record

		return $columns;
	}

	/**
	 * Returns data which can be serialized by json_encode().
	 *
	 * @return array
	 */
	public function jsonSerialize(): array
	{
		return $this->toArray();
	}

	/**
	 * Returns a json representation of the record.
	 *
	 * @param  int    $options JSON encode options
	 * @return string
	 */
	public function toJson(int $options = 0): string
	{
		return json_encode($this->toArray(), $options);
	}

	/**
	 * Returns a json representation of the record.
	 *
	 * @return string
	 */
	public function __toString(): string
	{
		return $this->toJson();
	}

	/**
	 * Forwards method calls to the query builder.
	 *
	 * @param  string $name      Method name
	 * @param  array  $arguments Method arguments
	 * @return mixed
	 */
	public function __call(string $name, array $arguments)
	{
		return $this->builder()->{$name}(...$arguments);
	}

	/**
	 * Forwards static method calls to the query builder.
	 *
	 * @param  string $name      Method name
	 * @param  array  $arguments Method arguments
	 * @return mixed
	 */
	public static function __callStatic(string $name, array $arguments)
	{
		return (new static)->builder()->{$name}(...$arguments);
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
   <S:Body>
      <ns6:RepairDetailsResponse xmlns:ns2="http://asp.core.endpoint.ws.gsx.ist.apple.com/" xmlns:ns3="http://gsxws.apple.com/elements/global" xmlns:ns4="http://gsxws.apple.com/elements/core/asp" xmlns:ns5="http://gsxws.apple.com/elements/core/asp/am" xmlns:ns6="http://gsxws.apple.com/elements/core">
         <RepairDetailsResponse>
            <operationId>2ed251309391636165</operationId>
            <lookupResponseData>
               <repairConfirmationNumber>2093174681</repairConfirmationNumber>
               <soldToCode>0000033523</soldToCode>
               <warrantyDescription>Out Of Warranty (No Coverage)</warrantyDescription>
               <dispatchId>G2093174681</dispatchId>
               <sroNumber>030044147665</sroNumber>
               <serialNumber>UV45204MS85</serialNumber>
               <dispatchSentDate>2011-01-27 11:45:01 PST</dispatchSentDate>
               <coverageStatusDescription>Out Of Warranty (No Coverage)</coverageStatusDescription>
               <productName>iBook G4 (14-inch Late 2004)</productName>
               <configuration>IBOOK 14.1/1.33G/CTO</configuration>
               <purchaseOrderNumber>321213213</purchaseOrderNumber>
               <referenceNumber>2123123</referenceNumber>
               <isACPlusConsumed>N</isACPlusConsumed>
               <notes>Customer Reported Symptom:sa
               Service Provider Diagnosis:asda
               Notes:ad
               -Address Cosmetic Damage? No</notes>
               <notaFiscalNumber>123456789</notaFiscalNumber>
               <primaryAddress>
                  <addressLine1>155 ca</addressLine1>
                  <country>US</country>
                  <zipCode>95014</zipCode>
                  <county>Madera</county>
                  <region>005</region>
                  <city>CUPERTINO</city>
                  <firstName>Ääkköset</firstName>
                  <lastName>Tässäkin</lastName>
                  <primaryPhone>999999999</primaryPhone>
               </primaryAddress>
               <partsInfo>
                  <partNumber>076-1157</partNumber>
                  <partDescription>Foot Kit, Rubber Feet and Sockets</partDescription>
                  <partCoverageDescription>Out Of Warranty (No Coverage)</partCoverageDescription>
                  <orderStatus>Outbound Order Created</orderStatus>
                  <orderStatusCode>ORDC</orderStatusCode>
                  <orderStatusDate>2012-04-30 01:26:48 -07:00</orderStatusDate>
                  <returnStatus>NRET</returnStatus>
                  <returnCode>NRET</returnCode>
                  <orderNumber>7148187912</orderNumber>
                  <orderLineNumber>4</orderLineNumber>
                  <isSerialized>N</isSerialized>
                  <notaFiscalNumber>123456789</notaFiscalNumber>
               </partsInfo>
               <partsInfo>
                  <partNumber>076-1255</partNumber>
                  <partDescription>VC,SCREWS,IBOOK MLB, W/NYLOCK</partDescription>
                  <partCoverageDescription>Out Of Warranty (No Coverage)</partCoverageDescription>
                  <orderStatus>Outbound Order Created</orderStatus>
                  <orderStatusCode>ORDC</orderStatusCode>
                  <orderStatusDate>2012-04-30 05:16:28 -07:00</orderStatusDate>
                  <returnStatus>NRET</returnStatus>
                  <returnCode>NRET</returnCode>
                  <orderNumber>7148187912</orderNumber>
                  <orderLineNumber>5</orderLineNumber>
                  <isSerialized>N</isSerialized>
                  <notaFiscalNumber>123456789</notaFiscalNumber>
               </partsInfo>
               <partsInfo>
                  <partNumber>ACSH08</partNumber>
                  <partDescription>SHIPPING CHARGES FOR CARRY-IN ORDER</partDescription>
                  <orderStatus>Outbound Order Created</orderStatus>
                  <orderStatusCode>ORDC</orderStatusCode>
                  <orderStatusDate>2012-04-30 18:29:58 -07:00</orderStatusDate>
                  <orderNumber>7148187912</orderNumber>
                  <orderLineNumber>6</orderLineNumber>
                  <isSerialized>N</isSerialized>
                  <notaFiscalNumber>123456789</notaFiscalNumber>
               </partsInfo>
               <acPlusFlag>N</acPlusFlag>
            </lookupResponseData>
            <communicationMessage/>
         </RepairDetailsResponse>
      </ns6:RepairDetailsResponse>
   </S:Body>
</S:Envelope>

redpajama_set_name: RedPajamaGithub


text:
class DecMplsTTLAction < Action

# _Parameters_
# * +order+:: integer : The order of the action relative to other actions in Instruction.
  def initialize(order: 0)
    super(order: order)
  end

  def to_hash
    {:order => @order, 'dec-mpls-ttl' => {}}
  end
end


text:
package Server;

import java.net.*;
import java.io.*;

//Test Kommentar! gdff
public class Conn extends Thread{

	private int id;
	private String nick;
	private boolean ready;	//raus und in Mechanics

	public boolean isReady() {
		return ready;
	}

	public void setReady(boolean ready) {
		this.ready = ready;
	}

	private Socket socket;
	private PrintWriter out = null;
	private BufferedReader in = null;
	private boolean active = true;
	private Handler handler;

public Conn (Socket socket,  Handler handler) {
	this.socket = socket;
	this.handler = handler;
	try {
		out = new PrintWriter(socket.getOutputStream(), true);
		in = new BufferedReader(new InputStreamReader( socket.getInputStream()));
	} catch (IOException e) {
		// TODO Auto-generated catch block
		close();
		e.printStackTrace();

	}

	start();
}

public void run() {
	send("CONNECTED "); //damit Client-Thread beginnt
	System.out.print("Run gestartet...Server");
	int tmp = this.handler.getPlayerID(this);
	if(tmp!=-1){
		this.id = tmp;
	} else {
		System.out.println("Error while asking for Player ID");
	}

	while(active){		//horchen
			String txt;
			try {
				if ((txt = in.readLine()) != null) {
					System.out.println("Server bekommt: " + txt + ";" + this.nick);
					handler.handleString(txt, this);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				close();
			}
	}
}

public void send (String txt){
	System.out.println("Server sendet: " + txt);
	out.println(txt);
}

public void close(){
	active = false;
	handler.spread("CHAT " + handler.getPlayerID(this)+ " " + nick + " hat das Spiel verlassen.");
	//socket.close();
}

public String getNick() {
	return nick;
}

public void setNick(String nick) {
	this.nick = nick;
}

}


text:
using System;
using Akka.Cluster.Tools.PublishSubscribe;
using Akka.Configuration;
using Xunit;

namespace Akka.Cluster.Tools.Tests.PublishSubscribe
{
    public class DistributedPubSubConfigSpec : TestKit.Xunit2.TestKit
    {
        public DistributedPubSubConfigSpec() : base(GetConfig())
        {
        }

        public static Config GetConfig()
        {
            return ConfigurationFactory.ParseString("akka.actor.provider = \"Akka.Cluster.ClusterActorRefProvider, Akka.Cluster\"");
        }

        [Fact]
        public void Should_distributed_pub_sub_settings_have_default_config()
        {
            DistributedPubSub.Get(Sys);
            var config = Sys.Settings.Config.GetConfig("akka.cluster.pub-sub");

            Assert.NotNull(config);
            Assert.Equal("distributedPubSubMediator", config.GetString("name"));
            Assert.Equal(string.Empty, config.GetString("role"));
            Assert.Equal("random", config.GetString("routing-logic"));
            Assert.Equal(TimeSpan.FromSeconds(1), config.GetTimeSpan("gossip-interval"));
            Assert.Equal(TimeSpan.FromSeconds(120), config.GetTimeSpan("removed-time-to-live"));
            Assert.Equal(3000, config.GetInt("max-delta-elements"));
            Assert.Equal(string.Empty, config.GetString("use-dispatcher"));
        }
    }
}


text:
package plzinit

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"github.com/thought-machine/please/src/assets"
	"github.com/thought-machine/please/src/cli"
	"github.com/thought-machine/please/src/cli/logging"
	"github.com/thought-machine/please/src/core"
	"github.com/thought-machine/please/src/fs"
	"github.com/thought-machine/please/src/scm"
)

const configTemplate = `; Please config file
; Leaving this file as is is enough to use plz to build your project.
; Please will stay on whatever version you currently have until you run
; 'plz update', when it will download the latest available version.
;
; Or you can uncomment the following to pin everyone to a particular version;
; when you change it all users will automatically get updated.
; [please]
; version = %s
`

const bazelCompatibilityConfig = `
[bazel]
compatibility = true
`
const wrapperScriptName = "pleasew"

const pleasingsSubrepoTemplate = `
github_repo(
  name = "pleasings",
  repo = "thought-machine/pleasings",
  revision = "%s",
)
`

var log = logging.Log

// InitConfig initialises a .plzconfig template in the given directory.
func InitConfig(dir string, bazelCompatibility bool, noPrompt bool) {
	if dir == "." {
		if core.FindRepoRoot() {
			if noPrompt {
				log.Fatalf("This repository is already initialised with a .plzconfig. Aborting.")
			}
			config := filepath.Join(core.RepoRoot, core.ConfigFileName)
			if !cli.PromptYN(fmt.Sprintf("You already seem to be in a plz repo (found %s). Continue", config), false) {
				os.Exit(1)
			}
		}
	}
	dir, err := filepath.Abs(dir)
	if err != nil {
		log.Warning("Can't determine absolute directory: %s", err)
	}
	config := filepath.Join(dir, core.ConfigFileName)
	contents := fmt.Sprintf(configTemplate, core.PleaseVersion)

	if bazelCompatibility {
		contents += bazelCompatibilityConfig
	}

	contents += golangConfig(dir, noPrompt)

	if err := os.WriteFile(config, []byte(contents), 0644); err != nil {
		log.Fatalf("Failed to write file: %s", err)
	}
	fmt.Printf("Wrote config template to %s, you're now ready to go!\n", config)
	// Now write the wrapper script
	InitWrapperScript()
	fmt.Printf("\nAlso wrote wrapper script to %s; users can invoke that directly to run Please, even without it installed.\n", wrapperScriptName)
	// If we're in a known repository type, ignore the plz-out directory.
	if s := scm.New(dir); s != nil {
		fmt.Printf("Also marking plz-out to be ignored by your SCM.\n")
		if err := s.IgnoreFiles(".gitignore", nil); err != nil {
			log.Error("Failed to ignore plz-out: %s", err)
		}
	}
}

// InitConfigFile sets a bunch of values in a config file.
func InitConfigFile(filename string, options map[string]string) {
	b := readConfig(filename)
	for k, v := range options {
		parts := strings.Split(k, ".")
		if len(parts) != 2 {
			log.Fatalf("unknown key format: %s", k)
		}
		b = append(b, []byte(fmt.Sprintf("[%s]\n%s = %s\n", parts[0], parts[1], v))...)
	}
	if err := fs.EnsureDir(filename); err != nil {
		log.Fatalf("Cannot create directory for new file: %s", err)
	} else if err := os.WriteFile(filename, b, 0644); err != nil {
		log.Fatalf("Failed to write updated config file: %s", err)
	}
}

func readConfig(filename string) []byte {
	if !fs.PathExists(filename) {
		return nil
	}
	b, err := os.ReadFile(filename)
	if err != nil {
		log.Fatalf("Failed to read config file: %s", err)
	}
	return b
}

// InitWrapperScript initialises the pleasew script.
func InitWrapperScript() {
	data := assets.Pleasew
	if err := os.WriteFile(wrapperScriptName, data, 0755); err != nil {
		log.Fatalf("Failed to write file: %s", err)
	}
}


text:
module Locomotive
  module Heroku
    module CustomDomain

      extend ActiveSupport::Concern

      included do
        before_save   :store_domains_to_remove_from_heroku
        after_save    :sync_heroku_domains
        after_destroy :remove_heroku_domains
      end

      protected

      def store_domains_to_remove_from_heroku
        @domains_to_remove = (self.domains_was || []) - [self.full_subdomain_was] - [self.full_subdomain] - self.domains_without_subdomain
      end

      def sync_heroku_domains
        # all the Heroku domains should also referenced in the site, if not then remove them from Heroku.
        (@domains_to_remove || []).each do |domain|
          if Locomotive::Heroku.domains.include?(domain)
            Locomotive::Heroku.remove_domain(domain)
          end
        end

        # Locomotive::Heroku.domains.each do |domain|
        #   unless self.domains_without_subdomain.include?(domain)
        #     Locomotive::Heroku.remove_domain(domain)
        #   end
        # end

        # add the site domains should referenced in the Heroku domains, if not then add them to Heroku
        self.domains_without_subdomain.each do |domain|
          unless Locomotive::Heroku.domains.include?(domain)
            Locomotive::Heroku.add_domain(domain)
          end
        end
      end

      def remove_heroku_domains
        self.domains_without_subdomain.each do |domain|
          Locomotive::Heroku.remove_domain(domain)
        end
      end

    end
  end
end


text:
[CmdletBinding()]
param (
    [Parameter()]
    [scriptblock] $ScriptBlock,
    [ValidateSet('Powershell', 'Pwsh')]
    $Shell = 'Powershell',
    [string[]]$PSArgs = ('-NoProfile', '-NoExit')
)
$argList = $PSArgs + @('-Command', 'Invoke-Command', '-ScriptBlock', "{$ScriptBlock}")
Write-Verbose "$Shell $argList"

$process = Start-Process $Shell -Verb RunAs -PassThru -ArgumentList $argList
# so waits for the end...
$process.WaitForExit()


text:
module API
  # groups API
  class Groups < Grape::API
    before { authenticate! }

    resource :groups do
      helpers do
        def find_group(id)
          group = Group.find(id)

          if can?(current_user, :read_group, group)
            group
          else
            render_api_error!("403 Forbidden - #{current_user.username} lacks sufficient access to #{group.name}", 403)
          end
        end

        def validate_access_level?(level)
          Gitlab::Access.options_with_owner.values.include? level.to_i
        end
      end

      # Get a groups list
      #
      # Example Request:
      #  GET /groups
      get do
        if current_user.admin
          @groups = paginate Group
        else
          @groups = paginate current_user.groups
        end
        present @groups, with: Entities::Group
      end

      # Create group. Available only for admin
      #
      # Parameters:
      #   name (required) - The name of the group
      #   path (required) - The path of the group
      # Example Request:
      #   POST /groups
      post do
        authenticated_as_admin!
        required_attributes! [:name, :path]

        attrs = attributes_for_keys [:name, :path]
        @group = Group.new(attrs)
        @group.owner = current_user

        if @group.save
          present @group, with: Entities::Group
        else
          not_found!
        end
      end

      # Get a single group, with containing projects
      #
      # Parameters:
      #   id (required) - The ID of a group
      # Example Request:
      #   GET /groups/:id
      get ":id" do
        group = find_group(params[:id])
        present group, with: Entities::GroupDetail
      end

      # Remove group
      #
      # Parameters:
      #   id (required) - The ID of a group
      # Example Request:
      #   DELETE /groups/:id
      delete ":id" do
        group = find_group(params[:id])
        authorize! :manage_group, group
        group.destroy
      end

      # Transfer a project to the Group namespace
      #
      # Parameters:
      #   id - group id
      #   project_id  - project id
      # Example Request:
      #   POST /groups/:id/projects/:project_id
      post ":id/projects/:project_id" do
        authenticated_as_admin!
        @group = Group.find(params[:id])
        project = Project.find(params[:project_id])
        if project.transfer(@group)
          present @group
        else
          not_found!
        end
      end

      # Get a list of group members viewable by the authenticated user.
      #
      # Example Request:
      #  GET /groups/:id/members
      get ":id/members" do
        group = find_group(params[:id])
        members = group.users_groups
        users = (paginate members).collect(&:user)
        present users, with: Entities::GroupMember, group: group
      end

      # Add a user to the list of group members
      #
      # Parameters:
      #   id (required) - group id
      #   user_id (required) - the users id
      #   access_level (required) - Project access level
      # Example Request:
      #  POST /groups/:id/members
      post ":id/members" do
        required_attributes! [:user_id, :access_level]
        unless validate_access_level?(params[:access_level])
          render_api_error!("Wrong access level", 422)
        end
        group = find_group(params[:id])
        if group.users_groups.find_by(user_id: params[:user_id])
          render_api_error!("Already exists", 409)
        end
        group.add_users([params[:user_id]], params[:access_level])
        member = group.users_groups.find_by(user_id: params[:user_id])
        present member.user, with: Entities::GroupMember, group: group
      end

      # Remove member.
      #
      # Parameters:
      #   id (required) - group id
      #   user_id (required) - the users id
      #
      # Example Request:
      #   DELETE /groups/:id/members/:user_id
      delete ":id/members/:user_id" do
        group = find_group(params[:id])
        member =  group.users_groups.find_by(user_id: params[:user_id])
        if member.nil?
          render_api_error!("404 Not Found - user_id:#{params[:user_id]} not a member of group #{group.name}",404)
        else
          member.destroy
        end
      end
    end
  end
end


text:
_Bool checkEnv(const char* name) {
    const char* env  = getenv(name);
    return (env != 0 && strcmp(env, "1") == 0);
}

@implementation AppDelegate

- (void)dealloc
{
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    if (!checkEnv("debug")) {
        exit(0);
    }
    if (!checkEnv("demo")) {
        self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
        self.window.rootViewController = [UIViewController new];
        self.window.rootViewController.view.backgroundColor = UIColor.blackColor;
        [self.window makeKeyAndVisible];
#if true // test legacy
//		[CoreDataEnvir.backgroundInstance asyncWithBlock:^(CoreDataEnvir * _Nonnull db) {
//			[Team insertItemInContext:db fillData:^(Team*  _Nonnull item) {
//				item.name = @"CybLion";
//			}];
//			[db saveDataBase];
//		}];

//		[Team insertItemOnBackgroundWithFillingBlock:^(Team*  _Nonnull item) {
//			item.name = @"Lion";
//		}];

//        [Team insertItemWithFillingBlock:^(Team* item) {
//            item.name = @"Lion";
//            [item save];
//        }];

		CoreDataEnvir* db = [CoreDataEnvirDescriptor.defaultInstance backgroundInstance];
		[Team insertItemInContext:db];
		[db saveDataBase];
        printf("Team total count: %lu\n", Team.totalCount);
#else
        NSURL* modelURL = [NSBundle.mainBundle URLForResource:@"SampleModel" withExtension:@"momd"];
        CoreDataEnvirBlock initBlock = ^(CoreDataEnvir* db) {
            [db setupModelWithURL:modelURL];

            NSString* searchedPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true) lastObject];
            NSLog(@"search path: %@", searchedPath);
            NSURL* dbURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/db.sqlite", searchedPath]];
            NSLog(@"dbURL: %@", dbURL);
            if (dbURL) {
                [db setupDefaultPersistentStoreWithURL:dbURL];
            }
        };
        CoreDataEnvir* db = [CoreDataEnvir create];
        [db setupWithBlock:initBlock];
        CoreDataEnvir* db2 = [CoreDataEnvir create];
        [db2 setupWithBlock:initBlock];

        [db syncInBlock:^(CoreDataEnvir * _Nonnull db) {
            Team* obj = [Team insertItemInContext:db];
            obj.name = @"new pattern";
            [db saveDataBase];

            NSFetchRequest* req = [Team newFetchRequestInContext:db];
            NSError* err = nil;
            NSUInteger count = [db.context countForFetchRequest:req error:&err];
            printf("Team total count: %lu\n", count);
        }];

#endif
        return true;
    }
	NSLog(@"CoreDataEnvirVersionString: %s", CoreDataEnvirVersionString);
	NSLog(@"CoreDataEnvirVersionNumber: %f", CoreDataEnvirVersionNumber);
    //Set db file name and model file name.
//    [CoreDataEnvir registerDefaultDataFileName:@"db.sqlite"];
//    [CoreDataEnvir registerDefaultModelFileName:@"SampleModel"];

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.viewController = [[ViewController alloc] initWithNibName:nil bundle:nil];
    self.navigationController = [[UINavigationController alloc] initWithRootViewController:self.viewController];

    //NSLog(@"ver: %f", CoreDataEnvirVersionNumber);

    self.window.rootViewController = self.navigationController;
    [self.window makeKeyAndVisible];

    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end


text:
Thanks for reading our contribution guidelines! What do you want to do:

* [File a bug / an issue](#filing-issue)
* [Security issues](#security)
* [Contribute to Yoast SEO](#contribute)

#Filing issues

__Please Note:__ GitHub is for bug reports and code contributions only - if you have a support question or a request for a customisation don't post here, go to our [Support Forum](http://wordpress.org/support/plugin/wordpress-seo) instead.

For localization, please refer to [translate.yoast.com](http://translate.yoast.com/projects/wordpress-seo), though bugs with strings that can't be translated are welcome here.

## How to write a useful bug report
If you think you have found a bug (we acknowledge that that's a possibility), please make sure you're using the latest version of the plugin. If possible check out the latest version from GitHub and see if the bug still exists there.

A useful bug report explains:

1. What you were trying to achieve.
2. What you were expecting to happen.
3. What actually happened, illustrated with screenshots if possible.

Your bug report should also contain your WordPress version and if there are any errors, the _exact_ error text, including line numbers.

### Blank / white screen
If you're getting a blank screen and you report just that, we can do _absolutely_ nothing. By default, your WordPress install suppresses all errors, to prevent information leaks, but we need those errors to be able to help you. If you apply the small piece of code in [this post on WP_DEBUG](https://yoast.com/wordpress-debug/) to your site, you should be able to open the URL that gave you a white screen, append `?debug=debug` to the URL and get the actual error.

That error will help us, without that error, we're completely in the dark about your white page problem...

### Interface errors
If you're reporting a bug about specific interface elements not working as expected, there's probably an error showing in your browsers JavaScript console. Please open your browsers console and copy the exact error showing there, or make a screenshot. If you don't know how to open your browsers console, here is info for [Chrome](https://developer.chrome.com/devtools/docs/console) and [Firefox](https://developer.mozilla.org/en/docs/Tools/Web_Console). For IE, some Googling will help but it changes with every version.

#Security issues
Please do _not_ report security issues here, but email them to security at yoast dot com so we can deal with them securely and quickly.

#Contribute to Yoast SEO

Community made patches, localisations, bug reports and contributions are very welcome and help make Yoast SEO remains the #1 SEO plugin for WordPress.

When contributing please ensure you follow the guidelines below so that we can keep on top of things.

## Getting Started

If there is no ticket for your issue, submit it first, following the above guidelines.

## Making Changes

* Fork the repository on GitHub (make sure to use the trunk branch, not master).
* Make the changes to your forked repository.
  * Ensure you stick to the [WordPress Coding Standards](http://make.wordpress.org/core/handbook/coding-standards/) and have properly documented any new functions, actions and filters following the [documentation standards](http://make.wordpress.org/core/handbook/inline-documentation-standards/php-documentation-standards/).
* When committing, reference your issue (if present) and include a note about the fix.
* Push the changes to your fork and submit a pull request to the 'trunk' branch of the Yoast SEO repository.

At this point you're waiting on us to merge your pull request. We'll review all pull requests, and make suggestions and changes if necessary.

## "Patch welcome" issues

Some issues are labeled "Patch-welcome". This means we see the value in the particular enhancement being suggested but have decided for now not to prioritize it. If you however decide to write a patch for it we'll gladly include it after some code review.

# Additional Resources
* [Yoast SEO API](https://yoast.com/wordpress/plugins/seo/api/)
* [General GitHub Documentation](http://help.github.com/)
* [GitHub Pull Request documentation](http://help.github.com/send-pull-requests/)


text:
<?php

namespace Sk9\PersonalLibrary\Domain\Events;

use Sk9\PersonalLibrary\Domain\Commands\CreateBookCommand;

class BookWasCreated extends BookEvent
{

    /**
     * @var string $title of the book
     */
    public $title;

    /**
     * @var string $author of the book
     */
    public $author;

    /**
     * @var int number of $pages of the book has
     */
    public $pages;

    /**
     * @var string A $link to amazon to buy this book
     */
    public $link;

    public function __construct(CreateBookCommand $command)
    {
        parent::__construct($command->bookId);
        $this->title = $command->title;
        $this->author = $command->author;
        $this->pages = $command->pages;
        $this->link = $command->link;
    }

}


text:
package com.facebook.react.views.text;

import android.graphics.Paint;
import android.text.style.LineHeightSpan;

/**
 * We use a custom {@link LineHeightSpan}, because `lineSpacingExtra` is broken. Details here:
 * https://github.com/facebook/react-native/issues/7546
 */
public class CustomLineHeightSpan implements LineHeightSpan, ReactSpan {
  private final int mHeight;

  public CustomLineHeightSpan(float height) {
    this.mHeight = (int) Math.ceil(height);
  }

  @Override
  public void chooseHeight(
      CharSequence text, int start, int end, int spanstartv, int v, Paint.FontMetricsInt fm) {
    // This is more complicated that I wanted it to be. You can find a good explanation of what the
    // FontMetrics mean here: http://stackoverflow.com/questions/27631736.
    // The general solution is that if there's not enough height to show the full line height, we
    // will prioritize in this order: descent, ascent, bottom, top

    if (fm.descent > mHeight) {
      // Show as much descent as possible
      fm.bottom = fm.descent = Math.min(mHeight, fm.descent);
      fm.top = fm.ascent = 0;
    } else if (-fm.ascent + fm.descent > mHeight) {
      // Show all descent, and as much ascent as possible
      fm.bottom = fm.descent;
      fm.top = fm.ascent = -mHeight + fm.descent;
    } else if (-fm.ascent + fm.bottom > mHeight) {
      // Show all ascent, descent, as much bottom as possible
      fm.top = fm.ascent;
      fm.bottom = fm.ascent + mHeight;
    } else if (-fm.top + fm.bottom > mHeight) {
      // Show all ascent, descent, bottom, as much top as possible
      fm.top = fm.bottom - mHeight;
    } else {
      // Show proportionally additional ascent / top & descent / bottom
      final int additional = mHeight - (-fm.top + fm.bottom);

      // Round up for the negative values and down for the positive values  (arbitrary choice)
      // So that bottom - top equals additional even if it's an odd number.
      fm.top -= Math.ceil(additional / 2.0f);
      fm.bottom += Math.floor(additional / 2.0f);
      fm.ascent = fm.top;
      fm.descent = fm.bottom;
    }
  }
}


text:
namespace System.Activities.Presentation.Model
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Runtime;

    // This class provides useful shared utility functions that are
    // needed by our ModelItemImpl class implementations.
    internal static class ModelUtilities
    {
        internal static bool IsSwitchCase(ModelItem modelItem)
        {
            if (IsModelItemKeyValuePair(modelItem.ItemType))
            {
                if (modelItem.Parent != null && //modelItem.Parent - ItemsCollection
                    modelItem.Parent.Parent != null && //modelItem.Parent.Parent - Cases
                    modelItem.Parent.Parent.Parent != null && //modelItem.Parent.Parent.Parent - Switch
                    modelItem.Parent.Parent.Parent.ItemType.IsGenericType &&
                    modelItem.Parent.Parent.Parent.ItemType.GetGenericTypeDefinition() == typeof(System.Activities.Statements.Switch<>))
                {
                    return true;
                }
            }
            return false;
        }

        internal static bool IsModelItemKeyValuePair(Type type)
        {
            Fx.Assert(type != null, "Parameter type is null!");
            return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ModelItemKeyValuePair<,>);
        }

        // Returns a wrapped type converter for the given item.
        internal static TypeConverter GetConverter(IModelTreeItem item)
        {
            return GetConverter(item.ModelTreeManager, item.ModelItem);
        }

        // Returns a wrapped converter for the given item.
        internal static TypeConverter GetConverter(ModelTreeManager modelTreeManager, ModelItem item)
        {
            return new ModelTypeConverter(modelTreeManager, XamlUtilities.GetConverter(item.ItemType));
        }

        // Returns the default property on the item, or null if the item has
        internal static PropertyDescriptor GetDefaultProperty(ModelItem item)
        {
            DefaultPropertyAttribute propAttr = TypeDescriptor.GetAttributes(item.ItemType)[typeof(DefaultPropertyAttribute)] as DefaultPropertyAttribute;
            if (propAttr != null && !string.IsNullOrEmpty(propAttr.Name))
            {
                ModelProperty prop = item.Properties.Find(propAttr.Name);
                if (prop != null)
                {
                    return new ModelPropertyDescriptor(prop);
                }
            }
            return null;
        }

        // Wraps an item's properties in PropertyDescriptors and returns a
        // collection of them.
        internal static PropertyDescriptorCollection WrapProperties(ModelItem item)
        {
            List<PropertyDescriptor> descriptors = new List<PropertyDescriptor>();
            foreach (ModelProperty prop in item.Properties)
            {
                descriptors.Add(new ModelPropertyDescriptor(prop));
            }
            return new PropertyDescriptorCollection(descriptors.ToArray(), true);
        }

        internal static ModelItem ReverseFindFirst(ModelItem start, Predicate<ModelItem> matcher)
        {
            Fx.Assert(start != null, "start should not be null");
            Fx.Assert(matcher != null, "matcher should not be null");

            ModelItem result = null;
            ModelUtilities.ReverseTraverse(start, (ModelItem current) =>
            {
                if (matcher(current))
                {
                    result = current;
                    return false;
                }

                return true;
            });
            return result;
        }

        // Traverse model graph via ModelItem's parent. Stop traversing if shouldContinue returns false
        internal static void ReverseTraverse(ModelItem start, Predicate<ModelItem> shouldContinue)
        {
            Fx.Assert(start != null, "start should not be null");
            Fx.Assert(shouldContinue != null, "shouldContinue should not be null");

            HashSet<ModelItem> visited = new HashSet<ModelItem>();
            ModelItem current = start;

            while (current != null)
            {
                if (!shouldContinue(current))
                {
                    return;
                }

                visited.Add(current);
                current = current.Parent;
                if (visited.Contains(current))
                {
                    return;
                }
            }
        }
    }
}


text:
MODULE=vert_scroll.s
FLOPPY=bin/vert_scroll.adf
IMAGEDATA=out/image-palette.s out/image-ham.bin
IMAGEFILE=../assets/gigi_full.png
SIZED_IMAGEFILE=out/image.png

EXTRA=$(IMAGEDATA) init.s utils.s constants.i Makefile
BASE_ADDRESS=10000
DITHER=--dither

include ../shared/base.mk

$(SIZED_IMAGEFILE): $(IMAGEFILE) $(RESIZE) Makefile
	$(RESIZE) --width=320 --height=512 --blur=0.75 --input=$(IMAGEFILE) --output=$(SIZED_IMAGEFILE)

$(IMAGEDATA): $(IMAGECON) $(SIZED_IMAGEFILE) Makefile
	$(IMAGECON) --input $(SIZED_IMAGEFILE) --output out/image --colors 32 --output-bitplanes  --output-palette-asm   $(USE_PALETTE) --output-palette $(DITHER) --quantize


text:
require "cucumber/runtime/gated_receiver"

module Cucumber
  class Runtime
    module TagLimits
      class Filter
        def initialize(tag_limits, receiver)
          @gated_receiver = GatedReceiver.new(receiver)
          @test_case_index = TestCaseIndex.new
          @verifier = Verifier.new(tag_limits)
        end

        def test_case(test_case)
          gated_receiver.test_case(test_case)
          test_case_index.add(test_case)
        end

        def done
          verifier.verify!(test_case_index)
          gated_receiver.done
        end

        private

        attr_reader :gated_receiver
        attr_reader :test_case_index
        attr_reader :verifier
      end
    end
  end
end


text:
package org.entirej.applicationframework.tmt.application.components.menu;

import java.util.List;

import org.entirej.framework.core.data.controllers.EJTranslationController;
import org.entirej.framework.core.interfaces.EJApplicationManager;
import org.entirej.framework.core.properties.EJCoreMenuContainer;
import org.entirej.framework.core.properties.EJCoreMenuLeafActionProperties;
import org.entirej.framework.core.properties.EJCoreMenuLeafContainer;
import org.entirej.framework.core.properties.EJCoreMenuLeafFormProperties;
import org.entirej.framework.core.properties.EJCoreMenuLeafProperties;
import org.entirej.framework.core.properties.EJCoreMenuLeafSpacerProperties;
import org.entirej.framework.core.properties.EJCoreMenuProperties;
import org.entirej.framework.core.properties.EJCoreProperties;

/**
 * Build the menu properties by reading the form files defined in the
 * "Form Package" in applicaiton.ejprop file.

 * Each package will be a menu and each file will be a menu item.

 */
public class EJTMTDefaultMenuPropertiesBuilder
{
    private EJTMTDefaultMenuPropertiesBuilder()
    {
    }

    /**
     * Build a menu item properties based of the form packages defined in the
     * EntireJApplication.properties file and the forms contained in those
     * packages
     *
     * @param applicationManager
     *
     * @return a menu tree root object for opening the forms from the defined
     *         packages
     */
    public static EJTMTMenuTreeRoot buildMenuProperties(EJApplicationManager applicationManager, String menuId)
    {
        EJTMTMenuTreeRoot root = new EJTMTMenuTreeRoot();

        if (menuId != null)
        {
            EJTranslationController translationController = applicationManager.getFrameworkManager().getTranslationController();
            EJCoreMenuContainer menuContainer = EJCoreProperties.getInstance().getMenuContainer();
            EJCoreMenuProperties menuProperties = menuContainer.getMenuProperties(menuId);
            if (menuProperties != null)
            {
                root.setActionProcessorClassName(menuProperties.getActionProcessorClassName());
                translationController.translateMenuProperties(menuProperties);
                List<EJCoreMenuLeafProperties> leaves = menuProperties.getLeaves();
                for (EJCoreMenuLeafProperties leafProperties : leaves)
                {
                    addEJCoreMenuLeafProperties(root, leafProperties);
                }
                return root;
            }

        }

        return root;
    }

    private static void addEJCoreMenuLeafProperties(EJTMTMenuTreeElement parent, EJCoreMenuLeafProperties leafProperties)
    {

        if (leafProperties instanceof EJCoreMenuLeafContainer)
        {
            EJTMTMenuTreeElement subMenu = parent.addSubTreeElement(leafProperties.getDisplayName(), null, leafProperties.getIconName());

            EJCoreMenuLeafContainer container = (EJCoreMenuLeafContainer) leafProperties;
            for (EJCoreMenuLeafProperties subLeafProperties : container.getLeaves())
            {
                addEJCoreMenuLeafProperties(subMenu, subLeafProperties);
            }
            return;
        }
        if (leafProperties instanceof EJCoreMenuLeafSpacerProperties)
        {
            parent.addSeparatorItem();
            return;
        }
        if (leafProperties instanceof EJCoreMenuLeafFormProperties)
        {
            EJCoreMenuLeafFormProperties formLeaf = (EJCoreMenuLeafFormProperties) leafProperties;

            String actionCommand = formLeaf.getFormName();

            parent.addFormMenuItem(formLeaf.getDisplayName(), formLeaf.getHint(), actionCommand, formLeaf.getIconName());
            return;
        }
        if (leafProperties instanceof EJCoreMenuLeafActionProperties)
        {
            EJCoreMenuLeafActionProperties action = (EJCoreMenuLeafActionProperties) leafProperties;

            String actionCommand = action.getMenuAction();

            parent.addActionMenuItem(action.getDisplayName(), action.getHint(), actionCommand, action.getIconName());
            return;
        }
    }
}


text:
<?php

namespace Minsal\sifdaBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Minsal\sifdaBundle\Entity\CtlEstablecimiento;
use Minsal\sifdaBundle\Form\CtlEstablecimientoType;

/**
 * CtlEstablecimiento controller.
 *
 * @Route("/sifda/ctlestablecimiento")
 */
class CtlEstablecimientoController extends Controller
{

    /**
     * Lists all CtlEstablecimiento entities.
     *
     * @Route("/", name="sifda_ctlestablecimiento")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('MinsalsifdaBundle:CtlEstablecimiento')->findAll();

        return array(
            'entities' => $entities,
        );
    }
    /**
     * Creates a new CtlEstablecimiento entity.
     *
     * @Route("/", name="sifda_ctlestablecimiento_create")
     * @Method("POST")
     * @Template("MinsalsifdaBundle:CtlEstablecimiento:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity = new CtlEstablecimiento();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('sifda_ctlestablecimiento_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Creates a form to create a CtlEstablecimiento entity.
     *
     * @param CtlEstablecimiento $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(CtlEstablecimiento $entity)
    {
        $form = $this->createForm(new CtlEstablecimientoType(), $entity, array(
            'action' => $this->generateUrl('sifda_ctlestablecimiento_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    /**
     * Displays a form to create a new CtlEstablecimiento entity.
     *
     * @Route("/new", name="sifda_ctlestablecimiento_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction()
    {
        $entity = new CtlEstablecimiento();
        $form   = $this->createCreateForm($entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Finds and displays a CtlEstablecimiento entity.
     *
     * @Route("/{id}", name="sifda_ctlestablecimiento_show")
     * @Method("GET")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('MinsalsifdaBundle:CtlEstablecimiento')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find CtlEstablecimiento entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to edit an existing CtlEstablecimiento entity.
     *
     * @Route("/{id}/edit", name="sifda_ctlestablecimiento_edit")
     * @Method("GET")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('MinsalsifdaBundle:CtlEstablecimiento')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find CtlEstablecimiento entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
    * Creates a form to edit a CtlEstablecimiento entity.
    *
    * @param CtlEstablecimiento $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(CtlEstablecimiento $entity)
    {
        $form = $this->createForm(new CtlEstablecimientoType(), $entity, array(
            'action' => $this->generateUrl('sifda_ctlestablecimiento_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }
    /**
     * Edits an existing CtlEstablecimiento entity.
     *
     * @Route("/{id}", name="sifda_ctlestablecimiento_update")
     * @Method("PUT")
     * @Template("MinsalsifdaBundle:CtlEstablecimiento:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('MinsalsifdaBundle:CtlEstablecimiento')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find CtlEstablecimiento entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('sifda_ctlestablecimiento_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }
    /**
     * Deletes a CtlEstablecimiento entity.
     *
     * @Route("/{id}", name="sifda_ctlestablecimiento_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('MinsalsifdaBundle:CtlEstablecimiento')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find CtlEstablecimiento entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('sifda_ctlestablecimiento'));
    }

    /**
     * Creates a form to delete a CtlEstablecimiento entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('sifda_ctlestablecimiento_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }
}


text:
<?php

/**
 * Created by PhpStorm.
 * User: ebene
 * Date: 12/1/2016
 * Time: 12:37 PM
 */
class M_Pricing extends CI_Model
{
    function __construct()
    {
        parent::__construct();
    }

    function add_price(){

        $posted_data = array(
            'SOURCE_ID' => $this->input->post('instidd', TRUE),
            'DESTINATION_ID' => $this->input->post('statedd', TRUE),
            'STATE_POINT_ID' => $this->input->post('pointdd', TRUE),
            'CLASS_ID' => $this->input->post('classdd', TRUE),
            'PRICE' => $this->input->post('price', TRUE),
            'PRICE_STATUS' => 1
        );
        $this->db->insert('tbl_pricing', $posted_data);

        return $this->db->insert_id();
    }

    function get_all_prices(){
        $this->db->select('tbl_pricing.SOURCE_ID, DESTINATION_ID, PRICE_ID, PRICE, INSTITUTION, STATE, CLASS_TYPE, PRICE_STATUS, LOCATION');
        $this->db->from('tbl_pricing');
        $this->db->join('tbl_states', 'DESTINATION_ID = STATE_ID');
        $this->db->join('tbl_institutions', 'SOURCE_ID = INSTITUTION_ID');
        $this->db->join('tbl_class', 'tbl_class.CLASS_ID = tbl_pricing.CLASS_ID');
        $this->db->join('tbl_locations', 'LOCATION_ID = STATE_POINT_ID');
        $query = $this->db->get();
        return $query->result();
    }

    function get_active_pricess(){
        $this->db->select('*');
        $this->db->from('tbl_institutions');
        $this->db->where('status', 1);
        $this->db->order_by('institution');
        $query = $this->db->get();

        return $query->result();
    }

    function get_price($id){
        $this->db->select('*');
        $this->db->from('tbl_pricing');
        $this->db->where('price_id', $id);
        $query = $this->db->get();

        return $query->result();
    }

    function change_status($id, $status){
        $this->db->set('price_status', $status);
        $this->db->where('price_id', $id);

        return $this->db->update('tbl_pricing');
    }

    function update_price(){
        $this->db->set('price', $this->input->post('price', TRUE));
        $this->db->where('price_id', $this->input->post('price_id', TRUE));

        return $this->db->update('tbl_pricing');
    }
}


text:
package pl.wavesoftware.wfirma.api.core.model.invoices;

import lombok.Getter;
import lombok.Setter;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import pl.wavesoftware.wfirma.api.core.mapper.xml.BooleanToIntegerAdapter;
import pl.wavesoftware.wfirma.api.core.mapper.xml.CurrencyAdapter;
import pl.wavesoftware.wfirma.api.core.mapper.xml.DateAdapter;
import pl.wavesoftware.wfirma.api.core.mapper.xml.DateWithTimeAdapter;
import pl.wavesoftware.wfirma.api.core.mapper.xml.MoneyAdapter;
import pl.wavesoftware.wfirma.api.core.mapper.xml.TagsAdapter;
import pl.wavesoftware.wfirma.api.core.model.companies.Company;
import pl.wavesoftware.wfirma.api.core.model.contractors.Contractor;
import pl.wavesoftware.wfirma.api.core.model.utils.ReadOnly;
import pl.wavesoftware.wfirma.api.core.model.utils.Reference;
import pl.wavesoftware.wfirma.api.core.util.Copier;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.util.Collection;
import java.util.Date;

/**
 * <p/>
 * A abstract base Java class for invoiceType complex type.
 *
 * @author Krzysztof Suszyński <krzysztof.suszynski@wavesoftware.pl>
 */
@Setter
@Getter
@XmlTransient
public abstract class AbstractInvoice {

    @ReadOnly
    @XmlElement
    private Long id;

    @XmlTransient
    protected TypeOfInvoice type;

    @XmlElement(name = "contractor_detail")
    private Contractor contractorDetail;

    @ReadOnly
    @XmlElement(name = "company_detail")
    private Company companyDetail;

    @XmlElement(name = "paymentmethod")
    private PaymentMethod paymentMethod;

    @XmlJavaTypeAdapter(DateAdapter.class)
    @XmlElement(name = "paymentdate")
    private Date paymentDate;

    @ReadOnly
    @XmlElement(name = "paymentstate")
    private PaymentState paymentState;

    @XmlElement(name = "disposaldate_form")
    private DisposalDateForm disposalDateForm;

    @XmlJavaTypeAdapter(BooleanToIntegerAdapter.class)
    @XmlElement(name = "disposaldate_empty")
    private Boolean disposalDateEmpty;

    @XmlJavaTypeAdapter(DateAdapter.class)
    @XmlElement(name = "disposaldate")
    private Date disposalDate;

    @XmlJavaTypeAdapter(DateAdapter.class)
    @XmlElement
    private Date date;

    @XmlElement
    private Integer period;

    @ReadOnly
    @XmlJavaTypeAdapter(MoneyAdapter.class)
    @XmlElement
    private Money total;

    @ReadOnly
    @XmlJavaTypeAdapter(MoneyAdapter.class)
    @XmlElement(name = "total_composed")
    private Money totalComposed;

    @ReadOnly
    @XmlJavaTypeAdapter(MoneyAdapter.class)
    @XmlElement(name = "alreadypaid")
    private Money alreadyPaid;

    @XmlJavaTypeAdapter(MoneyAdapter.class)
    @XmlElement(name = "alreadypaid_initial")
    private Money alreadyPaidInitial;

    @ReadOnly
    @XmlJavaTypeAdapter(MoneyAdapter.class)
    @XmlElement
    private Money remaining;

    @XmlElement
    private Integer number;

    @XmlElement
    private Integer day;

    @XmlElement
    private Integer month;

    @XmlElement
    private Integer year;

    @XmlElement(name = "semitemplatenumber")
    private String semiTemplateNumber;

    @ReadOnly
    @XmlElement(name = "correction_type")
    private String correctionType;

    @ReadOnly
    @XmlElement
    private Integer corrections;

    @XmlJavaTypeAdapter(CurrencyAdapter.class)
    @XmlElement
    private CurrencyUnit currency;

    @ReadOnly
    @XmlElement(name = "currency_exchange")
    private Double currencyExchange;

    @ReadOnly
    @XmlElement(name = "currency_label")
    private String currencyLabel;

    @ReadOnly
    @XmlElement(name = "currency_date")
    private Date currencyDate;

    @ReadOnly
    @XmlElement(name = "price_currency_exchange")
    private Double priceCurrencyExchange;

    @ReadOnly
    @XmlElement(name = "good_price_group_currency_exchange")
    private Double goodPriceGroupCurrencyExchange;

    @XmlElement
    private Integer template;

    @XmlJavaTypeAdapter(BooleanToIntegerAdapter.class)
    @XmlElement(name = "auto_send")
    private Boolean autoSend;

    @XmlElement
    private String description;

    @ReadOnly
    @XmlElement
    private String header;

    @ReadOnly
    @XmlElement
    private String footer;

    @ReadOnly
    @XmlElement(name = "user_name")
    private String userName;

    @XmlElement
    private InvoiceSchema schema;

    @XmlJavaTypeAdapter(BooleanToIntegerAdapter.class)
    @XmlElement(name = "schema_bill")
    private Boolean schemaBill;

    @XmlJavaTypeAdapter(BooleanToIntegerAdapter.class)
    @XmlElement(name = "schema_canceled")
    private Boolean schemaCanceled;

    @XmlElement(name = "register_description")
    private String registerDescription;

    @ReadOnly
    @XmlJavaTypeAdapter(MoneyAdapter.class)
    @XmlElement
    private Money netto22;

    @ReadOnly
    @XmlJavaTypeAdapter(MoneyAdapter.class)
    @XmlElement
    private Money netto7;

    @ReadOnly
    @XmlJavaTypeAdapter(MoneyAdapter.class)
    @XmlElement
    private Money netto3;

    @ReadOnly
    @XmlJavaTypeAdapter(MoneyAdapter.class)
    @XmlElement
    private Money netto0;

    @ReadOnly
    @XmlJavaTypeAdapter(MoneyAdapter.class)
    @XmlElement(name = "nettozw")
    private Money nettoZw;

    @ReadOnly
    @XmlJavaTypeAdapter(MoneyAdapter.class)
    @XmlElement(name = "nettowdt")
    private Money nettoWdt;

    @ReadOnly
    @XmlJavaTypeAdapter(MoneyAdapter.class)
    @XmlElement(name = "nettoexp")
    private Money nettoExp;

    @ReadOnly
    @XmlJavaTypeAdapter(MoneyAdapter.class)
    @XmlElement(name = "nettonp")
    private Money nettoNp;

    @ReadOnly
    @XmlJavaTypeAdapter(MoneyAdapter.class)
    @XmlElement(name = "nettonpue")
    private Money nettoNpUe;

    @ReadOnly
    @XmlJavaTypeAdapter(MoneyAdapter.class)
    @XmlElement(name = "nettovat_buyer")
    private Money nettoVatBuyer;

    @ReadOnly
    @XmlJavaTypeAdapter(MoneyAdapter.class)
    @XmlElement
    private Money netto23;

    @ReadOnly
    @XmlJavaTypeAdapter(MoneyAdapter.class)
    @XmlElement
    private Money netto8;

    @ReadOnly
    @XmlJavaTypeAdapter(MoneyAdapter.class)
    @XmlElement
    private Money netto5;

    @ReadOnly
    @XmlJavaTypeAdapter(MoneyAdapter.class)
    @XmlElement
    private Money netto;

    @ReadOnly
    @XmlJavaTypeAdapter(MoneyAdapter.class)
    @XmlElement
    private Money tax22;

    @ReadOnly
    @XmlJavaTypeAdapter(MoneyAdapter.class)
    @XmlElement
    private Money tax7;

    @ReadOnly
    @XmlJavaTypeAdapter(MoneyAdapter.class)
    @XmlElement
    private Money tax3;

    @ReadOnly
    @XmlJavaTypeAdapter(MoneyAdapter.class)
    @XmlElement
    private Money tax23;

    @ReadOnly
    @XmlJavaTypeAdapter(MoneyAdapter.class)
    @XmlElement
    private Money tax8;

    @ReadOnly
    @XmlJavaTypeAdapter(MoneyAdapter.class)
    @XmlElement
    private Money tax5;

    @ReadOnly
    @XmlJavaTypeAdapter(MoneyAdapter.class)
    @XmlElement
    private Money tax;

    @ReadOnly
    @XmlJavaTypeAdapter(BooleanToIntegerAdapter.class)
    @XmlElement
    private Boolean signed;

    @ReadOnly
    @XmlElement
    private String hash;

    @XmlElement
    private String idExternal;

    @ReadOnly
    @XmlElement(name = "warehouse_type")
    private WarehouseType warehouseType;

    @ReadOnly
    @XmlElement
    private Integer notes;

    @ReadOnly
    @XmlElement
    private Integer documents;

    @XmlElement
    @XmlJavaTypeAdapter(TagsAdapter.class)
    private Collection<String> tags;

    @ReadOnly
    @XmlElement
    @XmlJavaTypeAdapter(DateWithTimeAdapter.class)
    private Date created;

    @ReadOnly
    @XmlElement
    @XmlJavaTypeAdapter(DateWithTimeAdapter.class)
    private Date modified;

    @XmlElement(name = "price_type")
    private PriceType priceType;

    @XmlElement(name = "invoicecontents")
    private InvoiceContents invoiceContents;

    @ReadOnly
    @XmlElement
    private Reference series;

    @ReadOnly
    @XmlElement
    private Reference company;

    @ReadOnly
    @XmlElement
    private Reference contractor;

    @ReadOnly
    @XmlElement
    private Reference parent;

    @ReadOnly
    @XmlElement
    private Reference order;

    @ReadOnly
    @XmlElement
    private Reference cronemail;

    @ReadOnly
    @XmlElement
    private Reference cronemail2;

    @ReadOnly
    @XmlElement
    private Reference expenses;

    @ReadOnly
    @XmlElement(name = "company_accounts")
    private Reference companyAccounts;

    @ReadOnly
    @XmlElement(name = "payment_cashboxes")
    private Reference paymentCashboxes;

    @ReadOnly
    @XmlElement(name = "translation_languages")
    private Reference translationLanguages;

    @ReadOnly
    @XmlElement(name = "postivo_shipments")
    private Reference postivoShipments;

    @ReadOnly
    @XmlElement(name = "postivo_shipment_contents")
    private Reference postivoShipmentContents;

    /**
     * Constructor
     *
     * @param type type of invoice
     */
    public AbstractInvoice(TypeOfInvoice type) {
        this.type = type;
    }

    public Date getPaymentDate() {
        return copy(paymentDate);
    }

    public void setPaymentDate(Date paymentDate) {
        this.paymentDate = copy(paymentDate);
    }

    public Date getDisposalDate() {
        return copy(disposalDate);
    }

    public void setDisposalDate(Date disposalDate) {
        this.disposalDate = copy(disposalDate);
    }

    public Date getDate() {
        return copy(date);
    }

    public void setDate(Date date) {
        this.date = copy(date);
    }

    public Date getCurrencyDate() {
        return copy(currencyDate);
    }

    public void setCurrencyDate(Date currencyDate) {
        this.currencyDate = copy(currencyDate);
    }

    public Date getCreated() {
        return copy(created);
    }

    public void setCreated(Date created) {
        this.created = copy(created);
    }

    public Date getModified() {
        return copy(modified);
    }

    public void setModified(Date modified) {
        this.modified = copy(modified);
    }

    private static Date copy(Date date) {
        return Copier.from(date).copy();
    }

    /**
     * Metoda płatności
     */
    public enum PaymentMethod {

        cash, transfer, compensation, cod, payment_card
    }

    /**
     * Stan płatności
     */
    public enum PaymentState {

        paid, unpaid, udefined
    }

    /**
     * Format daty sprzedaży na wydruku faktury
     */
    public enum DisposalDateForm {

        month, day
    }

    /**
     * Type of invoice
     */
    public enum TypeOfInvoice {

        // Vat
        normal,
        proforma,
        receipt_normal,
        receipt_fiscal_normal,
        income_normal,
        // Non-Vat
        bill,
        proforma_bill,
        receipt_bill,
        receipt_fiscal_bill,
        income_bill
    }

    /**
     * Schemat księgowy. W przypadku faktur dotyczących sprzedaży po 1 stycznia 2014 należy stosować schematy
     */
    public enum InvoiceSchema {

        normal, vat_invoice_date, assessor
    }

    /**
     * Warehouse type
     */
    public enum WarehouseType {

        extended, simple
    }

    /**
     * Price type
     */
    public enum PriceType {

        netto, brutto
    }

}


text:
package jadx.core.utils.files;

import jadx.core.utils.AsmUtils;
import jadx.core.utils.exceptions.DecodeException;
import jadx.core.utils.exceptions.JadxException;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.android.dex.Dex;

public class InputFile {
	private static final Logger LOG = LoggerFactory.getLogger(InputFile.class);

	private final File file;
	private final Dex dexBuf;

	public InputFile(File file) throws IOException, DecodeException {
		if (!file.exists()) {
			throw new IOException("File not found: " + file.getAbsolutePath());
		}
		this.file = file;
		this.dexBuf = loadDexBuffer();
	}

	private Dex loadDexBuffer() throws IOException, DecodeException {
		String fileName = file.getName();
		if (fileName.endsWith(".dex")) {
			return new Dex(file);
		}
		if (fileName.endsWith(".class")) {
			return loadFromClassFile(file);
		}
		if (fileName.endsWith(".apk") || fileName.endsWith(".zip")) {
			Dex dex = loadFromZip(file);
			if (dex == null) {
				throw new IOException("File 'classes.dex' not found in file: " + file);
			}
			return dex;
		}
		if (fileName.endsWith(".jar")) {
			// check if jar contains 'classes.dex'
			Dex dex = loadFromZip(file);
			if (dex != null) {
				return dex;
			}
			return loadFromJar(file);
		}
		throw new DecodeException("Unsupported input file format: " + file);
	}

	private static Dex loadFromJar(File jarFile) throws DecodeException {
		try {
			LOG.info("converting to dex: {} ...", jarFile.getName());
			JavaToDex j2d = new JavaToDex();
			byte[] ba = j2d.convert(jarFile.getAbsolutePath());
			if (ba.length == 0) {
				throw new JadxException(j2d.isError() ? j2d.getDxErrors() : "Empty dx output");
			} else if (j2d.isError()) {
				LOG.warn("dx message: {}", j2d.getDxErrors());
			}
			return new Dex(ba);
		} catch (Throwable e) {
			throw new DecodeException("java class to dex conversion error:\n " + e.getMessage(), e);
		}
	}

	private static Dex loadFromZip(File file) throws IOException {
		ZipFile zf = new ZipFile(file);
		ZipEntry dex = zf.getEntry("classes.dex");
		if (dex == null) {
			zf.close();
			return null;
		}
		ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
		InputStream in = null;
		try {
			in = zf.getInputStream(dex);
			byte[] buffer = new byte[8192];
			int count;
			while ((count = in.read(buffer)) != -1) {
				bytesOut.write(buffer, 0, count);
			}
		} finally {
			if (in != null) {
				in.close();
			}
			zf.close();
		}
		return new Dex(bytesOut.toByteArray());
	}

	private static Dex loadFromClassFile(File file) throws IOException, DecodeException {
		File outFile = File.createTempFile("jadx-tmp-", System.nanoTime() + ".jar");
		outFile.deleteOnExit();
		FileOutputStream out = null;
		JarOutputStream jo = null;
		try {
			out = new FileOutputStream(outFile);
			jo = new JarOutputStream(out);
			String clsName = AsmUtils.getNameFromClassFile(file);
			if (clsName == null) {
				throw new IOException("Can't read class name from file: " + file);
			}
			FileUtils.addFileToJar(jo, file, clsName + ".class");
		} finally {
			if (jo != null) {
				jo.close();
			}
			if (out != null) {
				out.close();
			}
		}
		return loadFromJar(outFile);
	}

	public File getFile() {
		return file;
	}

	public Dex getDexBuffer() {
		return dexBuf;
	}

	@Override
	public String toString() {
		return file.toString();
	}
}


text:
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Link } from 'react-router-dom'
import FormGroup from 'react-bootstrap/lib/FormGroup'
import ControlLabel from 'react-bootstrap/lib/ControlLabel'
import FormControl from 'react-bootstrap/lib/FormControl'
import Table from 'react-bootstrap/lib/Table'
import Grid from 'react-bootstrap/lib/Grid'
import Row from 'react-bootstrap/lib/Row'
import Col from 'react-bootstrap/lib/Col'
import Button from 'react-bootstrap/lib/Button'
import Glyphicon from 'react-bootstrap/lib/Glyphicon'
import Form from 'react-bootstrap/lib/Form'
import orderBy from 'lodash.orderby'

import { SORTBY_MOST_VOTES, SORTBY_MOST_RECENT } from '../constants'
import * as actions from '../actions'
import PostListItem from './PostListItem'

const tableHeadings = [
  'Title',
  'Category',
  'Body',
  'Author',
  'Date',
  'Votes',
  'Actions',
]

class PostsList extends Component {
  handleChange = event => {
    this.props.setOrderByPosts(event.target.value)
  }

  render() {
    const { posts } = this.props

    return (

        <Grid>
          <Row className="show-grid">
            <Col xs={12} mdPush={8} md={4}>
              <Form inline>
                <FormGroup controlId="formControlsSelect">
                  <ControlLabel>Sort by</ControlLabel>
                  {'  '}
                  <FormControl
                    bsSize="sm"
                    componentClass="select"
                    placeholder="select"
                    onChange={this.handleChange}
                    value={this.props.orderBy}
                  >
                    <option value={SORTBY_MOST_VOTES}>Most votes</option>
                    <option value={SORTBY_MOST_RECENT}>Most recent</option>
                  </FormControl>
                </FormGroup>
                <Link to="/addpost">
                  <Button bsStyle="primary" className="add-post-button">
                    <Glyphicon glyph="plus" /> Add Post
                  </Button>
                </Link>
              </Form>
            </Col>
          </Row>
        </Grid>

{tableHeadings.map(th => {th}	)}

              {posts.map(post => <PostListItem key={post.id} post={post} />)}

    )
  }
}

const mapStateToProps = ({ posts }) => {
  let orderedPosts
  if (posts.orderBy === SORTBY_MOST_VOTES) {
    orderedPosts = orderBy(posts.data, [SORTBY_MOST_VOTES], ['desc'])
  } else {
    orderedPosts = orderBy(posts.data, [SORTBY_MOST_RECENT], ['desc'])
  }
  return {
    posts: orderedPosts,
    orderBy: posts.orderBy,
  }
}

export default connect(mapStateToProps, actions)(PostsList)


text:
import sys

if sys.version_info < (3, 7):
    from ._yref import YrefValidator
    from ._yanchor import YanchorValidator
    from ._y import YValidator
    from ._xref import XrefValidator
    from ._xanchor import XanchorValidator
    from ._x import XValidator
    from ._visible import VisibleValidator
    from ._templateitemname import TemplateitemnameValidator
    from ._source import SourceValidator
    from ._sizing import SizingValidator
    from ._sizey import SizeyValidator
    from ._sizex import SizexValidator
    from ._opacity import OpacityValidator
    from ._name import NameValidator
    from ._layer import LayerValidator
else:
    from _plotly_utils.importers import relative_import

    __all__, __getattr__, __dir__ = relative_import(
        __name__,
        [],
        [
            "._yref.YrefValidator",
            "._yanchor.YanchorValidator",
            "._y.YValidator",
            "._xref.XrefValidator",
            "._xanchor.XanchorValidator",
            "._x.XValidator",
            "._visible.VisibleValidator",
            "._templateitemname.TemplateitemnameValidator",
            "._source.SourceValidator",
            "._sizing.SizingValidator",
            "._sizey.SizeyValidator",
            "._sizex.SizexValidator",
            "._opacity.OpacityValidator",
            "._name.NameValidator",
            "._layer.LayerValidator",
        ],
    )