text:
from ..voronoi import DualVoronoiGraph
from .radial import create_xy_of_node

class DualRadialGraph(DualVoronoiGraph):

    """Graph of a series of points on concentric circles.

    Examples
    --------
    >>> from landlab.graph import DualRadialGraph
    >>> graph = DualRadialGraph((1, 4))
    >>> graph.number_of_corners
    4
    >>> graph.y_of_corner
    array([-0.5, -0.5,  0.5,  0.5])
    >>> graph.x_of_corner
    array([-0.5,  0.5, -0.5,  0.5])
    """

    def __init__(self, shape, spacing=1., origin=(0., 0.)):
        """Create a structured grid of triangles arranged radially.

        Parameters
        ----------
        shape : tuple of int
            Shape of the graph as number of rings and number of points
            in the first ring.
        spacing : float, optional
            Spacing between rings.
        origin : tuple of float, optional
            Coordinates of the center of the grid.
        """
        try:
            spacing = float(spacing)
        except TypeError:
            raise TypeError('spacing must be a float')

        x_of_node, y_of_node = create_xy_of_node(shape, spacing=spacing,
                                                 origin=origin)

        super(DualRadialGraph, self).__init__(
            (y_of_node, x_of_node), xy_sort=True, rot_sort=True)


text:
					<bx_if:show_icon>

					</bx_if:show_icon>
					<bx_if:show_icon_empty>

					</bx_if:show_icon_empty>

						__item_owner_name__
			            <bx_if:show_timeline_owner>

				        	__owner_username__
				        </bx_if:show_timeline_owner>

						__item_date__

			__content__
			<bx_if:show_location>

__location__

			</bx_if:show_location>
			<bx_if:show_menu_item_actions>

__menu_item_actions__

			</bx_if:show_menu_item_actions>

__comments__

redpajama_set_name: RedPajamaGithub


text:
<?php

use yii\helpers\Html;
use yii\widgets\DetailView;

/* @var $this yii\web\View */
/* @var $model backend\models\Client */

$this->title = $model->client_name;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Clients'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>

        <?= Html::a(Yii::t('app', 'Update'), ['update', 'id' => $model->client_id], ['class' => 'btn btn-primary']) ?>
        <?= Html::a(Yii::t('app', 'Delete'), ['delete', 'id' => $model->client_id], [
            'class' => 'btn btn-danger',
            'data' => [
                'confirm' => Yii::t('app', 'Are you sure you want to delete this item?'),
                'method' => 'post',
            ],
        ]) ?>

    <?= DetailView::widget([
        'model' => $model,
        'attributes' => [
            'client_id',
            'client_name',
            'client_address',
            //'client_lat',
            //'client_long',
            'priority',
            'day',
        ],
    ]) ?>


text:
import React from 'react';

import DevSettings from '@ncigdc/components/DevSettings';

import { userAccessListStub } from './helpers';

const CADevSettings = ({
  isFakeLoggedIn,
  setIsFakeLoggedIn,
  setUserAccessList,
  userAccessList,
}) => {
  const buttons = [
    {
      active: !isFakeLoggedIn,
      label: 'logged out',
      onClick: () => {
        setIsFakeLoggedIn(false);
        setUserAccessList([]);
      },
    },
    {
      active: isFakeLoggedIn && userAccessList.length === 0,
      label: 'logged in, no controlled access',
      onClick: () => {
        setIsFakeLoggedIn(true);
        setUserAccessList([]);
      },
    },
    {
      active: isFakeLoggedIn && userAccessList.length === 1,
      label: 'logged in, some controlled access',
      onClick: () => {
        setIsFakeLoggedIn(true);
        setUserAccessList(userAccessListStub.slice(0, 1));
      },
    },
    {
      active: isFakeLoggedIn && userAccessList.length === 2,
      label: 'logged in, all controlled access',
      onClick: () => {
        setIsFakeLoggedIn(true);
        setUserAccessList(userAccessListStub);
      },
    },
  ];

  return (
    <DevSettings
      buttons={buttons}
      message="For local or Netlify. If you're on dev-oicr and you login, that will override these settings."
      />
  );
};

export default CADevSettings;


text:
import numpy as np
import pandas as pd

import string

import h5py
from fuel.datasets import IndexableDataset

def createH5Dataset(path,corpus):
    f = h5py.File(path, mode='w')
    sequence_length = 25

    in_splits  = corpus.get_splits(seq_len=sequence_length)
    out_splits = corpus.get_splits(seq_len=sequence_length, shifted=True)

    assert in_splits.shape == out_splits.shape

    char_in  = f.create_dataset('inchar',   in_splits.shape, dtype='uint8')
    char_out = f.create_dataset('outchar', out_splits.shape, dtype='uint8')

    char_in[...] = in_splits
    char_out[...] = out_splits

    f.attrs["vocab_size"] = corpus.vocab_size()

    f.flush()
    f.close()

def createDataset(corpus=None, sequence_length=25, repeat=1):
    if not corpus: corpus = Corpus(open("corpus.txt").read())
    vocab_size = corpus.vocab_size()
    in_splits  = corpus.get_splits(seq_len=sequence_length, repeat=repeat)
    out_splits = corpus.get_splits(seq_len=sequence_length, repeat=repeat, shifted=True)

    df = IndexableDataset({
        'inchar': in_splits.astype(np.uint8),
        'outchar': out_splits.astype(np.uint8)
    })

    return df,vocab_size

class Corpus(object):
    def __init__(self,corpus):
        self.encode_dict = {}
        self.decode_dict = {}
        self.corpus = None
        self.__vocab_size = 0
        self.__init(corpus)

    def __init(self,corpus):
        # prepare corpus by replacing useless whitespace
        corpus = corpus.replace(r"  ", " ")
        corpus = [c for c in corpus.lower() if c in string.printable]
        words,vocab = pd.factorize(corpus)
        # assign internal vars
        self.corpus = words
        self.__vocab_size = len(vocab)
        self.encode_dict = {word:idx for idx,word in enumerate(vocab)}
        self.decode_dict = {idx:word for idx,word in enumerate(vocab)}

    def get_splits(self,seq_len=25,repeat=1,shifted=False):
        corpus = np.tile(self.corpus, repeat)
        corpus = corpus[1:] if shifted else corpus[:-1]
        off_set = len(corpus) % seq_len
        # if last split is unequal the other ones, just skip it
        return corpus[:-off_set].reshape((len(corpus)/seq_len,seq_len)).T

    def vocab_size(self):
        return self.__vocab_size

    def tokenize(self):
        return self.corpus

    def encode(self,txt):
        return [self.encode_dict.get(c, 0) for c in txt]

    def decode(self,code):
        return [self.decode_dict.get(i, "<unk>") for i in code]

if __name__ == "__main__":
    with open("corpus.txt") as fh:
        corpus = Corpus(fh.read())
    words1 = corpus.get_splits()
    words2 = corpus.get_splits(shifted=True)
    print words1.shape
    print words1[:3]
    print words2[:3]
    createH5Dataset("dataset_rnn.hdf5", corpus)

#train_data = H5PYDataset('dataset.hdf5', which_sets=('train',), load_in_memory=True)
#test_data  = H5PYDataset('dataset.hdf5', which_sets=('test',), load_in_memory=True)


text:
using System;
using System.Collections.Generic;
using System.Text;
using NPOI.Util;
using NPOI.HWPF.UserModel;
using System.Xml;

namespace NPOI.HWPF.Converter
{
    /**
     * Converts Word files (95-2007) into HTML files.
     *

     * This implementation doesn't create images or links to them. This can be
     * changed by overriding {@link #processImage(XmlElement, boolean, Picture)}
     * method.
     *
     * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com)
     */
    ///
    /// Beta
    ///
    public class WordToHtmlConverter : AbstractWordConverter
    {
        /**
         * Holds properties values, applied to current <tt>p</tt> element. Those
         * properties shall not be doubled in children <tt>span</tt> elements.
         */
        private class BlockProperies
        {
            public String pFontName;
            public int pFontSize;

            public BlockProperies(String pFontName, int pFontSize)
            {
                this.pFontName = pFontName;
                this.pFontSize = pFontSize;
            }
        }

        private static POILogger logger = POILogFactory.GetLogger(typeof(WordToHtmlConverter));

        private static String GetSectionStyle(Section section)
        {
            float leftMargin = section.MarginLeft / AbstractWordUtils.TWIPS_PER_INCH;
            float rightMargin = section.MarginRight / AbstractWordUtils.TWIPS_PER_INCH;
            float topMargin = section.MarginTop / AbstractWordUtils.TWIPS_PER_INCH;
            float bottomMargin = section.MarginBottom / AbstractWordUtils.TWIPS_PER_INCH;

            String style = "margin: " + topMargin + "in " + rightMargin + "in "
                    + bottomMargin + "in " + leftMargin + "in;";

            if (section.NumColumns > 1)
            {
                style += "column-count: " + (section.NumColumns) + ";";
                if (section.IsColumnsEvenlySpaced)
                {
                    float distance = section.DistanceBetweenColumns / AbstractWordUtils.TWIPS_PER_INCH;
                    style += "column-gap: " + distance + "in;";
                }
                else
                {
                    style += "column-gap: 0.25in;";
                }
            }
            return style;
        }

        public static XmlDocument Process(string docFile)
        {
            HWPFDocumentCore wordDocument = WordToHtmlUtils.LoadDoc(docFile);
            XmlDocument xmlDoc = new XmlDocument();
            //WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(xmlDoc);
            // wordToHtmlConverter.ProcessDocument(wordDocument);
            return xmlDoc;
        }

        private Stack<BlockProperies> blocksProperies = new Stack<BlockProperies>();

        private HtmlDocumentFacade htmlDocumentFacade;

        private XmlElement notes = null;

        /**
         * Creates new instance of {@link WordToHtmlConverter}. Can be used for
         * output several {@link HWPFDocument}s into single HTML document.
         *
         * @param document
         *            XML DOM Document used as HTML document
         */
        public WordToHtmlConverter(XmlDocument document)
        {
            this.htmlDocumentFacade = new HtmlDocumentFacade(document);
        }

        protected override void AfterProcess()
        {
            if (notes != null)
                htmlDocumentFacade.Body.AppendChild(notes);

            htmlDocumentFacade.UpdateStylesheet();
        }

        public override XmlDocument Document
        {
            get
            {
                return htmlDocumentFacade.Document;
            }
        }

        protected override void OutputCharacters(XmlElement pElement, CharacterRun characterRun, string text)
        {
            XmlElement span = htmlDocumentFacade.Document.CreateElement("span");
            pElement.AppendChild(span);

            StringBuilder style = new StringBuilder();
            BlockProperies blockProperies = this.blocksProperies.Peek();
            Triplet triplet = GetCharacterRunTriplet(characterRun);

            if (!string.IsNullOrEmpty(triplet.fontName)
                    && !WordToHtmlUtils.Equals(triplet.fontName,
                            blockProperies.pFontName))
            {
                style.Append("font-family:" + triplet.fontName + ";");
            }
            if (characterRun.GetFontSize() / 2 != blockProperies.pFontSize)
            {
                style.Append("font-size:" + characterRun.GetFontSize() / 2 + "pt;");
            }
            if (triplet.bold)
            {
                style.Append("font-weight:bold;");
            }
            if (triplet.italic)
            {
                style.Append("font-style:italic;");
            }

            WordToHtmlUtils.AddCharactersProperties(characterRun, style);
            if (style.Length != 0)
                htmlDocumentFacade.AddStyleClass(span, "s", style.ToString());

            XmlText textNode = htmlDocumentFacade.CreateText(text);
            span.AppendChild(textNode);
        }

        protected override void ProcessBookmarks(HWPFDocumentCore wordDocument, XmlElement currentBlock, Range range, int currentTableLevel, IList<Bookmark> rangeBookmarks)
        {
            XmlElement parent = currentBlock;
            foreach (Bookmark bookmark in rangeBookmarks)
            {
                XmlElement bookmarkElement = htmlDocumentFacade.CreateBookmark(bookmark.Name);
                parent.AppendChild(bookmarkElement);
                parent = bookmarkElement;
            }

            if (range != null)
                ProcessCharacters(wordDocument, currentTableLevel, range, parent);
            throw new NotImplementedException();
        }

        protected override void ProcessDocumentInformation(NPOI.HPSF.SummaryInformation summaryInformation)
        {
            if (!string.IsNullOrEmpty(summaryInformation.Title))
                htmlDocumentFacade.Title = summaryInformation.Title;

            if (!string.IsNullOrEmpty(summaryInformation.Author))
                htmlDocumentFacade.AddAuthor(summaryInformation.Author);

            if (!string.IsNullOrEmpty(summaryInformation.Keywords))
                htmlDocumentFacade.AddKeywords(summaryInformation.Keywords);

            if (!string.IsNullOrEmpty(summaryInformation.Comments))
                htmlDocumentFacade.AddDescription(summaryInformation.Comments);
        }
        public void processDocumentPart(HWPFDocumentCore wordDocument, Range range)
        {
            base.ProcessDocumentPart(wordDocument, range);
            AfterProcess();
        }
        protected override void ProcessDrawnObject(HWPFDocument doc, CharacterRun characterRun, OfficeDrawing officeDrawing, string path, XmlElement block)
        {
            XmlElement img = htmlDocumentFacade.CreateImage(path);
            block.AppendChild(img);
        }

        protected override void ProcessEndnoteAutonumbered(HWPFDocument wordDocument, int noteIndex, XmlElement block, Range endnoteTextRange)
        {
            ProcessNoteAutonumbered(wordDocument, "end", noteIndex, block, endnoteTextRange);
        }

        private void ProcessNoteAutonumbered(HWPFDocument wordDocument, string type, int noteIndex, XmlElement block, Range noteTextRange)
        {
            String textIndex = (noteIndex + 1).ToString();
            String textIndexClass = htmlDocumentFacade.GetOrCreateCssClass("a", "a", "vertical-align:super;font-size:smaller;");
            String forwardNoteLink = type + "note_" + textIndex;
            String backwardNoteLink = type + "note_back_" + textIndex;

            XmlElement anchor = htmlDocumentFacade.CreateHyperlink("#" + forwardNoteLink);
            anchor.SetAttribute("name", backwardNoteLink);
            anchor.SetAttribute("class", textIndexClass + " " + type + "noteanchor");
            anchor.InnerText = textIndex;
            block.AppendChild(anchor);

            if (notes == null)
            {
                notes = htmlDocumentFacade.CreateBlock();
                notes.SetAttribute("class", "notes");
            }

            XmlElement note = htmlDocumentFacade.CreateBlock();
            note.SetAttribute("class", type + "note");
            notes.AppendChild(note);

            XmlElement bookmark = htmlDocumentFacade.CreateBookmark(forwardNoteLink);
            bookmark.SetAttribute("href", "#" + backwardNoteLink);
            bookmark.InnerText = (textIndex);
            bookmark.SetAttribute("class", textIndexClass + " " + type  + "noteindex");
            note.AppendChild(bookmark);
            note.AppendChild(htmlDocumentFacade.CreateText(" "));

            XmlElement span = htmlDocumentFacade.Document.CreateElement("span");
            span.SetAttribute("class", type + "notetext");
            note.AppendChild(span);

            this.blocksProperies.Push(new BlockProperies("", -1));
            try
            {
                ProcessCharacters(wordDocument, int.MinValue, noteTextRange, span);
            }
            finally
            {
                this.blocksProperies.Pop();
            }
        }

        protected override void ProcessFootnoteAutonumbered(HWPFDocument wordDocument, int noteIndex, XmlElement block, Range footnoteTextRange)
        {
            ProcessNoteAutonumbered(wordDocument, "foot", noteIndex, block, footnoteTextRange);
        }

        protected override void ProcessHyperlink(HWPFDocumentCore wordDocument, XmlElement currentBlock, Range textRange, int currentTableLevel, string hyperlink)
        {
            XmlElement basicLink = htmlDocumentFacade.CreateHyperlink(hyperlink);
            currentBlock.AppendChild(basicLink);

            if (textRange != null)
                ProcessCharacters(wordDocument, currentTableLevel, textRange, basicLink);
        }
        /**
         * This method shall store image bytes in external file and convert it if
         * necessary. Images shall be stored using PNG format. Other formats may be
         * not supported by user browser.
         *

         * Please note the {@link #processImage(XmlElement, boolean, Picture, String)}.
         *
         * @param currentBlock
         *            currently processed HTML element, like <tt>p</tt>. Shall be
         *            used as parent of newly created <tt>img</tt>
         * @param inlined
         *            if image is inlined
         * @param picture
         *            HWPF object, contained picture data and properties
         */
        protected override void ProcessImage(XmlElement currentBlock, bool inlined, Picture picture)
        {
            PicturesManager fileManager = GetPicturesManager();
            if (fileManager != null)
            {
                String url = fileManager
                        .SavePicture(picture.GetContent(),
                                picture.SuggestPictureType(),
                                picture.SuggestFullFileName());

                if (!string.IsNullOrEmpty(url))
                {
                    ProcessImage(currentBlock, inlined, picture, url);
                    return;
                }
            }

            // no default implementation -- skip
            currentBlock.AppendChild(htmlDocumentFacade.Document
                    .CreateComment("Image link to '"
                            + picture.SuggestFullFileName() + "' can be here"));
        }
        protected void ProcessImage(XmlElement currentBlock, bool inlined,
            Picture picture, String imageSourcePath)
        {
            int aspectRatioX = picture.HorizontalScalingFactor;
            int aspectRatioY = picture.VerticalScalingFactor;

            StringBuilder style = new StringBuilder();

            float imageWidth;
            float imageHeight;

            float cropTop;
            float cropBottom;
            float cropLeft;
            float cropRight;

            if (aspectRatioX > 0)
            {
                imageWidth = picture.DxaGoal * aspectRatioX / 1000
                        / AbstractWordUtils.TWIPS_PER_INCH;
                cropRight = picture.DxaCropRight * aspectRatioX / 1000
                        / AbstractWordUtils.TWIPS_PER_INCH;
                cropLeft = picture.DxaCropLeft * aspectRatioX / 1000
                        / AbstractWordUtils.TWIPS_PER_INCH;
            }
            else
            {
                imageWidth = picture.DxaGoal / AbstractWordUtils.TWIPS_PER_INCH;
                cropRight = picture.DxaCropRight / AbstractWordUtils.TWIPS_PER_INCH;
                cropLeft = picture.DxaCropLeft / AbstractWordUtils.TWIPS_PER_INCH;
            }

            if (aspectRatioY > 0)
            {
                imageHeight = picture.DyaGoal * aspectRatioY / 1000
                        / AbstractWordUtils.TWIPS_PER_INCH;
                cropTop = picture.DyaCropTop * aspectRatioY / 1000
                        / AbstractWordUtils.TWIPS_PER_INCH;
                cropBottom = picture.DyaCropBottom * aspectRatioY / 1000
                        / AbstractWordUtils.TWIPS_PER_INCH;
            }
            else
            {
                imageHeight = picture.DyaGoal / AbstractWordUtils.TWIPS_PER_INCH;
                cropTop = picture.DyaCropTop / AbstractWordUtils.TWIPS_PER_INCH;
                cropBottom = picture.DyaCropBottom / AbstractWordUtils.TWIPS_PER_INCH;
            }

            XmlElement root;
            if (cropTop != 0 || cropRight != 0 || cropBottom != 0 || cropLeft != 0)
            {
                float visibleWidth = Math.Max(0, imageWidth - cropLeft - cropRight);
                float visibleHeight = Math.Max(0, imageHeight - cropTop - cropBottom);

                root = htmlDocumentFacade.CreateBlock();
                htmlDocumentFacade.AddStyleClass(root, "d", "vertical-align:text-bottom;width:" + visibleWidth + "in;height:" + visibleHeight + "in;");

                // complex
                XmlElement inner = htmlDocumentFacade.CreateBlock();
                htmlDocumentFacade.AddStyleClass(inner, "d", "position:relative;width:" + visibleWidth + "in;height:" + visibleHeight + "in;overflow:hidden;");
                root.AppendChild(inner);

                XmlElement image = htmlDocumentFacade.CreateImage(imageSourcePath);
                htmlDocumentFacade.AddStyleClass(image, "i", "position:absolute;left:-" + cropLeft + ";top:-" + cropTop + ";width:" + imageWidth + "in;height:" + imageHeight + "in;");
                inner.AppendChild(image);

                style.Append("overflow:hidden;");
            }
            else
            {
                root = htmlDocumentFacade.CreateImage(imageSourcePath);
                root.SetAttribute("style", "width:" + imageWidth + "in;height:" + imageHeight + "in;vertical-align:text-bottom;");
            }

            currentBlock.AppendChild(root);
        }
        protected override void ProcessLineBreak(XmlElement block, CharacterRun characterRun)
        {
            block.AppendChild(htmlDocumentFacade.CreateLineBreak());
        }

        protected override void ProcessPageBreak(HWPFDocumentCore wordDocument, XmlElement flow)
        {
            flow.AppendChild(htmlDocumentFacade.CreateLineBreak());
        }

        protected override void ProcessPageref(HWPFDocumentCore wordDocument, XmlElement currentBlock, Range textRange, int currentTableLevel, string pageref)
        {
            XmlElement basicLink = htmlDocumentFacade.CreateHyperlink("#" + pageref);
            currentBlock.AppendChild(basicLink);

            if (textRange != null)
                ProcessCharacters(wordDocument, currentTableLevel, textRange, basicLink);
        }

        protected override void ProcessParagraph(HWPFDocumentCore wordDocument, XmlElement parentElement, int currentTableLevel, Paragraph paragraph, string bulletText)
        {
            XmlElement pElement = htmlDocumentFacade.CreateParagraph();
            parentElement.AppendChild(pElement);

            StringBuilder style = new StringBuilder();
            WordToHtmlUtils.AddParagraphProperties(paragraph, style);

            int charRuns = paragraph.NumCharacterRuns;

            if (charRuns == 0)
            {
                return;
            }

            {
                String pFontName;
                int pFontSize;
                CharacterRun characterRun = paragraph.GetCharacterRun(0);
                if (characterRun != null)
                {
                    Triplet triplet = GetCharacterRunTriplet(characterRun);
                    pFontSize = characterRun.GetFontSize() / 2;
                    pFontName = triplet.fontName;
                    WordToHtmlUtils.AddFontFamily(pFontName, style);
                    WordToHtmlUtils.AddFontSize(pFontSize, style);
                }
                else
                {
                    pFontSize = -1;
                    pFontName = string.Empty;
                }
                blocksProperies.Push(new BlockProperies(pFontName, pFontSize));
            }
            try
            {
                if (!string.IsNullOrEmpty(bulletText))
                {
                    XmlText textNode = htmlDocumentFacade.CreateText(bulletText);
                    pElement.AppendChild(textNode);
                }

                ProcessCharacters(wordDocument, currentTableLevel, paragraph, pElement);
            }
            finally
            {
                blocksProperies.Pop();
            }

            if (style.Length > 0)
                htmlDocumentFacade.AddStyleClass(pElement, "p", style.ToString());

            WordToHtmlUtils.CompactSpans(pElement);
        }

        protected override void ProcessSection(HWPFDocumentCore wordDocument, Section section, int s)
        {
            XmlElement div = htmlDocumentFacade.CreateBlock();
            htmlDocumentFacade.AddStyleClass(div, "d", GetSectionStyle(section));
            htmlDocumentFacade.Body.AppendChild(div);

            ProcessParagraphes(wordDocument, div, section, int.MinValue);
        }

        protected void processSingleSection(HWPFDocumentCore wordDocument,
            Section section)
        {
            htmlDocumentFacade.AddStyleClass(htmlDocumentFacade.Body, "b", GetSectionStyle(section));

            ProcessParagraphes(wordDocument, htmlDocumentFacade.Body, section, int.MinValue);
        }

        protected override void ProcessTable(HWPFDocumentCore wordDocument, XmlElement flow, Table table)
        {
            XmlElement tableHeader = htmlDocumentFacade.CreateTableHeader();
            XmlElement tableBody = htmlDocumentFacade.CreateTableBody();

            int[] tableCellEdges = WordToHtmlUtils.BuildTableCellEdgesArray(table);
            int tableRows = table.NumRows;

            int maxColumns = int.MinValue;
            for (int r = 0; r < tableRows; r++)
            {
                maxColumns = Math.Max(maxColumns, table.GetRow(r).NumCells());
            }

            for (int r = 0; r < tableRows; r++)
            {
                TableRow tableRow = table.GetRow(r);

                XmlElement tableRowElement = htmlDocumentFacade.CreateTableRow();
                StringBuilder tableRowStyle = new StringBuilder();
                WordToHtmlUtils.AddTableRowProperties(tableRow, tableRowStyle);

                // index of current element in tableCellEdges[]
                int currentEdgeIndex = 0;
                int rowCells = tableRow.NumCells();
                for (int c = 0; c < rowCells; c++)
                {
                    TableCell tableCell = tableRow.GetCell(c);

                    if (tableCell.IsVerticallyMerged() && !tableCell.IsFirstVerticallyMerged())
                    {
                        currentEdgeIndex += getTableCellEdgesIndexSkipCount(table, r, tableCellEdges, currentEdgeIndex, c, tableCell);
                        continue;
                    }

                    XmlElement tableCellElement;
                    if (tableRow.isTableHeader())
                    {
                        tableCellElement = htmlDocumentFacade.CreateTableHeaderCell();
                    }
                    else
                    {
                        tableCellElement = htmlDocumentFacade.CreateTableCell();
                    }
                    StringBuilder tableCellStyle = new StringBuilder();
                    WordToHtmlUtils.AddTableCellProperties(tableRow, tableCell, r == 0, r == tableRows - 1, c == 0, c == rowCells - 1, tableCellStyle);

                    int colSpan = GetNumberColumnsSpanned(tableCellEdges, currentEdgeIndex, tableCell);
                    currentEdgeIndex += colSpan;

                    if (colSpan == 0)
                        continue;

                    if (colSpan != 1)
                        tableCellElement.SetAttribute("colspan", colSpan.ToString());

                    int rowSpan = GetNumberRowsSpanned(table, r, c,
                           tableCell);
                    if (rowSpan > 1)
                        tableCellElement.SetAttribute("rowspan", rowSpan.ToString());

                    ProcessParagraphes(wordDocument, tableCellElement, tableCell, 0  /*table.TableLevel Todo: */);

                    if (!tableCellElement.HasChildNodes)
                    {
                        tableCellElement.AppendChild(htmlDocumentFacade.CreateParagraph());
                    }
                    if (tableCellStyle.Length > 0)
                        htmlDocumentFacade.AddStyleClass(tableCellElement, tableCellElement.LocalName, tableCellStyle.ToString());

                    tableRowElement.AppendChild(tableCellElement);
                }

                if (tableRowStyle.Length > 0)
                    tableRowElement.SetAttribute("class", htmlDocumentFacade.GetOrCreateCssClass("tr", "r", tableRowStyle.ToString()));

                if (tableRow.isTableHeader())
                {
                    tableHeader.AppendChild(tableRowElement);
                }
                else
                {
                    tableBody.AppendChild(tableRowElement);
                }
            }

            XmlElement tableElement = htmlDocumentFacade.CreateTable();
            tableElement.SetAttribute("class",
                            htmlDocumentFacade.GetOrCreateCssClass(tableElement.LocalName, "t", "table-layout:fixed;border-collapse:collapse;border-spacing:0;"));
            if (tableHeader.HasChildNodes)
            {
                tableElement.AppendChild(tableHeader);
            }
            if (tableBody.HasChildNodes)
            {
                tableElement.AppendChild(tableBody);
                flow.AppendChild(tableElement);
            }
            else
            {
                logger.Log(POILogger.WARN, "Table without body starting at [", table.StartOffset.ToString(), "; ", table.EndOffset.ToString(), ")");
            }
        }
    }
}


text:
linking_include_m=false
linkinging_lib_m=false
linking_config_m=false

PY_INCLUDE="${PREFIX}/include/python${PY_VER}"
if [[ ( ! -d "${PY_INCLUDE}" ) && ( -d "${PY_INCLUDE}m" ) ]]; then
    linking_include_m=true
    ln -s "${PY_INCLUDE}m" "${PY_INCLUDE}"
fi

if [[ ( ! -f "${PREFIX}/lib/libpython${PY_VER}.dylib" ) && ( -f "${PREFIX}/lib/libpython${PY_VER}m.dylib"  ) ]]; then
    linkinging_lib_m=true
    ln -s  "${PREFIX}/lib/libpython${PY_VER}m.dylib" "${PREFIX}/lib/libpython${PY_VER}.dylib"
fi

PY_LIB="${PREFIX}/lib/python${PY_VER}"
if [[ ( ! -d "${PY_LIB}/config" ) && ( -d "${PY_LIB}/config-${PY_VER}m" ) ]]; then
    linking_config_m=true
    ln -s "${PY_LIB}/config-${PY_VER}m" "${PY_LIB}/config"
fi

cxxflags="-fPIC -I${PREFIX}/include/"
linkflags="-L${PREFIX}/lib/"
if [[ "$OSTYPE" == "darwin"* ]]; then
    # http://stackoverflow.com/questions/20108407/how-do-i-compile-boost-for-os-x-64b-platforms-with-stdlibc
    cxxflags="${cxxflags} -stdlib=libstdc++"
    linkflags="${linkflags} -stdlib=libstdc++"
fi

./bootstrap.sh install --prefix=$PREFIX
./b2 -j$CPU_COUNT install cxxflags="$cxxflags" linkflags="$linkflags"

if [[ "$linking_include_m" == "true" ]]; then
    rm -f "${PY_INCLUDE}"
fi
if [[ "$linkinging_lib_m" == "true" ]]; then
    rm -f "${PREFIX}/lib/libpython${PY_VER}.dylib"
fi

if [[ "$linking_config_m" == "true" ]]; then
    rm -f "${PY_LIB}/config"
fi


text:
namespace Urho3D
{

static int const UICOMPONENT_DEFAULT_TEXTURE_SIZE = 512;
static int const UICOMPONENT_MIN_TEXTURE_SIZE = 64;
static int const UICOMPONENT_MAX_TEXTURE_SIZE = 4096;

UIComponent::UIComponent(Context* context) :
    Component(context),
    isStaticModelOwned_(false)
{
    vertexBuffer_ = new VertexBuffer(context_);
    debugVertexBuffer_ = new VertexBuffer(context_);
    texture_ = context_->CreateObject<Texture2D>();

    rootElement_ = context_->CreateObject<UIElement>();
    rootElement_->SetTraversalMode(TM_BREADTH_FIRST);

    material_ = context_->CreateObject<Material>();
    material_->SetTechnique(0, GetSubsystem<ResourceCache>()->GetResource<Technique>("Techniques/Diff.xml"));
    material_->SetTexture(TU_DIFFUSE, texture_);

    SubscribeToEvent(rootElement_, E_RESIZED, URHO3D_HANDLER(UIComponent, OnElementResized));

    // Triggers resizing of texture.
    rootElement_->SetSize(UICOMPONENT_DEFAULT_TEXTURE_SIZE, UICOMPONENT_DEFAULT_TEXTURE_SIZE);
}

UIComponent::~UIComponent()
{
}

void UIComponent::RegisterObject(Context* context)
{
    context->RegisterFactory<UIComponent>();
}

UIElement* UIComponent::GetRoot() const
{
    return rootElement_;
}

Material* UIComponent::GetMaterial() const
{
    return material_;
}

Texture2D* UIComponent::GetTexture() const
{
    return texture_;
}

void UIComponent::OnNodeSet(Node* node)
{
    if (node)
    {
        model_ = node->GetComponent<StaticModel>();
        if (model_.Null())
        {
            isStaticModelOwned_ = true;
            model_ = node->CreateComponent<StaticModel>();
        }
        model_->SetMaterial(material_);
    }
    else
    {
        model_->SetMaterial(nullptr);
        if (isStaticModelOwned_)
        {
            model_->GetNode()->RemoveComponent<StaticModel>();
            isStaticModelOwned_ = false;
        }
        model_ = nullptr;
    }

    UI* ui = GetSubsystem<UI>();
    // May be null on shutdown
    if (ui)
        ui->SetRenderToTexture(this, node != nullptr);
}

void UIComponent::OnElementResized(StringHash eventType, VariantMap& args)
{
    int width = args[Resized::P_WIDTH].GetInt();
    int height = args[Resized::P_HEIGHT].GetInt();

    if (width < UICOMPONENT_MIN_TEXTURE_SIZE || width > UICOMPONENT_MAX_TEXTURE_SIZE ||
        height < UICOMPONENT_MIN_TEXTURE_SIZE || height > UICOMPONENT_MAX_TEXTURE_SIZE)
    {
        URHO3D_LOGERRORF("UIComponent: Texture size %dx%d is not valid. Width and height should be between %d and %d.",
                         width, height, UICOMPONENT_MIN_TEXTURE_SIZE, UICOMPONENT_MAX_TEXTURE_SIZE);
        return;
    }

    if (texture_->SetSize(width, height, GetSubsystem<Graphics>()->GetRGBAFormat(), TEXTURE_RENDERTARGET))
    {
        texture_->SetFilterMode(FILTER_BILINEAR);
        texture_->SetAddressMode(COORD_U, ADDRESS_CLAMP);
        texture_->SetAddressMode(COORD_V, ADDRESS_CLAMP);
        texture_->SetNumLevels(1);                                                // No mipmaps
        texture_->GetRenderSurface()->SetUpdateMode(SURFACE_MANUALUPDATE);
    }
    else
        URHO3D_LOGERROR("UIComponent: resizing texture failed.");
}

bool UIComponent::ScreenToUIPosition(IntVector2 screenPos, IntVector2& result)
{
    Scene* scene = GetScene();
    if (!scene)
        return false;

    Renderer* renderer = GetSubsystem<Renderer>();
    if (!renderer)
        return false;

    // \todo Always uses the first viewport, in case there are multiple
    Viewport* viewport = renderer->GetViewportForScene(scene, 0);
    Octree* octree = scene->GetComponent<Octree>();

    if (!viewport || !octree)
        return false;

    Camera* camera = viewport->GetCamera();

    if (!camera)
        return false;

    IntRect rect = viewport->GetRect();
    if (rect == IntRect::ZERO)
    {
        Graphics* graphics = GetSubsystem<Graphics>();
        rect.right_ = graphics->GetWidth();
        rect.bottom_ = graphics->GetHeight();
    }

    Ray ray(camera->GetScreenRay((float)screenPos.x_ / rect.Width(), (float)screenPos.y_ / rect.Height()));
    PODVector<RayQueryResult> queryResultVector;
    RayOctreeQuery query(queryResultVector, ray, RAY_TRIANGLE_UV, M_INFINITY, DRAWABLE_GEOMETRY, DEFAULT_VIEWMASK);

    octree->Raycast(query);

    if (queryResultVector.Empty())
        return false;

    for (unsigned i = 0; i < queryResultVector.Size(); i++)
    {
        RayQueryResult& queryResult = queryResultVector[i];
        if (queryResult.drawable_ != model_)
        {
            // ignore billboard sets by default
            if (queryResult.drawable_->GetTypeInfo()->IsTypeOf(BillboardSet::GetTypeStatic()))
                continue;
            return false;
        }

        Vector2& uv = queryResult.textureUV_;
        result = IntVector2(static_cast<int>(uv.x_ * rootElement_->GetWidth()),
                            static_cast<int>(uv.y_ * rootElement_->GetHeight()));
        return true;
    }
    return false;
}

}


text:
using System.Windows;
using ESRI.ArcGIS.Client;
using ESRI.ArcGIS.Client.WebMap;

namespace OpeningWebMaps
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            // License setting and ArcGIS Runtime initialization is done in Application.xaml.cs.

            InitializeComponent();

            var webMap = new ESRI.ArcGIS.Client.WebMap.Document();
            webMap.GetMapCompleted += webMap_GetMapCompleted;

            // Get webmap from ArcGIS Online, this item is at this address, note the item Id in the Url:
            // http://www.arcgis.com/home/item.html?id=88b187a860934d8491bdff591d0b1e1a

            webMap.GetMapAsync("88b187a860934d8491bdff591d0b1e1a");
        }

        void webMap_GetMapCompleted(object sender, GetMapCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                // Enable accelerated display
                e.Map.UseAcceleratedDisplay = true;

                // Add Map to the UI
                MainGrid.Children.Add(e.Map);

                // Add bookmarks form Webmap to the UI too.
                if (e.WebMap.Bookmarks.Count > 0)
                {
                    // Add bookmarks
                    var bookmarkControl = new ESRI.ArcGIS.Client.Toolkit.Bookmark();
                    foreach (var item in e.WebMap.Bookmarks)
                    {
                        bookmarkControl.AddBookmark(item.Name, item.Extent);
                    }
                    // Note this could equally be pre defined in Xaml too.
                    bookmarkControl.Map = e.Map;
                    bookmarkControl.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                    bookmarkControl.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                    // Add to the UI
                    MainGrid.Children.Add(bookmarkControl);
                }
            }
            else
            {
                MessageBox.Show("Failed to load web map!");
            }
        }
    }
}


text:
<resources>
    <string name="app_name">SaveState</string>
</resources>


text:
layout: victorious
title: "Study Hub | Experience Victoria"

main-header:
  main-ia:
    - News
    - Covid-19
    - Rsearch
    - Alumni
    - Opinion

sub-header:
  - Message from the Vice-Chancellor

footer:
  links:
    - Why choose Victoria?
    - Living in Wellington
    - Life on campus
    - Getting involved
    - Student support
    - Student services

  phones:
    - phone1:
      number: 0800 VICTORIA (842 867)
      label:  general enquiries
    - phone2:
      number: +64 4 463 5350
      label:  international enquiries

  mails:
    - info@wgtn.ac.nz

---

      {{> victorious.section-header }}

News

 Article 1

 Donec ullamcorper nulla non metus auctor fringilla. Integer posuere erat a ante venenatis dapibus
                    posuere velit aliquet. Maecenas sed diam eget risus varius blandit sit amet non magna. Morbi leo risus,
                    porta ac consectetur ac, vestibulum at eros.

Research; COVID

 Article 2

 Donec ullamcorper nulla non metus auctor fringilla. Integer posuere erat a ante venenatis dapibus
                    posuere velit aliquet. Maecenas sed diam eget risus varius blandit sit amet non magna. Morbi leo risus,
                    porta ac consectetur ac, vestibulum at eros.

Opinion; COVID

 Article 3

 Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vestibulum id ligula porta felis
                    euismod semper. Donec ullamcorper nulla non metus auctor fringilla. Cras mattis consectetur purus sit
                    amet fermentum. Integer posuere erat a ante

Message from the Vice-Chancellor

 Article 4

 Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Curabitur blandit tempus porttitor. Cras
                    justo odio, dapibus ac facilisis in, egestas eget quam. Donec sed odio dui. Fusce dapibus, tellus ac
                    cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Morbi leo
                    risus, porta ac consectetur ac, vestibulum at.

Opinion

 Article 5

 Donec ullamcorper nulla non metus auctor fringilla. Cum sociis natoque penatibus et magnis dis
                    parturient montes, nascetur ridiculus mus. Cras mattis consectetur purus sit amet fermentum. Donec id
                    elit non mi porta gravida at eget metus. Nullam quis risus eget urna mollis ornare vel eu leo. Nullam
                    quis risus eget urna mollis ornare vel eu leo. Morb

Research

 Article 6

 Donec ullamcorper nulla non metus auctor fringilla. Cum sociis natoque penatibus et magnis dis
                    parturient montes, nascetur ridiculus mus. Cras mattis consectetur purus sit amet fermentum. Donec id
                    elit non mi porta gravida at eget metus. Nullam quis risus eget urna mollis ornare vel eu leo. Nullam
                    quis risus eget urna mollis ornare vel eu leo. Morb

Message from the Vice-Chancellor

 Article 7

 Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Curabitur blandit tempus porttitor. Cras
                    justo odio, dapibus ac facilisis in, egestas eget quam. Donec sed odio dui. Fusce dapibus, tellus ac
                    cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Morbi leo
                    risus, porta ac consectetur ac, vestibulum at.

Research; COVID

 Article 2

 Donec ullamcorper nulla non metus auctor fringilla. Integer posuere erat a ante venenatis dapibus
                    posuere velit aliquet. Maecenas sed diam eget risus varius blandit sit amet non magna. Morbi leo risus,
                    porta ac consectetur ac, vestibulum at eros.

Opinion; COVID

 Article 3

 Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vestibulum id ligula porta felis
                    euismod semper. Donec ullamcorper nulla non metus auctor fringilla. Cras mattis consectetur purus sit
                    amet fermentum. Integer posuere erat a ante

Message from the Vice-Chancellor

 Article 4

 Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Curabitur blandit tempus porttitor. Cras
                    justo odio, dapibus ac facilisis in, egestas eget quam. Donec sed odio dui. Fusce dapibus, tellus ac
                    cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Morbi leo
                    risus, porta ac consectetur ac, vestibulum at.

Opinion

 Article 5

 Donec ullamcorper nulla non metus auctor fringilla. Cum sociis natoque penatibus et magnis dis
                    parturient montes, nascetur ridiculus mus. Cras mattis consectetur purus sit amet fermentum. Donec id
                    elit non mi porta gravida at eget metus. Nullam quis risus eget urna mollis ornare vel eu leo. Nullam
                    quis risus eget urna mollis ornare vel eu leo. Morb

Research

 Article 6

 Donec ullamcorper nulla non metus auctor fringilla. Cum sociis natoque penatibus et magnis dis
                    parturient montes, nascetur ridiculus mus. Cras mattis consectetur purus sit amet fermentum. Donec id
                    elit non mi porta gravida at eget metus. Nullam quis risus eget urna mollis ornare vel eu leo. Nullam
                    quis risus eget urna mollis ornare vel eu leo. Morb

Message from the Vice-Chancellor

 Article 7

 Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Curabitur blandit tempus porttitor. Cras
                    justo odio, dapibus ac facilisis in, egestas eget quam. Donec sed odio dui. Fusce dapibus, tellus ac
                    cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Morbi leo
                    risus, porta ac consectetur ac, vestibulum at.


text:
package com.cidic.sdx.util;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

public class EHCacheService {

	private static CacheManager cacheManager;
	private static Cache cache;

	private EHCacheService() {
	}

	private static EHCacheService service = null;

	public static EHCacheService getInstance() {
		if (service == null) {
			cacheManager = new CacheManager();
			cacheManager.addCache("StyleImage");
			cache = cacheManager.getCache("StyleImage");
			service = new EHCacheService();
		}
		return service;
	}

	public Object getCacheElement(String cacheKey) throws Exception {
		Element e = cache.get(cacheKey);
		if (e == null) {
			return null;
		}
		return e.getValue();
	}

	public void addToCache(String cacheKey, Object result) throws Exception {
		Element element = new Element(cacheKey, result);
		cache.put(element);
	}

	public void removeFromCache(String cacheKey) throws Exception {
		cache.remove(cacheKey);
	}
}


text:
var FormNewProfileController = function(profile, $scope, $controller, profileService) {

    // extends the FormProfileController to inherit common methods
    angular.extend(this, $controller('FormProfileController', { profile: profile, $scope: $scope }));

    $scope.profileName = 'New';

    $scope.settings = {
        isNew: true,
        saveLabel: 'Create'
    };

    $scope.save = function(profile) {
        profileService.createProfile(profile);
    };

};

FormNewProfileController.$inject = ['profile', '$scope', '$controller', 'profileService'];
module.exports = FormNewProfileController;


text:
class FontMavenPro < Cask
  url 'https://github.com/w0ng/googlefontdirectory/trunk/fonts/mavenpro',
      :using      => :svn,
      :revision   => '50',
      :trust_cert => true
  homepage 'http://www.google.com/fonts/specimen/Maven%20Pro'
  version '1.003'
  sha256 :no_check
  font 'MavenPro-Black.ttf'
  font 'MavenPro-Bold.ttf'
  font 'MavenPro-Medium.ttf'
  font 'MavenPro-Regular.ttf'
end


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (C) 2015 Actor LLC. <https://actor.im>
  -->

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="@color/primary" />
    <stroke android:width="2dp" android:color="@color/primary"/>
</shape>


text:
<?php
/**
 * test case
 */
/**
 * test case.
 */
class WURFL_Handlers_MSIEHandlerTest extends PHPUnit_Framework_TestCase {

	private $msieHandler;

	function setUp() {
		$context = new WURFL_Context ( null );
		$userAgentNormalizer = new WURFL_Request_UserAgentNormalizer_Specific_MSIE ();
		$this->msieHandler = new WURFL_Handlers_MSIEHandler ($context, $userAgentNormalizer );
	}

	function testShoudHandle() {
		$userAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)";
		$this->assertTrue ( $this->msieHandler->canHandle ( $userAgent ) );
	}

}


text:
module DataOutput

  # Output class to visualize the interpolation of a region
  class RegionOutput < BaseOutput

    # singleton method to generate the output for the given region
    # @param [DataSet] data the data that should be visualized
    # @param [Hash] coordinates a hash containing the x and y coordinate of the
    #   central point of the region
    # @param [DataSeries] data_series the considered data series which is
    #   required for the extreme values
    # @param [Hash] values a hash containing all required values to interpolate
    #   the region
    def initialize(data, coordinates, data_series, values)
      set_attributes(data, values[:extreme_values])
      @legend = ColorLegend::ColorData.new(data_series.min_value,
                                           data_series.max_value)
      @domain_x = create_data_domain('X', coordinates[:x], values[:inter_x],
                                                          values[:delta_x])
      @domain_y = create_data_domain('Y', coordinates[:y], values[:inter_y],
                                                          values[:delta_y])

      print_output_head(coordinates, values)
      print_data(values[:legend], @domain_x, @domain_y)
    end

    private
    # @return [DataDomain] representing the section in the x-dimension
    attr :domain_x
    # @return [DataDomain] representing the section in the y-dimension
    attr :domain_y

    # method to create the special {MetaData::DataDomain}s for the x- and
    # y-dimension
    # @param [String] label the name of the domain
    # @param [Float] coordinate the coordinate of the region center in the
    #   required dimension
    # @param [Float] interval the value to specify the value set in the
    #   considered dimension
    # @param [Float] delta the steprange in the considered dimension
    # @return [DataDomain] the domain object based on the input parameter
    def create_data_domain(label, coordinate, interval, delta)
      lower = (coordinate - interval).round(3)
      upper = (coordinate + interval).round(3)

      MetaData::DataDomain.new(label, lower, upper, delta)
    end

    # method to print the output head
    # @param [Hash] coordinates a hash containing the coordinates of the origin
    # @param [Hash] values a hash containing the required values
    def print_output_head(coordinates, values)
      puts "Printing interpolated region around (%.2f, %.2f) for data set %d" %
            [coordinates[:x], coordinates[:y], values[:index] + 1]
      puts "\n"
    end

    # prints the meta information consisting of dataset name and informations
    # of the different dimensions
    def print_meta_information
      puts "\nRegional interpolation with domain properties:"

      print_domain_information(@domain_x, "\nX")
      print_domain_information(@domain_y, 'Y')
    end

  end

end


text:
<?php

namespace spec\Fitbug\Guzzle\SwaggerValidation;

use Fitbug\Guzzle\SwaggerValidation\Psr7ResponsePrinter;
use Fitbug\Guzzle\SwaggerValidation\Psr7ResponsePrinterInterface;
use PhpSpec\ObjectBehavior;
use Psr\Http\Message\ResponseInterface;

class Psr7ResponsePrinterSpec extends ObjectBehavior
{
    public function it_is_initializable()
    {
        $this->shouldHaveType(Psr7ResponsePrinter::class);
    }

    public function it_implements_an_interface()
    {
        $this->shouldImplement(Psr7ResponsePrinterInterface::class);
    }

    public function it_is_able_to_print_a_pretty_string_version_of_a_http_response(ResponseInterface $response)
    {
        $response->getProtocolVersion()->willReturn('1.1');
        $response->getStatusCode()->willReturn(200);
        $response->getReasonPhrase()->willReturn('OK');
        $response->getHeaders()->willReturn(
            [
                'Date'             => ['Mon, 23 May 2005 22:38:34 GMT'],
                'Content-Type'     => ['text/html; charset=UTF-8'],
                'Content-Encoding' => ['UTF-8'],
                'Content-Length'   => [138],
                'Last-Modified'    => ['Wed, 08 Jan 2003 23:11:55 GMT'],
                'Server'           => ['Apache/1.3.3.7 (Unix) (Red-Hat/Linux)'],
                'ETag'             => ['"3f80f-1b6-3e1cb03b"'],
                'Accept-Ranges'    => ['bytes'],
                'Connection'       => ['close'],
            ]
        );

        $response->getBody()->willReturn(
            '<html>
<head>
  <title>An Example Page</title>
</head>
<body>
  Hello World, this is a very simple HTML document.
</body>
</html>'
        );

        $expected
            = <<<'EXPECTED'
HTTP/1.1 200 OK
Date: Mon, 23 May 2005 22:38:34 GMT
Content-Type: text/html; charset=UTF-8
Content-Encoding: UTF-8
Content-Length: 138
Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux)
ETag: "3f80f-1b6-3e1cb03b"
Accept-Ranges: bytes
Connection: close

<html>
<head>
  <title>An Example Page</title>
</head>
<body>
  Hello World, this is a very simple HTML document.
</body>
</html>
EXPECTED;
        $this->toString($response)->shouldReturn($expected);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CslaRepositoryTest.DataAccess
{

    //DTO for order summary data
    public interface IOrderInfoDto
    {
        int Id { get; set; }
        string Customer { get; set; }
        DateTime Date { get; set; }
    }

}


text:
package org.springframework.boot.actuate.health;

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * Strategy used to aggregate {@link Status} instances.
 * <p>
 * This is required in order to combine subsystem states expressed through
 * {@link Health#getStatus()} into one state for the entire system.
 *
 * @author Phillip Webb
 * @since 2.2.0
 */
@FunctionalInterface
public interface StatusAggregator {

	/**
	 * Return the aggregate status for the given set of statuses.
	 * @param statuses the statuses to aggregate
	 * @return the aggregate status
	 */
	default Status getAggregateStatus(Status... statuses) {
		return getAggregateStatus(new LinkedHashSet<>(Arrays.asList(statuses)));
	}

	/**
	 * Return the aggregate status for the given set of statuses.
	 * @param statuses the statuses to aggregate
	 * @return the aggregate status
	 */
	Status getAggregateStatus(Set<Status> statuses);

}


text:
<?php

namespace Opifer\RulesEngine\Rule\Condition;

interface ConditionInterface
{
    public function getLeft();

    public function getRight();

    public function getOperator();
}


text:
/*

browser_launcher.js
===================

This file more or less figures out how to launch any browser on any platform.

*/

var path = require('path')
var rimraf = require('rimraf')
var async = require('async')
var fs = require('fs')
var fileutils = require('./fileutils')
var browserExeExists = fileutils.browserExeExists
var findableByWhich = fileutils.findableByWhich
var findableByWhichOrModule = fileutils.findableByWhichOrModule
var findableByWhereOrModule = fileutils.findableByWhereOrModule
var os = require('os')

// Find the temporary directory for the system
var tempDir = function(){
  return os.tmpdir()
}()

var userHomeDir = process.env.HOME || process.env.USERPROFILE

function setupFirefoxProfile(profileDir, done){
  rimraf(profileDir, function(){
    // using prefs.js to suppress the check default browser popup
    // and the welcome start page
    var prefs = [
      'user_pref("browser.shell.checkDefaultBrowser", false);',
      'user_pref("browser.cache.disk.smart_size.first_run", false);'
    ]
    fs.mkdir(profileDir, function(){
      fs.writeFile(profileDir + '/prefs.js', prefs.join('\n'), function(){
        done()
      })
    })
  })
}

function buildPhantomJsArgs(config) {
  var options = [path.join(path.dirname( __dirname ), '/assets/phantom.js'), this.getUrl()]
  var debug_port = config.get( "phantomjs_debug_port" )
  if (debug_port) {
    options.unshift( "--remote-debugger-autorun=true" )
    options.unshift( "--remote-debugger-port=" + debug_port )
  }
  var phantom_args = config.get("phantomjs_args")
  if (phantom_args) {
    options = phantom_args.concat(options)
  }
  return options
}

// Return the catalogue of the browsers that Testem supports for the platform. Each "browser object"
// will contain these fields:
//
// * `name` - the display name of the browser
// * `exe` - path to the executable to use to launch the browser
// * `setup(app, done)` - any initial setup needed before launching the executable(this is async,
//        the second parameter `done()` must be invoked when done).
// * `supported(cb)` - an async function which tells us whether the browser is supported by the current machine.
function browsersForPlatform(){
  var platform = process.platform

  if (platform === 'win32'){
    return  [
      {
        name: "IE",
        exe: "C:\\Program Files\\Internet Explorer\\iexplore.exe",
        supported: browserExeExists
      },
      {
        name: "Firefox",
        exe: [
          "C:\\Program Files\\Mozilla Firefox\\firefox.exe",
          "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe"
        ],
        args: ["-profile", tempDir + "\\testem.firefox"],
        setup: function(config, done){
          setupFirefoxProfile(tempDir + '/testem.firefox', done)
        },
        supported: browserExeExists
      },
      {
        name: "Chrome",
        exe: [
          userHomeDir + "\\Local Settings\\Application Data\\Google\\Chrome\\Application\\chrome.exe",
          userHomeDir + "\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe",
          "C:\\Program Files\\Google\\Chrome\\Application\\Chrome.exe",
          "C:\\Program Files (x86)\\Google\\Chrome\\Application\\Chrome.exe"
        ],
        args: ["--user-data-dir=" + tempDir + "\\testem.chrome", "--no-default-browser-check", "--no-first-run", "--ignore-certificate-errors", "--test-type"],
        setup: function(config, done){
          rimraf(tempDir + '\\testem.chrome', done)
        },
        supported: browserExeExists
      },
      {
        name: "Safari",
        exe: [
          "C:\\Program Files\\Safari\\safari.exe",
          "C:\\Program Files (x86)\\Safari\\safari.exe"
        ],
        supported: browserExeExists
      },
      {
        name: "Opera",
        exe: [
          "C:\\Program Files\\Opera\\opera.exe",
          "C:\\Program Files (x86)\\Opera\\opera.exe"
        ],
        args: ["--user-data-dir=" + tempDir + "\\testem.opera", "-pd", tempDir + "\\testem.opera"],
        setup: function(config, done){
          rimraf(tempDir + '\\testem.opera', done)
        },
        supported: browserExeExists
      },
      {
        name: 'PhantomJS',
        exe: 'phantomjs',
        useCrossSpawn: true,
        args: buildPhantomJsArgs,
        supported: findableByWhereOrModule
      }
    ]
  }else if (platform === 'darwin'){
    return [
      {
        name: "Chrome",
        exe: [
          process.env.HOME + "/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome",
          "/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome"
        ],
        args: ["--user-data-dir=" + tempDir + "/testem.chrome", "--no-default-browser-check", "--no-first-run", "--ignore-certificate-errors", "--test-type"],
        setup: function(config, done){
          rimraf(tempDir + '/testem.chrome', done)
        },
        supported: browserExeExists
      },
      {
        name: "Chrome Canary",
        exe: [
          process.env.HOME + "/Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome\ Canary",
          "/Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome\ Canary"
        ],
        args: ["--user-data-dir=" + tempDir + "/testem.chrome-canary", "--no-default-browser-check", "--no-first-run", "--ignore-certificate-errors", "--test-type"],
        setup: function(config, done){
          rimraf(tempDir + '/testem.chrome-canary', done)
        },
        supported: browserExeExists
      },
      {
        name: "Firefox",
        exe: [
          process.env.HOME + "/Applications/Firefox.app/Contents/MacOS/firefox",
          "/Applications/Firefox.app/Contents/MacOS/firefox"
        ],
        args: ["-profile", tempDir + "/testem.firefox"],
        setup: function(config, done){
          setupFirefoxProfile(tempDir + '/testem.firefox', done)
        },
        supported: browserExeExists
      },
      {
        name: "Safari",
        exe: [
          process.env.HOME + "/Applications/Safari.app/Contents/MacOS/Safari",
          "/Applications/Safari.app/Contents/MacOS/Safari"
        ],
        setup: function(config, done){
          var url = this.getUrl()
          fs.writeFile(tempDir + '/testem.safari.html', "<script>window.location = '" + url + "'</script>", done)
        },
        args: function(){
          return [tempDir + '/testem.safari.html']
        },
        supported: browserExeExists
      },
      {
        name: "Opera",
        exe: [
          process.env.HOME + "/Applications/Opera.app/Contents/MacOS/Opera",
          "/Applications/Opera.app/Contents/MacOS/Opera"
        ],
        args: ["--user-data-dir=" + tempDir + "/testem.opera", "-pd", tempDir + "/testem.opera"],
        setup: function(config, done){
          rimraf(tempDir + '/testem.opera', done)
        },
        supported: browserExeExists
      },
      {
        name: 'PhantomJS',
        exe: 'phantomjs',
        args: buildPhantomJsArgs,
        supported: findableByWhichOrModule
      }
    ]
  }else if (platform === 'linux'){
    return [
      {
        name: 'Firefox',
        exe: 'firefox',
        args: ["-no-remote", "-profile", tempDir + "/testem.firefox"],
        setup: function(config, done){
          rimraf(tempDir + '/testem.firefox', function(err){
            if (!err){
              fs.mkdir(tempDir + '/testem.firefox', done)
            }else{
              done()
            }
          })
        },
        supported: findableByWhich
      },
      {
        name: 'Chrome',
        exe: 'google-chrome',
        args: ["--user-data-dir=" + tempDir + "/testem.chrome",
          "--no-default-browser-check", "--no-first-run", "--ignore-certificate-errors"],
        setup: function(config, done){
          rimraf(tempDir + '/testem.chrome', done)
        },
        supported: findableByWhich
      },
      {
        name: 'Chromium',
        exe: ['chromium', 'chromium-browser'],
        args: ["--user-data-dir=" + tempDir + "/testem.chromium",
          "--no-default-browser-check", "--no-first-run", "--ignore-certificate-errors"],
        setup: function(config, done){
          rimraf(tempDir + '/testem.chromium', done)
        },
        supported: findableByWhich
      },
      {
        name: 'PhantomJS',
        exe: 'phantomjs',
        args: buildPhantomJsArgs,
        supported: findableByWhichOrModule
      }
    ]
  }else if (platform === 'sunos') {
  	return [
        {
          name: 'PhantomJS',
          exe: 'phantomjs',
          args: buildPhantomJsArgs,
          supported: findableByWhichOrModule
        }
  	]
  }else{
    return []
  }
}

// Returns the avaliable browsers on the current machine.
function getAvailableBrowsers(cb){
  var browsers = browsersForPlatform()
  browsers.forEach(function(b){
    b.protocol = 'browser'
  })
  async.filter(browsers, function(browser, cb){
    browser.supported(cb)
  }, function(available){
    cb(available)
  })
}

exports.getAvailableBrowsers = getAvailableBrowsers


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Arebis.Web
{
    /// <summary>
    /// Represents a shopping cart of T items stored in the session.
    /// </summary>
    public static class Cart<T>
    {
        public static void Clear()
        {
            HttpContext.Current.Session[typeof(Cart<T>).FullName] = null;
        }

        public static void Add(T item)
        {
            GetCartList().Add(item);
        }

        public static void RemoveAt(int index)
        {
            GetCartList().RemoveAt(index);
        }

        public static IList<T> Content
        {
            get
            {
                return GetCartList();
            }
        }

        private static List<T> GetCartList()
        {
            var cart = (List<T>)HttpContext.Current.Session[typeof(Cart<T>).FullName];
            if (cart == null)
            {
                HttpContext.Current.Session[typeof(Cart<T>).FullName] = cart = new List<T>();
            }

            return cart;
        }
    }
}


text:
package com.thales.ga;

import static org.jenetics.engine.EvolutionResult.toBestPhenotype;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.jenetics.Chromosome;
import org.jenetics.EnumGene;
import org.jenetics.Genotype;
import org.jenetics.Mutator;
import org.jenetics.Optimize;
import org.jenetics.PartiallyMatchedCrossover;
import org.jenetics.PermutationChromosome;
import org.jenetics.Phenotype;
import org.jenetics.RouletteWheelSelector;
import org.jenetics.SwapMutator;
import org.jenetics.TournamentSelector;
import org.jenetics.engine.Engine;
import org.jenetics.engine.EvolutionStatistics;
import org.jenetics.engine.limit;
import org.jenetics.util.ISeq;

import com.thales.model.Item;
import com.thales.model.Manifest;
import com.thales.model.Store;
import com.thales.model.Vessel;

public class ManifestOptimiser {

	private final Store store;
	private final List<Vessel> vessels;

	public ManifestOptimiser(Store store, List<Vessel> vessels) {
		this.store = store;
		this.vessels = vessels;
	}

	private static class ManifestComparitor implements Comparator<EnumGene<Item>> {

		@Override
		public int compare(EnumGene<Item> o1, EnumGene<Item> o2) {
			Item item1 = o1.getAllele();
			Item item2 = o2.getAllele();
			int delta = item1.getDestination().compareTo(item2.getDestination());
			if (delta == 0) {
				return item1.getPriority().compareTo(item2.getPriority());
			}
			return delta;
		}

	}

	private List<Manifest> create(Genotype<EnumGene<Item>> genotype) {
		List<Manifest> manifests = vessels.stream().map((v) -> new Manifest(v)).collect(Collectors.toList());
		ISeq<EnumGene<Item>> seq = ((PermutationChromosome<Item>) genotype.getChromosome()).toSeq();

		for (int i = 0; i < manifests.size(); i++) {
			Manifest m = manifests.get(i);
			List<EnumGene<Item>> genes = seq.subSeq(i, i + m.getVessel().getDimension().size).stream()
					.sorted(new ManifestComparitor()).collect(Collectors.toList());
			for (EnumGene<Item> gene : genes) {
				m.addItem(gene.getAllele());
			}
		}

		return manifests;
	}

	public List<Manifest> optimise(ManifestOptimsationFunction func) {
		ISeq<Item> seq = ISeq.of(store.allItems());

		PermutationChromosome<Item> c = PermutationChromosome.of(seq,
				vessels.stream().mapToInt((v) -> v.getDimension().size).sum());
		final Engine<EnumGene<Item>, Double> engine = Engine.builder(new ManifestFitnessFunction(vessels), c)
				.optimize(Optimize.MINIMUM).populationSize(500).maximalPhenotypeAge(70)
				.alterers(new SwapMutator<>(0.3), new PartiallyMatchedCrossover<>(0.5)).build();
		EvolutionStatistics<Double, ?> statistics = EvolutionStatistics.ofNumber();

		Phenotype<EnumGene<Item>, Double> best = engine.stream().limit(limit.bySteadyFitness(2000)).peek(statistics)
				.peek((r) -> func.apply(r.getGeneration(), statistics, create(r.getBestPhenotype().getGenotype())))
				.collect(toBestPhenotype());

		return create(best.getGenotype());
	}

}


text:
package forms

import (
	"go/ast"

	. "github.com/mvader/bolt/compiler/internal/context"
	"github.com/mvader/bolt/compiler/internal/errors"
	"github.com/mvader/bolt/compiler/internal/gen"
	"github.com/mvader/bolt/lang"
)

func Def(form *lang.List) DeclCompiler {
	return &def{form}
}

type def struct {
	*lang.List
}

func (f def) Compile(ctx *Ctx) (ast.Decl, error) {
	var (
		ok    bool
		name  *lang.Symbol
		elems = f.RestList()
		n     = elems.First()
	)

	if elems.Count() != 2 {
		return nil, ctx.Error(errors.Arity, elems.RestList().Count())
	}

	if name, ok = n.(*lang.Symbol); !ok {
		return nil, ctx.Error(errors.ExpectedTypeSymbol, n)
	}

	name, err := declarePublicSymbol(name, ctx)
	if err != nil {
		return nil, err
	}

	expr, err := compileExpr(elems.RestList().First(), ctx)
	if err != nil {
		return nil, err
	}

	return f.assemble(name, expr), nil
}

func (f def) assemble(name *lang.Symbol, expr ast.Expr) ast.Decl {
	return gen.DeclVars(gen.VarSpec(
		gen.Ident(name.Ident()),
		expr,
	))
}

func Defn(form *lang.List) DeclCompiler {
	return &defn{form}
}

type defn struct {
	*lang.List
}

// compileDefnForm compiles the special form "defn", which defines a function.
// There can be two cases when defining a function:
// - the identifier is "main", in which case we have to compile the main func.
// - the identifier is another thing, so a regular lang.Fn has to be compiled.
func (f defn) Compile(ctx *Ctx) (ast.Decl, error) {
	var (
		ok    bool
		name  *lang.Symbol
		elems = f.RestList()
		n     = elems.First()
	)

	if name, ok = n.(*lang.Symbol); !ok {
		return nil, ctx.Error(errors.ExpectedTypeSymbol, n)
	}

	name, err := declarePublicSymbol(name, ctx)
	if err != nil {
		return nil, err
	}

	return Func{
		List: elems.RestList().WithMeta(f.Meta),
		Name: name,
	}.CompileDeclaration(ctx.Child(f.Meta))
}

func declarePublicSymbol(name *lang.Symbol, ctx *Ctx) (*lang.Symbol, error) {
	name = lang.NewPublicSymbol("", name.Name()).WithMeta(name.Meta)
	if s := ctx.GetSymbol(name); s != nil {
		return nil, errors.New(errors.SymbolAlreadyDefined, name.Meta, name.String())
	}
	if err := ctx.AssignSymbol(name); err != nil {
		return nil, err
	}

	return name, nil
}


text:
<?php
namespace MOC\MarkIV\Plugin\OSMEngine\Source\Element;

/**
 * Class Relation
 *
 * @package MOC\MarkIV\Plugin\OSMEngine\Source\Element
 */
class Relation
{

}


text:
import React from 'react';
import classnames from 'classnames';
import { Button } from 'react-polymorph/lib/components/Button';
import SVGInline from 'react-svg-inline';
import externalLinkIcon from '../../assets/images/external-link-ic.inline.svg';
import styles from './ExternalLinkButton.scss';

type Props = {
  label: string;
  onClick: (...args: Array<any>) => any;
};
export function ExternalLinkButton({ label, onClick }: Props) {
  const buttonStyles = classnames(['flat', styles.overrideButton]);
  return (
    <Button
      label={
        <div className={styles.labelBlock}>
          {label}
          <SVGInline
            svg={externalLinkIcon}
            className={styles.externalLinkIcon}
          />
        </div>
      }
      className={buttonStyles}
      onClick={onClick}
    />
  );
}


text:
<?php

declare(strict_types=1);

namespace GrumPHPTest\Uni\Task;

use GrumPHP\Task\Context\GitPreCommitContext;
use GrumPHP\Task\Context\RunContext;
use GrumPHP\Task\Make;
use GrumPHP\Task\TaskInterface;
use GrumPHP\Test\Task\AbstractExternalTaskTestCase;

class MakeTest extends AbstractExternalTaskTestCase
{
    protected function provideTask(): TaskInterface
    {
        return new Make(
            $this->processBuilder->reveal(),
            $this->formatter->reveal()
        );
    }

    public function provideConfigurableOptions(): iterable
    {
        yield 'defaults' => [
            [],
            [
                'make_file' => null,
                'task' => null,
                'triggered_by' => ['php'],
            ]
        ];
    }

    public function provideRunContexts(): iterable
    {
        yield 'run-context' => [
            true,
            $this->mockContext(RunContext::class)
        ];

        yield 'pre-commit-context' => [
            true,
            $this->mockContext(GitPreCommitContext::class)
        ];

        yield 'other' => [
            false,
            $this->mockContext()
        ];
    }

    public function provideFailsOnStuff(): iterable
    {
        yield 'exitCode1' => [
            [],
            $this->mockContext(RunContext::class, ['hello.php']),
            function () {
                $this->mockProcessBuilder('make', $process = $this->mockProcess(1));
                $this->formatter->format($process)->willReturn('nope');
            },
            'nope'
        ];
    }

    public function providePassesOnStuff(): iterable
    {
        yield 'exitCode0' => [
            [],
            $this->mockContext(RunContext::class, ['hello.php']),
            function () {
                $this->mockProcessBuilder('make', $this->mockProcess(0));
            }
        ];
    }

    public function provideSkipsOnStuff(): iterable
    {
        yield 'no-files' => [
            [],
            $this->mockContext(RunContext::class),
            function () {}
        ];
        yield 'no-files-after-triggered-by' => [
            [],
            $this->mockContext(RunContext::class, ['notaphpfile.txt']),
            function () {}
        ];
    }

    public function provideExternalTaskRuns(): iterable
    {
        yield 'defaults' => [
            [],
            $this->mockContext(RunContext::class, ['hello.php', 'hello2.php']),
            'make',
            []
        ];

        yield 'make-file' => [
            [
                'make_file' => 'Makefile'
            ],
            $this->mockContext(RunContext::class, ['hello.php', 'hello2.php']),
            'make',
            [
                '--makefile=Makefile'
            ]
        ];

        yield 'task' => [
            [
                'task' => 'mytask',
            ],
            $this->mockContext(RunContext::class, ['hello.php', 'hello2.php']),
            'make',
            [
                'mytask',
            ]
        ];
    }
}


text:
<?php

namespace pWhoisd;

use pWhoisd\Application;
use pWhoisd\Inet;

/**
 * Security class.
 */
class Security {

	/*
	 * @const  int  One second period
	 */
	const interval_second = 1;

	/*
	 * @const  int  One minute period
	 */
	const interval_minute = 60;

	/*
	 * @const  int  One hour period
	 */
	const interval_hour   = 3600;

	/*
	 * @const  int  One day period
	 */
	const interval_day    = 86400;

	/*
	 * @var  array   Interval pools [[interval, time(), key, counter], ...]
	 */
	private $interval_pool = [];

	/*
	 * @var  object  Instance of Client class
	 */
	private $client;

	/*
	 * @var  array   Access control rules
	 */
	private $rules;

	/*
	 * @var  string  Message sent to client
	 */
	private $message;

	/*
	 * @var  string  Last assigned action
	 */
	private $action;

	/**
	 * Assigning class properties and parse rules configuration.
	 *
	 * @return  void
	 */
	public function __construct()
	{
		$this->rules = Application::$config->get('security.rules');

		$this->parse_rules();
	}

	/**
	 * Initialize security by client request.
	 *
	 * @param   object  $client  Instance of Client class
	 * @return  void
	 */
	public function initialize(Client $client)
	{
		$this->client = $client;

		$this->process_rules();
	}

	/**
	 * Process defined access control rules.
	 *
	 * @return  void
	 */
	private function process_rules()
	{
		$this->message   = NULL;
		$this->action    = NULL;
		$this->intervals = [];

		foreach (array_reverse($this->rules) as $rule)
		{
			if ($this->process_conditions($rule['conditions']))
			{
				$this->message = Application::$config->get('messages.'.$rule['message'], FALSE);
				$this->action  = $rule['action'];
			}
		}

		// Update presented intervals
		foreach ($this->intervals as $key => $interval)
		{
			$this->interval_check($interval, $key, TRUE);
		}
	}

	/**
	 * Process rule condition.
	 *
	 * @return  bool  TRUE if all rules is accepted
	 */
	private function process_conditions($conditions)
	{
		if (empty($conditions))
		{
			return TRUE;
		}

		$client_address = $this->client->get_address();

		$expressions = [TRUE];

		foreach (['client_ip', 'requests', 'rate'] as $matched_condition)
		{
			foreach ($conditions as $condition)
			{
				$expression = NULL;

				if ($condition['l'] != $matched_condition)
				{
					continue;
				}

				switch ($condition['l'])
				{
					// Match client IP policy
					case 'client_ip':
						$expression =  $this->compare_client_ip($condition['r']);
						break;

					// Client-based interval policy
					case 'requests':
						$expression = $this->compare_interval
						(
							$condition['op'],
							$condition['r'],
							$client_address
						);
						break;

					// Global interval policy
					case 'rate':
						$expression = $this->compare_interval
						(
							$condition['op'],
							$condition['r']
						);
						break;
				}

				if ($expression !== NULL)
				{
					$expressions[] = $expression;

					if ($expression === FALSE)
					{
						break 2; // stop conditions checking
					}
				}
			}
		}

		return (bool) min($expressions);
	}

	/**
	 * Compares interval method.
	 *
	 * @param   string  Compare operator
	 * @param   string  Variable parameter (count/type)
	 * @param   string  Interval key
	 * @return  bool  TRUE if condition is accepted
	 */
	private function compare_interval($op, $variable, $key = NULL)
	{
		@list($variable, $interval) = explode('/', $variable, 2);

		switch ($interval)
		{
			case 'sec': $seconds = self::interval_second; break;
			case 'min': $seconds = self::interval_minute; break;
			case 'hr' : $seconds = self::interval_hour;   break;
			case 'day': $seconds = self::interval_day;    break;
		}

		if (!isset($seconds) OR empty($variable))
		{
			return FALSE;
		}

		$counter = $this->interval_check($seconds, $key);

		$this->intervals[$key] = $seconds;

		$variable = (float) $variable;

		switch ($op)
		{
			case '==': return $counter == $variable;
			case '!=': return $counter != $variable;
			case '>=': return $counter >= $variable;
			case '<=': return $counter <= $variable;
			case '>' : return $counter >  $variable;
			case '<' : return $counter <  $variable;
		}

		return FALSE;
	}

	/**
	 * Compares IP address method.
	 *
	 * @param   string|array  Variable parameter
	 * @return  bool  TRUE if condition is accepted
	 */
	private function compare_client_ip($variable)
	{
		return Inet::ip_in_subnets($this->client->get_address(), $variable);
	}

	/**
	 * Checks all intervals and returns current counter value.
	 *
	 * @param   int     Interval type
	 * @param   string  Interval key
	 * @return  int
	 */
	private function interval_check($interval = self::interval_second, $key = NULL, $update = FALSE)
	{
		$counter = FALSE;

		foreach ($this->interval_pool as $id => $element)
		{
			if ($element[1] <= time() - $element[0])
			{
				$this->interval_pool[$id] = NULL;

				unset($this->interval_pool[$id]);

				continue;
			}

			if ($element[0] == $interval AND $element[2] == $key)
			{
				if ($update)
				{
					$counter = ++$this->interval_pool[$id][3];
				}
				else
				{
					$counter = $element[3];
				}
			}
		}

		if ($counter === FALSE)
		{
			$counter = 1;

			if ($update)
			{
				$this->interval_pool[] = [$interval, time(), $key, ++$counter];
			}
		}

		return $counter;
	}

	/**
	 * Parse access control rules configuration.
	 *
	 * @return  void
	 */
	private function parse_rules()
	{
		$rules = [];

		foreach ($this->rules as $id => $rule)
		{
			if (!is_array($rule))
			{
				continue;
			}

			$rules[$id]['action']     = NULL;
			$rules[$id]['message']    = NULL;
			$rules[$id]['conditions'] = [];

			foreach ($rule as $rule_part)
			{
				// Assigning action
				if (is_null($rules[$id]['action']) AND ($rule_part == 'allow' OR $rule_part == 'deny' OR $rule_part == 'drop'))
				{
					$rules[$id]['action'] = $rule_part;
				}

				// Assigning message
				elseif (is_null($rules[$id]['message']) AND is_string($rule_part))
				{
					$rules[$id]['message'] = $rule_part;
				}

				// Assugning conditions
				elseif (is_array($rule_part) AND sizeof($rule_part) >= 2)
				{
					$rules[$id]['conditions'][] = $this->parse_condition($rule_part);
				}
			}

			if (is_null($rules[$id]['action']))
			{
				unset($rules[$id]);
			}
		}

		$this->rules = $rules;
	}

	/**
	 * Parse conditions in rule configuration.
	 *
	 * @param   array  Raw conditions array
	 * @return  array
	 */
	private function parse_condition($condition_part)
	{
		$condition = [];

		if (sizeof($condition_part) >= 3)
		{
			$condition['l']  = $condition_part[0];
			$condition['op'] = $condition_part[1];
			$condition['r']  = $condition_part[2];
		}
		else
		{
			$condition['l']  = $condition_part[0];
			$condition['r']  = $condition_part[1];
		}

		if (!isset($condition['op']) OR !in_array($condition['op'], ['==', '!=', '=<', '=>', '<', '>']))
		{
			$condition['op'] = '==';
		}

		return $condition;
	}

	/**
	 * Gets message sent to client.
	 *
	 * @return  string|NULL
	 */
	public function get_message()
	{
		return $this->message;
	}

	/**
	 * Gets last assigned action.
	 *
	 * @return  string
	 */
	public function get_action()
	{
		return strtolower($this->action);
	}

} // end of class Security


text:
void Engine::loadLevel() {
	m_Playing = false;

	// Delete the previously allocated memory
	for (int i = 0; i < m_LM.getLevelSize().y; ++i)
	{
		delete[] m_ArrayLevel[i];

	}
	delete[] m_ArrayLevel;
	// Load the next 2d array with the map for the level
	// And repopulate the vertex array as well
	m_ArrayLevel = m_LM.nextLevel(m_VALevel);

	// Prepare sound
	populateEmitters(m_FireEmitters, m_ArrayLevel);

	// How long is this new time limit
	m_TimeRemaining = m_LM.getTimeLimit();

	// Spawn Thomas and Bob
	m_Thomas.spawn(m_LM.getStartPosition(), GRAVITY);
	m_Bob.spawn(m_LM.getStartPosition(), GRAVITY);

	// Make sure this code isn't run again
	m_NewLevelRequired = false;
}


text:
_[www.codever.land/bookmarks/t/development](https://www.codever.land/bookmarks/t/development)_
---
#### [Taimoor Sattar | tech articles and entrepreneur](https://taimoorsattar.dev)
_https://taimoorsattar.dev_

I'm a full-stack developer. I write about tech articles and entrepreneur. I write about content that more related to problem-solving related to programming, money, and the latest trends.
* :calendar: **published on**: 2021-01-12
* **tags**: [javascript](../tagged/javascript.md), [website](../tagged/website.md), [development](../tagged/development.md), [blog](../tagged/blog.md)
* :octocat: **[source code](https://github.com/taimoorsattar7/taimoorsattar.dev)**
---
#### [Developer Roadmaps](https://roadmap.sh/)
_https://roadmap.sh/_

Community driven roadmaps, articles, guides, quizzes, tips and resources for developers to learn from, identify their career paths, know what they don't know, find out the knowledge gaps, learn and im...
* **tags**: [roadmaps](../tagged/roadmaps.md), [development](../tagged/development.md)
* :octocat: **[source code](https://github.com/kamranahmedse/developer-roadmap)**
---
#### [GitHub - EbookFoundation/free-programming-books: Freely available programming books](https://github.com/EbookFoundation/free-programming-books?utm_campaign=explore-email&utm_medium=email&utm_source=newsletter&utm_term=daily)
_https://github.com/EbookFoundation/free-programming-books?utm_campaign=explore-email&utm_medium=emai..._

:books: Freely available programming books. Contribute to EbookFoundation/free-programming-books development by creating an account on GitHub.
* **tags**: [programming](../tagged/programming.md), [development](../tagged/development.md)
---
#### [GitHub - codingsett/telepota: Python3 wrapper/library that simplifies telegram bot development](https://github.com/codingsett/telepota)
_https://github.com/codingsett/telepota_

Python3 wrapper/library that simplifies telegram bot development. It supports both sync and asyncio methods of programming. Dive in and start making awesome bots! - codingsett/telepota
* **tags**: [telegram-bot](../tagged/telegram-bot.md), [python](../tagged/python.md), [development](../tagged/development.md)
---
#### [Developer Roadmaps](https://roadmap.sh/roadmaps)
_https://roadmap.sh/roadmaps_

* **tags**: [roadmaps](../tagged/roadmaps.md), [development](../tagged/development.md)
---
#### [Tools | the New DynamicTwitter_Logo_Blue](https://www.thenewdynamic.org/tool/)
_https://www.thenewdynamic.org/tool/_

A curated collection of tools and services
* **tags**: [dev](../tagged/dev.md), [development](../tagged/development.md), [programming](../tagged/programming.md), [tools](../tagged/tools.md)
---
#### [the New Dynamic](https://www.thenewdynamic.org/)
_https://www.thenewdynamic.org/_

* **tags**: [dev](../tagged/dev.md), [development](../tagged/development.md), [programming](../tagged/programming.md), [tools](../tagged/tools.md)
---
#### [GitHub - joshwcomeau/react-collection-helpers: A suite of composable utility components to manipulate collections.](https://github.com/joshwcomeau/react-collection-helpers)
_https://github.com/joshwcomeau/react-collection-helpers_

A suite of composable utility components to manipulate collections. - joshwcomeau/react-collection-helpers
* :calendar: **published on**: 2020-01-13
* **tags**: [development](../tagged/development.md)
* :octocat: **[source code](https://github.com/joshwcomeau/react-collection-helpers)**
---
#### [AspectJ](https://eclipse.org/aspectj)
_https://eclipse.org/aspectj_

Seamless aspect-oriented programming extension.
* **tags**: [java](../tagged/java.md), [development](../tagged/development.md)
---
#### [DCEVM](https://dcevm.github.io)
_https://dcevm.github.io_

JVM modification that allows unlimited redefinition of loaded classes at runtime.
* **tags**: [java](../tagged/java.md), [development](../tagged/development.md)
---
#### [Faux Pas](https://github.com/zalando/faux-pas)
_https://github.com/zalando/faux-pas_

Library that simplifies error handling by circumventing the issue that none of the functional interfaces in the Java Runtime is allowed by default to throw checked exceptions.
* **tags**: [java](../tagged/java.md), [development](../tagged/development.md)
* :octocat: **[source code](https://github.com/zalando/faux-pas)**
---
#### [HotswapAgent](https://github.com/HotswapProjects/HotswapAgent)
_https://github.com/HotswapProjects/HotswapAgent_

Unlimited runtime class and resource redefinition.
* **tags**: [java](../tagged/java.md), [development](../tagged/development.md)
* :octocat: **[source code](https://github.com/HotswapProjects/HotswapAgent)**
---
#### [JavaParser](https://github.com/javaparser/javaparser)
_https://github.com/javaparser/javaparser_

Parse, modify and generate Java code.
* **tags**: [java](../tagged/java.md), [development](../tagged/development.md)
* :octocat: **[source code](https://github.com/javaparser/javaparser)**
---
#### [JavaSymbolSolver](https://github.com/javaparser/javasymbolsolver)
_https://github.com/javaparser/javasymbolsolver_

A symbol solver for Java.
* **tags**: [java](../tagged/java.md), [development](../tagged/development.md)
* :octocat: **[source code](https://github.com/javaparser/javasymbolsolver)**
---
#### [JRebel ![c](https://zeroturnaround.com/software/jrebel)
_https://zeroturnaround.com/software/jrebel_

Instantly reloads code and configuration changes without redeploys.
* **tags**: [java](../tagged/java.md), [development](../tagged/development.md)
---
#### [NoException](https://noexception.machinezoo.com)
_https://noexception.machinezoo.com_

Allows checked exceptions in functional interfaces and converts exceptions to Optional return.
* **tags**: [java](../tagged/java.md), [development](../tagged/development.md)
---
#### [SneakyThrow](https://github.com/rainerhahnekamp/sneakythrow)
_https://github.com/rainerhahnekamp/sneakythrow_

Ignores checked exceptions without bytecode manipulation. Can also be used inside Java 8 stream operations.
* **tags**: [java](../tagged/java.md), [development](../tagged/development.md)
* :octocat: **[source code](https://github.com/rainerhahnekamp/sneakythrow)**
---


text:
<?php defined('BX_DOL') or die('hack attempt');

/**
 * System services related to Extended Search.
 *
 * @see BxDolSearchExtended
 */
class BxBaseSearchExtendedServices extends BxDol
{
    public function __construct()
    {
        parent::__construct();
    }

    public function serviceGetForm($aParams)
    {
        $this->prepareParams($aParams);

        if(empty($aParams['object']))
            return '';

        $oSearch = BxDolSearchExtended::getObjectInstance($aParams['object']);
        if(!$oSearch || !$oSearch->isEnabled())
            return '';

        return $oSearch->getForm($aParams);
    }

    public function serviceGetResults($aParams)
    {
        $this->prepareParams($aParams);

        if(empty($aParams['object']))
            return '';

        $oSearch = BxDolSearchExtended::getObjectInstance($aParams['object']);
        if(!$oSearch || !$oSearch->isEnabled())
            return '';

        $sResults = $oSearch->getResults($aParams);

        return !empty($sResults) ? $sResults : (isset($aParams['show_empty']) && (bool)$aParams['show_empty'] ? MsgBox(_t('_Empty')) : '');
    }

    public function prepareParams(&$aParams)
    {
        if(empty($aParams['object']) && bx_get('object') !== false)
            $aParams['object'] = bx_process_input(bx_get('object'), BX_DATA_TEXT);

        if(!isset($aParams['show_empty']) && bx_get('show_empty') !== false)
            $aParams['show_empty'] = (bool)bx_get('show_empty');

        if(empty($aParams['template']) && bx_get('template') !== false)
            $aParams['template'] = bx_process_input(bx_get('template'), BX_DATA_TEXT);

        if(empty($aParams['cond']) && bx_get('cond') !== false)
            $aParams['cond'] = BxDolSearchExtended::decodeConditions(bx_process_input(bx_get('cond'), BX_DATA_TEXT));

        if(!isset($aParams['start']) && bx_get('start') !== false)
            $aParams['start'] = (int)bx_get('start');

        if(!isset($aParams['per_page']) && bx_get('per_page') !== false)
            $aParams['per_page'] = (int)bx_get('per_page');
    }
}

/** @} */


text:
{{<govuk_template}}

{{$head}}
  {{>includes/elements_head}}

{{/head}}

{{$propositionHeader}}
  {{>includes/govuk_vmacquireprop}}
{{/propositionHeader}}

{{$headerClass}}with-proposition{{/headerClass}}

{{$content}}

<link href="/public/stylesheets/application.css" media="screen" rel="stylesheet" type="text/css" />

<link href="/public/stylesheets/numberplate.css" media="screen" rel="stylesheet" type="text/css" />

Provide trader details

	<form method="get" action="find-postcode" class="form" data-parsley-validate>
		<input type="hidden" name="nextlink" value="vm-acquire-trader">
	    <input type="hidden" name="regmark" value="{{defaultreg}}">
	    <input type="hidden" name="email" value="{{email}}">
		<input type="hidden" name="paynum" value="{{paynum}}">
		<input type="hidden" name="kind" value="{{kind}}">

		Trader name

		Name of the company that the vehicle is being sold from

		<input id="tradername" name="tradername" autocomplete="off" class="form-control  input-large form-control-1-3" type="text" required style="text-transform:uppercase" />

		<legend style="padding:3em 0 0 0">Do you want to provide your email address?</legend>
		This may help us resolve problems later.

		<fieldset class="inline">

			<input id="radio-inline-1" type="radio"  name="emailreceipt" value="Y">
			Yes

			<input id="radio-inline-2" type="radio"  name="emailreceipt" value="N">
			No

		</fieldset>

		    Trader email address

			Please enter a valid email address

			<input id="email" name="email" type="email" class="form-control input-large" data-parsley-trigger="change" data-parsley-id="7756"required data-parsley-required-message="You must provide an email so we can send your direct debit schedule" />

		    Postcode

			<input id="postcode" name="postcode" autocomplete="off" class="form-control input-large form-control-1-4" type="text" required style="text-transform:uppercase">

			<input type="submit" class="button" value="Find address">

    </form>

{{/content}}

{{$bodyEnd}}
  {{>includes/elements_scripts}}
{{/bodyEnd}}

{{/govuk_template}}


text:
/*-------------------------------------------------------------------------
  Copyright 2008 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
// .NAME vtkApplyIcons - apply icons to a data set.
//
// .SECTION Description
// vtkApplyIcons performs a iconing of the dataset using default icons,
// lookup tables, annotations, and/or a selection. The output is a
// vtkIntArray containing the icon index for each
// element in the dataset. The first input is the dataset to be iconed, which
// may be a vtkTable, vtkGraph subclass, or vtkDataSet subclass.
//
// The second (optional) input is a vtkAnnotationLayers object, which stores
// a list of annotation layers, with each layer holding a list of
// vtkAnnotation objects. The annotation specifies a subset of data along with
// other properties, including icon. For annotations with icon properties,
// this algorithm will use the icon index of annotated elements,
// using a "top one wins" strategy.
//
// The third (optional) input is a vtkSelection object, meant for specifying
// the current selection. You can control the icon of the selection, or whether
// there is a set of selected icons at a particular offset in the icon sheet.
//
// The algorithm takes an input array, specified with
// SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, name)
// This sets data arrays to use to icon the data with
// the associated lookup table. For vtkGraph and vtkTable inputs, you would use
// FIELD_ASSOCIATION_VERTICES, FIELD_ASSOCIATION_EDGES, or
// FIELD_ASSOCIATION_ROWS as appropriate. The icon array will be added to the same
// set of attributes that the input array came from. If there is no input array,
// the icon array will be applied to the attributes associated with the
// AttributeType parameter.
//
// Icons are assigned with the following priorities:
//

//
 If an item is part of the selection, it is glyphed with that icon.
//
 Otherwise, if the item is part of an annotation, it is glyphed
//      with the icon of the final (top) annotation in the set of layers.
//
 Otherwise, if a lookup table is used, it is glyphed using the
//      lookup table icon for the data value of the element.
//
 Otherwise it will be glyphed with the default icon.
//

#ifndef __vtkApplyIcons_h
#define __vtkApplyIcons_h

#include "vtkViewsInfovisModule.h" // For export macro
#include "vtkPassInputTypeAlgorithm.h"
#include "vtkVariant.h" // For variant arguments.

class VTKVIEWSINFOVIS_EXPORT vtkApplyIcons : public vtkPassInputTypeAlgorithm
{
public:
  static vtkApplyIcons *New();
  vtkTypeMacro(vtkApplyIcons, vtkPassInputTypeAlgorithm);
  void PrintSelf(ostream& os, vtkIndent indent);

  // Description:
  // Edits the lookup table to use for point icons. This is only used if
  // input array 0 is set and UsePointLookupTable is on.
  void SetIconType(vtkVariant v, int icon);
  void SetIconType(double v, int icon)
    { this->SetIconType(vtkVariant(v), icon); }
  void SetIconType(const char* v, int icon)
    { this->SetIconType(vtkVariant(v), icon); }
  void ClearAllIconTypes();

  // Description:
  // If on, uses the point lookup table to set the colors of unannotated,
  // unselected elements of the data.
  vtkSetMacro(UseLookupTable, bool);
  vtkGetMacro(UseLookupTable, bool);
  vtkBooleanMacro(UseLookupTable, bool);

  // Description:
  // The default point icon for all unannotated, unselected elements
  // of the data. This is used if UsePointLookupTable is off.
  vtkSetMacro(DefaultIcon, int);
  vtkGetMacro(DefaultIcon, int);

  // Description:
  // The point icon for all selected elements of the data.
  // This is used if the annotation input has a current selection.
  vtkSetMacro(SelectedIcon, int);
  vtkGetMacro(SelectedIcon, int);

  // Description:
  // The output array name for the point icon index array.
  // Default is "vtkApplyIcons icon".
  vtkSetStringMacro(IconOutputArrayName);
  vtkGetStringMacro(IconOutputArrayName);

  //BTX
  enum
  {
    SELECTED_ICON,
    SELECTED_OFFSET,
    ANNOTATION_ICON,
    IGNORE_SELECTION
  };
  //ETX

  // Description:
  // Changes the behavior of the icon to use for selected items.
  //

  //
SELECTED_ICON uses SelectedIcon as the icon for all selected elements.
  //
SELECTED_OFFSET uses SelectedIcon as an offset to add to all selected elements.
  //
ANNOTATION_ICON uses the ICON_INDEX() property of the current annotation.
  //
IGNORE_SELECTION does not change the icon based on the current selection.
  //

  // The default is IGNORE_SELECTION.
  vtkSetMacro(SelectionMode, int);
  vtkGetMacro(SelectionMode, int);
  virtual void SetSelectionModeToSelectedIcon()
    { this->SetSelectionMode(SELECTED_ICON); }
  virtual void SetSelectionModeToSelectedOffset()
    { this->SetSelectionMode(SELECTED_OFFSET); }
  virtual void SetSelectionModeToAnnotationIcon()
    { this->SetSelectionMode(ANNOTATION_ICON); }
  virtual void SetSelectionModeToIgnoreSelection()
    { this->SetSelectionMode(IGNORE_SELECTION); }

  // Description:
  // The attribute type to append the icon array to, used only if the
  // input array is not specified or does not exist. This is set to one
  // of the AttributeTypes enum in vtkDataObject (e.g. POINT, CELL, VERTEX
  // EDGE, FIELD).
  vtkSetMacro(AttributeType, int);
  vtkGetMacro(AttributeType, int);

protected:
  vtkApplyIcons();
  ~vtkApplyIcons();

  // Description:
  // Convert the vtkGraph into vtkPolyData.
  int RequestData(
    vtkInformation *, vtkInformationVector **, vtkInformationVector *);

  // Description:
  // Set the input type of the algorithm to vtkGraph.
  int FillInputPortInformation(int port, vtkInformation* info);

  int DefaultIcon;
  int SelectedIcon;
  bool UseLookupTable;
  char* IconOutputArrayName;
  int SelectionMode;
  int AttributeType;

  //BTX
  class Internals;
  Internals* Implementation;
  //ETX

private:
  vtkApplyIcons(const vtkApplyIcons&);  // Not implemented.
  void operator=(const vtkApplyIcons&);  // Not implemented.
};

#endif


text:
using DocumentFormat.OpenXml.Office.Excel;
using X14 = DocumentFormat.OpenXml.Office2010.Excel;

namespace SpreadsheetLightWrapper.Core.office2010
{
    internal class SLConditionalFormattingValueObject2010
    {
        internal SLConditionalFormattingValueObject2010()
        {
            SetAllNull();
        }

        //http://msdn.microsoft.com/en-us/library/documentformat.openxml.office2010.excel.conditionalformattingvalueobject.aspx

        internal string Formula { get; set; }
        internal X14.ConditionalFormattingValueObjectTypeValues Type { get; set; }
        internal bool GreaterThanOrEqual { get; set; }

        private void SetAllNull()
        {
            Formula = string.Empty;
            Type = X14.ConditionalFormattingValueObjectTypeValues.Percentile;
            GreaterThanOrEqual = true;
        }

        internal void FromConditionalFormattingValueObject(X14.ConditionalFormattingValueObject cfvo)
        {
            SetAllNull();

            if (cfvo.Formula != null) Formula = cfvo.Formula.Text;
            Type = cfvo.Type.Value;
            if (cfvo.GreaterThanOrEqual != null) GreaterThanOrEqual = cfvo.GreaterThanOrEqual.Value;
        }

        internal X14.ConditionalFormattingValueObject ToConditionalFormattingValueObject()
        {
            var cfvo = new X14.ConditionalFormattingValueObject();

            if (Formula.Length > 0)
                if (Formula.StartsWith("="))
                    cfvo.Formula = new Formula(Formula.Substring(1));
                else
                    cfvo.Formula = new Formula(Formula);
            cfvo.Type = Type;
            if (!GreaterThanOrEqual) cfvo.GreaterThanOrEqual = GreaterThanOrEqual;

            return cfvo;
        }

        internal SLConditionalFormattingValueObject2010 Clone()
        {
            var cfvo = new SLConditionalFormattingValueObject2010();
            cfvo.Formula = Formula;
            cfvo.Type = Type;
            cfvo.GreaterThanOrEqual = GreaterThanOrEqual;

            return cfvo;
        }
    }
}