text:
<?php
/**
 * @package Model
 */
abstract class Kwf_Model_Abstract implements Kwf_Model_Interface
{
    protected $_rowClass = 'Kwf_Model_Row_Abstract';
    protected $_rowsetClass = 'Kwf_Model_Rowset_Abstract';
    protected $_default = array();
    protected $_siblingModels = array();
    protected $_dependentModels = array();
    protected $_referenceMap = array();
    protected $_toStringField;

    protected $_hasDeletedFlag = false;
    /**
     * Row-Filters für automatisch befüllte Spalten
     *
     * Anwendungsbeispiele:
     * _filters = 'filename' //verwendet autom. Kwf_Filter_Ascii
     * _filters = array('filename') //verwendet autom. Kwf_Filter_Ascii
     * _filters = array('pos')      //Kwf_Filter_Row_Numberize
     * _filters = array('pos' => 'MyFilter')
     * _filters = array('pos' => new MyFilter($settings))
     */
    protected $_filters = array();

    /**
     * Unterstützte Import / Export Formate
     *
     * Reihenfolge: Bevorzugtes Format muss als erstes stehen.
     */
    protected $_supportedImportExportFormats = array(self::FORMAT_ARRAY);

    protected $_exprs = array();

    protected $_rows = array();

    private static $_allInstances = array();
    private $_hasColumnsCache = array();
    private $_factoryConfig = null;

    protected $_proxyContainerModels = array();

    //public static $instanceCount = array();

    protected $_columnMappings = array();

    public function __construct(array $config = array())
    {
        if (isset($config['default'])) $this->_default = (array)$config['default'];
        if (isset($config['siblingModels'])) $this->_siblingModels = (array)$config['siblingModels'];
        if (isset($config['dependentModels'])) $this->_dependentModels = (array)$config['dependentModels'];
        if (isset($config['referenceMap'])) $this->_referenceMap = (array)$config['referenceMap'];
        if (isset($config['filters'])) $this->_filters = (array)$config['filters'];
        if (isset($config['toStringField'])) $this->_toStringField = (string)$config['toStringField'];
        if (isset($config['exprs'])) $this->_exprs = (array)$config['exprs'];
        if (isset($config['hasDeletedFlag'])) $this->_hasDeletedFlag = $config['hasDeletedFlag'];
        //self::$instanceCount[spl_object_hash($this)] = get_class($this);
        self::$_allInstances[] = $this;
        $this->_init();
    }

    public function __destruct()
    {
        //unset(self::$instanceCount[spl_object_hash($this)]);
    }

    /**
     * @param Kwf_Model_Abstract|string wenn string: entweder aus config (models.modelName)
     *                                               oder Klassenname von Model
     * @return Kwf_Model_Interface
     **/
    public static function getInstance($modelName)
    {
        if (is_object($modelName)) return $modelName;
        static $config;
        if (!isset($config)) $config = Kwf_Config::getValueArray('models');
        if (array_key_exists($modelName, $config)) {
            if (!$config[$modelName]) return null;
            $modelName = $config[$modelName];
        }
        return Kwf_Model_Factory_ClassName::getModelInstance($modelName);
    }

    //für unit-tests
    public static function clearInstances()
    {
        Kwf_Model_Factory_ClassName::clearInstances();
        self::$_allInstances = array();
    }

    protected function _init()
    {
        $this->_setupFilters();
    }

    //kann gesetzt werden von proxy
    public function addProxyContainerModel($m)
    {
        $this->_proxyContainerModels[] = $m;
    }

    protected function _setupFilters()
    {
    }

    public function getFilters()
    {
        if (is_string($this->_filters)) $this->_filters = array($this->_filters);
        foreach ($this->_filters as $k=>$f) {
            if (is_int($k)) {
                unset($this->_filters[$k]);
                $k = $f;
                if ($k == 'pos') {
                    $f = 'Kwf_Filter_Row_Numberize';
                } else {
                    $f = 'Kwf_Filter_Ascii';
                }
            }
            if (is_string($f)) {
                if (!class_exists($f)) {
                    if (class_exists('Kwf_Filter_Row_'.$f)) {
                        $f = 'Kwf_Filter_Row_'.$f;
                        $f = new $f();
                    } else if (class_exists('Kwf_Filter_'.$f)) {
                        $f = 'Kwf_Filter_'.$f;
                        $f = new $f();
                    } else {
                        throw new Kwf_Exception("Invalid filter class");
                    }
                }
                $f = new $f();
            }
            if ($f instanceof Kwf_Filter_Row_Abstract) {
                $f->setField($k);
            }
            $this->_filters[$k] = $f;
        }
        return $this->_filters;
    }

    public function setDefault(array $default)
    {
        $this->_default = $default;
        return $this;
    }

    public function createRow(array $data=array())
    {
        return $this->_createRow($data);
    }
    protected function _createRow(array $data=array(), array $rowConfig = array())
    {
        $rowConfig['model'] = $this;
        $rowConfig['data'] = $this->_default;
        $ret = new $this->_rowClass($rowConfig);

        $siblingRows = array();
        foreach ($this->getSiblingModels() as $m) {
            if ($m instanceof Kwf_Model_SubModel_Interface) {
                $siblingRows[] = $m->getRowBySiblingRow($ret);
            } else {
                $siblingRows[] = $m->createRow();
            }
        }
        $ret->setSiblingRows($siblingRows);
        foreach ($data as $k=>$i) {
            $ret->$k = $i;
        }
        $pk = $this->getPrimaryKey();
        if (isset($ret->$pk) && !$ret->$pk) {
            $ret->$pk = null;
        }
        return $ret;
    }

    public function getRow($select)
    {
        if (!$select) {
            throw new Kwf_Exception('getRow needs a parameter, null is not allowed.');
        }
        if (!is_object($select)) {
            $select = $this->select($select);
        } else {
            $select = clone $select;
        }
        $select->limit(1);
        $rows = $this->getRows($select);
        if ($rows->valid()) {
            return $rows->current();
        } else {
            return null;
        }
    }

    public function getIds($where=null, $order=null, $limit=null, $start=null)
    {
        $ret = array();
        foreach ($this->getRows($where, $order, $limit, $start) as $row) {
            $ret[] = $row->{$this->getPrimaryKey()};
        }
        return $ret;
    }

    public function countRows($select = array())
    {
        return count($this->getRows($select));
    }

    public function getDefault()
    {
        return $this->_default;
    }

    public function isEqual(Kwf_Model_Interface $other)
    {
        throw new Kwf_Exception("Method 'isEqual' is not yet implemented in '".get_class($this)."'");
    }

    public function select($where = array(), $order = null, $limit = null, $start = null)
    {
        if (is_array($where)) {
            $ret = new Kwf_Model_Select($where);
        } else if (!($where instanceof Kwf_Model_Select)) {
            $ret = new Kwf_Model_Select();
            if ($where) {
                $ret->whereEquals($this->getPrimaryKey(), $where);
            }
        } else {
            $ret = $where;
        }
        if ($order) $ret->order($order);
        if ($limit || $start) $ret->limit($limit, $start);
        return $ret;
    }

    public function getColumnType($col)
    {
        if (in_array($col, $this->getExprColumns())) {
            return $this->_exprs[$col]->getResultType();
        }
        foreach ($this->getSiblingModels() as $m) {
            return $m->getColumnType($col);
        }
        return null;
    }

    private function _hasColumn($col)
    {
        if (!$this->getOwnColumns()) return true;
        if (in_array($col, $this->getOwnColumns())) return true;
        if (in_array($col, $this->getExprColumns())) return true;
        foreach ($this->getSiblingModels() as $m) {
            if ($m->hasColumn($col)) return true;
        }
        return false;
    }

    public function hasColumn($col)
    {
        if (!isset($this->_hasColumnsCache[$col])) {
            $this->_hasColumnsCache[$col] = $this->_hasColumn($col);
        }
        return $this->_hasColumnsCache[$col];
    }

    public function getExprColumns()
    {
        return array_keys($this->_exprs);
    }

    public final function getOwnColumns()
    {
        $ret = $this->_getOwnColumns();
        return $ret;
    }

    abstract protected function _getOwnColumns();

    public function getColumns()
    {
        $ret = $this->getOwnColumns();
        $ret = array_merge($ret, $this->getExprColumns());
        foreach ($this->getSiblingModels() as $m) {
            $ret = array_merge($ret, $m->getColumns());
        }
        return $ret;
    }

    public function getSiblingModels()
    {
        foreach ($this->_siblingModels as $k=>$i) {
            if (is_string($i)) $this->_siblingModels[$k] = Kwf_Model_Abstract::getInstance($i);
        }
        return $this->_siblingModels;
    }

    public function getReferenceRuleByModelClass($modelClassName)
    {
        $rules = $this->getReferenceRulesByModelClass($modelClassName);
        if (count($rules) > 1) {
            throw new Kwf_Exception("there exist more than one rule with modelclass '$modelClassName'. "
                ."Try getReferenceRulesByModelClass(\$modelClassName) to get all matching rules.");
        } else if (count($rules) == 0) {
            throw new Kwf_Exception("there is no rule with modelclass '$modelClassName'.");
        } else {
            return $rules[0];
        }
    }

    public function getReferenceRulesByModelClass($modelClassName)
    {
        $ret = array();
        foreach ($this->getReferences() as $rule) {
            $ref = $this->getReference($rule);
            if ($ref === Kwf_Model_RowsSubModel_Interface::SUBMODEL_PARENT) {
                $c = $this->getParentModel();
            } else if (isset($ref['refModelClass'])) {
                $c = $ref['refModelClass'];
            } else if (isset($ref['refModel'])) {
                $c = $ref['refModel'];
            } else {
                throw new Kwf_Exception("refModelClass and refModel not set");
            }
            if (is_instance_of($modelClassName, $c)) {
                $ret[$rule] = $ref;
            }
        }
        if (count($ret) >= 1) {
            return array_keys($ret);
        } else {
            throw new Kwf_Exception("No reference from '".get_class($this)."' to '$modelClassName'");
        }
    }

    public function getReferenceByModelClass($modelClassName, $rule)
    {
        $models = array($this);
        $models = array_merge($models, $this->_proxyContainerModels);
        $m = $this;
        while ($m instanceof Kwf_Model_Proxy) {
            $m = $m->getProxyModel();
            $models[] = $m;
        }
        foreach ($models as $m) {
            $matchingRules = $m->getReferenceRulesByModelClass($modelClassName);

            if (count($matchingRules) > 1) {
                if ($rule && in_array($rule, $matchingRules)) {
                    return $m->getReference($rule);
                } else {
                    throw new Kwf_Exception("Multiple references from '".get_class($this)."' to '$modelClassName' found, but none with rule-name '$rule'");
                }
            } else if (count($matchingRules) == 1) {
                return $m->getReference($matchingRules[0]);
            }
        }
        throw new Kwf_Exception("No reference from '".get_class($this)."' to '$modelClassName'");
    }

    /**
     * Namen der verfügbaren References
     *
     * Details zu einer Reference über getReferencedModel() bzw. getReference() holen
     */
    public function getReferences()
    {
        return array_keys($this->_referenceMap);
    }

    public function getReference($rule)
    {
        $models = array($this);
        $models = array_merge($models, $this->_proxyContainerModels);
        $m = $this;
        while ($m instanceof Kwf_Model_Proxy) {
            $m = $m->getProxyModel();
            $models[] = $m;
        }
        foreach ($models as $m) {
            if (isset($m->_referenceMap[$rule])) {
                $ret = $m->_referenceMap[$rule];
                if (is_string($ret)) {
                    if ($ret === Kwf_Model_RowsSubModel_Interface::SUBMODEL_PARENT) {
                    } else {
                        if (strpos($ret, '->') === false) {
                            throw new Kwf_Exception("Reference '$rule' for model '".get_class($m)."' is a string but doesn't contain ->");
                        }
                        $ret = array(
                            'refModelClass' => substr($ret, strpos($ret, '->')+2),
                            'column' => substr($ret, 0, strpos($ret, '->')),
                        );
                    }
                }
                return $ret;
            }
        }

        $keys = array();
        foreach ($models as $m) {
            $keys = array_merge($keys, array_keys($m->_referenceMap));
        }
        throw new Kwf_Exception("Reference '$rule' for model '".get_class($this)."' not set, set are '".implode(', ', $keys)."'");
    }

    public function getReferencedModel($rule)
    {
        $ref = $this->getReference($rule);
        if ($ref === Kwf_Model_RowsSubModel_Interface::SUBMODEL_PARENT) {
            return $this->getParentModel();
        }
        if (isset($ref['refModelClass'])) {
            return self::getInstance($ref['refModelClass']);
        }
        if (isset($ref['refModel'])) {
            return $ref['refModel'];
        }
        throw new Kwf_Exception("refModelClass not set for reference '$rule'");
    }

    public function getDependentRuleByModelClass($modelClassName)
    {
        $rules = $this->getDependentRulesByModelClass($modelClassName);
        if (count($rules) > 1) {
            throw new Kwf_Exception("there exist more than one rule with modelclass '$modelClassName'. "
                ."Try getDependentRulesByModelClass(\$modelClassName) to get all matching rules.");
        } else if (count($rules) == 0) {
            throw new Kwf_Exception("there is no rule with modelclass '$modelClassName'.");
        } else {
            return $rules[0];
        }
    }

    public function getDependentRulesByModelClass($modelClassName)
    {
        $ret = array();
        foreach ($this->_dependentModels as $k => $m) {
            if (is_instance_of($modelClassName, $m)) {
                $ret[] = $k;
            }
        }
        return $ret;
    }

    protected function _createDependentModel($rule)
    {
        $ret = $this->_dependentModels[$rule];
        if (is_array($ret)) {
            if (!isset($ret['model'])) {
                throw new Kwf_Exception("model not set for dependentModel");
            }
            $ret = $ret['model'];
        }
        if (is_string($ret)) {
            if (strpos($ret, '->') !== false) {
                $m = Kwf_Model_Abstract::getInstance(substr($ret, 0, strpos($ret, '->')));
                $ret = $m->_createDependentModel(substr($ret, strpos($ret, '->')+2));
            } else {
                $ret = Kwf_Model_Abstract::getInstance($ret);
            }
        }
        return $ret;
    }

    public function getDependentModelWithDependentOf($rule)
    {
        if (!$rule) {
            throw new Kwf_Exception("rule parameter is required");
        }
        if (!is_string($rule)) {
            throw new Kwf_Exception("rule parameter as string is required, ".gettype($rule)." given");
        }
        $models = $this->_proxyContainerModels;
        $models[] = $this;
        $m = $this;
        while ($m instanceof Kwf_Model_Proxy) {
            $m = $m->getProxyModel();
            $models[] = $m;
        }
        foreach ($models as $m) {
            if (isset($m->_dependentModels[$rule])) {
                $ret = $m->_dependentModels[$rule];
                if (!is_array($ret)) $ret = array();
                $ret['model'] = $m->_createDependentModel($rule);
                $ret['dependentOf'] = $m;
                return $ret;
            }
        }

        $existingRules = array();
        foreach ($models as $m) {
            $existingRules = array_merge($existingRules, array_keys($m->_dependentModels));
        }
        throw new Kwf_Exception("dependent Model with rule '$rule' does not exist for '".get_class($this)."', possible are '".implode("', '", $existingRules)."'");
    }

    public function getDependentModel($rule)
    {
        $ret = $this->getDependentModelWithDependentOf($rule);
        return $ret['model'];
    }

    /**
     * @internal return value will change, don't use it
     */
    public function getDependentModels()
    {
        $ret = array();
        //TODO _proxyContainerModels berücksichtigen
        foreach (array_keys($this->_dependentModels) as $rule) {
            $ret[$rule] = $this->_createDependentModel($rule);
        }
        return $ret;
    }

    public function getRowsetClass()
    {
        return $this->_rowsetClass;
    }

    public function find($id)
    {
        $s = $this->select();
        $s->whereEquals($this->getPrimaryKey(), $id);
        return $this->getRows($s);
    }

    public function fetchAll($where=null, $order=null, $limit=null, $start=null)
    {
        return $this->getRows($where, $order, $limit, $start);
    }

    public function fetchCount($where = array())
    {
        return $this->countRows($where);
    }

    public function getToStringField()
    {
        return $this->_toStringField;
    }

    public function getSupportedImportExportFormats()
    {
        if (!$this->_supportedImportExportFormats) return null;
        return $this->_supportedImportExportFormats;
    }

    protected static final function _optimalImportExportFormat(Kwf_Model_Interface $model1, Kwf_Model_Interface $model2)
    {
        $formats = array_values(array_intersect(
            $model1->getSupportedImportExportFormats(),
            $model2->getSupportedImportExportFormats()
        ));
        if (!$formats || !$formats[0]) {
            throw new Kwf_Exception("Model '".get_class($model1)."' cannot copy data "
                ."from model '".get_class($model2)."'. Import / Export Formats are not compatible.");
        }
        return $formats[0];
    }

    public function copyDataFromModel(Kwf_Model_Interface $sourceModel, Kwf_Model_Select $select = null, array $importOptions = array())
    {
        $format = self::_optimalImportExportFormat($this, $sourceModel);
        $this->import($format, $sourceModel->export($format, $select), $importOptions);
    }

    public function export($format, $select = array(), $options = array())
    {
        if ($format == self::FORMAT_ARRAY) {
            return $this->getRows($select)->toArray();
        } else {
            throw new Kwf_Exception_NotYetImplemented();
        }
    }

    public function import($format, $data, $options = array())
    {
        if ($format == self::FORMAT_ARRAY) {
            if (isset($options['replace']) && $options['replace']) {
                throw new Kwf_Exception_NotYetImplemented();
            }
            Kwf_Events_ModelObserver::getInstance()->disable();
            foreach ($data as $k => $v) {
                $this->createRow($v)->save();
            }
            Kwf_Events_ModelObserver::getInstance()->enable();
            $this->_afterImport($format, $data, $options);
        } else {
            throw new Kwf_Exception_NotYetImplemented();
        }
    }

    protected function _afterImport($format, $data, $options)
    {
        foreach ($this->_proxyContainerModels as $m) {
            $m->_afterImport($format, $data, $options);
        }
    }

    public function writeBuffer()
    {
    }

    public function deleteRows($where)
    {
        throw new Kwf_Exception('not implemented yet.');
    }

    protected function _afterDeleteRows($where)
    {
    }

    public function updateRows($data, $where)
    {
        throw new Kwf_Exception('not implemented yet.');
    }

    public function transformColumnName($c)
    {
        return $c;
    }

    public function getUniqueIdentifier()
    {
        throw new Kwf_Exception_NotYetImplemented();
    }

    public function getExprValue($row, $name)
    {
        if ($name instanceof Kwf_Model_Select_Expr_Interface) {
            $expr = $name;
        } else {
            $expr = $this->_exprs[$name];
        }

        if ($expr instanceof Kwf_Model_Select_Expr_Child_Contains) {
            if (!$row instanceof Kwf_Model_Row_Interface) {
                $row = $this->getRow($row[$this->getPrimaryKey()]);
            }
            $ret = (bool)$row->countChildRows($expr->getChild(), $expr->getSelect());
            return $ret;
        } else if ($expr instanceof Kwf_Model_Select_Expr_Child_First) {
            if (!$row instanceof Kwf_Model_Row_Interface) {
                $row = $this->getRow($row[$this->getPrimaryKey()]);
            }
            $s = clone $expr->getSelect();
            $s->limit(1);
            $childRows = $row->getChildRows($expr->getChild(), $s);
            if (count($childRows)) {
                return $childRows[0]->{$expr->getField()};
            } else {
                return null;
            }
        } else if ($expr instanceof Kwf_Model_Select_Expr_Child) {
            if (!$row instanceof Kwf_Model_Row_Interface) {
                $row = $this->getRow($row[$this->getPrimaryKey()]);
            }
            $childs = $row->getChildRows($expr->getChild(), $expr->getSelect());
            return self::_evaluateExprForRowset($childs, $expr->getExpr());
        } else if ($expr instanceof Kwf_Model_Select_Expr_Parent) {
            if (!$row instanceof Kwf_Model_Row_Interface) {
                $row = $this->getRow($row[$this->getPrimaryKey()]);
            }
            $reference = $row->getModel()->getReference($expr->getParent());
            $parentModel = $row->getModel()->getReferencedModel($expr->getParent());
            $select = new Kwf_Model_Select();
            $select->whereId($row->{$reference['column']});
            $select->ignoreDeleted(true);
            $parent = $parentModel->getRow($select);
            if (!$parent) return null;
            $field = $expr->getField();
            if (is_string($field)) {
                return $parent->$field;
            } else {
                return $this->getExprValue($parent, $field);
            }
        } else if ($expr instanceof Kwf_Model_Select_Expr_Concat) {
            $ret = '';
            foreach ($expr->getExpressions() as $e) {
                if ($e instanceof Kwf_Model_Select_Expr_Interface) {
                    $ret .= $this->getExprValue($row, $e);
                } else {
                    if (is_array($row)) {
                        $ret .= $row[$e];
                    } else {
                        $ret .= $row->$e;
                    }
                }
            }
            return $ret;
        } else if ($expr instanceof Kwf_Model_Select_Expr_String) {
            return $expr->getString();
        } else if ($expr instanceof Kwf_Model_Select_Expr_Boolean) {
            return $expr->getValue();
        } else if ($expr instanceof Kwf_Model_Select_Expr_Integer) {
            return $expr->getValue();
        } else if ($expr instanceof Kwf_Model_Select_Expr_StrPad) {
            $f = $expr->getField();
            if (is_array($row)) {
                $v = $row[$f];
            } else {
                $v = $row->$f;
            }
            // faking mysql's implementation of LPAD / RPAD
            // mysql cuts always right when the string is too long, it does not
            // depend on the pad-type
            if ($expr->getPadLength() < mb_strlen($v)) {
                return substr($v, 0, $expr->getPadLength());
            }
            $padType = STR_PAD_RIGHT;
            if ($expr->getPadType() == Kwf_Model_Select_Expr_StrPad::LEFT) {
                $padType = STR_PAD_LEFT;
            } else if ($expr->getPadType() == Kwf_Model_Select_Expr_StrPad::RIGHT) {
                $padType = STR_PAD_RIGHT;
            }
            return str_pad($v, $expr->getPadLength(), $expr->getPadStr(), $padType);
        } else if ($expr instanceof Kwf_Model_Select_Expr_Date_Year) {
            $field = $expr->getField();
            $format = $expr->getFormat();
            if (is_array($row)) {
                $v = $row[$field];
            } else {
                $v = $row->$field;
            }
            return date($format, strtotime($v));
        } else if ($expr instanceof Kwf_Model_Select_Expr_Date_Format) {
            $field = $expr->getField();
            $format = $expr->getFormat();
            if (is_array($row)) {
                $v = $row[$field];
            } else {
                $v = $row->$field;
            }
            return date($format, strtotime($v));
        } else if ($expr instanceof Kwf_Model_Select_Expr_Field) {
            $f = $expr->getField();
            if (is_array($row)) {
                return $row[$f];
            } else {
                return $row->$f;
            }
        } else if ($expr instanceof Kwf_Model_Select_Expr_PrimaryKey) {
            $f = $this->getPrimaryKey();
            if (is_array($row)) {
                return $row[$f];
            } else {
                return $row->$f;
            }
        } else if ($expr instanceof Kwf_Model_Select_Expr_SumFields) {
            $ret = 0;
            foreach ($expr->getFields() as $f) {
                if (is_int($f)) {
                    $ret += $f;
                } else if (is_string($f)) {
                    if (is_array($row)) {
                        $ret += $row[$f];
                    } else {
                        $ret += $row->$f;
                    }
                } else if ($f instanceof Kwf_Model_Select_Expr_Interface) {
                    $ret += $this->getExprValue($row, $f);
                } else {
                    throw new Kwf_Exception_NotYetImplemented();
                }
            }
            return $ret;
        } else if ($expr instanceof Kwf_Model_Select_Expr_If) {
            if ($this->getExprValue($row, $expr->getIf())) {
                return $this->getExprValue($row, $expr->getThen());
            } else {
                return $this->getExprValue($row, $expr->getElse());
            }
        } else if ($expr instanceof Kwf_Model_Select_Expr_IsNull) {
            if ($expr->getField() instanceof Kwf_Model_Select_Expr_Interface) {
                $rowValue = $this->getExprValue($row, $expr->getField());
            } else {
                $rowValue = $row->{$expr->getField()};
            }
            return is_null($rowValue);
        } else if ($expr instanceof Kwf_Model_Select_Expr_Not) {
            return !$this->getExprValue($row, $expr->getExpression());
        } else if ($expr instanceof Kwf_Model_Select_Expr_Position) {
            $f = $expr->getField();
            $s = $this->select();
            foreach ($expr->getGroupBy() as $i) {
                $s->whereEquals($i, $row->$i);
            }
            if ($expr->getDirection() == Kwf_Model_Select_Expr_Position::DIRECTION_ASC) {
                $s->where(new Kwf_Model_Select_Expr_Lower($f, $row->$f));
            } else {
                $s->where(new Kwf_Model_Select_Expr_Higher($f, $row->$f));
            }
            return $this->countRows($s)+1;
        } elseif ($expr instanceof Kwf_Model_Select_Expr_Date_Age) {
            $f = $expr->getField();
            if (!$row->$f) return null;
            $timeFrom = strtotime($row->$f);
            $timeTo = $expr->getDate()->getTimestamp();
            $ret = (date('Y', $timeTo) - date('Y', $timeFrom))
                - intval((date('md', $timeTo) < date('md', $timeFrom)));
            return $ret;
        } else if ($expr instanceof Kwf_Model_Select_Expr_Divide) {
            $ret = null;
            foreach ($expr->getExpressions() as $e) {
                $value = $this->getExprValue($row, $e);
                if ($ret === null) {
                    $ret = $value;
                } else {
                    if ($value == 0) {
                        //throw new Kwf_Exception('division by 0 not possible, check you expressions');
                    } else {
                        $ret = $ret / $value;
                    }
                }
            }
            if (!$ret) $ret = 0;
            return $ret;
        } else if ($expr instanceof Kwf_Model_Select_Expr_Multiply) {
            $ret = null;
            foreach ($expr->getExpressions() as $e) {
                $value = $this->getExprValue($row, $e);
                if ($ret === null) {
                    $ret = $value;
                } else {
                    $ret *= $value;
                }
            }
            if (!$ret) $ret = 0;
            return $ret;
        } else if ($expr instanceof Kwf_Model_Select_Expr_Subtract) {
            $ret = null;
            foreach ($expr->getExpressions() as $e) {
                $value = $this->getExprValue($row, $e);
                if ($ret === null) {
                    $ret = $value;
                } else {
                    $ret -= $value;
                }
            }
            if (!$ret) $ret = 0;
            return $ret;
        } else if ($expr instanceof Kwf_Model_Select_Expr_Add) {
            $ret = 0;
            foreach ($expr->getExpressions() as $e) {
                $ret += $this->getExprValue($row, $e);
            }
            return $ret;
        } else if ($expr instanceof Kwf_Model_Select_Expr_And) {
            foreach ($expr->getExpressions() as $e) {
                if (!$this->getExprValue($row, $e)) { return false; }
            }
            return true;
        } else if ($expr instanceof Kwf_Model_Select_Expr_Or) {
            foreach ($expr->getExpressions() as $e) {
                $value = $this->getExprValue($row, $e);
                if ($this->getExprValue($row, $e)) { return true; }
            }
            return false;
        } else if ($expr instanceof Kwf_Model_Select_Expr_CompareField_Abstract) {
            $value = $expr->getFormattedValue();
            if ($value instanceof Kwf_Model_Select_Expr_Interface) {
                $value = $this->getExprValue($row, $value);
            }
            if ($expr->getField() instanceof Kwf_Model_Select_Expr_Interface) {
                $rowValue = $this->getExprValue($row, $expr->getField());
            } else {
                $rowValue = $row->{$expr->getField()};
            }

            if ($expr instanceof Kwf_Model_Select_Expr_Higher) {
                return $rowValue > $value;
            } else if ($expr instanceof Kwf_Model_Select_Expr_Lower) {
                return $rowValue < $value;
            } else if ($expr instanceof Kwf_Model_Select_Expr_HigherEqual) {
                return $rowValue >= $value;
            } else if ($expr instanceof Kwf_Model_Select_Expr_Equal) {
                return ($rowValue == $value);
            } else if ($expr instanceof Kwf_Model_Select_Expr_NotEquals) {
                return ($rowValue != $value);
            } else if ($expr instanceof Kwf_Model_Select_Expr_LowerEqual) {
                return $rowValue <= $value;
            } else {
                throw new Kwf_Exception_NotYetImplemented(
                    "CompareField-Expression '".(is_string($expr) ? $expr : get_class($expr))."' is not yet implemented"
                );
            }
        } else if ($expr instanceof Kwf_Model_Select_Expr_Parent_Contains) {
            if (!$row instanceof Kwf_Model_Row_Interface) {
                $row = $this->getRow($row[$this->getPrimaryKey()]);
            }
            $refModel = $this->getReferencedModel($expr->getParent());
            $ref = $this->getReference($expr->getParent());
            return in_array($row->{$ref['column']}, $refModel->getIds($expr->getSelect()));
        } else {
            throw new Kwf_Exception_NotYetImplemented(
                "Expression '".(is_string($expr) ? $expr : get_class($expr))."' is not yet implemented"
            );
        }
    }

    public function evaluateExpr(Kwf_Model_Select_Expr_Interface $expr, Kwf_Model_Select $select = null)
    {
        $rows = $this->getRows($select);
        return self::_evaluateExprForRowset($rows, $expr);
    }

    private static function _evaluateExprForRowset($rowset, Kwf_Model_Select_Expr_Interface $expr)
    {
        if ($expr instanceof Kwf_Model_Select_Expr_Count) {
            if ($expr->getField() != '*') {
                $f = $expr->getField();
                $values = array();
                foreach ($rowset as $r) {
                    if (!is_null($r->$f)) $values[] = $r->$f;
                }
                if ($expr->getDistinct()) {
                    $values = array_unique($values);
                }
                return count($values);
            } else {
                return $rowset->count();
            }
        } else if ($expr instanceof Kwf_Model_Select_Expr_Sum) {
            $f = $expr->getField();
            $ret = 0;
            foreach ($rowset as $r) {
                $ret += $r->$f;
            }
            return $ret;
        } else if ($expr instanceof Kwf_Model_Select_Expr_Max) {
            $f = $expr->getField();
            if (!count($rowset)) return null;
            $ret = $rowset->current()->$f;
            foreach ($rowset as $r) {
                $ret = max($ret, $r->$f);
            }
            return $ret;
        } else if ($expr instanceof Kwf_Model_Select_Expr_Min) {
            $f = $expr->getField();
            if (!count($rowset)) return null;
            $ret = $rowset->current()->$f;
            foreach ($rowset as $r) {
                $ret = min($ret, $r->$f);
            }
            return $ret;
        } else if ($expr instanceof Kwf_Model_Select_Expr_GroupConcat) {
            $f = $expr->getField();
            $orderField = $expr->getOrderField();
            $ret = array();

            if ($orderField) {
                $orderFieldValue = $orderField['field'];
                $orderFieldDirection = ($orderField['direction'] == 'DESC') ? SORT_DESC : SORT_ASC;

                $rowData = array();
                foreach ($rowset as $r) {
                    $rowData[] = array(
                        $f => $r->$f,
                        $orderFieldValue => $r->$orderFieldValue
                    );
                }

                $orderFieldValues = array();

                foreach ($rowData as $key => $data) {
                    $orderFieldValues[$key] = $data[$orderFieldValue];
                }
                array_multisort($orderFieldValues, $orderFieldDirection, $rowData);
                foreach ($rowData as $r) {
                    $ret[] = $r[$f];
                }
            } else {
                foreach ($rowset as $r) {
                    $ret[] = $r->$f;
                }
            }

            return implode($expr->getSeparator(), $ret);
        } else if ($expr instanceof Kwf_Model_Select_Expr_Field) {
            if (!count($rowset)) {
                return null;
            }
            $f = $expr->getField();
            return $rowset->current()->$f;
        } else {
            throw new Kwf_Exception_NotYetImplemented("support for ".get_class($expr)." is not yet implemented");
        }
    }

    public function updateRow(array $data)
    {
        $row = $this->getRow($data[$this->getPrimaryKey()]);
        if (!$row) {
            throw new Kwf_Exception("Can't update row, row not found");
        }
        foreach ($data as $k => $v) {
            $row->$k = $v;
        }
        $row->save();
        return $row->toArray();
    }

    public function insertRow(array $data)
    {
        $row = $this->createRow();
        foreach ($data as $k => $v) {
            if ($this->getPrimaryKey() != $k) {
                $row->$k = $v;
            }
        }
        $row->save();
        return $row->toArray();
    }

    public function callMultiple(array $call)
    {
        $ret = array();
        foreach ($call as $method=>$arguments) {
            $ret[$method] = call_user_func_array(array($this, $method), $arguments);
        }
        return $ret;
    }

    public function toDebug()
    {
        $ret = '<pre> Model '.get_class($this).'</pre>';
        return $ret;
    }

    /**
     * @internal
     */
    public function dependentModelRowUpdated(Kwf_Model_Row_Abstract $row, $action)
    {
    }

    /**
     * @internal
     */
    public function childModelRowUpdated(Kwf_Model_Row_Abstract $row, $action)
    {
    }

    /**
     * Kann zum Speicher-Sparen aufgerufen werden
     * @internal
     * @deprecated
     */
    public function clearRows()
    {
    }

    /**
     * @internal
     */
    public function getProxyContainerModels()
    {
        return $this->_proxyContainerModels;
    }

    /**
     * @internal
     */
    public function getExpr($name)
    {
        return $this->_exprs[$name];
    }

    public function freeMemory()
    {
        foreach ($this->_rows as $row) {
            if (is_object($row)) $row->freeMemory();
        }
        $this->_rows = array();
    }

    public static function clearAllRows()
    {
        foreach (self::$_allInstances as $i) {
            $i->freeMemory();
        }
    }

    public function fetchColumnByPrimaryId($column, $id)
    {
        $row = $this->getRow($id);
        if (!$row) return null;
        return $row->$column;
    }

    public function fetchColumnsByPrimaryId(array $columns, $id)
    {
        $row = $this->getRow($id);
        if (!$row) return array();
        $ret = array();
        foreach ($columns as $c) {
            $ret[$c] = $row->$c;
        }
        return $ret;
    }

    public function getColumnMapping($mapping, $column)
    {
        $models = array($this);
        $models = array_merge($models, $this->_proxyContainerModels);
        foreach ($models as $model) {
            foreach ($model->_columnMappings as $map=>$columns) {
                do {
                    if (isset($model->_columnMappings[$map]) &&
                        array_key_exists($column, $model->_columnMappings[$map])
                    ) {
                        return $model->_columnMappings[$map][$column];
                    }
                } while ($map = get_parent_class($map));
            }
        }
        throw new Kwf_Exception("unknown mapping column: '$column' for mapping '$mapping' in model '".get_class($model)."'");
    }

    public function getColumnMappings($mapping)
    {
        $models = array($this);
        $models = array_merge($models, $this->_proxyContainerModels);

        foreach ($models as $model) {

            foreach ($model->_columnMappings as $map=>$columns) {
                $curMap = $map;
                do {
                    if ($curMap == $mapping) {
                        return $model->_columnMappings[$map];
                    }
                } while ($curMap = get_parent_class($curMap));
            }

        }

        throw new Kwf_Exception("unknown mapping '$mapping' for '".get_class($this)."'");
    }

    public function hasColumnMappings($mapping)
    {
        $models = array($this);
        $models = array_merge($models, $this->_proxyContainerModels);

        foreach ($models as $model) {

            foreach ($model->_columnMappings as $map=>$columns) {
                do {
                    if ($map == $mapping) {
                        return true;
                    }
                } while ($map = get_parent_class($map));
            }
        }
        return false;
    }

    public function hasDeletedFlag()
    {
        return $this->_hasDeletedFlag;
    }

    public static function convertValueToType($value, $type)
    {
        if (is_null($value)) return $value;

        if ($type == Kwf_Model_Abstract::TYPE_STRING) {
            $value = (string)$value;
        } else if ($type == Kwf_Model_Abstract::TYPE_BOOLEAN) {
            $value = (bool)$value;
        } else if ($type == Kwf_Model_Abstract::TYPE_INTEGER) {
            $value = (int)$value;
        } else if ($type == Kwf_Model_Abstract::TYPE_DATE) {
            $value = (string)$value;
        } else if ($type == Kwf_Model_Abstract::TYPE_DATETIME) {
            $value = (string)$value;
        } else if ($type == Kwf_Model_Abstract::TYPE_FLOAT) {
            $value = (float)$value;
        }
        return $value;
    }

    public function getEventSubscribers()
    {
        return array();
    }

    public function setFactoryConfig(array $factoryConfig)
    {
        $this->_factoryConfig = $factoryConfig;
    }

    public function getFactoryId()
    {
        $c = $this->getFactoryConfig();
        if (!$c) return null;
        return $c['id'];
    }

    public function getFactoryConfig()
    {
        if ($this->_factoryConfig && !isset($this->_factoryConfig['id'])) {
            $this->_factoryConfig = call_user_func(array('Kwf_Model_Factory_'.$this->_factoryConfig['type'], 'processConfig'), $this->_factoryConfig);
        }
        return $this->_factoryConfig;
    }

    private static function _findAllInstancesProcessModel(&$ret, $model)
    {
        $model = self::getInstance($model);
        if (isset($ret[$model->getFactoryId()])) {
            return;
        }
        $ret[$model->getFactoryId()] = $model;

        if ($model instanceof Kwf_Model_Proxy) {
            self::_findAllInstancesProcessModel($ret, $model->getProxyModel());
        } else if ($model instanceof Kwf_Model_Union) {
            foreach ($model->getUnionModels() as $subModel) {
                self::_findAllInstancesProcessModel($ret, $subModel);
            }
        }

        foreach ($model->getDependentModels() as $m) {
            self::_findAllInstancesProcessModel($ret, $m);
        }
        foreach ($model->getSiblingModels() as $m) {
            self::_findAllInstancesProcessModel($ret, $m);
        }
        foreach ($model->getReferences() as $rule) {
            $m = $model->getReferencedModel($rule);
            self::_findAllInstancesProcessModel($ret, $m);
        }
    }

    /**
     * Try to find all used models in the current app
     */
    public static function findAllInstances()
    {
        $ret = array();
        foreach (glob('models/*.php') as $m) {
            $m = str_replace('/', '_', substr($m, 7, -4));
            $reflectionClass = new ReflectionClass($m);
            if (!$reflectionClass->isAbstract() && is_instance_of($m, 'Kwf_Model_Interface')) {
                self::_findAllInstancesProcessModel($ret, $m);
            }
        }

        if (Kwf_Config::getValue('user.model')) {
            self::_findAllInstancesProcessModel($ret, Kwf_Config::getValue('user.model'));
        }

        foreach (Kwc_Abstract::getComponentClasses() as $componentClass) {
            $cls = strpos($componentClass, '.') ? substr($componentClass, 0, strpos($componentClass, '.')) : $componentClass;
            $m = call_user_func(array($cls, 'createOwnModel'), $componentClass);
            if ($m) self::_findAllInstancesProcessModel($ret, $m);

            $m = call_user_func(array($cls, 'createChildModel'), $componentClass);
            if ($m) self::_findAllInstancesProcessModel($ret, $m);

            foreach (Kwc_Abstract::getSetting($componentClass, 'generators') as $g) {
                if (isset($g['model'])) {
                    self::_findAllInstancesProcessModel($ret, $g['model']);
                }
            }
        }

        foreach (Kwf_Component_Data_Root::getInstance()->getPlugins('Kwf_Component_PluginRoot_Interface_Models') as $plugin) {
            foreach ($plugin->getModels() as $model) {
                self::_findAllInstancesProcessModel($ret, $model);
            }
        }

        //hardcoded models that always exist
        self::_findAllInstancesProcessModel($ret, 'Kwf_Util_Model_Welcome');
        self::_findAllInstancesProcessModel($ret, 'Kwf_Util_Model_Redirects');
        return $ret;
    }

    public function getUpdates()
    {
        if ($this->_factoryConfig['type'] == 'ClassName') {
            $id = $this->_factoryConfig['id'];
            if (strpos($id, '_') === false) {
                $classPrefix = 'Update_'.$id;
            } else {
                $classPrefix = substr($id, 0, strrpos($id, '_')).'_Update_'.substr($id, strrpos($id, '_')+1);
            }
            return Kwf_Util_Update_Helper::getUpdatesForDir($classPrefix);
        } else {
            return array();
        }
    }
}


text:
@protocol DemoInputViewDelegate;

@interface DemoInputView : UIView
@property (nonatomic, weak) id<DemoInputViewDelegate> delegate;
@end

@protocol DemoInputViewDelegate <NSObject>
@optional
- (void)demoInputViewDidInputText:(DemoInputView *)inputView text:(NSString *)text;
@end

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Linq;
using System.Threading.Tasks;

namespace FacetedWorlds.MyCon.Model
{
    public partial class Individual
    {
        public async Task<Schedule> AddScheduleAsync(SessionPlace sessionPlace)
        {
            Attendee attendee = (await Attendees.EnsureAsync()).FirstOrDefault();
            if (attendee == null)
                attendee = await Community.AddFactAsync(new Attendee(
                    sessionPlace.Session.Conference,
                    Guid.NewGuid().ToString()));
            await Community.AddFactAsync(new IndividualAttendee(this, attendee));
            var slot = await Community.AddFactAsync(new Slot(
                attendee,
                sessionPlace.Place.PlaceTime));
            return await Community.AddFactAsync(new Schedule(slot, sessionPlace));
        }

        public async Task RemoveScheduleAsync(SessionPlace sessionPlace)
        {
            foreach (var attendee in await Attendees.EnsureAsync())
            {
                foreach (var schedule in await attendee.CurrentSchedules.EnsureAsync())
                {
                    if (schedule.SessionPlace == sessionPlace)
                        await Community.AddFactAsync(new ScheduleRemove(schedule));
                }
            }
        }

        public bool IsScheduled(SessionPlace sessionPlace)
        {
            var sessions =
                from attendee in Attendees
                from sp in attendee.ScheduledSessionPlaces
                select sp;
            return sessions.Contains(sessionPlace);
        }
    }
}


text:
package org.apache.spark.status.api.v1

import javax.ws.rs.{GET, PathParam, Produces}
import javax.ws.rs.core.MediaType

@Produces(Array(MediaType.APPLICATION_JSON))
private[v1] class OneApplicationResource(uiRoot: UIRoot) {

  @GET
  def getApp(@PathParam("appId") appId: String): ApplicationInfo = {
    val apps = uiRoot.getApplicationInfo(appId)
    apps.getOrElse(throw new NotFoundException("unknown app: " + appId))
  }

}


text:
package com.keygenteam.mamiferosenpeligro;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;

public class Splash extends FragmentActivity{
	/*creamos la vista de pagina*/
	ViewPager vp_splash;
	/*creamos el adaptador*/
	private vpAdapter miAdaptador;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);

		vp_splash = (ViewPager) findViewById(R.id.viewpagerSplash);
		miAdaptador = new vpAdapter();
		vp_splash.setAdapter(miAdaptador);
	}

	private class vpAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			return 3;
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == ((RelativeLayout) object);
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			((ViewPager) container).removeView((RelativeLayout) object);
		}
		@Override
		public void finishUpdate(ViewGroup container) {
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			LayoutInflater inflater = (LayoutInflater) container.getContext()
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View s = null;
			switch (position) {

			case 0:
				s = inflater.inflate(R.layout.demo1, null);
				break;
			case 1:
				s = inflater.inflate(R.layout.demo2, null);
				break;
			case 2:
				s = inflater.inflate(R.layout.demo3, null);

				Button btn1 = (Button) s.findViewById(R.id.btn_demo_start);
				btn1.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						Intent aHome = new Intent(Splash.this, Main.class);
						Splash.this.startActivity(aHome);
						Splash.this.finish();

					}
				});
				break;
			}
			((ViewPager) container).addView(s, 0);
			return s;
		}
		@Override
		public Parcelable saveState() {
			return null;
		}
		@Override
		public void startUpdate(ViewGroup container) {
			super.startUpdate(container);
		}

	}

	@Override
	public void onBackPressed() {
		System.exit(0);
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<SAXEvents>
  <startDocument/>
  <startPrefixMapping>
    <prefix/>
    <data>http://example.org/rosé</data>
  </startPrefixMapping>
  <startElement>
    <namespaceURI>http://example.org/rosé</namespaceURI>
    <localName>foo</localName>
    <qualifiedName>foo</qualifiedName>
    <attributes/>
  </startElement>
  <endElement>
    <namespaceURI>http://example.org/rosé</namespaceURI>
    <localName>foo</localName>
    <qualifiedName>foo</qualifiedName>
  </endElement>
  <endPrefixMapping>
    <prefix/>
  </endPrefixMapping>
  <endDocument/>
</SAXEvents>


text:
/**
 * Select the entire state
 */

const globalSelector = () => (state) => state.get('global');

export default globalSelector;


text:
create table bookmarks (
	id smallint unsigned primary key auto_increment,
	sort tinyint unsigned not null,
	page varchar(16) not null,
	spec varchar(128) not null,
	unique(page, spec),
	name varchar(64) not null
);


text:
add_definitions(-DBUILDING_JSCONLY__)

set(PROJECT_VERSION_MAJOR 1)
set(PROJECT_VERSION_MINOR 0)
set(PROJECT_VERSION_MICRO 0)
set(PROJECT_VERSION ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_MICRO})

WEBKIT_OPTION_BEGIN()
WEBKIT_OPTION_DEFINE(ENABLE_STATIC_JSC "Whether to build JavaScriptCore as a static library." PUBLIC OFF)
WEBKIT_OPTION_END()

set(ALL_EVENT_LOOP_TYPES
    GLib
    Generic
)

set(DEFAULT_EVENT_LOOP_TYPE "Generic")

set(EVENT_LOOP_TYPE ${DEFAULT_EVENT_LOOP_TYPE} CACHE STRING "Implementation of event loop to be used in JavaScriptCore (one of ${ALL_EVENT_LOOP_TYPES})")

set(ENABLE_WEBCORE OFF)
set(ENABLE_WEBKIT OFF)
set(ENABLE_WEBKIT2 OFF)
set(ENABLE_API_TESTS ON)

if (WTF_CPU_X86 OR WTF_CPU_X86_64)
    SET_AND_EXPOSE_TO_BUILD(USE_UDIS86 1)
endif ()

if (ENABLE_STATIC_JSC)
    set(JavaScriptCore_LIBRARY_TYPE STATIC)
endif ()

string(TOLOWER ${EVENT_LOOP_TYPE} LOWERCASE_EVENT_LOOP_TYPE)
if (LOWERCASE_EVENT_LOOP_TYPE STREQUAL "glib")
    find_package(GLIB 2.36 REQUIRED COMPONENTS gio gobject)
    SET_AND_EXPOSE_TO_BUILD(USE_GLIB 1)
    SET_AND_EXPOSE_TO_BUILD(USE_GLIB_EVENT_LOOP 1)
    SET_AND_EXPOSE_TO_BUILD(WTF_DEFAULT_EVENT_LOOP 0)
else ()
    SET_AND_EXPOSE_TO_BUILD(USE_GENERIC_EVENT_LOOP 1)
    SET_AND_EXPOSE_TO_BUILD(WTF_DEFAULT_EVENT_LOOP 0)
endif ()

#if (NOT APPLE)
#    # find_package(ICU REQUIRED)
#else ()
#    set(ICU_INCLUDE_DIRS
#        "${WEBCORE_DIR}/icu"
#        "${JAVASCRIPTCORE_DIR}/icu"
#        "${WTF_DIR}/icu"
#    )
#    set(ICU_LIBRARIES libicucore.dylib)
#endif ()

set(ICU_INCLUDE_DIRS
    "${WEBCORE_DIR}/icu"
    "${JAVASCRIPTCORE_DIR}/icu"
    "${WTF_DIR}/icu"
)

# From OptionsGTK.cmake
if (CMAKE_MAJOR_VERSION LESS 3)
    # Before CMake 3 it was necessary to use a build script instead of using cmake --build directly
    # to preserve colors and pretty-printing.

    build_command(COMMAND_LINE_TO_BUILD)
    # build_command unconditionally adds -i (ignore errors) for make, and there's
    # no reasonable way to turn that off, so we just replace it with -k, which has
    # the same effect, except that the return code will indicate that an error occurred.
    # See: http://www.cmake.org/cmake/help/v3.0/command/build_command.html
    string(REPLACE " -i" " -k" COMMAND_LINE_TO_BUILD ${COMMAND_LINE_TO_BUILD})
    file(WRITE
        ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/build.sh
        "#!/bin/sh\n"
        "${COMMAND_LINE_TO_BUILD} $@"
    )
    file(COPY ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/build.sh
        DESTINATION ${CMAKE_BINARY_DIR}
        FILE_PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE
    )
endif ()


text:
DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )

# Prepare
echo "$DOCKER_PASS" | docker login -u "$DOCKER_USER" --password-stdin
export REPO=mikeallanson/gatsby-graphql
export TAG=latest

# Build
# Build the Dockerfile located at ../, using ../ as the context directory
docker build -t "$REPO":"$TRAVIS_COMMIT" -f "$DIR"/../Dockerfile "$DIR"/../

docker tag "$REPO":"$TRAVIS_COMMIT" "$REPO":"$TAG"
docker tag "$REPO":"$TRAVIS_COMMIT" "$REPO":travis-"$TRAVIS_BUILD_NUMBER"

# Push
docker push "$REPO"


text:
GitHubHomeWorkExercise

This will create a conflict

Edit from web Browser


text:
package apple.uikit;

import apple.NSObject;
import apple.foundation.NSArray;
import apple.foundation.NSCoder;
import apple.foundation.NSMethodSignature;
import apple.foundation.NSPredicate;
import apple.foundation.NSSet;
import apple.foundation.protocol.NSSecureCoding;
import org.moe.natj.c.ann.FunctionPtr;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Library;
import org.moe.natj.general.ann.Mapped;
import org.moe.natj.general.ann.NInt;
import org.moe.natj.general.ann.NUInt;
import org.moe.natj.general.ann.Owned;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.general.ptr.VoidPtr;
import org.moe.natj.objc.Class;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.SEL;
import org.moe.natj.objc.ann.ObjCClassBinding;
import org.moe.natj.objc.ann.ProtocolClassMethod;
import org.moe.natj.objc.ann.Selector;
import org.moe.natj.objc.map.ObjCObjectMapper;

@Generated
@Library("UIKit")
@Runtime(ObjCRuntime.class)
@ObjCClassBinding
public class UISceneActivationConditions extends NSObject implements NSSecureCoding {
    static {
        NatJ.register();
    }

    @Generated
    protected UISceneActivationConditions(Pointer peer) {
        super(peer);
    }

    @Generated
    @Selector("accessInstanceVariablesDirectly")
    public static native boolean accessInstanceVariablesDirectly();

    @Generated
    @Owned
    @Selector("alloc")
    public static native UISceneActivationConditions alloc();

    @Owned
    @Generated
    @Selector("allocWithZone:")
    public static native UISceneActivationConditions allocWithZone(VoidPtr zone);

    @Generated
    @Selector("automaticallyNotifiesObserversForKey:")
    public static native boolean automaticallyNotifiesObserversForKey(String key);

    /**
     * default is [NSPredicate predicateWithValue:YES]
     */
    @Generated
    @Selector("canActivateForTargetContentIdentifierPredicate")
    public native NSPredicate canActivateForTargetContentIdentifierPredicate();

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:")
    public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:selector:object:")
    public static native void cancelPreviousPerformRequestsWithTargetSelectorObject(
            @Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector,
            @Mapped(ObjCObjectMapper.class) Object anArgument);

    @Generated
    @Selector("classFallbacksForKeyedArchiver")
    public static native NSArray<String> classFallbacksForKeyedArchiver();

    @Generated
    @Selector("classForKeyedUnarchiver")
    public static native Class classForKeyedUnarchiver();

    @Generated
    @Selector("debugDescription")
    public static native String debugDescription_static();

    @Generated
    @Selector("description")
    public static native String description_static();

    @Generated
    @Selector("encodeWithCoder:")
    public native void encodeWithCoder(NSCoder coder);

    @Generated
    @Selector("hash")
    @NUInt
    public static native long hash_static();

    @Generated
    @Selector("init")
    public native UISceneActivationConditions init();

    @Generated
    @Selector("initWithCoder:")
    public native UISceneActivationConditions initWithCoder(NSCoder aDecoder);

    @Generated
    @Selector("instanceMethodForSelector:")
    @FunctionPtr(name = "call_instanceMethodForSelector_ret")
    public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector);

    @Generated
    @Selector("instanceMethodSignatureForSelector:")
    public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector);

    @Generated
    @Selector("instancesRespondToSelector:")
    public static native boolean instancesRespondToSelector(SEL aSelector);

    @Generated
    @Selector("isSubclassOfClass:")
    public static native boolean isSubclassOfClass(Class aClass);

    @Generated
    @Selector("keyPathsForValuesAffectingValueForKey:")
    public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key);

    @Generated
    @Owned
    @Selector("new")
    public static native UISceneActivationConditions new_objc();

    /**
     * default is [NSPredicate predicateWithValue:NO];
     */
    @Generated
    @Selector("prefersToActivateForTargetContentIdentifierPredicate")
    public native NSPredicate prefersToActivateForTargetContentIdentifierPredicate();

    @Generated
    @Selector("resolveClassMethod:")
    public static native boolean resolveClassMethod(SEL sel);

    @Generated
    @Selector("resolveInstanceMethod:")
    public static native boolean resolveInstanceMethod(SEL sel);

    /**
     * default is [NSPredicate predicateWithValue:YES]
     */
    @Generated
    @Selector("setCanActivateForTargetContentIdentifierPredicate:")
    public native void setCanActivateForTargetContentIdentifierPredicate(NSPredicate value);

    /**
     * default is [NSPredicate predicateWithValue:NO];
     */
    @Generated
    @Selector("setPrefersToActivateForTargetContentIdentifierPredicate:")
    public native void setPrefersToActivateForTargetContentIdentifierPredicate(NSPredicate value);

    @Generated
    @Selector("setVersion:")
    public static native void setVersion_static(@NInt long aVersion);

    @Generated
    @Selector("superclass")
    public static native Class superclass_static();

    @Generated
    @Selector("supportsSecureCoding")
    public static native boolean supportsSecureCoding();

    @Generated
    @ProtocolClassMethod("supportsSecureCoding")
    public boolean _supportsSecureCoding() {
        return supportsSecureCoding();
    }

    @Generated
    @Selector("version")
    @NInt
    public static native long version_static();
}


text:
using System;
using System.Security.Principal;

namespace Sautom.Server.Security
{
    class Principal : IPrincipal
    {
	    public Principal(string userName)
        {
            Identity = new Identity(userName);
        }

	    public static Principal PrincipalInstance { get; set; }

	    #region Implementation of IPrincipal

	    public bool IsInRole(string role)
        {
            throw new NotImplementedException();
        }

	    public IIdentity Identity { get; }

	    #endregion
    }

    class Identity : IIdentity
    {
	    public Identity(string name)
        {
            Name = name;
        }

	    #region Implementation of IIdentity

	    public string Name { get; }

	    public string AuthenticationType
        {
            get { throw new NotImplementedException(); }
        }

	    public bool IsAuthenticated
        {
            get { throw new NotImplementedException(); }
        }

	    #endregion
    }
}


text:
using System;
using System.Runtime.InteropServices;

namespace System.Windows.Forms
{
    public class MyListView : ListView
    {
        [DllImport("uxtheme.dll", CharSet = CharSet.Unicode)]
        private extern static int SetWindowTheme(IntPtr hWnd, string pszSubAppName, string pszSubIdList);
        [DllImport("user32.dll")]
        private static extern int SendMessage(IntPtr hWnd, int wMsg, int wParam, int lParam);

        public MyListView()
        {
            SendMessage(Handle, 0x127, 0x10001, 0);

            SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
            SetStyle(ControlStyles.EnableNotifyMessage, true);
        }

        protected override void OnEnter(EventArgs e)
        {
            base.OnEnter(e);
            SendMessage(Handle, 0x127, 0x10001, 0);
        }
        protected override void OnHandleCreated(EventArgs e)
        {
            base.OnHandleCreated(e);
            if (!DesignMode && Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion.Version.Major >= 6)
                SetWindowTheme(Handle, "explorer", null);
        }
        protected override void OnSelectedIndexChanged(EventArgs e)
        {
            base.OnSelectedIndexChanged(e);
            SendMessage(Handle, 0x127, 0x10001, 0);
        }
        protected override void OnNotifyMessage(Message m)
        {
            if (m.Msg != 0x14)
                base.OnNotifyMessage(m);
        }
    }
}


text:
'use strict';

module.exports = function delay(runtime) {
//  var proc = fbp.getCurrentProc();
  var inport = this.openInputPort('IN');
  var intvlport = this.openInputPort('INTVL');
  var outport = this.openOutputPort('OUT');
  var intvl_ip = intvlport.receive();
  var intvl = intvl_ip.contents;
  this.dropIP(intvl_ip);

  while (true) {
    var ip = inport.receive();
    if (ip === null) {
      break;
    }
    //fbp.setCallbackPending(true);
    //console.log('start wait for ' + Math.round(intvl * 100) / 100 + ' msecs: ' + ip.contents);
    runtime.runAsyncCallback(genSleepFun(this, intvl));
    var name = outport.name.substring(0, outport.name.indexOf("."));
    console.log(name + ' end sleep ' );
    //fbp.setCallbackPending(false);
    outport.send(ip);
  }
}

function genSleepFun(proc, ms) {
  return function (done) {
    console.log(proc.name + ' start sleep: ' + Math.round(ms * 100) / 100 + ' msecs');

    setTimeout(function() {
      done();
    }, ms);
  };
}


text:
layout:     post
title:      "Leetcode Test Notes(1-20)"
subtitle:   " \"Hello World, Hello Blog\""
date:       2018-9-9 14:00
author:     "Leonard Yuan"
header-img: "img/home-bg-art.jpg"
catalog: true
tags:
    - Leetcode
    - Internship
    - Interview
---

>pre
>
>This week, I start learn and solve questions in leetcode, my goal is that I will solve 150 questions until October. Meanwhile, I will use my blog to document the solutions and thinkings about these question. So, let's start it.

	Notice: we use python3 as coding language to deal with these problems.

## 5. Longest Palindromic Substring

this is a classic algorithm question, there are some solutions about this questions.

- Brute Force

This is the easiest solution, but cannot pass from leetcode because of running so much time, but I will give my codes as follows:

	# brute force
	class Solution:
	    def longestPalindrome(self, s):
	        if len(s) == 0:
	            return s
	        elif len(s) == 1:
	            return s
	        else:
	            substring = ''
	            for m in range(len(s)):
	                for n in range(m+1,len(s)+1):
	                    flag = self.whetherpa(s[m:n])
	                    if flag == 1 and len(s[m:n]) > len(substring):
	                        substring = s[m:n]

	            return substring

	    def whetherpa(self, m):
	        l = m[::-1]
	        if l == m:
	            return 1
	        else:
	            return 0

- Expand from a center

This is a effective solution, we can test a string from a center, if we find that the former word and the later one are same, we can define that this string are also a palindromic substring, thus, we can find the longest palindromic substring easily according to this principle. There is another issue we should care about, that is what kind of center we should choose. After observation, we can find there are two kinds of different centers, one is like 'a', 'b', and so on, another is a substring having two same words, like 'aa', 'ee', and so on. Here is the code:

	# center way
	class Solution:
	    def longestPalindrome(self, s):
	        substring = ''
	        for m in range(len(s)):
	            returnstring = self.findstring(s,m,m)

	            if len(returnstring) > len(substring):
	                substring = returnstring

	            returnstring = self.findstring(s,m,m+1)
	            if len(returnstring) > len(substring):
	                substring = returnstring

	        return substring

	    def findstring(self, s, p, q):
	        while p > -1 and q <len(s) and s[p] == s[q]:
	            p -= 1
	            q += 1

	        return s[p+1:q]

- Dynamic Programming

......

- Manacher's Algorithm

......

## 6. ZigZag Conversion

- Just iterate the array

ZigZag conversion problem is likely that we arrange the existed array into new python lists, then we can join the elements in this list, and we will get the final array in the end. In my code, I use a variable to tag the direction of storing elements of the array into new list. I will give my code as follows:

	class Solution:
	    def convert(self, s, numRows):
	        if numRows == 1:
	            print(s)
	        nlist = [""]*numRows
	        flag = 0
	        dire = 0
	        for m in range(len(s)):
	            nlist[flag] = nlist[flag] + s[m]
	            if dire == 0:
	                if flag == numRows-1:
	                    dire = 1
	                    flag -= 1
	                else:
	                    flag += 1
	            else:
	                if flag == 0:
	                    dire = 0
	                    flag += 1
	                else:
	                    flag -= 1

	        return ''.join(nlist)

- Finding the characters

Another way to solve this problem is to find the characters of new array, so we can define certain equations to arrange the elements of given array into certain rows. We can find the equations in the solution page of this question in leetcode. Here is the link:

[the equation of this question](https://leetcode.com/problems/zigzag-conversion/solution/)

But my code has low effeciency, it is about 33.85%. Thus, I will take some further progress. I will give my code as follows:

	class Solution:
	    def convert(self, s, numRows):
	        if numRows == 1:
	            return s
	        nlist = ['']*numRows
	        for m in range(numRows):
	            if m == 0:
	                flag = 0
	                while flag*(2*numRows - 2) < len(s):
	                    nlist[m] = nlist[m] + s[flag*(2*numRows - 2)]
	                    flag += 1

	            elif m == numRows -1:
	                flag = 0
	                while (flag*(2*numRows - 2) + numRows - 1) < len(s):
	                    nlist[m] = nlist[m] + s[flag*(2*numRows - 2) + numRows - 1]
	                    flag += 1

	            else:
	                flag = 0
	                while (flag*(2*numRows-2) + m) < len(s) or ((flag + 1)*(2*numRows - 2) - m) < len(s):
	                    if (flag*(2*numRows-2) + m) < len(s):
	                        nlist[m] = nlist[m] + s[flag*(2*numRows-2) + m]
	                    if ((flag + 1)*(2*numRows - 2) - m) < len(s):
	                        nlist[m] = nlist[m] + s[(flag + 1)*(2*numRows - 2) - m]

	                    flag += 1

	        return ''.join(nlist)

## 9. Palindrome Number

This is an easy question, the best solution is that, we can choose elements from head and end, then we can compare them. If they are same, go on, or, return False. In the end, when head flag and end flag meet on certain position, we can define that this is a palindrome number, then return True. Here is the code:

	class Solution:
	    def isPalindrome(self, x):
	        x = str(x)
	        head = 0
	        end = len(x) -1
	        while end - head > 0:
	            if x[head] == x[end]:
	                head += 1
	                end -= 1
	            else:
	                return False

	        return True

## 10. Regular Expression Matching

......

## 11. Container With Most Water

- Brute Force

This is the easiest way, you should calculate the volume between two lines, then you can get the maximum volume. Omit the code.

- Two Pointer Approach

As we all know, if we want to find a container, which has the maximum volume, we must choose the longest lines to  make sure that we can get the container, having maximum volume. The video about this question on leetcode is pretty good, here is the link.

[vedio of 11th question](https://leetcode.com/problems/container-with-most-water/description/)

Here is the final code:

	class Solution:
	    def maxArea(self, height):
	        maxn = 0
	        head = 0
	        end = len(height) - 1
	        while end - head> 0:
	            print('%d : %d'% (head,end))
	            if (end - head) * min(height[head], height[end]) > maxn:
	                maxn = (end - head) * min(height[head], height[end])
	            if height[head] < height[end]:
	                head += 1
	            else:
	                end -= 1
	        return maxn

## 12. Integer to Roman

This is a pretty easy question, we can three lists to solve this question, every list contains the conversion of integers, the only thing we should do is to take the remainers to gain roman words, then we can join them into the final roman numbers. Here is the code:

	class Solution:
	    def intToRoman(self, num):
	        M = ['','M','MM','MMM']
	        C = ['','C','CC','CCC','CD','D','DC','DCC','DCCC','CM']
	        X = ['','X','XX','XXX','XL','L','LX','LXX','LXXX','XC']
	        I = ['','I','II','III','IV','V','VI','VII','VIII','IX']
	        return M[int(num/1000)] + C[int((num%1000)/100)] + X[int((num%100)/10)] + I[num%10]

## 13. Roman to Integer

First, I use the easiest way to fulfill this function, that is I build a dict to store as many as substring, when we achieve the comversion of Roman, the only thing we should do, is to match keys of the dict, then I can find the right number, and add it into sum variable. But it is of low effeicency, I just beats 5.18% by using this way. So I should make progress on my solution. Here is the code, which has the low effeciency.

	class Solution:
	    def romanToInt(self, s):
	        d = {'I':1, 'IV':4, 'V':5, 'IX':9, 'X':10, 'XL':40, 'L':50, 'XC':90, 'C':100, 'CD':400, 'D':500, 'CM':900, 'M':1000}
	        sum = 0
	        m = 0
	        while m < len(s) - 1:
	            if d.get(s[m] + s[m+1]):
	                sum = sum + d[s[m] + s[m+1]]
	                # print('2: '+ s[m] + s[m+1])
	                m += 2
	            else:
	                sum = sum + d[s[m]]
	                # print('1: '+ s[m])
	                m += 1
	        if m == len(s) - 1:
	            sum = sum + d[s[m]]
	        return sum

There is other way to improve the effeciency of my algorithm, that is we can reverse the array, then we can compare the late one with former one, if the former one is better, sum substracts the late one. If not, add it. Here is the code:

	class Solution:
	    def romanToInt(self, s):
	        d = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500,'M':1000}
	        sum = 0
	        s = s[::-1]
	        sum = d[s[0]]
	        for m in range(1,len(s)):
	            if d[s[m]] <d[s[m-1]]:
	                sum -= d[s[m]]
	            else:
	                sum += d[s[m]]
	        return sum

## 14. Longest Common Prefix

This is a pretty easy case, and the most important thing is that you should care about every possible situation, such as [], [""] and so on. We can use strs[0] as a standard array to match other arrays in strs, if they are not same, return, else, keep going. Here is the code as follows:

	class Solution:
	    def longestCommonPrefix(self, strs):
	        if len(strs) == 1:
	            return strs[0]
	        elif len(strs) == 0:
	            return ''
	        else:
	            rstr = ''
	            for m in range(len(strs[0])):
	                for l in strs[1:]:
	                    if strs[0][0:m+1] == l[0: m + 1]:
	                        pass
	                    else:
	                        return rstr
	                rstr = rstr + strs[0][m]

	            return rstr

## 15. 3Sum

This is an pretty interesting question, I first use two pointers, one from head, another from end, to start sort, but I found that there is an omition, thus I used Brute Force algorithm to solve this question. Although we can get final result, if we cannot pass from leetcode website because of the `Time Limit Exceeded`. Here is the code of brute force algorithm.

	class Solution:
	    def threeSum(self, nums):
	        if len(nums) == 0:
	            return []
	        else:
	            retset = []
	            nums = sorted(nums)
	            for m in range(0, len(nums) - 2):
	                for n in range( m + 1, len(nums) - 1):
	                    if 0 - (nums[m] + nums[n]) in nums[n+1 : len(nums)]:
	                        temp = sorted([nums[m], nums[n], 0 - nums[m] - nums[n]])
	                        if temp  not in retset:
	                            retset.append(temp)
	            return retset

We must make progress on my algorithm.

Here is the progress of this question, we use two pointers to fulfill my algorithm, and there are two loops, thus the complexity of my algorithm is O(n^2), but my solution still cannot pass the leetcode test system. So, keep going. Here is the code as following:

	class Solution:
	    def threeSum(self, nums):
	        if len(nums) == 0:
	            return []
	        else:
	            retset = []
	            nums = sorted(nums)
	            head = 0

	            while head < len(nums) - 2:
	                end = len(nums) - 1
	                while end > head + 1:
	                    if 0 - (nums[end] + nums[head])in nums[head + 1: end]:
	                        if [nums[head] ,0 - (nums[end] + nums[head]) , nums[end]] not in retset:
	                            print('1 %d : %d'%(nums[head], nums[end]))
	                            retset.append([nums[head] ,0 - (nums[end] + nums[head]) , nums[end]])
	                        end -= 1
	                    elif nums[end] - nums[head] > 0:
	                        print('1 %d : %d'%(nums[head], nums[end]))
	                        end -= 1
	                    else:
	                        break
	                head += 1
	            return retset

## 16. 3Sum Closest

The solution of this question is similar to question15, so I just give the code:

	class Solution:
	    def threeSumClosest(self, numbers, target):
	        numbers = sorted(numbers)
	        retans = None
	        for m in range(len(numbers)):
	            left = m + 1
	            right = len(numbers) - 1
	            while left < right:
	                sum = numbers[left] + numbers[right] + numbers[m]
	                if retans is None or abs(retans - target) >abs(sum - target):
	                    retans = sum
	                if sum <target:
	                    left += 1
	                else:
	                    right -= 1
	        return retans

## 17. Letter Combinations of a Phone Number

This is also an easy question, we can use three loops to solve this question. Here is the code:

	class Solution:
	    def letterCombinations(self, digits):
	        intger_char = {
	        '0':[],
	        '1':[],
	        '2':['a','b','c'],
	        '3': ['d', 'e', 'f'],
	        '4': ['g', 'h', 'i'],
	        '5': ['j', 'k', 'l'],
	        '6': ['m', 'n', 'o'],
	        '7': ['p', 'q', 'r', 's'],
	        '8': ['t', 'u', 'v'],
	        '9': ['w', 'x', 'y', 'z']
	        }

	        if len(digits) == 0:
	            return []
	        else:
	            rlist = intger_char[digits[0]]
	            for num in digits[1:]:
	                temp = []
	                for m in intger_char[num]:
	                    for item in rlist:
	                        temp.append(item + m)
	                rlist = temp
	        return rlist

I once found a pretty good solution, which uses recursion. I copy that code as following:

	class Solution:
	    def letterCombinations(self, digits):
	        """
	        :type digits: str
	        :rtype: List[str]
	        """
	        result = []
	        if len(digits) == 0:
	            return result

	        int_to_char = {'2': ['a', 'b', 'c'],
	                       '3': ['d', 'e', 'f'],
	                       '4': ['g', 'h', 'i'],
	                       '5': ['j', 'k', 'l'],
	                       '6': ['m', 'n', 'o'],
	                       '7': ['p', 'q', 'r', 's'],
	                       '8': ['t', 'u', 'v'],
	                       '9': ['w', 'x', 'y', 'z']}

	        # backtracking function
	        def f(s, idx):
	            if idx == len(digits):
	                result.append(s)
	            else:
	                for char in int_to_char[digits[idx]]:
	                    f(s+char, idx+1)
	        f('', 0)
	        return result

## 18.

.....

## 19. Remove Nth Node From End of List

This question requires knowledge about linked list, because in Python language, we can use list to substitute linked list, thus, we can store numbers into the a list first, then we can delete number in certain postion. In the end, we can get the final linked list:

	class Solution:
	    def removeNthFromEnd(self, head, n):
	        temp = head
	        mlist = []
	        while temp != None:
	            mlist.append(temp.val)
	            temp = temp.next
	        del mlist[len(mlist) - n]
	        return mlist

`note: We can make progress on my algorithm question.`

## 20. Valid Parentheses

This is an easy question, the only data structure we should use is stack. We can first append left parenthesises into stack, then we can pop the elements from the stack, if they are compatible, go on, else, return False. Here is the code as following:

	class Solution:
	    def isValid(self, s):
	        mystack = []
	        sdict = {")":"(","]":"[","}":"{"}
	        for item in s:
	            if item in sdict.values():
	                mystack.append(item)
	            elif len(mystack) > 0 and sdict[item] == mystack.pop():
	                continue
	            else:
	                return False
	        return not mystack


text:
package org.eclipse.emf.cdo.server.db.mapping;

import org.eclipse.emf.cdo.common.id.CDOID;
import org.eclipse.emf.cdo.common.revision.delta.CDOListFeatureDelta;
import org.eclipse.emf.cdo.server.db.IDBStoreAccessor;

/**
 * Interface to complement {@link IListMapping} in order to provide list delta processing support.
 *
 * @author Eike Stepper
 * @author Stefan Winkler
 * @since 2.0
 */
public interface IListMappingDeltaSupport
{
  /**
   * Process a set of CDOFeatureDeltas for a many-valued feature.
   *
   * @param accessor
   *          the accessor to use
   * @param id
   *          the ID of the revision affected
   * @param oldVersion
   *          the original version of the revision
   * @param newVersion
   *          the new revision of the revision (after the change)
   * @param created
   *          the creation date for the new revision
   * @param delta
   *          the {@link CDOListFeatureDelta} which contains the list deltas.
   * @since 4.0
   */
  public void processDelta(IDBStoreAccessor accessor, CDOID id, int branchId, int oldVersion, int newVersion,
      long created, CDOListFeatureDelta delta);
}


text:
*Please note that parts of this package are still unimplemented.*

## Introduction

This package provides support for reflection which may be tailored to cover
certain reflective features and omit others, thus reducing the resource
requirements at runtime.

The core idea is that the desired level of support for reflection is specified
explicitly and statically, and any usage of reflection at runtime must stay
within the boundaries thus specified; otherwise a `NoSuchCapabilityError` is
thrown. In return for statically confining the required reflection support,
programs can be smaller. Other than that, using this package and using
`dart:mirrors` is very similar.

The core concept in the reflection support specification is that of a
reflectable **capability**. For a more detailed discussion about capabilities,
please consult the [reflectable capability design document][1]. On this page we
just use a couple of simple special cases.

[1]: doc/TheDesignofReflectableCapabilities.pdf

The resource benefits obtained by using this package are established by
transformation. That is, this package includes a [`pub` transformer][2]. The
transformer receives a specification of which programs to transform (see the
description of `entry_points:` below), and it uses certain elements in the
program itself to decide how to transform it. As a result, the transformed
program will contain generated code providing the requested level of support for
reflection. If a quick turn-around is more important than space economy, it is
also possible to run the code without transformation. In this case, the behavior
of the program is identical, but it is implemented by delegation to
`dart:mirrors`, which means that the execution may be costly in terms of space.

[2]: https://www.dartlang.org/tools/pub/assets-and-transformers.html

In other words, the package can be used in two modes: **transformed** mode and
**untransformed** mode.

For both modes, your code will not depend directly on `dart:mirrors`. In the
untransformed mode there is an indirect dependency because the support for
reflective features is implemented by delegation to mirror objects from
`dart:mirrors`. In the transformed mode there is no dependency on `dart:mirrors`
at all, because the transformer `reflectable` generates specialized, static code
that supports the required reflective features.

The use of dynamic reflection is supported if and only if the usage is covered
by the set of *capabilities* specified.

In general, reflection is provided via a subclass of the class
`Reflectable` (we use the term *reflector* to designate an instance of such a
subclass).

```dart
class Reflector extends Reflectable {
  const Reflector() : super(capability1, capability2, ...);
}
```

Reflection is disabled by default, and it is enabled by specifying reflectable
capabilities. With `Reflector` we have specified that `capability1`,
`capability2`, and so on must be supported. The main case for using this is
annotating a given class `A` with a reflector. This implies that the specified
level of reflection support for that reflector should be provided for the class
`A` and its instances.

```dart
@Reflector()
class A {
  ...
}
```

Only classes covered by a reflector `R` and their instances can be accessed
reflectively using `R`, and that access is constrained by the capabilities
passed as the superinitializer in the class of `R`. The basic case is when `R`
is used as an annotation of a given class (as is the case with `A` above), but a
class `C` can also be covered by a reflector `R` if a supertype `A` of `C` is
annotated by a reflector which specifies that subtypes of `A` are covered as
well.

As a result, the available universe of reflection related operations is so
well-known at compile time that it is possible to specialize the support for
reflection to a purely static form that satisfies the requirements of the given
annotations and capabilities.

## Usage

Here is a simple usage example. Assume that we have the following code in the
file `web/main.dart`:

```dart
import 'package:reflectable/reflectable.dart';

// Annotate with this class to enable reflection.
class Reflector extends Reflectable {
  const Reflector()
  : super(invokingCapability); // Request the capability to invoke methods.
}

const reflector = const Reflector();

@reflector // This annotation enables reflection on A.
class A {
  final int a;
  A(this.a);
  greater(int x) => x > a;
  lessEqual(int x) => x <= a;
}

main() {
  A x = new A(10);
  // Reflect upon [x] using the const instance of the reflector:
  InstanceMirror instanceMirror = reflector.reflect(x);
  int weekday = new DateTime.now().weekday;
  // On Fridays we test if 3 is greater than 10, on other days if it is less
  // than or equal.
  String methodName = weekday == DateTime.FRIDAY ? "greater" : "lessEqual";
  // Reflectable invocation:
  print(instanceMirror.invoke(methodName, [3]));
}
```

You can directly run this code in untransformed mode, for instance using the
Dart VM. To avoid the dependency on `dart:mirrors` and save space, you can
transform the code using the transformer in this package.

In order to do this, add the following to your `pubspec.yaml`:
```yaml
dependencies:
  reflectable: any

transformers:
- reflectable:
    entry_points:
      - web/main.dart # The path to your main file
```

And then run `pub build --mode=debug web` (you can omit `web` because that
is the default). This will create a new file
`build/web/main_reflection_data.dart` containing the static data needed for
reflection, and a modified `build/web/main.dart` that will initialize the
reflection framework before running `main`. When you run this file, it is
important that the package-root is set to `build/web/packages` for everything to
work.

For a more advanced example implementing the base of a serialization framework,
please look into [serialize_test.dart][3] test and its [library][4].

[3]: https://github.com/dart-lang/reflectable/test_reflectable/test/serialize_test.dart
[4]: https://github.com/dart-lang/reflectable/test_reflectable/lib/serialize.dart

### Comparison with `dart:mirrors` with `MirrorsUsed` annotations

A lot of the overhead of `dart:mirrors` can be mitigated by using a
`MirrorsUsed` annotation, just as specifying capabilities of reflectable.

One advantage of the reflectable approach is that the same restrictions are
implemented both for running untransformed (on top of `dart:mirrors` in the VM)
and transformed. So the behaviour will be the same on Dartium and the
transformed code compiled with Dart2js.

Another advantage is that, where the interaction between two different
`MirrorsUsed` annotations often is hard to predict, `Reflectable` allows for
several separate mirror-systems (reflectors) with different capabilities. It
means that for some reflection-targets used by one sub-system of the program
(say, a serializer) detailed information can be generated, and only little
information about those used by another.

## Known limitations

Several parts of the library have not yet been implemented. In particular, the
following parts are still missing:

- Side-tagging, i.e., the ability to annotate a class in another file.
- Library-mirrors (hence top-level functions).
- Generic types.
- Reflection on closures.
- Private members. There is currently no support for reflection on private
members, as this would require special support from the runtime for accessing
private names from other libraries.

## Feature requests and bug reports

Please file feature requests and bugs using the
[github issue tracker for this repository][5].

[5]: https://github.com/dart-lang/reflectable/issues


text:
from setuptools import setup, find_packages
import re

for line in open('pyea/__init__.py'):
    match = re.match("__version__ *= *'(.*)'", line)
    if match:
        __version__, = match.groups()

setup(name='pyea',
      version=__version__,
      description='Set of pure python libraries including the most common evolutionary algorithms',
      long_description=open('README.rst').read(),
      author='Alejandro CORREA BAHNSEN',
      author_email='al.bahnsen@gmail.com',
      url='https://github.com/albahnsen/pyea',
      license='new BSD',
      packages=find_packages(),
      keywords=['optimization', 'evolutionary', 'genetic'],
      install_requires=['scikit-learn>=0.15.0b2','pandas>=0.14.0','numpy>=1.8.0'],
      classifiers=['Intended Audience :: Science/Research',
                   'Intended Audience :: Developers',
                   'Programming Language :: Python',
                   'Topic :: Software Development',
                   'Topic :: Scientific/Engineering',
                   'Programming Language :: Python :: 2.7',
                   'Programming Language :: Python :: 3',
                   'Programming Language :: Python :: 3.3',
                   'Programming Language :: Python :: 3.4',
                   'Programming Language :: Python :: 3.5',
                   'Topic :: Scientific/Engineering :: Artificial Intelligence',
                   'License :: OSI Approved :: BSD License',
                   'Operating System :: OS Independent',],
      )


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.IO;
using System.Net.Sockets;

using SimFTP;

using SimFTP.Net.MetadataPackets;

namespace SimFTP.Net.DataPackets
{
	public class BasicDataPacket
	{
		public short FileNameLength { get; protected set; }
		public long FileSize { get; protected set; }

		public string FileName { get; protected set; }

		public FileStream File { get; protected set; }

		private bool _CalledOnlyBasicDataPacket = false;

		public virtual BasicMetadataPacket CreateMetadata(int dataCount)
		{
			return new BasicMetadataPacket(dataCount);
		}

		private BasicDataPacket () { }

		public BasicDataPacket(string fileName, FileStream file)
		{
			SetFileData(fileName, file);
		}

		public byte[] GetBinaryData()
		{
			if (!_CalledOnlyBasicDataPacket)
				return Util.AttachByteArray(BitConverter.GetBytes(FileNameLength), BitConverter.GetBytes(FileSize), Encoding.UTF8.GetBytes(FileName));
			else
				return new byte[] { };
		}

		public byte[] GetOnlyBasicDataPacket()
		{
			this._CalledOnlyBasicDataPacket = true;
			return Util.AttachByteArray(BitConverter.GetBytes(FileNameLength), BitConverter.GetBytes(FileSize), Encoding.UTF8.GetBytes(FileName));
		}

		protected BasicDataPacket(BasicDataPacket data)
		{
			SetFileData(data.FileName, data.File);
		}

		private void SetFileData(string fileName, FileStream stream)
		{
			this.FileNameLength = (short)Encoding.UTF8.GetByteCount(fileName);
			this.FileName = fileName;
			this.File = stream;

			if(stream != null)
				this.FileSize = stream.Length;
		}
	}
}


text:
static const bool SignedNormalOutput = true;

float ManualInterpolate(Texture2D tex, float2 texCoords)
{
    uint2 dims; tex.GetDimensions(dims.x, dims.y);
    float2 exploded = texCoords*float2(dims.xy);
    float result00 = tex[uint2(exploded) + uint2(0,0)].a;
    float result10 = tex[uint2(exploded) + uint2(1,0)].a;
    float result01 = tex[uint2(exploded) + uint2(0,1)].a;
    float result11 = tex[uint2(exploded) + uint2(1,1)].a;
    float2 fracPart = frac(exploded);
    return
          result00 * (1.0f-fracPart.x) * (1.0f-fracPart.y)
        + result10 * (     fracPart.x) * (1.0f-fracPart.y)
        + result01 * (1.0f-fracPart.x) * (     fracPart.y)
        + result11 * (     fracPart.x) * (     fracPart.y)
        ;
}

float3 GBuffer_CalculateBestFitNormal(float3 inputNormal)
{
	//
	//		Calculate the normal value that will
	//		quantize down to 8 bit best and still
	//		best represent this normal...
	//
	//		This requires a little more calculation
	//		in our shader, but it means we can write
	//		to a R8G8B8A8 output normal buffer, instead
	//		of a 16 bit floating point buffer.
	//
	//		see:
	//			http://advances.realtimerendering.com/s2010/Kaplanyan-CryEngine3(SIGGRAPH%202010%20Advanced%20RealTime%20Rendering%20Course).pdf
	//

		//	(assuming input normal is already normalized)

	// get unsigned normal for the cubemap lookup
	float3 vNormalUns = abs(inputNormal.rgb);
	// get the main axis for cubemap lookup
	float maxNAbs = max(vNormalUns.z, max(vNormalUns.x, vNormalUns.y));
	// get the texture coordinates in a collapsed cubemap
	float2 vTexCoord = vNormalUns.z<maxNAbs?(vNormalUns.y<maxNAbs?vNormalUns.yz:vNormalUns.xz):vNormalUns.xy;
	vTexCoord = vTexCoord.x < vTexCoord.y ? vTexCoord.yx : vTexCoord.xy;
    if (vTexCoord.x != 0.f)   // DavidJ -- when x & y are zero, can get a divide by zero here
        vTexCoord.y /= vTexCoord.x;
	// fit normal into the edge of the unit cube
	float3 result = inputNormal.xyz / maxNAbs;
	// look-up fitting length and scale the normal to get the best fit
    #if defined(_CS)
        const bool interpolateBetweenSamples = false;       // non interpolating version seems accurate enough
        float fFittingScale;
        if (interpolateBetweenSamples) {
            fFittingScale = ManualInterpolate(NormalsFittingTexture, vTexCoord);
        } else {
            uint2 dims; NormalsFittingTexture.GetDimensions(dims.x, dims.y);
            fFittingScale = NormalsFittingTexture[uint2(saturate(vTexCoord)*dims.xy + 0.5.xx)%dims].a;
            // fFittingScale = NormalsFittingTexture[uint2(vTexCoord*dims.xy)].a;
        }
    #else
	    float fFittingScale = NormalsFittingTexture.Sample(ClampingSampler, vTexCoord).a;
    #endif
	// scale the normal to get the best fit
	result.rgb *= fFittingScale;
	// wrap to [0;1] unsigned form
	if (!SignedNormalOutput)
        result.rgb = result.rgb * .5f + .5f;
	return result;
}

float4 CompressGBufferNormal(float3 inputNormal)
{
	return float4(GBuffer_CalculateBestFitNormal(inputNormal),0);
}

float3 DecompressGBufferNormal(float3 gBufferNormalSample)
{
    float3 rangeAdj;
    if (!SignedNormalOutput) {
        rangeAdj = -1.0.xxx + 2.f * gBufferNormalSample;
    } else {
        rangeAdj = gBufferNormalSample;
    }

    float lengthSq = dot(rangeAdj, rangeAdj);

    // note -- we're getting issues with zero length normals in the gbuffer
    //          this can occur when the texture mapping bends around geometry
    //          in an extreme way.
    float mult;
    [flatten] if (lengthSq < 1e-4f) mult = 1.f;
    else mult = rsqrt(lengthSq);
    return rangeAdj * mult;
}

#if GBUFFER_TYPE & 1
    #define HAS_PROPERTIES_BUFFER 1
#else
    #define HAS_PROPERTIES_BUFFER 0
#endif

#if GBUFFER_TYPE & 2
    #define NORMAL_BUFFER_8BIT 0
#else
    #define NORMAL_BUFFER_8BIT 1
#endif

struct GBufferEncoded
{
    float4 diffuseBuffer    : SV_Target0;
    float4 normalBuffer     : SV_Target1;
    #if HAS_PROPERTIES_BUFFER == 1
        float4 propertiesBuffer : SV_Target2;
    #endif
};

struct PerPixelMaterialParam
{
    float   roughness;
    float   specular;
    float   metal;
};

struct GBufferValues
{
        // Basic geometry parameters
    float3 diffuseAlbedo;      //  (expressed here in RGB format)
    float3 worldSpaceNormal;   //  (here, in full 3D format)

        // Per-pixel material parameters
    PerPixelMaterialParam material;

        // Special case parameters used by some shaders
    float blendingAlpha;
    float normalMapAccuracy;
    float cookedAmbientOcclusion;
    float cookedLightOcclusion; // this is precalculated occlusion of the dominant light source

    float3 transmission;
};

PerPixelMaterialParam PerPixelMaterialParam_Default()
{
    PerPixelMaterialParam result;
    result.roughness = 0.5f;
    result.specular = 0.05f;
    result.metal = 0.f;
    return result;
}

GBufferValues GBufferValues_Default()
{
    GBufferValues result;
    result.diffuseAlbedo     = 1.0.xxx;
    result.worldSpaceNormal  = 0.0.xxx;

    result.material = PerPixelMaterialParam_Default();

    result.blendingAlpha = 1.f;
    result.normalMapAccuracy = 1.f;
    result.cookedAmbientOcclusion = 1.f;
    result.cookedLightOcclusion = 1.f;

    result.transmission = 0.0.xxx;
    return result;
}

GBufferEncoded Encode(GBufferValues values)
{
        //
        //      Take the raw gbuffer input values and
        //      generate the encoded values
        //
    GBufferEncoded result;
    result.diffuseBuffer.rgb = values.diffuseAlbedo;
    #if NORMAL_BUFFER_8BIT == 1
        result.normalBuffer.xyz = CompressGBufferNormal(values.worldSpaceNormal.xyz).xyz;
    #else
        result.normalBuffer.xyz = values.worldSpaceNormal.xyz;
    #endif

    #if defined(DECAL_BLEND)
        const bool decalBlend = (DECAL_BLEND == 1);
    #else
        const bool decalBlend = false;
    #endif
    if (decalBlend) {
        result.diffuseBuffer.a = values.blendingAlpha;
        result.normalBuffer.a = values.blendingAlpha;
    } else {
            // todo -- "normal map accuracy" can be used to soften the roughness here...
        result.diffuseBuffer.a = values.material.roughness;
        result.normalBuffer.a = values.material.specular;
    }

    #if HAS_PROPERTIES_BUFFER == 1
        result.propertiesBuffer.r = values.material.metal;
        result.propertiesBuffer.g = values.cookedAmbientOcclusion;
        result.propertiesBuffer.b = values.cookedLightOcclusion;
        result.propertiesBuffer.a = values.blendingAlpha;
    #endif

    return result;
}

GBufferValues Decode(GBufferEncoded values)
{
    GBufferValues result = GBufferValues_Default();
	result.diffuseAlbedo = values.diffuseBuffer.rgb;
	result.worldSpaceNormal  = DecompressGBufferNormal(values.normalBuffer.xyz);

    result.material.roughness = values.diffuseBuffer.a;
    result.material.specular = values.normalBuffer.a;

	result.blendingAlpha = 1.f;
	result.normalMapAccuracy = 1.f;

	#if HAS_PROPERTIES_BUFFER==1
        result.material.metal = values.propertiesBuffer.r;
		result.cookedAmbientOcclusion = values.propertiesBuffer.g;
        result.cookedLightOcclusion = values.propertiesBuffer.b;
        result.blendingAlpha = values.propertiesBuffer.a;
	#endif
	return result;
}

GBufferValues GetSystemStruct_GBufferValues()
{
        //  called by the shader nodes editor to get the
        //  gbuffer values for preview
    return GBufferValues_Default();
}

#endif


text:
CREATE INDEX f_i ON folders(foldername);
SELECT count(*) FROM folders WHERE foldername < 'FolderC' COLLATE nocase;