text:
Router.map(function () {
    this.route('home', {
        path: '/', layoutTemplate: 'mainLayout'
    });
    this.route('hashtags', { path: '/admin', layoutTemplate: 'mainLayout' }, function () {

        this.render('hashtags');
    });
    this.route('display', {
        path: '/display', layoutTemplate: 'mainLayout', onAfterAction: function (pause) {

            Tweets = new Meteor.Collection(null);
            var hashtags = Hashtags.find().fetch();// Template.display.helpers.hashtags();
            for (var j = hashtags.length-1; j >= 0 ; j--) {
                var hashtag = hashtags[j].text;
                Meteor.call("checkTwitter", hashtag, function (err, result, data) {
                    console.log(result);
                    for (var i = 0; i < result.length; i++) {
                        result[i].html = result[i].text; //this does not work => result[i].text.replace(hashtag, "" + hashtag + "");
                        Tweets.insert(result[i]);
                    }
                });
            }
        }
    });
});

// Default routing settings
Router.configure({
    layoutTemplate: 'mainLayout',
    notFoundTemplate: '404'
});

Hashtags = new Mongo.Collection("hashtags");
Tweets = new Meteor.Collection(null);

if (Meteor.isClient) {
  // This code only runs on the client
  Meteor.subscribe("hashtags");

  Template.hashtags.helpers({
    hashtags: function () {
      if (Session.get("hideCompleted")) {
        // If hide completed is checked, filter hashtags
        return Hashtags.find({checked: {$ne: true}}, {sort: {createdAt: -1}});
      } else {
        // Otherwise, return all of the hashtags
        return Hashtags.find({}, {sort: {createdAt: -1}});
      }
    },
    hideCompleted: function () {
      return Session.get("hideCompleted");
    },
    incompleteCount: function () {
      return Hashtags.find({checked: {$ne: true}}).count();
    }
  });

  Template.hashtags.events({
    "submit .new-hashtag": function (event) {
      // This function is called when the new hashtag form is submitted
      var text = event.target.text.value;

      Meteor.call("addHashtag", text);

      // Clear form
      event.target.text.value = "";

      event.preventDefault();
      // Prevent default form submit
      return false;
    },
    "change .hide-completed input": function (event) {
      Session.set("hideCompleted", event.target.checked);
    }
  });

  Template.hashtag.events({
    "click .toggle-checked": function () {
      // Set the checked property to the opposite of its current value
      Meteor.call("setChecked", this._id, ! this.checked);
    },
    "click .delete": function () {
        Meteor.call("deleteHashtag", this._id);
    },
    "click .toggle-private": function () {
      Meteor.call("setPrivate", this._id, ! this.private);
    }
  });

  Template.hashtag.helpers({
    isOwner: function () {
      return this.owner === Meteor.userId();
    }
  });

  Template.display.helpers({
      tweets: function () {
          return Tweets.find({});
      },
      hashtags: function () {
          return Hashtags.find({}, { sort: { createdAt: -1 } });
      }
  });

  Accounts.ui.config({
    passwordSignupFields: "USERNAME_ONLY"
  });
}

Meteor.methods({
  addHashtag: function (text) {
      if (text.indexOf('#') == 0 && text.length > 1)
          text = text.substring(1);
    Hashtags.insert({
        text: text,
      createdAt: new Date(),
      owner: Meteor.userId(),
      username: Meteor.user().username
    });
  },
  deleteHashtag: function (hashtagId) {
    var hashtag = Hashtags.findOne(hashtagId);
    if (hashtag.private && hashtag.owner !== Meteor.userId()) {
      // If the hashtag is private, make sure only the owner can delete it
      throw new Meteor.Error("not-authorized");
    }

    Hashtags.remove(hashtagId);
  },
  setChecked: function (hashtagId, setChecked) {
    var hashtag = Hashtags.findOne(hashtagId);
    if (hashtag.private && hashtag.owner !== Meteor.userId()) {
      // If the hashtag is private, make sure only the owner can check it off
      throw new Meteor.Error("not-authorized");
    }

    Hashtags.update(hashtagId, { $set: { checked: setChecked} });
  },
  setPrivate: function (hashtagId, setToPrivate) {
    var hashtag = Hashtags.findOne(hashtagId);

    // Make sure only the hashtag owner can make a hashtag private
    if (hashtag.owner !== Meteor.userId()) {
      throw new Meteor.Error("not-authorized");
    }

    Hashtags.update(hashtagId, { $set: { private: setToPrivate } });
  }
});

if (Meteor.isServer) {
        var Twit = Meteor.npmRequire('twit');
        var T = new Twit({
            consumer_key: Meteor.settings.twitter_consumer_key, // API key
            consumer_secret: Meteor.settings.twitter_consumer_secret,// API secret
            access_token: Meteor.settings.twitter_access_token,
            access_token_secret: Meteor.settings.twitter_access_token_secret,
        });
        var wrapGet = Meteor.wrapAsync(T.get, T);

  // Only publish hashtags that are public or belong to the current user
  Meteor.publish("hashtags", function () {
    return Hashtags.find({
      $or: [
        { private: {$ne: true} },
        { owner: this.userId }
      ]
    });
  });
  Meteor.methods({
      checkTwitter: function (hashtag) {
          //  search twitter for all tweets containing the word 'banana'
          //  since 2015
          data = wrapGet('search/tweets',
             {
                 q: '#'+hashtag + ' since:2015-03-11',
                 count: 10
             }
         );
          if (data)
              return data.statuses;
      },
      checkInstagram: function (hashtag) {
          var api = 'https://api.instagram.com/v1/tags/search?q=' + hashtag + '&access_token=' + Meteor.settings.InstagramAPI.CLIENT_SECRET;
          data = Meteor.wrapAsync(HTTP.call("GET", api));

          return data;
          //this.unblock();
          //try {
          //    var result = ;
          //    return true;
          //} catch (e) {
          //    // Got a network error, time-out or HTTP error in the 400 or 500 range.
          //    return false;
          //}
      }
  });

  Meteor.publish('instagramSearch', function (hashtag) {
      var self = this;
      try {
          var response = HTTP.get('https://api.instagram.com/v1/tags/search', {
              params: {
                  q: hashtag,
                  access_token: Meteor.settings.InstagramAPI.CLIENT_SECRET
              }
          });

          _.each(response.data.items, function (item) {
              var doc = {
                  title: item.title,
              };

              self.added('pictures', Random.id(), doc);
          });

          self.ready();

      } catch (error) {
          console.log(error);
      }
  });
}


text:
cd gui/final
sh run.sh

redpajama_set_name: RedPajamaGithub


text:
using namespace std;

template<typename T>
struct is_void
{
  static bool const value = false;
};

template<>
struct is_void<void>
{
  static bool const value = true;
};

int main(int argc, char* argv[])
{
  cout << is_void<int>::value << endl;
  cout << is_void<void>::value << endl;

  return 0;
}


text:
using System.Text.Json;
using Azure.Core;

namespace Azure.Management.Network.Models
{
    public partial class PrivateLinkServiceConnectionState : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Status != null)
            {
                writer.WritePropertyName("status");
                writer.WriteStringValue(Status);
            }
            if (Description != null)
            {
                writer.WritePropertyName("description");
                writer.WriteStringValue(Description);
            }
            if (ActionsRequired != null)
            {
                writer.WritePropertyName("actionsRequired");
                writer.WriteStringValue(ActionsRequired);
            }
            writer.WriteEndObject();
        }

        internal static PrivateLinkServiceConnectionState DeserializePrivateLinkServiceConnectionState(JsonElement element)
        {
            string status = default;
            string description = default;
            string actionsRequired = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("status"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    status = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("description"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    description = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("actionsRequired"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    actionsRequired = property.Value.GetString();
                    continue;
                }
            }
            return new PrivateLinkServiceConnectionState(status, description, actionsRequired);
        }
    }
}


text:
<?php

namespace Wei;

/**
 * A base database record class
 *
 * @author      Twin Huang <twinhuang@qq.com>
 * @property    Db $db A database service inspired by Doctrine DBAL
 * @method      \Wei\Record db($table = null) Create a new record object
 * @property    \Wei\BaseCache $cache A cache service (Optional)
 * @method      \Wei\TagCache tagCache($tags) Create a new cache service with tagging support (Optional)
 */
class Record extends Base implements \ArrayAccess, \IteratorAggregate, \Countable
{
    /* The query types. */
    public const SELECT = 0;
    public const DELETE = 1;
    public const UPDATE = 2;

    /* The builder states. */
    public const STATE_DIRTY = 0;
    public const STATE_CLEAN = 1;

    /**
     * The record table name
     *
     * @var string
     */
    protected $table;

    /**
     * The complete record table name with table prefix
     *
     * @var string
     */
    protected $fullTable;

    /**
     * The table fields
     * If leave it blank, it will automatic generate form the database table,
     * or fill it to speed up the record
     *
     * @var array
     */
    protected $fields = [];

    /**
     * The primary key field
     *
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * Whether it's a new record and has not save to database
     *
     * @var bool
     */
    protected $isNew = true;

    /**
     * The record data
     *
     * @var array|$this[]
     */
    protected $data = [];

    /**
     * The fields that are assignable through fromArray method
     *
     * @var array
     */
    protected $fillable = [];

    /**
     * The fields that aren't assignable through fromArray method
     *
     * @var array
     */
    protected $guarded = ['id'];

    /**
     * Whether the record's data is changed
     *
     * @var bool
     */
    protected $isChanged = false;

    /**
     * The record data before changed
     *
     * @var array
     */
    protected $changedData = [];

    /**
     * Whether the record has been removed from database
     *
     * @var bool
     */
    protected $isDestroyed = false;

    /**
     * Whether the record is waiting to remove from database
     *
     * @var bool
     */
    protected $detached = false;

    /**
     * Whether the data is loaded
     *
     * @var bool
     */
    protected $loaded = false;

    /**
     * Whether it contains multiple or single row data
     *
     * @var bool
     */
    protected $isColl;

    /**
     * The parts of SQL
     *
     * @var array
     */
    protected $sqlParts = [
        'select' => [],
        'from' => null,
        'join' => [],
        'set' => [],
        'where' => null,
        'groupBy' => [],
        'having' => null,
        'orderBy' => [],
        'limit' => null,
        'offset' => null,
    ];

    /**
     * A field to be the key of the fetched array, if not provided, return
     * default number index array
     *
     * @var string
     */
    protected $indexBy;

    /**
     * @var string the complete SQL string for this query
     */
    protected $sql;

    /**
     * The query parameters
     *
     * @var array
     */
    protected $params = [];

    /**
     * The parameter type map of this query
     *
     * @var array
     */
    protected $paramTypes = [];

    /**
     * The type of query this is. Can be select, update or delete
     *
     * @var int
     */
    protected $type = self::SELECT;

    /**
     * The state of the query object. Can be dirty or clean
     *
     * @var int
     */
    protected $state = self::STATE_CLEAN;

    /**
     * The default cache time
     *
     * @var int
     */
    protected $defaultCacheTime = 60;

    /**
     * The specified cache time
     *
     * @var int|false
     */
    protected $cacheTime = false;

    /**
     * @var string
     */
    protected $cacheKey = '';

    /**
     * The cache tags
     *
     * @var array
     */
    protected $cacheTags = [];

    /**
     * @var string|bool
     */
    protected $lock = '';

    /**
     * Constructor
     *
     * @param array $options
     */
    public function __construct(array $options = [])
    {
        parent::__construct($options);

        // Clear changed status after created
        $this->changedData = [];
        $this->isChanged = false;

        $this->triggerCallback('afterLoad');
    }

    /**
     * Return the record table name
     *
     * @return string
     */
    public function getTable()
    {
        return $this->table;
    }

    /**
     * Set the record table name
     *
     * @param string $table
     * @return $this
     */
    public function setTable($table)
    {
        return $this->from($table);
    }

    /**
     * Returns the record data as array
     *
     * @param array $returnFields A indexed array specified the fields to return
     * @return array
     */
    public function toArray($returnFields = [])
    {
        if (!$this->isColl) {
            $data = array_fill_keys($returnFields ?: $this->getFields(), null);
            if (!$returnFields) {
                return $this->data + $data;
            } else {
                $data = array_fill_keys($returnFields, null);
                return array_intersect_key($this->data, $data) + $data;
            }
        } else {
            $data = [];
            /** @var $record Record */
            foreach ($this->data as $key => $record) {
                $data[$key] = $record->toArray($returnFields);
            }
            return $data;
        }
    }

    /**
     * Returns the record and relative records data as JSON string
     *
     * @param array $returnFields A indexed array specified the fields to return
     * @return array
     */
    public function toJson($returnFields = [])
    {
        return json_encode($this->toArray($returnFields));
    }

    /**
     * Import a PHP array in this record
     *
     * @param array|\ArrayAccess $data
     * @return $this
     */
    public function fromArray($data)
    {
        foreach ($data as $key => $value) {
            if (is_int($key) || $this->isFillable($key)) {
                $this->set($key, $value);
            }
        }
        return $this;
    }

    /**
     * Check if the field is assignable through fromArray method
     *
     * @param string $field
     * @return bool
     */
    public function isFillable($field)
    {
        return !in_array($field, $this->guarded, true) && !$this->fillable || in_array($field, $this->fillable, true);
    }

    /**
     * Import a PHP array in this record
     *
     * @param array|\ArrayAccess $data
     * @return $this
     */
    public function setData($data)
    {
        foreach ($data as $field => $value) {
            $this->set($field, $value);
        }
        return $this;
    }

    /**
     * Save the record or data to database
     *
     * @param array $data
     * @return $this
     */
    public function save($data = [])
    {
        // 1. Merges data from parameters
        $data && $this->fromArray($data);

        // 2.1 Saves single record
        if (!$this->isColl) {
            // 2.1.1 Returns when record has been destroy to avoid store dirty data
            if ($this->isDestroyed) {
                return $this;
            }

            // Deletes the record when it's waiting to remove from database
            if ($this->detached) {
                $this->db->delete($this->table, [$this->primaryKey => $this->data[$this->primaryKey]]);
                $this->isDestroyed = true;
                return $this;
            }

            // 2.1.2 Triggers before callbacks
            $isNew = $this->isNew;
            $this->triggerCallback('beforeSave');
            $this->triggerCallback($isNew ? 'beforeCreate' : 'beforeUpdate');

            // 2.1.3.1 Inserts new record
            if ($isNew) {
                // Removes primary key value when it's empty to avoid SQL error
                if (array_key_exists($this->primaryKey, $this->data) && !$this->data[$this->primaryKey]) {
                    unset($this->data[$this->primaryKey]);
                }

                $this->db->insert($this->table, $this->data);
                $this->isNew = false;

                // Receives primary key value when it's empty
                if (!isset($this->data[$this->primaryKey]) || !$this->data[$this->primaryKey]) {
                    // Prepare sequence name for PostgreSQL
                    $sequence = sprintf('%s_%s_seq', $this->fullTable, $this->primaryKey);
                    $this->data[$this->primaryKey] = $this->db->lastInsertId($sequence);
                }
                // 2.1.3.2 Updates existing record
            } else {
                if ($this->isChanged) {
                    $data = array_intersect_key($this->data, $this->changedData);
                    $this->db->update($this->table, $data, [
                        $this->primaryKey => $this->data[$this->primaryKey],
                    ]);
                }
            }

            // 2.1.4 Reset changed data and changed status
            $this->changedData = [];
            $this->isChanged = false;

            // 2.1.5. Triggers after callbacks
            $this->triggerCallback($isNew ? 'afterCreate' : 'afterUpdate');
            $this->triggerCallback('afterSave');
        // 2.2 Loop and save collection records
        } else {
            foreach ($this->data as $record) {
                $record->save();
            }
        }

        return $this;
    }

    /**
     * Delete the current record and trigger the beforeDestroy and afterDestroy callback
     *
     * @param mixed $conditions
     * @return $this
     */
    public function destroy($conditions = false)
    {
        $this->andWhere($conditions);
        !$this->loaded && $this->loadData(0);

        if (!$this->isColl) {
            $this->triggerCallback('beforeDestroy');
            $this->executeDestroy();
            $this->isDestroyed = true;
            $this->triggerCallback('afterDestroy');
        } else {
            foreach ($this->data as $record) {
                $record->destroy();
            }
        }

        return $this;
    }

    /**
     * Reload the record data from database
     *
     * @return $this
     */
    public function reload()
    {
        $this->data = (array) $this->db->select($this->table, [$this->primaryKey => $this->get($this->primaryKey)]);
        $this->changedData = [];
        $this->isChanged = false;
        $this->triggerCallback('afterLoad');
        return $this;
    }

    /**
     * Merges data into collection and save to database, including insert, update and delete
     *
     * @param array $data A two-dimensional array
     * @param array $extraData The extra data for new rows
     * @param bool $sort
     * @return $this
     */
    public function saveColl($data, $extraData = [], $sort = false)
    {
        if (!is_array($data)) {
            return $this;
        }

        // 1. Uses primary key as data index
        $newData = [];
        foreach ($this->data as $key => $record) {
            unset($this->data[$key]);
            // Ignore default data
            if ($record instanceof $this) {
                $newData[$record[$this->primaryKey]] = $record;
            }
        }
        $this->data = $newData;

        // 2. Removes empty rows from data
        foreach ($data as $index => $row) {
            if (!array_filter($row)) {
                unset($data[$index]);
            }
        }

        // 3. Removes missing rows
        $existIds = [];
        foreach ($data as $row) {
            if (isset($row[$this->primaryKey]) && null !== $row[$this->primaryKey]) {
                $existIds[] = $row[$this->primaryKey];
            }
        }
        /** @var $record Record */
        foreach ($this->data as $key => $record) {
            if (!in_array($record[$this->primaryKey], $existIds, false)) {
                $record->destroy();
                unset($this->data[$key]);
            }
        }

        // 4. Merges existing rows or create new rows
        foreach ($data as $index => $row) {
            if ($sort) {
                $row[$sort] = $index;
            }
            if (isset($row[$this->primaryKey], $this->data[$row[$this->primaryKey]])) {
                $this->data[$row[$this->primaryKey]]->fromArray($row);
            } else {
                $this[] = $this->db($this->table)->fromArray($extraData + $row);
            }
        }

        // 5. Save and return
        return $this->save();
    }

    /**
     * Receives the record field value
     *
     * @param string $name
     * @return mixed|$this
     * @throws \InvalidArgumentException When field not found
     */
    public function get($name)
    {
        // Check if field exists when it is not a collection
        if (!$this->isColl && !in_array($name, $this->getFields(), false)) {
            throw new \InvalidArgumentException(sprintf(
                'Field "%s" not found in record class "%s"',
                $name,
                static::class
            ));
        }
        return isset($this->data[$name]) ? $this->data[$name] : null;
    }

    /**
     * Set the record field value
     *
     * @param string $name
     * @param mixed $value
     * @return $this
     * @throws \InvalidArgumentException
     */
    public function set($name, $value = null)
    {
        $this->loaded = true;

        // Set record for collection
        if (!$this->data && $value instanceof static) {
            $this->isColl = true;
        }

        if (!$this->isColl) {
            if (in_array($name, $this->getFields(), false)) {
                $this->changedData[$name] = isset($this->data[$name]) ? $this->data[$name] : null;
                $this->data[$name] = $value;
                $this->isChanged = true;
            }
        } else {
            if (!$value instanceof static) {
                throw new \InvalidArgumentException('Value for collection must be an instance of Wei\Record');
            } else {
                // Support $coll[] = $value;
                if (null === $name) {
                    $this->data[] = $value;
                } else {
                    $this->data[$name] = $value;
                }
            }
        }
        return $this;
    }

    /**
     * Set field value for every record in collection
     *
     * @param string $name
     * @param mixed $value
     * @return $this
     */
    public function setAll($name, $value)
    {
        foreach ($this->data as $record) {
            $record[$name] = $value;
        }
        return $this;
    }

    /**
     * Return the value of field from every record in collection
     *
     * @param string $name
     * @return array
     */
    public function getAll($name)
    {
        $data = [];
        foreach ($this->data as $record) {
            $data[] = $record[$name];
        }
        return $data;
    }

    /**
     * Remove field value
     *
     * @param string $name The name of field
     * @return $this
     */
    public function remove($name)
    {
        if (!$this->isColl) {
            if (array_key_exists($name, $this->data)) {
                $this->data[$name] = null;
            }
        } else {
            unset($this->data[$name]);
        }
        return $this;
    }

    /**
     * Increment a field
     *
     * @param string $name
     * @param int $offset
     * @return $this
     */
    public function incr($name, $offset = 1)
    {
        $this[$name] = $this->db->raw($name . ' + ' . $offset);
        return $this;
    }

    /**
     * Decrement a field
     *
     * @param string $name
     * @param int $offset
     * @return $this
     */
    public function decr($name, $offset = 1)
    {
        $this[$name] = $this->db->raw($name . ' - ' . $offset);
        return $this;
    }

    /**
     * Set the detach status for current record
     *
     * @param bool $bool
     * @return $this
     */
    public function detach($bool = true)
    {
        $this->detached = (bool) $bool;
        return $this;
    }

    /**
     * Check if it's a new record and has not save to database
     *
     * @return bool
     */
    public function isNew()
    {
        return $this->isNew;
    }

    /**
     * Check if the record's data or specified field is changed
     *
     * @param string $field
     * @return bool
     */
    public function isChanged($field = null)
    {
        if ($field) {
            return array_key_exists($field, $this->changedData);
        }
        return $this->isChanged;
    }

    /**
     * Check if the record has been removed from the database
     *
     * @return bool
     */
    public function isDestroyed()
    {
        return $this->isDestroyed;
    }

    /**
     * Check if the record is waiting to remove from database
     *
     * @return bool
     */
    public function isDetached()
    {
        return $this->detached;
    }

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

    /**
     * Returns whether the data is loaded
     *
     * @return bool
     */
    public function isLoaded()
    {
        return $this->loaded;
    }

    /**
     * Sets the primary key field
     *
     * @param string $primaryKey
     * @return $this
     */
    public function setPrimaryKey($primaryKey)
    {
        $this->primaryKey = $primaryKey;
        return $this;
    }

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

    /**
     * Returns the name of fields of current table
     *
     * @return array
     */
    public function getFields()
    {
        if (empty($this->fields)) {
            $this->fields = $this->db->getTableFields($this->fullTable, true);
        }
        return $this->fields;
    }

    /**
     * Return the field data before changed
     *
     * @param string $field
     * @return string|array
     */
    public function getChangedData($field = null)
    {
        if ($field) {
            return isset($this->changedData[$field]) ? $this->changedData[$field] : null;
        }
        return $this->changedData;
    }

    /**
     * Get the state of this query builder instance
     *
     * @return int
     */
    public function getState()
    {
        return $this->state;
    }

    /**
     * Execute this query using the bound parameters and their types
     *
     * @return mixed
     */
    public function execute()
    {
        if (self::SELECT == $this->type) {
            $this->loaded = true;
            if (false !== $this->cacheTime) {
                return $this->fetchFromCache();
            } else {
                return $this->db->fetchAll($this->getSql(), $this->params, $this->paramTypes);
            }
        } else {
            return $this->db->executeUpdate($this->getSql(), $this->params, $this->paramTypes);
        }
    }

    /**
     * Clear cache that tagged with current table name
     *
     * @return $this
     */
    public function clearTagCache()
    {
        $this->tagCache($this->getCacheTags())->clear();
        return $this;
    }

    /**
     * Executes the generated SQL and returns the found record object or false
     *
     * @param mixed $conditions
     * @return $this|false
     */
    public function find($conditions = false)
    {
        $this->isColl = false;
        $data = $this->fetch($conditions);
        if ($data) {
            $this->data = $data + $this->data;
            $this->triggerCallback('afterFind');
            return $this;
        } else {
            return false;
        }
    }

    /**
     * Find a record by specified conditions and init with the specified data if record not found
     *
     * @param mixed $conditions
     * @param array $data
     * @return $this
     */
    public function findOrInit($conditions = false, $data = [])
    {
        if (!$this->find($conditions)) {
            // Reset status when record not found
            $this->isNew = true;

            !is_array($conditions) && $conditions = [$this->primaryKey => $conditions];

            // Convert to object to array
            if (is_object($data) && method_exists($data, 'toArray')) {
                $data = $data->toArray();
            }

            // conditions data are fillable
            $this->fromArray($data);
            $this->setData($conditions);
        }
        return $this;
    }

    /**
     * Find a record by specified conditions and throws 404 exception if record not found
     *
     * @param mixed $conditions
     * @return $this
     * @throws \Exception
     */
    public function findOne($conditions = false)
    {
        if ($this->find($conditions)) {
            return $this;
        } else {
            throw new \Exception('Record not found', 404);
        }
    }

    /**
     * Executes the generated SQL and returns the found record collection object or false
     *
     * @param mixed $conditions
     * @return $this|$this[]
     */
    public function findAll($conditions = false)
    {
        $this->isColl = true;
        $data = $this->fetchAll($conditions);

        $records = [];
        foreach ($data as $key => $row) {
            /** @var $records Record[] */
            $records[$key] = $this->db->init($this->table, $row, false);
            $records[$key]->triggerCallback('afterFind');
        }

        $this->data = $records;
        return $this;
    }

    /**
     * Find a record by primary key value
     *
     * @param mixed $value
     * @return $this|false
     */
    public function findById($value)
    {
        return $this->find([$this->primaryKey => $value]);
    }

    /**
     * Find a record by primary key value and throws 404 exception if record not found
     *
     * @param mixed $value
     * @return $this
     */
    public function findOneById($value)
    {
        return $this->findOne([$this->primaryKey => $value]);
    }

    /**
     * Find a record by primary key value and init with the specified data if record not found
     *
     * @param mixed $value
     * @param array $data
     * @return $this
     */
    public function findOrInitById($value, $data = [])
    {
        return $this->findOrInit([$this->primaryKey => $value], $data);
    }

    /**
     * Executes the generated query and returns the first array result
     *
     * @param mixed $conditions
     * @return array|false
     */
    public function fetch($conditions = false)
    {
        $this->andWhere($conditions);
        $this->limit(1);
        $data = $this->execute();
        return $data ? $data[0] : false;
    }

    /**
     * Executes the generated query and returns a column value of the first row
     *
     * @param mixed $conditions
     * @return array|false
     */
    public function fetchColumn($conditions = false)
    {
        $data = $this->fetch($conditions);
        return $data ? current($data) : false;
    }

    /**
     * Executes the generated query and returns all array results
     *
     * @param mixed $conditions
     * @return array|false
     */
    public function fetchAll($conditions = false)
    {
        $this->andWhere($conditions);
        $data = $this->execute();
        if ($this->indexBy) {
            $data = $this->executeIndexBy($data, $this->indexBy);
        }
        return $data;
    }

    /**
     * Executes a COUNT query to receive the rows number
     *
     * @param mixed $conditions
     * @param string $count
     * @return int
     */
    public function count($conditions = false, $count = '1')
    {
        $this->andWhere($conditions);

        $select = $this->sqlParts['select'];
        $this->select('COUNT(' . $count . ')');
        $count = (int) $this->db->fetchColumn($this->getSqlForSelect(true), $this->params);
        $this->sqlParts['select'] = $select;

        return $count;
    }

    /**
     * Executes a sub query to receive the rows number
     *
     * @param mixed $conditions
     * @return int
     */
    public function countBySubQuery($conditions = false)
    {
        $this->andWhere($conditions);
        return (int) $this->db->fetchColumn($this->getSqlForCount(), $this->params);
    }

    /**
     * Returns the record number in collection
     *
     * @return int
     */
    public function length()
    {
        return $this->size();
    }

    /**
     * Returns the record number in collection
     *
     * @return int
     */
    public function size()
    {
        $this->loadData(0);
        return count($this->data);
    }

    /**
     * Execute a update query with specified data
     *
     * @param array|string $set
     * @return int
     */
    public function update($set = [])
    {
        if (is_array($set)) {
            $params = [];
            foreach ($set as $field => $param) {
                $this->add('set', $field . ' = ?', true);
                $params[] = $param;
            }
            $this->params = array_merge($params, $this->params);
        } else {
            $this->add('set', $set, true);
        }
        $this->type = self::UPDATE;
        return $this->execute();
    }

    /**
     * Execute a delete query with specified conditions
     *
     * @param mixed $conditions
     * @return mixed
     */
    public function delete($conditions = false)
    {
        $this->andWhere($conditions);
        $this->type = self::DELETE;
        return $this->execute();
    }

    /**
     * Sets the position of the first result to retrieve (the "offset")
     *
     * @param int $offset The first result to return
     * @return $this
     */
    public function offset($offset)
    {
        $offset = (int) $offset;
        $offset < 0 && $offset = 0;
        return $this->add('offset', $offset);
    }

    /**
     * Sets the maximum number of results to retrieve (the "limit")
     *
     * @param int $limit The maximum number of results to retrieve
     * @return $this
     */
    public function limit($limit)
    {
        $limit = (int) $limit;
        $limit < 1 && $limit = 1;
        return $this->add('limit', $limit);
    }

    /**
     * Sets the page number, the "OFFSET" value is equals "($page - 1) * LIMIT"
     *
     * @param int $page The page number
     * @return $this
     */
    public function page($page)
    {
        $limit = $this->getSqlPart('limit');
        if (!$limit) {
            $limit = 10;
            $this->add('limit', $limit);
        }
        return $this->offset(($page - 1) * $limit);
    }

    /**
     * Specifies an item that is to be returned in the query result.
     * Replaces any previously specified selections, if any.
     *
     * @param mixed $select the selection expressions
     * @return $this
     */
    public function select($select = null)
    {
        $this->type = self::SELECT;

        if (empty($select)) {
            return $this;
        }

        $selects = is_array($select) ? $select : func_get_args();
        return $this->add('select', $selects, false);
    }

    /**
     * Adds an item that is to be returned in the query result.
     *
     * @param mixed $select the selection expression
     * @return $this
     */
    public function addSelect($select = null)
    {
        $this->type = self::SELECT;

        if (empty($select)) {
            return $this;
        }

        $selects = is_array($select) ? $select : func_get_args();
        return $this->add('select', $selects, true);
    }

    /**
     * Sets table for FROM query
     *
     * @param string $from The table
     * @return $this
     */
    public function from($from)
    {
        $pos = strpos($from, ' ');
        if (false !== $pos) {
            $this->table = substr($from, 0, $pos);
        } else {
            $this->table = $from;
        }
        $this->fullTable = $this->db->getTable($this->table);
        return $this->add('from', $this->db->getTable($from));
    }

    /**
     * Adds a inner join to the query
     *
     * @param string $table The table name to join
     * @param string $on The condition for the join
     * @return $this
     */
    public function join($table, $on = null)
    {
        return $this->innerJoin($table, $on);
    }

    /**
     * Adds a inner join to the query
     *
     * @param string $table The table name to join
     * @param string $on The condition for the join
     * @return $this
     */
    public function innerJoin($table, $on = null)
    {
        return $this->add('join', ['type' => 'inner', 'table' => $table, 'on' => $on], true);
    }

    /**
     * Adds a left join to the query
     *
     * @param string $table The table name to join
     * @param string $on The condition for the join
     * @return $this
     */
    public function leftJoin($table, $on = null)
    {
        return $this->add('join', ['type' => 'left', 'table' => $table, 'on' => $on], true);
    }

    /**
     * Adds a right join to the query
     *
     * @param string $table The table name to join
     * @param string $on The condition for the join
     * @return $this
     */
    public function rightJoin($table, $on = null)
    {
        return $this->add('join', ['type' => 'right', 'table' => $table, 'on' => $on], true);
    }

    /**
     * Specifies one or more restrictions to the query result.
     * Replaces any previously specified restrictions, if any.
     *
     * ```php
     * $user = wei()->db('user')->where('id = 1');
     * $user = wei()->db('user')->where('id = ?', 1);
     * $users = wei()->db('user')->where(array('id' => '1', 'username' => 'twin'));
     * $users = wei()->where(array('id' => array('1', '2', '3')));
     * ```
     *
     * @param mixed $conditions The WHERE conditions
     * @param array $params The condition parameters
     * @param array $types The parameter types
     * @return $this
     */
    public function where($conditions, $params = [], $types = [])
    {
        if (false === $conditions) {
            return $this;
        } else {
            $conditions = $this->processCondition($conditions, $params, $types);
            return $this->add('where', $conditions);
        }
    }

    /**
     * Adds one or more restrictions to the query results, forming a logical
     * conjunction with any previously specified restrictions
     *
     * @param string|array $conditions The WHERE conditions
     * @param array $params The condition parameters
     * @param array $types The parameter types
     * @return $this
     */
    public function andWhere($conditions, $params = [], $types = [])
    {
        if (false === $conditions) {
            return $this;
        } else {
            $conditions = $this->processCondition($conditions, $params, $types);
            return $this->add('where', $conditions, true, 'AND');
        }
    }

    /**
     * Adds one or more restrictions to the query results, forming a logical
     * disjunction with any previously specified restrictions.
     *
     * @param string $conditions The WHERE conditions
     * @param array $params The condition parameters
     * @param array $types The parameter types
     * @return $this
     */
    public function orWhere($conditions, $params = [], $types = [])
    {
        $conditions = $this->processCondition($conditions, $params, $types);
        return $this->add('where', $conditions, true, 'OR');
    }

    /**
     * Specifies a grouping over the results of the query.
     * Replaces any previously specified groupings, if any.
     *
     * @param mixed $groupBy the grouping expression
     * @return $this
     */
    public function groupBy($groupBy)
    {
        if (empty($groupBy)) {
            return $this;
        }

        $groupBy = is_array($groupBy) ? $groupBy : func_get_args();
        return $this->add('groupBy', $groupBy, false);
    }

    /**
     * Adds a grouping expression to the query.
     *
     * @param mixed $groupBy the grouping expression
     * @return $this
     */
    public function addGroupBy($groupBy)
    {
        if (empty($groupBy)) {
            return $this;
        }
        $groupBy = is_array($groupBy) ? $groupBy : func_get_args();
        return $this->add('groupBy', $groupBy, true);
    }

    /**
     * Specifies a restriction over the groups of the query.
     * Replaces any previous having restrictions, if any.
     *
     * @param string $conditions The having conditions
     * @param array $params The condition parameters
     * @param array $types The parameter types
     * @return $this
     */
    public function having($conditions, $params = [], $types = [])
    {
        $conditions = $this->processCondition($conditions, $params, $types);
        return $this->add('having', $conditions);
    }

    /**
     * Adds a restriction over the groups of the query, forming a logical
     * conjunction with any existing having restrictions.
     *
     * @param string $conditions The HAVING conditions to append
     * @param array $params The condition parameters
     * @param array $types The parameter types
     * @return $this
     */
    public function andHaving($conditions, $params = [], $types = [])
    {
        $conditions = $this->processCondition($conditions, $params, $types);
        return $this->add('having', $conditions, true, 'AND');
    }

    /**
     * Adds a restriction over the groups of the query, forming a logical
     * disjunction with any existing having restrictions.
     *
     * @param string $conditions The HAVING conditions to add
     * @param array $params The condition parameters
     * @param array $types The parameter types
     * @return $this
     */
    public function orHaving($conditions, $params = [], $types = [])
    {
        $conditions = $this->processCondition($conditions, $params, $types);
        return $this->add('having', $conditions, true, 'OR');
    }

    /**
     * Specifies an ordering for the query results.
     * Replaces any previously specified orderings, if any.
     *
     * @param string $sort the ordering expression
     * @param string $order the ordering direction
     * @return $this
     */
    public function orderBy($sort, $order = 'ASC')
    {
        return $this->add('orderBy', $sort . ' ' . ($order ?: 'ASC'), false);
    }

    /**
     * Adds an ordering to the query results.
     *
     * @param string $sort the ordering expression
     * @param string $order the ordering direction
     * @return $this
     */
    public function addOrderBy($sort, $order = 'ASC')
    {
        return $this->add('orderBy', $sort . ' ' . ($order ?: 'ASC'), true);
    }

    /**
     * Adds a DESC ordering to the query
     *
     * @param string $field The name of field
     * @return $this
     */
    public function desc($field)
    {
        return $this->addOrderBy($field, 'DESC');
    }

    /**
     * Add an ASC ordering to the query
     *
     * @param string $field The name of field
     * @return $this
     */
    public function asc($field)
    {
        return $this->addOrderBy($field, 'ASC');
    }

    /**
     * Specifies a field to be the key of the fetched array
     *
     * @param string $field
     * @return $this
     */
    public function indexBy($field)
    {
        $this->data = $this->executeIndexBy($this->data, $field);
        $this->indexBy = $field;
        return $this;
    }

    /**
     * Returns a SQL query part by its name
     *
     * @param string $name The name of SQL part
     * @return mixed
     */
    public function getSqlPart($name)
    {
        return isset($this->sqlParts[$name]) ? $this->sqlParts[$name] : false;
    }

    /**
     * Get all SQL parts
     *
     * @return array $sqlParts
     */
    public function getSqlParts()
    {
        return $this->sqlParts;
    }

    /**
     * Reset all SQL parts
     *
     * @param array $name
     * @return $this
     */
    public function resetSqlParts($name = null)
    {
        if (null === $name) {
            $name = array_keys($this->sqlParts);
        }
        foreach ($name as $queryPartName) {
            $this->resetSqlPart($queryPartName);
        }
        return $this;
    }

    /**
     * Reset single SQL part
     *
     * @param string $name
     * @return $this
     */
    public function resetSqlPart($name)
    {
        $this->sqlParts[$name] = is_array($this->sqlParts[$name]) ? [] : null;
        $this->state = self::STATE_DIRTY;
        return $this;
    }

    /**
     * Sets a query parameter for the query being constructed
     *
     * @param string|int $key The parameter position or name
     * @param mixed $value The parameter value
     * @param string|null $type PDO::PARAM_*
     * @return $this
     */
    public function setParameter($key, $value, $type = null)
    {
        if (null !== $type) {
            $this->paramTypes[$key] = $type;
        }

        $this->params[$key] = $value;
        return $this;
    }

    /**
     * Gets a (previously set) query parameter of the query being constructed
     *
     * @param mixed $key The key (index or name) of the bound parameter
     * @return mixed The value of the bound parameter
     */
    public function getParameter($key)
    {
        return isset($this->params[$key]) ? $this->params[$key] : null;
    }

    /**
     * Sets a collection of query parameters for the query being constructed
     *
     * @param array $params The query parameters to set
     * @param array $types The query parameters types to set
     * @return $this
     */
    public function setParameters(array $params, array $types = [])
    {
        $this->paramTypes = $types;
        $this->params = $params;
        return $this;
    }

    /**
     * Gets all defined query parameters for the query being constructed.
     *
     * @return array the currently defined query parameters
     */
    public function getParameters()
    {
        return $this->params;
    }

    /**
     * Get the complete SQL string formed by the current specifications of this QueryBuilder
     *
     * @return string The sql query string
     */
    public function getSql()
    {
        if (null !== $this->sql && self::STATE_CLEAN === $this->state) {
            return $this->sql;
        }

        switch ($this->type) {
            case self::DELETE:
                $this->sql = $this->getSqlForDelete();
                break;

            case self::UPDATE:
                $this->sql = $this->getSqlForUpdate();
                break;

            case self::SELECT:
            default:
                $this->sql = $this->getSqlForSelect();
                break;
        }

        $this->state = self::STATE_CLEAN;

        return $this->sql;
    }

    /**
     * Check if the offset exists
     *
     * @param string $offset
     * @return bool
     */
    public function offsetExists($offset)
    {
        $this->loadData($offset);
        return isset($this->data[$offset]);
    }

    /**
     * Get the offset value
     *
     * @param string $offset
     * @return mixed
     */
    public function offsetGet($offset)
    {
        $this->loadData($offset);
        return $this->get($offset);
    }

    /**
     * Set the offset value
     *
     * @param string $offset
     * @param mixed $value
     */
    public function offsetSet($offset, $value)
    {
        $this->loadData($offset);
        $this->set($offset, $value);
    }

    /**
     * Unset the offset
     *
     * @param string $offset
     */
    public function offsetUnset($offset)
    {
        $this->loadData($offset);
        $this->remove($offset);
    }

    /**
     * Retrieve an array iterator
     *
     * @return \ArrayIterator
     */
    public function getIterator()
    {
        $this->loadData(0);
        return new \ArrayIterator($this->data);
    }

    /**
     * Filters elements of the collection using a callback function
     *
     * @param \Closure $fn
     * @return $this
     */
    public function filter(\Closure $fn)
    {
        $data = array_filter($this->data, $fn);
        $records = $this->db->init($this->table, [], $this->isNew);
        $records->data = $data;
        $records->isColl = true;
        $records->loaded = $this->loaded;
        return $records;
    }

    /**
     * Set or remove cache time for the query
     *
     * @param int|false|null $seconds
     * @return $this
     */
    public function cache($seconds = null)
    {
        if (null === $seconds) {
            $this->cacheTime = $this->defaultCacheTime;
        } elseif (false === $seconds) {
            $this->cacheTime = false;
        } else {
            $this->cacheTime = (int) $seconds;
        }
        return $this;
    }

    /**
     * Set or remove cache tags
     *
     * @param array|false|null $tags
     * @return $this
     */
    public function tags($tags = null)
    {
        $this->cacheTags = false === $tags ? false : $tags;
        return $this;
    }

    /**
     * Set cache key
     *
     * @param string $cacheKey
     * @return $this
     */
    public function setCacheKey($cacheKey)
    {
        $this->cacheKey = $cacheKey;
        return $this;
    }

    /**
     * Generate cache key form query and params
     *
     * @return string
     */
    public function getCacheKey()
    {
        return $this->cacheKey ?: md5(
            $this->db->getDbname()
            . $this->getSql()
            . serialize($this->params)
            . serialize($this->paramTypes)
        );
    }

    /**
     * @return $this
     */
    public function forUpdate()
    {
        return $this->lock(true);
    }

    /**
     * @return $this
     */
    public function forShare()
    {
        return $this->lock(false);
    }

    /**
     * @param string $lock
     * @return $this
     */
    public function lock($lock)
    {
        $this->lock = $lock;

        return $this;
    }

    /**
     * The method called after load a record
     */
    public function afterLoad()
    {
    }

    /**
     * The method called after find a record
     */
    public function afterFind()
    {
    }

    /**
     * The method called before save a record
     */
    public function beforeSave()
    {
    }

    /**
     * The method called after save a record
     */
    public function afterSave()
    {
    }

    /**
     * The method called before insert a record
     */
    public function beforeCreate()
    {
    }

    /**
     * The method called after insert a record
     */
    public function afterCreate()
    {
    }

    /**
     * The method called before update a record
     */
    public function beforeUpdate()
    {
    }

    /**
     * The method called after update a record
     */
    public function afterUpdate()
    {
    }

    /**
     * The method called before delete a record
     */
    public function beforeDestroy()
    {
    }

    /**
     * The method called after delete a record
     */
    public function afterDestroy()
    {
    }

    protected function executeDestroy()
    {
        $this->db->delete($this->table, [$this->primaryKey => $this->data[$this->primaryKey]]);
    }

    /**
     * @return mixed
     */
    protected function fetchFromCache()
    {
        $cache = false === $this->cacheTags ? $this->cache : $this->tagCache($this->cacheTags ?: $this->getCacheTags());
        $params = $this->params;
        $paramTypes = $this->paramTypes;
        return $cache->remember($this->getCacheKey(), $this->cacheTime, function () use ($params, $paramTypes) {
            return $this->db->fetchAll($this->getSql(), $params, $paramTypes);
        });
    }

    /**
     * @param array $data
     * @param string $field
     * @return array
     */
    protected function executeIndexBy($data, $field)
    {
        if (!$data) {
            return $data;
        }

        $newData = [];
        foreach ($data as $row) {
            $newData[$row[$field]] = $row;
        }
        return $newData;
    }

    /**
     * Converts this instance into an SELECT string in SQL
     *
     * @param bool $count
     * @return string
     */
    protected function getSqlForSelect($count = false)
    {
        $parts = $this->sqlParts;

        if (!$parts['select']) {
            $parts['select'] = ['*'];
        }

        $query = 'SELECT ' . implode(', ', $parts['select']) . ' FROM ' . $this->getFrom();

        // JOIN
        foreach ($parts['join'] as $join) {
            $query .= ' ' . strtoupper($join['type'])
                . ' JOIN ' . $join['table']
                . ' ON ' . $join['on'];
        }

        $query .= (null !== $parts['where'] ? ' WHERE ' . ((string) $parts['where']) : '')
            . ($parts['groupBy'] ? ' GROUP BY ' . implode(', ', $parts['groupBy']) : '')
            . (null !== $parts['having'] ? ' HAVING ' . ((string) $parts['having']) : '');

        if (false === $count) {
            $query .= ($parts['orderBy'] ? ' ORDER BY ' . implode(', ', $parts['orderBy']) : '')
                . (null !== $parts['limit'] ? ' LIMIT ' . $parts['limit'] : '')
                . (null !== $parts['offset'] ? ' OFFSET ' . $parts['offset'] : '');
        }

        $query .= $this->generateLockSql();

        return $query;
    }

    /**
     * Converts this instance into an SELECT COUNT string in SQL
     */
    protected function getSqlForCount()
    {
        return 'SELECT COUNT(*) FROM (' . $this->getSqlForSelect(true) . ') wei_count';
    }

    /**
     * Converts this instance into an UPDATE string in SQL.
     *
     * @return string
     */
    protected function getSqlForUpdate()
    {
        $query = 'UPDATE ' . $this->getFrom()
            . ' SET ' . implode(', ', $this->sqlParts['set'])
            . (null !== $this->sqlParts['where'] ? ' WHERE ' . ((string) $this->sqlParts['where']) : '');
        return $query;
    }

    /**
     * Converts this instance into a DELETE string in SQL.
     *
     * @return string
     */
    protected function getSqlForDelete()
    {
        return 'DELETE FROM '
            . $this->getFrom()
            . (null !== $this->sqlParts['where'] ? ' WHERE ' . ((string) $this->sqlParts['where']) : '');
    }

    /**
     * Returns the from SQL part
     *
     * @return string
     */
    protected function getFrom()
    {
        if (!$this->sqlParts['from']) {
            $this->from($this->table);
        }
        return $this->sqlParts['from'];
    }

    /**
     * Either appends to or replaces a single, generic query part.
     *
     * The available parts are: 'select', 'from', 'set', 'where',
     * 'groupBy', 'having', 'orderBy', 'limit' and 'offset'.
     *
     * @param string $sqlPartName
     * @param string $sqlPart
     * @param bool $append
     * @param string $type
     * @return $this
     */
    protected function add($sqlPartName, $sqlPart, $append = false, $type = null)
    {
        $this->isNew = false;

        if (!$sqlPart) {
            return $this;
        }

        $isArray = is_array($sqlPart);
        $isMultiple = is_array($this->sqlParts[$sqlPartName]);

        if ($isMultiple && !$isArray) {
            $sqlPart = [$sqlPart];
        }

        $this->state = self::STATE_DIRTY;

        if ($append) {
            if ('where' == $sqlPartName || 'having' == $sqlPartName) {
                if ($this->sqlParts[$sqlPartName]) {
                    $this->sqlParts[$sqlPartName] = '(' . $this->sqlParts[$sqlPartName] . ') '
                        . $type . ' (' . $sqlPart . ')';
                } else {
                    $this->sqlParts[$sqlPartName] = $sqlPart;
                }
            } elseif (in_array($sqlPartName, ['orderBy', 'groupBy', 'select', 'set'], true)) {
                foreach ($sqlPart as $part) {
                    $this->sqlParts[$sqlPartName][] = $part;
                }
            } elseif ($isMultiple) {
                $this->sqlParts[$sqlPartName][] = $sqlPart;
            }
            return $this;
        }

        $this->sqlParts[$sqlPartName] = $sqlPart;
        return $this;
    }

    /**
     * Generate condition string for WHERE or Having statement
     *
     * @param mixed $conditions
     * @param array $params
     * @param array $types
     * @return string
     */
    protected function processCondition($conditions, $params, $types)
    {
        // Regard numeric and null as primary key value
        if (is_numeric($conditions) || empty($conditions)) {
            $conditions = [$this->primaryKey => $conditions];
        }

        if (is_array($conditions)) {
            $where = [];
            $params = [];
            foreach ($conditions as $field => $condition) {
                if (is_array($condition)) {
                    $where[] = $field . ' IN (' . implode(', ', array_pad([], count($condition), '?')) . ')';
                    $params = array_merge($params, $condition);
                } else {
                    $where[] = $field . ' = ?';
                    $params[] = $condition;
                }
            }
            $conditions = implode(' AND ', $where);
        }

        if (false !== $params) {
            if (is_array($params)) {
                $this->params = array_merge($this->params, $params);
                $this->paramTypes = array_merge($this->paramTypes, $types);
            } else {
                $this->params[] = $params;
                if ($types) {
                    $this->paramTypes[] = $types;
                }
            }
        }

        return $conditions;
    }

    /**
     * Load record by array offset
     *
     * @param int|string $offset
     */
    protected function loadData($offset)
    {
        if (!$this->loaded && !$this->isNew) {
            if (is_numeric($offset) || null === $offset) {
                $this->findAll();
            } else {
                $this->find();
            }
        }
    }

    /**
     * @return array
     */
    protected function getCacheTags()
    {
        $tags[] = $this->getFrom();
        foreach ($this->sqlParts['join'] as $join) {
            $tags[] = $join['table'];
        }
        return $tags;
    }

    /**
     * Trigger a callback
     *
     * @param string $name
     */
    protected function triggerCallback($name)
    {
        $this->{$name}();
    }

    /**
     * @return string
     */
    protected function generateLockSql()
    {
        if ('' === $this->lock) {
            return '';
        }

        if (is_string($this->lock)) {
            return ' ' . $this->lock;
        }

        if ($this->lock) {
            return ' FOR UPDATE';
        } else {
            return ' LOCK IN SHARE MODE';
        }
    }
}


text:
import mock
import pytest
from requests import HTTPError

from f5.bigip import BigIP
from f5.bigip.resource import KindTypeMismatch
from f5.bigip.resource import MissingRequiredCreationParameter
from f5.bigip.resource import MissingRequiredReadParameter
from f5.bigip.resource import URICreationCollision
from f5.bigip.tm.sys.application import Aplscript
from f5.bigip.tm.sys.application import Customstat
from f5.bigip.tm.sys.application import Service
from f5.bigip.tm.sys.application import Template

KIND_MISMATCH = {
    "kind": "tm:sys:application:service:servicecollectionstate",
    "name": "tt_serv",
    "partition": "Common",
    "subPath": "tt_serv.app",
    "selfLink": "https://localhost/mgmt/tm/sys/application/service/' \
        '~Common~tt_serv.app~tt_serv?ver=11.6.0",
    "template": "/Common/tt"
}

SUCCESSFUL_CREATE = {
    "kind": "tm:sys:application:service:servicestate",
    "name": "test_service",
    "partition": "Common",
    "subPath": "tt_serv.app",
    "selfLink": "https://localhost/mgmt/tm/sys/application/service/' \
        '~Common~tt_serv.app~tt_serv?ver=11.6.0",
    "template": "test_template"
}

TRUE_INHERITED_DEVGROUP = {
    "kind": "tm:sys:application:service:servicestate",
    "name": "test_service",
    "partition": "Common",
    "inheritedDevicegroup": "true",
    "deviceGroup": "test_dev_group",
    "subPath": "tt_serv.app",
    "selfLink": "https://localhost/mgmt/tm/sys/application/service/' \
        '~Common~tt_serv.app~tt_serv?ver=11.6.0",
    "template": "test_template"
}

FALSE_INHERITED_DEVGROUP = {
    "kind": "tm:sys:application:service:servicestate",
    "name": "test_service",
    "partition": "Common",
    "inheritedDevicegroup": "false",
    "subPath": "tt_serv.app",
    "selfLink": "https://localhost/mgmt/tm/sys/application/service/' \
        '~Common~tt_serv.app~tt_serv?ver=11.6.0",
    "template": "test_template"
}

SIDE_EFFECT = {'only_key': 'this is the only key'}

@pytest.fixture
def FakeService():
    fake_serv_s = mock.MagicMock()
    return Service(fake_serv_s)

@pytest.fixture
def FakeTemplate():
    fake_templ_s = mock.MagicMock()
    return Template(fake_templ_s)

@pytest.fixture
def FakeAplscript():
    fake_apl_s = mock.MagicMock()
    return Aplscript(fake_apl_s)

@pytest.fixture
def FakeCustomstat():
    fake_custom_stat_s = mock.MagicMock()
    return Customstat(fake_custom_stat_s)

@pytest.fixture
@mock.patch('f5.bigip')
def MakeFakeContainer(FakeService, mock_json, mock_bigip):
    mock_session = mock.MagicMock(name='mock_session')
    mock_get_response = mock.MagicMock(name='mock_get_response')
    mock_put_response = mock.MagicMock(name='mock_put_response')
    mock_get_response.json.return_value = mock_json.copy()
    mock_put_response.json.return_value = SUCCESSFUL_CREATE.copy()
    # Mock the get and put when the container calls icr_session.get/put
    mock_session.get.return_value = mock_get_response
    mock_session.put.return_value = mock_put_response
    mock_bigip._meta_data = {
        'hostname': 'testhost',
        'icr_session': mock_session,
        'uri': '',
        'icontrol_version': ''
    }
    FakeService._meta_data['bigip'] = mock_bigip
    FakeService._meta_data['icontrol_version'] = ''
    return FakeService

@pytest.fixture
@mock.patch('f5.bigip')
def MakeFakeContainerRaise(FakeService, mock_json, side_effect, mock_bigip):
    mock_session = mock.MagicMock(name='mock_session')
    mock_get_response = mock.MagicMock(name='mock_get_response')
    mock_get_response.json.return_value = mock_json.copy()
    mock_session.get.side_effect = side_effect
    mock_bigip._meta_data = {
        'hostname': 'testhost',
        'icr_session': mock_session,
        'uri': '',
        'icontrol_version': ''
    }
    FakeService._meta_data['bigip'] = mock_bigip
    mock_base_uri = mock.MagicMock()
    mock_base_uri._meta_data = {'uri': 'base_uri'}
    FakeService._meta_data['container'] = mock_base_uri
    FakeService._meta_data['icontrol_version'] = ''
    return FakeService

@pytest.fixture
def SideEffectFixture():
    # Let's show that fixture side-effects can cause test interactions
    # that are surprising to the untrained eye.
    SIDE_EFFECT['new_key'] = 'Added new key to module variable.'

class MockHTTPError(HTTPError):
    def __init__(self, response_obj):
        self.response = response_obj

class MockHTTPErrorResponseSuccessful(HTTPError):
    def __init__(self):
        self.text = 'The configuration was updated successfully but could not' \
            ' be retrieved'

class MockHTTPErrorResponse404(HTTPError):
    def __init__(self):
        self.text = 'Something else happened.'
        self.status_code = 404

class MockHTTPErrorResponse400(HTTPError):
    def __init__(self):
        self.status_code = 400

class TestServiceCreate(object):
    def test_create_two(self):
        b = BigIP('192.168.1.1', 'admin', 'admin')
        serv1 = b.sys.applications.services.service
        serv2 = b.sys.applications.services.service
        assert serv1 is not serv2

    def test_create_no_args(self, FakeService):
        with pytest.raises(MissingRequiredCreationParameter) as ex:
            FakeService.create()
        assert 'name' in ex.value.message
        assert 'template' in ex.value.message
        assert 'partition' in ex.value.message

    def test_create_no_template(self, FakeService):
        with pytest.raises(MissingRequiredCreationParameter) as ex:
            FakeService.create(name='test_service')
        assert 'template' in ex.value.message

    def test_create_no_partition(self, FakeService):
        with pytest.raises(MissingRequiredCreationParameter) as ex:
            FakeService.create(name='test_service', template='test_template')
        assert 'partition' in ex.value.message

    def test_create_uri_collision(self, FakeService):
        FakeService._meta_data = {'uri': 'already_defined'}
        with pytest.raises(URICreationCollision) as ex:
            FakeService.create(fakeuri='FAKEURI')
        assert "There was an attempt to assign a new uri to this resource, " \
            "the _meta_data['uri'] is already_defined and it should not be " \
            "changed." in ex.value.message

    def test_create_http_error_not_successful(self):
        with mock.patch(target='f5.bigip.resource.Resource._create') as \
                mock_create:
            mock_create.side_effect = MockHTTPError(
                MockHTTPErrorResponse404()
            )
            sv1 = Service(mock.MagicMock())
            with pytest.raises(HTTPError):
                sv1.create()
                assert sv1 is None

    def test_create_kindtype_mismatch(self, FakeService):
        FakeService = MakeFakeContainer(FakeService, KIND_MISMATCH)
        with mock.patch(target='f5.bigip.resource.Resource._create') as \
                mock_create:
            mock_create.side_effect = MockHTTPError(
                MockHTTPErrorResponseSuccessful()
            )
            with pytest.raises(KindTypeMismatch):
                FakeService.create(
                    name='test_server', template='test_template'
                )

    def test_create_success(self, FakeService):
        FakeService = MakeFakeContainer(FakeService, SUCCESSFUL_CREATE)
        with mock.patch(target='f5.bigip.resource.Resource._create') as \
                mock_create:
            mock_create.side_effect = MockHTTPError(
                MockHTTPErrorResponseSuccessful()
            )
            sv1 = FakeService.create(
                name='test_service',
                template='test_template'
            )
            assert sv1 is not None
            assert sv1.name == 'test_service'
            assert sv1.template == 'test_template'

class TestServiceExists(object):
    def test_exists(self, FakeService):
        FakeService = MakeFakeContainer(FakeService, {})
        assert FakeService.exists(name='test', partition='test') is True

    def test_exists_failure(self, FakeService):
        FakeService = MakeFakeContainerRaise(FakeService, {}, Exception())
        with pytest.raises(Exception):
            FakeService.exists(name='test', partition='test')
        assert FakeService._meta_data['bigip']._meta_data['icr_session'].get.\
            call_args == mock.call(
                'base_uri~test~test.app~test',
                uri_as_parts=False
            )

    def test_exists_false(self, FakeService):
        FakeService = MakeFakeContainerRaise(
            FakeService,
            {},
            MockHTTPError(MockHTTPErrorResponse404())
        )
        assert FakeService.exists(name='test', partition='test') is False

    def test_exists_http_error_raise(self, FakeService):
        FakeService = MakeFakeContainerRaise(
            FakeService,
            {},
            MockHTTPError(MockHTTPErrorResponse400())
        )
        with pytest.raises(HTTPError):
            FakeService.exists(name='test', partition='test')

class TestServiceLoad(object):
    def test_load_no_args(self, FakeService):
        with pytest.raises(MissingRequiredReadParameter) as ex:
            FakeService.load()
        assert ex.value.message == \
            "Missing required params: set(['partition', 'name'])"

    def test_load_no_partition(self, FakeService):
        with pytest.raises(MissingRequiredReadParameter) as ex:
            FakeService.load(name='test_service')
        assert ex.value.message == \
            "Missing required params: set(['partition'])"

class TestServiceUpdate(object):
    def test_update_inherit_tg_true(self, FakeService):
        FakeService = MakeFakeContainer(FakeService, TRUE_INHERITED_DEVGROUP)
        with mock.patch(target='f5.bigip.resource.Resource._create') as \
                mock_create:
            mock_create.side_effect = MockHTTPError(
                MockHTTPErrorResponseSuccessful()
            )
            sv1 = FakeService.create(
                name='test_service',
                template='test_template'
            )
            sv1.update()
            assert hasattr(sv1, 'deviceGroup') is False

    def test_update_inherit_tg_false(self, FakeService):
        FakeService = MakeFakeContainer(FakeService, FALSE_INHERITED_DEVGROUP)
        with mock.patch(target='f5.bigip.resource.Resource._create') as \
                mock_create:
            mock_create.side_effect = MockHTTPError(
                MockHTTPErrorResponseSuccessful()
            )
            sv1 = FakeService.create(
                name='test_service',
                template='test_template'
            )
            sv1.update()
            # Since the SUCCESSFUL_CREATE dictionary is the result of the
            # update, the inheritedDevicegroup and deviceGroup should not
            # be there.
            assert hasattr(sv1, 'deviceGroup') is False
            assert hasattr(sv1, 'inheritedDevicegroup') is False

class TestTemplateCreate(object):
    def test_create_two(self):
        b = BigIP('192.168.1.1', 'admin', 'admin')
        templ1 = b.sys.applications.templates.template
        templ2 = b.sys.applications.templates.template
        assert templ1 is not templ2

    def test_create_no_args(self, FakeTemplate):
        with pytest.raises(MissingRequiredCreationParameter) as ex:
            FakeTemplate.create()
        assert 'name' in ex.value.message
        assert 'partition' in ex.value.message

class TestAplscript(object):
    def test_create_two(self):
        b = BigIP('192.168.1.1', 'admin', 'admin')
        templ1 = b.sys.applications.aplscripts.aplscript
        templ2 = b.sys.applications.aplscripts.aplscript
        assert templ1 is not templ2

    def test_create_no_args(self, FakeAplscript):
        with pytest.raises(MissingRequiredCreationParameter) as ex:
            FakeAplscript.create()
        assert 'name' in ex.value.message

class TestCustomstat(object):
    def test_create_two(self):
        b = BigIP('192.168.1.1', 'admin', 'admin')
        templ1 = b.sys.applications.customstats.customstat
        templ2 = b.sys.applications.customstats.customstat
        assert templ1 is not templ2

    def test_create_no_args(self, FakeCustomstat):
        with pytest.raises(MissingRequiredCreationParameter) as ex:
            FakeCustomstat.create()
        assert 'name' in ex.value.message

def test_setup_side_effect_in_fixture(SideEffectFixture):
    # Show the module dict has the new key while this fixture is in use.
    assert 'new_key' in SIDE_EFFECT

def test_side_effect_from_fixture():
    # Show the added key from the previous fixture is still there
    assert 'new_key' in SIDE_EFFECT


text:
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace vtortola.Redis
{
    internal sealed class PingCommanderOperation : ICommandOperation
    {
        static readonly RESPCommand[] _ping = new [] { new RESPCommand(new RESPCommandLiteral("PING"), false) };
        public Boolean IsCompleted { get; private set; }

        public IEnumerable<RESPCommand> Execute()
        {
            return _ping;
        }

        public void HandleResponse(RESPObject response)
        {
            Contract.Assert(response.ToString() == "PONG", "PingCommanderOperation handler trying to work out a non-ping response. ");

            IsCompleted = true;
        }
    }
}


text:
package com.albedinsky.android.dialog.view;

import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;

import com.albedinsky.android.ui.widget.LinearProgressBar;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
 * Interface specifying API layer for a view that can be used as content view for {@link com.albedinsky.android.dialog.ProgressDialog ProgressDialog}
 * to ensure proper working of binding process of the content view for such a dialog.
 *

 * See default {@link com.albedinsky.android.dialog.widget.DialogProgressContent implementation}
 * for more info.
 *
 * @author Martin Albedinsky
 */
public interface ProgressDialogView extends DialogView {

    /**
     * Interface ===================================================================================
     */

    /**
     * Formatter that can be used to supply custom formatting logic of progress value for implementation
     * of {@link ProgressDialogView}.
     *
     * @author Martin Albedinsky
     * @see #setProgressFormatter(ProgressDialogView.ProgressFormatter)
     */
    interface ProgressFormatter {

        /**
         * Formats the given set of progress values.
         *
         * @param progress The desired progress values to format.
         * @return Formatted progress.
         */
        @NonNull
        CharSequence formatProgress(@NonNull int... progress);
    }

    /**
     * Formatter that can be used to supply custom formatting logic of progress time value for
     * implementation of {@link ProgressDialogView}.
     *
     * @author Martin Albedinsky
     * @see #setTimeFormatter(ProgressDialogView.TimeFormatter)
     */
    interface TimeFormatter {

        /**
         * Formats the given time value.
         *
         * @param time The desired time to format.
         * @return Formatted time.
         */
        @NonNull
        CharSequence formatTime(long time);
    }

    /**
     * Constants ===================================================================================
     */

    /**
     * Defines an annotation for determining set of allowed modes for {@link #setProgressMode(int)}
     * method.
     */
    @Retention(RetentionPolicy.SOURCE)
    @IntDef({
            MODE_DETERMINATE,
            MODE_INDETERMINATE,
            MODE_QUERY_INDETERMINATE_DETERMINATE,
            MODE_BUFFER
    })
    public @interface Mode {
    }

    /**
     * Flag copied from {@link LinearProgressBar#MODE_DETERMINATE}.
     */
    int MODE_DETERMINATE = LinearProgressBar.MODE_DETERMINATE;

    /**
     * Flag copied from {@link LinearProgressBar#MODE_INDETERMINATE}.
     */
    int MODE_INDETERMINATE = LinearProgressBar.MODE_INDETERMINATE;

    /**
     * Flag copied from {@link LinearProgressBar#MODE_BUFFER}.
     */
    int MODE_BUFFER = LinearProgressBar.MODE_BUFFER;

    /**
     * Flag copied from {@link LinearProgressBar#MODE_QUERY_INDETERMINATE_DETERMINATE}.
     */
    int MODE_QUERY_INDETERMINATE_DETERMINATE = LinearProgressBar.MODE_QUERY_INDETERMINATE_DETERMINATE;

    /**
     * Defines an annotation for determining set of allowed flags for {@link #setProgressIndicator(int)}
     * method.
     */
    @Retention(RetentionPolicy.SOURCE)
    @IntDef(flag = true, value = {INDICATOR_NONE, INDICATOR_PROGRESS, INDICATOR_TIME})
    public @interface Indicator {
    }

    /**
     * Indicator flag for {@link #setProgressIndicator(int)}. Use this to not show any indicator within
     * progress dialog view.
     */
    int INDICATOR_NONE = 0x00;

    /**
     * Indicator flag for {@link #setProgressIndicator(int)}. Use this to show indicator which presents
     * the current progress value.
     */
    int INDICATOR_PROGRESS = 0x01;

    /**
     * Indicator flag for {@link #setProgressIndicator(int)}. Use this to show indicator which presents
     * the current progress time value.
     */
    int INDICATOR_TIME = 0x02;

    /**
     * Methods =====================================================================================
     */

    /**
     * Sets a mode for {@link LinearProgressBar} determining how should be the progress graphics
     * presented in this dialog view.
     *
     * @param mode The desired mode. One of {@link #MODE_DETERMINATE}, {@link #MODE_INDETERMINATE},
     *             {@link #MODE_BUFFER} or {@link #MODE_QUERY_INDETERMINATE_DETERMINATE}.
     */
    void setProgressMode(@Mode int mode);

    /**
     * Returns the progress mode specified for this dialog view.
     *

     * Default value: {@link #MODE_DETERMINATE}
     *
     * @return One of {@link #MODE_DETERMINATE}, {@link #MODE_INDETERMINATE}, {@link #MODE_BUFFER}
     * or {@link #MODE_QUERY_INDETERMINATE_DETERMINATE}.
     */
    @Mode
    int getProgressMode();

    /**
     * Sets a progress indicator flags for this dialog view.
     *
     * @param indicator The desired indicator flags to determine which indicators to show within
     *                  this progress dialog view. One of {@link #INDICATOR_PROGRESS}, {@link #INDICATOR_TIME}
     *                  or theirs combination or {@link #INDICATOR_NONE} to not show any indicator.
     * @see #getProgressIndicator()
     */
    void setProgressIndicator(@Indicator int indicator);

    /**
     * Returns the current progress indicator flags.
     *

     * Default value: {@link ProgressDialogView#INDICATOR_PROGRESS} | {@link ProgressDialogView#INDICATOR_TIME}
     *
     * @return One of {@link #INDICATOR_PROGRESS}, {@link #INDICATOR_TIME} or theirs combination or
     * {@link #INDICATOR_NONE} if no indicator should be displayed.
     * @see #setProgressIndicator(int)
     */
    @Indicator
    int getProgressIndicator();

    /**
     * Same as {@link #setProgressFormat(String)} for resource id.
     *
     * @param resId Resource id of the desired format.
     * @see #getProgressFormat()
     */
    void setProgressFormat(@StringRes int resId);

    /**
     * Sets the format used when formatting progress values.
     *
     * @param format The desired format for progress.
     * @see #getProgressFormat()
     * @see #setProgressFormatter(ProgressFormatter)
     */
    void setProgressFormat(@NonNull String format);

    /**
     * Returns the current progress format.
     *
     * @return Format for progress values.
     * @see #setProgressFormat(int)
     * @see #setProgressFormat(String)
     */
    @NonNull
    String getProgressFormat();

    /**
     * Sets a formatter used to format progress values.
     *
     * @param formatter The desired formatter.
     * @see #getProgressFormatter()
     * @see #setProgressFormat(String)
     */
    void setProgressFormatter(@NonNull ProgressFormatter formatter);

    /**
     * Returns the current progress formatter.
     *
     * @return Formatter for progress values.
     * @see #setProgressFormatter(ProgressFormatter)
     */
    @NonNull
    ProgressFormatter getProgressFormatter();

    /**
     * Sets the current progress for this dialog view.
     *

     * Note, that if {@link #INDICATOR_TIME} flag has been requested and this method is called
     * for the first time, this will start counting of the progress time. Progress time can be later
     * paused ({@link #pauseTime()}) and resumed ({@link #resumeTime()}). Counting stops when the
     * associated dialog is dismissed.
     *
     * @param progress The desired progress values.
     * @see #getProgress()
     */
    void setProgress(@NonNull int... progress);

    /**
     * Returns the current progress of this dialog view.
     *
     * @return Current progress values.
     * @see #setProgress(int...)
     */
    @NonNull
    int[] getProgress();

    /**
     * Same as {@link #setTimeFormat(String)} for resource id.
     *
     * @param resId Resource id of the desired format.
     * @see #getTimeFormat()
     */
    void setTimeFormat(@StringRes int resId);

    /**
     * Sets the format used when formatting current progress time.
     *
     * @param format The desired format for progress time.
     * @see #getTimeFormat()
     * @see #setTimeFormatter(TimeFormatter)
     */
    void setTimeFormat(@NonNull String format);

    /**
     * Returns the current progress time format.
     *
     * @return Format for progress time.
     * @see #setTimeFormat(int)
     * @see #setTimeFormat(String)
     */
    @NonNull
    String getTimeFormat();

    /**
     * Sets a formatter used to format progress time.
     *
     * @param formatter The desired formatter.
     * @see #getTimeFormatter()
     * @see #setTimeFormat(String)
     */
    void setTimeFormatter(@NonNull TimeFormatter formatter);

    /**
     * Returns the current time formatter.
     *
     * @return Formatter for progress time value.
     * @see #setTimeFormatter(TimeFormatter)
     */
    @NonNull
    TimeFormatter getTimeFormatter();

    /**
     * Sets an interval that determines how often the progress time should be updated.
     *
     * @param interval The desired update interval in milliseconds.
     * @see #getTimeUpdateInterval()
     */
    void setTimeUpdateInterval(long interval);

    /**
     * Returns the update interval for progress time.
     *

     * Default value: 1 000 millis
     *
     * @return Update interval in milliseconds
     * @see #setTimeUpdateInterval(long) .
     */
    long getTimeUpdateInterval();

    /**
     * Pauses counting of the progress time.
     *
     * @see #resumeTime()
     */
    void pauseTime();

    /**
     * Resumes counting of the progress time.
     *
     * @see #pauseTime()
     */
    void resumeTime();

    /**
     * Returns the current progress time in milliseconds.
     *
     * @return Progress time or {@code -1} if there was no progress time counted yet.
     */
    long getTime();

    /**
     * Same as {@link #setContent(CharSequence)} for resource id.
     *
     * @param resId Resource id of the desired content text.
     * @see #getContent()
     */
    void setContent(@StringRes int resId);

    /**
     * Sets a content text for this dialog view.
     *
     * @param text The desired content text. May be {@code null} to clear the current one.
     * @see #getContent()
     */
    void setContent(@Nullable CharSequence text);

    /**
     * Returns the current content text presented by this dialog view.
     *
     * @return Current content text.
     * @see #setContent(int)
     * @see #setContent(CharSequence)
     */
    @NonNull
    CharSequence getContent();
}


text:
package com.adobe.acs.commons.quickly.results.impl.lists;

import com.adobe.acs.commons.quickly.results.Result;
import org.apache.commons.lang.StringUtils;
import org.apache.sling.api.resource.ResourceResolver;

import java.util.ArrayList;
import java.util.List;

public abstract class AbstractAccessibleResults {

    public final List<Result> getResults(final ResourceResolver resourceResolver) {
        List<Result> results = new ArrayList<Result>();

        for(Result result : getResults()) {
            if(StringUtils.isNotBlank(result.getPath())) {
                results.add(result);
            } else if (resourceResolver.resolve(result.getPath()) != null) {
                results.add(result);
            }
        }

        return results;
    }

    public abstract List<Result> getResults();
}


text:
class EventsController < ApplicationController
  caches_page :index, :show

  if Forge::Settings[:events][:display] == 'calendar'
    helper LaterDude::CalendarHelper
  end

  def index
    @page_title = 'Listing Events'

    if Forge::Settings[:events][:display] == 'calendar'
      now = Time.now

      @year = (params[:year] || now.year).to_i
      @month = (params[:month] || now.month).to_i

      template = 'events/index_calendar'
    else
      # this roundabout sorting is necessary because ruby 1.8
      # doesn't preserve insertion order - sorting and then using
      # group_by doesn't guarantee the items will remain in that order
      @events = Event\
        .published\
        .order('starts_at DESC')\
        .group_by { |e| e.starts_at.strftime('%Y/%m') }\
        .sort_by(&:first)\
        .reverse

      template = 'events/index_list'
    end

    respond_to do |format|
      format.html { render :template => template }
      format.mobile { render :template => 'mobile/events' }
    end
  end

  def show
    @event = Event.find_by_id!(params[:id])
    @page_title = @event.title

    respond_to do |format|
      format.html
      format.mobile { render :template => 'mobile/event' }
    end
  end
end


text:
<?php

/**
 * ArticleTranslation form base class.
 *
 * @method ArticleTranslation getObject() Returns the current form's model object
 *
 * @package    Acme
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrineFormGeneratedTemplate.php 29553 2010-05-20 14:33:00Z Kris.Wallsmith $
 */
abstract class BaseArticleTranslationForm extends BaseFormDoctrine
{
  public function setup()
  {
    $this->setWidgets(array(
      'id'         => new sfWidgetFormInputHidden(),
      'title'      => new sfWidgetFormInputText(),
      'extract'    => new sfWidgetFormTextarea(),
      'body'       => new sfWidgetFormTextarea(),
      'is_active'  => new sfWidgetFormInputCheckbox(),
      'lang'       => new sfWidgetFormInputHidden(),
      'created_at' => new sfWidgetFormDateTime(),
      'updated_at' => new sfWidgetFormDateTime(),
      'version'    => new sfWidgetFormInputText(),
    ));

    $this->setValidators(array(
      'id'         => new sfValidatorChoice(array('choices' => array($this->getObject()->get('id')), 'empty_value' => $this->getObject()->get('id'), 'required' => false)),
      'title'      => new sfValidatorString(array('max_length' => 120)),
      'extract'    => new sfValidatorString(array('max_length' => 2000)),
      'body'       => new sfValidatorString(array('required' => false)),
      'is_active'  => new sfValidatorBoolean(array('required' => false)),
      'lang'       => new sfValidatorChoice(array('choices' => array($this->getObject()->get('lang')), 'empty_value' => $this->getObject()->get('lang'), 'required' => false)),
      'created_at' => new sfValidatorDateTime(),
      'updated_at' => new sfValidatorDateTime(),
      'version'    => new sfValidatorInteger(array('required' => false)),
    ));

    $this->widgetSchema->setNameFormat('article_translation[%s]');

    $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);

    $this->setupInheritance();

    parent::setup();
  }

  public function getModelName()
  {
    return 'ArticleTranslation';
  }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="1dp"
    android:background="#FFFFFF"
    android:weightSum="2">

    <TextView
        android:id="@+id/meaning"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:layout_weight="1"
        android:text="kalemah"
        android:textAlignment="center"
        android:textSize="25sp" />

    <TextView
        android:id="@+id/word"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:layout_weight="1"
        android:text="meaining"
        android:textAlignment="center"
        android:textSize="25sp" />

</LinearLayout>


text:
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;

fn main() {
    let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());

    let memory_x = include_bytes!("memory.x.in");
    let mut f = File::create(out_dir.join("memory.x")).unwrap();
    f.write_all(memory_x).unwrap();

    println!("cargo:rustc-link-search={}", out_dir.display());
}


text:
import test from 'ava';
import * as Nodes from '../../nodes/index';
import compile from '../helpers/compile';

test('should compile an or node', async t => {
  const ast = new Nodes.Or(0, 0, {
    left: new Nodes.Literal(0, 0, { value: 1 }),
    right: new Nodes.Literal(0, 0, { value: 'foobar' })
  });
  t.is(await compile(ast), '1 || \'foobar\'');
});


text:
require File.dirname(__FILE__) + '/../spec_helper'

describe OpenidProfilesController do
  describe "handling GET /members/1/openid_profiles/1" do
    it_should_behave_like "A Registered Member"
    before(:each) do
      @openid_profile = mock_openid_profile
      @member.openid_profiles.stub!(:find).and_return(@openid_profile)
    end

    def do_get
      get :show, :id => "1"
    end

    it "should be successful" do
      do_get
      response.should be_success
    end

    it "should render show template" do
      do_get
      response.should render_template('show')
    end

    it "should find the openids requested" do
      @member.openid_profiles.should_receive(:find).with("1").and_return(@openid_profile)
      do_get
    end

    it "should assign the found openids for the view" do
      do_get
      assigns[:openid_profile].should equal(@openid_profile)
    end
  end

  describe "handling GET /members/1/openid_profiles/new" do
    it_should_behave_like "A Registered Member"
    before(:each) do
      @openid_profile = mock_openid_profile
      @member.openid_profiles.stub!(:build).and_return(@openid_profile)
    end

    def do_get
      get :new
    end

    it "should be successful" do
      do_get
      response.should be_success
    end

    it "should render new template" do
      do_get
      response.should render_template('new')
    end

    it "should create an new openid_profile" do
      @member.openid_profiles.stub!(:build).and_return(@openid_profile)
      do_get
    end

    it "should assign the new openid_profile for the view" do
      do_get
      assigns[:openid_profile].should equal(@openid_profile)
    end
  end

  describe "handling POST /openid_profiles" do
    it_should_behave_like "A Registered Member"
    before(:each) do
      @openid_profile = mock_openid_profile
      @member.openid_profiles.stub!(:build).and_return(@openid_profile)
    end

    describe "with successful save" do

      def do_post
        @openid_profile.should_receive(:save).and_return(true)
        post :create, :openid_profile => {}
      end

      it "should create a new openid_profile" do
        @member.openid_profiles.should_receive(:build).with({}).and_return(@openid_profile)
        do_post
      end

      it "should redirect to the new openid_profile" do
        do_post
        response.should redirect_to(member_openid_profile_url(@member, @openid_profile))
      end

    end

    describe "with failed save" do
      it_should_behave_like "A Registered Member"
      def do_post
        @openid_profile.should_receive(:save).and_return(false)
        post :create, :openid_profile => {}
      end

      it "should re-render 'new'" do
        do_post
        response.should render_template('new')
      end

    end
  end

  describe "handling DELETE /members/1/openid_profiles/1" do
    it_should_behave_like "A Registered Member"
    before(:each) do
      @openid_profile = mock_model(OpenidProfile, :destroy => true)
      @member.openid_profiles.stub!(:find).and_return(@openid_profile)
    end

    def do_delete
      delete :destroy, :id => "1"
    end

    it "should find the openid_profile requested" do
      @member.openid_profiles.should_receive(:find).with("1").and_return(@openid_profile)
      do_delete
    end

    it "should call destroy on the found openid_profile" do
      @openid_profile.should_receive(:destroy)
      do_delete
    end

    it "should redirect to the openid_profile list" do
      do_delete
      response.should redirect_to(member_openid_profiles_url(@member))
    end
  end
end


text:
Learn Basic PHP OOP

======
##### File 1.php
How to create class / object

======
##### File 2.php
Visibility of Properties public / private / protected

======
##### File 3.php
How to create method

======
##### File 4.php
Magic Method __construct(), __destruct()

======
##### File 5.php
Set / Get

======
##### File 6.php
Inheritance

======
##### File 7.php
Override Method


text:
@interface NSImage (AKAdditions)

- (CGImageRef) CGImage;
- (void) useCGImageWithBlock:(void(^)(CGImageRef img))block;
- (NSImage *) imageWithAlpha:(float)alpha;

- (void)writeToFile:(NSURL *)fileURL;

@end


text:
from flask import request
from google.cloud import kms_v1
import base64
import os

def run():

  action = request.values.get("action");
  data = request.values.get("data");

  project_id = os.environ.get('CLOUD_KMS_PROJECT')
  location_id = os.environ.get('CLOUD_KMS_LOCATION')
  key_ring_id = os.environ.get('CLOUD_KMS_KEYRING')
  crypto_key_id = os.environ.get('CLOUD_KMS_KEY')

  client = kms_v1.KeyManagementServiceClient()
  name = client.crypto_key_path_path(project_id, location_id, key_ring_id,
                                     crypto_key_id)
  out = ""
  if action == "encrypt":
    encr = client.encrypt(name, data.encode("utf-8")).ciphertext
    out = base64.b64encode(encr).decode("utf-8")
  elif action == "decrypt":
    out = client.decrypt(name, base64.b64decode(data)).plaintext.decode("utf-8")
  else:
    out = """
  Source (Secret or encoded base64):
<FORM name=form1 method=POST target='out' action='/kms'>
  <INPUT NAME='action' TYPE='HIDDEN'>
  <TEXTAREA name='data' style='width:800px;height:300px'></TEXTAREA>

  <INPUT VALUE='Encode' type=button onclick='encrypt()'>
  <INPUT VALUE='Decode' type=button onclick='decrypt()'>
</FORM>

Encoded base64

  """

  return out