text:
package sudoku;

import java.awt.Point;
import sudoku.generate.BottomUpGenerator;
import sudoku.generate.DeductionGenerator;
import sudoku.generate.SudokuGenerator;
import sudoku.generate.TopDownGenerator;
import sudoku.util.ArrayUtil;

/**
 * Parses the command line arguments.
 *
 * @author Taras Mychaskiw
 */
public class ArgsParser {

    private final SudokuGenerator gen;
    private final int p, q;
    private final int num;
    private final String path;
    private final boolean verbose;

    /**
     * Pulls all the information out of the command line arguments.
     *
     * @param args the command line arguments
     */
    public ArgsParser(String[] args){
        if (args.length == 0){
            usage();    //display help and exit
            System.exit(0);
        }
        Point size = parseSize(args);
        p = size.x; q = size.y;
        gen = parseGen(args);
        num = parseNum(args);
        path = parsePath(args);
        verbose = ArrayUtil.contains(args, "-v");
    }

    public SudokuGenerator getGenerator(){ return gen; }
    public int getSmallWidth(){ return p; }
    public int getSmallHeight(){ return q; }
    public int getNumToCreate(){ return num; }
    public String getPath(){ return path; }
    public boolean isVerbose(){ return verbose; }

    /**
     * @param args the command line arguments
     * @return the size of the sudoku to create
     */
    private Point parseSize(String[] args){
        for (int i = 0; i < args.length; i++){
            if (args[i].equals("-s")){
                return new Point(Integer.valueOf(args[i+1]), Integer.valueOf(args[i+2]));
            }
        }
        return new Point(3, 3);
    }

    /**
     * @param args the command line arguments
     * @return the generator to use
     */
    private SudokuGenerator parseGen(String[] args){
        for (int i = 0; i < args.length; i++){
            if (args[i].equals("-g")){
                switch (args[i+1]) {
                    case "t":
                        return new TopDownGenerator(p, q);
                    case "b":
                        return new BottomUpGenerator(p, q);
                    case "d":
                        return new DeductionGenerator(p, q);
                }
            }
        }
        throw new IllegalArgumentException("generator type if required: use -g t|b");
    }

    /**
     * @param args the command line arguments
     * @return the number of sudokus to create
     */
    private int parseNum(String[] args){
        for (int i = 0; i < args.length; i++){
            if (args[i].equals("-n")){
                return Integer.valueOf(args[i+1]);
            }
        }
        return 100;
    }

    /**
     * @param args the command line arguments
     * @return the file path to where the sudoku problems should be stored
     */
    private String parsePath(String[] args){
        for (int i = 0; i < args.length; i++){
            if (args[i].equals("-o")){
                return args[i+1];
            }
        }
        return System.currentTimeMillis() + ".sudoku.txt";
    }

    /**
     * Displays usage details.
     */
    public void usage(){
        System.out.println("Usage: java -cp ./build/classes sudoku.Main [-s p q] -g t|b|d [-n number] [-o path] [-v]\n\n"
                + "\t-s\tSpecifiy the size of the sudoku boards to create.\n"
                + "\t\tp: width of the box regions\n"
                + "\t\tq: height of the box regions\n"
                + "\t\tBy default, 9x9 (p=q=3) boards are created.\n\n"
                + "\t-g\tSpecifiy which type of generator to use.\n"
                + "\t\tt: use a top down generator\n"
                + "\t\tb: use a bottom up generator\n"
                + "\t\td: use a deduction generator\n\n"
                + "\t-n\tSpecify the number of sudokus to create.\n"
                + "\t\tnumber: the number of sudokus to create\n"
                + "\t\tBy default, 100 sudokus are created.\n\n"
                + "\t-o\tSpecify the location to store the sudokus.\n"
                + "\t\tpath: the file to store all the sudokus in\n"
                + "\t\tBy default, \"[system_time].sudoku.txt\" is used.\n\n"
                + "\t-v\tTurn verbose mode on, default off.\n"
        );
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using Sm = System.ServiceModel;
using Smc = System.ServiceModel.Channels;
using Smd = System.ServiceModel.Description;
using System.Collections.Generic;

namespace ZBrad.WcfLib
{

    public class TcpClient<T> : ClientBase<T>
        where T : class
    {
        static Sm.NetTcpBinding binding = new Sm.NetTcpBinding(Sm.SecurityMode.None);

        internal TcpClient() : base(binding)
        {
        }

        /// <summary>
        /// create a WCF TCP client
        /// </summary>
        /// <param name="path">endpoint name</param>
        /// <param name="client">the new client</param>
        /// <param name="headers">optional headers to add</param>
        /// <returns>true if client created</returns>
        public static bool TryCreate(Uri path, out TcpClient<T> client, params KeyValuePair<string, string>[] headers)
        {
            client = new TcpClient<T>();
            return client.TryInit(path, headers);
        }

        /// <summary>
        /// create a WCF TCP client
        /// </summary>
        /// <param name="path">endpoint name</param>
        /// <param name="via">endpoint of router to resolve name</param>
        /// <param name="client">the new client</param>
        /// <param name="headers">optional headers to add</param>
        /// <returns>true if client created</returns>
        public static bool TryCreate(Uri path, Uri via, out TcpClient<T> client, params KeyValuePair<string, string>[] headers)
        {
            client = new TcpClient<T>();
            return client.TryInit(path, via, headers);
        }
    }
}


text:
require 'spec_helper'

describe Branch do

  before(:each) do
    @branch = FactoryGirl.build(:branch)
  end

  it "is valid with valid attributes" do
    @branch.should be_valid
  end

  it "is not valid without a company" do
    @branch.company_id = nil
    @branch.should_not be_valid
  end

  it "is not valid without a name" do
    @branch.name = nil
    @branch.should_not be_valid
  end

  it "is not valid with a short name" do
    @branch.name = "na"
    @branch.should_not be_valid
  end

end


text: This folder contains all examples used by Switch Docmentation and more.


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

class Disqus {
    /*
     *  Local CI instance
     */
    private $CI;
    /*
     *  Disqus shortname config item
     */
    private $disqus_shortname;
    /*
     *  Disqus developer setting
     */
    private $disqus_developer;

    /*
     * Init Disqus library
     */
    public function Disqus()
    {
        $this->CI =& get_instance();

        $this->CI->config->load('disqus');

        $this->disqus_shortname = $this->CI->config->item('disqus_shortname');
        $this->disqus_developer = $this->CI->config->item('disqus_developer');

        log_message('debug', 'Disqus library loaded');
    }

    /*
    * Get Diqsus html
    */
    public function get_html()
    {
        // Validate config items
        if (!in_array($this->disqus_developer, array(0,1)) || strlen($this->disqus_shortname) == 0) {
            return "Disqus config items not setup correctly, please check library config settings";
        }

        return  "

                Please enable JavaScript to view the comments powered by Disqus.
                blog comments powered by Disqus";
    }
}


text:
package com.google.developers.schemas.music_actions;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.schema.SearchAction;

import com.google.developers.schemas.impl.SearchActionImpl;
import com.google.developers.schemas.jsonld.JsonLdSerializer;
import com.google.developers.schemas.music_actions.doa.AlbumDao;
import com.google.developers.schemas.music_actions.doa.ArtistDao;
import com.google.developers.schemas.music_actions.doa.TrackDao;
import com.google.developers.schemas.music_actions.model.Album;
import com.google.developers.schemas.music_actions.model.Artist;
import com.google.developers.schemas.music_actions.model.Track;

public class SearchServlet extends HttpServlet {

	private JsonLdSerializer serializer = new JsonLdSerializer();

	private SearchAction doSearch(String query)  {
		SearchAction searchAction = new SearchActionImpl();

		for (Artist artist : ArtistDao.findArtistsByName(query)) {
			searchAction.addResult(artist.asSchemaOrg(true, false));
		}
		for (Album album : AlbumDao.findAlbumsByName(query)) {
			searchAction.addResult(album.asSchemaOrg(true, false));
		}
		for (Track track : TrackDao.findTracksByName(query)) {
			searchAction.addResult(track.asSchemaOrg(true, false));
		}
    	return searchAction;
    }

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
        	String query = request.getParameter("q");
        	SearchAction searchAction = doSearch(query);

        	// Generate JSON-LD markup for artist and actions
        	ByteArrayOutputStream os = new ByteArrayOutputStream();
    		serializer.serialize(searchAction, os);
    		String jsonld = new String(os.toByteArray(),"UTF-8");

        	if ((request.getServletPath() != null &&
        		 request.getServletPath().endsWith(".json")) ||
        		(request.getHeader("Accept") != null &&
        		 request.getHeader("Accept").contains("application/ld+json"))) {
        		response.setContentType("application/ld+json");
	    		PrintWriter writer = response.getWriter();
	    		writer.write(jsonld);
	    		writer.close();
        	} else {
	    		request.setAttribute("jsonld", jsonld);
	    		// Render page template
	    		request.setAttribute("query", query);
	    		request.setAttribute("results", searchAction.getResults());
	    		request.setAttribute("title", "Jarek & Shawn Music - Seach Results");
	    		request.getRequestDispatcher("/search.jsp").forward(request, response);
        	}
        }
        catch (Throwable e1) {
            e1.printStackTrace();
        }

    }

}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis
{
    internal class SyntaxDiffer
    {
        private const int InitialStackSize = 8;
        private const int MaxSearchLength = 8;
        private readonly Stack<SyntaxNodeOrToken> _oldNodes = new Stack<SyntaxNodeOrToken>(InitialStackSize);
        private readonly Stack<SyntaxNodeOrToken> _newNodes = new Stack<SyntaxNodeOrToken>(InitialStackSize);
        private readonly List<ChangeRecord> _changes = new List<ChangeRecord>();
        private readonly TextSpan _oldSpan;
        private readonly bool _computeNewText;
        private readonly HashSet<GreenNode> _nodeSimilaritySet = new HashSet<GreenNode>();
        private readonly HashSet<string> _tokenTextSimilaritySet = new HashSet<string>();

        private SyntaxDiffer(SyntaxNode oldNode, SyntaxNode newNode, bool computeNewText)
        {
            _oldNodes.Push((SyntaxNodeOrToken)oldNode);
            _newNodes.Push((SyntaxNodeOrToken)newNode);

            _oldSpan = oldNode.FullSpan;
            _computeNewText = computeNewText;
        }

        // return a set of text changes that when applied to the old document produces the new document
        internal static IList<TextChange> GetTextChanges(SyntaxTree before, SyntaxTree after)
        {
            if (before == after)
            {
                return SpecializedCollections.EmptyList<TextChange>();
            }
            else if (before == null)
            {
                return new[] { new TextChange(new TextSpan(0, 0), after.GetText().ToString()) };
            }
            else if (after == null)
            {
                throw new ArgumentNullException(nameof(after));
            }
            else
            {
                return GetTextChanges(before.GetRoot(), after.GetRoot());
            }
        }

        // return a set of text changes that when applied to the old document produces the new document
        internal static IList<TextChange> GetTextChanges(SyntaxNode oldNode, SyntaxNode newNode)
        {
            return new SyntaxDiffer(oldNode, newNode, computeNewText: true).ComputeTextChangesFromOld();
        }

        private IList<TextChange> ComputeTextChangesFromOld()
        {
            this.ComputeChangeRecords();
            var reducedChanges = this.ReduceChanges(_changes);

            return reducedChanges.Select(c => new TextChange(c.Range.Span, c.NewText!)).ToList();
        }

        internal static IList<TextSpan> GetPossiblyDifferentTextSpans(SyntaxTree? before, SyntaxTree? after)
        {
            if (object.ReferenceEquals(before, after))
            {
                // They're the same, so nothing changed.
                return SpecializedCollections.EmptyList<TextSpan>();
            }
            else if (before == null)
            {
                // The tree is completely new, everything has changed.
                return new[] { new TextSpan(0, after!.GetText().Length) };
            }
            else if (after == null)
            {
                throw new ArgumentNullException(nameof(after));
            }
            else
            {
                return GetPossiblyDifferentTextSpans(before.GetRoot(), after.GetRoot());
            }
        }

        // return which spans of text in the new document are possibly different than text in the old document
        internal static IList<TextSpan> GetPossiblyDifferentTextSpans(SyntaxNode oldNode, SyntaxNode newNode)
        {
            return new SyntaxDiffer(oldNode, newNode, computeNewText: false).ComputeSpansInNew();
        }

        private IList<TextSpan> ComputeSpansInNew()
        {
            this.ComputeChangeRecords();
            var reducedChanges = ReduceChanges(_changes);

            // this algorithm assumes changes are in non-overlapping document order
            var newSpans = new List<TextSpan>();
            int delta = 0; // difference between old & new start positions
            foreach (var change in reducedChanges)
            {
                if (change.Range.NewLength > 0) // delete-only ranges cannot be expressed as part of new text
                {
                    int start = change.Range.Span.Start + delta;
                    newSpans.Add(new TextSpan(start, change.Range.NewLength));
                }

                delta += change.Range.NewLength - change.Range.Span.Length;
            }

            return newSpans;
        }

        private void ComputeChangeRecords()
        {
            while (true)
            {
                // first check end-of-lists termination cases...
                if (_newNodes.Count == 0)
                {
                    // remaining old nodes are deleted
                    if (_oldNodes.Count > 0)
                    {
                        RecordDeleteOld(_oldNodes.Count);
                    }
                    break;
                }
                else if (_oldNodes.Count == 0)
                {
                    // remaining nodes were inserted
                    if (_newNodes.Count > 0)
                    {
                        RecordInsertNew(_newNodes.Count);
                    }
                    break;
                }
                else
                {
                    var action = GetNextAction();
                    switch (action.Operation)
                    {
                        case DiffOp.SkipBoth:
                            RemoveFirst(_oldNodes, action.Count);
                            RemoveFirst(_newNodes, action.Count);
                            break;
                        case DiffOp.ReduceOld:
                            ReplaceFirstWithChildren(_oldNodes);
                            break;
                        case DiffOp.ReduceNew:
                            ReplaceFirstWithChildren(_newNodes);
                            break;
                        case DiffOp.ReduceBoth:
                            ReplaceFirstWithChildren(_oldNodes);
                            ReplaceFirstWithChildren(_newNodes);
                            break;
                        case DiffOp.InsertNew:
                            RecordInsertNew(action.Count);
                            break;
                        case DiffOp.DeleteOld:
                            RecordDeleteOld(action.Count);
                            break;
                        case DiffOp.ReplaceOldWithNew:
                            RecordReplaceOldWithNew(action.Count, action.Count);
                            break;
                    }
                }
            }
        }

        private enum DiffOp
        {
            None = 0,
            SkipBoth,
            ReduceOld,
            ReduceNew,
            ReduceBoth,
            InsertNew,
            DeleteOld,
            ReplaceOldWithNew
        }

        private struct DiffAction
        {
            public readonly DiffOp Operation;
            public readonly int Count;

            public DiffAction(DiffOp operation, int count)
            {
                System.Diagnostics.Debug.Assert(count >= 0);
                this.Operation = operation;
                this.Count = count;
            }
        }

        private DiffAction GetNextAction()
        {
            bool oldIsToken = _oldNodes.Peek().IsToken;
            bool newIsToken = _newNodes.Peek().IsToken;

            // look for exact match
            int indexOfOldInNew;
            int similarityOfOldInNew;
            int indexOfNewInOld;
            int similarityOfNewInOld;

            FindBestMatch(_newNodes, _oldNodes.Peek(), out indexOfOldInNew, out similarityOfOldInNew);
            FindBestMatch(_oldNodes, _newNodes.Peek(), out indexOfNewInOld, out similarityOfNewInOld);

            if (indexOfOldInNew == 0 && indexOfNewInOld == 0)
            {
                // both first nodes are somewhat similar to each other

                if (AreIdentical(_oldNodes.Peek(), _newNodes.Peek()))
                {
                    // they are identical, so just skip over both first new and old nodes.
                    return new DiffAction(DiffOp.SkipBoth, 1);
                }
                else if (!oldIsToken && !newIsToken)
                {
                    // neither are tokens, so replace each first node with its child nodes
                    return new DiffAction(DiffOp.ReduceBoth, 1);
                }
                else
                {
                    // otherwise just claim one's text replaces the other..
                    // NOTE: possibly we can improve this by reducing the side that may not be token?
                    return new DiffAction(DiffOp.ReplaceOldWithNew, 1);
                }
            }
            else if (indexOfOldInNew >= 0 || indexOfNewInOld >= 0)
            {
                // either the first old-node is similar to some node in the new-list or
                // the first new-node is similar to some node in the old-list

                if (indexOfNewInOld < 0 || similarityOfOldInNew >= similarityOfNewInOld)
                {
                    // either there is no match for the first new-node in the old-list or the
                    // the similarity of the first old-node in the new-list is much greater

                    // if we find a match for the old node in the new list, that probably means nodes were inserted before it.
                    if (indexOfOldInNew > 0)
                    {
                        // look ahead to see if the old node also appears again later in its own list
                        int indexOfOldInOld;
                        int similarityOfOldInOld;
                        FindBestMatch(_oldNodes, _oldNodes.Peek(), out indexOfOldInOld, out similarityOfOldInOld, 1);

                        // don't declare an insert if the node also appeared later in the original list
                        var oldHasSimilarSibling = (indexOfOldInOld >= 1 && similarityOfOldInOld >= similarityOfOldInNew);
                        if (!oldHasSimilarSibling)
                        {
                            return new DiffAction(DiffOp.InsertNew, indexOfOldInNew);
                        }
                    }

                    if (!newIsToken)
                    {
                        if (AreSimilar(_oldNodes.Peek(), _newNodes.Peek()))
                        {
                            return new DiffAction(DiffOp.ReduceBoth, 1);
                        }
                        else
                        {
                            return new DiffAction(DiffOp.ReduceNew, 1);
                        }
                    }
                    else
                    {
                        return new DiffAction(DiffOp.ReplaceOldWithNew, 1);
                    }
                }
                else
                {
                    if (indexOfNewInOld > 0)
                    {
                        return new DiffAction(DiffOp.DeleteOld, indexOfNewInOld);
                    }
                    else if (!oldIsToken)
                    {
                        if (AreSimilar(_oldNodes.Peek(), _newNodes.Peek()))
                        {
                            return new DiffAction(DiffOp.ReduceBoth, 1);
                        }
                        else
                        {
                            return new DiffAction(DiffOp.ReduceOld, 1);
                        }
                    }
                    else
                    {
                        return new DiffAction(DiffOp.ReplaceOldWithNew, 1);
                    }
                }
            }
            else
            {
                // no similarities between first node of old-list in new-list or between first new-node in old-list

                if (!oldIsToken && !newIsToken)
                {
                    // check similarity anyway
                    var sim = GetSimilarity(_oldNodes.Peek(), _newNodes.Peek());
                    if (sim >= Math.Max(_oldNodes.Peek().FullSpan.Length, _newNodes.Peek().FullSpan.Length))
                    {
                        return new DiffAction(DiffOp.ReduceBoth, 1);
                    }
                }

                return new DiffAction(DiffOp.ReplaceOldWithNew, 1);
            }
        }

        private static void ReplaceFirstWithChildren(Stack<SyntaxNodeOrToken> stack)
        {
            var node = stack.Pop();

            int c = 0;
            var children = new SyntaxNodeOrToken[node.ChildNodesAndTokens().Count];
            foreach (var child in node.ChildNodesAndTokens())
            {
                if (child.FullSpan.Length > 0)
                {
                    children[c] = child;
                    c++;
                }
            }

            for (int i = c - 1; i >= 0; i--)
            {
                stack.Push(children[i]);
            }
        }

        private void FindBestMatch(Stack<SyntaxNodeOrToken> stack, in SyntaxNodeOrToken node, out int index, out int similarity, int startIndex = 0)
        {
            index = -1;
            similarity = -1;

            int i = 0;
            foreach (var stackNode in stack)
            {
                if (i >= MaxSearchLength)
                {
                    break;
                }

                if (i >= startIndex)
                {
                    if (AreIdentical(stackNode, node))
                    {
                        var sim = node.FullSpan.Length;
                        if (sim > similarity)
                        {
                            index = i;
                            similarity = sim;
                            return;
                        }
                    }
                    else if (AreSimilar(stackNode, node))
                    {
                        var sim = GetSimilarity(stackNode, node);

                        // Are these really the same? This may be expensive so only check this if
                        // similarity is rated equal to them being identical.
                        if (sim == node.FullSpan.Length && node.IsToken)
                        {
                            if (stackNode.ToFullString() == node.ToFullString())
                            {
                                index = i;
                                similarity = sim;
                                return;
                            }
                        }

                        if (sim > similarity)
                        {
                            index = i;
                            similarity = sim;
                        }
                    }
                    else
                    {
                        // check one level deep inside list node's children
                        int j = 0;
                        foreach (var child in stackNode.ChildNodesAndTokens())
                        {
                            if (j >= MaxSearchLength)
                            {
                                break;
                            }

                            j++;

                            if (AreIdentical(child, node))
                            {
                                index = i;
                                similarity = node.FullSpan.Length;
                                return;
                            }
                            else if (AreSimilar(child, node))
                            {
                                var sim = GetSimilarity(child, node);
                                if (sim > similarity)
                                {
                                    index = i;
                                    similarity = sim;
                                }
                            }
                        }
                    }
                }

                i++;
            }
        }

        private int GetSimilarity(in SyntaxNodeOrToken node1, in SyntaxNodeOrToken node2)
        {
            // count the characters in the common/identical nodes
            int w = 0;
            _nodeSimilaritySet.Clear();
            _tokenTextSimilaritySet.Clear();

            if (node1.IsToken && node2.IsToken)
            {
                var text1 = node1.ToString();
                var text2 = node2.ToString();

                if (text1 == text2)
                {
                    // main text of token is the same
                    w += text1.Length;
                }

                foreach (var tr in node1.GetLeadingTrivia())
                {
                    Debug.Assert(tr.UnderlyingNode is object);
                    _nodeSimilaritySet.Add(tr.UnderlyingNode);
                }

                foreach (var tr in node1.GetTrailingTrivia())
                {
                    Debug.Assert(tr.UnderlyingNode is object);
                    _nodeSimilaritySet.Add(tr.UnderlyingNode);
                }

                foreach (var tr in node2.GetLeadingTrivia())
                {
                    Debug.Assert(tr.UnderlyingNode is object);
                    if (_nodeSimilaritySet.Contains(tr.UnderlyingNode))
                    {
                        w += tr.FullSpan.Length;
                    }
                }

                foreach (var tr in node2.GetTrailingTrivia())
                {
                    Debug.Assert(tr.UnderlyingNode is object);
                    if (_nodeSimilaritySet.Contains(tr.UnderlyingNode))
                    {
                        w += tr.FullSpan.Length;
                    }
                }
            }
            else
            {
                foreach (var n1 in node1.ChildNodesAndTokens())
                {
                    Debug.Assert(n1.UnderlyingNode is object);
                    _nodeSimilaritySet.Add(n1.UnderlyingNode);

                    if (n1.IsToken)
                    {
                        _tokenTextSimilaritySet.Add(n1.ToString());
                    }
                }

                foreach (var n2 in node2.ChildNodesAndTokens())
                {
                    Debug.Assert(n2.UnderlyingNode is object);
                    if (_nodeSimilaritySet.Contains(n2.UnderlyingNode))
                    {
                        w += n2.FullSpan.Length;
                    }
                    else if (n2.IsToken)
                    {
                        var tokenText = n2.ToString();
                        if (_tokenTextSimilaritySet.Contains(tokenText))
                        {
                            w += tokenText.Length;
                        }
                    }
                }
            }

            return w;
        }

        private static bool AreIdentical(in SyntaxNodeOrToken node1, in SyntaxNodeOrToken node2)
        {
            return node1.UnderlyingNode == node2.UnderlyingNode;
        }

        private static bool AreSimilar(in SyntaxNodeOrToken node1, in SyntaxNodeOrToken node2)
        {
            return node1.RawKind == node2.RawKind;
        }

        private readonly struct ChangeRecord
        {
            public readonly TextChangeRange Range;
            public readonly Queue<SyntaxNodeOrToken>? OldNodes;
            public readonly Queue<SyntaxNodeOrToken>? NewNodes;

            internal ChangeRecord(TextChangeRange range, Queue<SyntaxNodeOrToken>? oldNodes, Queue<SyntaxNodeOrToken>? newNodes)
            {
                this.Range = range;
                this.OldNodes = oldNodes;
                this.NewNodes = newNodes;
            }
        }

        private void RecordDeleteOld(int oldNodeCount)
        {
            var oldSpan = GetSpan(_oldNodes, 0, oldNodeCount);
            var removedNodes = CopyFirst(_oldNodes, oldNodeCount);
            RemoveFirst(_oldNodes, oldNodeCount);
            RecordChange(new ChangeRecord(new TextChangeRange(oldSpan, 0), removedNodes, null));
        }

        private void RecordReplaceOldWithNew(int oldNodeCount, int newNodeCount)
        {
            if (oldNodeCount == 1 && newNodeCount == 1)
            {
                // Avoid creating a Queue<T> which we immediately discard in the most common case for old/new counts
                var removedNode = _oldNodes.Pop();
                var oldSpan = removedNode.FullSpan;

                var insertedNode = _newNodes.Pop();
                var newSpan = insertedNode.FullSpan;

                RecordChange(new TextChangeRange(oldSpan, newSpan.Length), removedNode, insertedNode);
            }
            else
            {
                var oldSpan = GetSpan(_oldNodes, 0, oldNodeCount);
                var removedNodes = CopyFirst(_oldNodes, oldNodeCount);
                RemoveFirst(_oldNodes, oldNodeCount);
                var newSpan = GetSpan(_newNodes, 0, newNodeCount);
                var insertedNodes = CopyFirst(_newNodes, newNodeCount);
                RemoveFirst(_newNodes, newNodeCount);
                RecordChange(new ChangeRecord(new TextChangeRange(oldSpan, newSpan.Length), removedNodes, insertedNodes));
            }
        }

        private void RecordInsertNew(int newNodeCount)
        {
            var newSpan = GetSpan(_newNodes, 0, newNodeCount);
            var insertedNodes = CopyFirst(_newNodes, newNodeCount);
            RemoveFirst(_newNodes, newNodeCount);
            int start = _oldNodes.Count > 0 ? _oldNodes.Peek().Position : _oldSpan.End;
            RecordChange(new ChangeRecord(new TextChangeRange(new TextSpan(start, 0), newSpan.Length), null, insertedNodes));
        }

        private void RecordChange(ChangeRecord change)
        {
            if (_changes.Count > 0)
            {
                var last = _changes[_changes.Count - 1];
                if (last.Range.Span.End == change.Range.Span.Start)
                {
                    // merge changes...
                    _changes[_changes.Count - 1] = new ChangeRecord(
                        new TextChangeRange(new TextSpan(last.Range.Span.Start, last.Range.Span.Length + change.Range.Span.Length), last.Range.NewLength + change.Range.NewLength),
                        Combine(last.OldNodes, change.OldNodes),
                        Combine(last.NewNodes, change.NewNodes));
                    return;
                }

                Debug.Assert(change.Range.Span.Start >= last.Range.Span.End);
            }

            _changes.Add(change);
        }

        private void RecordChange(TextChangeRange textChangeRange, in SyntaxNodeOrToken removedNode, SyntaxNodeOrToken insertedNode)
        {
            if (_changes.Count > 0)
            {
                var last = _changes[_changes.Count - 1];
                if (last.Range.Span.End == textChangeRange.Span.Start)
                {
                    // merge changes...
                    last.OldNodes?.Enqueue(removedNode);
                    last.NewNodes?.Enqueue(insertedNode);
                    _changes[_changes.Count - 1] = new ChangeRecord(
                        new TextChangeRange(new TextSpan(last.Range.Span.Start, last.Range.Span.Length + textChangeRange.Span.Length), last.Range.NewLength + textChangeRange.NewLength),
                        last.OldNodes ?? CreateQueue(removedNode),
                        last.NewNodes ?? CreateQueue(insertedNode));
                    return;
                }

                Debug.Assert(textChangeRange.Span.Start >= last.Range.Span.End);
            }

            _changes.Add(new ChangeRecord(textChangeRange, CreateQueue(removedNode), CreateQueue(insertedNode)));

            // Local Functions
            Queue<SyntaxNodeOrToken> CreateQueue(SyntaxNodeOrToken nodeOrToken)
            {
                var queue = new Queue<SyntaxNodeOrToken>();
                queue.Enqueue(nodeOrToken);
                return queue;
            }
        }

        private static TextSpan GetSpan(Stack<SyntaxNodeOrToken> stack, int first, int length)
        {
            int start = -1, end = -1, i = 0;
            foreach (var n in stack)
            {
                if (i == first)
                {
                    start = n.Position;
                }

                if (i == first + length - 1)
                {
                    end = n.EndPosition;
                    break;
                }

                i++;
            }

            Debug.Assert(start >= 0);
            Debug.Assert(end >= 0);

            return TextSpan.FromBounds(start, end);
        }

        private static TextSpan GetSpan(Queue<SyntaxNodeOrToken> queue, int first, int length)
        {
            int start = -1, end = -1, i = 0;
            foreach (var n in queue)
            {
                if (i == first)
                {
                    start = n.Position;
                }

                if (i == first + length - 1)
                {
                    end = n.EndPosition;
                    break;
                }

                i++;
            }

            Debug.Assert(start >= 0);
            Debug.Assert(end >= 0);

            return TextSpan.FromBounds(start, end);
        }

        private static Queue<SyntaxNodeOrToken>? Combine(Queue<SyntaxNodeOrToken>? first, Queue<SyntaxNodeOrToken>? next)
        {
            if (first == null || first.Count == 0)
            {
                return next;
            }

            if (next == null || next.Count == 0)
            {
                return first;
            }

            foreach (var nodeOrToken in next)
            {
                first.Enqueue(nodeOrToken);
            }

            return first;
        }

        private static Queue<SyntaxNodeOrToken>? CopyFirst(Stack<SyntaxNodeOrToken> stack, int n)
        {
            if (n == 0)
            {
                return null;
            }

            var queue = new Queue<SyntaxNodeOrToken>(n);

            int remaining = n;
            foreach (var node in stack)
            {
                if (remaining == 0)
                {
                    break;
                }

                queue.Enqueue(node);
                remaining--;
            }

            return queue;
        }

        private static void RemoveFirst(Stack<SyntaxNodeOrToken> stack, int count)
        {
            for (int i = 0; i < count; ++i)
            {
                stack.Pop();
            }
        }

        private readonly struct ChangeRangeWithText
        {
            public readonly TextChangeRange Range;
            public readonly string? NewText;

            public ChangeRangeWithText(TextChangeRange range, string? newText)
            {
                this.Range = range;
                this.NewText = newText;
            }
        }

        private List<ChangeRangeWithText> ReduceChanges(List<ChangeRecord> changeRecords)
        {
            var textChanges = new List<ChangeRangeWithText>(changeRecords.Count);

            var oldText = new StringBuilder();
            var newText = new StringBuilder();

            foreach (var cr in changeRecords)
            {
                // try to reduce change range by finding common characters
                if (cr.Range.Span.Length > 0 && cr.Range.NewLength > 0)
                {
                    var range = cr.Range;

                    CopyText(cr.OldNodes, oldText);
                    CopyText(cr.NewNodes, newText);

                    int commonLeadingCount;
                    int commonTrailingCount;
                    GetCommonEdgeLengths(oldText, newText, out commonLeadingCount, out commonTrailingCount);

                    // did we have any common leading or trailing characters between the strings?
                    if (commonLeadingCount > 0 || commonTrailingCount > 0)
                    {
                        range = new TextChangeRange(
                            new TextSpan(range.Span.Start + commonLeadingCount, range.Span.Length - (commonLeadingCount + commonTrailingCount)),
                            range.NewLength - (commonLeadingCount + commonTrailingCount));

                        if (commonTrailingCount > 0)
                        {
                            newText.Remove(newText.Length - commonTrailingCount, commonTrailingCount);
                        }

                        if (commonLeadingCount > 0)
                        {
                            newText.Remove(0, commonLeadingCount);
                        }
                    }

                    // only include adjusted change if there is still a change
                    if (range.Span.Length > 0 || range.NewLength > 0)
                    {
                        textChanges.Add(new ChangeRangeWithText(range, _computeNewText ? newText.ToString() : null));
                    }
                }
                else
                {
                    // pure inserts and deletes
                    textChanges.Add(new ChangeRangeWithText(cr.Range, _computeNewText ? GetText(cr.NewNodes) : null));
                }
            }

            return textChanges;
        }

        private static void GetCommonEdgeLengths(StringBuilder oldText, StringBuilder newText, out int commonLeadingCount, out int commonTrailingCount)
        {
            int maxChars = Math.Min(oldText.Length, newText.Length);

            commonLeadingCount = 0;
            for (; commonLeadingCount < maxChars; commonLeadingCount++)
            {
                if (oldText[commonLeadingCount] != newText[commonLeadingCount])
                {
                    break;
                }
            }

            // don't double count the chars we matched at the start of the strings
            maxChars = maxChars - commonLeadingCount;

            commonTrailingCount = 0;
            for (; commonTrailingCount < maxChars; commonTrailingCount++)
            {
                if (oldText[oldText.Length - commonTrailingCount - 1] != newText[newText.Length - commonTrailingCount - 1])
                {
                    break;
                }
            }
        }

        private static string GetText(Queue<SyntaxNodeOrToken>? queue)
        {
            if (queue == null || queue.Count == 0)
            {
                return string.Empty;
            }

            var span = GetSpan(queue, 0, queue.Count);
            var builder = new StringBuilder(span.Length);

            CopyText(queue, builder);

            return builder.ToString();
        }

        private static void CopyText(Queue<SyntaxNodeOrToken>? queue, StringBuilder builder)
        {
            builder.Length = 0;

            if (queue != null && queue.Count > 0)
            {
                var writer = new System.IO.StringWriter(builder);

                foreach (var n in queue)
                {
                    n.WriteTo(writer);
                }

                writer.Flush();
            }
        }
    }
}


text:
define(["app/ecs/component"], function(Component) {
    "use strict";

    var PlayerController = Component.extend({
        name: "playercontroller",
        init: function (playerName, keyBindings) {
            this.actions = {
                "moveup": {
                    "delay": 0
                },
                "moveleft": {
                    "delay": 0
                },
                "movedown": {
                    "delay": 0
                },
                "moveright": {
                    "delay": 0
                },
                "shoot": {
                    "delay": 500
                }
            };
            this.playerName = playerName;
            this.keyBindings = keyBindings;
        }
    });

    return PlayerController;
});


text:
using System;
using System.IO;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace CocosSharp
{

    public enum CCRenderTargetUsage
    {
        DiscardContents,
        PreserveContents,
        PlatformContents
    }

    public partial class CCRenderTexture : CCNode
    {

        [Flags]
        enum ClearFlags
        {
            None           =           0x0,
            ColorBuffer    =           0x1,
            DepthBuffer    =           0x2,
            StencilBuffer  =           0x4,
            All            = DepthBuffer | StencilBuffer | ColorBuffer
        }

        bool firstUsage = true;
        RenderTarget2D renderTarget2D;

        #region Properties

        public CCSprite Sprite { get; set; }
        public CCTexture2D Texture { get; private set; }
        protected CCSurfaceFormat PixelFormat { get; private set; }

        #endregion Properties

        CCColor4B beginClearColor = CCColor4B.Transparent;
        float beginDepthValue = 0;
        int beginStencilValue = 0;

        ClearFlags clearFlags = ClearFlags.None;

        #region Constructors

        public CCRenderTexture()
        {
            PixelFormat = CCSurfaceFormat.Color;
        }

        public CCRenderTexture(CCSize contentSize, CCSize textureSizeInPixels,
            CCSurfaceFormat colorFormat=CCSurfaceFormat.Color,
            CCDepthFormat depthFormat=CCDepthFormat.None,
            CCRenderTargetUsage usage=CCRenderTargetUsage.DiscardContents)
        {
            int textureWidth = (int)textureSizeInPixels.Width;
            int textureHeight = (int)textureSizeInPixels.Height;

            firstUsage = true;
            renderTarget2D = CCDrawManager.SharedDrawManager.CreateRenderTarget(textureWidth, textureHeight, colorFormat, depthFormat, usage);

            Texture = new CCTexture2D(renderTarget2D, colorFormat, true, false);
            Texture.IsAntialiased = false;

            Sprite = new CCSprite(Texture);
            Sprite.ContentSize = contentSize;
            Sprite.BlendFunc = CCBlendFunc.AlphaBlend;

            // Make sure we set our content size or AnchorPoint will not work correctly
            ContentSize = textureSizeInPixels;

            AddChild(Sprite);
        }

        #endregion Constructors

        public virtual void Begin()
        {
            CCDrawManager drawManager = CCDrawManager.SharedDrawManager;

            // Save the current matrix
            drawManager.PushMatrix();

//            Matrix projection = Matrix.CreateOrthographicOffCenter(
//                -1.0f / widthRatio, 1.0f / widthRatio,
//                -1.0f / heightRatio, 1.0f / heightRatio,
//                -1, 1
//            );
//
//            drawManager.MultMatrix(ref projection);

            drawManager.SetRenderTarget(Texture);

            if (firstUsage)
            {
                drawManager.Clear(beginClearColor);
                firstUsage = false;
            }
        }

        public void BeginWithClear(float r, float g, float b, float a)
        {
            Begin();
            beginClearColor = new CCColor4B(r, g, b, a);
            clearFlags = ClearFlags.ColorBuffer;
            CCDrawManager.SharedDrawManager.Clear(beginClearColor);
        }

        public void BeginWithClear(float r, float g, float b, float a, float depthValue)
        {
            Begin();
            beginClearColor = new CCColor4B(r, g, b, a);
            beginDepthValue = depthValue;
            clearFlags = ClearFlags.ColorBuffer | ClearFlags.DepthBuffer;
            CCDrawManager.SharedDrawManager.Clear(beginClearColor, depthValue);
        }

		public void BeginWithClear(float r, float g, float b, float a, float depthValue, int stencilValue)
		{
			Begin();
            beginClearColor = new CCColor4B(r, g, b, a);
            beginDepthValue = depthValue;
            beginStencilValue = stencilValue;
            clearFlags = ClearFlags.All;
			CCDrawManager.SharedDrawManager.Clear(beginClearColor, depthValue, stencilValue);
		}

		public void BeginWithClear(CCColor4B col)
		{
			Begin();
            beginClearColor = col;
            clearFlags = ClearFlags.ColorBuffer;
			CCDrawManager.SharedDrawManager.Clear(col);
		}

		public void BeginWithClear(CCColor4B col, float depthValue)
		{
			Begin();
            beginClearColor = col;
            beginDepthValue = depthValue;
            clearFlags = ClearFlags.ColorBuffer | ClearFlags.DepthBuffer;

			CCDrawManager.SharedDrawManager.Clear(col, depthValue);
		}

		public void BeginWithClear(CCColor4B col, float depthValue, int stencilValue)
		{
			Begin();
            beginClearColor = col;
            beginDepthValue = depthValue;
            beginStencilValue = stencilValue;
            clearFlags = ClearFlags.All;
			CCDrawManager.SharedDrawManager.Clear(col, depthValue, stencilValue);
		}

        public void ClearDepth(float depthValue)
        {
            Begin();
            beginDepthValue = depthValue;
            clearFlags |= ClearFlags.DepthBuffer;
            CCDrawManager.SharedDrawManager.Clear(ClearOptions.DepthBuffer, Microsoft.Xna.Framework.Color.White, depthValue, 0);
            End();
        }

        public void ClearStencil(int stencilValue)
        {
            Begin();
            beginStencilValue = stencilValue;
            clearFlags |= ClearFlags.StencilBuffer;
            CCDrawManager.SharedDrawManager.Clear(ClearOptions.Stencil, Microsoft.Xna.Framework.Color.White, 1, stencilValue);
            End();
        }

        public void Clear(float r, float g, float b, float a)
        {
            Clear(new CCColor4B(r, g, b, a));
        }

        public void Clear(CCColor4B col)
        {
            Begin();
            beginClearColor = col;
            clearFlags |= ClearFlags.ColorBuffer;
            CCDrawManager.SharedDrawManager.Clear(beginClearColor);
            End();
        }

        void Clear(ClearFlags clearFlags, CCColor4B color, float depth, int stencil)
        {
            if (clearFlags.HasFlag(ClearFlags.ColorBuffer))
                CCDrawManager.SharedDrawManager.Clear(color);

            if (clearFlags.HasFlag(ClearFlags.DepthBuffer))
                CCDrawManager.SharedDrawManager.Clear(ClearOptions.DepthBuffer, Microsoft.Xna.Framework.Color.White, depth, 0);

            if (clearFlags.HasFlag(ClearFlags.StencilBuffer))
                CCDrawManager.SharedDrawManager.Clear(ClearOptions.Stencil, Microsoft.Xna.Framework.Color.White, 1, stencil);

        }

        public virtual void End()
        {
            CCDrawManager.SharedDrawManager.PopMatrix();

            CCDrawManager.SharedDrawManager.SetRenderTarget((CCTexture2D) null);
        }

        public override void Visit()
        {

            if (!Visible)
                return;

            Sprite.XnaLocalMatrix = XnaLocalMatrix;
            Sprite.Visit();
            Draw();

        }

        public bool AutoDraw = false;
        protected override void Draw()
        {
            if (AutoDraw)
            {
                Begin();

                //Begin will create a render group using new render target
                Clear(clearFlags, beginClearColor, beginDepthValue, beginStencilValue);

                //! make sure all children are drawn
                SortAllChildren();

                foreach(var child in Children)
                {
                    if (child != Sprite)
                        child.Visit();
                }

                //End will pop the current render group
                End();
            }

            //base.Draw();
        }

        public bool SaveToStream(Stream stream, CCImageFormat format)
        {
            if (format == CCImageFormat.Png)
            {
                Texture.SaveAsPng(stream, Texture.PixelsWide, Texture.PixelsHigh);
            }
            else if (format == CCImageFormat.Jpg)
            {
                Texture.SaveAsJpeg(stream, Texture.PixelsWide, Texture.PixelsHigh);
            }
            else
            {
                return false;
            }

            return true;
        }
    }
}


text:
<!-- TODO hardcode the required JS because on 2016-02-01 GitHub pages migrated to jekyll 3 and broke this template -->
<script src="/js/jquery-1.11.2.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
<script src="/js/main.js"></script>
<!-- end TODO -->

{% if page.common-ext-js %}
  {% for js in page.common-ext-js %}
	<script src="{{ js }}"></script>
  {% endfor %}
{% endif %}

{% if page.common-js %}
  {% for js in page.common-js %}
	<script src="{{ js | prepend: site.baseurl | replace: '//', '/' }}"></script>
  {% endfor %}
{% endif %}

{% if page.ext-js %}
  {% for js in page.ext-js %}
	<script src="{{ js }}"></script>
  {% endfor %}
{% endif %}

{% if page.js %}
  {% for js in page.js %}
	<script src="{{ js | prepend: site.baseurl | replace: '//', '/' }}"></script>
  {% endfor %}
{% endif %}

{% include google_analytics.html %}


text:
package voldemort.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

import voldemort.VoldemortException;

/**
 * Testing on EC2 requires quite a few configuration properties; these are
 * provided in a *.properties file, the path of which is provided in the
 * "ec2PropertiesFile" System property. Below is a table of the properties:
 *
 *

 * Name
 * Description
 *

 * ec2AccessId
 * EC2 access ID, provided by Amazon
 *

 *

 * ec2SecretKey
 * EC2 secret key, provided by Amazon
 *

 *

 * ec2Ami
 * ID of the EC2 AMI used for the instances that are started
 *

 *

 * ec2KeyPairId
 * Key pair ID
 *

 *

 * ec2SshPrivateKeyPath
 * SSH private key path to key used to connect to instances (optional)
 *

 *

 * ec2HostUserId
 * User ID on the hosts; for EC2 this is usually "root"
 *

 *

 * ec2VoldemortRootDirectory
 * Root directory on remote instances that points to the the Voldemort
 * "distribution" directory; relative to the host user ID's home directory. For
 * example, if the remote user's home directory is /root and the Voldemort
 * distribution directory is /root/voldemort, ec2VoldemortRootDirectory would be
 * "voldemort"
 *

 *

 * ec2VoldemortHomeDirectory
 * Home directory on remote instances that points to the configuration
 * directory, relative to the host user ID's home directory. For example, if the
 * remote user's home directory is /root and the Voldemort configuration
 * directory is /root/voldemort/config/single_node_cluster,
 * ec2VoldemortHomeDirectory would be "voldemort/config/single_node_cluster"
 *

 *

 * ec2SourceDirectory
 * Source directory on local machine from which to copy the Voldemort
 * "distribution" to the remote hosts; e.g. "/home/kirk/voldemortdev/voldemort"
 *

 *

 * ec2ParentDirectory
 * Parent directory on the remote machine into which to copy the
 * Voldemort "distribution". For example, if the remote user's home directory is
 * /root and the Voldemort distribution directory is /root/voldemort,
 * ec2ParentDirectory would be "." or "/root".
 *

 *

 * ec2ClusterXmlFile
 * Local path to which cluster.xml will be written with EC2 hosts;
 * this needs to live under the ec2SourceDirectory's configuration directory
 * that is copied to the remote host.
 *

 *

 * ec2InstanceCount
 * The number of instances to create.
 *

 *

 * ec2InstanceIdFile
 * File in which to list the instances that are created; used by external
 * tools to stop instances in case of catastrophic test failure
 *

 *

 *
 */

public class Ec2RemoteTestConfig extends RemoteTestConfig {

    protected String accessId;

    protected String secretKey;

    protected String ami;

    protected String keyPairId;

    protected int instanceCount;

    protected File instanceIdFile;

    public Ec2RemoteTestConfig() {
        Properties properties = getEc2Properties();
        init(properties);
    }

    public String getAccessId() {
        return accessId;
    }

    public void setAccessId(String accessId) {
        this.accessId = accessId;
    }

    public String getSecretKey() {
        return secretKey;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    public String getAmi() {
        return ami;
    }

    public void setAmi(String ami) {
        this.ami = ami;
    }

    public String getKeyPairId() {
        return keyPairId;
    }

    public void setKeyPairId(String keyPairId) {
        this.keyPairId = keyPairId;
    }

    public int getInstanceCount() {
        return instanceCount;
    }

    public void setInstanceCount(int instanceCount) {
        this.instanceCount = instanceCount;
    }

    public File getInstanceIdFile() {
        return instanceIdFile;
    }

    public void setInstanceIdFile(File instanceIdFile) {
        this.instanceIdFile = instanceIdFile;
    }

    protected void init(Properties properties) {
        setAccessId(properties.getProperty("ec2AccessId"));
        setSecretKey(properties.getProperty("ec2SecretKey"));
        setAmi(properties.getProperty("ec2Ami"));
        setKeyPairId(properties.getProperty("ec2KeyPairId"));
        setHostUserId(properties.getProperty("ec2HostUserId"));
        setSshPrivateKey(getFileProperty(properties, "ec2SshPrivateKeyPath"));
        setVoldemortRootDirectory(properties.getProperty("ec2VoldemortRootDirectory"));
        setVoldemortHomeDirectory(properties.getProperty("ec2VoldemortHomeDirectory"));
        setSourceDirectory(getFileProperty(properties, "ec2SourceDirectory"));
        setParentDirectory(properties.getProperty("ec2ParentDirectory"));
        setClusterXmlFile(getFileProperty(properties, "ec2ClusterXmlFile"));
        setInstanceCount(getIntProperty(properties, "ec2InstanceCount"));
        setInstanceIdFile(getFileProperty(properties, "ec2InstanceIdFile"));
    }

    protected File getFileProperty(Properties properties, String propertyName) {
        String value = properties.getProperty(propertyName);
        return value != null ? new File(value) : null;
    }

    protected int getIntProperty(Properties properties, String propertyName) {
        String value = properties.getProperty(propertyName);
        return value != null ? Integer.parseInt(value) : 0;
    }

    protected int getIntProperty(Properties properties, String propertyName, int defaultValue) {
        String value = properties.getProperty(propertyName);
        return value != null ? Integer.parseInt(value) : defaultValue;
    }

    protected Properties getEc2Properties() {
        String propertiesFileName = System.getProperty("ec2PropertiesFile");

        List<String> requireds = getRequiredPropertyNames();

        if(propertiesFileName == null)
            throw new VoldemortException("ec2PropertiesFile system property must be defined that "
                                         + "provides the path to file containing the following "
                                         + "required properties: "
                                         + StringUtils.join(requireds, ", "));

        Properties properties = new Properties();
        InputStream in = null;

        try {
            in = new FileInputStream(propertiesFileName);
            properties.load(in);
        } catch(IOException e) {
            throw new VoldemortException(e);
        } finally {
            IOUtils.closeQuietly(in);
        }

        for(String required: requireds) {
            // Allow system properties to override
            if(System.getProperties().containsKey(required))
                properties.put(required, System.getProperty(required));

            if(!properties.containsKey(required))
                throw new VoldemortException("Required properties: "
                                             + StringUtils.join(requireds, ", ") + "; missing "
                                             + required);
        }

        return properties;
    }

    protected List<String> getRequiredPropertyNames() {
        // There's a reason we're making two lists: Arrays.asList makes an
        // immutable list. However, we want to return a mutable list to the
        // caller as subclasses may modify the list "in place."
        return new ArrayList<String>(Arrays.asList("ec2AccessId",
                                                   "ec2SecretKey",
                                                   "ec2Ami",
                                                   "ec2KeyPairId",
                                                   "ec2HostUserId",
                                                   "ec2VoldemortRootDirectory",
                                                   "ec2VoldemortHomeDirectory",
                                                   "ec2SourceDirectory",
                                                   "ec2ParentDirectory",
                                                   "ec2ClusterXmlFile",
                                                   "ec2InstanceCount",
                                                   "ec2InstanceIdFile"));
    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>java.lang.ref Class Hierarchy (Java Platform SE 7 )</title>
<meta name="date" content="2014-12-18">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 7

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package java.lang.ref

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

java.lang.ref.Reference<T>

java.lang.ref.PhantomReference<T>

java.lang.ref.SoftReference<T>

java.lang.ref.WeakReference<T>

java.lang.ref.ReferenceQueue<T>

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 7

Prev

Next

Frames

No Frames

All Classes

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
package com.kickstarter.libs.utils;

public final class ProgressBarUtils {
  private ProgressBarUtils() {}

  /**
   * Clamps a value and converts it to an integer, ready for use by setProgress.
   */
  public static int progress(final float value) {
    return Math.round(Math.min(100.0f, value));
  }
}


text:
<?php

namespace app\facades\common;

use Yii;
use \app\models\EmailHistory;
use app\web\util\Codes\LookupCodes;
use yii\web\UploadedFile;

/**
 * This is a facades class for mail module.
 */
class MailFacade {

    /*
     * function for sending generated mail to queue
     * @author: Waseem
     */

    public function sendEmail($emailObj, $recepient, $eventId, $langId, $sender=NULL, $immiate) {
        $att = '';
        $attachment = '';
        $lookupObj = \app\models\Lookups::find()
                    ->select(['parent_id', 'id'])
                    ->where(['id'=>$eventId])->one();

        if($lookupObj){
            if($lookupObj->parent_id != ''){
                $sender = $lookupObj->parent->value;
            }
        }

        if($sender == ""){
            $sender = Yii::$app->params['configurations']['ADMIN_EMAIL'];
        }

        $template = CommonFacade::getEmailTemplate($eventId, $langId);

        if($template){
            $subject = $template['subject'];
            $content = $template['content'];
            if($template['attachment']){
                $attachment = $template['attachment'];
            }
        } else {
            $xml = CommonFacade::getEmailXml($eventId);
            $subject = $template['subject'];
            $content = $template['content'];
        }

        if($attachment != ''){
            $att =  \Yii::getAlias('@webroot').'/uploads/'.$attachment;
        }

        foreach ($emailObj as $key => $val) { //replacing placeholders with param values
            $content = str_replace('[['.$key.']]', $val, $content);
        }

        $mailMethod = \app\models\Configurations::find()->select(['value'])->where(['short_code'=>'MAIL_METHOD'])->one();

        $mailHistory = new EmailHistory();
        $mailHistory->email_id = $recepient;
        $mailHistory->event_id = $eventId;
        $mailHistory->status = LookupCodes::L_EMAIL_STATUS_PENDING;
        $mailHistory->subject = $subject;
        $mailHistory->mail_method = $mailMethod->value;
        $mailHistory->body = $content;
        if($attachment != ''){
            $mailHistory->attachment = $attachment;
        }
        $mailHistory->attempts = 0;
        $mailHistory->sender_email = $sender;
        $mailHistory->sent_on = gmdate('Y-m-d h:i:s', time());

        if($mailHistory->save()){

            /*
            $mailHistory->attempts = $mailHistory->attempts+1;

            if($mailMethod->value == LookupCodes::L_MAIL_METHOD_SMTP){

                $host = Yii::$app->params['configurations']['SMTP_HOST'];
                $port = Yii::$app->params['configurations']['SMTP_PORT'];
                $uname = Yii::$app->params['configurations']['SMTP_USER'];
                $pswd = Yii::$app->params['configurations']['SMTP_PASSWORD'];
                $encrp = Yii::$app->params['configurations']['SMTP_ENCRYPTION_TYPE'];

                Yii::$app->smtp->setMailType('SMTP');
                Yii::$app->smtp->setHost($host);
                Yii::$app->smtp->setUname($uname);
                Yii::$app->smtp->setPassd($pswd);
                Yii::$app->smtp->setEncType($encrp);
                Yii::$app->smtp->setServerPort($port);
                Yii::$app->smtp->configSet();
                Yii::$app->smtp->setFrom(array($sender));

                if($att != ''){
                    try{
                        Yii::$app->smtp->SendMail($sender, $recepient, $subject, $content, '', '', array($att));
                        $mailHistory->status = LookupCodes::L_EMAIL_STATUS_SENT;
                    } catch (\Swift_SwiftException $e) {
                        Yii::error($e);
                        $mailHistory->status = LookupCodes::L_EMAIL_STATUS_FAILED;
                        return true;
                    }
                } else {
                    try{
                        Yii::$app->smtp->SendMail($sender, $recepient, $subject, $content);
                        $mailHistory->status = LookupCodes::L_EMAIL_STATUS_SENT;
                    } catch (\Swift_SwiftException $e) {
                        Yii::error($e);
                        $mailHistory->status = LookupCodes::L_EMAIL_STATUS_FAILED;
                        return true;
                    }
                }

            } else if($mailMethod->value == LookupCodes::L_MAIL_METHOD_SES){

                Yii::$app->ses->access_key = Yii::$app->params['configurations']['AWS_ACCESS_KEY'];
                Yii::$app->ses->secret_key = Yii::$app->params['configurations']['AWS_SECRET_KEY'];
                Yii::$app->ses->host = Yii::$app->params['configurations']['AWS_HOST_NAME'];

                if($att != ''){
                    try{
                        Yii::$app->ses->compose()->setFrom($sender)->setTo($recepient)->setSubject($subject)->setHtmlBody($content)->attach($att)->send();
                        $mailHistory->status = LookupCodes::L_EMAIL_STATUS_SENT;
                    } catch (\yii\base\Exception $e) {
                        Yii::error($e);
                        $mailHistory->status = LookupCodes::L_EMAIL_STATUS_FAILED;
                        return true;
                    }
                } else {
                    try{
                        Yii::$app->ses->compose()->setFrom($sender)->setTo($recepient)->setSubject($subject)->setHtmlBody($content)->send();
                        $mailHistory->status = LookupCodes::L_EMAIL_STATUS_SENT;
                    } catch (\yii\base\Exception $e) {
                        Yii::error($e);
                        $mailHistory->status = LookupCodes::L_EMAIL_STATUS_FAILED;
                        return true;
                    }
                }

            }
            $mailHistory->save();
             *
             */
            $status = true;
        } else {

            $status = false;
        }
        return $status;
    }

}

//Yii::$app->ses->compose('contact/html', ['contactForm' => 'Test'])

/*
            try {
                Yii::$app->mailer->compose()
                ->setFrom($mailHistory->sender_email)
                ->setTo($mailHistory->email_id)
                ->setSubject($mailHistory->subject)
                ->setHtmlBody($mailHistory->body)
                ->send();

                $mailHistory->attempts = $mailHistory->attempts+1;
                $mailHistory->status = 400002;
            } catch (\Swift_SwiftException $e) {
                $mailHistory->status = 400003;
            }
            */


text:
using NewsSite.Core.Application;
using NewsSite.Core.Database.Tables;
using NewsSite.Data.UnitOfWork;
using NewsSite.Service.CategoryServices;
using NewsSite.Service.PostServices;
using NewsSite.Web.Framework.Controllers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace NewsSite.Web.Controllers
{
    public class HomeController : PublicController
    {
        private readonly IPostService _postService;
        private readonly ICategoryService _categoryService;

        public HomeController(IUnitOfWork uow, IPostService postService, ICategoryService categoryService)
            : base(uow)
        {
            _postService = postService;
            _categoryService = categoryService;
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult _CategoryPosts()
        {
            var categories = _categoryService.GetAll()
                .OrderBy(x => x.Order);

            return PartialView(categories);
        }

        public ActionResult _SliderPosts()
        {
            var posts = _postService.GetAll()
                .OrderByDescending(x => x.Id)
                .Take(7)
                .ToList();

            return PartialView(posts);
        }

        public ActionResult _MostReaded()
        {
            var posts = _postService.GetAll()
                .OrderByDescending(x => x.ReadCount)
                .Take(5);

            return PartialView(posts);
        }

        public ActionResult _CategoriesMenu()
        {
            var categories = new List<Category>();

            if (Session[Keys.Categories] == null)
            {
                categories = _categoryService.GetAll().ToList();
                Session[Keys.Categories] = categories;
            }

            return PartialView();
        }

        public ActionResult Contact()
        {
            return View();
        }
    }
}


text:
HTML video 1

You can link tags in HTML
 means anchor
requires attribute --->href="url.com"

src attribute goes with img tag
no closing tag for img

ex

ordered/unordered lists

Unordered List

List

Ordered Lis

What is special about HTML5?
additional tags like aside and footer -
checkout html5doctor element index for reference

table rows and shit

metatags go in head - used to provide additional info
description tag useful to use

ex
<meta name="something" content="index.whatever" >

accessibility

id tags used for styling, and help with automated testing
some robot that can check for functionality, javascript

Mozilla design network
check it out

------------------------------------------------------------
HTML primer video
checkout jkymarsh.com to see the host's tools and projects

markup language used to structure web pages
interpreted by browser
semantics - HTML elements have meaning associated with them, and their placement and structure within the page further leverages this meaning.

Noice

html5boilerplate.com - great starting place for every new HTML - you can pull it straight off Github

*meta, link, img tags have no closing tags

comments in html

Note the above syntax

HTML created in 1990 by Tim Berners-Lee, inventor of the WWW for CERN reasearchers as well as both the browser and server technology - originally had only 18 tags - no audio/video/images

--Modern HTML
-100+ tags, some self-closing
-Variety of required and optional atributes
-Support for stylesheet languages
-support for advanced media objects
-ability to store arbitrary data
-advanced form capabilities - filling out forms
-enhanced semantics via new HTML5 tags and attributes

twitter, for example, has about 8000 lines of code for a regular page

** attributes in sublime show up lime green

to understand HTML, think about

#1 - structure - a tree of nested nodes (tags)
#2 - tags themselves - familiarizing yourself with them
#3 - attributes - both concepts and examples
required to hareness the power of HTML

Other Considerations :
-CSS
-accessibility (visible v. audible websites)
-Cross-browser support and limitations - tricky tricky
-Form design and implemenation
-Mobile and responsive design
-HTML5 and CSS3 features and capabilities

checkout HTML5boilerplate.com for a good starting template

checkout source code for websites as you go about your day, both good and bad

---------------------------------------------------------------

Design stuffs

1.plan (at least a little bit)
--intent--
--content--
get an idea of what info you want out there/different ways to display that shit
think about what content in first and what will be secondary
--CREATE A SITEMAP--
looks like a chart that shows each part you want to display
--sketching--
just a way to visualize - often done on a whiteboard
--wireframes--
make it clear that this is not the final design - balsamiq.com - just how the pages flow together
--establish hierarchy--
how important are the elements?

"hierarchy is also about storytelling; it's about our user's jorney through the website and the user flow we create" -Rachel Shillcock

on emotional colors check out tuts.com -maybe -
colour lovers - predetermined colors with hex values
color hex - pick out your own colors and provides you with more
kuler - awesome one from adobe - you can even import a pic and get info
paletton

google fonts
typecast - helps you pick
size/contrast/space
contrast ratio

Modular scale
said to increase legibility/readability
applies common ratios

trust your eyes

responsive type - for making sure everything works no matter the size of he screen

imagery - stock images - consider licensing

always think back to tone and intent

#2 - Iterate
what minimum amount of features make this a working product?
keeps you from rabbit hole

--USE THE INSPECTOR!--
important - doing the changes in the browser inspector before you add to your code WORKS WAY BETTER - it even has an emulator to tell you how things would look on different devices

--FRAMEWORKS--
include from beginning
additional style sheets will customize further

cheat sheet on responsive web design - find it
relative units - use them - automatically scales in response to different sizes of mobile devices etc

links to this talk


text:
/*
===============================================================================
A C++ port of a speed-improved simplex noise algorithm for 2D in Java.

Based on example code by Stefan Gustavson (stegu@itn.liu.se).
Optimisations by Peter Eastman (peastman@drizzle.stanford.edu).
Better rank ordering method by Stefan Gustavson in 2012.
C++ port and minor type and algorithm changes by Josh Koch (jdk1337@gmail.com).

This could be speeded up even further, but it's useful as it is.

Version 2012-04-12

The original Java code was placed in the public domain by its original author,
Stefan Gustavson. You may use it as you see fit,
but attribution is appreciated.
===============================================================================
*/

#ifndef __SIMPLEX_H__
#define __SIMPLEX_H__

#include <cstdint>

class Grad {
public:
    Grad( int8_t x, int8_t y, int8_t z ) : x(x), y(y), z(z) {}
    int8_t x, y, z;
};

class Simplex {
public:
    // Initialize permutation arrays
    static void init();
    // 2D simplex noise
    static double noise( double xin, double yin );

private:
    static int32_t fastFloor( double x );
    static double dot( const Grad& g, double x, double y );
    static const double F2;
    static const double G2;
    static const Grad grad3[12];
    static const uint8_t p[256];
    static uint8_t perm[512];
    static uint8_t permMod12[512];
};

#endif


text:
require "minitest/autorun"
require "webmock/minitest"

unless ENV["CI"]
  socket = Socket.new(:INET, :STREAM, 0)
  socket.bind(Addrinfo.tcp("127.0.0.1", 0))
  port = socket.local_address.ip_port
  socket.close

  ENV["REDIS_URL"] = "redis://localhost:%d" % port
  redis_test_instance = IO.popen("redis-server --port %d --save '' --appendonly no" % port)

  Minitest.after_run do
    Process.kill("INT", redis_test_instance.pid)
  end
end

require "sidekiq/testing"
Sidekiq::Testing.fake!
Sidekiq.logger.level = Logger::WARN

require_relative "../lib/image"
require_relative "../lib/refresher"

def flush
  Sidekiq::Worker.clear_all
  Sidekiq.redis do |redis|
    redis.flushdb
  end
end

def support_file(file_name)
  path = File.join Dir.tmpdir, SecureRandom.hex
  FileUtils.cp File.join("test/support/www", file_name), path
  path
end

def stub_request_file(file, url, options = {})
  defaults = {body: File.new(support_file(file)), status: 200}
  stub_request(:get, url)
    .to_return(defaults.merge(options))
end

def load_xml
  File.read("test/support/www/atom.xml")
end

def random_string
  (0...50).map { ("a".."z").to_a[rand(26)] }.join
end

def aws_copy_body
  <<~EOT
    <?xml version="1.0" encoding="UTF-8"?>
    <CopyObjectResult>
       <ETag>string</ETag>
       <LastModified>Tue, 02 Mar 2021 12:58:45 GMT</LastModified>
    </CopyObjectResult>
  EOT
end

class EntryImage
  include Sidekiq::Worker
  def perform(*args)
  end
end


text:
class task : public object
{
  object_body

public:
  task()
    : can_kill(false)
    , priority(5000)
  {}

  virtual bool start() = 0;
  virtual void on_suspend()
  {}
  virtual void update() = 0;
  virtual void on_resume()
  {}
  virtual void stop() = 0;

  bool can_kill;
  long priority;
};

// ****************************************************************************
using task_ptr = object_ptr<task>;