text:
package simx.components.ai.mipro.supervisedlearning.slprovider.neuralnetwork

import org.encog.ml.data.basic.BasicMLDataSet
import org.encog.ml.train.MLTrain
import org.encog.ml.train.strategy._
import org.encog.neural.networks.ContainsFlat
import org.encog.neural.networks.training.propagation.Propagation
import org.encog.neural.networks.training.propagation.back.Backpropagation
import org.encog.neural.networks.training.propagation.resilient.ResilientPropagation
import simx.components.ai.mipro.supervisedlearning.slprovider.neuralnetwork.EncogPropagations.EncogPropagations
import simx.components.ai.mipro.supervisedlearning.slprovider.neuralnetwork.EncogTrainStrategies.EncogTrainStrategies

import scala.xml.NodeSeq

/**
 * Enum holding representations of the different propagration modes contained in encog.
 */
object EncogPropagations extends Enumeration
{
  type EncogPropagations = Value
  val BackPropagation, ResilientPropagation = Value

  /**
   * Deserializes a propagation instance from XML.
   *
   * @param aStr The XML String.
   * @return
   */
  def fromString(aStr: String): Option[EncogPropagations] =
  {
    var tBack: Option[EncogPropagations] = None

    val tBackPropagationStr = BackPropagation.toString
    val tResilientPropagationStr = ResilientPropagation.toString

    aStr match
    {
      case `tBackPropagationStr` => tBack = Some(BackPropagation)
      case `tResilientPropagationStr` => tBack = Some(ResilientPropagation)
      case _ => tBack = None
    }

    tBack
  }
}

/**
 * Enum holding representations of the different train srategies contained in encog.
 */
object EncogTrainStrategies extends Enumeration
{
  type EncogTrainStrategies = Value
  val Greedy, HybridStrategy, ResetStrategy, RequiredImprovementStrategy, StopTrainingStrategy = Value

  /**
   * Deserializes a train strategy instance from XML.
   *
   * @param aStr The XML String.
   * @return
   */
  def fromString(aStr: String): Option[EncogTrainStrategies] =
  {
    var tBack: Option[EncogTrainStrategies] = None

    val tGreedyStr = Greedy.toString
    val tHybridStrategyStr = HybridStrategy.toString
    val tResetStrategyStr = ResetStrategy.toString
    val tRequiredImprovementStrategyStr = RequiredImprovementStrategy.toString
    val tStopTrainingStrategyStr = StopTrainingStrategy.toString

    aStr match
    {
      case `tGreedyStr`=> tBack = Some(Greedy)
      case `tHybridStrategyStr` => tBack = Some(HybridStrategy)
      case `tResetStrategyStr` => tBack = Some(ResetStrategy)
      case `tRequiredImprovementStrategyStr` => tBack = Some(RequiredImprovementStrategy)
      case `tStopTrainingStrategyStr` => tBack = Some(StopTrainingStrategy)
      case _ => tBack = None
    }

    tBack
  }
}

/**
 * Configuration object for the encog library.
 */
case class EncogConfiguration(aPropagation: EncogPropagations = EncogPropagations.ResilientPropagation,
                              aTrainError: Float = 0.01f,
                              aTrainStrategy: EncogTrainStrategies = EncogTrainStrategies.RequiredImprovementStrategy,
                              aCycles: Int = 300)
{
  private var iPropagation = aPropagation
  private var iTrainError = aTrainError
  private var iTrainStrategy = aTrainStrategy
  private var iCycles = aCycles

  def setPropagation(aPropagation: EncogPropagations) = iPropagation = aPropagation
  def setTrainError(aTrainError: Float) = iTrainError = aTrainError
  def setTrainStrategy(aTrainStrategy: EncogTrainStrategies) = iTrainStrategy = aTrainStrategy
  def setCycles(aCycles: Int) = iCycles = aCycles

  def getPropagation(): EncogPropagations = iPropagation
  def getTrainError(): Float = iTrainError
  def getTrainStrategy(): EncogTrainStrategies = iTrainStrategy
  def getCycles(): Int = iCycles

  /**
   * Creates an XML representation of an EncogConfiguration.
   * @return The XML representation.
   */
  def toXml() =
  {
    <ENCOG_CONFIG>
      <!-- Possible propagations are: BackPropagation, ResilientPropagation -->
      <PROPAGATION>{iPropagation}</PROPAGATION>
      <TRAIN_ERROR>{iTrainError}</TRAIN_ERROR>
      <!-- Possible train strategies are: Greedy, HybridStrategy, ResetStrategy, RequiredImprovementStrategy, StopTrainingStrategy -->
      <TRAIN_STRATEGY>{iTrainStrategy}</TRAIN_STRATEGY>
      <CYCLES>{iCycles}</CYCLES>
    </ENCOG_CONFIG>
  }

  /**
   * Restores an EncogConfiguration from XML.
   *
   * @param aXml A deserialized XML element.
   */
  def fromXml(aXml: NodeSeq): Unit =
  {
    if (aXml.nonEmpty)
    {
      val tRoot = aXml \\ "ENCOG_CONFIG"
      val tPropagationXml = tRoot \\ "PROPAGATION"
      val tTrainErrorXml = tRoot \\ "TRAIN_ERROR"
      val tTrainStrategyXml = tRoot \\ "TRAIN_STRATEGY"
      val tCyclesXml = tRoot \\ "CYCLES"

      val tPropagation: Option[EncogPropagations] = EncogPropagations.fromString(tPropagationXml.text)
      val tTrainError: Float = tTrainErrorXml.text.toFloat
      val tTrainStrategy: Option[EncogTrainStrategies] = EncogTrainStrategies.fromString(tTrainStrategyXml.text)
      val tCycles: Int = tCyclesXml.text.toInt

      /* Set the restored values into the corresponding members. */
      if (tPropagation.isDefined && tTrainStrategy.isDefined)
      {
        iPropagation = tPropagation.get
        iTrainError = tTrainError
        iTrainStrategy = tTrainStrategy.get
        iCycles = tCycles
      }
    }
  }

  /**
   * Returns an Option that can contain an instance of a Propagation.
   *
   * @param aNeuralNetwork A ContainsFlat instance, typically a NeuralNetwork instance.
   * @param aDataSet The BasicMLDataSet to use.
   * @return
   */
  def getPropagationInstance(aNeuralNetwork: ContainsFlat, aDataSet: BasicMLDataSet): Option[Propagation] =
  {
    var tBack: Option[Propagation] = None

    iPropagation match
    {
      case EncogPropagations.BackPropagation => tBack = Some(new Backpropagation(aNeuralNetwork, aDataSet))
      case EncogPropagations.ResilientPropagation => tBack = Some(new ResilientPropagation(aNeuralNetwork, aDataSet))
      case _ => tBack = None
    }

    tBack
  }

  /**
   * Returns an Option that can contain an instance of a Strategy.
   *
   * @param aTrain An MLTrain instance, typically a Propagation instance.
   * @return
   */
  def getTrainStrategyInstance(aTrain: MLTrain): Option[Strategy] =
  {
    var tBack: Option[Strategy] = None

    iTrainStrategy match
    {
      case EncogTrainStrategies.Greedy => tBack = Some(new Greedy())
      case EncogTrainStrategies.HybridStrategy => tBack = Some(new HybridStrategy(aTrain))
      case EncogTrainStrategies.RequiredImprovementStrategy => tBack = Some(new RequiredImprovementStrategy(aTrainError,
        0.035f, iCycles))
      case EncogTrainStrategies.ResetStrategy => tBack = Some(new ResetStrategy(iTrainError, aCycles))
      case EncogTrainStrategies.StopTrainingStrategy => tBack = Some(new StopTrainingStrategy(iTrainError, aCycles))
      case _ => tBack = None
    }

    tBack
  }

  override def toString(): String = "EncogConfiguration: Propagation - " + iPropagation + " | TrainError - " +
    iTrainError + " | TrainStrategy - " + iTrainStrategy + " | Cycles - " + iCycles
}


text:
import * as exported from "./BridgeVideoType";

// this test is brittle on purpose because it's designed to ensure that the TypeScript conversion maintains backward compatibility

describe( "/service/RTC/BridgeVideoType members", () => {
    const {
        CAMERA,
        DESKTOP,
        DESKTOP_HIGH_FPS,
        NONE,
        BridgeVideoType,
        ...others
    } = exported as any; // TODO: remove cast after typescript conversion

    it( "known members", () => {
        expect( CAMERA ).toBe( 'camera' );
        expect( DESKTOP ).toBe( 'desktop' );
        expect( DESKTOP_HIGH_FPS ).toBe( 'desktop_high_fps' );
        expect( NONE ).toBe( 'none' );
        if ( BridgeVideoType ) {
            expect( BridgeVideoType.CAMERA ).toBe( 'camera' );
            expect( BridgeVideoType.DESKTOP ).toBe( 'desktop' );
            expect( BridgeVideoType.DESKTOP_HIGH_FPS ).toBe( 'desktop_high_fps' );
            expect( BridgeVideoType.NONE ).toBe( 'none' );
        }
    } );

    it( "unknown members", () => {
        const keys = Object.keys( others );
        expect( keys ).withContext( `Extra members: ${ keys.join( ", " ) }` ).toEqual( [] );
    } );
} );

redpajama_set_name: RedPajamaGithub


text:
#include <termcap.h>  /* tgetent, tgetnum */
#include <assert.h>
#include <limits.h>
#include "progressbar.h"

#define PROGRESSBAR_WIDTH 200

/**
* Create a new progress bar with the specified label, max number of steps, and format string.
* Note that `format` must be exactly three characters long, e.g. "<->" to render a progress
* bar like "<---------->".
*/
progressbar *progressbar_new_with_format(char *label, unsigned long max, const char *format)
{
  progressbar *new = malloc(sizeof(progressbar));
  progressbar_update_label(new, label);
  new->max = max;
  new->value = 0;
  new->start = time(NULL);
  new->step = 0;
  new->progress_str = calloc(PROGRESSBAR_WIDTH+1, sizeof(char));
  new->format = calloc(strlen(format)+1, sizeof(char));
  strncpy(new->format, format, strlen(format));
  memset(new->progress_str,' ', PROGRESSBAR_WIDTH);
  new->progress_str[new->steps] = 0;
  new->last_printed = 0;
  new->termtype = getenv("TERM");

  progressbar_draw(new, 0);

  return new;
}

/**
* Create a new progress bar with the specified label and max number of steps.
*/
progressbar *progressbar_new(char *label, unsigned long max)
{
  return progressbar_new_with_format(label, max, "|=|");
}

void progressbar_update_label(progressbar *bar, char *label)
{
  bar->label = label;
  int newsteps;
  int columns = 80; // by default 80
  static char termbuf[2048];
  if (!(tgetent(termbuf, bar->termtype) < 0)) {
    // otherwise size of terminal if it works
    columns = tgetnum("co") - 2;
  }
  // make sure newsteps is positive
  int maxstrlen = columns - 17;
  if (maxstrlen - 10 > 10 && strlen(label) > maxstrlen - 10) {
    label[maxstrlen - 10] = 0;
  }
  if (strlen(label) >= maxstrlen) {
    label[maxstrlen] = 0;
  }
  // Reserve two possible colums for pre- and post- spacing
  columns -= 2;

  newsteps = columns - (strlen(label) + 17);
  if (newsteps < 0) {
    newsteps = 0;
  }
  if (newsteps > PROGRESSBAR_WIDTH - 1) {
    newsteps = PROGRESSBAR_WIDTH - 1;
  }
  if (newsteps != bar->steps && bar->step >= bar->steps) {
    bar->step = 0;
  }
  bar->steps = newsteps;
}

/**
* Delete an existing progress bar.
*/
void progressbar_free(progressbar *bar)
{
  // We malloc'd a couple of strings, so let's be sure to free those...
  free(bar->progress_str);
  free(bar->format);
  // ...before we free the struct itself.
  free(bar);

  return;
}

/**
* Increment an existing progressbar by `value` steps.
*/
void progressbar_update(progressbar *bar, unsigned long value)
{
  bar->value = value;
  unsigned int current_step = (bar->value * (unsigned long)bar->steps / (long double)bar->max);

  // Only redraw the progressbar if the visual progress display (the current 'step')
  // has changed.
  if(1 || current_step != bar->step) {
    // Fill the bar to the current step...
    for(int i=0; i < current_step; i++) {
      bar->progress_str[i] = bar->format[1];
    }
    for(int i=current_step; i < bar->steps; i++) {
      bar->progress_str[i] = ' ';
    }
    bar->progress_str[bar->steps] = 0;
    bar->step = current_step;

    // Draw using a rough estimated time remaining.
    // Time remaining is estimated quite roughly, as the number of increments
    // remaining * the average time per increment thus far.
    double offset = difftime(time(NULL), bar->start);
    unsigned int estimate;
    if (bar->value > 0 && offset > 0) {
       estimate = (offset/(long double)bar->value) * (bar->max - bar->value);
    } else {
      estimate = 0;
    }
    progressbar_draw(bar, estimate);
  }
}

/**
* Increment an existing progressbar by a single step.
*/
void progressbar_inc(progressbar *bar)
{
  progressbar_update(bar, bar->value+1);
}

/**
* Render a progress bar. You probably don't need to call this directly; it's
* automatically called when you update a progressbar and a re-render is required.
*/
void progressbar_draw(progressbar *bar, unsigned int timeleft)
{
  // Convert the time to display into HHH:MM:SS
  unsigned int h = timeleft / 3600;
  timeleft -= h*3600;
  unsigned int m = timeleft / 60;
  timeleft -= m*60;
  unsigned int s = timeleft;
  // ...and display!
  bar->last_printed = fprintf(
            stderr,
            "%s %c%s%c ETA:%2dh%02dm%02ds\r",
            bar->label,
            bar->format[0],
            bar->progress_str,
            bar->format[2],
            h,
            m,
            s
        );
  return;
}

/**
* Finish a progressbar, indicating 100% completion, and free it.
*/
void progressbar_finish(progressbar *bar)
{
  // Draw one more time, with the actual time to completion instead of a useless
  // 00:00:00 remaining estimate.
  unsigned int offset = time(NULL) - (bar->start);
  // Make sure we fill the progressbar too, so things look complete.
  for(int i=0; i < bar->steps; i++) {
    bar->progress_str[i] = bar->format[1];
  }
  progressbar_draw(bar, offset);

  // Print a newline, so that future outputs to stderr look prettier
  fprintf(stderr, "\n");

  // We've finished with this progressbar, so go ahead and free it.
  progressbar_free(bar);

  return;
}


text:
'use strict';

var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var serveStatic = require('serve-static');
var methodOverride = require('method-override');
var errorhandler = require('errorhandler');
var multer  = require('multer')

var storage = multer.memoryStorage();
var upload = multer({ storage: storage });

var app = express();

let db = require('./db.js');

let url = process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'mongodb://localhost:27017/my_database_name';
let port = process.env.PORT || 8080;

// all environments

app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(morgan('combined'));
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(methodOverride('X-HTTP-Method-Override'))
app.use(serveStatic(__dirname + '/public'))

// development only
if ('development' == app.get('env')) {
  app.use(errorhandler());
}
//app.use(app.router);

app.get('/', routes.index);
app.get('/result/:channel', routes.result);
app.post('/result/:channel', routes.sms);
app.get('/result/:channel/result.xlsx', routes.download);
app.post('/resend/:channel', routes.resend);
app.post('/send', upload.single('members'), routes.send);

http.createServer(app).listen(app.get('port'), function() {
  console.log('Express server listening on port ' + app.get('port'));
});

db.connect(url, function(err) {
  if (err) {
    console.log('Unable to connect to Mongo.');
  } else {
    console.log('Connection established to', url);
  }
});


text:
<?php

require_once(dirname(__FILE__) . '/../interface/startOfLine.interface.php');
require_once(dirname(__FILE__) . '/../interface/startOfFile.interface.php');
require_once(dirname(__FILE__) . '/../interface/endOfFile.interface.php');

class Verbatim implements startOfFile
{

    public function __construct()
    {

    }
    function verbatim_begin($text) {
        $pattern = "/\\\\begin\{verbatim\}/xu";
        $z = preg_replace($pattern, '
', $text);
        return $z;
    }

    function verbatim_end($text) {
        $pattern = "/\\\\end\{verbatim\}/xu";
        $z = preg_replace($pattern, '
', $text);
        return $z;
    }

    function verbatim_gamut($text) {
        $z = $this::verbatim_begin($text);
        $z = $this::verbatim_end($z);
       return $z;
    }

    public function startOfFile($line)
    {
	    return self::verbatim_gamut($line);

    }

}

?>


text:
> **Warning:** The Model Factory implementation for Ditto should be considered as a prototype / proof-of-concept. You will receive **zero support** (from the Ditto team) if you choose to use it.

As of v7.1.4, Umbraco ships with using a default model factory for `IPublishedContent`.
For more information about the [IPublishedContentModelFactory](https://github.com/zpqrtbnk/Zbu.ModelsBuilder/wiki/IPublishedContentModelFactory) please the "Zbu.ModelsBuilder" wiki:

> [https://github.com/zpqrtbnk/Zbu.ModelsBuilder/wiki/IPublishedContentModelFactory](https://github.com/zpqrtbnk/Zbu.ModelsBuilder/wiki/IPublishedContentModelFactory)

## Configuration

Ditto offers a custom model factory, to enable this, first you need to install the NuGet package:

```bash
PM> Install-Package Our.Umbraco.Ditto.ModelFactory
```

Then, use the following code:

```csharp
using Our.Umbraco.Ditto;

public class ConfigurePublishedContentModelFactory : ApplicationEventHandler
{
	protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
	{
		var types = PluginManager.Current.ResolveTypes<PublishedContentModel>();
		var factory = new DittoPublishedContentModelFactory(types);
		PublishedContentModelFactoryResolver.Current.SetFactory(factory);
	}
}
```

The factory will look for any POCO models that inherit from the `PublishedContentModel` class and automatically map those to the requested `IPublishedContent` objects.

> **Warning:** If you have a POCO model that contains a reference to a child node, then this may create a circular-reference and cause the model-factory to enter an endless loop!  This is fixable by marking your property with the `virtual` keyword, as this enables the lazy-loading feature.

## Video demonstrations

* [Using Ditto with the `IPublishedContentModelFactory`](https://www.screenr.com/9oRN) (5 mins)
* [Using a custom Umbraco MVC controller with `IPublishedContentModelFactory` and Ditto](https://www.screenr.com/PPRN) (5 mins)


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta content="IE=edge" http-equiv="X-UA-Compatible">
    <meta content="width=device-width, initial-scale=1, maximum-scale=1" name="viewport">

    <title>Ett Smart Hotell - The Loft</title>
    <meta content="" name="description">
    <meta content="" name="keywords">
    <meta content="" name="author">

    <link rel="apple-touch-icon-precomposed" href="images/favicon-apple.png" />
    <link rel="icon" href="images/favicon.png">

    <link href="css/custom.css" rel=stylesheet>

    <link href="fonts/font-awesome.min.css" rel="stylesheet">
    <link href="fonts/flaticon.css" rel="stylesheet">

    <link href="https://fonts.googleapis.com/css?family=Lato:300,400,700,900%7cRaleway:400,500,600,700" rel="stylesheet">

 08 546 308 10

 info@ettsmart.se

Svenska

                    <button type="button" class="navbar-toggle mobile_menu_btn" data-toggle="collapse" data-target=".mobile_menu" aria-expanded="false">

                    </button>

MENU

HOME

ROOMS

ALL ROOMS

Single Room

Studio Room

Studio Extra

Double Room

Family Room

APARTMENTS

ALL APARTMENTS

The loft

Etageapartments

STHLM Apartments...

ABOUT US

About us

Contact

FAQ

LOCATION

                            BOOK NOW

The Loft

Home

Apartments

The Loft

The Loft Details

6 People

6 Beds

Kitchen

Free-WiFi

TV

Bathroom with hot floor and shower

Desk

Our Apartments

The Loft

Etageapartments

Sthlmhotel

                                          <button class="button btn_lg btn_blue btn_full" type="submit">&nbsp BOOK THE LOFT</button>

About The Loft

 The Loft is placed at the top of the building. Its Equipped with a complete kitchen, dining room, two beds and a living room.
Equipped with a complete kitchen and dining room.
Plus a livingroom with a corner couch with TV.

 The Loft is big enough for cooking as well as socializing. Sheets and towels are changed daily by the hotel staff.

 Our goal is to make your stay as pleasant as possible.

 The whole area has Free Wi-Fi

SOCIAL MEDIA

Facebook Like Our Facebook Page

LINKS

Our Rooms

Contact Us

About Us

Book Room

Contact Us

                            <address>

 Sollentunavägen 133,
       191 44 Sollentuna

 Phone: 08 546 308 10

 Email: info@ettsmart.se

							</address>

                                 Copyright 2017 Ett Smart Hotell  All Rights Reserved. | Designed by Breakfast Boys


text:
using JiraAssistant.Domain;
using JiraAssistant.Domain.Exceptions;
using JiraAssistant.Domain.Jira;
using Newtonsoft.Json;
using NLog;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace JiraAssistant.Logic.Services
{
    public class AgileBoardDataCache
    {
        private static readonly Logger _logger = LogManager.GetCurrentClassLogger();

        private const string MetaFileName = ".metafile";
        private const string IssuesCacheFileName = "issues.db";
        private readonly DateTime _initialDateTime = new DateTime(1970, 1, 1);

        private readonly int _boardId;
        private AgileBoardCacheMetadata _metadata;
        private readonly string _cachePath;
        private readonly string _jiraUrl;

        public AgileBoardDataCache(string baseCacheDirectory, int boardId, string jiraUrl)
        {
            _boardId = boardId;
            _jiraUrl = jiraUrl;
            _cachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                                                              "Yakuza", "Jira Assistant", "Cache", "AgileBoards", boardId.ToString());

            FetchCacheInformation();
        }

        public bool IsAvailable { get; private set; }

        private void FetchCacheInformation()
        {
            if (Directory.Exists(_cachePath) == false)
            {
                IsAvailable = false;
                return;
            }

            var metaFilePath = Path.Combine(_cachePath, MetaFileName);
            if (File.Exists(metaFilePath) == false)
            {
                IsAvailable = false;
                return;
            }

            try
            {
                using (var reader = new StreamReader(metaFilePath))
                {
                    _metadata = JsonConvert.DeserializeObject<AgileBoardCacheMetadata>(reader.ReadToEnd());

                    if (_metadata.ModelVersion != JiraIssue.ModelVersion)
                    {
                        IsAvailable = false;
                        return;
                    }

                    IsAvailable = true;
                }
            }
            catch (Exception e)
            {
                _logger.Info(e, "Invalidating cache because it failed to load.");
                IsAvailable = false;
                return;
            }
        }

        public async Task<IList<JiraIssue>> UpdateCache(IList<JiraIssue> updatedIssues)
        {
            if (_jiraUrl == "demo")
                return updatedIssues;

            try
            {
                if (IsAvailable == false)
                    InitializeCacheDirectory();

                var cachedItems = await LoadIssuesFromCache();

                var updatedCache = (await Task.Factory.StartNew(() => updatedIssues.Union(cachedItems))).ToList();

                await DumpCache(updatedCache);
                await StoreMetafile();

                return updatedCache;
            }
            catch (Exception e)
            {
                _logger.Warn(e, "Cache update failed");
                throw new CacheCorruptedException();
            }
        }

        private async Task StoreMetafile()
        {
            var metadata = new AgileBoardCacheMetadata
            {
                DownloadedTime = DateTime.Now,
                GeneratorVersion = GetType().Assembly.GetName().Version,
                ModelVersion = JiraIssue.ModelVersion
            };

            var metaFilePath = Path.Combine(_cachePath, MetaFileName);

            using (var writer = new StreamWriter(metaFilePath))
            {
                await writer.WriteAsync(JsonConvert.SerializeObject(metadata));
            }
        }

        private async Task DumpCache(IEnumerable<JiraIssue> updatedCache)
        {
            if (Directory.Exists(_cachePath) == false)
                Directory.CreateDirectory(_cachePath);

            var issuesCachePath = Path.Combine(_cachePath, IssuesCacheFileName);

            await Task.Factory.StartNew(async () =>
            {
                using (var writer = new StreamWriter(issuesCachePath))
                {
                    foreach (var issue in updatedCache)
                    {
                        var line = await Task.Factory.StartNew(() => JsonConvert.SerializeObject(issue));
                        await writer.WriteLineAsync(line);
                    }
                }
            });
        }

        private async Task<IEnumerable<JiraIssue>> LoadIssuesFromCache()
        {
            var issuesCachePath = Path.Combine(_cachePath, IssuesCacheFileName);

            var result = new List<JiraIssue>();

            if (File.Exists(issuesCachePath) == false)
                return result;

            using (var reader = new StreamReader(issuesCachePath))
            {
                string line = null;
                while ((line = await reader.ReadLineAsync()) != null)
                {
                    var issue = await Task.Factory.StartNew(() => JsonConvert.DeserializeObject<JiraIssue>(line));
                    result.Add(issue);
                }
            }

            return result;
        }

        public string PrepareSearchStatement(string originalJql)
        {
            if (IsAvailable == false)
                return originalJql;

            return string.Format("updated >= '{1:yyyy-MM-dd hh:mm}' AND {0}", originalJql, _metadata.DownloadedTime);
        }

        private async void InitializeCacheDirectory()
        {
            if (Directory.Exists(_cachePath))
                Directory.Delete(_cachePath, recursive: true);

            Directory.CreateDirectory(_cachePath);

            await StoreMetafile();
        }

        public void Invalidate()
        {
            Directory.Delete(_cachePath, recursive: true);
            FetchCacheInformation();
        }
    }
}


text:
package org.pentaho.di.core.database;

import org.pentaho.di.core.Const;
import org.pentaho.di.core.row.ValueMetaInterface;

/**
 * Contains DB2 specific information through static final members
 *
 * @author Matt
 * @since 11-mrt-2005
 */

public class CacheDatabaseMeta extends BaseDatabaseMeta implements DatabaseInterface {
  @Override
  public int[] getAccessTypeList() {
    return new int[] {
      DatabaseMeta.TYPE_ACCESS_NATIVE, DatabaseMeta.TYPE_ACCESS_ODBC, DatabaseMeta.TYPE_ACCESS_JNDI };
  }

  @Override
  public int getDefaultDatabasePort() {
    if ( getAccessType() == DatabaseMeta.TYPE_ACCESS_NATIVE ) {
      return 1972;
    }
    return -1;
  }

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

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

  /**
   * @return Whether or not the database can use auto increment type of fields (pk)
   */
  @Override
  public boolean supportsAutoInc() {
    return false;
  }

  @Override
  public String getDriverClass() {
    if ( getAccessType() == DatabaseMeta.TYPE_ACCESS_ODBC ) {
      return "sun.jdbc.odbc.JdbcOdbcDriver";
    } else {
      return "com.intersys.jdbc.CacheDriver";
    }
  }

  @Override
  public String getURL( String hostname, String port, String databaseName ) {
    if ( getAccessType() == DatabaseMeta.TYPE_ACCESS_ODBC ) {
      return "jdbc:odbc:" + databaseName;
    } else {
      return "jdbc:Cache://" + hostname + ":" + port + "/" + databaseName;
    }
  }

  /**
   * Generates the SQL statement to add a column to the specified table
   *
   * @param tablename
   *          The table to add
   * @param v
   *          The column defined as a value
   * @param tk
   *          the name of the technical key field
   * @param use_autoinc
   *          whether or not this field uses auto increment
   * @param pk
   *          the name of the primary key field
   * @param semicolon
   *          whether or not to add a semi-colon behind the statement.
   * @return the SQL statement to add a column to the specified table
   */
  @Override
  public String getAddColumnStatement( String tablename, ValueMetaInterface v, String tk, boolean use_autoinc,
    String pk, boolean semicolon ) {
    return "ALTER TABLE "
      + tablename + " ADD COLUMN ( " + getFieldDefinition( v, tk, pk, use_autoinc, true, false ) + " ) ";
  }

  /**
   * Generates the SQL statement to drop a column from the specified table
   *
   * @param tablename
   *          The table to add
   * @param v
   *          The column defined as a value
   * @param tk
   *          the name of the technical key field
   * @param use_autoinc
   *          whether or not this field uses auto increment
   * @param pk
   *          the name of the primary key field
   * @param semicolon
   *          whether or not to add a semi-colon behind the statement.
   * @return the SQL statement to drop a column from the specified table
   */
  @Override
  public String getDropColumnStatement( String tablename, ValueMetaInterface v, String tk, boolean use_autoinc,
    String pk, boolean semicolon ) {
    return "ALTER TABLE " + tablename + " DROP COLUMN " + v.getName() + Const.CR;
  }

  /**
   * Generates the SQL statement to modify a column in the specified table
   *
   * @param tablename
   *          The table to add
   * @param v
   *          The column defined as a value
   * @param tk
   *          the name of the technical key field
   * @param use_autoinc
   *          whether or not this field uses auto increment
   * @param pk
   *          the name of the primary key field
   * @param semicolon
   *          whether or not to add a semi-colon behind the statement.
   * @return the SQL statement to modify a column in the specified table
   */
  @Override
  public String getModifyColumnStatement( String tablename, ValueMetaInterface v, String tk, boolean use_autoinc,
    String pk, boolean semicolon ) {
    return "ALTER TABLE "
      + tablename + " ALTER COLUMN " + getFieldDefinition( v, tk, pk, use_autoinc, true, false );
  }

  @Override
  public String getFieldDefinition( ValueMetaInterface v, String tk, String pk, boolean use_autoinc,
    boolean add_fieldname, boolean add_cr ) {
    String retval = "";

    String fieldname = v.getName();
    int length = v.getLength();
    int precision = v.getPrecision();

    if ( add_fieldname ) {
      retval += fieldname + " ";
    }

    int type = v.getType();
    switch ( type ) {
      case ValueMetaInterface.TYPE_DATE:
        retval += "TIMESTAMP";
        break;
      case ValueMetaInterface.TYPE_BOOLEAN:
        retval += "CHAR(1)";
        break;
      case ValueMetaInterface.TYPE_NUMBER:
      case ValueMetaInterface.TYPE_INTEGER:
      case ValueMetaInterface.TYPE_BIGNUMBER:
        if ( fieldname.equalsIgnoreCase( tk ) ) // Technical & primary key : see at bottom
        {
          retval += "DECIMAL";
        } else {
          if ( length < 0 || precision < 0 ) {
            retval += "DOUBLE";
          } else if ( precision > 0 || length > 9 ) {
            retval += "DECIMAL(" + length;
            if ( precision > 0 ) {
              retval += ", " + precision;
            }
            retval += ")";
          } else {
            // Precision == 0 && length<=9
            retval += "INT";
          }
        }
        break;
      case ValueMetaInterface.TYPE_STRING: // CLOBs are just VARCHAR in the Cache database: can be very large!
        retval += "VARCHAR";
        if ( length > 0 ) {
          retval += "(" + length + ")";
        }
        break;
      default:
        retval += " UNKNOWN";
        break;
    }

    if ( add_cr ) {
      retval += Const.CR;
    }

    return retval;
  }

  @Override
  public String[] getUsedLibraries() {
    return new String[] { "CacheDB.jar" };
  }

  /**
   * @return true if we need to append the PRIMARY KEY block in the create table block after the fields, required for
   *         Cache.
   */
  @Override
  public boolean requiresCreateTablePrimaryKeyAppend() {
    return true;
  }

  /**
   * @return true if the database supports newlines in a SQL statements.
   */
  @Override
  public boolean supportsNewLinesInSQL() {
    return false;
  }

}


text:
<?php

namespace ntentan\atiaa;

use ntentan\utils\Text;

class DriverFactory
{
    private $config;

    /**
     * Create an instance of the driver factory with the connection configurations.
     *
     * @param array $config
     */
    public function __construct(array $config = null)
    {
        $this->config = $config;
    }

    /**
     * Set or replace the configuration found in the factory.
     *
     * @param $config
     */
    public function setConfig($config) : void
    {
        $this->config = $config;
    }

    /**
     * Return the configuration currently stored in the factory.
     *
     * @return array
     */
    public function getConfig() : array
    {
        return $this->config;
    }

    /**
     * Create a new driver based on the configuration in the factory.
     *
     * @return \ntentan\atiaa\Driver
     */
    public function createDriver() : Driver
    {
        $classname = '\ntentan\atiaa\drivers\\'.Text::ucamelize($this->config['driver']).'Driver';

        return new $classname($this->config);
    }
}


text:
DOCUMENTATION = '''
---
module: ohai
short_description: Returns inventory data from I(Ohai)
description:
     - Similar to the M(facter) module, this runs the I(Ohai) discovery program
       (U(http://wiki.opscode.com/display/chef/Ohai)) on the remote host and
       returns JSON inventory data.
       I(Ohai) data is a bit more verbose and nested than I(facter).
version_added: "0.6"
options: {}
notes: []
requirements: [ "ohai" ]
author: Michael DeHaan
'''

EXAMPLES = '''
# Retrieve (ohai) data from all Web servers and store in one-file per host
ansible webservers -m ohai --tree=/tmp/ohaidata
'''

def main():
    module = AnsibleModule(
        argument_spec = dict()
    )
    cmd = ["/usr/bin/env", "ohai"]
    rc, out, err = module.run_command(cmd, check_rc=True)
    module.exit_json(**json.loads(out))

# import module snippets
from ansible.module_utils.basic import *

main()


text:
import { NgModule } from '@angular/core';
import { CoreCronDelegate } from '@providers/cron';
import { CoreCourseModuleDelegate } from '@core/course/providers/module-delegate';
import { CoreCourseModulePrefetchDelegate } from '@core/course/providers/module-prefetch-delegate';
import { CoreContentLinksDelegate } from '@core/contentlinks/providers/delegate';
import { CorePushNotificationsDelegate } from '@core/pushnotifications/providers/delegate';
import { AddonModQuizAccessRuleDelegate } from './providers/access-rules-delegate';
import { AddonModQuizProvider } from './providers/quiz';
import { AddonModQuizOfflineProvider } from './providers/quiz-offline';
import { AddonModQuizHelperProvider } from './providers/helper';
import { AddonModQuizSyncProvider } from './providers/quiz-sync';
import { AddonModQuizModuleHandler } from './providers/module-handler';
import { AddonModQuizPrefetchHandler } from './providers/prefetch-handler';
import { AddonModQuizSyncCronHandler } from './providers/sync-cron-handler';
import { AddonModQuizIndexLinkHandler } from './providers/index-link-handler';
import { AddonModQuizGradeLinkHandler } from './providers/grade-link-handler';
import { AddonModQuizReviewLinkHandler } from './providers/review-link-handler';
import { AddonModQuizListLinkHandler } from './providers/list-link-handler';
import { AddonModQuizPushClickHandler } from './providers/push-click-handler';
import { AddonModQuizComponentsModule } from './components/components.module';
import { CoreUpdateManagerProvider } from '@providers/update-manager';

// Access rules.
import { AddonModQuizAccessDelayBetweenAttemptsModule } from './accessrules/delaybetweenattempts/delaybetweenattempts.module';
import { AddonModQuizAccessIpAddressModule } from './accessrules/ipaddress/ipaddress.module';
import { AddonModQuizAccessNumAttemptsModule } from './accessrules/numattempts/numattempts.module';
import { AddonModQuizAccessOfflineAttemptsModule } from './accessrules/offlineattempts/offlineattempts.module';
import { AddonModQuizAccessOpenCloseDateModule } from './accessrules/openclosedate/openclosedate.module';
import { AddonModQuizAccessPasswordModule } from './accessrules/password/password.module';
import { AddonModQuizAccessSafeBrowserModule } from './accessrules/safebrowser/safebrowser.module';
import { AddonModQuizAccessSecureWindowModule } from './accessrules/securewindow/securewindow.module';
import { AddonModQuizAccessTimeLimitModule } from './accessrules/timelimit/timelimit.module';

// List of providers (without handlers).
export const ADDON_MOD_QUIZ_PROVIDERS: any[] = [
    AddonModQuizAccessRuleDelegate,
    AddonModQuizProvider,
    AddonModQuizOfflineProvider,
    AddonModQuizHelperProvider,
    AddonModQuizSyncProvider
];

@NgModule({
    declarations: [
    ],
    imports: [
        AddonModQuizComponentsModule,
        AddonModQuizAccessDelayBetweenAttemptsModule,
        AddonModQuizAccessIpAddressModule,
        AddonModQuizAccessNumAttemptsModule,
        AddonModQuizAccessOfflineAttemptsModule,
        AddonModQuizAccessOpenCloseDateModule,
        AddonModQuizAccessPasswordModule,
        AddonModQuizAccessSafeBrowserModule,
        AddonModQuizAccessSecureWindowModule,
        AddonModQuizAccessTimeLimitModule
    ],
    providers: [
        AddonModQuizAccessRuleDelegate,
        AddonModQuizProvider,
        AddonModQuizOfflineProvider,
        AddonModQuizHelperProvider,
        AddonModQuizSyncProvider,
        AddonModQuizModuleHandler,
        AddonModQuizPrefetchHandler,
        AddonModQuizSyncCronHandler,
        AddonModQuizIndexLinkHandler,
        AddonModQuizGradeLinkHandler,
        AddonModQuizReviewLinkHandler,
        AddonModQuizListLinkHandler,
        AddonModQuizPushClickHandler
    ]
})
export class AddonModQuizModule {
    constructor(moduleDelegate: CoreCourseModuleDelegate, moduleHandler: AddonModQuizModuleHandler,
            prefetchDelegate: CoreCourseModulePrefetchDelegate, prefetchHandler: AddonModQuizPrefetchHandler,
            cronDelegate: CoreCronDelegate, syncHandler: AddonModQuizSyncCronHandler, linksDelegate: CoreContentLinksDelegate,
            indexHandler: AddonModQuizIndexLinkHandler, gradeHandler: AddonModQuizGradeLinkHandler,
            reviewHandler: AddonModQuizReviewLinkHandler, updateManager: CoreUpdateManagerProvider,
            listLinkHandler: AddonModQuizListLinkHandler,
            pushNotificationsDelegate: CorePushNotificationsDelegate, pushClickHandler: AddonModQuizPushClickHandler) {

        moduleDelegate.registerHandler(moduleHandler);
        prefetchDelegate.registerHandler(prefetchHandler);
        cronDelegate.register(syncHandler);
        linksDelegate.registerHandler(indexHandler);
        linksDelegate.registerHandler(gradeHandler);
        linksDelegate.registerHandler(reviewHandler);
        linksDelegate.registerHandler(listLinkHandler);
        pushNotificationsDelegate.registerClickHandler(pushClickHandler);

        // Allow migrating the tables from the old app to the new schema.
        updateManager.registerSiteTableMigration({
            name: 'mod_quiz_attempts',
            newName: AddonModQuizOfflineProvider.ATTEMPTS_TABLE,
            fields: [
                {
                    name: 'quizAndUser',
                    delete: true
                },
                {
                    name: 'finished',
                    type: 'boolean'
                }
            ]
        });
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Copyright 2005-2006 The Apache Software Foundation or its licensors, as applicable

    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.
-->
<!DOCTYPE Test SYSTEM "test.dtd">
<!--
Author:  Maxim V. Makarov
Version: $Revision: 1.1.1.1 $
-->
<Test ID="dstore_00801" date-of-creation="2006-04-25" timeout="1">
  <Author value="Maxim V. Makarov"/>
  <Description>
   Checks that instructions dstore_0 and dstore 0 are equal
   Covered assertions assert_instr23a209
  </Description>
  <Source name="dstore_00801p.j"/>
  <Runner ID="Runtime">
    <Param name="toRun" value="org.apache.harmony.vts.test.vm.jvms.instructions.loadStore.dstore_0.dstore_008.dstore_00801.dstore_00801p"/>
  </Runner>
</Test>


text:
package annis.sqlgen;

import java.util.List;

import annis.model.QueryNode;
import annis.ql.parser.QueryData;

public abstract class AbstractSolutionMatchInFromClauseSqlGenerator extends
    AbstractSqlGenerator implements FromClauseSqlGenerator<QueryData>
{

  private SolutionSqlGenerator solutionSqlGenerator;

  @Override
  public String fromClause(QueryData queryData, List<QueryNode> alternative,
      String indent)
  {
    StringBuilder sb = new StringBuilder();

    sb.append(indent).append("(\n");

    sb.append(solutionSqlGenerator.toSql(queryData, indent + TABSTOP));
    sb.append(indent).append(TABSTOP).append(") AS solutions");

    return sb.toString();
  }

  public SolutionSqlGenerator getSolutionSqlGenerator()
  {
    return solutionSqlGenerator;
  }

  public void setSolutionSqlGenerator(SolutionSqlGenerator solutionSqlGenerator)
  {
    this.solutionSqlGenerator = solutionSqlGenerator;
  }

}


text:
import * as React from 'react';
import {Toggle} from 'office-ui-fabric-react';
import {Setting} from '../types';

interface ITrdSetSearchProps {
    onToggleClick(id:string);
    settings:Setting[];
    id:string;
}

export default class TrsSetSearch extends React.Component<ITrdSetSearchProps, any> {

    render(): JSX.Element {
        // console.log(this.props);
        const toggles = this.props.settings.map(t => {
        return <Toggle key={t.id} label={t.title} checked={t.activated} onChanged={(checked) => {this.props.onToggleClick(t.id);}} />
        });
        return (

                    {toggles}

        )
    }
}


text:
package org.ojalgo.type.keyvalue;

import static org.ojalgo.constant.PrimitiveMath.*;

import org.ojalgo.netio.ASCII;

public final class IntToDouble implements KeyValue<Integer, Double> {

    public final int key;
    public final double value;

    public IntToDouble(final int aKey, final double aValue) {

        super();

        key = aKey;
        value = aValue;
    }

    public IntToDouble(final int aKey, final Double aValue) {

        super();

        key = aKey;
        value = aValue != null ? aValue : ZERO;
    }

    public IntToDouble(final Integer aKey, final double aValue) {

        super();

        key = aKey != null ? aKey : 0;
        value = aValue;
    }

    public IntToDouble(final Integer aKey, final Double aValue) {

        super();

        key = aKey != null ? aKey : 0;
        value = aValue != null ? aValue : ZERO;
    }

    IntToDouble() {
        this(0, ZERO);
    }

    public int compareTo(final IntToDouble aReference) {
        return (key < aReference.key ? -1 : (key == aReference.key ? 0 : 1));
    }

    public int compareTo(final KeyValue<Integer, ?> aReference) {
        return Double.compare(key, aReference.getKey());
    }

    @Override
    public boolean equals(final Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (!(obj instanceof IntToDouble)) {
            return false;
        }
        final IntToDouble other = (IntToDouble) obj;
        if (key != other.key) {
            return false;
        }
        return true;
    }

    public Integer getKey() {
        return key;
    }

    public Double getValue() {
        return value;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + key;
        return result;
    }

    @Override
    public String toString() {
        return String.valueOf(key) + String.valueOf(ASCII.EQUALS) + String.valueOf(value);
    }

}


text:
#ifndef GRPCPP_CHANNEL_IMPL_H
#define GRPCPP_CHANNEL_IMPL_H

#include <memory>
#include <mutex>

#include <grpc/grpc.h>
#include <grpcpp/impl/call.h>
#include <grpcpp/impl/codegen/channel_interface.h>
#include <grpcpp/impl/codegen/client_interceptor.h>
#include <grpcpp/impl/codegen/completion_queue_impl.h>
#include <grpcpp/impl/codegen/config.h>
#include <grpcpp/impl/codegen/grpc_library.h>
#include <grpcpp/impl/codegen/sync.h>

struct grpc_channel;

namespace grpc {

std::shared_ptr<::grpc_impl::Channel> CreateChannelInternal(
    const grpc::string& host, grpc_channel* c_channel,
    std::vector<
        std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
        interceptor_creators);
}  // namespace grpc
namespace grpc_impl {

namespace experimental {
/// Resets the channel's connection backoff.
/// TODO(roth): Once we see whether this proves useful, either create a gRFC
/// and change this to be a method of the Channel class, or remove it.
void ChannelResetConnectionBackoff(Channel* channel);
}  // namespace experimental

/// Channels represent a connection to an endpoint. Created by \a CreateChannel.
class Channel final : public ::grpc::ChannelInterface,
                      public ::grpc::internal::CallHook,
                      public std::enable_shared_from_this<Channel>,
                      private ::grpc::GrpcLibraryCodegen {
 public:
  ~Channel();

  /// Get the current channel state. If the channel is in IDLE and
  /// \a try_to_connect is set to true, try to connect.
  grpc_connectivity_state GetState(bool try_to_connect) override;

  /// Returns the LB policy name, or the empty string if not yet available.
  grpc::string GetLoadBalancingPolicyName() const;

  /// Returns the service config in JSON form, or the empty string if
  /// not available.
  grpc::string GetServiceConfigJSON() const;

 private:
  template <class InputMessage, class OutputMessage>
  friend class ::grpc::internal::BlockingUnaryCallImpl;
  friend void experimental::ChannelResetConnectionBackoff(Channel* channel);
  friend std::shared_ptr<Channel> grpc::CreateChannelInternal(
      const grpc::string& host, grpc_channel* c_channel,
      std::vector<std::unique_ptr<
          ::grpc::experimental::ClientInterceptorFactoryInterface>>
          interceptor_creators);
  friend class ::grpc::internal::InterceptedChannel;
  Channel(const grpc::string& host, grpc_channel* c_channel,
          std::vector<std::unique_ptr<
              ::grpc::experimental::ClientInterceptorFactoryInterface>>
              interceptor_creators);

  ::grpc::internal::Call CreateCall(const ::grpc::internal::RpcMethod& method,
                                    ::grpc_impl::ClientContext* context,
                                    ::grpc_impl::CompletionQueue* cq) override;
  void PerformOpsOnCall(::grpc::internal::CallOpSetInterface* ops,
                        ::grpc::internal::Call* call) override;
  void* RegisterMethod(const char* method) override;

  void NotifyOnStateChangeImpl(grpc_connectivity_state last_observed,
                               gpr_timespec deadline,
                               ::grpc_impl::CompletionQueue* cq,
                               void* tag) override;
  bool WaitForStateChangeImpl(grpc_connectivity_state last_observed,
                              gpr_timespec deadline) override;

  ::grpc_impl::CompletionQueue* CallbackCQ() override;

  ::grpc::internal::Call CreateCallInternal(
      const ::grpc::internal::RpcMethod& method,
      ::grpc_impl::ClientContext* context, ::grpc_impl::CompletionQueue* cq,
      size_t interceptor_pos) override;

  const grpc::string host_;
  grpc_channel* const c_channel_;  // owned

  // mu_ protects callback_cq_ (the per-channel callbackable completion queue)
  grpc::internal::Mutex mu_;

  // callback_cq_ references the callbackable completion queue associated
  // with this channel (if any). It is set on the first call to CallbackCQ().
  // It is _not owned_ by the channel; ownership belongs with its internal
  // shutdown callback tag (invoked when the CQ is fully shutdown).
  ::grpc_impl::CompletionQueue* callback_cq_ = nullptr;

  std::vector<
      std::unique_ptr<::grpc::experimental::ClientInterceptorFactoryInterface>>
      interceptor_creators_;
};

}  // namespace grpc_impl

#endif  // GRPCPP_CHANNEL_IMPL_H


text:
using System;
using System.Reflection;
using System.Text;
using System.Collections.Generic;
using Enexure.Fire.Reflection;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Enexure.Fire.Tests.Reflection.TypeExtensionsTests
{
	[TestClass]
	public class IsNullableTypeTests
	{
		[TestMethod]
		public void NullableTypes()
		{
			typeof(int?).GetTypeInfo().IsNullable().Should().Be(true);
			typeof(DateTime?).GetTypeInfo().IsNullable().Should().Be(true);
		}

		[TestMethod]
		public void NonNullableTypes()
		{
			typeof(List<int>).GetTypeInfo().IsNullable().Should().Be(false);
			typeof(int[]).GetTypeInfo().IsNullable().Should().Be(false);
		}
	}
}


text:
package id.qsolution.models;

import java.io.Serializable;
import com.turbomanage.storm.api.Entity;
import com.turbomanage.storm.api.Id;

@SuppressWarnings("serial")
@Entity
public class TmPosm implements Serializable {

	@Id
	private long id;
	private String kode = "00";
	private String nama;

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getKode() {
		return kode;
	}

	public void setKode(String kode) {
		this.kode = kode;
	}

	public String getNama() {
		return nama;
	}

	public void setNama(String nama) {
		this.nama = nama;
	}

}


text:
<?php

namespace Billplz\Four\Bill;

use Billplz\Three\Bill\Transaction as Request;

class Transaction extends Request
{
    //
}


text:
/**
 * Created by 陈志杭 on 2016/12/27.
 * @file admin/view/Register
 */
define([
    'zh/app/view/PageView',
    'admin/api/identityHttpService',
    'admin/util/context',
    'admin/util/viewRouter',
    'dojo/on',
    "dojo/_base/declare",
    "dojo/text!./templates/register.html",

    'admin/util/loginStateUtils',
    'dojo/_base/lang',
    "dojo/parser",
    'dijit/registry',
    "dojo/ready",
    'dojo/dom-class',
    'zh/app/util/hashUtils',
    'zh/core',

    'zh/util/stringUtils',
    'admin/util/tipUtils',
    "dijit/_WidgetsInTemplateMixin",
    'dijit/form/Form',
    'dijit/form/_FormValueWidget',
    'dojox/form/Manager',
], function (PageView, identityHttpService, context, viewRouter, on, declare, template, loginStateUtils, lang, parser, registry, ready, domClass, hashUtils
    , zh, stringUtils, tipUtils, _WidgetsInTemplateMixin, Form, _FormValueWidget, FormManager) {

    return declare([PageView, _WidgetsInTemplateMixin], {
        frmLoginPoint: null,
        txtAccountPoint: null,
        txtPasswordPoint: null,
        divInviterIdPoint: null,
        txtInviterIdPoint: null,
        txtInviterTextPoint: null,
        templateString: template,
        showDivInviterIdPoint: function () {
            domClass.remove(this.divInviterIdPoint, 'hide');
        },
        isHasInviterId: function () {
            return zh.isNotEmptyObject(this.getInviterIdParam());
        },
        getInviterIdParam: function () {
            return hashUtils.getParams().inviterId;
        },
        postCreate: function () {
            var me = this;
            me.inherited(arguments);

        },
        // 视图加载完成时候回调
        onLoaded: function (route) {
            var me = this;
            if (this.isHasInviterId()) {
                this.hide();
                identityHttpService.getAccountNameOrAccount({
                    data: {
                        accountId: this.getInviterIdParam()
                    }
                }).then({
                    success: function (res) {
                        if (zh.isNotEmptyObject(res)) {
                            me.txtInviterIdPoint.value = me.getInviterIdParam();
                            me.txtInviterTextPoint.value = '邀请人:' + res.accountOrName;
                        } else {
                            me.txtInviterIdPoint.value = me.getInviterIdParam();
                            me.txtInviterTextPoint.value = '该邀请链接失效';
                            tipUtils.warning('该邀请链接失效');
                        }
                    },
                    complete: function () {
                        me.show();
                        me.showDivInviterIdPoint();
                    }
                });
            } else {
                this.show();
            }
            on(me.frmLoginPoint, 'submit', function () {
                event.preventDefault();
                event.stopPropagation();
                lang.hitch(me, 'submit')(arguments);
                return false;
            });
        },
        submit: function () {
            var me = this;
            var data = me.frmLoginPoint.gatherFormValues({
                inviterId: '',
                password: '',
                confirmPassword: '',
                account: '',
                name: '',
            });
            var svcMethod = identityHttpService.register;
            var data = data;
            if (me.isHasInviterId()) {
                svcMethod = identityHttpService.registerByInvitation
            }
            svcMethod({
                data: data
            }).success(function (res) {
                loginStateUtils.setAccount(res);
                viewRouter.go('/main');
            });
            return false;
        }
    });
});


text:
This plugin adds completion for Git, using the zsh completion from git.git folks, which is much faster than the official one from zsh. A lot of zsh-specific features are not supported, like descriptions for every argument, but everything the bash completion has, this one does too (as it is using it behind the scenes). Not only is it faster, it should be more robust, and updated regularly to the latest git upstream version.

To use it, add `gitfast` to the plugins array in your zshrc file:

```zsh
plugins=(... gitfast)
```

## Aliases

An earlier version of the plugin also loaded the git plugin. If you want to keep those
aliases enable the [git plugin](https://github.com/ohmyzsh/ohmyzsh/tree/master/plugins/git)
as well.


text:
class Open3
    @@collected_commands = []
    @@collected_dirs = []

    @@returned_text = ""
    @@returned_status = 0

    def self.capture2e(command, chdir: ".")
        @@collected_commands.push(command)
        @@collected_dirs.push(chdir)

        return [*@@returned_text, @@returned_status]
    end

    def self.collected_commands
        return @@collected_commands
    end

    def self.collected_dirs
        return @@collected_dirs
    end

    def self.set_returned_text(text)
        @@returned_text = text
    end

    def self.set_returned_status(status)
        @@returned_status = status
    end

    def self.reset()
        @@collected_commands = []
        @@collected_dirs = []

        @@returned_text = ""
        @@returned_status = 0
    end
end


text:
Aleksi Pekkala (alvianpe@student.jyu.fi)</br>19.3.2017

## Aihe

Harjoitustyön aiheena on yksinkertainen Lisp-kääntäjä. Kääntäjä toteutetaan
funktionaalisella [Elixir](http://elixir-lang.org/)-kielellä. Kielestä löytyy monia ML-kieliä vastaavia ominaisuuksia
kuten pattern matching, joten se sopinee hyvin isäntäkieleksi. Lisäksi [yecc](http://erlang.org/doc/man/yecc.html)- ja
[leex](http://erlang.org/doc/man/leex.html)-kirjastot tarjoavat `yacc`- ja `lex`-työkaluja  vastaavat toiminnot, joskin
pyrin ainakin aluksi välttämään näiden käyttöä. Kääntäjän työnimi on **sammal**.

## Vaatimukset

Lähdekieli tulee kattamaan jonkinlaisen osuuden [Scheme-kielestä](http://www.schemers.org/Documents/Standards/R5RS/HTML/):

- Tietotyypit: listat, [kokonais-ja liukuluvut, symbolit](http://www.schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-7.html#%_sec_4.1.2)
- Muuttujat: [`define`, `set!`, `let`](http://www.schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-8.html#%_sec_5.2)
- Tulostaminen: [`quote`](http://www.schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-7.html#%_sec_4.1.2)
- Ehtolauseet: [`if`, `and`, `or`](http://www.schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-7.html#%_sec_4.1.5)
- Funktiot: [`lambda`](http://www.schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-7.html#%_sec_4.1.4)
- Ajan salliessa muita ominaisuuksia:
  - [`case` ja `cond`-ehtolauseet](http://www.schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-7.html#%_sec_4.2.1)
  - [makrot](http://www.schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-7.html#%_sec_4.3)
  - [laiska laskenta](http://www.schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-7.html#%_sec_4.2.5)
  - [tail recursion](http://www.schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-6.html#%_sec_3.5)

Esimerkki lähdekielestä:
```scheme
; Fibonacci-sarja:
(define (fib-rec n)
  (if (< n 2)
      n
      (+ (fib-rec (- n 1))
         (fib-rec (- n 2)))))
```

## Testaus

Testaus hoidetaan toteutuksen edetessä yksikkötesteillä TDD-periaatteiden mukaisesti, sekä erikseen laajemmilla integraatiotesteillä.


text:
cask :v1 => 'jetphoto-studio' do
  version '5.5'
  sha256 'c583a173d018696d613545acacba4c43f641d770de4e5d5bbb0964c1cb2e9f7f'

  url "http://www.jetphotosoft.com/web/download/JetPhoto_Studio_mac#{version}.zip"
  homepage 'http://www.jetphotosoft.com/web/home/'
  license :unknown    # todo: improve this machine-generated value

  container :nested => "JetPhoto Studio #{version}.dmg"
  app 'JetPhoto Studio.app'
end


text:
import sys
import struct

from mutagen._compat import swap_to_string, text_type, PY2, reraise
from mutagen._util import total_ordering

from ._util import ASFError

class ASFBaseAttribute(object):
    """Generic attribute."""

    TYPE = None

    _TYPES = {}

    value = None
    """The Python value of this attribute (type depends on the class)"""

    language = None
    """Language"""

    stream = None
    """Stream"""

    def __init__(self, value=None, data=None, language=None,
                 stream=None, **kwargs):
        self.language = language
        self.stream = stream
        if data:
            self.value = self.parse(data, **kwargs)
        else:
            if value is None:
                # we used to support not passing any args and instead assign
                # them later, keep that working..
                self.value = None
            else:
                self.value = self._validate(value)

    @classmethod
    def _register(cls, other):
        cls._TYPES[other.TYPE] = other
        return other

    @classmethod
    def _get_type(cls, type_):
        """Raises KeyError"""

        return cls._TYPES[type_]

    def _validate(self, value):
        """Raises TypeError or ValueError in case the user supplied value
        isn't valid.
        """

        return value

    def data_size(self):
        raise NotImplementedError

    def __repr__(self):
        name = "%s(%r" % (type(self).__name__, self.value)
        if self.language:
            name += ", language=%d" % self.language
        if self.stream:
            name += ", stream=%d" % self.stream
        name += ")"
        return name

    def render(self, name):
        name = name.encode("utf-16-le") + b"\x00\x00"
        data = self._render()
        return (struct.pack("<H", len(name)) + name +
                struct.pack("<HH", self.TYPE, len(data)) + data)

    def render_m(self, name):
        name = name.encode("utf-16-le") + b"\x00\x00"
        if self.TYPE == 2:
            data = self._render(dword=False)
        else:
            data = self._render()
        return (struct.pack("<HHHHI", 0, self.stream or 0, len(name),
                            self.TYPE, len(data)) + name + data)

    def render_ml(self, name):
        name = name.encode("utf-16-le") + b"\x00\x00"
        if self.TYPE == 2:
            data = self._render(dword=False)
        else:
            data = self._render()

        return (struct.pack("<HHHHI", self.language or 0, self.stream or 0,
                            len(name), self.TYPE, len(data)) + name + data)

@ASFBaseAttribute._register
@swap_to_string
@total_ordering
class ASFUnicodeAttribute(ASFBaseAttribute):
    """Unicode string attribute.

    ::

        ASFUnicodeAttribute(u'some text')
    """

    TYPE = 0x0000

    def parse(self, data):
        try:
            return data.decode("utf-16-le").strip("\x00")
        except UnicodeDecodeError as e:
            reraise(ASFError, e, sys.exc_info()[2])

    def _validate(self, value):
        if not isinstance(value, text_type):
            if PY2:
                return value.decode("utf-8")
            else:
                raise TypeError("%r not str" % value)
        return value

    def _render(self):
        return self.value.encode("utf-16-le") + b"\x00\x00"

    def data_size(self):
        return len(self._render())

    def __bytes__(self):
        return self.value.encode("utf-16-le")

    def __str__(self):
        return self.value

    def __eq__(self, other):
        return text_type(self) == other

    def __lt__(self, other):
        return text_type(self) < other

    __hash__ = ASFBaseAttribute.__hash__

@ASFBaseAttribute._register
@swap_to_string
@total_ordering
class ASFByteArrayAttribute(ASFBaseAttribute):
    """Byte array attribute.

    ::

        ASFByteArrayAttribute(b'1234')
    """
    TYPE = 0x0001

    def parse(self, data):
        assert isinstance(data, bytes)
        return data

    def _render(self):
        assert isinstance(self.value, bytes)
        return self.value

    def _validate(self, value):
        if not isinstance(value, bytes):
            raise TypeError("must be bytes/str: %r" % value)
        return value

    def data_size(self):
        return len(self.value)

    def __bytes__(self):
        return self.value

    def __str__(self):
        return "[binary data (%d bytes)]" % len(self.value)

    def __eq__(self, other):
        return self.value == other

    def __lt__(self, other):
        return self.value < other

    __hash__ = ASFBaseAttribute.__hash__

@ASFBaseAttribute._register
@swap_to_string
@total_ordering
class ASFBoolAttribute(ASFBaseAttribute):
    """Bool attribute.

    ::

        ASFBoolAttribute(True)
    """

    TYPE = 0x0002

    def parse(self, data, dword=True):
        if dword:
            return struct.unpack("<I", data)[0] == 1
        else:
            return struct.unpack("<H", data)[0] == 1

    def _render(self, dword=True):
        if dword:
            return struct.pack("<I", bool(self.value))
        else:
            return struct.pack("<H", bool(self.value))

    def _validate(self, value):
        return bool(value)

    def data_size(self):
        return 4

    def __bool__(self):
        return bool(self.value)

    def __bytes__(self):
        return text_type(self.value).encode('utf-8')

    def __str__(self):
        return text_type(self.value)

    def __eq__(self, other):
        return bool(self.value) == other

    def __lt__(self, other):
        return bool(self.value) < other

    __hash__ = ASFBaseAttribute.__hash__

@ASFBaseAttribute._register
@swap_to_string
@total_ordering
class ASFDWordAttribute(ASFBaseAttribute):
    """DWORD attribute.

    ::

        ASFDWordAttribute(42)
    """

    TYPE = 0x0003

    def parse(self, data):
        return struct.unpack("<L", data)[0]

    def _render(self):
        return struct.pack("<L", self.value)

    def _validate(self, value):
        value = int(value)
        if not 0 <= value <= 2 ** 32 - 1:
            raise ValueError("Out of range")
        return value

    def data_size(self):
        return 4

    def __int__(self):
        return self.value

    def __bytes__(self):
        return text_type(self.value).encode('utf-8')

    def __str__(self):
        return text_type(self.value)

    def __eq__(self, other):
        return int(self.value) == other

    def __lt__(self, other):
        return int(self.value) < other

    __hash__ = ASFBaseAttribute.__hash__

@ASFBaseAttribute._register
@swap_to_string
@total_ordering
class ASFQWordAttribute(ASFBaseAttribute):
    """QWORD attribute.

    ::

        ASFQWordAttribute(42)
    """

    TYPE = 0x0004

    def parse(self, data):
        return struct.unpack("<Q", data)[0]

    def _render(self):
        return struct.pack("<Q", self.value)

    def _validate(self, value):
        value = int(value)
        if not 0 <= value <= 2 ** 64 - 1:
            raise ValueError("Out of range")
        return value

    def data_size(self):
        return 8

    def __int__(self):
        return self.value

    def __bytes__(self):
        return text_type(self.value).encode('utf-8')

    def __str__(self):
        return text_type(self.value)

    def __eq__(self, other):
        return int(self.value) == other

    def __lt__(self, other):
        return int(self.value) < other

    __hash__ = ASFBaseAttribute.__hash__

@ASFBaseAttribute._register
@swap_to_string
@total_ordering
class ASFWordAttribute(ASFBaseAttribute):
    """WORD attribute.

    ::

        ASFWordAttribute(42)
    """

    TYPE = 0x0005

    def parse(self, data):
        return struct.unpack("<H", data)[0]

    def _render(self):
        return struct.pack("<H", self.value)

    def _validate(self, value):
        value = int(value)
        if not 0 <= value <= 2 ** 16 - 1:
            raise ValueError("Out of range")
        return value

    def data_size(self):
        return 2

    def __int__(self):
        return self.value

    def __bytes__(self):
        return text_type(self.value).encode('utf-8')

    def __str__(self):
        return text_type(self.value)

    def __eq__(self, other):
        return int(self.value) == other

    def __lt__(self, other):
        return int(self.value) < other

    __hash__ = ASFBaseAttribute.__hash__

@ASFBaseAttribute._register
@swap_to_string
@total_ordering
class ASFGUIDAttribute(ASFBaseAttribute):
    """GUID attribute."""

    TYPE = 0x0006

    def parse(self, data):
        assert isinstance(data, bytes)
        return data

    def _render(self):
        assert isinstance(self.value, bytes)
        return self.value

    def _validate(self, value):
        if not isinstance(value, bytes):
            raise TypeError("must be bytes/str: %r" % value)
        return value

    def data_size(self):
        return len(self.value)

    def __bytes__(self):
        return self.value

    def __str__(self):
        return repr(self.value)

    def __eq__(self, other):
        return self.value == other

    def __lt__(self, other):
        return self.value < other

    __hash__ = ASFBaseAttribute.__hash__

def ASFValue(value, kind, **kwargs):
    """Create a tag value of a specific kind.

    ::

        ASFValue(u"My Value", UNICODE)

    :rtype: ASFBaseAttribute
    :raises TypeError: in case a wrong type was passed
    :raises ValueError: in case the value can't be be represented as ASFValue.
    """

    try:
        attr_type = ASFBaseAttribute._get_type(kind)
    except KeyError:
        raise ValueError("Unknown value type %r" % kind)
    else:
        return attr_type(value=value, **kwargs)


text:
package cn.org.eshow.demo.common;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.lang.ref.WeakReference;

/**
 * 使用弱引用的handler,防止出现内存泄露
 * Created by daikting on 16/2/19.
 */
public class WeakRefHandler extends Handler {
    private final WeakReference<Callback> mRef;
    private final int mLoopTime;
    private int NO_LOOP = -1;

    public WeakRefHandler(Callback loopAction, int loopTime) {
        super();
        mRef = new WeakReference<>(loopAction);
        mLoopTime = loopTime;
    }

    // 不循环
    public WeakRefHandler(Callback loopAction) {
        super();
        mRef = new WeakReference<>(loopAction);
        mLoopTime = NO_LOOP;
    }

    @Override
    public void handleMessage(Message msg) {
        Log.d("", "loophandle");
        Callback action = mRef.get();
        if (action != null) {
            action.handleMessage(msg);
            if (mLoopTime != NO_LOOP) {
                sendEmptyMessageDelayed(0, mLoopTime);
            }
        }
    }

    public void start() {
        removeMessages(0);
        sendEmptyMessageDelayed(0, 0);
    }

    public void start(int what, long delay) {
        removeMessages(0);
        sendEmptyMessageDelayed(what, delay);
    }

    public void stop() {
        removeMessages(0);
    }

    public void clear() {
        removeMessages(0);
        mRef.clear();
    }
}


text:
/**
 * Headless Hello World.
 *
 * @author   Patrick Schroen / https://github.com/pschroen
 * @license  MIT Licensed
 */

/* jshint strict:true, eqeqeq:true, newcap:false, multistr:true, expr:true, loopfunc:true, shadow:true, node:true, phantom:true, indent:4 */
/* globals shell */
"use strict";

var utils = require(shell.path+'/modules/utils'),
    Script = utils.Script(module.id, "Hello World");

/**
 * Initialize.
 *
 * @param    {Probe} probe Instance
 * @param    {undefined|Object} [load] Payload
 * @param    {undefined|initCallback} [callback]
 */
function init(probe, load, callback) {
    var headers = {
            'Access-Control-Allow-Origin': load.origin,
            'Access-Control-Allow-Credentials': 'true'
        };
    probe.log("["+exports.id+"] "+exports.name);
    callback({
        title: exports.name,
        text: 'The Headless framework simply receives and sends JavaScript Objects as input and output. The name of this file is your webhook, for example; /hello.'
    }, headers);
}
Script.prototype.init = init;

module.exports = exports = new Script();


text:
#ifndef RenderFrame_h
#define RenderFrame_h

#include "RenderFrameBase.h"
#include "RenderFrameSet.h"

namespace WebCore {

class HTMLFrameElement;

class RenderFrame final : public RenderFrameBase {
public:
    RenderFrame(HTMLFrameElement&, PassRef<RenderStyle>);

    HTMLFrameElement& frameElement() const;
    FrameEdgeInfo edgeInfo() const;

private:
    void frameOwnerElement() const = delete;

    virtual const char* renderName() const override { return "RenderFrame"; }
    virtual bool isFrame() const override { return true; }

    virtual void updateFromElement() override;
};

RENDER_OBJECT_TYPE_CASTS(RenderFrame, isFrame())

} // namespace WebCore

#endif // RenderFrame_h


text:
package org.apache.myfaces.config.impl.digester.elements;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Oliver Rossmueller
 */
public class LocaleConfigImpl extends org.apache.myfaces.config.element.LocaleConfig implements Serializable
{

    private String defaultLocale;
    private List<String> supportedLocales = new ArrayList<String>();

    public void setDefaultLocale(String defaultLocale)
    {
        this.defaultLocale = defaultLocale;
    }

    public void addSupportedLocale(String locale)
    {
        supportedLocales.add(locale);
    }

    public String getDefaultLocale()
    {
        return defaultLocale;
    }

    public List<String> getSupportedLocales()
    {
        return supportedLocales;
    }
}