text:
///////////////////////////////////////////////////////////////////////////////////
// Open 3D Model Viewer (open3mod) (v2.0)
// [NormalVectorGenerator.cs]
// (c) 2012-2015, Open3Mod Contributors
//
// Licensed under the terms and conditions of the 3-clause BSD license. See
// the LICENSE file in the root folder of the repository for the details.
//
// HIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
///////////////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.Diagnostics;
using Amib.Threading;
using Assimp;

namespace open3mod
{
    public class NormalVectorGenerator
    {
        private readonly Mesh _mesh;
        private readonly EditMesh _editMesh;

        private static SmartThreadPool _threadPool = null;
        private static readonly object ThreadPoolMutex = new object();
        private const int ParallelizationChunkSize = 1000;

        /// <summary>
        /// This is an expensive operation due to EditMesh construction, avoid.
        /// </summary>
        /// <param name="mesh"></param>
        public NormalVectorGenerator(Mesh mesh)
        {
            Debug.Assert(!mesh.PrimitiveType.HasFlag(PrimitiveType.Polygon));
            _mesh = mesh;
            lock (_mesh)
            {
                _editMesh = new EditMesh(_mesh);
            }

            lock (ThreadPoolMutex)
            {
                if (_threadPool != null)
                    return;
                int cpuCount = Environment.ProcessorCount;
                // One thread is busy rendering, so many extra threads that do not block on IO
                // (which our computation-heavy jobs don't) easily starve the GUI. Thus,
                // always reserve 25% and at least one core.
                int jobCount = Math.Max(1, (cpuCount * 3) / 4);
                _threadPool = new SmartThreadPool(1000, jobCount, jobCount);
            }
        }

        /// <summary>
        /// Compute normal vectors with the given threshold for smoothing.
        ///
        /// Updates the original |mesh|. This can be called multiple times.
        /// </summary>
        /// <param name="thresholdAngleInDegrees"></param>
        public void Compute(float thresholdAngleInDegrees)
        {
            CalculateFaceNormals();
            if (thresholdAngleInDegrees > 0.0f)
            {
                SmoothNormals(thresholdAngleInDegrees);
            }
            lock (_mesh)
            {
                _editMesh.ApplyToMesh(_mesh);
            }
        }

        private void CalculateFaceNormals()
        {
            _editMesh.Faces.ParallelDo(
                face =>
                {
                    Vector3D faceNormal = new Vector3D();
                    if (face.Vertices.Count == 3)
                    {
                        Vector3D v0 = face.Vertices[0].Position;
                        Vector3D v1 = face.Vertices[1].Position;
                        Vector3D v2 = face.Vertices[2].Position;
                        faceNormal = Vector3D.Cross(v1 - v0, v2 - v1);
                    }
                    if (faceNormal.LengthSquared() > 0.0f)
                    {
                        faceNormal.Normalize();
                    }
                    foreach (var vert in face.Vertices)
                    {
                        vert.Normal = faceNormal;
                    }
                    face.Normal = faceNormal;
                }, ParallelizationChunkSize, _threadPool);
        }

        private void SmoothNormals(float thresholdAngleInDegrees)
        {
            float thresholdAngleInRadians = (float)(thresholdAngleInDegrees*Math.PI/180.0);
            float cosThresholdAngle = (float)Math.Cos(thresholdAngleInRadians);
            _editMesh.Vertices.ParallelDo(
                vert =>
                {
                    var faceNormal = vert.Face.Normal.Value;
                    vert.Normal = faceNormal;
                    foreach (var adjacentVert in vert.AdjacentVertices)
                    {
                        if (vert == adjacentVert)
                        {
                            continue;
                        }
                        var adjacentFace = adjacentVert.Face;
                        var adjacentFaceNormal = adjacentFace.Normal.Value;
                        if (Vector3D.Dot(faceNormal, adjacentFaceNormal) >= cosThresholdAngle)
                        {
                            vert.Normal += adjacentFaceNormal;
                        }
                    }
                    if (vert.Normal.Value.LengthSquared() > 0.0f)
                    {
                        var v = vert.Normal.Value;
                        v.Normalize();
                        vert.Normal = v;
                    }
                }, ParallelizationChunkSize, _threadPool);
        }
    }
}

/* vi: set shiftwidth=4 tabstop=4: */


text:
import set from 'lodash.set';
import unset from 'lodash.unset';
import clone from 'lodash.clonedeep';

import { createValidator } from '@jsiwhitehead/validator';

import { Meteor } from '../global.js';
import getCollection from '../getCollection.js';

export default function addDataValidation(collectionKey, collectionSchema) {
  if (Meteor.isServer) {
    const schema = {
      ...collectionSchema,
      properties: {
        _id: { type: 'string', format: 'id' },
        createdAt: { type: 'integer' },
        modifiedAt: { type: 'integer' },
        ...collectionSchema.properties,
      },
    };

    const validator = createValidator(schema);
    getCollection(collectionKey).before.insert((userId, doc) => {
      const errors = validator(doc);
      if (Object.keys(errors).length > 0) {
        throw new Meteor.Error(
          `Insert data doesn\'t match collection schema: ${JSON.stringify(errors)}`,
        );
      }
      return true;
    });
    getCollection(collectionKey).before.update((userId, doc, fieldNames, modifier) => {
      const newSet = modifier.$set || {};
      const newUnset = modifier.$unset || {};

      const newDoc = clone(doc);
      Object.keys(newSet).forEach(k => set(newDoc, k, newSet[k]));
      Object.keys(newUnset).forEach(k => unset(newDoc, k));

      const errors = validator(newDoc);
      if (Object.keys(errors).length > 0) {
        throw new Meteor.Error(
          `Update data doesn\'t match collection schema: ${JSON.stringify(errors)}`,
        );
      }
      return true;
    });
  }
}

redpajama_set_name: RedPajamaGithub


text:
## Getting Started

1. Make sure you have node and npm installed
2. Install node globals with `npm install -g bower gulp typings`
3. Install local node modules with `npm install`
4. Install bower packages (none at the moment) with `bower install`
5. Install typescript definitions with `typings install`
6. Run `gulp watch` and go to localhost:3000

## Gulp Commands
`gulp clean` - clears out the `server/public/` directory
`gulp compile` - compiles the scss, images, html, and typescript
`gulp watch` - compiles everything and continously watches for changes
`gulp minify` - the minified version of `gulp compile`
`gulp` - defaults to `gulp watch`

The remaining gulp commands can be found in `gulpfile.js`


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.operator.window;

import com.facebook.presto.metadata.BoundVariables;
import com.facebook.presto.metadata.FunctionManager;
import com.facebook.presto.metadata.Signature;
import com.facebook.presto.metadata.SqlFunction;
import com.facebook.presto.spi.type.TypeManager;

import static java.util.Objects.requireNonNull;

public class SqlWindowFunction
        implements SqlFunction
{
    private final WindowFunctionSupplier supplier;

    public SqlWindowFunction(WindowFunctionSupplier supplier)
    {
        this.supplier = requireNonNull(supplier, "supplier is null");
    }

    @Override
    public final Signature getSignature()
    {
        return supplier.getSignature();
    }

    @Override
    public boolean isHidden()
    {
        return false;
    }

    @Override
    public boolean isDeterministic()
    {
        return true;
    }

    @Override
    public String getDescription()
    {
        return supplier.getDescription();
    }

    public WindowFunctionSupplier specialize(BoundVariables boundVariables, int arity, TypeManager typeManager, FunctionManager functionManager)
    {
        return supplier;
    }
}


text:
dstandarddialogs
================

Standard dialogs based on dojox/mobile/SimpleDialog


text:
require 'digest/sha1'

module Logster

  MAX_GROUPING_LENGTH = 50

  class Message
    LOGSTER_ENV = "_logster_env".freeze
    ALLOWED_ENV = %w{
      HTTP_HOST
      REQUEST_URI
      REQUEST_METHOD
      HTTP_USER_AGENT
      HTTP_ACCEPT
      HTTP_REFERER
      HTTP_X_FORWARDED_FOR
      HTTP_X_REAL_IP
      hostname
      process_id
    }

    attr_accessor :timestamp, :severity, :progname, :message, :key, :backtrace, :count, :env, :protected

    def initialize(severity, progname, message, timestamp = nil, key = nil)
      @timestamp = timestamp || get_timestamp
      @severity = severity
      @progname = progname
      @message = message
      @key = key || SecureRandom.hex
      @backtrace = nil
      @count = 1
      @protected = false
    end

    def to_h
      {
        message: @message,
        progname: @progname,
        severity: @severity,
        timestamp: @timestamp,
        key: @key,
        backtrace: @backtrace,
        count: @count,
        env: @env,
        protected: @protected
      }
    end

    def to_json(opts = nil)
      JSON.fast_generate(to_h, opts)
    end

    def self.from_json(json)
      parsed = ::JSON.parse(json)
      msg = new( parsed["severity"],
            parsed["progname"],
            parsed["message"],
            parsed["timestamp"],
            parsed["key"] )
      msg.backtrace = parsed["backtrace"]
      msg.env = parsed["env"]
      msg.count = parsed["count"]
      msg
    end

    def self.hostname
      @hostname ||= `hostname`.strip! rescue "<unknown>"
    end

    def populate_from_env(env)
      env ||= {}
      env["hostname"] ||= self.class.hostname
      env["process_id"] ||= Process.pid
      @env = Message.populate_from_env(env)
    end

    # in its own method so it can be overridden
    def grouping_hash
      return { message: self.message, severity: self.severity, backtrace: self.backtrace }
    end

    # todo - memoize?
    def grouping_key
      Digest::SHA1.hexdigest JSON.fast_generate grouping_hash
    end

    def is_similar?(other)
      self.grouping_key == other.grouping_key
    end

    def merge_similar_message(other)
      other_env = JSON.load JSON.fast_generate other.env
      other_env.keys.each do |env_key|
        self.env[env_key] = Message.env_merge_helper(self.env[env_key], other_env[env_key])
      end
    end

    def self.populate_from_env(env)
      env[LOGSTER_ENV] ||= begin
          unless env.include? "rack.input"
            # Not a web request
            return env
          end
          scrubbed = {}
          request = Rack::Request.new(env)
          params = {}
          request.params.each do |k,v|
            if k.include? "password"
              params[k] = "[redacted]"
            elsif Array === v
              params[k] = v[0..20]
            else
              params[k] = v && v[0..100]
            end
          end
          scrubbed["params"] = params if params.length > 0
          ALLOWED_ENV.map{ |k|
           scrubbed[k] = env[k] if env[k]
          }
          scrubbed
      end
    end

    def <=>(other)
      time = self.timestamp <=> other.timestamp
      return time if time && time != 0

      self.key <=> other.key
    end

    def =~(pattern)
      case pattern
        when Hash
          IgnorePattern.new(nil, pattern).matches? self
        when String
          IgnorePattern.new(pattern, nil).matches? self
        when Regexp
          IgnorePattern.new(pattern, nil).matches? self
        when IgnorePattern
          pattern.matches? self
        else
          nil
      end
    end

    protected

    def get_timestamp
      (Time.new.to_f * 1000).to_i
    end

    private

    def self.env_merge_helper(self_value, other_value)
      other_value = other_value.to_s if Symbol === other_value

      if (Hash === self_value || self_value.nil?) && (Hash === other_value || other_value.nil?) && (!self_value.nil? || !other_value.nil?)
        # one or both is a hash but not neither -> recurse on the keys
        self_value = {} unless self_value
        other_value = {} unless other_value
        shared_keys = self_value.keys | (other_value.keys rescue [])
        shared_keys.each do |key|
          self_value[key] = env_merge_helper(self_value[key], other_value[key])
        end
        self_value
      elsif self_value.is_a?(Array) && !other_value.is_a?(Array)
        # Already have grouped data, so append to array (it's actually a set)
        self_value << other_value unless self_value.include?(other_value) || self_value.length >= Logster::MAX_GROUPING_LENGTH
        self_value
      elsif !self_value.is_a?(Array)
        if self_value == other_value
          self_value
        else
          [self_value, other_value]
        end
      else
        # They're both arrays.
        # Three cases:
        # self = [1,2,3] and other = [1,2,4] -> make into array of array
        # self = [] and other = [1,2,4] -> make into array of array
        # self = [[1,2,3], [1,2,5]] and other = [1,2,4] -> append to array
        if self_value.length > 0 && self_value[0].is_a?(Array)
          self_value << other_value unless self_value.include?(other_value) || self_value.length >= Logster::MAX_GROUPING_LENGTH
          self_value
        else
          if self_value == other_value
            self_value
          else
            [self_value, other_value]
          end
        end
      end
    end
  end
end


text:
using UnityEngine;

[System.Serializable]
public class DiscordJoinEvent : UnityEngine.Events.UnityEvent<string> { }

[System.Serializable]
public class DiscordSpectateEvent : UnityEngine.Events.UnityEvent<string> { }

[System.Serializable]
public class DiscordJoinRequestEvent : UnityEngine.Events.UnityEvent<DiscordRpc.DiscordUser> { }

public class DiscordController : MonoBehaviour
{
    public DiscordRpc.RichPresence presence = new DiscordRpc.RichPresence();
    public string applicationId;
    public string optionalSteamId;
    public int clickCounter;
    public DiscordRpc.DiscordUser joinRequest;
    public UnityEngine.Events.UnityEvent onConnect;
    public UnityEngine.Events.UnityEvent onDisconnect;
    public UnityEngine.Events.UnityEvent hasResponded;
    public DiscordJoinEvent onJoin;
    public DiscordJoinEvent onSpectate;
    public DiscordJoinRequestEvent onJoinRequest;

    DiscordRpc.EventHandlers handlers;

    public void OnClick()
    {
        Debug.Log("Discord: on click!");
        clickCounter++;

        presence.details = string.Format("Button clicked {0} times", clickCounter);

        DiscordRpc.UpdatePresence(presence);
    }

    public void RequestRespondYes()
    {
        Debug.Log("Discord: responding yes to Ask to Join request");
        DiscordRpc.Respond(joinRequest.userId, DiscordRpc.Reply.Yes);
        hasResponded.Invoke();
    }

    public void RequestRespondNo()
    {
        Debug.Log("Discord: responding no to Ask to Join request");
        DiscordRpc.Respond(joinRequest.userId, DiscordRpc.Reply.No);
        hasResponded.Invoke();
    }

    public void ReadyCallback(ref DiscordRpc.DiscordUser connectedUser)
    {
        Debug.Log(string.Format("Discord: connected to {0}#{1}: {2}", connectedUser.username, connectedUser.discriminator, connectedUser.userId));
        onConnect.Invoke();
    }

    public void DisconnectedCallback(int errorCode, string message)
    {
        Debug.Log(string.Format("Discord: disconnect {0}: {1}", errorCode, message));
        onDisconnect.Invoke();
    }

    public void ErrorCallback(int errorCode, string message)
    {
        Debug.Log(string.Format("Discord: error {0}: {1}", errorCode, message));
    }

    public void JoinCallback(string secret)
    {
        Debug.Log(string.Format("Discord: join ({0})", secret));
        onJoin.Invoke(secret);
    }

    public void SpectateCallback(string secret)
    {
        Debug.Log(string.Format("Discord: spectate ({0})", secret));
        onSpectate.Invoke(secret);
    }

    public void RequestCallback(ref DiscordRpc.DiscordUser request)
    {
        Debug.Log(string.Format("Discord: join request {0}#{1}: {2}", request.username, request.discriminator, request.userId));
        joinRequest = request;
        onJoinRequest.Invoke(request);
    }

    void Start()
    {
    }

    void Update()
    {
        DiscordRpc.RunCallbacks();
    }

    void OnEnable()
    {
        Debug.Log("Discord: init");
        handlers = new DiscordRpc.EventHandlers();
        handlers.readyCallback += ReadyCallback;
        handlers.disconnectedCallback += DisconnectedCallback;
        handlers.errorCallback += ErrorCallback;
        handlers.joinCallback += JoinCallback;
        handlers.spectateCallback += SpectateCallback;
        handlers.requestCallback += RequestCallback;
        DiscordRpc.Initialize(applicationId, ref handlers, true, optionalSteamId);
    }

    void OnDisable()
    {
        Debug.Log("Discord: shutdown");
        DiscordRpc.Shutdown();
    }

    void OnDestroy()
    {

    }
}


text:
<?php

declare(strict_types=1);

use OAuth2Framework\Component\ImplicitGrant\TokenResponseType;
use OAuth2Framework\Component\OpenIdConnect\IdTokenGrant\IdTokenResponseType;
use OAuth2Framework\Component\OpenIdConnect\IdTokenGrant\IdTokenTokenResponseType;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use function Symfony\Component\DependencyInjection\Loader\Configurator\ref;

return function (ContainerConfigurator $container) {
    $container = $container->services()->defaults()
        ->private()
        ->autoconfigure()
    ;

    $container->set(IdTokenTokenResponseType::class)
        ->args([
            ref(IdTokenResponseType::class),
            ref(TokenResponseType::class),
        ])
    ;
};


text:
<?php
 namespace Post\Model;

 use Zend\Db\TableGateway\TableGateway;
 use Zend\Db\Sql\Select;
 use Zend\Db\Sql\Sql;
 use Zend\Db\Sql\Expression;

 class PostTable
 {
     const FIRST_ITEMS_PER_GROUP = 2;
     const ITEMS_PER_GROUP = 4;

     protected $tableGateway;
     protected $adapter;

     public function __construct(TableGateway $tableGateway)
     {
         $this->tableGateway = $tableGateway;
         $this->adapter = $this->tableGateway->adapter;
     }

     public function fetchAll()
     {
         $resultSet = $this->tableGateway->select();
         return $resultSet;
     }

     /**
     * select all main posts - type = 'n'
     *
     */
     public function fetchMainJoinUsers($position = null, $items_per_page)
     {

         $test = $items_per_page;
         $pos = $position;
         /*if($test == 4 && $pos == 4) {
            DebugBreak();
         }*/
         if($position === null) {
             throw new \Exception('A position/limit should be specified to extract from table!');
         }
         $select = new Select('posts');

        $select->columns(array('*'))
               ->order(array('post_time DESC'))
               ->where(array('post_type' => 'n'))
               ->limit($items_per_page)
               ->offset($position);

        $select->join('users', 'users.id = posts.post_user_id'
                     , array('post_username' => 'username',
                             'post_username_img' => 'img'));
        $select->join('likes', 'likes.like_post_id = posts.post_id', array(), 'left')
               ->join(array('users_like' => 'users'),
                      'likes.like_user_id = users_like.id',
                      array('post_like_usernames' =>
                      new Expression('GROUP_CONCAT(DISTINCT users_like.username)')),
                      'left')
               ->join('post_files', 'post_files.file_post_id = posts.post_id',
                        array('post_file_new_names' =>
                      new Expression('GROUP_CONCAT(DISTINCT post_files.file_new_name)'),
                      'post_file_old_names' =>
                      new Expression('GROUP_CONCAT(DISTINCT post_files.file_old_name)')),
                      'left')
               ->group(array('post_id'));
        $sql = new Sql($this->adapter);
        $statement = $sql->prepareStatementForSqlObject($select);

        $rowset = $statement->execute();

        /*if($test == 4 && $pos == 4) {
            foreach ($rowset as $row) {
                $res = $row;
            }

        }*/

        return $rowset;
     }

     /**
     * select all reply posts of particular parent id - type = 'r'
     *
     */
     public function fetchReplyJoinUsers($parentId = null)
     {
        if($parentId == null) {
            throw new \Exception(
                'You must specify a parent to find its replies.'
            );
        }

        $select = new Select('posts');

        $select->columns(array('*'))
               ->order(array('post_time'))
               ->where(array('post_parent_id' => $parentId,
                             'post_type' => 'r'));

        $select->join('users', 'users.id = posts.post_user_id'
                     , array('post_username' => 'username',
                             'post_username_img' => 'img'
                            ));
        $select->join('likes', 'likes.like_post_id = posts.post_id', array(), 'left')
               ->join(array('users_like' => 'users'), 'likes.like_user_id = users_like.id',
                      array('post_like_usernames' =>
                      new Expression('GROUP_CONCAT(DISTINCT users_like.username)')),
                      'left')
               ->join('post_files', 'post_files.file_post_id = posts.post_id',
                        array('post_file_new_names' =>
                      new Expression('GROUP_CONCAT(DISTINCT post_files.file_new_name)'),
                      'post_file_old_names' =>
                      new Expression('GROUP_CONCAT(DISTINCT post_files.file_old_name)')),
                      'left')
               ->group('post_id');

        $sql = new Sql($this->adapter);
        $statement = $sql->prepareStatementForSqlObject($select);
        $rowset = $statement->execute();

        return $rowset;
     }

     public function fetchAllJoinUsers($posts = null)
     {
        if($posts == null) {
            throw new \Exception('There are no posts.');
        }

        $postsArray = array();

        foreach ($posts as $post) {
            $postChildren = $this->findChildren($post['post_id']);

            if(is_array($postChildren)){
                $post['post_children'] = $postChildren;
            } else {
                $post['post_children'] = null;
            }

            $postsArray[]= $post;

            /*$postsArray[]['post_username'] = $post['post_username'];
            $postsArray[]['post_time'] = $post['post_time'];
            $postsArray[]['post_message'] = $post['post_message'];
            $postsArray[]['post_children'] = null;*/

        }

        return $postsArray;
     }

     public function findPostUser($postId) {
        if($postId == null) {
            throw new \Exception(
                'You must specify a post to find its writer.'
            );
        }

        $select = new Select('posts');

        $select->columns(array('*'))
               ->where(array('post_id' => $postId));

        $select->join('users', 'users.id = posts.post_user_id'
                     , array('post_username' => 'username'));

        $sql = new Sql($this->adapter);
        $statement = $sql->prepareStatementForSqlObject($select);
        $rowset = $statement->execute();
        $postRec = $rowset->current();
        return $postRec;

     }
     public function postsCount() {
          $select = new Select('posts');
        $select->columns(array('COUNT'=>new \Zend\Db\Sql\Expression('COUNT(*)')));

        $sql = new Sql($this->adapter);
        $statement = $sql->prepareStatementForSqlObject($select);
        $rowset = $statement->execute();
        $postsCount = $rowset->current();
        return $postsCount['COUNT'];
     }

     public function getPost($id)
     {
         $id  = (int) $id;
         $rowset = $this->tableGateway->select(array('post_id' => $id));
         $row = $rowset->current();
         if (!$row) {
             throw new \Exception("Could not find row $id");
         }
         return $row;
     }

     public function savePost(Post $post)
     {
         $data = array(
             'post_id' => $post->post_id,
             'post_parent_id'  => $post->post_parent_id,
             'post_replyto_id'  => $post->post_replyto_id,
             'post_user_id'  => $post->post_user_id,
             'post_message'  => $post->post_message,
             'post_type'  => $post->post_type,
             'post_time'  => $post->post_time,
         );

         $id = (int) $post->post_id;
         if ($id == 0) {
             $this->tableGateway->insert($data);
             return $this->tableGateway->lastInsertValue;
         } else {
             if ($this->getPost($id)) {
                 $this->tableGateway->update($data, array('post_id' => $id));
                 return $this->tableGateway->lastInsertValue;
             } else {
                 throw new \Exception('Post id does not exist');
             }
         }
     }

     public function deletePost($id = null)
     {
        if($id == null) {
            throw new \Exception('There is no post to delete.');
        }

        $this->tableGateway->delete(array('id' => (int) $id));
     }

     public function updatePostMsg($postId = null, $msg = null)
     {
         if ($this->getPost($postId)) {
             $data['post_message'] = $msg;
             $this->tableGateway->update($data, array('post_id' => $postId));
             return $this->tableGateway->lastInsertValue;
         } else {
             throw new \Exception('Post id does not exist');
         }
     }

     private function childExists($parentId = null)
     {

        /*$select->columns(array('*'))
                ->where(array('post_parent_id' => $parentId,
                             'post_type' => 'r'));*/
        $result = $this->tableGateway->select(array('post_parent_id' => $parentId,
                             'post_type' => 'r'));

        return $result;
     }

     private function findChildren($parentId = null)
     {
         if($parentId == null) {
            throw new \Exception(
                'You must specify a parent to find its replies.'
            );
         }

         $exists = $this->childExists($parentId);
         $counter = 0;
         foreach($exists as $exist)
         {
             ++$counter;
         }
         if($counter==0) return false;

         $replies = $this->fetchReplyJoinUsers($parentId);

         $postsArray = array();

         foreach ($replies as $reply) {
             $reply['post_parent_id'] = $parentId;
             $replyToUser = $this->findPostUser($reply['post_replyto_id']);
             $reply['post_replyto_name'] = $replyToUser['post_username'];
             $postsArray[] = $reply;
            /*$postsArray[]['post_id']       = $reply['post_id'];
            $postsArray[]['post_username'] = $reply['post_username'];
            $postsArray[]['post_time']     = $reply['post_time'];
            $postsArray[]['post_message']  = $reply['post_message'];
            $postsArray[]['post_children'] = null;*/

         }

         return $postsArray;

     }
 }
?>


text:
package org.apache.commons.digester3;

import static org.junit.Assert.assertEquals;

import java.util.Iterator;
import java.util.List;

import org.junit.Test;

/**
 *

 * Runs standard tests for RulesBase as well as tests of extensions.
 */
public class ExtendedBaseRulesTestCase
    extends RulesBaseTestCase
{

    // -------------------------------------------------- Overall Test Methods

    /**
     *

     * This should be overriden by subclasses.
     *
     * @return the matching rules to be tested.
     */
    @Override
    protected Rules createMatchingRulesForTest()
    {

        return new ExtendedBaseRules();
    }

    /**
     * Basic test of parent matching rules. A parent match matches any child of a particular kind of parent. A wild
     * parent has a wildcard prefix. This method tests non-universal wildcards.
     */
    @Test
    public void testBasicParentMatch()
    {

        // clear any existing rules
        digester.getRules().clear();

        assertEquals( "Initial rules list is empty", 0, digester.getRules().rules().size() );

        // Set up rules
        // since these are all NON-UNIVERSAL matches
        // only expect one match at each stage
        digester.addRule( "alpha/beta/gamma/delta", new TestRule( "exact" ) );
        digester.addRule( "*/beta/gamma/epsilon", new TestRule( "wild_child" ) );
        digester.addRule( "alpha/beta/gamma/?", new TestRule( "exact_parent" ) );
        digester.addRule( "*/beta/gamma/?", new TestRule( "wild_parent" ) );

        // this should match just the exact since this has presidence
        List<Rule> list = digester.getRules().match( null, "alpha/beta/gamma/delta", null, null );

        // all three rules should match
        assertEquals( "Testing basic parent mismatch (A)", 1, list.size() );

        Iterator<Rule> it = list.iterator();
        assertEquals( "Testing basic parent mismatch (B)", "exact", ( (TestRule) it.next() ).getIdentifier() );

        // we don't have an exact match for this child so we should get the exact parent
        list = digester.getRules().match( null, "alpha/beta/gamma/epsilon", null, null );

        // all three rules should match
        assertEquals( "Testing basic parent mismatch (C)", 1, list.size() );

        it = list.iterator();
        assertEquals( "Testing basic parent mismatch (D)", "exact_parent", ( (TestRule) it.next() ).getIdentifier() );

        // wild child overrides wild parent
        list = digester.getRules().match( null, "alpha/omega/beta/gamma/epsilon", null, null );

        // all three rules should match
        assertEquals( "Testing basic parent mismatch (E)", 1, list.size() );

        it = list.iterator();
        assertEquals( "Testing basic parent mismatch (F)", "wild_child", ( (TestRule) it.next() ).getIdentifier() );

        // nothing else matches so return wild parent
        list = digester.getRules().match( null, "alpha/omega/beta/gamma/zeta", null, null );

        // all three rules should match
        assertEquals( "Testing basic parent mismatch (G)", 1, list.size() );

        it = list.iterator();
        assertEquals( "Testing basic parent mismatch (H)", "wild_parent", ( (TestRule) it.next() ).getIdentifier() );

        // clean up
        digester.getRules().clear();

    }

    /**
     * Basic test of universal matching rules. Universal rules act independent.
     */
    @Test
    public void testBasicUniversal()
    {

        // clear any existing rules
        digester.getRules().clear();

        assertEquals( "Initial rules list is empty", 0, digester.getRules().rules().size() );

        // Set up rules
        // set up universal matches against non-universal ones
        digester.addRule( "alpha/beta/gamma", new TestRule( "exact" ) );
        digester.addRule( "*/beta/gamma", new TestRule( "non_wild_head" ) );
        digester.addRule( "!*/beta/gamma", new TestRule( "universal_wild_head" ) );
        digester.addRule( "!alpha/beta/gamma/?", new TestRule( "universal_wild_child" ) );
        digester.addRule( "alpha/beta/gamma/?", new TestRule( "non_wild_child" ) );
        digester.addRule( "alpha/beta/gamma/epsilon", new TestRule( "exact2" ) );
        digester.addRule( "alpha/epsilon/beta/gamma/zeta", new TestRule( "exact3" ) );
        digester.addRule( "*/gamma/?", new TestRule( "non_wildhead_child" ) );
        digester.addRule( "!*/epsilon/beta/gamma/?", new TestRule( "universal_wildhead_child" ) );

        List<Rule> list;
        Iterator<Rule> it;

        // test universal wild head
        list = digester.getRules().match( null, "alpha/beta/gamma", null, null );

        assertEquals( "Testing universal wildcard mismatch (A)", 2, list.size() );

        it = list.iterator();
        assertEquals( "Testing universal wildcard mismatch (B)", "exact", ( (TestRule) it.next() ).getIdentifier() );
        assertEquals( "Testing universal wildcard mismatch (C)", "universal_wild_head",
                      ( (TestRule) it.next() ).getIdentifier() );

        // test universal parent
        list = digester.getRules().match( null, "alpha/beta/gamma/epsilon", null, null );

        assertEquals( "Testing universal wildcard mismatch (D)", 2, list.size() );

        it = list.iterator();
        assertEquals( "Testing universal wildcard mismatch (E)", "universal_wild_child",
                      ( (TestRule) it.next() ).getIdentifier() );
        assertEquals( "Testing universal wildcard mismatch (F)", "exact2", ( (TestRule) it.next() ).getIdentifier() );

        // test universal parent
        list = digester.getRules().match( null, "alpha/beta/gamma/zeta", null, null );

        assertEquals( "Testing universal wildcard mismatch (G)", 2, list.size() );

        it = list.iterator();
        assertEquals( "Testing universal wildcard mismatch (H)", "universal_wild_child",
                      ( (TestRule) it.next() ).getIdentifier() );
        assertEquals( "Testing universal wildcard mismatch (I)", "non_wild_child",
                      ( (TestRule) it.next() ).getIdentifier() );

        // test wildcard universal parent
        list = digester.getRules().match( null, "alpha/epsilon/beta/gamma/alpha", null, null );

        assertEquals( "Testing universal wildcard mismatch (J)", 2, list.size() );

        it = list.iterator();
        assertEquals( "Testing universal wildcard mismatch (K)", "non_wildhead_child",
                      ( (TestRule) it.next() ).getIdentifier() );
        assertEquals( "Testing universal wildcard mismatch (L)", "universal_wildhead_child",
                      ( (TestRule) it.next() ).getIdentifier() );

        // test wildcard universal parent
        list = digester.getRules().match( null, "alpha/epsilon/beta/gamma/zeta", null, null );

        assertEquals( "Testing universal wildcard mismatch (M)", 2, list.size() );

        it = list.iterator();
        assertEquals( "Testing universal wildcard mismatch (M)", "exact3", ( (TestRule) it.next() ).getIdentifier() );
        assertEquals( "Testing universal wildcard mismatch (O)", "universal_wildhead_child",
                      ( (TestRule) it.next() ).getIdentifier() );

        // clean up
        digester.getRules().clear();

    }

    /**
     * Basic test of wild matches. A universal will match matches anything! A non-universal will match matches anything
     * not matched by something else. This method tests non-universal and universal wild matches.
     */
    @Test
    public void testWildMatch()
    {

        // clear any existing rules
        digester.getRules().clear();

        assertEquals( "Initial rules list is empty", 0, digester.getRules().rules().size() );

        // Set up rules
        // The combinations a little large to test everything but we'll pick a couple and try them.
        digester.addRule( "*", new TestRule( "basic_wild" ) );
        digester.addRule( "!*", new TestRule( "universal_wild" ) );
        digester.addRule( "alpha/beta/gamma/delta", new TestRule( "exact" ) );
        digester.addRule( "*/beta/gamma/?", new TestRule( "wild_parent" ) );

        List<Rule> list;
        Iterator<Rule> it;

        // The universal wild will always match whatever else does
        list = digester.getRules().match( null, "alpha/beta/gamma/delta", null, null );

        // all three rules should match
        assertEquals( "Testing wild mismatch (A)", 2, list.size() );

        it = list.iterator();
        assertEquals( "Testing wild mismatch (B)", "universal_wild", ( (TestRule) it.next() ).getIdentifier() );
        assertEquals( "Testing wild mismatch (C)", "exact", ( (TestRule) it.next() ).getIdentifier() );

        // The universal wild will always match whatever else does
        list = digester.getRules().match( null, "alpha/beta/gamma/epsilon", null, null );

        assertEquals( "Testing wild mismatch (D)", 2, list.size() );

        it = list.iterator();
        assertEquals( "Testing wild mismatch (E)", "universal_wild", ( (TestRule) it.next() ).getIdentifier() );
        assertEquals( "Testing wild mismatch (F)", "wild_parent", ( (TestRule) it.next() ).getIdentifier() );

        // The universal wild will always match whatever else does
        // we have no other non-universal matching so this will match the non-universal wild as well
        list = digester.getRules().match( null, "alpha/gamma", null, null );

        assertEquals( "Testing wild mismatch (G)", 2, list.size() );

        it = list.iterator();
        assertEquals( "Testing wild mismatch (H)", "basic_wild", ( (TestRule) it.next() ).getIdentifier() );
        assertEquals( "Testing wild mismatch (I)", "universal_wild", ( (TestRule) it.next() ).getIdentifier() );

        // clean up
        digester.getRules().clear();

    }

    /**
     * Basic test of wild matches. A universal will match matches anything! A non-universal will match matches anything
     * not matched by something else. This method tests non-universal and universal wild matches.
     */
    @Test
    public void testRootTailMatch()
    {

        // clear any existing rules
        digester.getRules().clear();

        assertEquals( "Initial rules list is empty", 0, digester.getRules().rules().size() );

        // Set up rules
        // The combinations a little large to test everything but we'll pick a couple and try them.
        digester.addRule( "*/a", new TestRule( "a_tail" ) );

        List<Rule> list;

        list = digester.getRules().match( null, "a", null, null );

        assertEquals( "Testing tail wrong size (A)", 1, list.size() );
        assertEquals( "Testing tail mismatch (B)", "a_tail", ( (TestRule) list.get( 0 ) ).getIdentifier() );

        list = digester.getRules().match( null, "beta/a", null, null );

        assertEquals( "Testing tail wrong size (C)", 1, list.size() );
        assertEquals( "Testing tail mismatch (D)", "a_tail", ( (TestRule) list.get( 0 ) ).getIdentifier() );

        list = digester.getRules().match( null, "be/aaa", null, null );

        assertEquals( "Testing tail no matches (E)", 0, list.size() );

        list = digester.getRules().match( null, "aaa", null, null );

        assertEquals( "Testing tail no matches (F)", 0, list.size() );

        list = digester.getRules().match( null, "a/beta", null, null );

        assertEquals( "Testing tail no matches (G)", 0, list.size() );

        // clean up
        digester.getRules().clear();

    }

    @Test
    public void testAncesterMatch()
        throws Exception
    {
        // test fixed root ancester
        digester.getRules().clear();

        digester.addRule( "!a/b/*", new TestRule( "uni-a-b-star" ) );
        digester.addRule( "a/b/*", new TestRule( "a-b-star" ) );
        digester.addRule( "a/b/c", new TestRule( "a-b-c" ) );
        digester.addRule( "a/b/?", new TestRule( "a-b-child" ) );

        List<Rule> list = digester.getRules().match( null, "a/b/c", null, null );

        assertEquals( "Simple ancester matches (1)", 2, list.size() );
        assertEquals( "Univeral ancester mismatch (1)", "uni-a-b-star", ( (TestRule) list.get( 0 ) ).getIdentifier() );
        assertEquals( "Parent precedence failure", "a-b-c", ( (TestRule) list.get( 1 ) ).getIdentifier() );

        list = digester.getRules().match( null, "a/b/b", null, null );
        assertEquals( "Simple ancester matches (2)", 2, list.size() );
        assertEquals( "Univeral ancester mismatch (2)", "uni-a-b-star", ( (TestRule) list.get( 0 ) ).getIdentifier() );
        assertEquals( "Child precedence failure", "a-b-child", ( (TestRule) list.get( 1 ) ).getIdentifier() );

        list = digester.getRules().match( null, "a/b/d", null, null );
        assertEquals( "Simple ancester matches (3)", 2, list.size() );
        assertEquals( "Univeral ancester mismatch (3)", "uni-a-b-star", ( (TestRule) list.get( 0 ) ).getIdentifier() );
        assertEquals( "Ancester mismatch (1)", "a-b-child", ( (TestRule) list.get( 1 ) ).getIdentifier() );

        list = digester.getRules().match( null, "a/b/d/e/f", null, null );
        assertEquals( "Simple ancester matches (4)", 2, list.size() );
        assertEquals( "Univeral ancester mismatch (4)", "uni-a-b-star", ( (TestRule) list.get( 0 ) ).getIdentifier() );
        assertEquals( "Ancester mismatch (2)", "a-b-star", ( (TestRule) list.get( 1 ) ).getIdentifier() );

        // test wild root ancester
        digester.getRules().clear();

        digester.addRule( "!*/a/b/*", new TestRule( "uni-star-a-b-star" ) );
        digester.addRule( "*/b/c/*", new TestRule( "star-b-c-star" ) );
        digester.addRule( "*/b/c/d", new TestRule( "star-b-c-d" ) );
        digester.addRule( "a/b/c", new TestRule( "a-b-c" ) );

        list = digester.getRules().match( null, "a/b/c", null, null );
        assertEquals( "Wild ancester match (1)", 2, list.size() );
        assertEquals( "Univeral ancester mismatch (5)", "uni-star-a-b-star",
                      ( (TestRule) list.get( 0 ) ).getIdentifier() );
        assertEquals( "Match missed (1)", "a-b-c", ( (TestRule) list.get( 1 ) ).getIdentifier() );

        list = digester.getRules().match( null, "b/c", null, null );
        assertEquals( "Wild ancester match (2)", 1, list.size() );
        assertEquals( "Match missed (2)", "star-b-c-star", ( (TestRule) list.get( 0 ) ).getIdentifier() );

        list = digester.getRules().match( null, "a/b/c/d", null, null );
        assertEquals( "Wild ancester match (3)", 2, list.size() );
        assertEquals( "Match missed (3)", "uni-star-a-b-star", ( (TestRule) list.get( 0 ) ).getIdentifier() );
        assertEquals( "Match missed (4)", "star-b-c-d", ( (TestRule) list.get( 1 ) ).getIdentifier() );

        list = digester.getRules().match( null, "b/b/c/e/d", null, null );
        assertEquals( "Wild ancester match (2)", 1, list.size() );
        assertEquals( "Match missed (5)", "star-b-c-star", ( (TestRule) list.get( 0 ) ).getIdentifier() );
    }

    @Test
    public void testLongMatch()
    {

        digester.getRules().clear();

        digester.addRule( "a/b/c/d/*", new TestRule( "a-b-c-d-star" ) );

        List<Rule> list = digester.getRules().match( null, "a/b/c/d/e", null, null );
        assertEquals( "Long match (1)", 1, list.size() );
        assertEquals( "Match missed (1)", "a-b-c-d-star", ( (TestRule) list.get( 0 ) ).getIdentifier() );

        list = digester.getRules().match( null, "a/b/c/d/e/f", null, null );
        assertEquals( "Long match (2)", 1, list.size() );
        assertEquals( "Match missed (2)", "a-b-c-d-star", ( (TestRule) list.get( 0 ) ).getIdentifier() );

        list = digester.getRules().match( null, "a/b/c/d/e/f/g", null, null );
        assertEquals( "Long match (3)", 1, list.size() );
        assertEquals( "Match missed (3)", "a-b-c-d-star", ( (TestRule) list.get( 0 ) ).getIdentifier() );

        list = digester.getRules().match( null, "a/b/c/d", null, null );
        assertEquals( "Long match (4)", 0, list.size() );
    }

    @Test
    public void testInstructors()
    {
        digester.getRules().clear();

        digester.addRule( "!instructors/*", new TestRule( "instructors" ) );
        digester.addRule( "!instructor/*", new TestRule( "instructor" ) );

        final List<Rule> list = digester.getRules().match( null, "instructors", null, null );
        assertEquals( "Only expect to match instructors", 1, list.size() );
        assertEquals( "Instructors expected", "instructors", ( (TestRule) list.get( 0 ) ).getIdentifier() );

    }

    @Test
    public void testMiddleInstructors()
    {
        digester.getRules().clear();

        digester.addRule( "!instructors/*", new TestRule( "instructors" ) );

        final List<Rule> list = digester.getRules().match( null, "/tosh/instructors/fiddlesticks", null, null );
        assertEquals( "No matches expected", 0, list.size() );

    }
}


text:
using System;
using Cake.Core.IO;
using Cake.Core.Scripting.Analysis;

namespace Cake.Core.Scripting.Processors
{
    internal sealed class LoadDirectiveProcessor : LineProcessor
    {
        public LoadDirectiveProcessor(ICakeEnvironment environment)
            : base(environment)
        {
        }

        public override bool Process(IScriptAnalyzerContext context, string line, out string replacement)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            replacement = null;

            var tokens = Split(line);
            if (tokens.Length <= 0)
            {
                return false;
            }

            if (!tokens[0].Equals("#l", StringComparison.Ordinal) &&
                !tokens[0].Equals("#load", StringComparison.Ordinal))
            {
                return false;
            }

            var directoryPath = GetAbsoluteDirectory(context.Script.Path);
            var scriptPath = new FilePath(tokens[1].UnQuote()).MakeAbsolute(directoryPath);

            context.Analyze(scriptPath);

            return true;
        }
    }
}


text:
<?php

namespace DotBlue\Templating\Helpers;

use InvalidArgumentException;
use Nette;

class Registry
{

	/** @var IHelper[] */
	private $helpers;

	/** @var Caller */
	private $caller;

	/** @var mixed|NULL */
	private $locale;

	/**
	 * @return mixed|NULL
	 */
	public function getLocale()
	{
		return $this->locale;
	}

	/**
	 * @param  mixed|NULL
	 */
	public function setLocale($locale = NULL)
	{
		$this->locale = $locale;
	}

	/**
	 * @return Caller
	 */
	public function getCaller()
	{
		if (!isset($this->caller)) {
			$this->caller = new Caller($this);
		}
		return $this->caller;
	}

	public function addHelper(IHelper $helper)
	{
		$name = $this->normalizeName($helper->getName());
		if ($this->isRegisteredGlobally($name)) {
			throw new InvalidArgumentException("Helper with name '$name' is already registered.");
		}
		$this->helpers[$name] = $helper;
	}

	/**
	 * @param  string
	 * @return callable|FALSE
	 */
	public function loader($name)
	{
		$name = $this->normalizeName($name);
		if ($this->isRegisteredLocally($name)) {
			return $this->createCallback($name);
		}
		return FALSE;
	}

	/**
	 * @param  string
	 * @return callable
	 */
	public function createCallback($name)
	{
		return function ($value) use ($name) {
			$args = func_get_args();
			array_shift($args);
			$options = new Options($name, $args, $this->getCaller());
			if ($this->locale) {
				$options->setLocale($this->locale);
			}
			return call_user_func(
				array($this->helpers[$name], 'execute'),
				$value,
				$options
			);
		};
	}

	/**
	 * @internal
	 */
	public function setCaller(Caller $caller)
	{
		$this->caller = $caller;
	}

	private function isRegisteredLocally($name)
	{
		return isset($this->helpers[$name]);
	}

	private function isRegisteredGlobally($name)
	{
		return $this->isRegisteredLocally($name) || Nette\Templating\Helpers::loader($name) !== NULL;
	}

	private function normalizeName($name)
	{
		return strtolower($name);
	}

}


text:
use atom::Atom;
use consumer::*;
use parallel_stream::*;
use std::cmp::PartialOrd;
use stream::*;
use utils::replace_until_change;

struct MaxState<C, T>
    where C: Consumer<T>,
          T: PartialOrd
{
    consumer: C,
    value: Option<T>,
}

impl<C, T> Consumer<T> for MaxState<C, T>
    where C: Consumer<T>,
          T: PartialOrd
{
    fn emit(&mut self, mut item: T) -> bool {

        if let Some(current) = self.value.take() {
            if current > item {
                item = current;
            }
        }

        self.value = Some(item);
        true
    }
}

impl<C, T> Drop for MaxState<C, T>
    where C: Consumer<T>,
          T: PartialOrd
{
    fn drop(&mut self) {
        if let Some(value) = self.value.take() {
            self.consumer.emit(value);
        }
    }
}

#[must_use = "stream adaptors are lazy and do nothing unless consumed"]
pub struct Max<S> {
    stream: S,
}

impl<S> Stream for Max<S>
    where S: Stream,
          S::Item: PartialOrd
{
    type Item = S::Item;

    fn consume<C>(self, consumer: C)
        where C: Consumer<Self::Item>
    {
        self.stream.consume(MaxState {
            consumer: consumer,
            value: None,
        });
    }
}

impl<S> Max<S> {
    pub fn new(stream: S) -> Self {
        Max { stream: stream }
    }
}

#[must_use = "stream adaptors are lazy and do nothing unless consumed"]
pub struct ParallelMax<S> {
    stream: S,
}

impl<S> ParallelStream for ParallelMax<S>
    where S: ParallelStream,
          S::Item: PartialOrd + Send
{
    type Item = S::Item;

    fn consume<C>(self, consumer: C)
        where C: ParallelConsumer<Self::Item>
    {
        self.stream.consume(ParallelMaxState {
            consumer: consumer,
            value: Atom::empty(),
        });
    }
}

impl<S> ParallelMax<S> {
    pub fn new(stream: S) -> Self {
        ParallelMax { stream: stream }
    }
}

struct ParallelMaxState<C, T>
    where C: ParallelConsumer<T>,
          T: PartialOrd + Send
{
    consumer: C,
    value: Atom<Box<T>>,
}

impl<C, T> ParallelConsumer<T> for ParallelMaxState<C, T>
    where C: ParallelConsumer<T>,
          T: PartialOrd + Send
{
    fn emit(&self, item: T) -> bool {
        replace_until_change(&self.value, item, |current, item| if *current > *item {
            current
        } else {
            item
        });
        true
    }
}

impl<C, T> Drop for ParallelMaxState<C, T>
    where C: ParallelConsumer<T>,
          T: PartialOrd + Send
{
    fn drop(&mut self) {
        if let Some(value) = self.value.take() {
            self.consumer.emit(*value);
        }
    }
}


text:
module DeliveryCluster
  module Helpers
    #
    # Analytics Module
    #
    # This module provides helpers related to the Analytics Component
    module Analytics
      module_function

      # Get the Hostname of the Analytics Server
      #
      # @param node [Chef::Node] Chef Node object
      # @return hostname [String] The hostname of the Analytics server
      def analytics_server_hostname(node)
        DeliveryCluster::Helpers::Component.component_hostname(node, 'analytics')
      end

      # Returns the FQDN of the Analytics Server
      #
      # @param node [Chef::Node] Chef Node object
      # @return [String] Analytics FQDN
      def analytics_server_fqdn(node)
        @analytics_server_fqdn ||= DeliveryCluster::Helpers::Component.component_fqdn(node, 'analytics')
      end

      # Generates the Analytics Server Attributes
      #
      # @param node [Chef::Node] Chef Node object
      # @return [Hash] Analytics attributes for a machine resource
      def analytics_server_attributes(node)
        return {} unless analytics_enabled?(node)
        {
          'chef-server-12' => {
            'analytics' => {
              'fqdn' => analytics_server_fqdn(node)
            }
          }
        }
      end

      # Activate the Analytics Component
      # This method will touch a lock file to activate the Analytics component
      #
      # @param node [Chef::Node] Chef Node object
      def activate_analytics(node)
        FileUtils.touch(analytics_lock_file(node))
      end

      # Analytics Lock File
      #
      # @param node [Chef::Node] Chef Node object
      # @return [String] The PATH of the Analytics lock file
      def analytics_lock_file(node)
        "#{DeliveryCluster::Helpers.cluster_data_dir(node)}/analytics"
      end

      # Verify the state of the Analytics Component
      # If the lock file exist, then we have the Analytics component enabled,
      # otherwise it is NOT enabled yet.
      #
      # @param node [Chef::Node] Chef Node object
      # @return [Bool] The state of the Analytics component
      def analytics_enabled?(node)
        File.exist?(analytics_lock_file(node))
      end
    end
  end

  # Module that exposes multiple helpers
  module DSL
    # Hostname of the Analytics Server
    def analytics_server_hostname
      DeliveryCluster::Helpers::Analytics.analytics_server_hostname(node)
    end

    # FQDN of the Analytics Server
    def analytics_server_fqdn
      DeliveryCluster::Helpers::Analytics.analytics_server_fqdn(node)
    end

    # Analytics Server Attributes
    def analytics_server_attributes
      DeliveryCluster::Helpers::Analytics.analytics_server_attributes(node)
    end

    # Activate the Analytics Component
    def activate_analytics
      DeliveryCluster::Helpers::Analytics.activate_analytics(node)
    end

    # Analytics Lock File
    def analytics_lock_file
      DeliveryCluster::Helpers::Analytics.analytics_lock_file(node)
    end

    # Verify the state of the Analytics Component
    def analytics_enabled?
      DeliveryCluster::Helpers::Analytics.analytics_enabled?(node)
    end
  end
end


text:
package com.gae.pidictcloud.fts;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.gae.pidictcloud.entity.PiDictEntity;
import com.gae.pidictcloud.entity.QuestionEntity;
import com.gae.pidictcloud.util.Constant;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.search.Document;
import com.google.appengine.api.search.Index;
import com.google.appengine.api.search.IndexSpec;
import com.google.appengine.api.search.Query;
import com.google.appengine.api.search.QueryOptions;
import com.google.appengine.api.search.Results;
import com.google.appengine.api.search.ScoredDocument;
import com.google.appengine.api.search.SearchServiceFactory;
import com.google.appengine.api.search.SortExpression;
import com.google.appengine.api.search.SortOptions;

public class QuestionIndex {
	private static final Index INDEX = SearchServiceFactory.getSearchService()
		      .getIndex(IndexSpec.newBuilder().setName("question_index"));
	private static final Logger LOG = Logger.getLogger(
			QuestionIndex.class.getName());

	public static String IndexingDocument(Document doc)
	{
		try {
			LOG.info("Adding document:\n" + doc.toString());
			INDEX.put(doc);
			return "Indexing question OK";
		} catch (RuntimeException e) {
			LOG.log(Level.SEVERE, "Failed to add " + doc, e);
			return "Indexing question error " + e.getMessage();
		}
	}

	public static String Delete(String [] docIds)
	{
		try {
			LOG.info("Detete index" );
			INDEX.delete(docIds);
			return "Detete question OK";
		} catch (RuntimeException e) {
			LOG.log(Level.SEVERE, "Failed to delete ", e);
			return "delete question error " + e.getMessage();
		}
	}

	public static String UpdateIndexingDocument(PiDictEntity piEntity)
	{
		try {
			Query query = Query.newBuilder()
					.setOptions(QueryOptions.newBuilder().setLimit(1).
					build()).build(PiDictEntity.entity_key_property+":"+KeyFactory.keyToString(piEntity.getKey()));
			LOG.info("Sending query " + query);
			Results<ScoredDocument> results = INDEX.search(query);
			 for (ScoredDocument scoredDoc : results) {
				 Document doc = piEntity.updateDocument(scoredDoc);
				 INDEX.put(doc);
			 }
			return "Update indexing question OK";
		} catch (RuntimeException e) {
			LOG.log(Level.SEVERE, "Failed to update " ,e);
			return "Update indexing question error " + e.getMessage();
		}
	}

	public static List<QuestionEntity> FullTextSearch(String searchPhrase, String[] searchFields){
		List<QuestionEntity> found = new ArrayList<QuestionEntity>();
		try {
			String plural = "";
			if(searchPhrase.length()>0 && searchPhrase.charAt(0)=='"' && searchPhrase.charAt(searchPhrase.length()-1)=='"')
				plural = "~";
			else{
				if(searchPhrase.indexOf(' ')==-1 || searchFields.length==2){
					plural = "~";
					searchPhrase = "\""+searchPhrase+"\"";
				}
			}
			String queryStr = "";
			int i = 1;
			for (String field : searchFields){
				if("1".equals(field)){
					queryStr += plural + searchPhrase;
					break;
				}else if("6".equals(field)){
					queryStr += PiDictEntity.question_property+":"+plural+searchPhrase+ (i==searchFields.length?"":" OR ");
				}else if("7".equals(field)){
					queryStr += PiDictEntity.answer_property+":"+plural+searchPhrase+(i==searchFields.length?"":" OR ");
				}
				i++;
			}
			/*SortOptions sortOptions = SortOptions.newBuilder()
		            .addSortExpression(SortExpression.newBuilder()
		                .setExpression(PiDictEntity.createdOn_property)
		                .setDirection(SortExpression.SortDirection.DESCENDING)
		                .setDefaultValue(""))
		            .setLimit(1000)
		            .build();*/
			QueryOptions options = QueryOptions.newBuilder()
				    .setLimit(Constant.SEARCH_RESULT_LIMIT)
				    /*.setSortOptions(sortOptions)*/
				    .build();
			Query query = Query.newBuilder().setOptions(options).build(queryStr);
			LOG.info("Sending query " + query);
		    Results<ScoredDocument> results = INDEX.search(query);
		    for (ScoredDocument scoredDoc : results) {
		    	QuestionEntity qObj = new QuestionEntity();
		    	qObj.setKey(KeyFactory.stringToKey(scoredDoc.getOnlyField(PiDictEntity.entity_key_property).getText()));
		    	qObj.setQuestion(scoredDoc.getOnlyField(PiDictEntity.question_property).getText());
		    	qObj.setAnswer(scoredDoc.getOnlyField(PiDictEntity.answer_property).getText());
		    	qObj.setCreatedOn(scoredDoc.getOnlyField(PiDictEntity.createdOn_property).getDate());
		    	found.add(qObj);
		    }
		} catch (RuntimeException e) {
			LOG.log(Level.SEVERE, "Failed to search " ,e);
		}
		return found;
	}
}


text:
<script src="js/libs/d3/d3.min.js"></script>
<script src="js/libs/jquery/jquery.min.js"></script>
<script src="js/libs/jquery/jquery.number.min.js"></script>
<script src="js/libs/modernizr/modernizr.js"></script>
<script src="js/libs/bootstrap/bootstrap.min.js"></script>
<script src="js/libs/sinclair.js"></script>
<script src="js/libs/data/zipdata.js"></script>
<script src="js/libs/leaflet/leaflet.js"></script>
<script src="js/libs/leaflet/tile.stamen.js"></script>
<script src="js/functions.js"></script>
<script src="js/main.js"></script>


text: CKEDITOR.plugins.setLang("save","sq",{toolbar:"Ruaje"});


text:
import os
import socket
import paramiko
import ConfigParser
from string import Template
from common import saxslog

class ChangeoverParser(ConfigParser.ConfigParser):
    """
    Extends the ConfigParser by a method that returns a dictionary of the
    settings file and converts "true" and "false" strings to Boolean values.
    """
    def to_dict(self):
        """
        Returns a dictionary of the settings file
        """
        conf_dict = dict(self._sections)
        for key in conf_dict:
            conf_dict[key] = dict(self._defaults, **conf_dict[key])
            for k, v in conf_dict[key].iteritems():
                if v.lower() == "true":
                    conf_dict[key][k] = True
                elif v.lower == "false":
                    conf_dict[key][k] = False
            conf_dict[key].pop('__name__', None)
        return conf_dict

class __SettingsSingleton(object):
    d = {}

def Settings():
    return __SettingsSingleton().d

def read(conf_path):
    """
    Read the settings from the specified configuration file and builds a
    dictionary.
    conf_path: The path to the settings file
    """
    conf_parser = ChangeoverParser()
    conf_parser.read(conf_path)
    Settings().clear()
    Settings().update(conf_parser.to_dict())

    # build the source folder list
    conf = Settings()
    conf['source']['folder_list'] = conf['source']['folder'].split('/')

    # set the statistics file configuration
    conf['statistics']['has_year'] = (conf['statistics']['file'].find("${year}") > -1)
    conf['statistics']['has_month'] = (conf['statistics']['file'].find("${month}") > -1)
    conf['statistics']['has_day'] = (conf['statistics']['file'].find("${day}") > -1)

def validate():
    """
    Performs a validation of the settings.
    Returns True if the settings are valid, otherwise False is returned.
    """
    conf = Settings()
    logger, raven_client = saxslog.setup(__name__,
                                        conf['logging']['debug'],
                                        conf['logging']['sentry'])

    # check if the watchfolder exists
    if not os.path.isdir(conf['source']['watch']):
        logger.error("The watch folder '%s' doesn't exist!"%conf['source']['watch'])
        return False
    logger.info("Watchfolder exists and is valid")

    # check if all keys in the target folder string have been declared in the
    # source folder string
    try:
        check_dict = {}
        for token in conf['source']['folder_list']:
            if token.startswith('${') and token.endswith('}'):
                check_dict[token[2:len(token)-1]] = ""
        Template(conf['target']['folder']).substitute(check_dict)
        logger.info("Source and target folder keys match")
    except KeyError, e:
        if raven_client != None:
            raven_client.captureException()
        else:
            logger.error("Key %s doesn't exist in the source folder settings!"%e)
        return False

    # check if the target host is reachable (uses key pair authentication)
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        client.connect(conf['target']['host'],
                       username=conf['target']['user'],
                       timeout=20)
        client.close()
        logger.info("Connection to the target host was successfully established")
    except (paramiko.SSHException, socket.error), e:
        if raven_client != None:
            raven_client.captureException()
        else:
            logger.error("Can't connect to target host: %s"%e)
        client.close()
        return False

    # check if the statistics filename has either no or a valid list of
    # template parameters.
    has_year = conf['statistics']['has_year']
    has_month = conf['statistics']['has_month']
    has_day = conf['statistics']['has_day']
    if (has_day and not (has_month and has_year)) or \
       (has_month and not has_year):
        logger.error("The statistics filename has to contain either no "+
                     "template parameters or a non-ambiguous combination "+
                     "of '${day}' '${year}' and '${month}'")
        return False

    return True


text:
'use strict';

const { isType, isFunction } = require('lib/util');
const NotEnoughDataError = require('lib/not-enough-data-error');
const BinaryStream = require('lib/binary-stream');

module.exports = buffer;

/**
 * Buffer type.
 * @param {number|Object} length The number of bytes or type for size-prefixed buffers.
 * @returns {Object}
 */
function buffer(length) {
  const isnum = typeof length === 'number';
  const istype = isType(length);
  const isfunc = isFunction(length);
  const isNull = length === null;

  if (!isnum && !istype && !isfunc && !isNull) {
    throw new TypeError('Unknown type of argument #1.');
  }

  return {
    encode,
    decode,
    encodingLength,
  };

  /**
   * Encode buffer.
   * @param {Buffer} buf
   * @param {EncodeStream} wstream
   */
  function encode(buf, wstream) {
    checkBuffer(buf);
    encode.bytes = 0;

    // eslint-disable-next-line no-invalid-this
    const context = this;

    if (isnum) {
      checkLength(length, buf.length);
    }

    if (istype) {
      length.encode.call(context, buf.length, wstream);
      encode.bytes += length.encode.bytes;
    }

    if (isfunc) {
      const expectedLength = length(context);

      checkLengthType(expectedLength);
      checkLength(expectedLength, buf.length);
    }

    wstream.writeBuffer(Buffer.isBuffer(buf) ? buf : buf.buffer);
    encode.bytes += buf.length;

    if (isNull) {
      wstream.writeUInt8(0);
      encode.bytes += 1;
    }
  }

  /**
   * Read the buffer from the stream.
   * @param {DecodeStream} rstream
   * @returns {Buffer}
   */
  function decode(rstream) {
    let size = 0;
    decode.bytes = 0;

    // eslint-disable-next-line no-invalid-this
    const context = this;

    if (isnum) {
      size = length;
    } else if (istype) {
      size = length.decode.call(context, rstream);
      decode.bytes += length.decode.bytes;
      checkLengthType(size);
    } else if (isfunc) {
      size = length(context);

      checkLengthType(size);
    } else if (isNull) {
      size = rstream.indexOf(0);

      if (size === -1) {
        throw new NotEnoughDataError(rstream.length + 1, rstream.length);
      }
    }

    const buf = rstream.readBuffer(size);
    decode.bytes += size;

    if (isNull) {
      decode.bytes += 1;
      rstream.consume(1);
    }

    return buf;
  }

  /**
   * Get the number bytes of an encoded buffer.
   * @param {Buffer} buf
   * @returns {number}
   */
  function encodingLength(buf) {
    checkBuffer(buf);
    let size = 0;

    if (isnum) {
      return length;
    }

    if (isNull) {
      size = 1;
    } else if (istype) {
      size = length.encodingLength(buf.length);
    }

    return size + buf.length;
  }
}

/**
 * Check if item is a Buffer.
 * @param {any} buf
 * @private
 */
function checkBuffer(buf) {
  if (!Buffer.isBuffer(buf) && !(buf instanceof BinaryStream)) {
    throw new TypeError('Argument 1 should be a Buffer or a BinaryStream.');
  }
}

/**
 * Check the length of a Buffer to encode.
 * @param {number} requiredSize
 * @param {number} havingSize
 */
function checkLength(requiredSize, havingSize) {
  if (requiredSize !== havingSize) {
    throw new Error(
      `Buffer required length ${requiredSize} instead of ${havingSize}`
    );
  }
}

/**
 * Check if the length type is a number.
 * @param {any} length
 */
function checkLengthType(length) {
  if (typeof length !== 'number') {
    throw new TypeError('Length of a buffer should be a number.');
  }
}