text:
Joke
====

Joke is a internal DSL based on RAKE #irresponsibleruby
Take a Look  [Jokefile](https://github.com/tdantas/Joke/blob/master/Jokefile)

###  Context
A good friend asked me to help him to implement a Build tool, for his Job Interview. *GL my friend*
Read the Interview below

Inspired by Rake, I decied to create my own Internal DSL.

Why ?? 4 fun

When I like something, I will read the code, study and try to reproduce. Just because I liked it :D

I called **JOKE** ( Job + Rake ) = Joke :)

### How to use ? ( #irresponsibleruby )

````
  $ git clone  https://github.com/tdantas/Joke.git
  $ cd joke
  $ bundle install
  $ bundle exec joke deploy

````

Options

	$ bundle exec joke -h
	joke [options] job_name
      -j, --jokefile PATH              path to Jokefile
      -l, --list                       list jobs descriptions (TODO)
      -v, --version                    Print version and exit
      -h, --help                       Show help

### How to Test ?

Why not use the JOKE to run our tests ?
*( Need more coverage tests, can you help me ? )*

	bundle exec joke rspec

===

# The Interview

````

Imagine we have a list of jobs, each represented by a character.
Because certain jobs must be done before others, a job may have a dependency on another job.
For example, a may depend on b, meaning the final sequence of jobs should place b before a.
If a has no dependency, the position of a in the final sequence does not matter.

  	* Given you're passed an empty string (no jobs), the result should be an empty sequence

  	* Given the following job structure:

  	  	a =>

  	 The result should be a sequence consisting of a single job a.

  	* Given the following job structure:
      	a =>
      	b =>
      	c =>

      The result should be a sequence containing all three jobs abc in no significant order.

   	* Given the following job structure:
   		a =>
		b => c
		c =>

	  The result should be a sequence that positions c before b, containing all three jobs abc.

	* Given the following job structure:
		a =>
		b => c
		c => f
		d => a
		e => b
		f =>

	  The result should be a sequence that positions
           f before c,
           c before b,
           b before e
           and a before d containing all six jobs abcdef.

	* Given the following job structure:
		a => a
		b =>
		c =>

	 The result should be an error stating that jobs can't depend on themselves.

	* Given the following job structure:

		a =>
		b => c
		c => f
		d => a
		e =>
		f => b
	 The result should be an error stating that jobs can't have circular dependencies.
````


text:
#include <gl/shader.h>
#include <ul/string.h>
#include <ul/log.h>
#include <string>

namespace gl {

void shader::destroy() {
  if (vertexId_) {
    glDeleteShader(vertexId_);
    vertexId_ = 0;
  }
  if (vertexId_) {
    glDeleteShader(vertexId_);
    vertexId_ = 0;
  }
  if (programId_) {
    glDeleteProgram(programId_);
    programId_ = 0;
  }
  timer_.destroy();
}

GLuint shader::_loadShaderFromString(const char* shaderCode,
                                     GLenum shaderType) {
  if (ul::strIsNull(shaderCode)) {
    ul::report(ul::kError, "No shader code to load");
    return 0;
  }

  GLuint shaderID = glCreateShader(shaderType);
  if (!shaderID) {
    ul::report(ul::kError, "Can't create a shader");
    return 0;
  }

  glShaderSource(shaderID, 1, &shaderCode, nullptr);
  glCompileShader(shaderID);

  GLint compiled;
  glGetShaderiv(shaderID, GL_COMPILE_STATUS, &compiled);
  if (!compiled) {
    GLchar errMsg[ul::kStrMaxSize];
    glGetShaderInfoLog(shaderID, ul::kStrMaxSize, nullptr, errMsg);
    ul::report(ul::kError, "Can't compile shader:\n%s", errMsg);
    glDeleteShader(shaderID);
    return 0;
  }

  return shaderID;
}

GLuint shader::_loadShaderFromFile(const std::string& shaderPath,
                                   GLenum shaderType) {
  FILE* file = std::fopen(shaderPath.c_str(), "r");
  if (!file) {
    ul::report(ul::kError, "Can't open shader '%s'", shaderPath.c_str());
    return 0;
  }
  std::fseek(file, 0, SEEK_END);
  size_t len = (size_t)std::ftell(file);
  std::fseek(file, 0, SEEK_SET);
  char* shaderCode = static_cast<char*>(malloc((len + 1) * sizeof(char)));

  if (std::fread(shaderCode, 1, len, file) != len) {
    ul::report(ul::kError, "Can't read shader '%s'", shaderPath.c_str());
    free(shaderCode);
    std::fclose(file);
    return 0;
  }
  shaderCode[len] = '\0';

  GLuint shaderID = _loadShaderFromString(shaderCode, shaderType);
  free(shaderCode);
  std::fclose(file);

  return shaderID;
}

bool shader::loadShader(const std::string& vertexPath,
                        const std::string& fragmentPath) {
  destroy();

  // Load the vertex shader
  vertexId_ = _loadShaderFromFile(vertexPath, GL_VERTEX_SHADER);
  if (!vertexId_) {
    destroy();
    return false;
  }

  // Load the fragment shader
  fragmentId_ = _loadShaderFromFile(fragmentPath, GL_FRAGMENT_SHADER);
  if (!fragmentId_) {
    destroy();
    return false;
  }

  // Create the program and attached the 2 shaders
  programId_ = glCreateProgram();
  if (!programId_) {
    ul::report(ul::kError, "Can't create a shader program");
    destroy();
    return false;
  }

  glAttachShader(programId_, vertexId_);
  glAttachShader(programId_, fragmentId_);

  glLinkProgram(programId_);
  GLint linked;
  glGetProgramiv(programId_, GL_LINK_STATUS, &linked);
  if (!linked) {
    GLchar errMsg[ul::kStrMaxSize];
    glGetProgramInfoLog(programId_, ul::kStrMaxSize, nullptr, errMsg);
    ul::report(ul::kError, "Can't link shader program:\n%s", errMsg);
    destroy();
    return false;
  }

  // Start the timer
  timer_.start();

  return true;
}

void shader::bind(const float trans[16]) const {
  if (!programId_) {
    // Nothing to bind
    return;
  }

  glUseProgram(programId_);

  // Aspect ratio
  GLint viewport[4];
  glGetIntegerv(GL_VIEWPORT, viewport);
  glUniform1f(glGetUniformLocation(programId_, "r"),
              static_cast<float>(viewport[3]) /
              static_cast<float>(viewport[2]));

  // Transformation
  if (!trans) {
    // If no transformation is specified, we use the identity
    static const GLfloat identity[16] = {
      1.0f, 0.0f, 0.0f, 0.0f,
      0.0f, 1.0f, 0.0f, 0.0f,
      0.0f, 0.0f, 1.0f, 0.0f,
      0.0f, 0.0f, 0.0f, 1.0f};
    trans = identity;
  }
  glUniformMatrix4fv(glGetUniformLocation(programId_, "trans"),
                     1, GL_FALSE, trans);

  // Position
  GLint p = glGetAttribLocation(programId_, "p");
  glEnableVertexAttribArray(p);
  glVertexAttribPointer(p, 2, GL_FLOAT, GL_FALSE,
                        4 * sizeof(GLfloat), nullptr);

  // Texture coordinate
  GLint tc = glGetAttribLocation(programId_, "tc");
  glEnableVertexAttribArray(tc);
  glVertexAttribPointer(tc, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat),
    (void*)(2 * sizeof(GLfloat)));  // NOLINT(readability/casting)

  // Time (in milli-seconds)
  glUniform1f(glGetUniformLocation(programId_, "t"), timer_.milliSecSince());
}

void shader::unbind() const {
  glUseProgram(0);
}

}  // namespace gl

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System;
using Microsoft.R.Host.Protocol;

namespace Microsoft.R.Host.Client {
    public class HostLoadChangedEventArgs : EventArgs {
        public HostLoad HostLoad { get; }

        public HostLoadChangedEventArgs(HostLoad hostLoad) {
            HostLoad = hostLoad;
        }
    }
}


text:
from __future__ import print_function

class Element(object):
    ''' Create data element with default value and next pointer. '''
    def __init__(self, value, priority=0):
        ''' Value and next pointer default to none. '''
        self.val = value
        self.prio = priority

class Priorityq(object):
    ''' Create an empty heap. '''
    def __init__(self):
        self.binlist = []

    def insert(self, value, priority=0):
        ''' Add a value to the heap. '''
        self.binlist.append(Element(value, priority))
        self._promote(len(self.binlist)-1)
        return

    def _parent(self, index):
        ''' Find the parents of a bin. '''
        return [(index-1)//2, self.binlist[(index-1)//2].prio]

    def _children(self, index):
        ''' Find the children of a bin. Build list of children. '''
        children = []
        try:
            child1 = (2 * index + 1, self.binlist[2*index+1].prio)
        except IndexError:
            pass
        else:
            children.append(child1)

        try:
            child2 = (2*index+2, self.binlist[2*index+2].prio)
        except IndexError:
            pass
        else:
            children.append(child2)

        return children

    def _swap(self, index1, index2):
        ''' Swap two bins. '''
        self.binlist[index1], self.binlist[index2] = self.binlist[index2], self.binlist[index1]
        return

    def pop(self):
        ''' Pop the top of the heap. '''
        last_index = len(self.binlist)-1
        top = self.binlist[0].val
        self._swap(0, last_index)
        self.binlist.pop()
        self._demote()
        return top

    def peek(self):
        ''' Return value of highest priority element. '''
        try:
            return self.binlist[0].val
        except AttributeError:
            raise IndexError('peek from empty queue')

    def _promote(self, index):
        ''' Promote a bin. '''
        child = self.binlist[index].prio
        parent = self._parent(index)
        if parent[0] >= 0:
            # If is true only when parent index is non-negative
            if parent[1] < child:
                self._swap(parent[0], index)
                self._promote(parent[0])
            else:
                return

    def _demote(self, index=0):
        children = self._children(index)
        ''' Demote a bin. '''
        if len(children):
            victor_index = self._battle_children(index, children)

            if victor_index:
                self._swap(victor_index, index)
                self._demote(victor_index)
        else:
            return

    def _battle_children(self, index, children):
        ''' Compare children bins. '''
        if len(children) == 2:
            # Handle two children
            if children[0][1] >= children[1][1]:
                return children[0][0]
            else:
                return children[1][0]

        elif len(children) == 1:
            # Handle one child
            return children[0][0]
        else:
            # Handle no children
            return None


text:
package org.dedunumax.xmongodbprofiler;

import org.dedunumax.xmongodbprofiler.ui.ProfilerWindow;

public class Main {

	public static void main(String[] args) {
		ProfilerWindow window = new ProfilerWindow();
		window.setVisible(true);
	}

}


text:
package ir.asparsa.android.ui.view;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

/**
 * @author hadi
 */
public class NonSwipeableViewPager extends ViewPager {

    public NonSwipeableViewPager(Context context) {
        super(context);
    }

    public NonSwipeableViewPager(
            Context context,
            AttributeSet attrs
    ) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        // Never allow swiping to switch between pages
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // Never allow swiping to switch between pages
        return false;
    }
}


text:
'use strict';

const archiver = require('archiver');
const fs = require('fs');
const istanbul = require('istanbul');
const jspm = require('jspm');
const Mocha = require('mocha');
const path = require('path');
const ps = require('child_process');
const sh = require('shelljs');
const systemIstanbul = require('systemjs-istanbul-hook');
const noop = () => {};

/**
 * Basic exec function.
 *
 * Unlike `shelljs.exec(cmd)`, it allow commands to print ansi colors.
 *
 * @param  {string} cmd  shell command to run
 * @param  {?{printCmd: boolean, ignoreStdout: boolean, ignoreStderr: boolean}} opts options
 */
exports.exec = function(cmd, opts) {
  opts = Object.assign({
    printCmd: true,
    ignoreStdout: false,
    ignoreStderr: false
  }, opts);

  exports.execPipe(cmd, {
    printCmd: opts.printCmd,
    stdout: opts.ignoreStdout ? 'ignore' : 'inherit',
    stderr: opts.ignoreStderr ? 'ignore' : 'inherit'
  });
};

function getStream(streamPath, flag) {
  if (!streamPath) {
    return 'ignore';
  }

  if (typeof streamPath !== 'string') {
    return streamPath;
  }

  switch (streamPath) {
    case 'ignore':
    case 'inherit':
      return streamPath;
    default:
      return fs.openSync(streamPath, flag);
  }
}

/**
 * Basic exec function which can pipe a child process standard stream to a
 * provided stream or file.
 *
 * `shelljs.exec(cmd).to(path)` seems to be affect by a 8kb limit.
 *
 * By default, the child process standard stream are pipe to the main process
 * one's.
 *
 * @example
 * execPipe('ls -lha dist/', {stdout: 'dist-list.txt'});
 *
 * @param  {string} cmd  shell command to run
 * @param  {?{printCmd: boolean, stdin: string, stdout: string, stderr: string}} opts options
 */
exports.execPipe = function(cmd, opts) {
  opts = Object.assign({
    printCmd: true,
    stdin: 'inherit',
    stdout: 'inherit',
    stderr: 'inherit'
  }, opts);

  if (opts.printCmd) {
    sh.echo(cmd);
  }

  const streams = ['stdin', 'stdout', 'stderr'];

  try {
    const stdio = streams.map(s => getStream(opts[s], s === 'stdin' ? 'r' : 'w'));

    ps.execSync(cmd, {stdio});

    streams.filter(
      s => stdio && stdio[s] && typeof stdio[s] !== 'string' && stdio[s] !== process[s]
    ).map(
      s => fs.closeSync(stdio[s])
    );
  } catch (e) {
    sh.exit(e.status);
  }
};

/**
 * Log and remove list of of file/directory.
 *
 * @param  {string|string[]}                   paths path of file/directory to remove
 * @param  {{message: string, force: boolean}} opts  options
 */
exports.clean = function(paths, opts) {
  opts = Object.assign({
    message: 'Removing build/test artifacts',
    force: false
  }, opts);
  paths = [].concat(paths).filter(p => sh.test('-e', p));

  if (paths.length === 0) {
    sh.echo('Nothing to remove.');
    return;
  }

  sh.echo(`${opts.message}: ${paths.map(p => `"${p}"`).join(', ')}...`);

  if (opts.force) {
    sh.rm('-rf', paths);
  }

  const dirs = paths.filter(p => sh.test('-d', p));
  const files = paths.filter(p => sh.test('-d', p) === false);

  if (dirs.length > 0) {
    sh.rm('-r', dirs);
  }

  if (files.length > 0) {
    sh.rm(files);
  }
};

/**
 * Resolve with a module loader.
 *
 * @param  {{config: function}} opts options
 * @return {Promise<jspm.Loader, Error>}
 */
function loadJspmConfig(opts) {
  sh.echo('Loading jspm config...');

  return new Promise(resolve => {
    const loader = new jspm.Loader();

    opts.config(loader);
    resolve(loader);
  });
}

/**
 * Resolve with a module loader which will add coverage instrumentation
 * to src code.
 *
 * @param  {{exclude: function, config: function}}  opts coverage options
 * @return {Promise<void, Error>}
 , config: {}*/
function hookInstanbul(opts) {
  return loadJspmConfig(opts).then(loader => {
    sh.echo('Registering instrumentation hook to loader...');
    systemIstanbul.hookSystemJS(loader, opts.exclude(loader.baseURL));

    return loader;
  });
}

/**
 * Run mocha tests.
 *
 * Collect test cases by importing the test modules.
 *
 * @param  {jspm.Loader}   loader  a module loader.
 * @param  {string|array}  modules modules defining mocha tests.
 * @param  {?{ui: string}} opts    mocha runner options.
 * @return {Promise<void, Error>}
 */
function runTests(loader, modules, opts) {
  const runner = new Mocha({ui: opts.ui});

  return new Promise((resolve, reject) => {
    switch (opts.ui) {
      case 'bdd':
      case 'tdd':
      case 'mocha-qunit-ui':
        sh.echo('Augmenting global with mocha API...');
        runner.suite.emit('pre-require', global, 'global-mocha-context', runner);

        // test cases are collected via mocha global API;
        // no need to do anything with the test modules after loading them
        resolve(() => undefined);
        break;

      case 'exports':

        // The test cases are exported with this ui;
        // they need to be added after import.The following
        // function should run with each module export
        resolve(testModule => runner.suite.emit('require', testModule));
        break;

      default:

        // The "require" interface is not currently supported.
        reject(new Error(`"${opts.ui}" is not supported by this runner.`));
    }
  }).then(moduleHandler => {
    sh.echo(`Loading tests in ${modules.map(m => `"${m}"`).join(', ')}...`);

    return Promise.all(modules.map(m => loader.import(m).then(moduleHandler)));
  }).then(
    () => new Promise(
      (resolve, reject) => runner.run((failures) => {
        if (failures) {
          reject(failures);
        } else {
          resolve();
        }
      })
    )
  );
}

/**
 * Save coverage data to "./coverage/coverage.json".
 *
 * @param  {{coverage: string}} opts coverage options
 * @return {Object}                  the coverage object
 */
function saveCoverage(opts) {
  const coveragePath = path.join(opts.coverage, 'coverage.json');
  const coverage = systemIstanbul.remapCoverage();

  sh.echo(`Saving coverage data in ${coveragePath}...`);

  fs.writeFileSync(coveragePath, JSON.stringify(coverage));

  return coverage;
}

/**
 * Create lcov and text reports.
 *
 * @param  {Object}             coverage the coverage object.
 * @param  {{coverage: string}} opts     coverage options
 */
function createReport(coverage, opts) {
  const collector = new istanbul.Collector();
  const reporter = new istanbul.Reporter(null, opts.coverage);
  const sync = true;

  sh.echo('Creating reports...');

  collector.add(coverage);
  reporter.addAll(opts.reports);
  reporter.write(collector, sync, () => sh.echo('Reports created.'));
}

/**
 * Print error to stderr and exit process when shelljs "-e" option is set.
 *
 * @param  {Error}   err error to print.
 * @return {Promise<void, Error>}
 */
function rejectHandler(err) {
  process.stderr.write(`${err.stack || err}\n`);

  if (sh.config.fatal) {
    sh.exit(1);
  }

  return Promise.reject(err);
}

/**
 * Run mocha tests.
 *
 * bridge mocha and jspm.
 *
 * @param  {string|array}  modules modules defining mocha tests.
 * @param  {?{ui: string, config: function}} opts    mocha runner options.
 * @return {Promise<void, Error>}
 */
exports.mocha = function(modules, opts) {

  // convert undefined or a string to an array
  modules = [].concat(modules);

  // set defaults options
  opts = Object.assign({ui: 'bdd', config: noop}, opts);

  return loadJspmConfig(opts).then(
    loader => runTests(loader, modules, opts)
  ).catch(rejectHandler);
};

/**
 * Run mocha tests with coverage and create lcov and text reports.
 *
 * Bridge between mocha, instanbul and jspm.
 *
 * @param  {string|array} modules modules defining mocha tests.
 * @param  {?{ui: string, exclude: function, coverage: string, config: function}} opts mocha runner options.
 * @return {Promise<void, Error>}
 */
exports.instanbul = function(modules, opts) {

  // convert undefined or a string to an array
  modules = [].concat(modules);

  // set defaults options
  opts = Object.assign({
    ui: 'bdd',
    coverage: path.resolve('./coverage'),
    reports: ['lcov', 'text'],
    config: noop,

    exclude(baseURL) {
      const jspmPackages = `${baseURL}jspm_packages`;

      return address => (
        address.startsWith(jspmPackages) ||
        address.endsWith('specs.js') ||
        address.endsWith('.css') ||
        address.endsWith('.html')
      );
    }
  }, opts);

  return hookInstanbul(opts).then(
    loader => runTests(loader, modules, opts)
  ).then(
    () => saveCoverage(opts)
  ).then(
    coverage => createReport(coverage, opts)
  ).catch(rejectHandler);
};

/**
 * Archive a directive.
 *
 * @param  {string}              source path to directory to archive
 * @param  {string}              dest   path to save the zip archive
 * @param  {?{root: string}}     opts   option; "root" will default to the
 *                                      directory name
 * @return {Promise<void, Error>}
 */
exports.zip = function(source, dest, opts) {
  return new Promise((resolve, reject) => {
    const output = fs.createWriteStream(dest);
    const archive = archiver('zip');

    opts = opts || {};

    if (!opts.root) {
      opts.root = path.basename(path.resolve(source));
    }

    output.on('close', function() {
      resolve();
    });

    archive.on('error', function(err) {
      reject(err);
    });

    archive.pipe(output);
    archive.bulk([{
      expand: true,
      cwd: source,
      src: ['**'],
      dest: opts.root
    }]);
    archive.finalize();
  }).catch(rejectHandler);
};


text:
{% extends 'default/base.html' %}
{% block title %}Watcher manage{% endblock %}
{% block heading %}Watcher - New Job{% endblock %}
{% block content %}

 Choose template

{% if msg %}

  <button type="button" class="close" data-dismiss="alert">×</button>

{{result}}

  {{content}}

{% endif %}

{%for template in templates %}

  <button type="button" style="width:100%" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#template-{{template.id}}">
    {{template.name}}
  </button>
  <form method="post" action="#" enctype="multipart/form-data">

          <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

{{template.name}}

            <input type="hidden" value="{{template.id}}" name="template_id">

                Watcher
                <input type="text" class="form-control" placeholder="Watcher name" id="watcher_name" name="watcher_name">

          {%for param in template.params %}
            {% if param.type == "text" %}

                {{param.name}}
                <input type="text" class="form-control" value="{{param.default}}" id="p-{{param.id}}" name="{{param.name}}">

            {% elif param.type == "file" %}

              {{param.name}}
              <input type="file" id="p-{{param.id}}" name="{{param.name}}">

            <input type="hidden" name="filehidden-{{param.name}}" value="{{param.default}}">
            {% endif %}
          {% endfor %}

          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          <button type="submit" class="btn btn-primary">Create</button>

  </form>

{% endfor %}
{% endblock %}


text:
class CreateFoos < ActiveRecord::Migration
  def change
    create_table :foos do |t|
      t.geometry :bar, spatial_type: 'LINESTRING', srid: 423
      t.geography :car, spatial_type: 'LINESTRING'

      t.timestamps
    end
  end
end


text:
.PHONY: all clean

# The base SDK directory.
SDK_ROOT=../../..

# Sources root directory
SRC_ROOT=..

# Lib Name
EXE_NAME=crc

USE_LIBS=driverlib

#for use full libc (for float printing), use `full`
#default is `nano`
LIBC_TYPE=nano

# Sources
SOURCES=crc_userinput.c main.c pinmux.c uart_if.c startup_gcc.c

# make all targets by vars defined here
include $(SDK_ROOT)/example/common/gcc/common.make


text:
import React from 'react';
import { NavLink } from 'react-router-dom';

const NavItem = ({ sub, toggleCollapse }) =>  (
  <button onClick={() => {
    toggleCollapse();
  }}>
    <NavLink
      to={sub.url}
      style={{display: 'block', height: '100%', textDecoration: 'none'}}
    >
      {sub.display_name}
    </NavLink>
  </button>
)

export default NavItem;


text:
#ident "@(#)/usr/src/head/storclass.h	3.1.1.1 6/1/90 07:33:17 - (c) Copyright 1988, 1989, 1990 Amdahl Corporation"

/*
 *   STORAGE CLASSES
 */

#define  C_EFCN          -1    /* physical end of function */
#define  C_NULL          0
#define  C_AUTO          1     /* automatic variable */
#define  C_EXT           2     /* external symbol */
#define  C_STAT          3     /* static */
#define  C_REG           4     /* register variable */
#define  C_EXTDEF        5     /* external definition */
#define  C_LABEL         6     /* label */
#define  C_ULABEL        7     /* undefined label */
#define  C_MOS           8     /* member of structure */
#define  C_ARG           9     /* function argument */
#define  C_STRTAG        10    /* structure tag */
#define  C_MOU           11    /* member of union */
#define  C_UNTAG         12    /* union tag */
#define  C_TPDEF         13    /* type definition */
#define C_USTATIC	 14    /* undefined static */
#define  C_ENTAG         15    /* enumeration tag */
#define  C_MOE           16    /* member of enumeration */
#define  C_REGPARM	 17    /* register parameter */
#define  C_FIELD         18    /* bit field */
#define  C_BLOCK         100   /* ".bb" or ".eb" */
#define  C_FCN           101   /* ".bf" or ".ef" */
#define  C_EOS           102   /* end of structure */
#define  C_FILE          103   /* file name */

	/*
	 * The following storage class is a "dummy" used only by STS
	 * for line number entries reformatted as symbol table entries
	 */

#define  C_LINE		 104
#define  C_ALIAS	 105   /* duplicate tag */
#define  C_HIDDEN	 106   /* special storage class for external */
			       /* symbols in dmert public libraries  */


text:
<?xml version='1.0' encoding='utf-8' standalone='no'?>
<sbml xmlns="http://www.sbml.org/sbml/level3/version1/core"
      groups:required="false"
      level="3"
      sboTerm="SBO:0000624"
      version="1"
      xmlns:groups="http://www.sbml.org/sbml/level3/version1/groups/version1">
  <model fbc:strict="true" id="tiny_invalid"
         metaid="tiny_invalid" name="This is a tiny invalid test model">
  </model>
</sbml>


text:
/*
 * uuids.c
 *
 *  Created on: Mar 17, 2015
 *      Author: tim
 */

#include <ble.h>
#include <app_error.h>

#include "mesh/mesh.h"

#include "uuids.h"

uint16_t primary_service_handle;

void uuids_init(void)
{
  static const ble_uuid128_t base_uuid = { { UUIDS_BASE_UUID } };
  uint32_t err_code;
  uint8_t uuids_type;

  err_code = sd_ble_uuid_vs_add(&base_uuid, &uuids_type);
  APP_ERROR_CHECK(err_code);
  // If the following fails, change UUIDS_BASE_TYPE so it doesn't. The value remains
  // constant unless we add another uuid earlier in the code. This allows us to use a
  // known constant when creating UUIDs elsewhere, and to make them constant also.
  if (uuids_type != UUIDS_BASE_TYPE)
  {
    APP_ERROR_CHECK(NRF_ERROR_INTERNAL);
  }

  // Create the primary service
  static const ble_uuid_t service_uuid =
  {
      .type = UUIDS_BASE_TYPE,
      .uuid = MESH_SERVICE_UUID
  };
  err_code = sd_ble_gatts_service_add(BLE_GATTS_SRVC_TYPE_PRIMARY, &service_uuid, &primary_service_handle);
  APP_ERROR_CHECK(err_code);
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>My AngularJS App</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" type="text/css" href="bower_components/bootstrap/dist/css/bootstrap.min.css" />
  <link rel="stylesheet" href="bower_components/html5-boilerplate/dist/css/normalize.css">
  <link rel="stylesheet" href="bower_components/html5-boilerplate/dist/css/main.css">
  <link rel="stylesheet" href="assets/css/style.css">
  <link rel="stylesheet" href="bower_components/font-awesome/css/font-awesome.min.css">

  <lol-header></lol-header>
  <ng-view></ng-view>
  <lol-footer></lol-footer>


text:
if defined?(ChefSpec)
  ChefSpec.define_matcher :jenkins_command
  def execute_jenkins_command(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_command,
      :execute,
      resource_name)
  end

  ChefSpec.define_matcher :jenkins_credentials
  def create_jenkins_credentials(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_credentials,
      :create,
      resource_name)
  end

  def delete_jenkins_credentials(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_credentials,
      :delete,
      resource_name)
  end

  ChefSpec.define_matcher :jenkins_password_credentials
  def create_jenkins_password_credentials(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_password_credentials,
      :create,
      resource_name)
  end

  def delete_jenkins_password_credentials(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_password_credentials,
      :delete,
      resource_name)
  end

  ChefSpec.define_matcher :jenkins_private_key_credentials
  def create_jenkins_private_key_credentials(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_private_key_credentials,
      :create,
      resource_name)
  end

  def delete_jenkins_private_key_credentials(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_private_key_credentials,
      :delete,
      resource_name)
  end

  ChefSpec.define_matcher :jenkins_secret_text_credentials
  def create_jenkins_secret_text_credentials(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_secret_text_credentials,
      :create,
      resource_name)
  end

  def delete_jenkins_secret_text_credentials(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_secret_text_credentials,
      :delete,
      resource_name)
  end

  ChefSpec.define_matcher :jenkins_job
  def create_jenkins_job(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_job,
      :create,
      resource_name)
  end

  def delete_jenkins_job(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_job,
      :delete,
      resource_name)
  end

  def disable_jenkins_job(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_job,
      :disable,
      resource_name)
  end

  def enable_jenkins_job(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_job,
      :enable,
      resource_name)
  end

  ChefSpec.define_matcher :jenkins_plugin
  def install_jenkins_plugin(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_plugin,
      :install,
      resource_name)
  end

  def uninstall_jenkins_plugin(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_plugin,
      :uninstall,
      resource_name)
  end

  def enable_jenkins_plugin(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_plugin,
      :enable,
      resource_name)
  end

  def disable_jenkins_plugin(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_plugin,
      :disable,
      resource_name)
  end

  ChefSpec.define_matcher :jenkins_script
  def execute_jenkins_script(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_script,
      :execute,
      resource_name)
  end

  ChefSpec.define_matcher :jenkins_slave
  def create_jenkins_slave(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_slave,
      :create,
      resource_name)
  end

  def delete_jenkins_slave(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_slave,
      :delete,
      resource_name)
  end

  def connect_jenkins_slave(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_slave,
      :connect,
      resource_name)
  end

  def disconnect_jenkins_slave(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_slave,
      :disconnect,
      resource_name)
  end

  def online_jenkins_slave(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_slave,
      :online,
      resource_name)
  end

  def offline_jenkins_slave(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_slave,
      :offline,
      resource_name)
  end

  ChefSpec.define_matcher :jenkins_jnlp_slave
  def create_jenkins_jnlp_slave(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_jnlp_slave,
      :create,
      resource_name)
  end

  def delete_jenkins_jnlp_slave(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_jnlp_slave,
      :delete,
      resource_name)
  end

  def connect_jenkins_jnlp_slave(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_jnlp_slave,
      :connect,
      resource_name)
  end

  def disconnect_jenkins_jnlp_slave(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_jnlp_slave,
      :disconnect,
      resource_name)
  end

  def online_jenkins_jnlp_slave(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_jnlp_slave,
      :online,
      resource_name)
  end

  def offline_jenkins_jnlp_slave(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_jnlp_slave,
      :offline,
      resource_name)
  end

  ChefSpec.define_matcher :jenkins_ssh_slave
  def create_jenkins_ssh_slave(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_ssh_slave,
      :create,
      resource_name)
  end

  def delete_jenkins_ssh_slave(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_ssh_slave,
      :delete,
      resource_name)
  end

  def connect_jenkins_ssh_slave(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_ssh_slave,
      :connect,
      resource_name)
  end

  def disconnect_jenkins_ssh_slave(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_ssh_slave,
      :disconnect,
      resource_name)
  end

  def online_jenkins_ssh_slave(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_ssh_slave,
      :online,
      resource_name)
  end

  def offline_jenkins_ssh_slave(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_ssh_slave,
      :offline,
      resource_name)
  end

  ChefSpec.define_matcher :jenkins_windows_slave
  def create_jenkins_windows_slave(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_windows_slave,
      :create,
      resource_name)
  end

  def delete_jenkins_windows_slave(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_windows_slave,
      :delete,
      resource_name)
  end

  def connect_jenkins_windows_slave(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_windows_slave,
      :connect,
      resource_name)
  end

  def disconnect_jenkins_windows_slave(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_windows_slave,
      :disconnect,
      resource_name)
  end

  def online_jenkins_windows_slave(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_windows_slave,
      :online,
      resource_name)
  end

  def offline_jenkins_windows_slave(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_windows_slave,
      :offline,
      resource_name)
  end

  ChefSpec.define_matcher :jenkins_user
  def create_jenkins_user(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_user,
      :create,
      resource_name)
  end

  def delete_jenkins_user(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(
      :jenkins_user,
      :delete,
      resource_name)
  end
end


text:
package net.interdon.domaincheck.parsers;

import net.interdon.domaincheck.containers.Domain;

import java.util.regex.Pattern;

public class OrgUaParser extends AbstractParser {
    private static final String EXPIRATION_DATE_REGEXP = "\\bexpires\\b:\\s*\\d{4}-\\d{2}-\\d{2}"; //matches "expires: YYYY-MM-DD"
    private static final String MODIFIED_DATE_REGEXP = "\\bmodified\\b:\\s*\\d{4}-\\d{2}-\\d{2}";
    private static final String CREATED_DATE_REGEXP = "\\bcreated\\b:\\s*\\d{4}-\\d{2}-\\d{2}";
    private static final Pattern expirationDatePattern = Pattern.compile(EXPIRATION_DATE_REGEXP);
    private static final Pattern modifiedDatePattern = Pattern.compile(MODIFIED_DATE_REGEXP);
    private static final Pattern createdDatePattern = Pattern.compile(CREATED_DATE_REGEXP);

    @Override
    public void parse(Domain sourceDomain) {
        if(sourceDomain.getWhoisResponce().isEmpty()) {
            return;
        }
        String value = getFieldValue(getMatchField(expirationDatePattern, sourceDomain.getWhoisResponce()), ":");
        if(!value.isEmpty()) {
            sourceDomain.setExpirationDate(value);
        }
        value = getFieldValue(getMatchField(modifiedDatePattern, sourceDomain.getWhoisResponce()), ":");
        if(!value.isEmpty()) {
            sourceDomain.setDateLastModifyed(value);
        }
        value = getFieldValue(getMatchField(createdDatePattern, sourceDomain.getWhoisResponce()), ":");
        if(!value.isEmpty()) {
            sourceDomain.setDateCreated(value);
        }

    }
}


text:
'use strict';

const path = require('path');
const assert = require('assert');
const uuid = require('uuid');
const cwd = path.join(__dirname, '..');
const {exec} = require('child_process');

// Use unique id to avoid conflicts between concurrent test runs
const entryGroupId = `fileset_entry_group_${uuid.v4().substr(0, 8)}`;
const entryId = `fileset_entry_id_${uuid.v4().substr(0, 8)}`;
const location = 'us-central1';

const {DataCatalogClient} = require('@google-cloud/datacatalog').v1beta1;
const datacatalog = new DataCatalogClient();

let projectId;
before(async () => {
  const client = new DataCatalogClient();
  projectId = await client.getProjectId();
});

describe('createFilesetEntry', () => {
  before(done => {
    // Must create entryGroup before creating entry
    exec(`node createEntryGroup.js ${projectId} ${entryGroupId}`, {cwd}, done);
  });

  it('should create a fileset entry', done => {
    const expectedLinkedResource = `//datacatalog.googleapis.com/projects/${projectId}/locations/${location}/entryGroups/${entryGroupId}/entries/${entryId}`;
    exec(
      `node createFilesetEntry.js ${projectId} ${entryGroupId} ${entryId}`,
      {cwd},
      (err, stdout) => {
        assert.ok(stdout.includes(expectedLinkedResource));
        done();
      }
    );
  });

  after(async () => {
    const entryPath = datacatalog.entryPath(
      projectId,
      location,
      entryGroupId,
      entryId
    );
    await datacatalog.deleteEntry({name: entryPath});
    const entryGroupPath = datacatalog.entryGroupPath(
      projectId,
      location,
      entryGroupId
    );
    await datacatalog.deleteEntryGroup({name: entryGroupPath});
  });
});


text:
package org.h2.dev.fs;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.channels.FileChannel;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.h2.command.dml.BackupCommand;
import org.h2.engine.Constants;
import org.h2.engine.SysProperties;
import org.h2.message.DbException;
import org.h2.store.fs.FileUtils;
import org.h2.util.IOUtils;
import org.h2.util.New;
import org.h2.util.StringUtils;
import org.h2.util.Tool;

/**
 * A shell tool that allows to list and manipulate files.
 */
public class FileShell extends Tool {

    private boolean verbose;
    private BufferedReader reader;
    private PrintStream err = System.err;
    private InputStream in = System.in;
    private String currentWorkingDirectory;

    /**
     * Options are case sensitive. Supported options are:
     *

     *
[-help] or [-?]
     * Print the list of options

     *
[-verbose]
     * Print stack traces

     *
[-run ...]
     * Execute the given commands and exit

     *

     * Multiple commands may be executed if separated by ;
     * @h2.resource
     *
     * @param args the command line arguments
     */
    public static void main(String... args) throws SQLException {
        new FileShell().runTool(args);
    }

    /**
     * Sets the standard error stream.
     *
     * @param err the new standard error stream
     */
    public void setErr(PrintStream err) {
        this.err = err;
    }

    /**
     * Redirects the standard input. By default, System.in is used.
     *
     * @param in the input stream to use
     */
    public void setIn(InputStream in) {
        this.in = in;
    }

    /**
     * Redirects the standard input. By default, System.in is used.
     *
     * @param reader the input stream reader to use
     */
    public void setInReader(BufferedReader reader) {
        this.reader = reader;
    }

    /**
     * Run the shell tool with the given command line settings.
     *
     * @param args the command line settings
     */
    @Override
    public void runTool(String... args) throws SQLException {
        try {
            currentWorkingDirectory = new File(".").getCanonicalPath();
        } catch (IOException e) {
            throw DbException.convertIOException(e, "cwd");
        }
        for (int i = 0; args != null && i < args.length; i++) {
            String arg = args[i];
            if (arg.equals("-run")) {
                try {
                    execute(args[++i]);
                } catch (Exception e) {
                    throw DbException.convert(e);
                }
            } else if (arg.equals("-verbose")) {
                verbose = true;
            } else if (arg.equals("-help") || arg.equals("-?")) {
                showUsage();
                return;
            } else {
                showUsageAndThrowUnsupportedOption(arg);
            }
        }
        promptLoop();
    }

    private void promptLoop() {
        println("");
        println("Welcome to H2 File Shell " + Constants.getFullVersion());
        println("Exit with Ctrl+C");
        showHelp();
        if (reader == null) {
            reader = new BufferedReader(new InputStreamReader(in));
        }
        println(FileUtils.toRealPath(currentWorkingDirectory));
        while (true) {
            try {
                print("> ");
                String line = readLine();
                if (line == null) {
                    break;
                }
                line = line.trim();
                if (line.length() == 0) {
                    continue;
                }
                try {
                    execute(line);
                } catch (Exception e) {
                    error(e);
                }
            } catch (Exception e) {
                error(e);
                break;
            }
        }
    }

    private void execute(String line) throws IOException {
        String[] commands = StringUtils.arraySplit(line, ';', true);
        for (String command : commands) {
            String[] list = StringUtils.arraySplit(command, ' ', true);
            if (!execute(list)) {
                break;
            }
        }
    }

    private boolean execute(String[] list) throws IOException {
        // TODO unit tests for everything (multiple commands, errors, ...)
        // TODO less (support large files)
        // TODO hex dump
        int i = 0;
        String c = list[i++];
        if ("exit".equals(c) || "quit".equals(c)) {
            end(list, i);
            return false;
        } else if ("help".equals(c) || "?".equals(c)) {
            showHelp();
            end(list, i);
        } else if ("cat".equals(c)) {
            String file = getFile(list[i++]);
            end(list, i);
            cat(file, Long.MAX_VALUE);
        } else if ("cd".equals(c)) {
            String dir = getFile(list[i++]);
            end(list, i);
            if (FileUtils.isDirectory(dir)) {
                currentWorkingDirectory = dir;
                println(dir);
            } else {
                println("Not a directory: " + dir);
            }
        } else if ("chmod".equals(c)) {
            String mode = list[i++];
            String file = getFile(list[i++]);
            end(list, i);
            if ("-w".equals(mode)) {
                boolean success = FileUtils.setReadOnly(file);
                println(success ? "Success" : "Failed");
            } else {
                println("Unsupported mode: " + mode);
            }
        } else if ("cp".equals(c)) {
            String source = getFile(list[i++]);
            String target = getFile(list[i++]);
            end(list, i);
            IOUtils.copyFiles(source, target);
        } else if ("head".equals(c)) {
            String file = getFile(list[i++]);
            end(list, i);
            cat(file, 1024);
        } else if ("ls".equals(c)) {
            String dir = currentWorkingDirectory;
            if (i < list.length) {
                dir = getFile(list[i++]);
            }
            end(list, i);
            println(dir);
            for (String file : FileUtils.newDirectoryStream(dir)) {
                StringBuilder buff = new StringBuilder();
                buff.append(FileUtils.isDirectory(file) ? "d" : "-");
                buff.append(FileUtils.canWrite(file) ? "rw" : "r-");
                buff.append(' ');
                buff.append(String.format("%10d", FileUtils.size(file)));
                buff.append(' ');
                long lastMod = FileUtils.lastModified(file);
                buff.append(new Timestamp(lastMod).toString());
                buff.append(' ');
                buff.append(FileUtils.getName(file));
                println(buff.toString());
            }
        } else if ("mkdir".equals(c)) {
            String dir = getFile(list[i++]);
            end(list, i);
            FileUtils.createDirectories(dir);
        } else if ("mv".equals(c)) {
            String source = getFile(list[i++]);
            String target = getFile(list[i++]);
            end(list, i);
            FileUtils.move(source, target);
        } else if ("pwd".equals(c)) {
            end(list, i);
            println(FileUtils.toRealPath(currentWorkingDirectory));
        } else if ("rm".equals(c)) {
            if ("-r".equals(list[i])) {
                i++;
                String dir = getFile(list[i++]);
                end(list, i);
                FileUtils.deleteRecursive(dir, true);
            } else if ("-rf".equals(list[i])) {
                i++;
                String dir = getFile(list[i++]);
                end(list, i);
                FileUtils.deleteRecursive(dir, false);
            } else {
                String file = getFile(list[i++]);
                end(list, i);
                FileUtils.delete(file);
            }
        } else if ("touch".equals(c)) {
            String file = getFile(list[i++]);
            end(list, i);
            truncate(file, FileUtils.size(file));
        } else if ("truncate".equals(c)) {
            if ("-s".equals(list[i])) {
                i++;
                long length = Long.decode(list[i++]);
                String file = getFile(list[i++]);
                end(list, i);
                truncate(file, length);
            } else {
                println("Unsupported option");
            }
        } else if ("unzip".equals(c)) {
            String file = getFile(list[i++]);
            end(list, i);
            unzip(file, currentWorkingDirectory);
        } else if ("zip".equals(c)) {
            boolean recursive = false;
            if ("-r".equals(list[i])) {
                i++;
                recursive = true;
            }
            String target = getFile(list[i++]);
            ArrayList<String> source = New.arrayList();
            readFileList(list, i, source, recursive);
            zip(target, currentWorkingDirectory, source);
        }
        return true;
    }

    private static void end(String[] list, int index) throws IOException {
        if (list.length != index) {
            throw new IOException("End of command expected, got: " + list[index]);
        }
    }

    private void cat(String fileName, long length) {
        if (!FileUtils.exists(fileName)) {
            print("No such file: " + fileName);
        }
        if (FileUtils.isDirectory(fileName)) {
            print("Is a directory: " + fileName);
        }
        InputStream inFile = null;
        try {
            inFile = FileUtils.newInputStream(fileName);
            IOUtils.copy(inFile, out, length);
        } catch (IOException e) {
            error(e);
        } finally {
            IOUtils.closeSilently(inFile);
        }
        println("");
    }

    private void truncate(String fileName, long length) {
        FileChannel f = null;
        try {
            f = FileUtils.open(fileName, "rw");
            f.truncate(length);
        } catch (IOException e) {
            error(e);
        } finally {
            try {
                f.close();
            } catch (IOException e) {
                error(e);
            }
        }
    }

    private void error(Exception e) {
        println("Exception: " + e.getMessage());
        if (verbose) {
            e.printStackTrace(err);
        }
    }

    private static void zip(String zipFileName, String base,
            ArrayList<String> source) {
        FileUtils.delete(zipFileName);
        OutputStream fileOut = null;
        try {
            fileOut = FileUtils.newOutputStream(zipFileName, false);
            ZipOutputStream zipOut = new ZipOutputStream(fileOut);
            for (String fileName : source) {
                String f = FileUtils.toRealPath(fileName);
                if (!f.startsWith(base)) {
                    DbException.throwInternalError(f + " does not start with " + base);
                }
                if (f.endsWith(zipFileName)) {
                    continue;
                }
                if (FileUtils.isDirectory(fileName)) {
                    continue;
                }
                f = f.substring(base.length());
                f = BackupCommand.correctFileName(f);
                ZipEntry entry = new ZipEntry(f);
                zipOut.putNextEntry(entry);
                InputStream in = null;
                try {
                    in = FileUtils.newInputStream(fileName);
                    IOUtils.copyAndCloseInput(in, zipOut);
                } catch (FileNotFoundException e) {
                    // the file could have been deleted in the meantime
                    // ignore this (in this case an empty file is created)
                } finally {
                    IOUtils.closeSilently(in);
                }
                zipOut.closeEntry();
            }
            zipOut.closeEntry();
            zipOut.close();
        } catch (IOException e) {
            throw DbException.convertIOException(e, zipFileName);
        } finally {
            IOUtils.closeSilently(fileOut);
        }
    }

    private void unzip(String zipFileName, String targetDir) {
        InputStream inFile = null;
        try {
            inFile = FileUtils.newInputStream(zipFileName);
            ZipInputStream zipIn = new ZipInputStream(inFile);
            while (true) {
                ZipEntry entry = zipIn.getNextEntry();
                if (entry == null) {
                    break;
                }
                String fileName = entry.getName();
                // restoring windows backups on linux and vice versa
                fileName = fileName.replace('\\',
                        SysProperties.FILE_SEPARATOR.charAt(0));
                fileName = fileName.replace('/',
                        SysProperties.FILE_SEPARATOR.charAt(0));
                if (fileName.startsWith(SysProperties.FILE_SEPARATOR)) {
                    fileName = fileName.substring(1);
                }
                OutputStream o = null;
                try {
                    o = FileUtils.newOutputStream(targetDir
                            + SysProperties.FILE_SEPARATOR + fileName, false);
                    IOUtils.copy(zipIn, o);
                    o.close();
                } finally {
                    IOUtils.closeSilently(o);
                }
                zipIn.closeEntry();
            }
            zipIn.closeEntry();
            zipIn.close();
        } catch (IOException e) {
            error(e);
        } finally {
            IOUtils.closeSilently(inFile);
        }
    }

    private int readFileList(String[] list, int i, ArrayList<String> target,
            boolean recursive) throws IOException {
        while (i < list.length) {
            String c = list[i++];
            if (";".equals(c)) {
                break;
            }
            c = getFile(c);
            if (!FileUtils.exists(c)) {
                throw new IOException("File not found: " + c);
            }
            if (recursive) {
                addFilesRecursive(c, target);
            } else {
                target.add(c);
            }
        }
        return i;
    }

    private void addFilesRecursive(String f, ArrayList<String> target) {
        if (FileUtils.isDirectory(f)) {
            for (String c : FileUtils.newDirectoryStream(f)) {
                addFilesRecursive(c, target);
            }
        } else {
            target.add(getFile(f));
        }
    }

    private String getFile(String f) {
        if (FileUtils.isAbsolute(f)) {
            return f;
        }
        String unwrapped = FileUtils.unwrap(f);
        String prefix = f.substring(0, f.length() - unwrapped.length());
        f = prefix + currentWorkingDirectory + SysProperties.FILE_SEPARATOR + unwrapped;
        return FileUtils.toRealPath(f);
    }

    private void showHelp() {
        println("Commands are case sensitive");
        println("? or help                  " +
                "Display this help");
        println("cat <file>                 " +
                "Print the contents of the file");
        println("cd <dir>                   " +
                "Change the directory");
        println("chmod -w <file>            " +
                "Make the file read-only");
        println("cp <source> <target>       " +
                "Copy a file");
        println("head <file>                " +
                "Print the first few lines of the contents");
        println("ls [<dir>]                 " +
                "Print the directory contents");
        println("mkdir <dir>                " +
                "Create a directory (including parent directories)");
        println("mv <source> <target>       " +
                "Rename a file or directory");
        println("pwd                        " +
                "Print the current working directory");
        println("rm <file>                  " +
                "Remove a file");
        println("rm -r <dir>                " +
                "Remove a directory, recursively");
        println("rm -rf <dir>               " +
                "Remove a directory, recursively; force");
        println("touch <file>               " +
                "Update the last modified date (creates the file)");
        println("truncate -s <size> <file>  " +
                "Set the file length");
        println("unzip <zip>                " +
                "Extract all files from the zip file");
        println("zip [-r] <zip> <files..>   " +
                "Create a zip file (-r to recurse directories)");
        println("exit                       Exit");
        println("");
    }

    private String readLine() throws IOException {
        String line = reader.readLine();
        if (line == null) {
            throw new IOException("Aborted");
        }
        return line;
    }

    private void print(String s) {
        out.print(s);
        out.flush();
    }

    private void println(String s) {
        out.println(s);
        out.flush();
    }

}


text:
using System;
using System.Net.Http;
using System.Threading.Tasks;
using UltimateTeam.Toolkit.Constants;
using UltimateTeam.Toolkit.Extensions;
using UltimateTeam.Toolkit.Models;

namespace UltimateTeam.Toolkit.Requests
{
    internal class TradePileRequest : FutRequestBase, IFutRequest<AuctionResponse>
    {
        public async Task<AuctionResponse> PerformRequestAsync()
        {
            var uriString = Resources.FutHome + Resources.TradePile;

            if (AppVersion == AppVersion.WebApp)
            {
                AddCommonHeaders(HttpMethod.Get);
            }
            else
            {
                AddCommonMobileHeaders();
                uriString += $"?_={DateTime.Now.ToUnixTime()}";
            }

            var tradePileResponseMessage = await HttpClient
                .GetAsync(string.Format(uriString))
                .ConfigureAwait(false);

            return await DeserializeAsync<AuctionResponse>(tradePileResponseMessage);
        }
    }
}


text:
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.HashSet;

public class Server {
    public enum Code {
        ERROR(-1), ALL_OK(0), PRINT(1), GET_FILE(2), REMOVE_FILE(3), ADD_FILE(4), EXIT(5);

        private final int value;

        Code(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }
    }

    private static final String SERVER_FILES_DIR = "./ServerFiles";
    private final ArrayList<File> serverFiles = new ArrayList<File>();
    // HashSet allows O(1) access to check if the set already contains a file before adding it.
    private final HashSet<Integer> fileHashes = new HashSet<Integer>();
    private ServerSocket socket;

    public Server(int port) {
        File folder = new File(SERVER_FILES_DIR);
        if (folder.exists())
            initializeFiles(folder.listFiles());
        else {
            System.err.println("'ServerFiles' directory not found.");
            System.err.println("The server uses the 'ServerFiles' directory to initialize files.");
            System.err.println("Please ensure there is a directory named 'ServerFiles' in the " +
                    "same directory from which you are running the server.");
            System.exit(-1);
        }

        try {
            socket = new ServerSocket(port);
        } catch (Exception e) {
            System.err.println(e.getMessage());
            System.exit(-1);
        }
    }

    // Adds all files in the server serverFiles directory including subdirectory files.
    private void initializeFiles(File[] files) {
        for (File file : files)
            if (file.isDirectory())
                initializeFiles(file.listFiles());
            else
                add(file);
    }

    public synchronized void addFile(File file) {
        String fileName = file.getName();

        if (!fileHashes.contains(file.hashCode())) {
            add(file);
            System.out.println(fileName + " added to the server.");
        } else
            System.out.println(fileName + " is already on the server.");
    }

    private void add(File file) {
        serverFiles.add(file);
        fileHashes.add(file.hashCode());
    }

    public void run() {
        try {
            spawnClientWorkersUponClientConnection();
        } catch (Exception e) {
            System.err.println(e.getMessage());
            System.exit(-1);
        }
    }

    /*
    The socket accept method blocks until a client connections. The server runs until
    the user sends the Control-C "SIGINT" program interrupt signal.
     */
    private void spawnClientWorkersUponClientConnection() throws IOException {
        System.out.println("Server running on " + socket.getLocalPort() + ".");
        System.out.println("Press Control-C to stop the server.");

        while (true) {
            Thread t = new Thread(new ClientWorker(socket.accept(), this));
            t.start();
        }
    }

    public synchronized String getServerFileList() {
        String serverFileList = "";

        for (int i = 0; i < serverFiles.size(); i++)
            serverFileList += (i + 1) + ". " + serverFiles.get(i).getName() + "\n";

        return serverFileList;
    }

    public synchronized File getFile(int fileNumber) {
        if (isInBounds(fileNumber))
            return serverFiles.get(fileNumber - 1);
        else
            return null;
    }

    public synchronized boolean tryRemoveFile(int fileNumber) {
        if (isInBounds(fileNumber)) {
            File file = serverFiles.remove(fileNumber - 1);
            fileHashes.remove(file.hashCode());
            return true;
        }
        return false;
    }

    private boolean isInBounds(int fileNumber) {
        return fileNumber > 0 && fileNumber <= serverFiles.size();
    }

    public static void main(String args[]) {
        if (args.length != 1) {
            System.err.println("Please provide the port number as an argument.");
            System.err.println("Example: java Server 5000");
            System.exit(1);
        }
        int port = Integer.valueOf(args[0]);
        Server s = new Server(port);
        s.run();
    }
}

class InvalidServerCodeException extends RuntimeException {
    public InvalidServerCodeException(String message) {
        super(message);
    }
}


text:
<!DOCTYPE html>

<title>CSS 2.1 Test Suite: Test for inline-table</title>
<link rel="author" title="L. David Baron" href="http://dbaron.org/" />
<link rel="author" title="Mozilla Corporation" href="http://mozilla.com/" />
<link rel="help" href="http://www.w3.org/TR/CSS21/tables.html#table-display" />
<meta name="assert" content="it is a rectangular block that participates in an inline formatting context)." />
<link rel="help" href="http://www.w3.org/TR/CSS21/visudet.html#leading" />
<meta name="assert" content="The baseline of an 'inline-table' is the baseline of the first row of the table." />
<meta name="flags" content="" />

abc


text:
class ChangeNameOfMemEvents < ActiveRecord::Migration
  def change
    rename_table :mem_events, :memevents
  end
end


text:
#ifndef SHIPSBATTLE_SUBSYSTEMS_PROJECTILEWEAPON_H
#define SHIPSBATTLE_SUBSYSTEMS_PROJECTILEWEAPON_H

#include <shipsbattle/components/subsystems/weapon.h>
#include <shipsbattle/objects/projectilemodel.h>

namespace shipsbattle {
namespace components {
namespace subsystems {

class ProjectileWeapon : public Weapon {
public:
    ProjectileWeapon(const std::string& name);

    bool Fire(const objects::Target& target) override;

    /** Gets the projectile model this weapon uses to fire. */
    objects::ProjectileModel projectile() const { return projectile_; }
    void set_projectile(const objects::ProjectileModel& model) { projectile_ = model; }
    /** Gets the speed at which the projectile is launched from this weapon. */
    double launching_speed() const { return launching_speed_; }
    void set_launching_speed(double speed) { launching_speed_ = speed; }

protected:
    objects::ProjectileModel projectile_;
    double launching_speed_;
};

} // namespace subsystems
} // namespace components
} // namespace shipsbattle

#endif // SHIPSBATTLE_SUBSYSTEMS_PROJECTILEWEAPON_H


text:
package com.owera.xaps.tr069.xml;

import java.util.ArrayList;

public class ParameterList {

	private ArrayList<ParameterValueStruct> params;
	private ArrayList<ParameterInfoStruct> info;
	private ArrayList<ParameterAttributeStruct> attributes;

	public ParameterList() {
		this.params = new ArrayList<ParameterValueStruct>();
		this.info = new ArrayList<ParameterInfoStruct>();
		this.attributes = new ArrayList<ParameterAttributeStruct>();
	}

	public void addParameterValueStruct(ParameterValueStruct param) {
		this.params.add(param);
	}

	public void addParameterInfoStruct(ParameterInfoStruct param) {
		this.info.add(param);
	}

	public void addParameterAttributeStruct(ParameterAttributeStruct attr) {
		this.attributes.add(attr);
	}

	public ArrayList<ParameterValueStruct> getParameterValueList() {
		return this.params;
	}

	public ArrayList<ParameterInfoStruct> getParameterInfoList() {
		return this.info;
	}

	public ArrayList<ParameterAttributeStruct> getParameterAttributeList() {
		return this.attributes;
	}

	public String getParameterValueListKeyValue(String key) {
		for (ParameterValueStruct struct : this.params) {
			if (struct.getName().equals(key)) {
				return struct.getValue();
			}
		}

		return null;
	}

	public void addOrChangeParameterValueStruct(String key, String value, String type) {
		boolean changed = false;
		for (ParameterValueStruct struct : this.params) {
			if (struct.getName().equals(key)) {
				struct.setValue(value);
				changed = true;
				break;
			}
		}
		if (!changed)
			this.params.add(new ParameterValueStruct(key, value, type));

	}

}


text:
package org.immutables.fixture;

import java.util.Collections;
import com.google.common.collect.*;
import org.immutables.value.Value;
import java.util.Arrays;

@Value.Immutable(singleton = true, prehash = true)
public interface ExtraCollection {
  @Value.Parameter
  Multiset<String> bag();

  @Value.Parameter
  Multimap<Integer, String> index();

  @Value.Parameter
  ListMultimap<Integer, String> indexList();

  @Value.Parameter
  SetMultimap<Integer, String> indexSet();

  @Value.Parameter
  BiMap<Integer, String> biMap();

  default void use() {
    ImmutableExtraCollection.of(
        ImmutableList.<String>of(),
        ImmutableMultimap.<Integer, String>of(),
        ImmutableMultimap.<Integer, String>of(),
        ImmutableMultimap.<Integer, String>of(),
        ImmutableBiMap.<Integer, String>of());
    ImmutableExtraCollection.of();
    ImmutableExtraCollection collection = ImmutableExtraCollection.builder()
        .addBag("2", "2")
        .putIndex(1, "2", "3", "4")
        .putAllIndex(1, Arrays.asList("2", "3", "4"))
        .putIndex(2, "5")
        .putIndexList(1, "")
        .putIndexSet(2, "2")
        .putAllIndexSet(2, Arrays.asList("3", "4"))
        .putBiMap(1, "a")
        .putBiMap(2, "b")
        .putAllBiMap(Collections.singletonMap(3, "c"))
        .build();

    collection.bag().count("2");
    collection.index().get(1);
    collection.indexList().get(1);
    collection.indexSet().get(2);
  }
}


text:
package dotty.tools.benchmarks

import org.openjdk.jmh.results.RunResult
import org.openjdk.jmh.runner.Runner
import org.openjdk.jmh.annotations._
import org.openjdk.jmh.results.format._
import org.openjdk.jmh.runner.options._
import java.util.concurrent.TimeUnit

import scala.io.Source

object Bench {
  def main(args: Array[String]): Unit = {
    if (args.contains("--help")) {
      printUsage()
      return
    }

    val (intArgs, args1) = args.span(x => try { x.toInt; true } catch { case _: Throwable => false } )

    def getIntArg(i: Int, default: Int): Int =
      if (intArgs.length > i) intArgs(i).toInt else default

    val warmup = getIntArg(0, 20)
    val iterations = getIntArg(1, 20)
    val forks = getIntArg(2, 1)

    if (args1.isEmpty) {
      println("Error: no benchmark was specified.")
      printUsage()
      return
    }

    var builder = new OptionsBuilder()
      .shouldFailOnError(true)
      .jvmArgs("-Xms2G", "-Xmx2G")
      .mode(Mode.AverageTime)
      .timeUnit(TimeUnit.NANOSECONDS)
      .warmupIterations(warmup)
      .warmupTime(TimeValue.milliseconds(750))
      .measurementIterations(iterations)
      .measurementTime(TimeValue.milliseconds(500))
      .forks(forks)
      .include(args1(0))

    if (args1.length > 1 && args1(1) != "--") {
      for ((param, values) <- paramsFromFile("inputs/" ++ args1(1)))
        builder = builder.param(param, values: _*)
    }

    if (args1.length > 2) {
      builder = builder.resultFormat(ResultFormatType.CSV).result(args1(2))
    }

    val runner = new Runner(builder.build)
    runner.run
  }

  def paramsFromFile(file: String): Array[(String, Array[String])] = {
    Source.fromFile(file).getLines.toArray.map { l =>
      val Array(param, values) = l split ':'
      (param, values split ',')
    }
  }

  def printUsage(): Unit = {
    println()
    println("Usage:")
    println()
    println("dotty-bench-run/jmh:run [<warmup>] [<iterations>] [<forks>] <regexp> [<input>|--] [<output>]")
    println()
    println("warmup: warmup iterations. defaults to 20.")
    println("iterations: benchmark iterations. defaults to 20.")
    println("forks: number of forks. defaults to 1.")
    println("regexp: regular expression that selects which benchmarks to run.")
    println("input: input vector file. each line should have format \'<paramName>: <comma-separated-values>\'")
    println("output: output file for the results of benchmarks.")
    println()
  }
}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=type.U642.html">

Redirecting to type.U642.html...


text:
<?php
/**
 * ExtReference class file
 */

namespace Graviton\DocumentBundle\Entity;

/**
 * Our internal MongoDbRef representation
 *
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
 * @license  https://opensource.org/licenses/MIT MIT License
 * @link     http://swisscom.ch
 */
class ExtReference implements \JsonSerializable
{
    /**
     * @var string Reference collection
     */
    private $ref;
    /**
     * @var string Document ID
     */
    private $id;

    /**
     * Create new extref
     *
     * @param string $ref Collection
     * @param string $id  ID
     * @return ExtReference
     */
    public static function create($ref, $id)
    {
        return (new ExtReference())->setRef($ref)->setId($id);
    }

    /**
     * Specify data which should be serialized to JSON
     *
     * @return mixed
     */
    public function jsonSerialize() : mixed
    {
        return ['$ref' => $this->ref, '$id' => $this->id];
    }

    /**
     * Get collection name
     *
     * @return string
     */
    public function getRef()
    {
        return $this->ref;
    }

    /**
     * Set collection name
     *
     * @param string $ref Collection
     * @return $this
     */
    public function setRef($ref)
    {
        $this->ref = $ref;
        return $this;
    }

    /**
     * Get document ID
     *
     * @return string
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set document ID
     *
     * @param string $id ID
     * @return $this
     */
    public function setId($id)
    {
        $this->id = $id;
        return $this;
    }
}


text:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\AdminController;
use App\User;

class ProfileController extends AdminController
{
  public function __construct(User $model)
  {
      $this->middleware('auth');
      $this->model = $model;
      $this->view = 'user.form';
  }
  public function index(){
      return view($this->view,[
        'model' => auth()->user(),
      ]);
  }
  public function store(Request $request){
      $inputs = $request->all();
      $model = $this->model->findOrFail($inputs['id']);
      try{
          if($inputs['password'] !== ''){
            $inputs['image'] = isset($inputs['image']) ? $this->upload_file($inputs,$model,$request,'image',''):$model->image;
            $inputs['password'] = bcrypt($inputs['password']);
            $model->update($inputs);
          }else{
            $inputs['image'] = isset($inputs['image']) ? $this->upload_file($inputs,$model,$request,'image',''):$model->image;
            $model->update(array_except($inputs, ['password']));
          }
          return redirect('profile')->with('success', 'Profil berhasil diubah.');
      }catch(\Exception $e){
          return redirect('profile')->with('error', $e->getMessage());
      }
  }
}