text:
#include "J2716SimulationDataGenerator.h"
#include "J2716AnalyzerSettings.h"

#include <AnalyzerHelpers.h>

J2716SimulationDataGenerator::J2716SimulationDataGenerator()
:	mSerialText( "My first analyzer, woo hoo!" ),
	u32MicroSecondVal( 0 )
{
}

J2716SimulationDataGenerator::~J2716SimulationDataGenerator()
{
}

void J2716SimulationDataGenerator::Initialize( U32 simulation_sample_rate, J2716AnalyzerSettings* settings )
{
	mSimulationSampleRateHz = simulation_sample_rate;
	mSettings = settings;

	mSerialSimulationData.SetChannel( mSettings->mInputChannel );
	mSerialSimulationData.SetSampleRate( simulation_sample_rate );
	mSerialSimulationData.SetInitialBitState( BIT_HIGH );
}

U32 J2716SimulationDataGenerator::GenerateSimulationData( U64 largest_sample_requested, U32 sample_rate, SimulationChannelDescriptor** simulation_channel )
{
	U8 u8SampleIndex = 0;
	U8 au8DataSamples[ 8/*Rows*/ ][6/*Cols*/] = {	{ 0x4 , 0x7 , 0x8 , 0x3 , 0x4 , 0x7 }/*CRC=0xD*/,
													{ 0x4 , 0x7 , 0x8 , 0x3 , 0x4 , 0x3 }/*CRC=0x3*/,
													{ 0x4 , 0x7 , 0x8 , 0x3 , 0x4 , 0x5 }/*CRC=0xA*/,
													{ 0x4 , 0x7 , 0x8 , 0x3 , 0x4 , 0x4 }/*CRC=0x7*/,
													{ 0x4 , 0x7 , 0x7 , 0x3 , 0x4 , 0x5 }/*CRC=0xC*/,
													{ 0x4 , 0x7 , 0x9 , 0x3 , 0x4 , 0x5 }/*CRC=0xE*/,
													{ 0x4 , 0x7 , 0x9 , 0x3 , 0x4 , 0x6 }/*CRC=0x4*/,
													{ 0x4 , 0x7 , 0x7 , 0x3 , 0x4 , 0x7 }/*CRC=0xB*/};
	U32 u32SampleData = 0x00DA4256;
	const U32 ku32MegaHert = 1000000U;
	const U32 ku32MicroSecond = mSimulationSampleRateHz / ku32MegaHert;
	U64 adjusted_largest_sample_requested = AnalyzerHelpers::AdjustSimulationTargetSample( largest_sample_requested, sample_rate, mSimulationSampleRateHz );
	u32MicroSecondVal = ku32MicroSecond;

	while( mSerialSimulationData.GetCurrentSampleNumber() < adjusted_largest_sample_requested )
	{
		CreateSyncField();
		StartOfData();
		/*ToDo: Generate STATUS NUBBLE here*/
		/* DATA nibbles */
		CreateSerialNibbles( &au8DataSamples[ u8SampleIndex ][ 0 ] , mSettings->u32Nibbles );
		/* CRC */
		u8CrcVal = ComputeCrc( &au8DataSamples[ u8SampleIndex ][ 0 ] , mSettings->u32Nibbles );
		StartOfData( );				/*Start CRC*/
		AdvanceTicks( u8CrcVal );	/*Add CRC*/
		/* Optional PAUSE pulse */
		if( true == mSettings->boPauseFlg )
		{
			CreatePausePulse( );
		}
		else
		{
			/*do nothing*/
		}
		u8SampleIndex++;		/*Point to next sample buffer*/
		u8SampleIndex &= 0x7;	/*Mask index (in oder to select just from 0 to 7)*/
	}

	*simulation_channel = &mSerialSimulationData;
	return 1;
}

void J2716SimulationDataGenerator::CreateSerialNibbles( U8* pu8Data , U8 u8Len )
{
	for( U16 i = 0; i < u8Len; i++ )
	{
		StartOfData();
		AdvanceTicks( *pu8Data );
		pu8Data++;
	}
}

void J2716SimulationDataGenerator::CreateSyncField( )
{
	CreateLowPulse();
	AdvanceTicks( 51 );
}

void J2716SimulationDataGenerator::CreateLowPulse()
{
	mSerialSimulationData.TransitionIfNeeded( BIT_LOW );
	AdvanceTicks( ku8LowPulseTicks );
	mSerialSimulationData.TransitionIfNeeded( BIT_HIGH );
}

void J2716SimulationDataGenerator::CreatePausePulse( )
{
	CreateLowPulse();
	AdvanceTicks( 72 );
}

void J2716SimulationDataGenerator::AdvanceTicks( U8 u8Ticks )
{
	mSerialSimulationData.Advance( ( mSettings->mBitRate* u32MicroSecondVal ) * u8Ticks );
}

void J2716SimulationDataGenerator::StartOfData( )
{
	CreateLowPulse();
	AdvanceTicks( 7 );
}

U8 J2716SimulationDataGenerator::ComputeCrc( U8* pu8Data , U8 u8Len )
{
	const U8 kau8CrcLookupTbl[ 16 ] = { 0 , 13 , 7 , 10 , 14 , 3 , 9 , 4 , 1 , 12 , 6 , 11 , 15 , 2 , 8 , 5 };
	U8 u8Crc = ku8CrcSeed;/*Seed*/
	U8 u8Temp;
	for( U8 i = 0; i < u8Len; i++ )
	{
		u8Temp = kau8CrcLookupTbl[u8Crc];
		u8Crc = u8Temp ^  *pu8Data;
		pu8Data++;
	}
	u8Crc = kau8CrcLookupTbl[ u8Crc ];
	return u8Crc;
}


text:
import 'html-document/lib/global';
global.React = global.$ = require('springbokjs-dom/lib/$');
import express from 'express';
import errorParser from 'springbokjs-errors';
import expressEngine from 'turaco/lib/renderers/expressEngine';
const fs = require('fs');
const app = express();
const argv = require('minimist')(process.argv.slice(2));
const errorsParser = require('springbokjs-errors');
import ErrorHtmlRenderer from 'springbokjs-errors/lib/HtmlRenderer';
const errorHtmlRenderer = new ErrorHtmlRenderer();

process.on('uncaughtException', function(err) {
    try {
        errorsParser.log(err);
    } catch (err2) {
        console.error(err.stack);
        console.error(err2.stack);
    }
});

app.set('view engine', 'js');
app.set('views', __dirname + '/views');

app.engine('js', expressEngine(app.get('views')));

app.locals.code = function(args) {
    var contents = args[0]
        .trim()
        .replace(/&(?!\w+;)/g, '&')
        .replace(/</g, '<')
        .replace(/>/g, '>')
        .replace(/"/g, '"');
    return '
' + contents + '
';
};

app.use(express.static(__dirname + '/../public'));

app.use(function(err, req, res, next) {
    errorsParser.log(err);
    if (argv.production) {
        res.status(500).send('Error: ' + err.message);
    } else {
        res.status(500).send(errorHtmlRenderer.render(err));
    }
});

app.get('/', function(req, res) {
    res.render('Index');
});

app.get(/^[1-9a-zA-Z\/\-]+$/, function(req, res) {
    console.log(req.path);
    res.render(req.path.substr(1), { dataLayout: { category: req.path.split('/')[1] } });
});

app.listen(argv.port || 3000);

redpajama_set_name: RedPajamaGithub


text:
""" Formatting for all sorts of DNS Records """

from aquilon.aqdb.model import NsRecord
from aquilon.worker.formats.list import ListFormatter
from aquilon.worker.formats.formatters import ObjectFormatter

class NsRecordFormatter(ObjectFormatter):
    template_raw = "ns_record.mako"

    def csv_fields(self, ns):
        yield (ns.dns_domain.name, ns.a_record.fqdn)

    def format_djb(self, ns):
        return ".%s::%s" % (ns.dns_domain.name, ns.a_record.fqdn)

ObjectFormatter.handlers[NsRecord] = NsRecordFormatter()

class SimpleNSRecordList(list):
    """By convention, holds a list of ns_records to be formatted in a simple
       (dns_domain: fqdn-only) manner."""
    pass

class SimpleNSRecordListFormatter(ListFormatter):
    def format_raw(self, snsrlist, indent="", embedded=True,
                   indirect_attrs=True):
        # return [self.redirect_raw(ns) for ns in snsrlist]
        # return "\n".join(
        #    [indent + ns.dns_domain.name + ": " + ns.a_record.fqdn for ns in snsrlist])

        return "\n".join(indent + self.redirect_raw(ns) for ns in snsrlist)

ObjectFormatter.handlers[SimpleNSRecordList] = SimpleNSRecordListFormatter()


text:
module EntryTypesHelper
end


text:
package com.intellij.codeInsight.intention.impl.config;

import com.intellij.ide.ui.search.SearchUtil;
import com.intellij.ide.ui.search.SearchableOptionsRegistrar;
import com.intellij.openapi.options.MasterDetails;
import com.intellij.openapi.ui.DetailsComponent;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.GuiUtils;
import com.intellij.util.Alarm;
import org.jetbrains.annotations.NonNls;

import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class IntentionSettingsPanel implements MasterDetails {
  private JPanel myPanel;
  private final IntentionSettingsTree myIntentionSettingsTree;
  private final IntentionDescriptionPanel myIntentionDescriptionPanel = new IntentionDescriptionPanel();

  private JPanel myTreePanel;
  private JPanel myDescriptionPanel;
  private DetailsComponent myDetailsComponent;

  private final Alarm myResetAlarm = new Alarm();

  public IntentionSettingsPanel() {
    myIntentionSettingsTree = new IntentionSettingsTree() {
      @Override
      protected void selectionChanged(Object selected) {
        if (selected instanceof IntentionActionMetaData) {
          final IntentionActionMetaData actionMetaData = (IntentionActionMetaData)selected;
          final Runnable runnable = new Runnable() {
            @Override
            public void run() {
              intentionSelected(actionMetaData);
              if (myDetailsComponent != null) {
                String[] text = new String[actionMetaData.myCategory.length + 1];
                System.arraycopy(actionMetaData.myCategory, 0, text,0,actionMetaData.myCategory.length);
                text[text.length - 1] = actionMetaData.getFamily();
                myDetailsComponent.setText(text);
              }
            }
          };
          myResetAlarm.cancelAllRequests();
          myResetAlarm.addRequest(runnable, 100);
        }
        else {
          categorySelected((String)selected);
          if (myDetailsComponent != null) {
            myDetailsComponent.setText((String)selected);
          }
        }
      }

      @Override
      protected List<IntentionActionMetaData> filterModel(String filter, final boolean force) {
        final List<IntentionActionMetaData> list = IntentionManagerSettings.getInstance().getMetaData();
        if (filter == null || filter.length() == 0) return list;
        final HashSet<String> quoted = new HashSet<String>();
        List<Set<String>> keySetList = SearchUtil.findKeys(filter, quoted);
        List<IntentionActionMetaData> result = new ArrayList<IntentionActionMetaData>();
        for (IntentionActionMetaData metaData : list) {
          if (isIntentionAccepted(metaData, filter, force, keySetList, quoted)){
            result.add(metaData);
          }
        }
        final Set<String> filters = SearchableOptionsRegistrar.getInstance().getProcessedWords(filter);
        if (force && result.isEmpty()){
          if (filters.size() > 1){
            result = filterModel(filter, false);
          }
        }
        return result;
      }
    };
    myTreePanel.setLayout(new BorderLayout());
    myTreePanel.add(myIntentionSettingsTree.getComponent(), BorderLayout.CENTER);

    GuiUtils.replaceJSplitPaneWithIDEASplitter(myPanel);

    myDescriptionPanel.setLayout(new BorderLayout());
    myDescriptionPanel.add(myIntentionDescriptionPanel.getComponent(), BorderLayout.CENTER);
  }

  private void intentionSelected(IntentionActionMetaData actionMetaData) {
    myIntentionDescriptionPanel.reset(actionMetaData, myIntentionSettingsTree.getFilter());
  }

  private void categorySelected(String intentionCategory) {
    myIntentionDescriptionPanel.reset(intentionCategory);
  }

  public void reset() {
    myIntentionSettingsTree.reset();
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        myIntentionDescriptionPanel.init(myPanel.getWidth() / 2);
      }
    });
  }

  @Override
  public void initUi() {
    myDetailsComponent = new DetailsComponent();
    myDetailsComponent.setContent(myDescriptionPanel);
  }

  @Override
  public JComponent getToolbar() {
    return myIntentionSettingsTree.getToolbarPanel();
  }

  @Override
  public JComponent getMaster() {
    return myTreePanel;
  }

  @Override
  public DetailsComponent getDetails() {
    return myDetailsComponent;
  }

  public void apply() {
    myIntentionSettingsTree.apply();
  }

  public JPanel getComponent() {
    return myPanel;
  }

  public JTree getIntentionTree(){
    return myIntentionSettingsTree.getTree();
  }

  public boolean isModified() {
    return myIntentionSettingsTree.isModified();
  }

  public void dispose() {
    myIntentionSettingsTree.dispose();
    myIntentionDescriptionPanel.dispose();
  }

  public void selectIntention(String familyName) {
    myIntentionSettingsTree.selectIntention(familyName);
  }

  private static boolean isIntentionAccepted(IntentionActionMetaData metaData, @NonNls String filter, boolean forceInclude,
                                             final List<Set<String>> keySetList, final HashSet<String> quoted) {
    if (StringUtil.containsIgnoreCase(metaData.getFamily(), filter)) {
      return true;
    }
    for (String category : metaData.myCategory) {
      if (category != null && StringUtil.containsIgnoreCase(category, filter)) {
        return true;
      }
    }
    for (String stripped : quoted) {
      if (StringUtil.containsIgnoreCase(metaData.getFamily(), stripped)) {
        return true;
      }
      for (String category : metaData.myCategory) {
        if (category != null && StringUtil.containsIgnoreCase(category, stripped)) {
          return true;
        }
      }
      try {
        final TextDescriptor description = metaData.getDescription();
        if (StringUtil.containsIgnoreCase(description.getText(), stripped)){
          if (!forceInclude) return true;
        } else if (forceInclude) return false;
      }
      catch (IOException e) {
        //skip then
      }
    }
    for (Set<String> keySet : keySetList) {
      if (keySet.contains(metaData.getFamily())) {
        if (!forceInclude) {
          return true;
        }
      }
      else {
        if (forceInclude) {
          return false;
        }
      }
    }
    return forceInclude;
  }

  public Runnable showOption(final String option) {
    return new Runnable() {
      @Override
      public void run() {
        myIntentionSettingsTree.filter(myIntentionSettingsTree.filterModel(option, true));
        myIntentionSettingsTree.setFilter(option);
      }
    };
  }
}


text:
using System;

namespace PcfProvider.ServiceBindings
{
	public class RootObject : InfoBase.RootObject<PcfServiceBinding>
	{
	}
}


text:
\section{The \variant{\edgetransitions} problem}
\label{sec:edges}

Whereas \variant{\nodeitems} (Problem~\ref{problem:nodes-variant}) seeks $k$
nodes to optimize expected uncertainty, \variant{\edgetransitions} seeks
$k$ edges.
\begin{problem}[{\edgeproblem}]
Given $G=(V,E)$, transition matrix $\transition$,
initial distribution of items to nodes
$\initial$ and integer $k$, find
$S\subseteq V$ such that $|S|=k$ such that
$\objective_\shortedgetransitions\left(S\right)$
(Equation~\eqref{eq:edgetransitions}) is minimized.
\label{problem:edges-variant}
\end{problem}
We provide two polynomial-time algorithms to solve
the problem, namely \edgeDP\ and \edgegreedy.
For the former, we can also prove that it is optimal, and thus Problem~\ref{problem:edges-variant}
is solvable in polynomial time.

\spara{The {\edgeDP} algorithm:}
{\edgeDP} is a dynamic-programming algorithm that
selects edges in two steps: first, it sorts the {\it outgoing}
edges of
each node in decreasing order of transition probability, thus
creating $|V| = n$ corresponding lists; secondly, it combines top edges from
each list to select a total of $k$ edges.
%The algorithm is polynomial and optimal.

In more detail, let $SOL_i(k)$ be the cost
of an optimal solution for the special case of
a budget of $k$ edges allocated among outgoing edges of nodes
$V_{i:} = \{i, i+1, \ldots, n\}$.
According to this notational convention,
the cost of an optimal solution $D_{opt}$ for the problem is given by
$SOL_1(k)$.
%  --
% and we define $SOL_i(k) = \infty$ for $k < 0$ and $SOL_i(k) = 0$
% for $i > \|V\| = n$.
Moreover, considering Equation~\eqref{eq:edgetransitions},
let $\objective_i$ be the function that corresponds to
the (outer) summation term for node $i$
\begin{equation}
	\objective_i(D) = \initial^{\prime\prime}(i)\sum_{v\in V\setminus S}\transition^{\prime\prime}(i,v)\left(1-\transition^{\prime\prime}(i,v)\right)
\end{equation}
(under the auxilliary definitions of Equations \eqref{eq:etinit}
and \eqref{eq:ettransit})
and $ISOL_i(m)$ its optimal value when $D$ contains no more than
$m\leq k$ outgoing edges from node $i$.
Let also $D_i^m$ be a subset of $k$ outgoing edges of $i$
with the highest transition
probabilities.
It can be shown that the optimal value
for $\objective_i(D)$ is achieved for
the edges $D_i^k$ with {\it highest} transition
probability\footnote{For a proof,
see Supplementary Material, Lemma~\ref{lemma:singlenodeoptimality}.}.
Having the outgoing edges of $i$ sorted by transition probability,
we can compute $ISOL_i(m)$ for all $m = 0\ldots k$.

The dynamic programming equation is:
\begin{equation}
	SOL_i(k) = \argmin_{0\leq m\leq k}\{ISOL_i(m) + SOL_{i+1}(k - m)\}
	\label{eq:dptop}
\end{equation}
\edgeDP\ essentially computes and keeps in memory
$\|V\| \times (k+1)$ values according to Eq.\eqref{eq:dptop}.

Given the above, we have the following result:

\begin{lemma}
The {\edgeDP} algorithm is optimal for the {\edgeproblem} problem.
\end{lemma}

% \begin{algorithm}
% \LinesNumbered
%  \KwIn{k}
%  \KwOut{SOL: Dynamic programming array}
%  initialize empty array $SOL_{\|V\| \times (k+1)}$;\\
%  \For{i = $\|V\|$..1}{
%   \For{$k'$ = 0:k}{
%     SOL[$i$, $k'$] := $\argmin_{0\leq k_i\leq k'}\{ISOL_i(k_i) + SOL[i+1, k' - k_i]\}\}$
%    }
%  }
%  \Return SOL;
%  \caption{Dynamic programming algorithm for the \edgetransitions\ variant.}
%  \label{alg:edgeDP}
% \end{algorithm}

For a proof sketch of this lemma see Supplementary Material,
Theorem~\ref{theorem:edgeDP}.

\emph{Running time:} \edgeDP\
computes $k\times |V|$ values. For each value to be
computed, up to $O(k)$ numerical operations are performed. Therefore,
\edgeDP\ runs in $O(k^2|V|)$ operations. Backtracking to retrieve the
optimal solution requires at most equal number of steps, so it does not
increase the asymptotic running time.

\spara{The {\edgegreedy} algorithm:}
\edgegreedy\ is a natural greedy algorithm that selects
$k$ edges in an equal number of steps, in each step selecting
one more edge to minimize $\objective_{\shortedgetransitions}$.
% \edgegreedy\ is described in Algorithm~\ref{alg:edgegreedy}.

% \begin{algorithm}
% \LinesNumbered
%  \KwIn{k}
%  \KwOut{$ResultEdges$: Set of selected edges}
%  $ResultEdges$ = $\{\}$ \\
%  \For{$i = 1 \cdots k$}{
%  	Select $e\in E$ :=
%  		$\argmin \objective_{\shortedgetransitions}(ResultEdges \cup \{e\})$ \\
%  	$ResultEdges$ := $ResultEdges$ $\cup$ \{e\}; \\
%  	E := E $\setminus$ \{e\}; \\
%  }
%  \Return $ResultEdges$;
%  \caption{Greedy algorithm for the \edgetransitions\ variant.}
%  \label{alg:edgegreedy}
% \end{algorithm}

%Unfortunately, we have not been able to prove or dispove optimality
%for \edgegreedy.

In all our experiments the performance of {\edgegreedy} is the same as the performance of
the optimal {\edgeDP} algorithm. However, we do not have a proof that the former is also optimal. We leave this as a problem for future work.

\emph{Running time:} Following Equation \eqref{eq:edgetransitions},
to select $k$ edges,
\edgegreedy\ %as defined in Algorithm~\ref{alg:edgegreedy}
invokes up to $k\times O(|E|)$ evaluations of
$\objective_{\shortedgetransitions}$.
% ; and each evaluation of
% $\objective_{\shortedgetransitions}$ involves $O(|E|)$ numerical operations.
As we discussed for \nodegreedy, if the evaluation of the
objective function is naively implemented with a double summation,
the running time of \edgegreedy\ is
$O(k|E||V|^2)$ numerical operations.
If the objective function is implemented as a summation over edges,
the running time improves to $O(k|E|^2)$.
Furthermore, following the observations similar to those we saw for {\nodegreedy}, the
running time of \edgegreedy\ becomes $O(|E| + k|E|) = O(k|E|)$.

We notice that \edgeDP\ has better
performance than \edgegreedy\ for dense graphs ($|E|\approxeq |V|^2$)
and small $k$. Moreover, as with \nodegreedy, \edgegreedy\ is
amenable to parallelization - the new value of the objective function
can be computed in independently for each edge that's considered for
selection.

% We have the following theorem for \edgegreedy.
% \begin{theorem}
% \edgegreedy\ is optimal for the \edgetransitions\ variant of
% the \mcproblem\ problem.
% \label{theorem:edgegreedy}
% \end{theorem}
% The proof for Theorem~\ref{theorem:edgegreedy} mirrors the proof for
% Theorem~\ref{theorem:nodegreedy}, adjusted to the selection of edges instead
% of nodes - and is omitted for brevity.


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="GenericMonthTest.cs" company="OBeautifulCode">
//   Copyright (c) OBeautifulCode 2018. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace OBeautifulCode.AccountingTime.Test
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Linq;

    using FakeItEasy;

    using OBeautifulCode.Assertion.Recipes;
    using OBeautifulCode.AutoFakeItEasy;
    using OBeautifulCode.CodeAnalysis.Recipes;
    using OBeautifulCode.CodeGen.ModelObject.Recipes;

    using Xunit;

    public static partial class GenericMonthTest
    {
        [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = ObcSuppressBecause.CA1810_InitializeReferenceTypeStaticFieldsInline_FieldsDeclaredInCodeGeneratedPartialTestClass)]
        static GenericMonthTest()
        {
            var referenceGenericMonth = A.Dummy<GenericMonth>();

            ConstructorArgumentValidationTestScenarios
                .RemoveAllScenarios()
                .AddScenario(() =>
                    new ConstructorArgumentValidationTestScenario<GenericMonth>
                    {
                        Name = "Constructor should throw ArgumentOutOfRangeException when parameter 'year' is < 0",
                        ConstructionFunc = () => new GenericMonth(A.Dummy<NegativeInteger>(), referenceGenericMonth.MonthNumber),
                        ExpectedExceptionMessageContains = new[] { "'year' < '1'" },
                        ExpectedExceptionType = typeof(ArgumentOutOfRangeException),
                    })
                .AddScenario(() =>
                    new ConstructorArgumentValidationTestScenario<GenericMonth>
                    {
                        Name = "Constructor should throw ArgumentOutOfRangeException when parameter 'year' = 0",
                        ConstructionFunc = () => new GenericMonth(0, referenceGenericMonth.MonthNumber),
                        ExpectedExceptionMessageContains = new[] { "'year' < '1'" },
                        ExpectedExceptionType = typeof(ArgumentOutOfRangeException),
                    })
                .AddScenario(() =>
                    new ConstructorArgumentValidationTestScenario<GenericMonth>
                    {
                        Name = "Constructor should throw ArgumentOutOfRangeException when parameter 'year' = 10000",
                        ConstructionFunc = () => new GenericMonth(10000, referenceGenericMonth.MonthNumber),
                        ExpectedExceptionMessageContains = new[] { "'year' > '9999'" },
                        ExpectedExceptionType = typeof(ArgumentOutOfRangeException),
                    })
                .AddScenario(() =>
                    new ConstructorArgumentValidationTestScenario<GenericMonth>
                    {
                        Name = "Constructor should throw ArgumentOutOfRangeException when parameter 'year' > 9999",
                        ConstructionFunc = () => new GenericMonth(A.Dummy<PositiveInteger>().ThatIs(_ => _ > 9999, -1), referenceGenericMonth.MonthNumber),
                        ExpectedExceptionMessageContains = new[] { "'year' > '9999'" },
                        ExpectedExceptionType = typeof(ArgumentOutOfRangeException),
                    })
                .AddScenario(() =>
                    new ConstructorArgumentValidationTestScenario<GenericMonth>
                    {
                        Name = "Constructor should throw ArgumentOutOfRangeException when parameter 'monthNumber' is MonthNumber.Invalid",
                        ConstructionFunc = () => new GenericMonth(referenceGenericMonth.Year, MonthNumber.Invalid),
                        ExpectedExceptionMessageContains = new[] { "monthNumber", "Invalid" },
                        ExpectedExceptionType = typeof(ArgumentOutOfRangeException),
                    });

            ComparableTestScenarios
                .RemoveAllScenarios()
                .AddScenario(() =>
                    new ComparableTestScenario<GenericMonth>
                    {
                        Name = "Comparable Test Scenario",
                        ReferenceObject = referenceGenericMonth,
                        ObjectsThatAreLessThanReferenceObject = new[]
                        {
                            referenceGenericMonth.TweakBy(-1, GenericMonthComponent.Month),
                            referenceGenericMonth.TweakBy(-1, GenericMonthComponent.Year),
                        },
                        ObjectsThatAreGreaterThanReferenceObject = new[]
                        {
                            referenceGenericMonth.TweakBy(1, GenericMonthComponent.Month),
                            referenceGenericMonth.TweakBy(1, GenericMonthComponent.Year),
                        },
                        ObjectsThatAreEqualToButNotTheSameAsReferenceObject = new[]
                        {
                            referenceGenericMonth.DeepClone(),
                        },
                        ObjectsThatAreNotOfTheSameTypeAsReferenceObject = new[]
                            {
                                A.Dummy<object>(),
                                A.Dummy<string>(),
                                A.Dummy<int>(),
                                A.Dummy<int?>(),
                                A.Dummy<Guid>(),
                            }
                            .Concat(TestCommon.GetDummyOfEachUnitOfTimeKind().Where(_ => _.GetType() != typeof(GenericMonth)))
                            .ToList(),
                        ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject = new GenericMonth[]
                        {
                        },
                    });

            StringRepresentationTestScenarios
                .RemoveAllScenarios()
                .AddScenario(() =>
                    new StringRepresentationTestScenario<GenericMonth>
                    {
                        Name = "String Representation - case 1",
                        SystemUnderTestExpectedStringRepresentationFunc = () =>
                            new SystemUnderTestExpectedStringRepresentation<GenericMonth>
                            {
                                SystemUnderTest = new GenericMonth(2017, MonthNumber.One),
                                ExpectedStringRepresentation = "1st month of 2017",
                            },
                    })
                .AddScenario(() =>
                    new StringRepresentationTestScenario<GenericMonth>
                    {
                        Name = "String Representation - case 2",
                        SystemUnderTestExpectedStringRepresentationFunc = () =>
                            new SystemUnderTestExpectedStringRepresentation<GenericMonth>
                            {
                                SystemUnderTest = new GenericMonth(2017, MonthNumber.Two),
                                ExpectedStringRepresentation = "2nd month of 2017",
                            },
                    })
                .AddScenario(() =>
                    new StringRepresentationTestScenario<GenericMonth>
                    {
                        Name = "String Representation - case 3",
                        SystemUnderTestExpectedStringRepresentationFunc = () =>
                            new SystemUnderTestExpectedStringRepresentation<GenericMonth>
                            {
                                SystemUnderTest = new GenericMonth(2017, MonthNumber.Three),
                                ExpectedStringRepresentation = "3rd month of 2017",
                            },
                    })
                .AddScenario(() =>
                    new StringRepresentationTestScenario<GenericMonth>
                    {
                        Name = "String Representation - case 4",
                        SystemUnderTestExpectedStringRepresentationFunc = () =>
                            new SystemUnderTestExpectedStringRepresentation<GenericMonth>
                            {
                                SystemUnderTest = new GenericMonth(2017, MonthNumber.Four),
                                ExpectedStringRepresentation = "4th month of 2017",
                            },
                    })
                .AddScenario(() =>
                    new StringRepresentationTestScenario<GenericMonth>
                    {
                        Name = "String Representation - case 5",
                        SystemUnderTestExpectedStringRepresentationFunc = () =>
                            new SystemUnderTestExpectedStringRepresentation<GenericMonth>
                            {
                                SystemUnderTest = new GenericMonth(2017, MonthNumber.Five),
                                ExpectedStringRepresentation = "5th month of 2017",
                            },
                    })
                .AddScenario(() =>
                    new StringRepresentationTestScenario<GenericMonth>
                    {
                        Name = "String Representation - case 6",
                        SystemUnderTestExpectedStringRepresentationFunc = () =>
                            new SystemUnderTestExpectedStringRepresentation<GenericMonth>
                            {
                                SystemUnderTest = new GenericMonth(2017, MonthNumber.Six),
                                ExpectedStringRepresentation = "6th month of 2017",
                            },
                    })
                .AddScenario(() =>
                    new StringRepresentationTestScenario<GenericMonth>
                    {
                        Name = "String Representation - case 7",
                        SystemUnderTestExpectedStringRepresentationFunc = () =>
                            new SystemUnderTestExpectedStringRepresentation<GenericMonth>
                            {
                                SystemUnderTest = new GenericMonth(2017, MonthNumber.Seven),
                                ExpectedStringRepresentation = "7th month of 2017",
                            },
                    })
                .AddScenario(() =>
                    new StringRepresentationTestScenario<GenericMonth>
                    {
                        Name = "String Representation - case 8",
                        SystemUnderTestExpectedStringRepresentationFunc = () =>
                            new SystemUnderTestExpectedStringRepresentation<GenericMonth>
                            {
                                SystemUnderTest = new GenericMonth(2017, MonthNumber.Eight),
                                ExpectedStringRepresentation = "8th month of 2017",
                            },
                    })
                .AddScenario(() =>
                    new StringRepresentationTestScenario<GenericMonth>
                    {
                        Name = "String Representation - case 9",
                        SystemUnderTestExpectedStringRepresentationFunc = () =>
                            new SystemUnderTestExpectedStringRepresentation<GenericMonth>
                            {
                                SystemUnderTest = new GenericMonth(2017, MonthNumber.Nine),
                                ExpectedStringRepresentation = "9th month of 2017",
                            },
                    })
                .AddScenario(() =>
                    new StringRepresentationTestScenario<GenericMonth>
                    {
                        Name = "String Representation - case 10",
                        SystemUnderTestExpectedStringRepresentationFunc = () =>
                            new SystemUnderTestExpectedStringRepresentation<GenericMonth>
                            {
                                SystemUnderTest = new GenericMonth(2017, MonthNumber.Ten),
                                ExpectedStringRepresentation = "10th month of 2017",
                            },
                    })
                .AddScenario(() =>
                    new StringRepresentationTestScenario<GenericMonth>
                    {
                        Name = "String Representation - case 11",
                        SystemUnderTestExpectedStringRepresentationFunc = () =>
                            new SystemUnderTestExpectedStringRepresentation<GenericMonth>
                            {
                                SystemUnderTest = new GenericMonth(2017, MonthNumber.Eleven),
                                ExpectedStringRepresentation = "11th month of 2017",
                            },
                    })
                .AddScenario(() =>
                    new StringRepresentationTestScenario<GenericMonth>
                    {
                        Name = "String Representation - case 12",
                        SystemUnderTestExpectedStringRepresentationFunc = () =>
                            new SystemUnderTestExpectedStringRepresentation<GenericMonth>
                            {
                                SystemUnderTest = new GenericMonth(2017, MonthNumber.Twelve),
                                ExpectedStringRepresentation = "12th month of 2017",
                            },
                    });
        }

        [Fact]
        public static void UnitOfTimeKind__Should_return_Generic___When_called()
        {
            // Arrange
            var unitOfTime = A.Dummy<GenericMonth>();

            // Act
            var kind = unitOfTime.UnitOfTimeKind;

            // Assert
            kind.AsTest().Must().BeEqualTo(UnitOfTimeKind.Generic);
        }

        [Fact]
        public static void UnitOfTimeGranularity__Should_return_Month___When_called()
        {
            // Arrange
            var unitOfTime = A.Dummy<GenericMonth>();

            // Act
            var granularity = unitOfTime.UnitOfTimeGranularity;

            // Assert
            granularity.AsTest().Must().BeEqualTo(UnitOfTimeGranularity.Month);
        }

        #pragma warning disable SA1201 // Elements should appear in the correct order
        private enum GenericMonthComponent
        #pragma warning disable SA1201 // Elements should appear in the correct order
        {
            Month,

            Year,
        }

        private static GenericMonth TweakBy(
            this GenericMonth genericMonth,
            int amount,
            GenericMonthComponent componentToTweak)
        {
            if (componentToTweak == GenericMonthComponent.Month)
            {
                var referenceMonth = new DateTime(genericMonth.Year, (int)genericMonth.MonthNumber, 1);

                var updatedMonth = referenceMonth.AddMonths(amount);

                var result = new GenericMonth(updatedMonth.Year, (MonthNumber)updatedMonth.Month);

                return result;
            }

            if (componentToTweak == GenericMonthComponent.Year)
            {
                var result = new GenericMonth(genericMonth.Year + amount, genericMonth.MonthNumber);

                return result;
            }

            throw new NotSupportedException("this generic month component is not supported: " + componentToTweak);
        }
    }
}


text:
var path = require('path');

module.exports = function (robot) {
  robot.load(path.join(__dirname, '/src/'));
};


text:
<?xml version="1.0" encoding="UTF-8"?>

  <wicket:head>

  </wicket:head>

<wicket:extend>

Data tables

Default data table

        This table also uses a PropertyConvertingColumn to calculate the age based on the birthday. It
        allows sorting over the birthday attribute.

Actions column

        This data table demontstrates the ActionColmun, and how it can be used to provide row-specific
        (ajax) actions.

Selection aware behavior

        SelectionAwareBehavior and subclasses allow the selection of rows and attach actions to select
        events. These examples makes ajax calls on select and log the selected item(s) (check your browser console!).

Single select

Single select (with deselect)

Multi select

</wicket:extend>


text:
// Created by Igor Markov, 070298
// Version 4 by Andrew Caldwell, 090998

#ifndef __ML_PART__H__
#define __ML_PART__H__

#include "Partitioning/partitioning.h"
#include "Placement/placeWOri.h"
#include "baseMLPart.h"

class FillableHierarchy;

class MLPart : public BaseMLPart {
        ClusteredHGraph* _makeClusterTrees(const Partitioning&, unsigned);
        ClusteredHGraph* _makeVCycleTrees(const Partitioning&, unsigned);

        void _doLastVCycle(double& curBestCost, unsigned curBestSolnNum);
        //    void _FMLegalizeOnly(PartitioningProblem& problem);

        void _startWithPartProblem(PartitioningProblem&, ClusteredHGraph&);

        bool _go();            // returns true if the solutions generated are valid
        bool _doMultiLevel();  // returns true if the solns generated are valid
        void _figureBestCost(PartitioningProblem&);

        double _peakMemUsage;

       public:
        MLPart(PartitioningProblem& problem, const MLPartParams& params, BBPartBitBoardContainer& bbBitBoards, /* MaxMem* maxMem, */ FillableHierarchy* hier = NULL);
        MLPart(PartitioningProblem& problem, const MLPartParams& params, BBPartBitBoardContainer& bbBitBoards, /* MaxMem* maxMem, */ int* part, int nLevels, FillableHierarchy* hier = NULL);
        MLPart(PartitioningProblem& problem, const MLPartParams& params, PlacementWOrient* placement, BBPartBitBoardContainer& bbBitBoards, /* MaxMem* maxMem, */ FillableHierarchy* hier = NULL);

        ~MLPart() {}
};

#endif


text:
require 'yaml_localization'

YamlLocalization.load


text:
using System;
using System.Collections.Generic;
using osuElements.Api;
using osuElements.Beatmaps;
using osuElements.Helpers;

namespace osuElements.Db
{
    public enum DbBeatmapState
    {
        None,
        Unsubmitted,
        Graveyard,
        WorkInProgress,
        Ranked,
        Approved,
        Qualified,
    }
    /// <summary>
    /// The database-driven approach to the beatmap object
    /// </summary>
    public class DbBeatmap : Beatmap
    {
        public DbBeatmap() {

            StandardDifficulties = new Dictionary<Mods, double>();
            TaikoDifficulties = new Dictionary<Mods, double>();
            ManiaDifficulties = new Dictionary<Mods, double>();
            CtbDifficulties = new Dictionary<Mods, double>();
        }

        public DbBeatmapState DbBeatmapState { get; set; }
        public ushort HitCircleAmount { get; set; }
        public ushort SliderAmount { get; set; }
        public ushort SpinnerAmount { get; set; }
        public ICollection<KeyValuePair<Mods, double>> StandardDifficulties { get; set; }
        public ICollection<KeyValuePair<Mods, double>> TaikoDifficulties { get; set; }
        public ICollection<KeyValuePair<Mods, double>> CtbDifficulties { get; set; }
        public ICollection<KeyValuePair<Mods, double>> ManiaDifficulties { get; set; }
        public ScoreRank HighestTaikoRank { get; set; }
        public ScoreRank HighestStandardRank { get; set; }
        public ScoreRank HighestCtbRank { get; set; }
        public ScoreRank HighestManiaRank { get; set; }
        public short UserOffset { get; set; }
        public short OnlineOffset { get; set; }
        public string TitleMarkdown { get; set; }
        public bool IgnoreHitsounds { get; set; }
        public bool IgnoreSkin { get; set; }
        public bool IgnoreStoryboard { get; set; }
        public bool IgnoreVideo { get; set; }
        public DateTime DownloadDate { get; set; }
        public DateTime LastRead { get; set; }
        public DateTime LastPlayTime { get; set; }
        public bool Unplayed { get; set; }

        //Unsure
        public int Int { get; set; } //nearly always 0
        public bool Bool1 { get; set; } //always false
        public bool Bool2 { get; set; } //always false
        public byte Byte { get; set; } //always 0
    }
}


text:
<!DOCTYPE html>

<meta charset="utf-8">
<title>Test for Timer Query objects with OffscreenCanvas</title>
<link rel="stylesheet" href="../../resources/js-test-style.css"/>


text:
package com.google.cloud.spring.data.datastore.repository.query;

import com.google.cloud.datastore.Cursor;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

/**
 * A pageable implementation for Cloud Datastore that uses the cursor for efficient reads.
 *
 * <p>The static methods can take either paged or unpaged {@link Pageable}, while instance methods
 * only deal with a paged self object.
 */
public class DatastorePageable extends PageRequest {
  private final String urlSafeCursor;

  private final Long totalCount;

  private DatastorePageable(Pageable pageable, String urlSafeCursor, Long totalCount) {
    super(pageable.getPageNumber(), pageable.getPageSize(), pageable.getSort());
    this.urlSafeCursor = urlSafeCursor;
    this.totalCount = totalCount;
  }

  DatastorePageable(Pageable pageable, Cursor cursor, Long totalCount) {
    this(pageable, cursor.toUrlSafe(), totalCount);
  }

  /**
   * Creates a {@link DatastorePageable} wrapper for a paged request, but passes unpaged requests
   * back unchanged.
   *
   * @param pageable The source {@link Pageable} that can be paged or unpaged
   * @param cursor Current cursor; null if not applicable
   * @param totalCount Total result count
   * @return an instance of {@link DatastorePageable} or the original unpaged {@link Pageable}.
   */
  public static Pageable from(Pageable pageable, Cursor cursor, Long totalCount) {
    return from(pageable, cursor == null ? null : cursor.toUrlSafe(), totalCount);
  }

  /**
   * Creates a {@link DatastorePageable} wrapper for a paged request, but passes unpaged requests
   * back unchanged.
   *
   * @param pageable The source {@link Pageable} that can be paged or unpaged
   * @param urlSafeCursor Current cursor as ; null if not applicable
   * @param totalCount Current cursor; null if not applicable
   * @return an instance of {@link DatastorePageable} or the original unpaged {@link Pageable}.
   */
  public static Pageable from(Pageable pageable, String urlSafeCursor, Long totalCount) {
    if (pageable.isUnpaged()) {
      return pageable;
    }
    return new DatastorePageable(pageable, urlSafeCursor, totalCount);
  }

  public String getUrlSafeCursor() {
    return this.urlSafeCursor;
  }

  @Override
  public PageRequest next() {
    Pageable nextPage = PageRequest.of(getPageNumber() + 1, getPageSize(), getSort());
    // Cast is safe because from() either returns the original PageRequest or a DatastorePageable.
    return (PageRequest) from(nextPage, this.urlSafeCursor, this.totalCount);
  }

  public Cursor toCursor() {
    return this.urlSafeCursor == null ? null : Cursor.fromUrlSafe(this.urlSafeCursor);
  }

  public Long getTotalCount() {
    return this.totalCount;
  }
}


text:
BEGIN_EVENT_TABLE(ExtentDlg,ExtentDlgBase)
	EVT_INIT_DIALOG (ExtentDlg::OnInitDialog)
	EVT_TEXT_ENTER( ID_EXTENT_N, ExtentDlg::OnExtentN )
	EVT_TEXT_ENTER( ID_EXTENT_W, ExtentDlg::OnExtentW )
	EVT_TEXT_ENTER( ID_EXTENT_E, ExtentDlg::OnExtentE )
	EVT_TEXT_ENTER( ID_EXTENT_S, ExtentDlg::OnExtentS )
	EVT_TEXT( ID_EXTENT_ALL, ExtentDlg::OnExtentAll )
	EVT_CHECKBOX( ID_DMS, ExtentDlg::OnDMS )
END_EVENT_TABLE()

ExtentDlg::ExtentDlg( wxWindow *parent, wxWindowID id, const wxString &title,
	const wxPoint &position, const wxSize& size, long style ) :
	ExtentDlgBase( parent, id, title, position, size, style )
{
	m_bSetting = false;
	m_bDMS = false;

	AddValidator(this, ID_EXTENT_ALL, &m_strAll);
	AddValidator(this, ID_EXTENT_E, &m_strEast);
	AddValidator(this, ID_EXTENT_N, &m_strNorth);
	AddValidator(this, ID_EXTENT_S, &m_strSouth);
	AddValidator(this, ID_EXTENT_W, &m_strWest);
	AddValidator(this, ID_DMS, &m_bDMS);

	GetSizer()->SetSizeHints(this);
}

void ExtentDlg::SetArea(DRECT area, bool bDegrees)
{
	m_area = area;
	m_bDegrees = bDegrees;
	if (m_bDegrees)
		m_fs = _T("%4.8lf");
	else
		m_fs = _T("%8.3lf");
}

void ExtentDlg::FormatExtent(wxString &str, double value)
{
	if (m_bDMS)
	{
		bool sign = value > 0;
		value = fabs(value);
		int degrees = (int) value;
		value = (value - degrees) * 60;
		int minutes = (int) value;
		value = (value - minutes) * 60;
		double seconds = value;

		str.Printf(_T("%s%d %d %.2lf"), sign?"":"-", degrees, minutes, seconds);
	}
	else
		str.Printf(m_fs, value);
}

double ExtentDlg::GetValueFrom(const wxString &str)
{
	if (m_bDMS)
	{
		vtString cstr = (const char *) str.mb_str(wxConvUTF8);
		int degrees, minutes;
		double seconds;
		sscanf(cstr, "%d %d %lf", &degrees, &minutes, &seconds);
		bool negative = (degrees < 0);
		if (negative)
			degrees = -degrees;
		double value = degrees + (minutes / 60.0) + (seconds / 3600.0);
		if (negative)
			value = -value;
		return value;
	}
	else
		return atof(str.mb_str(wxConvUTF8));
}

void ExtentDlg::FormatStrings(int which)
{
	m_bSetting = true;
	if (which == 1)
	{
		FormatExtent(m_strWest, m_area.left);
		FormatExtent(m_strEast, m_area.right);
		FormatExtent(m_strNorth, m_area.top);
		FormatExtent(m_strSouth, m_area.bottom);
	}
	if (which == 2)
	{
		m_strAll.Printf(_T("(")+m_fs+_T(", ")+m_fs+_T("), (")+m_fs+_T(", ")+m_fs+_T(")"),
			m_area.left, m_area.bottom, m_area.Width(), m_area.Height());
	}
	TransferDataToWindow();
	m_bSetting = false;
}

// WDR: handler implementations for ExtentDlg

void ExtentDlg::OnInitDialog(wxInitDialogEvent& event)
{
	GetDMS()->Enable(m_bDegrees);

	FormatStrings(1);
	FormatStrings(2);

	wxWindow::OnInitDialog(event);
}

void ExtentDlg::OnExtentAll( wxCommandEvent &event )
{
	if (m_bSetting) return;

	TransferDataFromWindow();
	double d1, d2, d3, d4;
	int ret = sscanf(m_strAll.mb_str(wxConvUTF8), "(%lf, %lf), (%lf, %lf)",
		&d1, &d2, &d3, &d4);
	if (ret == 4)
	{
		m_area.left = d1;
		m_area.right = d1 + d3;
		m_area.bottom = d2;
		m_area.top = d2 + d4;
		FormatStrings(1);
	}
}

void ExtentDlg::OnExtentS( wxCommandEvent &event )
{
	if (m_bSetting) return;

	TransferDataFromWindow();
	m_area.bottom = GetValueFrom(m_strSouth);
	FormatStrings(2);
}

void ExtentDlg::OnExtentE( wxCommandEvent &event )
{
	if (m_bSetting) return;

	TransferDataFromWindow();
	m_area.right = GetValueFrom(m_strEast);
	FormatStrings(2);
}

void ExtentDlg::OnExtentW( wxCommandEvent &event )
{
	if (m_bSetting) return;

	TransferDataFromWindow();
	m_area.left = GetValueFrom(m_strWest);
	FormatStrings(2);
}

void ExtentDlg::OnExtentN( wxCommandEvent &event )
{
	if (m_bSetting) return;

	TransferDataFromWindow();
	m_area.top = GetValueFrom(m_strNorth);
	FormatStrings(2);
}

void ExtentDlg::OnDMS( wxCommandEvent &event )
{
	if (m_bSetting) return;

	TransferDataFromWindow();
	FormatStrings(1);
}


text:
package shooting.example.stage;

/// ステージ選択に関するイベントのリスナ
public interface StageSelectListener {
	/// ステージが選択された
	/// @param selectedStage 選ばれたステージ
	public void stageSelected(Stage selectedStage);
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    android:layout_gravity="center_horizontal|center_vertical"
    tools:context="com.fsck.k9.activity.setup.PassphraseFrom">

    <EditText
        android:id="@+id/passphrasePrivateKey"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="Passphrase"
        android:inputType="textPassword"
        />

</LinearLayout>


text:
package edu.snu.csne.csne2543.loops;

/**
 * @author Brent Eskridge
 */
public class DoWhileLoopExamples
{
    public static void main( String[] args )
    {
        // Counter-controlled loop
        int counter = 5;
        do
        {
            // Do something interesting
            System.out.println( "Count=[" + counter + "]" );

            // Decrement the counter
            --counter;
        }
        while( 0 <= counter );
        System.out.println( "Blastoff!" );

        // Sentinel-controlled loop
        boolean done = false;
        do
        {
            // Do something interesting
            System.out.println( "Working..." );

            // Update the sentinel in some way
            done = Math.random() > 0.75;
        }
        while( !done );
        System.out.println( "Done" );

        // A do-while loop will execute at least once
        System.out.println( "Seeing if the loop will execute..." );
        done = true;
        do
        {
            System.out.println( "Not done..." );
        }
        while( !done );
        System.out.println( "Done" );
    }
}


text:
import libcontext, bee
from bee.segments import *
from libcontext.socketclasses import *
from libcontext.pluginclasses import *

# keyboard: trigger, pulse (tick-driven only) and impulse (real-time only)
#in case of pulse, add a new event at next tick
#in case of impulse, add a new event at a very small delay,
# so that it gets processed at the next frame

"""
If the keycode must be changed, simply disable the sensor and build a new one.
"""

class keyboardsensor_base(bee.worker):
    def set_add_listener(self, add_listener):
        self.add_listener = add_listener

    def set_remove_listener(self, remove_listener):
        self.remove_listener = remove_listener

    def place(self):
        libcontext.socket(("evin", ("input", "keyboard")), socket_flag())
        libcontext.socket(("evin", "add_listener"), socket_single_required(self.set_add_listener))
        libcontext.socket(("evin", "remove_listener"), socket_single_required(self.set_remove_listener))
        libcontext.plugin(("bee", "init"), plugin_single_required(self.enable))

    def enable(self):
        pass

    def disable(self):
        pass

"""
class keyboardsensor_pulse(keyboardsensor_base):
  keycode = variable("str")
  parameter(keycode, "SPACE")

  def __init__(self, keycode):
    self.pulses = []
    keyboardsensor_base.__init__(self, keycode)
    self.pressed = False
  def _pulse(self, channel, message):
    count = 1
    if channel[1] == "keyreleased" and self.pressed == False: count = 2
    if channel[1] == "keypressed" and self.pressed == True: count = 2
    for n in range(count):
      for p in self.pulses: p()
      self.pressed = not self.pressed
  def add_pulse(self, pulse):
    assert callable(pulse)
    self.pulses.append(pulse)
  def place(self):
    libcontext.socket("eventhandler", socket_single_required(self.set_eventhandler))
    libcontext.socket(("input", "keyboard", "keyreleased"), socket_flag())
    if self.keycode not in asciilist:
      libcontext.socket(("input", "keyboard", "extended"), socket_flag())
    libcontext.socket("pulse", socket_supplier(self.add_pulse))
    keyboardsensor_base.place(self)
  def enable(self):
    self.eventhandler.new_processor(("keyboard", "keypressed", self.keycode), self._pulse)
    self.eventhandler.new_processor(("keyboard", "keyreleased", self.keycode), self._pulse)
  def disable(self):
    self.eventhandler.remove_processor(("keyboard", "keypressed", self.keycode), self._pulse)
    self.eventhandler.remove_processor(("keyboard", "keyreleased", self.keycode), self._pulse)
"""

class mousesensor_base(bee.worker):
    def set_add_listener(self, add_listener):
        self.add_listener = add_listener

    def set_remove_listener(self, remove_listener):
        self.remove_listener = remove_listener

    def place(self):
        libcontext.socket(("evin", ("input", "mouse")), socket_flag())
        libcontext.socket(("evin", "add_listener"), socket_single_required(self.set_add_listener))
        libcontext.socket(("evin", "remove_listener"), socket_single_required(self.set_remove_listener))
        libcontext.plugin(("bee", "init"), plugin_single_required(self.enable))

    def enable(self):
        pass

    def disable(self):
        pass

    def __del__(self):
        self.disable()

"""
class mousebuttonsensor_pulse(mousebuttonsensor_base):
  #TODO
  def place(self):
    mousebuttonsensor_base.place(self)
"""


text:
#pragma once
#include<vector>
#include "entity.h"

class Fact
{
private :

	std::vector<Entity> m_entitiesSet;

public :

	Fact()
	{
		m_entitiesSet.clear();
	}

	static Fact loadFromJSON(std::string json)
	{
		//JSBool JS_ParseJSON(JSContext *cx, const jschar *chars, uint32 len, jsval *vp);
	}

}


text:
All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](http://keepachangelog.com/)
and this project adheres to [Semantic Versioning](http://semver.org/).

## [2.3.3] - 2022-04-29
### Changed
- Upgraded Tagmycode SDK and other libraries

## [2.3.2] - 2020-08-31
### Added
- Language filter with toggle button
- Show preferences directory in "About" dialog

### Fixed
- Save file in utf-8 format

### Changed
- Upgraded Guava version to 29.0-jre

## [2.3.1] - 2018-01-06
### Changed
- Added border to QuickSearch dialog

### Fixed
- Fixed syntax highlight for php and html

## [2.3.0] - 2017-11-05
### Added
- Added support to handle snippets in offline mode
- Added settings dialog with editor theme and font size option
- Added title and description to snippet view
- Added log4j.properties configuration
- Log error if can't open web browser
- Text can be dragged into table to create a new snippet
- Snippets can be dragged directly into editor and the code are copied
- Added "save as file" feature
- Added "clone snippet" feature
- Added "snippet properties" dialog
- Detect binary file

### Fixed
- Show a dialog error if verification code is not correct

## [2.2.0] - 2017-04-22
### Added
- Added key shortcut to get focus on filter snippets box
- Added welcome panel
- About dialog shows plugin version, framework version and data storage directory

## [2.1.0] - 2017-03-25
### Added
- New CHANGELOG.md file

### Changed
- Storage is based on internal db with [Ormlite](http://ormlite.com/) and [H2](http://www.h2database.com)

### Fixed
- Fixed logout on IDE restart

### Removed
- Removed IStorage

## 2.0.0 - 2016-07-11
### Added
- New user interface
- List of snippets stored locally
- Syntax highlight powered by RSyntaxTextArea
- Snippets are synchronized with server
- Filter snippets
- Quick search feature
- Insert selected snippet at cursor in document

### Changed
- Error messages with log and dialog

## 1.1.2 - 2014-10-03
### Added
- Console write also snippet title when new snippet is created (thanks to bejoy)

### Changed
- Switched authentication from OAuth 1.0a to OAuth 2

## 1.1.0 - 2014-08-19
### Added
- Added "Search snippets" feature
- Fixed some minor bugs

## 1.0.0 - 2014-04-14
### Added
- First release with feature "Create snippet"

[2.3.3]: https://github.com/massimozappino/tagmycode-java-plugin-framework/compare/v2.3.2...v2.3.3
[2.3.2]: https://github.com/massimozappino/tagmycode-java-plugin-framework/compare/v2.3.1...v2.3.2
[2.3.1]: https://github.com/massimozappino/tagmycode-java-plugin-framework/compare/v2.3.0...v2.3.1
[2.3.0]: https://github.com/massimozappino/tagmycode-java-plugin-framework/compare/v2.2.0...v2.3.0
[2.2.0]: https://github.com/massimozappino/tagmycode-java-plugin-framework/compare/v2.1.0...v2.2.0
[2.1.0]: https://github.com/massimozappino/tagmycode-java-plugin-framework/compare/v2.0.0...v2.1.0


text:
namespace net {
namespace test {
class QuicConnectionLoggerPeer;
}  // namespace test

class CryptoHandshakeMessage;
class CertVerifyResult;

// This class is a debug visitor of a QuicConnection which logs
// events to |net_log|.
class NET_EXPORT_PRIVATE QuicConnectionLogger
    : public QuicConnectionDebugVisitor,
      public QuicPacketCreator::DebugDelegate {
 public:
  QuicConnectionLogger(
      QuicSpdySession* session,
      const char* const connection_description,
      scoped_ptr<SocketPerformanceWatcher> socket_performance_watcher,
      const BoundNetLog& net_log);

  ~QuicConnectionLogger() override;

  // QuicPacketCreator::DebugDelegateInterface
  void OnFrameAddedToPacket(const QuicFrame& frame) override;

  // QuicConnectionDebugVisitorInterface
  void OnPacketSent(const SerializedPacket& serialized_packet,
                    QuicPacketNumber original_packet_number,
                    TransmissionType transmission_type,
                    QuicTime sent_time) override;
  void OnPacketReceived(const IPEndPoint& self_address,
                        const IPEndPoint& peer_address,
                        const QuicEncryptedPacket& packet) override;
  void OnUnauthenticatedHeader(const QuicPacketHeader& header) override;
  void OnIncorrectConnectionId(QuicConnectionId connection_id) override;
  void OnUndecryptablePacket() override;
  void OnDuplicatePacket(QuicPacketNumber packet_number) override;
  void OnProtocolVersionMismatch(QuicVersion version) override;
  void OnPacketHeader(const QuicPacketHeader& header) override;
  void OnStreamFrame(const QuicStreamFrame& frame) override;
  void OnAckFrame(const QuicAckFrame& frame) override;
  void OnStopWaitingFrame(const QuicStopWaitingFrame& frame) override;
  void OnRstStreamFrame(const QuicRstStreamFrame& frame) override;
  void OnConnectionCloseFrame(const QuicConnectionCloseFrame& frame) override;
  void OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) override;
  void OnBlockedFrame(const QuicBlockedFrame& frame) override;
  void OnGoAwayFrame(const QuicGoAwayFrame& frame) override;
  void OnPingFrame(const QuicPingFrame& frame) override;
  void OnPublicResetPacket(const QuicPublicResetPacket& packet) override;
  void OnVersionNegotiationPacket(
      const QuicVersionNegotiationPacket& packet) override;
  void OnConnectionClosed(QuicErrorCode error,
                          ConnectionCloseSource source) override;
  void OnSuccessfulVersionNegotiation(const QuicVersion& version) override;
  void OnRttChanged(QuicTime::Delta rtt) const override;

  void OnCryptoHandshakeMessageReceived(const CryptoHandshakeMessage& message);
  void OnCryptoHandshakeMessageSent(const CryptoHandshakeMessage& message);
  void UpdateReceivedFrameCounts(QuicStreamId stream_id,
                                 int num_frames_received,
                                 int num_duplicate_frames_received);
  void OnCertificateVerified(const CertVerifyResult& result);

  // Returns connection's overall packet loss rate in fraction.
  float ReceivedPacketLossRate() const;

 private:
  friend class test::QuicConnectionLoggerPeer;

  // Do a factory get for a histogram for recording data, about individual
  // packet numbers, that was gathered in the vectors
  // received_packets_ and received_acks_. |statistic_name| identifies which
  // element of data is recorded, and is used to form the histogram name.
  base::HistogramBase* GetPacketNumberHistogram(
      const char* statistic_name) const;
  // Do a factory get for a histogram to record a 6-packet loss-sequence as a
  // sample. The histogram will record the 64 distinct possible combinations.
  // |which_6| is used to adjust the name of the histogram to distinguish the
  // first 6 packets in a connection, vs. some later 6 packets.
  base::HistogramBase* Get6PacketHistogram(const char* which_6) const;
  // Do a factory get for a histogram to record cumulative stats across a 21
  // packet sequence.  |which_21| is used to adjust the name of the histogram
  // to distinguish the first 21 packets' loss data, vs. some later 21 packet
  // sequences' loss data.
  base::HistogramBase* Get21CumulativeHistogram(const char* which_21) const;
  // Add samples associated with a |bit_mask_of_packets| to the given histogram
  // that was provided by Get21CumulativeHistogram().  The LSB of that mask
  // corresponds to the oldest packet number in the series of packets,
  // and the bit in the 2^20 position corresponds to the most recently received
  // packet.  Of the maximum of 21 bits that are valid (correspond to packets),
  // only the most significant |valid_bits_in_mask| are processed.
  // A bit value of 0 indicates that a packet was never received, and a 1
  // indicates the packet was received.
  static void AddTo21CumulativeHistogram(base::HistogramBase* histogram,
                                         int bit_mask_of_packets,
                                         int valid_bits_in_mask);
  // For connections longer than 21 received packets, this call will calculate
  // the overall packet loss rate, and record it into a histogram.
  void RecordAggregatePacketLossRate() const;
  // At destruction time, this records results of |pacaket_received_| into
  // histograms for specific connection types.
  void RecordLossHistograms() const;

  BoundNetLog net_log_;
  QuicSpdySession* session_;  // Unowned.
  // The last packet number received.
  QuicPacketNumber last_received_packet_number_;
  // The size of the most recently received packet.
  size_t last_received_packet_size_;
  // The size of the previously received packet.
  size_t previous_received_packet_size_;
  // The timestamp of last packet sent.
  QuicTime last_packet_sent_time_;
  // The largest packet number received.  In the case where a packet is
  // received late (out of order), this value will not be updated.
  QuicPacketNumber largest_received_packet_number_;
  // The largest packet number which the peer has failed to
  // receive, according to the missing packet set in their ack frames.
  QuicPacketNumber largest_received_missing_packet_number_;
  // Number of times that the current received packet number is
  // smaller than the last received packet number.
  size_t num_out_of_order_received_packets_;
  // Number of times that the current received packet number is
  // smaller than the last received packet number and where the
  // size of the current packet is larger than the size of the previous
  // packet.
  size_t num_out_of_order_large_received_packets_;
  // The number of times that OnPacketHeader was called.
  // If the network replicates packets, then this number may be slightly
  // different from the real number of distinct packets received.
  QuicPacketCount num_packets_received_;
  // Number of times a truncated ACK frame was sent.
  size_t num_truncated_acks_sent_;
  // Number of times a truncated ACK frame was received.
  size_t num_truncated_acks_received_;
  // The kCADR value provided by the server in ServerHello.
  IPEndPoint local_address_from_shlo_;
  // The first local address from which a packet was received.
  IPEndPoint local_address_from_self_;
  // Count of the number of frames received.
  int num_frames_received_;
  // Count of the number of duplicate frames received.
  int num_duplicate_frames_received_;
  // Count of the number of packets received with incorrect connection IDs.
  int num_incorrect_connection_ids_;
  // Count of the number of undecryptable packets received.
  int num_undecryptable_packets_;
  // Count of the number of duplicate packets received.
  int num_duplicate_packets_;
  // Count of the number of BLOCKED frames received.
  int num_blocked_frames_received_;
  // Count of the number of BLOCKED frames sent.
  int num_blocked_frames_sent_;
  // Vector of inital packets status' indexed by packet numbers, where
  // false means never received.  Zero is not a valid packet number, so
  // that offset is never used, and we'll track 150 packets.
  std::bitset<151> received_packets_;
  // Vector to indicate which of the initial 150 received packets turned out to
  // contain solo ACK frames.  An element is true iff an ACK frame was in the
  // corresponding packet, and there was very little else.
  std::bitset<151> received_acks_;
  // The available type of connection (WiFi, 3G, etc.) when connection was first
  // used.
  const char* const connection_description_;
  // Receives notifications regarding the performance of the underlying socket
  // for the QUIC connection. May be null.
  const scoped_ptr<SocketPerformanceWatcher> socket_performance_watcher_;

  DISALLOW_COPY_AND_ASSIGN(QuicConnectionLogger);
};

}  // namespace net

#endif  // NET_QUIC_QUIC_CONNECTION_LOGGER_H_


text:
var editors = {};
var snippets = {};

function beautify() {
    $("textarea").each(function () {
        $(this).val(js_beautify($(this).val()));

        var name = $(this).attr('name');

        var cm_instance = CodeMirror.fromTextArea(this, {
            lineNumbers: true,
            onChange: function() {
                if (!editors[name].changed) {
                    $(".selector[rel="+name+"] select option").each(function () {
                        $(this).removeAttr('selected');
                    });
                    $(".selector[rel="+name+"] select option[value=custom]").attr('selected', 'yes');
                } else {
                    editors[name].changed = false;
                }
            },
            onFocus: function() {
            },
            onBlur: function() {
                $(".selector[rel="+name+"]").hide();
            }
        });

        var selector = $(".selector[rel="+name+"]");

        var mouse_in = function(){
            selector.show();
            var wrapper = $(editors[name].getWrapperElement());
            var w_offset = wrapper.offset();

            /* jQuery bug? Setting both the coordinates and the position
             * attribute in a single call makes the browser miscalculate the
             * final drawing coords. */
            selector.css('position', 'absolute');
            selector.css({
                top: w_offset.top + wrapper.height() - selector.height(),
                left: w_offset.left + wrapper.width() - selector.width()
            });
        }

        var mouse_out = function() {
            selector.hide();
        };

        $(cm_instance.getWrapperElement()).hover(mouse_in, mouse_out);
        selector.hover(mouse_in, mouse_out);

        selector.find('select').change(function() {
            var val = $(this).find("option:selected").val();
            if (val != "custom") {
                editors[name].changed = true;
                editors[name].setValue(snippets[name][val]);
            }
        });

        cm_instance.changed = false;
        editors[name] = cm_instance;

    });
}

$(document).ready(function () {
    $("form.edit").each(beautify);
    $("form.edit").submit(beautify);

    $.ajax({
        url: "/public/snippets.xml",
        dataType: "xml",
        success: function(xml) {
            $(xml).find("category").each(function () {
                var categ = $(this);
                var categ_name = categ.attr('name');
                categ_snippets = {};
                categ.find("snippet").each(function() {
                    var el = $(this);
                    var el_name = el.attr('name');
                    categ_snippets[el_name] = el.text();
                    $(".selector[rel="+categ_name+"] select").append($("<option>").val(el_name).text(el_name));
                });
                snippets[categ_name] = categ_snippets;
            });

            $(".selector select").each(function() {
                var init_val = $(this).attr('data_init');
                $(this).find("option[value="+init_val+"]").attr('selected', 'yes');
            });
        }
    });

    $(".btn-danger").click(function() {
        return confirm("Are you sure?");
    });

    $(".selector").hide();
});


text:
#if($TABNAME == $ResourceBundle.getString('CmisOutputConnector.Server'))

      <nobr>
        $Encoder.bodyEscape($ResourceBundle.getString('CmisOutputConnector.BindingColon'))
      </nobr>

      <select id="binding" name="binding">
#if($BINDING == "atom")
        <option value="atom" selected="selected">AtomPub</option>
        <option value="ws">Web Services</option>
#else
        <option value="atom">AtomPub</option>
        <option value="ws" selected="selected">Web Services</option>
#end
      </select>

      <nobr>
        $Encoder.bodyEscape($ResourceBundle.getString('CmisOutputConnector.UsernameColon'))
      </nobr>

      <input type="text" id="username" name="username" value="$Encoder.attributeEscape($USERNAME)" />

      <nobr>
        $Encoder.bodyEscape($ResourceBundle.getString('CmisOutputConnector.PasswordColon'))
      </nobr>

      <input type="password" id="password" name="password" value="$Encoder.attributeEscape($PASSWORD)" />

      <nobr>
        $Encoder.bodyEscape($ResourceBundle.getString('CmisOutputConnector.ProtocolColon'))
      </nobr>

      <select id="protocol" name="protocol">
#if($PROTOCOL == "https")
        <option value="http">http</option>
        <option value="https" selected="selected">https</option>
#else
        <option value="http" selected="selected">http</option>
        <option value="https">https</option>
#end
      </select>

      <nobr>
        $Encoder.bodyEscape($ResourceBundle.getString('CmisOutputConnector.ServerColon'))
      </nobr>

        <input id="server" name="server" type="text" size="32" value="$Encoder.attributeEscape($SERVER)"/>

      <nobr>
        $Encoder.bodyEscape($ResourceBundle.getString('CmisOutputConnector.PortColon'))
      </nobr>

        <input id="port" name="port" type="text" size="5" value="$Encoder.attributeEscape($PORT)" />

      <nobr>
        $Encoder.bodyEscape($ResourceBundle.getString('CmisOutputConnector.PathColon'))
      </nobr>

        <input id="path" name="path" type="text" size="32" value="$Encoder.attributeEscape($PATH)" />

      <nobr>
        $Encoder.bodyEscape($ResourceBundle.getString('CmisOutputConnector.CMISQueryColon'))
      </nobr>

        <input id="cmisQuery" name="cmisQuery" type="text" size="120" value="$Encoder.attributeEscape($CMISQUERY)" />

      <nobr>
        $Encoder.bodyEscape($ResourceBundle.getString('CmisOutputConnector.VersioningStateColon'))
      </nobr>

      <select id="versioningState" name="versioningState">
#if($VERSIONINGSTATE == "none")
        <option value="major">Major</option>
        <option value="minor">Minor</option>
        <option value="none" selected="selected">None</option>
#elseif($VERSIONINGSTATE == "major")
        <option value="major" selected="selected">Major</option>
        <option value="minor">Minor</option>
        <option value="none">None</option>
#else($VERSIONINGSTATE == "minor")
        <option value="major">Major</option>
        <option value="minor" selected="selected">Minor</option>
        <option value="none">None</option>
#end
      </select>

      <nobr>
        $Encoder.bodyEscape($ResourceBundle.getString('CmisOutputConnector.CreateTimestampTreeColon'))
      </nobr>

         <select id="createTimestampTree" name="createTimestampTree">
#if($CREATETIMESTAMPTREE == "true")
        <option value="false">Disabled</option>
        <option value="true" selected="selected">Enabled</option>
#else
        <option value="false" selected="selected">Disabled</option>
        <option value="true">Enabled</option>
#end
      </select>

      <nobr>
        $Encoder.bodyEscape($ResourceBundle.getString('CmisOutputConnector.RepositoryIDColon'))
      </nobr>

      <input type="text" id="repositoryId" name="repositoryId" value="$Encoder.attributeEscape($REPOSITORYID)" />
      <nobr>
        $Encoder.bodyEscape($ResourceBundle.getString('CmisOutputConnector.Optional'))
      </nobr>

#else

<input type="hidden" name="username" value="$Encoder.attributeEscape($USERNAME)" />
<input type="hidden" name="password" value="$Encoder.attributeEscape($PASSWORD)" />
<input type="hidden" name="protocol" value="$Encoder.attributeEscape($PROTOCOL)" />
<input type="hidden" name="server" value="$Encoder.attributeEscape($SERVER)" />
<input type="hidden" name="port" value="$Encoder.attributeEscape($PORT)" />
<input type="hidden" name="path" value="$Encoder.attributeEscape($PATH)" />
<input type="hidden" name="binding" value="$Encoder.attributeEscape($BINDING)" />
<input type="hidden" name="cmisQuery" value="$Encoder.attributeEscape($CMISQUERY)" />
<input type="hidden" name="createTimestampTree" value="$Encoder.attributeEscape($CREATETIMESTAMPTREE)"/>
<input type="hidden" name="repositoryId" value="$Encoder.attributeEscape($REPOSITORYID)" />
<input type="hidden" name="versioningState" value="$Encoder.attributeEscape($VERSIONINGSTATE)" />

#end


text:
package com.mitakas.flink.apriori;

import java.util.ArrayList;

import org.apache.flink.api.common.functions.GroupReduceFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

public class TransactionGroupReduceFunction implements GroupReduceFunction<Tuple2<Integer, Integer>, Tuple2<Integer, ArrayList<Integer>>> {

	private static final long serialVersionUID = 1L;

	@Override
	public void reduce(Iterable<Tuple2<Integer, Integer>> arg0, Collector<Tuple2<Integer, ArrayList<Integer>>> arg1)
			throws Exception {
		ArrayList<Integer> items = new ArrayList<>();
		Integer tid = null;
		for (Tuple2<Integer, Integer> transaction : arg0) {
			items.add(transaction.f1);
			tid = transaction.f0;
		}
		arg1.collect(new Tuple2<Integer, ArrayList<Integer>>(tid, items));
	}

}


text:
#include <Python.h>

#include "countscalc.h"

extern char* error_message;
extern int error_type;
extern const int FILE_ERROR;
extern const int MEMORY_ERROR;

const int MAX_LENGTH = 14;
const int MAX_GAP_LENGTH = 14;

typedef struct{
    int slen, pos, glen;
    int hash;
} SiteStruct;

static void fill_struct_hash(SiteStruct *s){
    if(s->slen <= 0){
        s->hash = 0;
        return;
    }
    int struct_hash = 0;
    struct_hash += s->slen;
    if(s->glen > 0 && s->pos > 0){
        struct_hash += MAX_LENGTH + 1;
        struct_hash += (s->pos - 1) * MAX_LENGTH;
        struct_hash += (s->glen - 1) * (MAX_LENGTH - 1) * MAX_LENGTH;
    }
    s->hash = struct_hash;
}

typedef struct{
    PyObject_HEAD
    long **countset;
    long *totals;
    SiteStruct *structs;
    int structs_num;
} Counts;

static PyObject *Counts_new(PyTypeObject *type, PyObject *args,
                            PyObject *kwds){
    Counts *self;
    self = (Counts *)type->tp_alloc(type, 0);
    return (PyObject *)self;
}

static int Counts_init(Counts *self, PyObject *args, PyObject *kwds){
    char *filename;
    PyObject *structs_seq;
    if(!PyArg_ParseTuple(args, "sO", &filename, &structs_seq))
        return -1;
    else{
        int structs_num = PySequence_Size(structs_seq);
        int i;
        SiteStruct *structs;
        structs = (SiteStruct *)calloc(structs_num, sizeof(SiteStruct));
        int max_hash = 0;
        for(i=0; i<structs_num; i++){
            PyObject *item = PySequence_GetItem(structs_seq, i);
            SiteStruct *sp = &(structs[i]);
            if(!PyArg_ParseTuple(item, "iii", &sp->slen, &sp->pos,
                                 &sp->glen))
                return -1;
            fill_struct_hash(sp);
            if(sp->hash > max_hash)
                max_hash = sp->hash;
        }
        // reuse of __init__ will cause memmory leak!! #TOFIX
        // add RuntimeError raising
        self->countset = (long **)calloc(max_hash+1, sizeof(long *));
        self->totals = (long *)calloc(max_hash+1, sizeof(long));
        for(i=0; i<structs_num; i++){
            SiteStruct s = structs[i];
            long **counts;
            if(s.glen)
                counts = count_bipart_words(filename, s.slen,
                                            s.pos, s.glen);
            else
                counts = count_short_words(filename, s.slen);
            if(!counts){
                if(error_type == FILE_ERROR)
                    PyErr_SetString(PyExc_IOError, error_message);
                else if(error_type == MEMORY_ERROR)
                    PyErr_NoMemory();
                else
                    PyErr_SetString(PyExc_Exception, "unknown error");
                return -1;
            }
            long word_limit = 1ul << (2 * s.slen);
            int num = s.slen-s.pos;
            int j;
            for(j=0; j<num; j++){
                long *word_counts = counts[j];
                self->countset[s.hash-j] = word_counts;
                int total = 0;
                int word;
                for(word=0; word<word_limit; word++)
                    total += word_counts[word];
                self->totals[s.hash-j] = total;
                word_limit >>= 2;
            }
            free(counts);
        }
        if(!self->totals[1]){
            PyErr_SetString(PyExc_ValueError,
                            "input file contains no sequence");
            return -1;
        }
        self->countset[0] = &(self->totals[1]); /* empty site count
                                is equal to total length in nucls */
        self->totals[0] = self->totals[1];
        self->structs = structs;
        self->structs_num = structs_num;
    }
    return 0;
}

static void Counts_dealloc(Counts *self){
    SiteStruct *structs;
    structs = self->structs;
    int i;
    for(i=0; i<self->structs_num; i++){
        SiteStruct s = structs[i];
        long **ptr;
        ptr = self->countset + s.hash;
        while(s.slen > s.pos){
            free(*ptr);
            ptr --;
            s.slen --;
        }
    }
    free(structs);
    free(self->countset);
    free(self->totals);
    self->ob_type->tp_free((PyObject *)self);
}

static PyObject *Counts_get_count(Counts *self, PyObject *args,
                                  PyObject *kwds){
    PyObject *dsite_seq;
    int struct_hash = 1;
    if(!PyArg_ParseTuple(args, "O|i", &dsite_seq, &struct_hash))
        return NULL;
    else{
        long *counts;
        counts = self->countset[struct_hash];
        long count = 0;
        int dsite_num = PySequence_Size(dsite_seq);
        long dsite;
        int i;
        for(i=0; i<dsite_num; i++){
            dsite = PyInt_AsLong(PySequence_GetItem(dsite_seq, i));
            count += counts[dsite];
        }
        return Py_BuildValue("l", count);
    }
}

static PyObject *Counts_get_freq(Counts *self, PyObject *args,
                                 PyObject *kwds){
    PyObject *dsite_seq;
    int struct_hash = 1;
    if(!PyArg_ParseTuple(args, "O|i", &dsite_seq, &struct_hash))
        return NULL;
    else{
        long *counts;
        counts = self->countset[struct_hash];
        long count = 0;
        int dsite_num = PySequence_Size(dsite_seq);
        long dsite;
        int i;
        for(i=0; i<dsite_num; i++){
            dsite = PyInt_AsLong(PySequence_GetItem(dsite_seq, i));
            count += counts[dsite];
        }
        double freq = (double) count;
        long total = self->totals[struct_hash];
        // if(total == 0)
        return Py_BuildValue("d", freq/total);
    }
}

static PyObject *Counts_get_total(Counts *self, PyObject *args,
                                  PyObject *kwds){
    int struct_hash = 1;
    if(!PyArg_ParseTuple(args, "|i", &struct_hash))
        return NULL;
    else{
        long total = self->totals[struct_hash];
        return Py_BuildValue("l", total);
    }
}

static PyMethodDef Counts_methods[] = {
    {
        "get_count", (PyCFunction)Counts_get_count, METH_VARARGS,
        "get_count(dsite, [struct_hash]) -> int\n\n"
        "Get number of occurences of the site.\n\n"
        "Arguments:\n"
        "    dsite -- the list of degenerate versions (words) of the\n"
        "             site in the digital form\n"
        "    struct_hash -- the hash of the site structure\n\n"
        "Returns:\n"
        "    int -- sum of counts of degenerate versions of the site\n"
    }, {
        "get_freq", (PyCFunction)Counts_get_freq, METH_VARARGS,
        "get_freq(dsite, [struct_hash]) -> float\n\n"
        "Get frequency of the site.\n\n"
        "Arguments:\n"
        "    dsite -- the list of degenerate versions of the site in the\n"
        "             digital form\n"
        "    struct_hash -- the hash of the site structure\n\n"
        "Returns:\n"
        "    float -- sum of counts of degenerate versions of the site\n"
        "             normalized by the total count\n\n"
    }, {
        "get_total", (PyCFunction)Counts_get_total, METH_VARARGS,
        "get_total([struct_hash]) -> int\n\n"
        "Get total count of all words of the given structure.\n\n"
        "Arguments:\n"
        "    struct_hash -- the hash of the word structure\n\n"
        "Returns:\n"
        "    int -- total count of all words of the given structure\n\n"
    }, {NULL}
};

static PyTypeObject CountsType = {
    PyObject_HEAD_INIT(NULL)
    0,                          /*ob_size*/
    "counts.Counts",            /*tp_name*/
    sizeof(Counts),             /*tp_basicsize*/
    0,                          /*tp_itemsize*/
    (destructor)Counts_dealloc, /*tp_dealloc*/
    0,                          /*tp_print*/
    0,                          /*tp_getattr*/
    0,                          /*tp_setattr*/
    0,                          /*tp_compare*/
    0,                          /*tp_repr*/
    0,                          /*tp_as_number*/
    0,                          /*tp_as_sequence*/
    0,                          /*tp_as_mapping*/
    0,                          /*tp_hash*/
    0,                          /*tp_call*/
    0,                          /*tp_str*/
    0,                          /*tp_getattro*/
    0,                          /*tp_setattro*/
    0,                          /*tp_as_buffer*/
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
    "Counts(filename, struct_tuple)\n\n"
    "Wrapper class for word counts.\n\n"
    "Arguments:\n"
    "    filename -- full name of the fasta file with genome sequence\n"
    "    struct_tuple -- a list of word structures to calculate counts\n"
    "                    for; word structure is a tuple (length,\n"
    "                    gap_position, gap_length)\n", /*tp_doc*/
    0,                          /*tp_traverse*/
    0,                          /*tp_clear*/
    0,                          /*tp_richcompare*/
    0,                          /*tp_weaklistoffset*/
    0,                          /*tp_iter*/
    0,                          /*tp_iternext*/
    Counts_methods,             /*tp_methods*/
    0,                          /*tp_members*/
    0,                          /*tp_getset*/
    0,                          /*tp_base*/
    0,                          /*tp_dict*/
    0,                          /*tp_descr_get*/
    0,                          /*tp_descr_set*/
    0,                          /*tp_dictoffset*/
    (initproc)Counts_init,      /*tp_init*/
    0,                          /*tp_alloc*/
    Counts_new,                 /*tp_new*/
};

static PyMethodDef counts_methods[] = {
    {NULL}
};

#ifndef PyMODINIT_FUNC
#define PyMODINIT_FUNC void
#endif

PyMODINIT_FUNC
initcounts(void){
    PyObject* counts;
    CountsType.tp_new = PyType_GenericNew;
    if (PyType_Ready(&CountsType) < 0)
        return;
    counts = Py_InitModule3("counts", counts_methods,
        "a module for calculation of word counts.\n\n"
        "The module contains the only class `Counts` wich gets a fasta\n"
        "file name and a list of word structures to calculate counts for\n"
        "in its constructor. The calculated values are available with\n"
        "`get_count`, `get_freq`, and `get_total` methods.\n"
    );
    Py_INCREF(&CountsType);
    PyModule_AddObject(counts, "Counts", (PyObject *)&CountsType);
}


text:
class AddRoleToUsers < ActiveRecord::Migration
  def change
    add_column :users, :role, :text
  end
end


text:
<?php namespace App\Http\Controllers;

use App\Label;
use Input, Auth, Exception;
use App\Http\Controllers\Controller;

class LabelsController extends Controller {

    public function __construct()
    {
        $this->middleware('loggedIn');
    }

    /**
     * Get items user has added given label to.
     *
     * @param  string $label
     * @return Collection
     */
    public function getItemsLabeled($label) {
        $files = Auth::user()->files()->whereHas('labels', function($q) use($label) {
            $q->where('name', $label);
        })->get();

        $folders = Auth::user()->folders()->whereHas('labels', function($q) use($label) {
            $q->where('name', $label);
        })->get();

        return $files->merge($folders);
    }

    /**
     * Attach label to a photo.
     *
     * @return Response
     */
    public function attach()
    {
        $label = Label::where('name', Input::get('label'))->firstOrFail();

        $items = $this->splitFilesAndFolders();

        if (count($items['files'])) {
            $label->files()->attach($items['files']);
        }

        if (count($items['folders'])) {
            $label->folders()->attach($items['folders']);
        }

        return response()->json(trans('app.'.Input::get('label').'Success'));
    }

    /**
     * Detach label from photo.
     *
     * @return Response
     */
    public function detach()
    {
        $label = Label::where('name', Input::get('label'))->firstOrFail();

        $items = $this->splitFilesAndFolders();

        if (count($items['files'])) {
            $label->files()->detach($items['files']);
        }

        if (count($items['folders'])) {
            $label->folders()->detach($items['folders']);
        }

        return response()->json(trans('app.'.Input::get('label').'DetachSuccess'));
    }
}


text:
/*
Package drive provides the definitions for the low-level pfs storage drivers.
*/
package drive

import (
	"io"

	"github.com/pachyderm/pachyderm/src/pfs"
)

// ReaderAtCloser is an interface that implements both io.ReaderAt and io.Closer.
type ReaderAtCloser interface {
	io.ReaderAt
	io.Closer
}

// Driver represents a low-level pfs storage driver.
type Driver interface {
	InitRepository(repository *pfs.Repository, shard map[int]bool) error
	ListRepositories(shard int) ([]*pfs.Repository, error)
	GetFile(path *pfs.Path, shard int) (ReaderAtCloser, error)
	GetFileInfo(path *pfs.Path, shard int) (*pfs.FileInfo, bool, error)
	MakeDirectory(path *pfs.Path, shards map[int]bool) error
	PutFile(path *pfs.Path, shard int, offset int64, reader io.Reader) error
	ListFiles(path *pfs.Path, shard int) ([]*pfs.FileInfo, error)
	Branch(commit *pfs.Commit, newCommit *pfs.Commit, shards map[int]bool) (*pfs.Commit, error)
	Commit(commit *pfs.Commit, shards map[int]bool) error
	PullDiff(commit *pfs.Commit, shard int, diff io.Writer) error
	PushDiff(commit *pfs.Commit, diff io.Reader) error
	GetCommitInfo(commit *pfs.Commit, shard int) (*pfs.CommitInfo, bool, error)
	ListCommits(repository *pfs.Repository, shard int) ([]*pfs.CommitInfo, error)
}


text:
<!DOCTYPE html>

      <meta charset="UTF-8">
      <title>GitLab Time Report</title>

      <link rel="stylesheet" href="/resources/css/main.css"/>


text:
!----------------------------------------------------------------------------!
!                                                                            !
!  Fortran Coarray MicroBenchmark Suite - Version 1.0                        !
!                                                                            !
!  David Henty, EPCC; d.henty@epcc.ed.ac.uk                                  !
!                                                                            !
!  Copyright 2013 the University of Edinburgh                                !
!                                                                            !
!  Licensed under the Apache License, Version 2.0 (the "License");           !
!  you may not use this file except in compliance with the License.          !
!  You may obtain a copy of the License at                                   !
!                                                                            !
!      http://www.apache.org/licenses/LICENSE-2.0                            !
!                                                                            !
!  Unless required by applicable law or agreed to in writing, software       !
!  distributed under the License is distributed on an "AS IS" BASIS,         !
!  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  !
!  See the License for the specific language governing permissions and       !
!  limitations under the License.                                            !
!                                                                            !
!----------------------------------------------------------------------------!

module cafclock

  implicit none

contains

  double precision function caftime()

    logical, save :: firstcall = .true.

    integer, parameter :: int32kind = selected_int_kind( 9)
    integer, parameter :: int64kind = selected_int_kind(18)

    integer, parameter :: intkind = int64kind

    integer(kind = intkind) :: count,rate

    double precision, save :: ticktime

    if (firstcall) then

       firstcall = .false.

       call system_clock(count, rate)

       ticktime = 1.0d0/dble(rate)
       caftime  = dble(count)*ticktime

       if (this_image() == 1) then
          write(*,*) 'Clock resolution is ', ticktime*1.0e6, ', usecs'
       end if

    else

       call system_clock(count)

       caftime = dble(count)*ticktime

    end if

  end function caftime

  logical function cafchecktime(nrep, time, targettime)

    integer :: nrep

    double precision :: time, targettime

    double precision :: tmax, tmin

    tmax = targettime * 4.0/3.0
    tmin = targettime * 2.0/3.0

    cafchecktime = .true.

    if (time > tmax) then

      nrep = max(nrep/2, 1)

    else if (time < tmin) then

      nrep = 2*nrep
      cafchecktime = .false.

    end if

end function cafchecktime

end module cafclock


text:
namespace chromeos {

namespace cellular_setup {

// Test OtaActivator implementation.
class FakeOtaActivator : public OtaActivator {
 public:
  explicit FakeOtaActivator(base::OnceClosure on_finished_callback);
  ~FakeOtaActivator() override;

  using OtaActivator::InvokeOnFinishedCallback;

  const std::vector<mojom::CarrierPortalStatus>& status_updates() const {
    return fake_carrier_portal_handler_.status_updates();
  }

 private:
  // mojom::CarrierPortalHandler:
  void OnCarrierPortalStatusChange(mojom::CarrierPortalStatus status) override;

  FakeCarrierPortalHandler fake_carrier_portal_handler_;

  DISALLOW_COPY_AND_ASSIGN(FakeOtaActivator);
};

}  // namespace cellular_setup

}  // namespace chromeos

#endif  // CHROMEOS_SERVICES_CELLULAR_SETUP_FAKE_OTA_ACTIVATOR_H_