text:
#include <stdio.h>
#include <curl/curl.h>

/* This is a simple example showing how to retrieve mail using libcurl's POP3
 * capabilities. It builds on the pop3-retr.c example to demonstrate how to use
 * libcurl's multi interface.
 *
 * Note that this example requires libcurl 7.20.0 or above.
 */

#define MULTI_PERFORM_HANG_TIMEOUT 60 * 1000

static struct timeval tvnow(void)
{
  struct timeval now;

  /* time() returns the value of time in seconds since the epoch */
  now.tv_sec = (long)time(NULL);
  now.tv_usec = 0;

  return now;
}

static long tvdiff(struct timeval newer, struct timeval older)
{
  return (newer.tv_sec - older.tv_sec) * 1000 +
    (newer.tv_usec - older.tv_usec) / 1000;
}

int main(void)
{
  CURL *curl;
  CURLM *mcurl;
  int still_running = 1;
  struct timeval mp_start;

  curl_global_init(CURL_GLOBAL_DEFAULT);

  curl = curl_easy_init();
  if(!curl)
    return 1;

  mcurl = curl_multi_init();
  if(!mcurl)
    return 2;

  /* Set username and password */
  curl_easy_setopt(curl, CURLOPT_USERNAME, "user");
  curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret");

  /* This will retreive message 1 from the user's mailbox */
  curl_easy_setopt(curl, CURLOPT_URL, "pop3://pop.example.com/1");

  /* Tell the multi stack about our easy handle */
  curl_multi_add_handle(mcurl, curl);

  /* Record the start time which we can use later */
  mp_start = tvnow();

  /* We start some action by calling perform right away */
  curl_multi_perform(mcurl, &still_running);

  while(still_running) {
    struct timeval timeout;
    fd_set fdread;
    fd_set fdwrite;
    fd_set fdexcep;
    int maxfd = -1;
    int rc;

    long curl_timeo = -1;

    /* Initialise the file descriptors */
    FD_ZERO(&fdread);
    FD_ZERO(&fdwrite);
    FD_ZERO(&fdexcep);

    /* Set a suitable timeout to play around with */
    timeout.tv_sec = 1;
    timeout.tv_usec = 0;

    curl_multi_timeout(mcurl, &curl_timeo);
    if(curl_timeo >= 0) {
      timeout.tv_sec = curl_timeo / 1000;
      if(timeout.tv_sec > 1)
        timeout.tv_sec = 1;
      else
        timeout.tv_usec = (curl_timeo % 1000) * 1000;
    }

    /* Get file descriptors from the transfers */
    curl_multi_fdset(mcurl, &fdread, &fdwrite, &fdexcep, &maxfd);

    /* In a real-world program you OF COURSE check the return code of the
       function calls. On success, the value of maxfd is guaranteed to be
       greater or equal than -1. We call select(maxfd + 1, ...), specially in
       case of (maxfd == -1), we call select(0, ...), which is basically equal
       to sleep. */
    rc = select(maxfd + 1, &fdread, &fdwrite, &fdexcep, &timeout);

    if(tvdiff(tvnow(), mp_start) > MULTI_PERFORM_HANG_TIMEOUT) {
      fprintf(stderr,
              "ABORTING: Since it seems that we would have run forever.\n");
      break;
    }

    switch(rc) {
    case -1:  /* select error */
      break;
    case 0:   /* timeout */
    default:  /* action */
      curl_multi_perform(mcurl, &still_running);
      break;
    }
  }

  /* Always cleanup */
  curl_multi_remove_handle(mcurl, curl);
  curl_multi_cleanup(mcurl);
  curl_easy_cleanup(curl);
  curl_global_cleanup();

  return 0;
}


text:
package main

import (
	"io/ioutil"
	"os"
	"testing"

	"github.com/stretchr/testify/assert"
)

const configuration = `
[[Repo]]
url = "https://github.com/clearcontainers/runtime"
run = [ ".ci/run.sh" ]
[Repo.language]
  language = "Go"
  version = "go1.8.3"
`

const configurationWithErrors = `
[[Repo]
url = https://github.com/clearcontainers/runtime"
run = [ ".ci/run.sh" ]
[Repo.language]
  language: "Go"
  version = "go1.8.3"
`

func TestNewConfig(t *testing.T) {
	var configFile *os.File
	var err error
	var conf *config
	assert := assert.New(t)

	conf, err = newConfig("")
	assert.Error(err)
	assert.Nil(conf)

	// load a configuration file that does not exist
	conf, err = newConfig("/wxyz/123/abc")
	assert.Error(err)
	assert.Nil(conf)

	// Test a configuration with errors
	configFile, err = ioutil.TempFile("/tmp", ".config.toml.")
	assert.NoError(err)
	assert.NotNil(configFile)
	defer os.Remove(configFile.Name())
	defer configFile.Close()

	_, err = configFile.WriteString(configurationWithErrors)
	assert.NoError(err)
	conf, err = newConfig(configFile.Name())
	assert.Error(err)
	assert.Nil(conf)

	// Test a good configuration
	configFile, err = ioutil.TempFile("/tmp", ".config.toml.")
	assert.NoError(err)
	assert.NotNil(configFile)
	defer os.Remove(configFile.Name())
	defer configFile.Close()

	_, err = configFile.WriteString(configuration)
	assert.NoError(err)
	conf, err = newConfig(configFile.Name())
	assert.NoError(err)
	assert.NotNil(conf)
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.hadoop.hive.ql.exec.vector.mapjoin.fast;

import java.io.IOException;

import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.io.BytesWritable;

import com.google.common.annotations.VisibleForTesting;

/*
 * An multi-key value hash map optimized for vector map join.
 *
 * The key is stored as the provided bytes (uninterpreted).
 */
public class VectorMapJoinFastMultiKeyHashMap
        extends VectorMapJoinFastBytesHashMap {

  /*
   * A Unit Test convenience method for putting key and value into the hash table using the
   * actual types.
   */
  @VisibleForTesting
  public void testPutRow(byte[] currentKey, byte[] currentValue) throws HiveException, IOException {
    if (testKeyBytesWritable == null) {
      testKeyBytesWritable = new BytesWritable();
      testValueBytesWritable = new BytesWritable();
    }
    testKeyBytesWritable.set(currentKey, 0, currentKey.length);
    testValueBytesWritable.set(currentValue, 0, currentValue.length);
    putRow(testKeyBytesWritable, testValueBytesWritable);
  }

  public VectorMapJoinFastMultiKeyHashMap(
        boolean isOuterJoin,
        int initialCapacity, float loadFactor, int writeBuffersSize) {
    super(initialCapacity, loadFactor, writeBuffersSize);
  }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>My AngularJS App - Dave Barrows testing</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="bower_components/html5-boilerplate/css/normalize.css">
  <link rel="stylesheet" href="bower_components/html5-boilerplate/css/main.css">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">

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

view1

view2

Angular seed app: v


text:
var str = '';

process.stdin.resume();
process.stdin.setEncoding('utf8');

process.stdin.on('data', function (data) {
    str += data;
});

process.stdin.on('end', function () {
    var Comb = require('./node_modules/csscomb/lib/csscomb'),
        comb = new Comb(),
        syntax = process.argv[2],
        config, promise;

    try {
        config = JSON.parse(process.argv[3]);
    } catch (e) {
        config = null;
    }

    process.chdir(process.argv[4]);

    config = Comb.getCustomConfig() ||
        config ||
        Comb.getConfig('csscomb');

    promise = comb.configure(config).processString(str, {syntax: syntax});

    promise.then(function(string) {
        process.stdout.write(string);
    })
});


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

<title>All Classes (Javadocs: controlP5)</title>
<meta name="date" content="2014-09-08">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

All Classes

Accordion

Background

Bang

BitFont

Button

ButtonBar

CallbackEvent

CallbackListener

Canvas

CColor

CDrawable

Chart

ChartData

ChartDataSet

CheckBox

ColorPicker

ColorWheel

ControlBehavior

ControlBroadcaster

ControlElement

ControlEvent

ControlFont

ControlGroup

ControlKey

Controller

ControllerGroup

ControllerInterface

ControllerList

ControllerPlug

ControllerProperties

ControllerProperty

ControllerStyle

ControllerView

ControlListener

ControlP5

ControlP5Base

ControlP5Constants

ControlP5Legacy

ControlTimer

ControlWindow

CP

DropdownList

DropdownList.DropdownListView

FrameRate

Group

Icon

Knob

Label

ListBox

ListBox.ListBoxView

Matrix

MultiList

MultiListButton

Numberbox

Pointer

Println

Radio

RadioButton

Range

ScrollableList

ScrollableList.ScrollableListView

Slider

Slider2D

Spacer

Tab

Textarea

Textfield

Textfield.InputFilter

Textlabel

TickMark

Toggle

Tooltip


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" "http://www.ibatis.com/dtd/sql-map-2.dtd">
	<!--      table information
		Generate time : 2009-11-11 14:38:20
   		Version :  1.0.1.V20070717
		tableName :XS.V_STD_RPT_UNDERLIMITPRICE
		 SEGNO  VARCHAR2   NOT NULL,
		 CONTRACTSUBID  VARCHAR2,
		 CONTRACTSUBSTATUS  CHAR,
		 CONTRACTSUBSTATUSNAME  VARCHAR2   NOT NULL,
		 PERSNAME  VARCHAR2,
		 CUSTOMERID  VARCHAR2,
		 CUSTNAME  VARCHAR2   NOT NULL,
		 PRODUCTTYPEID  VARCHAR2   NOT NULL,
		 PRODTYPEDESC  VARCHAR2,
		 SHOPSIGN  VARCHAR2,
		 SPEC  VARCHAR2,
		 PRODUCINGAREACODE  VARCHAR2   NOT NULL,
		 PRODUCINGAREANAME  VARCHAR2,
		 WEIGHTQTY  NUMBER,
		 SALEPRICEAT  NUMBER,
		 PUT_PRICE_AT  NUMBER,
		 PUBLICPRICE  NUMBER,
		 CONTAFFECTDATE  VARCHAR2
	-->
<sqlMap namespace="STRP0208">

	<select id="query" parameterClass="java.util.HashMap"
			resultClass="com.baosight.sts.st.rp.domain.STRP0208">
		SELECT
				SEGNO	as "segNo",
				CONTRACTSUBID	as "contractSubId",
				CONTRACTSUBSTATUS	as "contractSubStatus",
				CONTRACTSUBSTATUSNAME	as "contractSubStatusName",
				PERSNAME	as "persName",
				CUSTOMERID	as "customerId",
				CUSTNAME	as "custName",
				PRODUCTTYPEID	as "productTypeId",
				PRODTYPEDESC	as "prodTypeDesc",
				SHOPSIGN	as "shopsign",
				SPEC	as "spec",
				PRODUCINGAREACODE	as "producingAreaCode",
				PRODUCINGAREANAME	as "producingAreaName",
				WEIGHTQTY	as "weightQty",
				SALEPRICEAT	as "salePriceAt",
				PUT_PRICE_AT	as "putPriceAt",
				PUBLICPRICE	as "publicPrice",
				CONTAFFECTDATE	as "contAffectDate"
		FROM XS.V_STD_RPT_UNDERLIMITPRICE WHERE 1=1
		<isNotEmpty prepend=" AND " property="segNo">
			SEGNO = #segNo#
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="contAffectDateF">
			CONTAFFECTDATE >= #contAffectDateF#
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="contAffectDateT">
			CONTAFFECTDATE <= #contAffectDateT#
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="customerId">
			(CUSTOMERID like '%'||#customerId#||'%' or CUSTNAME like '%'||#customerId#||'%')
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="contractSubId">
			CONTRACTSUBID like '%'||#contractSubId#||'%'
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="persName">
			PERSNAME like '%'||#persName#||'%'
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="productTypeId">
			(PRODUCTTYPEID like '%'||#productTypeId#||'%' or PRODTYPEDESC like '%'||#productTypeId#||'%')
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="producingAreaCode">
			(PRODUCINGAREACODE like '%'||#producingAreaCode#||'%' or PRODUCINGAREANAME like '%'||#producingAreaCode#||'%')
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="shopsign">
			SHOPSIGN like '%'||#shopsign#||'%'
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="spec">
			SPEC like '%'||#spec#||'%'
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="contractSubStatus">
			CONTRACTSUBSTATUS = #contractSubStatus#
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="persNo">
				(user_id = #persNo# or sign_person = #persNo#)
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="deptNo">
				(user_seg_no = #deptNo# or sign_group_id = #deptNo#)
		</isNotEmpty>

			<dynamic prepend="ORDER BY">
         <isNotEmpty property="orderBy">
    		  $orderBy$
   		 </isNotEmpty>
			<isEmpty property="orderBy">
    		  CONTAFFECTDATE
   		 	</isEmpty>
  		</dynamic>

	</select>

	<select id="count" resultClass="int">
		SELECT COUNT(*) FROM XS.V_STD_RPT_UNDERLIMITPRICE WHERE 1=1
		<isNotEmpty prepend=" AND " property="segNo">
			SEGNO = #segNo#
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="contAffectDateF">
			CONTAFFECTDATE >= #contAffectDateF#
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="contAffectDateT">
			CONTAFFECTDATE <= #contAffectDateT#
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="customerId">
			(CUSTOMERID like '%'||#customerId#||'%' or CUSTNAME like '%'||#customerId#||'%')
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="contractSubId">
			CONTRACTSUBID like '%'||#contractSubId#||'%'
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="persName">
			PERSNAME like '%'||#persName#||'%'
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="productTypeId">
			(PRODUCTTYPEID like '%'||#productTypeId#||'%' or PRODTYPEDESC like '%'||#productTypeId#||'%')
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="producingAreaCode">
			(PRODUCINGAREACODE like '%'||#producingAreaCode#||'%' or PRODUCINGAREANAME like '%'||#producingAreaCode#||'%')
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="shopsign">
			SHOPSIGN like '%'||#shopsign#||'%'
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="spec">
			SPEC like '%'||#spec#||'%'
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="contractSubStatus">
			CONTRACTSUBSTATUS = #contractSubStatus#
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="persNo">
				(user_id = #persNo# or sign_person = #persNo#)
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="deptNo">
				(user_seg_no = #deptNo# or sign_group_id = #deptNo#)
		</isNotEmpty>
	</select>

	<!--
		<isNotEmpty prepend=" AND " property="segno">
			SEGNO = #segno#
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="contractsubid">
			CONTRACTSUBID = #contractsubid#
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="contractsubstatus">
			CONTRACTSUBSTATUS = #contractsubstatus#
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="contractsubstatusname">
			CONTRACTSUBSTATUSNAME = #contractsubstatusname#
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="persname">
			PERSNAME = #persname#
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="customerid">
			CUSTOMERID = #customerid#
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="custname">
			CUSTNAME = #custname#
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="producttypeid">
			PRODUCTTYPEID = #producttypeid#
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="prodtypedesc">
			PRODTYPEDESC = #prodtypedesc#
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="shopsign">
			SHOPSIGN = #shopsign#
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="spec">
			SPEC = #spec#
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="producingareacode">
			PRODUCINGAREACODE = #producingareacode#
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="producingareaname">
			PRODUCINGAREANAME = #producingareaname#
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="weightqty">
			WEIGHTQTY = #weightqty#
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="salepriceat">
			SALEPRICEAT = #salepriceat#
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="putPriceAt">
			PUT_PRICE_AT = #putPriceAt#
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="publicprice">
			PUBLICPRICE = #publicprice#
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="contaffectdate">
			CONTAFFECTDATE = #contaffectdate#
		</isNotEmpty>
	-->

	<select id="sum" parameterClass="java.util.HashMap" resultClass="java.util.HashMap">
		SELECT nvl(sum(nvl(WEIGHTQTY,0)),0) as "weightQty" FROM XS.V_STD_RPT_UNDERLIMITPRICE WHERE 1=1
		<isNotEmpty prepend=" AND " property="segNo">
			SEGNO = #segNo#
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="contAffectDateF">
			CONTAFFECTDATE >= #contAffectDateF#
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="contAffectDateT">
			CONTAFFECTDATE <= #contAffectDateT#
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="customerId">
			(CUSTOMERID like '%'||#customerId#||'%' or CUSTNAME like '%'||#customerId#||'%')
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="contractSubId">
			CONTRACTSUBID like '%'||#contractSubId#||'%'
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="persName">
			PERSNAME like '%'||#persName#||'%'
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="productTypeId">
			(PRODUCTTYPEID like '%'||#productTypeId#||'%' or PRODTYPEDESC like '%'||#productTypeId#||'%')
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="producingAreaCode">
			(PRODUCINGAREACODE like '%'||#producingAreaCode#||'%' or PRODUCINGAREANAME like '%'||#producingAreaCode#||'%')
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="shopsign">
			SHOPSIGN like '%'||#shopsign#||'%'
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="spec">
			SPEC like '%'||#spec#||'%'
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="contractSubStatus">
			CONTRACTSUBSTATUS = #contractSubStatus#
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="persNo">
				(user_id = #persNo# or sign_person = #persNo#)
		</isNotEmpty>
		<isNotEmpty prepend=" AND " property="deptNo">
				(user_seg_no = #deptNo# or sign_group_id = #deptNo#)
		</isNotEmpty>
	</select>
</sqlMap>


text:
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.angularMarked = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/*
 * angular-marked
 * (c) 2014 J. Harshbarger
 * Licensed MIT
 */

/* jshint undef: true, unused: true */
/* global angular, marked */

'use strict';

  /**
   * @ngdoc overview
   * @name index
   *
   * @description
   * AngularJS Markdown using [marked](https://github.com/chjj/marked).
   *
   * ## Why?
   *
   * I wanted to use [marked](https://github.com/chjj/marked) instead of [showdown](https://github.com/coreyti/showdown) as used in [angular-markdown-directive](https://github.com/btford/angular-markdown-directive) as well as expose the option to globally set defaults.
   *
   * ## How?
   *
   * - {@link hc.marked.directive:marked As a directive}
   * - {@link hc.marked.service:marked As a service}
   * - {@link hc.marked.service:markedProvider Set default options}
   *
   * @example

      Convert markdown to html at run time.  For example:

      <example module="app">
        <file name="example.html">
          <form ng-controller="MainController">
            Markdown:

            <textarea ng-model="my_markdown" cols="60" rows="5" class="span8"></textarea>

            Output:

          </form>
        </file>
        <file  name="example.js">
          function MainController($scope) {
            $scope.my_markdown = "*This* **is** [markdown](https://daringfireball.net/projects/markdown/)";
          }
          angular.module('app', ['hc.marked']).controller('MainController', MainController);
        </file>
      </example>

    *
    */

    /**
     * @ngdoc overview
     * @name hc.marked
     * @description # angular-marked (core module)
       # Installation
      First include angular-marked.js in your HTML:

      ```js
        <script src="angular-marked.js">
      ```

      Then load the module in your application by adding it as a dependency:

      ```js
      angular.module('yourApp', ['hc.marked']);
      ```

      With that you're ready to get started!
     */

module.exports = 'hc.marked';

angular.module('hc.marked', [])

    /**
    * @ngdoc service
    * @name hc.marked.service:marked
    * @requires $window
    * @description
    * A reference to the [marked](https://github.com/chjj/marked) parser.
    *
    * @example
    <example module="app">
      <file name="example.html">

          html: {{html}}

      </file>
      <file  name="example.js">
        function MainController($scope, marked) {
          $scope.html = marked('#TEST');
        }
        angular.module('app', ['hc.marked']).controller('MainController', MainController);
      </file>
    </example>
   **/

   /**
   * @ngdoc service
   * @name hc.marked.service:markedProvider
   * @description
   * Use `markedProvider` to change the default behavior of the {@link hc.marked.service:marked marked} service.
   *
   * @example

    ## Example using [google-code-prettify syntax highlighter](https://code.google.com/p/google-code-prettify/) (must include google-code-prettify.js script).  Also works with [highlight.js Javascript syntax highlighter](http://highlightjs.org/).

    <example module="myAppA">
      <file name="exampleA.js">
      angular.module('myAppA', ['hc.marked'])
        .config(['markedProvider', function(markedProvider) {
          markedProvider.setOptions({
            gfm: true,
            tables: true,
            highlight: function (code) {
              return prettyPrintOne(code);
            }
          });
        }]);
      </file>
      <file name="exampleA.html">
        <marked>
        ```js
        angular.module('myAppA', ['hc.marked'])
          .config(['markedProvider', function(markedProvider) {
            markedProvider.setOptions({
              gfm: true,
              tables: true,
              highlight: function (code) {
                return prettyPrintOne(code);
              }
            });
          }]);
        ```
        </marked>
      </file>
    </example>

    ## Example overriding the way custom markdown links are displayed

    <example module="myAppB">
      <file name="exampleB.js">
      angular.module('myAppB', ['hc.marked'])
        .config(['markedProvider', function(markedProvider) {
          markedProvider.setRenderer({
            link: function(href, title, text) {
              return "" + text + "";
            }
          });
        }]);
      </file>
      <file name="exampleB.html">
        <marked>
          This is [an example](http://example.com/ "Title") inline link.
          [This link](http://example.net/) has no title attribute.
        </marked>
      </file>
    </example>
  **/

.provider('marked', function () {
  var self = this;

  /**
   * @ngdoc method
   * @name markedProvider#setRenderer
   * @methodOf hc.marked.service:markedProvider
   *
   * @param {object} opts Default renderer options for [marked](https://github.com/chjj/marked#overriding-renderer-methods).
   */

  self.setRenderer = function (opts) {
    this.renderer = opts;
  };

  /**
   * @ngdoc method
   * @name markedProvider#setOptions
   * @methodOf hc.marked.service:markedProvider
   *
   * @param {object} opts Default options for [marked](https://github.com/chjj/marked#options-1).
   */

  self.setOptions = function (opts) {  // Store options for later
    this.defaults = opts;
  };

  self.$get = ['$log', '$window', function ($log, $window) {
    var m;

    try {
      m = require('marked');
    } catch (e) {
      m = $window.marked || marked;
    }

    if (angular.isUndefined(m)) {
      $log.error('angular-marked Error: marked not loaded.  See installation instructions.');
      return;
    }

    // override rendered markdown html
    // with custom definitions if defined
    if (self.renderer) {
      var r = new m.Renderer();
      var o = Object.keys(self.renderer);
      var l = o.length;

      while (l--) {
        r[o[l]] = self.renderer[o[l]];
      }

      // add the new renderer to the options if need be
      self.defaults = self.defaults || {};
      self.defaults.renderer = r;
    }

    m.setOptions(self.defaults);

    return m;
  }];
})

  // TODO: filter and tests */
  // app.filter('marked', ['marked', function(marked) {
  //   return marked;
  // }]);

  /**
   * @ngdoc directive
   * @name hc.marked.directive:marked
   * @restrict AE
   * @element any
   *
   * @description
   * Compiles source test into HTML.
   *
   * @param {expression=} marked The source text to be compiled.  If blank uses content as the source.
   * @param {expression=} opts Hash of options that override defaults.
   * @param {string=} src Expression evaluating to URL. If the source is a string constant,
 *                 make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
   *
   * @example

     ## A simple block of text

      <example module="hc.marked">
        <file name="exampleA.html">
         * <marked>
         *   ### Markdown directive
         *
         *   *It works!*
         *
         *   *This* **is** [markdown](https://daringfireball.net/projects/markdown/) in the view.
         * </marked>
        </file>
      </example>

     ## Bind to a scope variable

      <example module="app">
        <file name="exampleB.html">
          <form ng-controller="MainController">
            Markdown:

            <textarea ng-model="my_markdown" class="span8" cols="60" rows="5"></textarea>

            Output:

          </form>
        </file>
        <file  name="exampleB.js">
          * function MainController($scope) {
          *     $scope.my_markdown = '*This* **is** [markdown](https://daringfireball.net/projects/markdown/)';
          *     $scope.my_markdown += ' in a scope variable';
          * }
          * angular.module('app', ['hc.marked']).controller('MainController', MainController);
        </file>
      </example>

      ## Include a markdown file:

       <example module="hc.marked">
         <file name="exampleC.html">

         </file>
         * <file name="include.html">
         * *This* **is** [markdown](https://daringfireball.net/projects/markdown/) in a include file.
         * </file>
       </example>
   */

.directive('marked', ['marked', '$templateRequest', function (marked, $templateRequest) {
  return {
    restrict: 'AE',
    replace: true,
    scope: {
      opts: '=',
      marked: '=',
      src: '='
    },
    link: function (scope, element, attrs) {
      set(scope.marked || element.text() || '');

      if (attrs.marked) {
        scope.$watch('marked', set);
      }

      if (attrs.src) {
        scope.$watch('src', function (src) {
          $templateRequest(src, true).then(function (response) {
            set(response);
          });
        });
      }

      function unindent (text) {
        if (!text) return text;

        var lines = text
          .replace(/\t/g, '  ')
          .split(/\r?\n/);

        var min = null;
        var len = lines.length;

        var l, line;
        for (var i = 0; i < len; i++) {
          line = lines[i];
          l = line.match(/^(\s*)/)[0].length;
          if (l === line.length) { continue; }
          min = (l < min || min === null) ? l : min;
        }

        if (min !== null && min > 0) {
          for (i = 0; i < len; i++) {
            lines[i] = lines[i].substr(min);
          }
        }
        return lines.join('\n');
      }

      function set (text) {
        text = unindent(text || '');
        element.html(marked(text, scope.opts || null));
      }
    }
  };
}]);

},{"marked":"marked"}]},{},[1])(1)
});


text:
<?php

namespace chillerlan\QRCode\Output;

use chillerlan\QRCode\QRCode;

/**
 * Converts the matrix into markup types: HTML, SVG, ...
 */
class QRMarkup extends QROutputAbstract{

	protected $defaultMode = QRCode::OUTPUT_MARKUP_SVG;

	/**
	 * @return string|bool
	 */
	protected function html(){
		$html = '';

		foreach($this->matrix->matrix() as $row){
			$html .= '
';

			foreach($row as $pixel){
				$html .= 'options->moduleValues[$pixel] ?: 'lightgrey').';">';
			}

			$html .= '
'.$this->options->eol;
		}

		if($this->options->cachefile){
			return '<!DOCTYPE html><meta charset="UTF-8">'.$this->options->eol.$html.'';
		}

		return $html;
	}

	/**
	 * @link https://github.com/codemasher/php-qrcode/pull/5
	 *
	 * @return string|bool
	 */
	protected function svg(){
		$scale  = $this->options->scale;
		$length = $this->moduleCount * $scale;
		$matrix = $this->matrix->matrix();

		$svg = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="'.$length.'px" height="'.$length.'px">'
		       .$this->options->eol
		       .'<defs>'.$this->options->svgDefs.'</defs>'
		       .$this->options->eol;

		foreach($this->options->moduleValues as $M_TYPE => $value){

			// fallback
			if(is_bool($value)){
				$value = $value ? '#000' : '#fff';
			}

			$path = '';

			foreach($matrix as $y => $row){
				//we'll combine active blocks within a single row as a lightweight compression technique
				$start = null;
				$count = 0;

				foreach($row as $x => $module){

					if($module === $M_TYPE){
						$count++;

						if($start === null){
							$start = $x * $scale;
						}

						if($row[$x + 1] ?? false){
							continue;
						}
					}

					if($count > 0){
						$len = $count * $scale;
						$path .= 'M' .$start. ' ' .($y * $scale). ' h'.$len.' v'.$scale.' h-'.$len.'Z ';

						// reset count
						$count = 0;
						$start = null;
					}

				}

			}

			if(!empty($path)){
				$svg .= '<path class="qr-'.$M_TYPE.' '.$this->options->cssClass.'" stroke="transparent" fill="'.$value.'" fill-opacity="'.$this->options->svgOpacity.'" d="'.$path.'" />';
			}

		}

		// close svg
		$svg .= '</svg>'.$this->options->eol;

		// if saving to file, append the correct headers
		if($this->options->cachefile){
			return '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'.$this->options->eol.$svg;
		}

		return $svg;
	}

}


text:
package org.apache.sysds.runtime.instructions.spark.data;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;

import org.apache.sysds.common.Types.ValueType;
import org.apache.sysds.runtime.DMLRuntimeException;
import org.apache.sysds.runtime.matrix.data.FrameBlock;
import org.apache.sysds.runtime.matrix.data.Pair;
import org.apache.sysds.runtime.util.UtilFunctions;

public class FrameReblockBuffer
{
	//default buffer size: 5M -> 5M * 3x8B = 120MB
	public static final int DEFAULT_BUFFER_SIZE = 5000000;

	private int _bufflen = -1;
	private int _count = -1;

	private FrameCell[] _buff = null;

	private long _rlen = -1;
	private long _clen = -1;
	private int _blen = -1;

	private ValueType[] _schema;

	public FrameReblockBuffer( int buffersize,  long rlen, long clen, ValueType[] schema )
	{
		_bufflen = buffersize;
		_count = 0;

		_buff = new FrameCell[ _bufflen ];
		for(int i=0; i< _bufflen; i++)
			_buff[i] = new FrameCell();

		_rlen = rlen;
		_clen = clen;
		_blen = Math.max((int)(_bufflen/_clen), 1);
		_blen = (int)clen;

		_schema = schema;
	}

	public int getSize() {
		return _count;
	}

	public int getCapacity() {
		return _bufflen;
	}

	public void appendCell( long r, long c, Object obj ) {
		_buff[_count].setRow((int)r);
		_buff[_count].setCol((int)c);
		_buff[_count].setObjVal(obj);
		_count++;
	}

	public void flushBufferToBinaryBlocks( ArrayList<Pair<Long, FrameBlock>> outList )
		throws DMLRuntimeException
	{
		if( _count == 0 )
			return;

		//Step 1) sort reblock buffer (blockwise, no in-block sorting!)
		Arrays.sort( _buff, 0 ,_count, new FrameReblockBufferComparator() );

		//Step 2) output blocks
		Long tmpIx = -1L;
		FrameBlock tmpBlock = new FrameBlock(_schema);

		//put values into block and output
		long cbi = -1, cbj = -1; //current block indexes
		for( int i=0; i<_count; i++ )
		{
			//compute block indexes (w/ robustness for meta data handling)
			long bi = Math.max(UtilFunctions.computeBlockIndex(_buff[i].getRow(), _blen), 1);
			long bj = UtilFunctions.computeBlockIndex(_buff[i].getCol(), _blen);

			//output block and switch to next index pair
			if( bi != cbi || bj != cbj ) {
				if( cbi != -1 && cbj != -1)
					outputBlock(outList, tmpIx, tmpBlock);
				cbi = bi;
				cbj = bj;
				tmpIx = (bi-1)*_blen+1;
				tmpBlock = new FrameBlock(_schema);
				tmpBlock.ensureAllocatedColumns(Math.min(_blen, (int)(_rlen-(bi-1)*_blen)));
			}

			int ci = UtilFunctions.computeCellInBlock(_buff[i].getRow(), _blen);
			int cj = UtilFunctions.computeCellInBlock(_buff[i].getCol(), _blen);
			if( ci == -3 )
				tmpBlock.getColumnMetadata(cj).setMvValue(_buff[i].getObjVal().toString());
			else if( ci == -2 )
				tmpBlock.getColumnMetadata(cj).setNumDistinct(Long.parseLong(_buff[i].getObjVal().toString()));
			else
				tmpBlock.set(ci, cj, _buff[i].getObjVal());
		}

		//output last block
		if( cbi != -1 && cbj != -1)
			outputBlock(outList, tmpIx, tmpBlock);

		_count = 0;
	}

	private static void outputBlock( ArrayList<Pair<Long, FrameBlock>> out, Long key, FrameBlock value )
		throws DMLRuntimeException
	{
		//skip output of unassigned blocks
		if( key == -1 )
			return;

		//output block
		out.add(new Pair<>(Long.valueOf(key), value));
	}

	private static class FrameCell {
		private int iRow;
		private int iCol;
		private Object objVal;
		public int getRow() {
			return iRow;
		}
		public void setRow(int iRow) {
			this.iRow = iRow;
		}
		public int getCol() {
			return iCol;
		}
		public void setCol(int iCol) {
			this.iCol = iCol;
		}
		public Object getObjVal() {
			return objVal;
		}
		public void setObjVal(Object objVal) {
			this.objVal = objVal;
		}
	}

	/**
	 * Comparator to sort the reblock buffer by block indexes, where we
	 * compute the block indexes on-the-fly based on the given cell indexes.
	 *
	 */
	private static class FrameReblockBufferComparator implements Comparator<FrameCell> {
		@Override
		public int compare(FrameCell arg0, FrameCell arg1)
		{
			long bi0 = arg0.getRow();
			long bj0 = arg0.getCol();
			long bi1 = arg1.getRow();
			long bj1 = arg1.getCol();

			return ( bi0 < bi1 || (bi0 == bi1 && bj0 < bj1) ) ? -1 :
				(( bi0 == bi1 && bj0 == bj1)? 0 : 1);
		}
	}
}


text:
namespace FluentData
{
	public interface IDeleteBuilder : IExecute
	{
		BuilderData Data { get; }
		IDeleteBuilder Where(string columnName, object value, DataTypes parameterType = DataTypes.Object, int size = 0);
	}
}


text:
from django import http
from django.views.generic.edit import ModelFormMixin
from django.views.generic.detail import SingleObjectMixin
from django import forms
from django.forms import models as model_forms
from django.contrib.admin.utils import flatten_fieldsets
from django.db.models.fields import FieldDoesNotExist
from django.db import models
from django.core.exceptions import ValidationError

from . import helpers
from . import renders
from . import transaction
from .forms import LazyFormSetFactory
from .models import CMSLog
from .internal_tags import handler as tag_handler
from .base_views import ModelCMSMixin, ModelCMSView
from .actions import PublishView

class FormView(ModelCMSMixin, ModelFormMixin, ModelCMSView):
    """
    View for adding or editing an object.
    Inherits from ModelCMSMixin, ModelFormMixin, ModelCMSView.
    Adds a 'popup' value to self.renders that is an instance of
    PopupRender that uses the default_template.

    :param default_template: The default template. Defaults to \
    'cms/edit.html'.
    :param force_add: Treat this form as an add form. Defaults \
    to False.
    :param form_class: A ModelForm class to use instead of using \
    model_form_factory.
    :param fieldsets: The view's fieldsets. Use the same format as \
    django admin. Defaults to None.
    :param formsets: A dictionary where the keys are the formset \
    prefixes and the values are LazyFormSetFactory instances. \
    Defaults to an empty dictionary.
    :param redirect_to_view: The name of a view that we will redirect to \
    after a successful save.
    :param cancel_view: The name of a view the cancel links will point to.
    :param force_instance_values: A dictionary of keyword arguments that \
    will be set on every object before save. Defaults to empty dictionary.
    :param combined_formset_defs: A dictionary of keyward arguments for
    AdminFormset used to combine the display of formsets
    """

    default_template = 'cms/edit.html'
    force_add = False

    fieldsets = None
    formsets = {}
    redirect_to_view = "main"
    cancel_view = "main"
    readonly_fields = None
    prepopulated_fields = None
    force_instance_values = {}
    combined_formset_defs = None

    def __init__(self, *args, **kwargs):
        if args:
            super(FormView, self).__init__(*args, **kwargs)
        else:
            super(FormView, self).__init__(**kwargs)

        self.renders['popup'] = renders.PopupRender(
                        template=self.default_template
        )

        if self.formsets:
            for k, v in self.formsets.items():
                if not isinstance(v, LazyFormSetFactory):
                    raise TypeError(
                        '%s must be a LazyFormSetFactory instance' % k)

    def get_readonly_fields(self):
        """
        Hook for specifying custom readonly fields.
        """
        return self.readonly_fields

    def get_force_instance_values(self):
        """
        Returns values that must be set on
        any object before save.

        Defaults to returning `self.force_instance_values`.
        """
        return self.force_instance_values

    def get_object_url(self):
        """
        Returns the url where this object can be edited.
        """

        if self.kwargs.get(self.slug_url_kwarg, False) == \
                    unicode(getattr(self.object, self.slug_field, "")) \
                    and not self.force_add:
            url = self.request.build_absolute_uri()
        else:
            url = self.bundle.get_view_url('edit', self.request.user,
                                           {'object': self.object},
                                           self.kwargs)
        return url

    def get_cancel_url(self):
        """
        Returns the cancel url for this view.

        if `self.cancel_view` is None the current url will
        be used. Otherwise the get_view_url will be called with
        the current bundle using `self.cancel_view` as the
        view name.
        """
        if self.cancel_view:
            url = self.bundle.get_view_url(self.cancel_view,
                                            self.request.user, {},
                                            self.kwargs)
        else:
            url = self.request.build_absolute_uri()

        return self.customized_return_url(url)

    def get_success_url(self):
        """
        Returns the url to redirect to after a successful update.

        if `self.redirect_to_view` is None the current url will
        be used. Otherwise the get_view_url will be called
        on the current bundle using `self.redirect_to_view` as the
        view name. If the name is "main" or "main_list" no object
        will be passed. Otherwise `self.object` will be passed as
        a kwarg.
        """

        if self.redirect_to_view:
            kwargs = {}
            if self.redirect_to_view != 'main' and \
                        self.redirect_to_view != 'main_list':
                kwargs['object'] = self.object
            return self.bundle.get_view_url(self.redirect_to_view,
                                            self.request.user, kwargs,
                                            self.kwargs)
        else:
            return self.request.build_absolute_uri()

    def get_object(self):
        """
        Get the object we are working with. Makes sure
        get_queryset is called even when in add mode.
        """

        if not self.force_add and self.kwargs.get(self.slug_url_kwarg, None):
            return super(FormView, self).get_object()
        else:
            self.queryset = self.get_queryset()

        return None

    def get_fieldsets(self):
        """
        Hook for specifying fieldsets. If 'self.fieldsets' is
        empty this will default to include all the fields in
        the form with a title of None.
        """

        if self.fieldsets:
            return self.fieldsets
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        fields = form.base_fields.keys()

        readonly_fields = self.get_readonly_fields()
        if readonly_fields:
            fields.extend(readonly_fields)

        return [(None, {'fields': fields})]

    def get_form_class(self):
        """
        Returns the form class to use in this view. Makes
        sure that the form_field_callback is set to use
        the `formfield_for_dbfield` method and that any
        custom form classes are prepared by the
        `customize_form_widgets` method.
        """
        if self.fieldsets:
            fields = flatten_fieldsets(self.get_fieldsets())
        else:
            if (self.form_class and
                    getattr(self.form_class, 'Meta', None) and
                    getattr(self.form_class.Meta, 'fields', None)):
                fields = self.form_class.Meta.fields
            else:
                fields = []

        exclude = None
        if self.parent_field:
            exclude = (self.parent_field,)

        readonly_fields = self.get_readonly_fields()
        if readonly_fields:
            if exclude:
                exclude = list(exclude)
            else:
                exclude = []

            for field in readonly_fields:
                try:
                    try:
                        f = self.model._meta.get_field(field)
                        if fields:
                            fields.remove(field)
                        else:
                            exclude.append(field)
                    except models.FieldDoesNotExist:
                        if fields:
                            fields.remove(field)
                except ValueError:
                    pass

        params = {'fields': fields or '__all__',
                  'exclude': exclude,
                  'formfield_callback': self.formfield_for_dbfield}

        if self.form_class:
            if issubclass(self.form_class, forms.ModelForm) and \
                    getattr(self.form_class._meta, 'model', None):
                model = self.form_class.Meta.model
            else:
                model = self.model
            fc = self.customize_form_widgets(self.form_class, fields=fields)
            params['form'] = fc
        else:
            if self.model is not None:
                # If a model has been explicitly provided, use it
                model = self.model
            elif hasattr(self, 'object') and self.object is not None:
                # If this view is operating on a single object, use
                # the class of that object
                model = self.object.__class__
            else:
                # Try to get a queryset and extract the model class
                # from that
                model = self.get_queryset().model

        return model_forms.modelform_factory(model, **params)

    def get_form_kwargs(self):
        """
        Returns the keyword arguments for instantiating the form.
        """
        kwargs = {'initial': self.get_initial(),
                  'instance': self.object}

        if self.request.method in ('POST', 'PUT') and self.can_submit:
            kwargs.update({
                'data': self.request.POST,
                'files': self.request.FILES
            })
        return kwargs

    def get_formsets_dict(self):
        return self.formsets

    def get_formset_parent_object(self, parent_form, saving=False):
        if parent_form.is_valid() and saving:
            obj = parent_form.save(commit=False)
        elif self.object:
            obj = self.object
        else:
            obj = parent_form._meta.model()
        return obj

    def get_formset_queryset(self, key, klass):
        """
        Hook for specifying a custom queryset for
        a particular formset. Returns None by default.

        :param key: The prefix for the formset. This \
        matches with the key of the formset in the \
        self.formsets dictionary.
        :param klass: The FormSet class.
        """
        return None

    def get_formsets(self, parent_form, saving=False):
        fdict = self.get_formsets_dict()
        if not fdict:
            return {}

        obj = self.get_formset_parent_object(parent_form,
                                             saving=saving)

        formsets = {}
        for k, v in fdict.items():
            formsets[k] = self._init_formset(k, v,
                                         obj, saving=saving)
        return formsets

    def get_combined_formset_defs(self):
        return self.combined_formset_defs

    def get_admin_formsets(self, formsets):
        """
        Hook for specifying custom admin formsets
        """
        if formsets:
            return helpers.AdminFormSets(formsets, self.get_combined_formset_defs())
        return None

    def get_admin_form(self, form):
        """
        Hook for specifying custom admin forms
        """
        return helpers.AdminForm(form, self.get_fieldsets())

    def _init_formset(self, key, lazy_klass, obj, saving=False):
        klass = lazy_klass(self.formfield_for_dbfield,
                           self.customize_form_widgets)
        prefix = klass.__name__.lower()
        queryset = self.get_formset_queryset(key, klass)

        if saving:
            ins = klass(self.request.POST, files=self.request.FILES,
                                instance=obj, prefix=prefix,
                                queryset=queryset)
        else:
            ins = klass(instance=obj, prefix=prefix, queryset=queryset)

        return ins

    def form_invalid(self, **context):
        """
        Response for invalid form. Calls the render method
        passing self.request and any passed in keyword arguments.
        """
        return self.render(self.request, **context)

    def save_form(self, form):
        """
        Save a valid form. If there is a parent attribute,
        this will make sure that the parent object is added
        to the saved object. Either as a relationship before
        saving or in the case of many to many relations after
        saving. Any forced instance values are set as well.

        Returns the saved object.
        """

        # Add any force_instance_values
        force = self.get_force_instance_values()
        if force:
            for k, v in force.items():
                setattr(form.instance, k, v)

        # Are we adding to an attr or manager
        should_add = False
        if self.parent_object:
            m2ms = [f.name for f in form.instance._meta.many_to_many]
            m2ms.extend(
                [f.field.rel.related_name for f in
                    [
                        f for f in form.instance._meta.get_fields(include_hidden=True)
                        if f.many_to_many and f.auto_created
                    ]
                ]
            )

            if self.parent_field in m2ms:
                should_add = True
            else:
                try:
                    form.instance._meta.get_field(self.parent_field)
                    setattr(form.instance, self.parent_field,
                            self.parent_object)
                except FieldDoesNotExist:
                    pass

        obj = form.save()
        # Do we need to add this to a m2m
        if should_add:
            getattr(obj, self.parent_field).add(self.parent_object)

        return obj

    def save_formsets(self, form, formsets, auto_tags=None):
        """
        Hook for saving formsets. Loops through
        all the given formsets and calls their
        save method.
        """
        for formset in formsets.values():
            tag_handler.set_auto_tags_for_formset(formset, auto_tags)
            formset.save()

    def form_valid(self, form, formsets):
        """
        Response for valid form. In one transaction this will
        save the current form and formsets, log the action
        and message the user.

        Returns the results of calling the `success_response` method.
        """
        # check if it's a new object before it save the form
        new_object = False
        if not self.object:
            new_object = True

        instance = getattr(form, 'instance', None)
        auto_tags, changed_tags, old_tags = tag_handler.get_tags_from_data(
            form.data, self.get_tags(instance))
        tag_handler.set_auto_tags_for_form(form, auto_tags)

        with transaction.commit_on_success():
            self.object = self.save_form(form)
            self.save_formsets(form, formsets, auto_tags=auto_tags)

            url = self.get_object_url()
            self.log_action(self.object, CMSLog.SAVE, url=url)
            msg = self.write_message()

        # get old and new tags
        if not new_object and changed_tags and old_tags:
            tag_handler.update_changed_tags(changed_tags, old_tags)

        return self.success_response(msg)

    def success_response(self, message=None):
        """
        Returns a 'render redirect' to the result of the
        `get_success_url` method.
        """

        return self.render(self.request,
                           redirect_url=self.get_success_url(),
                           obj=self.object,
                           message=message,
                           collect_render_data=False)

    def render(self, request, **kwargs):
        """
        Renders this view. Adds cancel_url to the context.
        If the request get parameters contains 'popup' then
        the `render_type` is set to 'popup'.
        """
        if request.GET.get('popup'):
            self.render_type = 'popup'
            kwargs['popup'] = 1

        kwargs['cancel_url'] = self.get_cancel_url()
        if not self.object:
            kwargs['single_title'] = True
        return super(FormView, self).render(request, **kwargs)

    def get(self, request, *args, **kwargs):
        """
        Method for handling GET requests.
        Calls the `render` method with the following
        items in context.

        * **adminForm** - The main form wrapped in an helper class \
        that helps with fieldset iteration and html attributes.
        * **obj** - The object being edited.
        * **formsets** - Any attached formsets.
        """

        self.object = self.get_object()
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        formsets = self.get_formsets(form)

        adminForm = self.get_admin_form(form)
        adminFormSets = self.get_admin_formsets(formsets)
        context = {
            'adminForm': adminForm,
            'obj': self.object,
            'formsets': adminFormSets,
        }
        return self.render(request, **context)

    def is_valid(self, form, formsets):
        valid_formsets = True
        for formset in formsets.values():
            if not formset.is_valid():
                valid_formsets = False
                break

        if form.is_valid() and valid_formsets:
            # Add any force_instance_values
            force = self.get_force_instance_values()
            if force:
                for k, v in force.items():
                    setattr(form.instance, k, v)
                try:
                    form.instance.full_clean()
                except ValidationError, e:
                    form._update_errors(e)
                    return False
            return True

        return False

    def post(self, request, *args, **kwargs):
        """
        Method for handling POST requests.
        Validates submitted form and
        formsets. Saves if valid, re displays
        page with errors if invalid.
        """

        self.object = self.get_object()
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        formsets = self.get_formsets(form, saving=True)

        valid_formsets = True
        for formset in formsets.values():
            if not formset.is_valid():
                valid_formsets = False
                break

        if self.is_valid(form, formsets):
            return self.form_valid(form, formsets)
        else:
            adminForm = self.get_admin_form(form)
            adminFormSets = self.get_admin_formsets(formsets)
            context = {
                'adminForm': adminForm,
                'formsets': adminFormSets,
                'obj': self.object,
            }
            return self.form_invalid(form=form, **context)

class PreviewWrapper(ModelCMSMixin, SingleObjectMixin, ModelCMSView):
    """
    Wrapper View for providing a preview that is based on another view.
    Inherits from ModelCMSMixin, SingleObjectMixin and ModelCMSView.

    :param preview_view: A view class with a as_string method that can be \
    called to return a string for previewing an object.
    :param pass_through_kwarg: The name of keyword argument that the \
    `preview_view` callable expects to identify to object being requested. \
    Defaults to 'slug'.
    :param pass_through_attr: The name of the attribute on the object \
    being previewed that should be the value passed to the `preview_view` \
    to identify the object. Defaults to 'slug'.
    :param default_template: The default template to render. Defaults \
    to 'cms/preview.html'.
    """

    pass_through_kwarg = 'slug'
    pass_through_attr = 'slug'
    preview_view = None

    slug_field = 'pk'
    slug_url_kwarg = 'pk'

    default_template = 'cms/preview.html'

    def get_context_data(self, **kwargs):
        """
        Hook for adding arguments to the context.
        """
        return kwargs

    def get_object(self):
        """
        Get the object for previewing.
        Raises a http404 error if the object is not found.
        """
        obj = super(PreviewWrapper, self).get_object()

        if not obj:
            raise http.Http404

        return obj

    def get_preview_kwargs(self, **kwargs):
        """
        Gets the url keyword arguments to pass to the
        `preview_view` callable. If the `pass_through_kwarg`
        attribute is set the value of `pass_through_attr` will
        be looked up on the object.

        So if you are previewing an item Obj<id=2> and

            ::

                self.pass_through_kwarg = 'object_id'
                self.pass_through_attr = 'pk'

        This will return

            ::

                { 'object_id' : 2 }

        """
        if not self.pass_through_kwarg:
            return {}

        obj = self.get_object()
        return {
            self.pass_through_kwarg: getattr(obj, self.pass_through_attr)
        }

    def get(self, request, *args, **kwargs):
        """
        Method for handling GET requests.
        Sets the renderer to be a RenderResponse instance
        that uses `default_template` as the template.

        The `preview_view` callable is called and passed to `render`
        method as the data keyword argument.
        """

        self.renders = {
            'response': renders.RenderResponse(template=self.default_template),
        }
        kwargs = self.get_preview_kwargs(**kwargs)
        view = self.preview_view.as_string()
        return self.render(request, data=view(request, **kwargs))

class VersionsList(PublishView):
    """
    View for deleting and reverting to previous versions.
    Inherits from PublishView.

    :param default_template: 'cms/versions.html'.
    :param redirect_to_view: 'edit'.
    """

    default_template = 'cms/versions.html'
    redirect_to_view = "edit"

    def _get_versions(self):
        self.object = self.get_object()
        klass = self.object.get_version_class()
        return klass.normal.filter(object_id=self.object.pk).exclude(
                                state=klass.DRAFT).order_by('-date_published')

    def get(self, request, *args, **kwargs):
        """
        Method for handling GET requests. Passes the
        following arguments to the context:

        * **versions** - The versions available for this object.\
        These will be instances of the inner version class, and \
        will not have access to the fields on the base model.
        * **done_url** - The result of the `get_done_url` method.
        """
        versions = self._get_versions()
        return self.render(request, obj=self.object, versions=versions,
                           done_url=self.get_done_url())

    def revert(self, version, url):
        """
        Set the given version to be the active draft.
        This is done by calling the object's `make_draft` method.
        Logs the revert as a 'save' and messages the user.
        """
        message = "Draft replaced with %s version. This revert has not been published." % version.date_published
        version.make_draft()

        # Log action as a save
        self.log_action(self.object, CMSLog.SAVE, url=url)
        return self.write_message(message=message)

    def delete(self, version):
        """
        Deletes the given version, not the object itself.
        No log entry is generated but the user is notified
        with a message.
        """
        # Shouldn't be able to delete live or draft version
        if version.state != version.DRAFT and \
                      version.state != version.PUBLISHED:
            version.delete()
            message = "%s version deleted." % version.date_published
            return self.write_message(message=message)

    def post(self, request, *args, **kwargs):
        """
        Method for handling POST requests.
        Expects the 'vid' of the version to act on
        to be passed as in the POST variable 'version'.

        If a POST variable 'revert' is present this will
        call the revert method and then return a 'render
        redirect' to the result of the `get_done_url` method.

        If a POST variable 'delete' is present this will
        call the delete method and return a 'render redirect'
        to the result of the `get_done_url` method.

        If this method receives unexpected input, it will
        silently redirect to the result of the `get_done_url`
        method.
        """

        versions = self._get_versions()
        url = self.get_done_url()
        msg = None

        try:
            vid = int(request.POST.get('version', ''))
            version = versions.get(vid=vid)
            if request.POST.get('revert'):
                object_url = self.get_object_url()
                msg = self.revert(version, object_url)
            elif request.POST.get('delete'):
                msg = self.delete(version)
                # Delete should redirect back to itself
                url = self.request.build_absolute_uri()

        # If the give version isn't valid we'll just silently redirect
        except (ValueError, versions.model.DoesNotExist):
            pass

        return self.render(request, redirect_url=url,
                   message=msg,
                   obj=self.object,
                   collect_render_data=False)


text:
"use strict"

const dom = require('../dom.js')
const common = require('./common.js')

function createCharacterTab(object, ref) {
    var el = dom.span()

    common.nameEditor(object, el, ref)
    common.notes(object, el, ref)

    return el
}

module.exports = createCharacterTab


text:
<?php

if (!function_exists('trigger_deprecation')) {
    /**
     * Triggers a silenced deprecation notice.
     *
     * @param string $package The name of the Composer package that is triggering the deprecation
     * @param string $version The version of the package that introduced the deprecation
     * @param string $message The message of the deprecation
     * @param mixed  ...$args Values to insert in the message using printf() formatting
     *
     * @author Nicolas Grekas <p@tchwork.com>
     */
    function trigger_deprecation(string $package, string $version, string $message, mixed ...$args): void
    {
        @trigger_error(($package || $version ? "Since $package $version: " : '').($args ? vsprintf($message, $args) : $message), \E_USER_DEPRECATED);
    }
}


text:
package javax.cache.expiry;

import javax.cache.configuration.Factory;
import javax.cache.configuration.FactoryBuilder;
import java.io.Serializable;

public final class ModifiedExpiryPolicy implements ExpiryPolicy, Serializable {
    public static final long serialVersionUID = 201305101602L;

    private final Duration expiryDuration;

    public ModifiedExpiryPolicy(Duration expiryDuration) {
        this.expiryDuration = expiryDuration;
    }

    public static Factory<ExpiryPolicy> factoryOf(Duration duration) {
        return new FactoryBuilder.SingletonFactory<ExpiryPolicy>(new ModifiedExpiryPolicy(duration));
    }

    @Override
    public Duration getExpiryForCreation() {
        return expiryDuration;
    }

    @Override
    public Duration getExpiryForAccess() {
        return null;
    }

    @Override
    public Duration getExpiryForUpdate() {
        return expiryDuration;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((expiryDuration == null) ? 0 : expiryDuration.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object object) {
        if (this == object) {
            return true;
        }
        if (object == null) {
            return false;
        }
        if (!(object instanceof ModifiedExpiryPolicy)) {
            return false;
        }
        ModifiedExpiryPolicy other = (ModifiedExpiryPolicy) object;
        if (expiryDuration == null) {
            if (other.expiryDuration != null) {
                return false;
            }
        } else if (!expiryDuration.equals(other.expiryDuration)) {
            return false;
        }
        return true;
    }
}


text:
export const isPromise = (obj: any): obj is PromiseLike<unknown> =>
  !!obj &&
  (typeof obj === `object` || typeof obj === `function`) &&
  typeof obj.then === `function`

export const isRunning = (pid: number): boolean => {
  try {
    // "As a special case, a signal of 0 can be used to test for the existence of a process."
    // See https://nodejs.org/api/process.html#process_process_kill_pid_signal
    process.kill(pid, 0)
    return true
  } catch (e) {
    return false
  }
}


text:
<?php namespace Boss\Providers\Nwidart\DbExporter\Exceptions;

use Exception;

class InvalidDatabaseException extends Exception
{

}


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

namespace Cradiator.Config
{
	public interface IConfigSettings
	{
		string URL { get; set; }
		string SkinName { get; set; }
		int PollFrequency { get; set; }
		string ProjectNameRegEx { get; set; }
		bool ShowCountdown { get; set; }
		TimeSpan PollFrequencyTimeSpan { get; }
		string BrokenBuildSound { get; set; }
		string FixedBuildSound { get; set; }
		string BrokenBuildText { get; set; }
		string FixedBuildText { get; set; }
		bool PlaySounds { get; set; }
		bool PlaySpeech { get; set; }
		string SpeechVoiceName { get; set; }
		string CategoryRegEx { get; set; }
		bool ShowProgress { get; set; }
		IDictionary<string, string> UsernameMap { get; }
		GuiltStrategyType BreakerGuiltStrategy { get; }
		void AddObserver(IConfigObserver observer);
		void Load();
		void NotifyObservers();
		void Save();

	}
}


text:
[![Code Climate](https://codeclimate.com/github/kaspernj/emoji_replace/badges/gpa.svg)](https://codeclimate.com/github/kaspernj/emoji_replace)
[![Test Coverage](https://codeclimate.com/github/kaspernj/emoji_replace/badges/coverage.svg)](https://codeclimate.com/github/kaspernj/emoji_replace/coverage)
[![Build Status](https://img.shields.io/shippable/5608fd811895ca4474187ec1.svg)](https://app.shippable.com/projects/5608fd811895ca4474187ec1/builds/latest)

# EmojiReplace

A library to work around the special UTF8MB4 encoding in Ruby and Ruby on Rails.

Uses the "emoji" gem here: https://github.com/wpeterson/emoji

## Install

Add this to your Gemfile and bundle:

```ruby
gem "emoji_replace"
```

## Seamless usage

Modify your model like this:

```ruby
class Message < ActiveRecord::Base
  include EmojiReplace::Seamless
  replace_emoji_seamlessly :message
end
```

You can now call the attributes like normal:

```ruby
message.message = "I ❤ you"
message.message #=> "I ❤ you"
message.read_attribute(:message) #=> "I %{emoji:heart} you"
message.message(html: true) #=> "I <img alt=\"heart\" class=\"emoji\" src=\"http://localhost:3000/heart.png\"> you"
```

## Manual usage

If you don't want the seamless functionality, you can also perform the replace manually like this:

Replace emoji's to the code format:
```ruby
replacer = EmojiReplace::Replacer.new(text: "I ❤ you")
replacer.replace
replacer.text #=> "I %{emoji:heart} you"
```

Replace the code format back to emoji's:
```ruby
replacer = EmojiReplace::Replacer.new(text: "I %{emoji:heart} you")
replacer.back
replacer.text #=> "I ❤ you"
```

Replace the code format back to HTML:
```ruby
replacer = EmojiReplace::Replacer.new(text: "I %{emoji:heart} you")
replacer.back(html: true)
replacer.text #=> "I <img alt=\"heart\" class=\"emoji\" src=\"http://localhost:3000/heart.png\"> you"
```

## Contributing to emoji_replace

* Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet.
* Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it.
* Fork the project.
* Start a feature/bugfix branch.
* Commit and push until you are happy with your contribution.
* Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
* Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.

## Copyright

Copyright (c) 2015 kaspernj. See LICENSE.txt for
further details.


text:
lgtm,codescanning
* The `cwd` option from the `read-pkg` library is recognized as a sink for `js/tainted-path`.
  Affected packages are
    [read-pkg](https://npmjs.com/package/read-pkg)


text:
import { CONTEXT_MENU_CHANNEL, CONTEXT_MENU_CLOSE_CHANNEL, IContextMenuEvent, IContextMenuItem, IPopupOptions, ISerializableContextMenuItem } from 'vs/base/parts/contextmenu/common/contextmenu';
import { ipcRenderer } from 'vs/base/parts/sandbox/electron-sandbox/globals';

let contextMenuIdPool = 0;

export function popup(items: IContextMenuItem[], options?: IPopupOptions, onHide?: () => void): void {
	const processedItems: IContextMenuItem[] = [];

	const contextMenuId = contextMenuIdPool++;
	const onClickChannel = `vscode:onContextMenu${contextMenuId}`;
	const onClickChannelHandler = (event: unknown, itemId: number, context: IContextMenuEvent) => {
		const item = processedItems[itemId];
		item.click?.(context);
	};

	ipcRenderer.once(onClickChannel, onClickChannelHandler);
	ipcRenderer.once(CONTEXT_MENU_CLOSE_CHANNEL, (event: unknown, closedContextMenuId: number) => {
		if (closedContextMenuId !== contextMenuId) {
			return;
		}

		ipcRenderer.removeListener(onClickChannel, onClickChannelHandler);

		onHide?.();
	});

	ipcRenderer.send(CONTEXT_MENU_CHANNEL, contextMenuId, items.map(item => createItem(item, processedItems)), onClickChannel, options);
}

function createItem(item: IContextMenuItem, processedItems: IContextMenuItem[]): ISerializableContextMenuItem {
	const serializableItem: ISerializableContextMenuItem = {
		id: processedItems.length,
		label: item.label,
		type: item.type,
		accelerator: item.accelerator,
		checked: item.checked,
		enabled: typeof item.enabled === 'boolean' ? item.enabled : true,
		visible: typeof item.visible === 'boolean' ? item.visible : true
	};

	processedItems.push(item);

	// Submenu
	if (Array.isArray(item.submenu)) {
		serializableItem.submenu = item.submenu.map(submenuItem => createItem(submenuItem, processedItems));
	}

	return serializableItem;
}


text:
using System;
using QuantConnect.Data.Market;

namespace QuantConnect.Indicators.CandlestickPatterns
{
    /// <summary>
    /// Long Line Candle candlestick pattern indicator
    /// </summary>
    /// <remarks>
    /// Must have:
    /// - long real body
    /// - short upper and lower shadow
    /// The meaning of "long" and "short" is specified with SetCandleSettings
    /// The returned value is positive(+1) when white(bullish), negative(-1) when black(bearish)
    /// </remarks>
    public class LongLineCandle : CandlestickPattern
    {
        private readonly int _bodyLongAveragePeriod;
        private readonly int _shadowShortAveragePeriod;

        private decimal _bodyLongPeriodTotal;
        private decimal _shadowShortPeriodTotal;

        /// <summary>
        /// Initializes a new instance of the <see cref="LongLineCandle"/> class using the specified name.
        /// </summary>
        /// <param name="name">The name of this indicator</param>
        public LongLineCandle(string name)
            : base(name, Math.Max(CandleSettings.Get(CandleSettingType.BodyLong).AveragePeriod, CandleSettings.Get(CandleSettingType.ShadowShort).AveragePeriod) + 1)
        {
            _bodyLongAveragePeriod = CandleSettings.Get(CandleSettingType.BodyLong).AveragePeriod;
            _shadowShortAveragePeriod = CandleSettings.Get(CandleSettingType.ShadowShort).AveragePeriod;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="LongLineCandle"/> class.
        /// </summary>
        public LongLineCandle()
            : this("LONGLINECANDLE")
        {
        }

        /// <summary>
        /// Gets a flag indicating when this indicator is ready and fully initialized
        /// </summary>
        public override bool IsReady
        {
            get { return Samples >= Period; }
        }

        /// <summary>
        /// Computes the next value of this indicator from the given state
        /// </summary>
        /// <param name="window">The window of data held in this indicator</param>
        /// <param name="input">The input given to the indicator</param>
        /// <returns>A new value for this indicator</returns>
        protected override decimal ComputeNextValue(IReadOnlyWindow<TradeBar> window, TradeBar input)
        {
            if (!IsReady)
            {
                if (Samples >= Period - _bodyLongAveragePeriod)
                {
                    _bodyLongPeriodTotal += GetCandleRange(CandleSettingType.BodyLong, input);
                }

                if (Samples >= Period - _shadowShortAveragePeriod)
                {
                    _shadowShortPeriodTotal += GetCandleRange(CandleSettingType.ShadowShort, input);
                }

                return 0m;
            }

            decimal value;
            if (GetRealBody(input) > GetCandleAverage(CandleSettingType.BodyLong, _bodyLongPeriodTotal, input) &&
                GetUpperShadow(input) < GetCandleAverage(CandleSettingType.ShadowShort, _shadowShortPeriodTotal, input) &&
                GetLowerShadow(input) < GetCandleAverage(CandleSettingType.ShadowShort, _shadowShortPeriodTotal, input)
                )
                value = (int)GetCandleColor(input);
            else
                value = 0m;

            // add the current range and subtract the first range: this is done after the pattern recognition
            // when avgPeriod is not 0, that means "compare with the previous candles" (it excludes the current candle)

            _bodyLongPeriodTotal += GetCandleRange(CandleSettingType.BodyLong, input) -
                                    GetCandleRange(CandleSettingType.BodyLong, window[_bodyLongAveragePeriod]);

            _shadowShortPeriodTotal += GetCandleRange(CandleSettingType.ShadowShort, input) -
                                       GetCandleRange(CandleSettingType.ShadowShort, window[_shadowShortAveragePeriod]);

            return value;
        }

        /// <summary>
        /// Resets this indicator to its initial state
        /// </summary>
        public override void Reset()
        {
            _bodyLongPeriodTotal = 0m;
            _shadowShortPeriodTotal = 0m;
            base.Reset();
        }
    }
}


text:
namespace ash {

namespace {
UsbguardClient* g_instance = nullptr;
}  // namespace

class UsbguardClientImpl : public UsbguardClient {
 public:
  UsbguardClientImpl() = default;

  UsbguardClientImpl(const UsbguardClientImpl&) = delete;
  UsbguardClientImpl& operator=(const UsbguardClientImpl&) = delete;

  ~UsbguardClientImpl() override = default;

  // UsbguardClient:
  void AddObserver(UsbguardObserver* observer) override {
    observers_.AddObserver(observer);
  }

  // UsbguardClient:
  void RemoveObserver(UsbguardObserver* observer) override {
    observers_.RemoveObserver(observer);
  }

  // UsbguardClient:
  bool HasObserver(const UsbguardObserver* observer) const override {
    return observers_.HasObserver(observer);
  }

  void Init(dbus::Bus* bus) {
    bus_ = bus;

    usbguard_proxy_ = bus_->GetObjectProxy(
        usbguard::kUsbguardServiceName,
        dbus::ObjectPath(usbguard::kUsbguardDevicesInterfacePath));

    usbguard_proxy_->ConnectToSignal(
        usbguard::kUsbguardDevicesInterface,
        usbguard::kDevicePolicyChangedSignalName,
        base::BindRepeating(&UsbguardClientImpl::DevicePolicyChanged,
                            weak_ptr_factory_.GetWeakPtr()),
        base::BindOnce(&UsbguardClientImpl::OnSignalConnected,
                       weak_ptr_factory_.GetWeakPtr()));
  }

 private:
  // Dispatches the DevicePolicyChanged signal with signature: uuusua{ss}
  void DevicePolicyChanged(dbus::Signal* signal) {
    dbus::MessageReader signal_reader(signal);
    dbus::MessageReader array_reader(nullptr);

    uint32_t id;
    uint32_t target_old;
    uint32_t target_new;
    std::string device_rule;
    uint32_t rule_id;
    if (!signal_reader.PopUint32(&id) ||
        !signal_reader.PopUint32(&target_old) ||
        !signal_reader.PopUint32(&target_new) ||
        !signal_reader.PopString(&device_rule) ||
        !signal_reader.PopUint32(&rule_id) ||
        !signal_reader.PopArray(&array_reader)) {
      LOG(ERROR) << "Error reading signal from usbguard: "
                 << signal->ToString();
      return;
    }

    std::map<std::string, std::string> attributes;
    while (array_reader.HasMoreData()) {
      dbus::MessageReader dict_entry(nullptr);
      std::string key;
      std::string value;
      if (!array_reader.PopDictEntry(&dict_entry) ||
          !dict_entry.PopString(&key) || !dict_entry.PopString(&value)) {
        LOG(ERROR) << "Error reading array from signal from usbguard: "
                   << signal->ToString();
        return;
      }
      attributes[key] = value;
    }

    for (auto& observer : observers_) {
      observer.DevicePolicyChanged(
          id, static_cast<UsbguardObserver::Target>(target_old),
          static_cast<UsbguardObserver::Target>(target_new), device_rule,
          rule_id, attributes);
    }
  }

  // Called when the biometrics signal is initially connected.
  void OnSignalConnected(const std::string& interface_name,
                         const std::string& signal_name,
                         bool success) {
    LOG_IF(ERROR, !success)
        << "Failed to connect to usbguard signal: " << signal_name;
  }

  dbus::Bus* bus_ = nullptr;
  dbus::ObjectProxy* usbguard_proxy_ = nullptr;
  base::ObserverList<UsbguardObserver> observers_;

  // Note: This should remain the last member so it'll be destroyed and
  // invalidate its weak pointers before any other members are destroyed.
  base::WeakPtrFactory<UsbguardClientImpl> weak_ptr_factory_{this};
};

UsbguardClient::UsbguardClient() {
  DCHECK(!g_instance);
  g_instance = this;
}

UsbguardClient::~UsbguardClient() {
  DCHECK_EQ(this, g_instance);
  g_instance = nullptr;
}

// static
void UsbguardClient::Initialize(dbus::Bus* bus) {
  DCHECK(bus);
  (new UsbguardClientImpl())->Init(bus);
}

// static
void UsbguardClient::InitializeFake() {
  new FakeUsbguardClient();
}

// static
void UsbguardClient::Shutdown() {
  DCHECK(g_instance);
  delete g_instance;
}

// static
UsbguardClient* UsbguardClient::Get() {
  return g_instance;
}

}  // namespace ash


text:
/* Dynamically injected post-processing code for the API docs */

$(document).ready(function() {
  var annotations = $("dt:contains('Annotations')").next("dd").children("span.name");
  addBadges(annotations, "AlphaComponent", ":: AlphaComponent ::", 'Alpha Component');
  addBadges(annotations, "DeveloperApi", ":: DeveloperApi ::", 'Developer API');
  addBadges(annotations, "Experimental", ":: Experimental ::", 'Experimental');
});

function addBadges(allAnnotations, name, tag, html) {
  var annotations = allAnnotations.filter(":contains('" + name + "')")
  var tags = $(".cmt:contains(" + tag + ")")

  // Remove identifier tags from comments
  tags.each(function(index) {
    var oldHTML = $(this).html();
    var newHTML = oldHTML.replace(tag, "");
    $(this).html(newHTML);
  });

  // Add badges to all containers
  tags.prevAll("h4.signature")
    .add(annotations.closest("div.fullcommenttop"))
    .add(annotations.closest("div.fullcomment").prevAll("h4.signature"))
    .prepend(html);
}

$(document).ready(function() {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.async = true;
  script.onload = function(){
    MathJax.Hub.Config({
      displayAlign: "left",
      tex2jax: {
        inlineMath: [ ["$", "$"], ["\\(","\\)"] ],
        displayMath: [ ["$$","$$"], ["\\[", "\\]"] ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'a']
      }
    });
  };
  script.src = ('https:' == document.location.protocol ? 'https://' : 'http://') +
                'cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML';
  document.getElementsByTagName('head')[0].appendChild(script);
});


text:
using namespace CasaEngine;

class Character :
	public Character2DBase
{
public:
	static const int Deadzone = 20;

public:
	~Character() override;

	void Initialize() override;
	void Update(const GameTime& gameTime_) override;
	void Draw() override;

protected:
	Character(BaseEntity* pEntity);

	void CollideWith(CollisionParameters* collisionParameters, BaseEntity* otherEntity, CollisionParameters* otherCollisionParameters) override;

private:
	int m_HPMax;
	int m_HP;
	//
	int m_MPMax;
	int m_MP;
};


text:
import constants from 'namespace-constants';

export const {
    MODAL_CREATE_RECORD,
    MODAL_UPDATE_RECORD
} = constants('containers/settings/machineProfiles', [
    'MODAL_CREATE_RECORD',
    'MODAL_UPDATE_RECORD'
]);


text:
package com.netflix.spinnaker.clouddriver.cloudfoundry.deploy.ops;

import static com.netflix.spinnaker.clouddriver.cloudfoundry.deploy.ops.CloudFoundryOperationUtils.describeProcessState;
import static com.netflix.spinnaker.clouddriver.deploy.DeploymentResult.*;
import static com.netflix.spinnaker.clouddriver.deploy.DeploymentResult.Deployment.*;
import static java.util.stream.Collectors.toList;

import com.netflix.spinnaker.clouddriver.artifacts.config.ArtifactCredentials;
import com.netflix.spinnaker.clouddriver.artifacts.maven.MavenArtifactCredentials;
import com.netflix.spinnaker.clouddriver.cloudfoundry.CloudFoundryCloudProvider;
import com.netflix.spinnaker.clouddriver.cloudfoundry.artifacts.CloudFoundryArtifactCredentials;
import com.netflix.spinnaker.clouddriver.cloudfoundry.client.CloudFoundryApiException;
import com.netflix.spinnaker.clouddriver.cloudfoundry.client.CloudFoundryClient;
import com.netflix.spinnaker.clouddriver.cloudfoundry.client.model.v3.ProcessStats;
import com.netflix.spinnaker.clouddriver.cloudfoundry.deploy.CloudFoundryServerGroupNameResolver;
import com.netflix.spinnaker.clouddriver.cloudfoundry.deploy.description.DeployCloudFoundryServerGroupDescription;
import com.netflix.spinnaker.clouddriver.cloudfoundry.model.CloudFoundryOrganization;
import com.netflix.spinnaker.clouddriver.cloudfoundry.model.CloudFoundryServerGroup;
import com.netflix.spinnaker.clouddriver.cloudfoundry.model.CloudFoundrySpace;
import com.netflix.spinnaker.clouddriver.cloudfoundry.model.ServerGroupMetaDataEnvVar;
import com.netflix.spinnaker.clouddriver.deploy.DeploymentResult;
import com.netflix.spinnaker.clouddriver.helpers.OperationPoller;
import com.netflix.spinnaker.clouddriver.orchestration.AtomicOperation;
import com.netflix.spinnaker.kork.artifacts.model.Artifact;
import java.io.*;
import java.util.*;
import java.util.function.Function;
import javax.annotation.Nullable;
import lombok.Builder;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

@RequiredArgsConstructor
public class DeployCloudFoundryServerGroupAtomicOperation
    extends AbstractCloudFoundryLoadBalancerMappingOperation
    implements AtomicOperation<DeploymentResult> {
  private static final String PHASE = "DEPLOY";

  private final OperationPoller operationPoller;
  private final DeployCloudFoundryServerGroupDescription description;

  @Override
  protected String getPhase() {
    return PHASE;
  }

  @Override
  public DeploymentResult operate(List priorOutputs) {
    getTask().updateStatus(PHASE, "Deploying '" + description.getApplication() + "'");

    CloudFoundryClient client = description.getClient();

    CloudFoundryServerGroupNameResolver serverGroupNameResolver =
        new CloudFoundryServerGroupNameResolver(client, description.getSpace());

    description.setServerGroupName(
        serverGroupNameResolver.resolveNextServerGroupName(
            description.getApplication(),
            description.getStack(),
            description.getFreeFormDetails(),
            false));

    CloudFoundryServerGroup serverGroup;
    String packageId;
    // we download the package artifact first, because if this fails, we don't want to create an
    // empty CF app
    File packageArtifact = downloadPackageArtifact(description);
    try {
      serverGroup = createApplication(description);
      packageId = buildPackage(serverGroup.getId(), description, packageArtifact);
    } finally {
      if (packageArtifact != null) {
        packageArtifact.delete();
      }
    }

    buildDroplet(packageId, serverGroup.getId(), description);
    scaleApplication(serverGroup.getId(), description);
    if (description.getApplicationAttributes().getHealthCheckType() != null) {
      updateProcess(serverGroup.getId(), description);
    }

    client
        .getServiceInstances()
        .createServiceBindingsByName(
            serverGroup, description.getApplicationAttributes().getServices());

    if (!mapRoutes(
        description,
        description.getApplicationAttributes().getRoutes(),
        description.getSpace(),
        serverGroup.getId())) {
      return deploymentResult();
    }

    final int desiredInstanceCount = description.getApplicationAttributes().getInstances();
    if (description.isStartApplication() && desiredInstanceCount > 0) {
      client.getApplications().startApplication(serverGroup.getId());
      ProcessStats.State state =
          operationPoller.waitForOperation(
              () -> client.getApplications().getProcessState(serverGroup.getId()),
              inProgressState ->
                  inProgressState == ProcessStats.State.RUNNING
                      || inProgressState == ProcessStats.State.CRASHED,
              null,
              getTask(),
              description.getServerGroupName(),
              PHASE);

      if (state != ProcessStats.State.RUNNING) {
        throw new CloudFoundryApiException(
            "Failed to start '"
                + description.getServerGroupName()
                + "' which instead "
                + describeProcessState(state));
      }
    } else {
      getTask()
          .updateStatus(PHASE, "Stop state requested for '" + description.getServerGroupName());
    }

    getTask().updateStatus(PHASE, "Deployed '" + description.getApplication() + "'");

    return deploymentResult();
  }

  private DeploymentResult deploymentResult() {
    DeploymentResult deploymentResult = new DeploymentResult();
    deploymentResult.setServerGroupNames(
        Collections.singletonList(
            description.getRegion() + ":" + description.getServerGroupName()));
    deploymentResult
        .getServerGroupNameByRegion()
        .put(description.getRegion(), description.getServerGroupName());
    deploymentResult.setMessages(
        getTask().getHistory().stream()
            .map(hist -> hist.getPhase() + ":" + hist.getStatus())
            .collect(toList()));
    List<String> routes = description.getApplicationAttributes().getRoutes();
    if (routes == null) {
      routes = Collections.emptyList();
    }
    final Integer desiredInstanceCount = description.getApplicationAttributes().getInstances();
    final Deployment deployment = new Deployment();
    deployment.setCloudProvider(CloudFoundryCloudProvider.ID);
    deployment.setAccount(description.getAccountName());
    deployment.setServerGroupName(description.getServerGroupName());
    final Capacity capacity = new Capacity();
    capacity.setDesired(desiredInstanceCount);
    deployment.setCapacity(capacity);
    final Map<String, Object> metadata = new HashMap<>();
    metadata.put("env", description.getApplicationAttributes().getEnv());
    metadata.put("routes", routes);
    deployment.setMetadata(metadata);
    if (!routes.isEmpty()) {
      deployment.setLocation(routes.get(0));
    }
    deploymentResult.setDeployments(Collections.singleton(deployment));
    return deploymentResult;
  }

  private static CloudFoundryServerGroup createApplication(
      DeployCloudFoundryServerGroupDescription description) {
    CloudFoundryClient client = description.getClient();
    getTask()
        .updateStatus(
            PHASE, "Creating Cloud Foundry application '" + description.getServerGroupName() + "'");

    CloudFoundryServerGroup serverGroup =
        client
            .getApplications()
            .createApplication(
                description.getServerGroupName(),
                description.getSpace(),
                description.getApplicationAttributes().getBuildpacks(),
                getEnvironmentVars(description));
    getTask()
        .updateStatus(
            PHASE, "Created Cloud Foundry application '" + description.getServerGroupName() + "'");

    return serverGroup;
  }

  private static Map<String, String> getEnvironmentVars(
      DeployCloudFoundryServerGroupDescription description) {
    Map<String, String> environmentVars =
        Optional.ofNullable(description.getApplicationAttributes().getEnv())
            .map(HashMap::new)
            .orElse(new HashMap<>());

    final Artifact applicationArtifact = description.getApplicationArtifact();
    if (CloudFoundryArtifactCredentials.TYPE.equals(applicationArtifact.getType())) {
      CloudFoundryClient client = description.getClient();
      final CloudFoundrySpace orgAndSpaceName =
          CloudFoundrySpace.fromRegion(applicationArtifact.getLocation());
      final Optional<CloudFoundryOrganization> orgOptional =
          client.getOrganizations().findByName(orgAndSpaceName.getOrganization().getName());
      orgOptional.ifPresent(
          org -> {
            final CloudFoundrySpace space =
                client.getSpaces().findByName(org.getId(), orgAndSpaceName.getName());
            if (space != null) {
              final CloudFoundryServerGroup serverGroup =
                  client
                      .getApplications()
                      .findServerGroupByNameAndSpaceId(
                          applicationArtifact.getName(), space.getId());
              if (serverGroup != null) {
                serverGroup.getEnv().entrySet().stream()
                    .filter(e -> e.getKey().startsWith(ServerGroupMetaDataEnvVar.PREFIX))
                    .forEach(i -> environmentVars.put(i.getKey(), i.getValue().toString()));
              }
            }
          });
    }

    final ExternalReference artifactInfo = resolveArtifactInfo(description);
    artifactInfo
        .getName()
        .map(name -> environmentVars.put(ServerGroupMetaDataEnvVar.ArtifactName.envVarName, name));
    artifactInfo
        .getNumber()
        .map(
            number ->
                environmentVars.put(ServerGroupMetaDataEnvVar.ArtifactVersion.envVarName, number));
    artifactInfo
        .getUrl()
        .map(url -> environmentVars.put(ServerGroupMetaDataEnvVar.ArtifactUrl.envVarName, url));
    final ExternalReference buildInfo = resolveBuildInfo(description);
    buildInfo
        .getName()
        .map(name -> environmentVars.put(ServerGroupMetaDataEnvVar.JobName.envVarName, name));
    buildInfo
        .getNumber()
        .map(number -> environmentVars.put(ServerGroupMetaDataEnvVar.JobNumber.envVarName, number));
    buildInfo
        .getUrl()
        .map(url -> environmentVars.put(ServerGroupMetaDataEnvVar.JobUrl.envVarName, url));
    Optional.ofNullable(description.getExecutionId())
        .ifPresent(
            executionId ->
                environmentVars.put(ServerGroupMetaDataEnvVar.PipelineId.envVarName, executionId));

    return environmentVars;
  }

  private static ExternalReference resolveArtifactInfo(
      DeployCloudFoundryServerGroupDescription description) {
    return Optional.ofNullable(description.getApplicationArtifact())
        .map(
            applicationArtifact -> {
              final ExternalReference.ExternalReferenceBuilder artifactInfo =
                  ExternalReference.builder();
              if (MavenArtifactCredentials.TYPES.contains(applicationArtifact.getType())) {
                final ArtifactCredentials artifactCredentials =
                    description.getArtifactCredentials();
                artifactInfo
                    .name(artifactCredentials.resolveArtifactName(applicationArtifact))
                    .number(artifactCredentials.resolveArtifactVersion(applicationArtifact))
                    .url(Optional.ofNullable(applicationArtifact.getLocation()));
              }
              return artifactInfo.build();
            })
        .orElseGet(() -> ExternalReference.builder().build());
  }

  private static ExternalReference resolveBuildInfo(
      DeployCloudFoundryServerGroupDescription description) {
    Map<String, Object> buildInfo = null;
    final Artifact applicationArtifact = description.getApplicationArtifact();
    if (applicationArtifact != null) {
      final Map<String, Object> metadata = applicationArtifact.getMetadata();
      if (metadata != null) {
        buildInfo = (Map<String, Object>) applicationArtifact.getMetadata().get("build");
      }
    }
    if (buildInfo == null) {
      final Map<String, Object> trigger = description.getTrigger();
      if (trigger != null) {
        final String triggerType = (String) trigger.get("type");
        if (triggerType.equals("jenkins") || triggerType.equals("manual")) {
          final Map<String, Object> triggerBuildInfo =
              (Map<String, Object>) trigger.get("buildInfo");
          if (triggerBuildInfo != null) {
            buildInfo = triggerBuildInfo;
          }
        }
      }
    }
    return Optional.ofNullable(buildInfo)
        .map(
            buildInfoMap ->
                ExternalReference.builder()
                    .name(Optional.ofNullable(buildInfoMap.get("name")).map(Object::toString))
                    .number(Optional.ofNullable(buildInfoMap.get("number")).map(Object::toString))
                    .url(Optional.ofNullable(buildInfoMap.get("url")).map(Object::toString))
                    .build())
        .orElse(ExternalReference.builder().build());
  }

  @Data
  @Builder
  private static class ExternalReference {
    @Builder.Default private Optional<String> name = Optional.empty();

    @Builder.Default private Optional<String> number = Optional.empty();

    @Builder.Default private Optional<String> url = Optional.empty();
  }

  @Nullable
  private File downloadPackageArtifact(DeployCloudFoundryServerGroupDescription description) {
    File file = null;
    try {
      InputStream artifactInputStream =
          description.getArtifactCredentials().download(description.getApplicationArtifact());
      file = File.createTempFile(UUID.randomUUID().toString(), null);
      FileOutputStream fileOutputStream = new FileOutputStream(file);
      IOUtils.copy(artifactInputStream, fileOutputStream);
      fileOutputStream.close();
    } catch (IOException e) {
      if (file != null) {
        file.delete();
      }
      throw new UncheckedIOException(e);
    }
    return file;
  }

  private String buildPackage(
      String serverGroupId,
      DeployCloudFoundryServerGroupDescription description,
      File packageArtifact) {
    CloudFoundryClient client = description.getClient();
    getTask()
        .updateStatus(
            PHASE, "Creating package for application '" + description.getServerGroupName() + "'");

    String packageId = client.getApplications().createPackage(serverGroupId);
    client.getApplications().uploadPackageBits(packageId, packageArtifact);

    operationPoller.waitForOperation(
        () -> client.getApplications().packageUploadComplete(packageId),
        Function.identity(),
        null,
        getTask(),
        description.getServerGroupName(),
        PHASE);

    getTask()
        .updateStatus(
            PHASE,
            "Completed creating package for application '"
                + description.getServerGroupName()
                + "'");

    return packageId;
  }

  private void buildDroplet(
      String packageId,
      String serverGroupId,
      DeployCloudFoundryServerGroupDescription description) {
    CloudFoundryClient client = description.getClient();
    getTask().updateStatus(PHASE, "Building droplet for package '" + packageId + "'");

    String buildId = client.getApplications().createBuild(packageId);

    operationPoller.waitForOperation(
        () -> client.getApplications().buildCompleted(buildId),
        Function.identity(),
        null,
        getTask(),
        description.getServerGroupName(),
        PHASE);

    String dropletGuid = client.getApplications().findDropletGuidFromBuildId(buildId);

    client.getApplications().setCurrentDroplet(serverGroupId, dropletGuid);
    getTask().updateStatus(PHASE, "Droplet built for package '" + packageId + "'");
  }

  private void scaleApplication(
      String serverGroupId, DeployCloudFoundryServerGroupDescription description) {
    CloudFoundryClient client = description.getClient();
    getTask().updateStatus(PHASE, "Scaling application '" + description.getServerGroupName() + "'");

    Integer memoryAmount =
        convertToMb("memory", description.getApplicationAttributes().getMemory());
    Integer diskSizeAmount =
        convertToMb("disk quota", description.getApplicationAttributes().getDiskQuota());

    client
        .getApplications()
        .scaleApplication(
            serverGroupId,
            description.getApplicationAttributes().getInstances(),
            memoryAmount,
            diskSizeAmount);
    getTask().updateStatus(PHASE, "Scaled application '" + description.getServerGroupName() + "'");
  }

  private void updateProcess(
      String serverGroupId, DeployCloudFoundryServerGroupDescription description) {
    CloudFoundryClient client = description.getClient();
    getTask().updateStatus(PHASE, "Updating process '" + description.getServerGroupName() + "'");
    client
        .getApplications()
        .updateProcess(
            serverGroupId,
            null,
            description.getApplicationAttributes().getHealthCheckType(),
            description.getApplicationAttributes().getHealthCheckHttpEndpoint());
    getTask().updateStatus(PHASE, "Updated process '" + description.getServerGroupName() + "'");
  }

  // VisibleForTesting
  @Nullable
  static Integer convertToMb(String field, @Nullable String size) {
    if (size == null) {
      return null;
    } else if (StringUtils.isNumeric(size)) {
      return Integer.parseInt(size);
    } else if (size.toLowerCase().endsWith("g")) {
      String value = size.substring(0, size.length() - 1);
      if (StringUtils.isNumeric(value)) return Integer.parseInt(value) * 1024;
    } else if (size.toLowerCase().endsWith("m")) {
      String value = size.substring(0, size.length() - 1);
      if (StringUtils.isNumeric(value)) return Integer.parseInt(value);
    }

    throw new IllegalArgumentException(
        "Invalid size for application " + field + " = '" + size + "'");
  }
}


text:
CREATE TABLE IF NOT EXISTS `assets` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` char(255) NOT NULL,
  `asset_url` char(255) NOT NULL,
  `size` int(11) NOT NULL,
  `mime` char(255) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `asset_url` (`asset_url`),
  KEY `username` (`username`)
) ENGINE=MYISAM DEFAULT CHARSET=utf8;


text:
<?php

namespace FSi\Component\DataGrid;

interface DataGridFactoryInterface
{
    /**
     * Check if column is registered in factory. Column types can be registered
     * only by extensions.
     *
     * @param boolean $type
     */
    public function hasColumnType($type);

    /**
     * @throws UnexpectedTypeException if column is not registered in factory.
     * @param string $type
     */
    public function getColumnType($type);

    /**
     * Return all registered in factory DataGrid extensions as array.
     *
     * @return array
     */
    public function getExtensions();

    /**
     * Create data grid with unique name.
     *
     * @param string $name
     * @throws DataGridColumnException
     */
    public function createDataGrid($name = 'grid');

    /**
     * @return DataMapper\DataMapperInterface
     */
    public function getDataMapper();

    /**
     * @return IndexingStrategyInterface
     */
    public function getIndexingStrategy();
}