text:
<?php

namespace EllipseSynergie\ApiResponse\Laravel;

use EllipseSynergie\ApiResponse\AbstractResponse;
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Contracts\Validation\Validator;
use League\Fractal\Resource\Collection;

class Response extends AbstractResponse
{
    /**
     * @param array $array
     * @param array $headers
     * @param int $json_options @link http://php.net/manual/en/function.json-encode.php
     * @return ResponseFactory
     */
    public function withArray(array $array, array $headers = [], $json_options = 0)
    {
        return response()->json($array, $this->statusCode, $headers, $json_options);
    }

    /**
     * Respond with a paginator, and a transformer.
     *
     * @param LengthAwarePaginator $paginator
     * @param callable|\League\Fractal\TransformerAbstract $transformer
     * @param string $resourceKey
     * @param array $meta
     * @return ResponseFactory
     */
    public function withPaginator(LengthAwarePaginator $paginator, $transformer, $resourceKey = null, $meta = [])
    {
        $queryParams = array_diff_key($_GET, array_flip(['page']));
        $paginator->appends($queryParams);

        $resource = new Collection($paginator->items(), $transformer, $resourceKey);
        $resource->setPaginator(new IlluminatePaginatorAdapter($paginator));

        foreach ($meta as $metaKey => $metaValue) {
            $resource->setMetaValue($metaKey, $metaValue);
        }

        $rootScope = $this->manager->createData($resource);

        return $this->withArray($rootScope->toArray());
    }

    /**
     * Generates a Response with a 400 HTTP header and a given message from validator
     *
     * @param Validator $validator
     * @return ResponseFactory
     */
    public function errorWrongArgsValidator(Validator $validator)
    {
        return $this->errorWrongArgs($validator->getMessageBag()->toArray());
    }
}


text:
namespace elang {

//////////////////////////////////////////////////////////////////////
//
// AtomicStringFactory
//
AtomicStringFactory::AtomicStringFactory() : unique_name_counter_(0) {
}

AtomicStringFactory::~AtomicStringFactory() {
}

AtomicString* AtomicStringFactory::NewAtomicString(base::StringPiece16 string) {
  auto const it = map_.find(string);
  if (it != map_.end())
    return it->second;
  auto const atomic_string = new (zone()) AtomicString(NewString(string));
  map_[atomic_string->string()] = atomic_string;
  return atomic_string;
}

base::StringPiece16 AtomicStringFactory::NewString(
    base::StringPiece16 string_piece) {
  auto const size = string_piece.size() * sizeof(base::char16);
  auto const string = static_cast<base::char16*>(Allocate(size));
  ::memcpy(string, string_piece.data(), size);
  return base::StringPiece16(string, string_piece.size());
}

AtomicString* AtomicStringFactory::NewUniqueAtomicString(
    const base::char16* format) {
  for (;;) {
    auto const string = base::StringPrintf(format, ++unique_name_counter_);
    auto const it = map_.find(string);
    if (it == map_.end())
      return NewAtomicString(string);
  }
}

}  // namespace elang

redpajama_set_name: RedPajamaGithub


text:
:- ensure_loaded( xml_utilities ).

/* xml_pp( +XMLDocument ) "pretty prints" XMLDocument on the current
 * output stream.
 */
xml_pp( xml(Attributes, Document) ) :-
	write( 'xml( ' ), pp_attributes( Attributes, "" ), put( 0', ), nl,
	xml_pp_list( Document, "	" ),
	format( ' ).~n', [] ).
xml_pp( malformed(Attributes, Document) ) :-
	write( 'malformed( ' ), pp_attributes( Attributes, "" ), put( 0', ), nl,
	xml_pp_list( Document, "	" ),
	format( ' ).~n', [] ).

xml_pp_indented( [], Indent ) :-
	format( '~s[]', [Indent] ).
xml_pp_indented( List, Indent ) :-
	List = [_|_],
	format( '~s', [Indent] ),
	xml_pp_list( List, Indent ).
xml_pp_indented( comment(Text), Indent ) :-
	format( '~scomment(', [Indent] ), pp_string(Text), put( 0') ). %'
xml_pp_indented( namespace(URI,Prefix,Element), Indent ) :-
	format( '~snamespace( ~q, "~s",~n', [Indent,URI,Prefix] ),
	xml_pp_indented( Element, [0'	|Indent] ),
	format( '~n~s)', [[0'	|Indent]] ).
xml_pp_indented( element(Tag,Attributes,Contents), Indent ) :-
	format( '~selement( ~q,~n', [Indent,Tag] ),
	pp_attributes( Attributes, [0'	|Indent] ), put(0',), nl,
	xml_pp_list( Contents, [0'	|Indent] ), write( ' )' ). %'
xml_pp_indented( instructions(Target, Processing), Indent ) :-
	format( '~sinstructions( ~q, ', [Indent,Target] ),
	pp_string(Processing), put( 0') ). %'
xml_pp_indented( doctype(Name, DoctypeId), Indent ) :-
	format( '~sdoctype( ~q, ', [Indent,Name] ),
	xml_pp_indented( DoctypeId, [0'	|Indent] ), %'
	write( ' )' ).
xml_pp_indented( cdata(CData), Indent ) :-
	format( '~scdata(', [Indent] ), pp_string(CData), put( 0') ). %'
xml_pp_indented( pcdata(PCData), Indent ) :-
	format( '~spcdata(', [Indent] ), pp_string(PCData), put( 0') ). %'
xml_pp_indented( public(URN,URL), _Indent ) :-
	format( 'public( "~s", "~s" )', [URN,URL] ).
xml_pp_indented( public(URN,URL,Literals), Indent ) :-
	format( 'public( "~s", "~s",~n', [URN,URL] ),
	xml_pp_list( Literals, [0'	|Indent] ), write( ' )' ). %'
xml_pp_indented( system(URL), _Indent ) :-
	format( 'system( "~s" )', [URL] ).
xml_pp_indented( system(URL,Literals), Indent ) :-
	format( 'system( "~s",~n', [URL] ),
	xml_pp_list( Literals, [0'	|Indent] ), write( ' )' ). %'
xml_pp_indented( local, _Indent ) :-
	write( local ).
xml_pp_indented( local(Literals), Indent ) :-
	write( 'local(' ), nl,
	xml_pp_list( Literals, [0'	|Indent] ), write( ' )' ). %'
xml_pp_indented( dtd_literal(String), Indent ) :-
	format( '~sdtd_literal(', [Indent] ), pp_string(String), put( 0') ). %'
xml_pp_indented( out_of_context(Tag), Indent ) :-
	format( '~s/* SYNTAX ERROR */ out_of_context( ~q )', [Indent,Tag] ).
xml_pp_indented( unparsed(String), Indent ) :-
	format( '~s/* SYNTAX ERROR */ unparsed( ', [Indent] ),
	pp_string(String), put( 0') ). %'

xml_pp_list( [], Indent ) :-
	format( '~s[]', [Indent] ).
xml_pp_list( [H|T], Indent ) :-
	format( '~s[~n', [Indent] ),
	xml_pp_indented( H, Indent ),
	xml_pp_list1( T, Indent ),
	format( '~s]', [Indent] ).

xml_pp_list1( [], _Indent ) :-
	nl.
xml_pp_list1( [H|T], Indent ) :-
	put( 0', ), nl, %'
	xml_pp_indented( H, Indent ),
	xml_pp_list1( T, Indent ).

pp_attributes( [], Indent ) :-
	format( '~s[]', [Indent] ).
pp_attributes( [Attribute|Attributes], Indent ) :-
	format( '~s[', [Indent] ),
	pp_attributes1( Attributes, Attribute ),
	put( 0'] ). %'

pp_attributes1( [], Name=Value ) :-
	pp_name( Name ), pp_string( Value ).
pp_attributes1( [H|T], Name=Value ) :-
	pp_name( Name ), pp_string( Value ), write( ', ' ),
	pp_attributes1( T, H ).

pp_name( Name ) :-
	( possible_operator( Name ) ->
		format( '(~w)=', [Name] )
	; otherwise ->
		format( '~q=', [Name] )
	).

possible_operator( (abolish) ).
possible_operator( (attribute) ).
possible_operator( (check_advice) ).
possible_operator( (compile_command) ).
possible_operator( (delay) ).
possible_operator( (demon) ).
possible_operator( (discontiguous) ).
possible_operator( (div) ).
possible_operator( (do) ).
possible_operator( (document_export) ).
possible_operator( (document_import) ).
possible_operator( (dy) ).
possible_operator( (dynamic) ).
possible_operator( (edb) ).
possible_operator( (eexport) ).
possible_operator( (else) ).
possible_operator( (except) ).
possible_operator( (export) ).
possible_operator( (foreign_pred) ).
possible_operator( (from) ).
possible_operator( (from_chars) ).
possible_operator( (from_file) ).
possible_operator( (from_stream) ).
possible_operator( (global) ).
possible_operator( (help) ).
possible_operator( (hilog) ).
possible_operator( (if) ).
possible_operator( (import) ).
possible_operator( (index) ).
possible_operator( (initialization) ).
possible_operator( (is) ).
possible_operator( (listing) ).
possible_operator( (local) ).
possible_operator( (locked) ).
possible_operator( (meta_predicate) ).
possible_operator( (mod) ).
possible_operator( (mode) ).
possible_operator( (module_transparent) ).
possible_operator( (multifile) ).
possible_operator( (namic) ).
possible_operator( (nocheck_advice) ).
possible_operator( (nospy) ).
possible_operator( (not) ).
possible_operator( (of) ).
possible_operator( (once) ).
possible_operator( (onto_chars) ).
possible_operator( (onto_file) ).
possible_operator( (onto_stream) ).
possible_operator( (parallel) ).
possible_operator( (public) ).
possible_operator( (r) ).
possible_operator( (rem) ).
possible_operator( (skipped) ).
possible_operator( (spy) ).
possible_operator( (table) ).
possible_operator( (then) ).
possible_operator( (thread_local) ).
possible_operator( (ti) ).
possible_operator( (ti_off) ).
possible_operator( (traceable) ).
possible_operator( (unskipped) ).
possible_operator( (untraceable) ).
possible_operator( (use_subsumptive_tabling) ).
possible_operator( (use_variant_tabling) ).
possible_operator( (volatile) ).
possible_operator( (with) ).
possible_operator( (with_input_from_chars) ).
possible_operator( (with_output_to_chars) ).
possible_operator( (xor) ).


text:
'use strict';

import * as customFunctions from '../../shared/methods/common-functions.js';

const createEventRESTResource = (app) => {

	app.factory('createEventRESTResource', ['$http', ($http) => {

		return (resourceName, callback) => {
			return {
				getAllEvents: (callback) => {
					$http.get('/api/allevents')
					.then(function successCallback(data){
						callback(null, data)
					}, function errorCallback(data){
						callback(data)
					})
				},
				getAllSpeakers: (callback) => {
					$http.get('/api/speakers')
					.then(function successCallback(data){
						callback(null, data)
					}, function errorCallback(data){
						callback(data)
					})
				},
				createEvent: (resourceData, callback) => {
          $http.post('/api/createevent', resourceData)
		  			.then(function successCallback(data){
						callback(null, data)
					}, function errorCallback(data){
						callback(data)
					})

        	}
			}

		}

	}])
}

module.exports = createEventRESTResource;


text:
(function() {

    tinymce.create('tinymce.plugins.AnyFontPlugin', {
		/**
		 * Initializes the plugin
		 *
		 * @param {tinymce.Editor} ed Editor instance that the plugin is initialized in.
		 * @param {string} url Absolute URL to where the plugin is located.
		 */
		init : function(ed, url) {
// 			console.log(ed);
			// Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('mceExample');
			AF_Data.url = url;

			ed.addCommand('mceAnyFont', function() {
				var title = document.getElementById('title').value;
				ed.windowManager.open({
					file : url + '/dialog.php?text='+escape(ed.selection.getContent({format : 'text'})),
					width : 400,
					height : 145,
					inline : 1
				}, {
					plugin_url : url,
					postTitle: title
				});
			});

			// Register button
// 			ed.addButton('anyfont', {
// 				title : "Insert text using AnyFont styles",
// 				cmd : 'mceAnyFont',
// 				image : url + '/insert-text.gif'
// 			});

			ed.addCommand('mcesetFont', function(v) {
				tinyMCE.activeEditor.contentDocument.head.innerHTML+='<link rel="stylesheet" href="/af-css/'+v+'.css" type="text/css" media="all">';
				tinyMCE.execCommand('mceInsertContent', false, ''+tinyMCE.activeEditor.selection.getContent({format : 'text'})+'');

			});

// 			ed.addButton('fontlist', {
// 				title : "Change highlighted text to selected font.",
// 				cmd : 'mceAnyFontList',
// 				image : url + '/insert-text.gif'
// 			});

			// Add a node change handler, selects the button in the UI when a image is selected
// 			ed.onNodeChange.add(function(ed, cm, n) {
// 				cm.setActive('anyfont', n.nodeName == 'IMG');
// 			});
		},

		createControl: function(n, cm) {

			switch (n) {
// 				case 'fontlist':
// 					AF_Data.listbox = cm.createListBox('fontlist', {
// 						title : 'Select font',
// 						onselect : function(v) {
// 							tinyMCE.activeEditor.contentDocument.head.innerHTML+='<link rel="stylesheet" href="/af-css/'+v+'.css" type="text/css" media="all">';
// 							tinyMCE.execCommand('mceInsertContent', false, ''+tinyMCE.activeEditor.selection.getContent({format : 'text'})+'');
// // 							tinyMCE.activeEditor.windowManager.alert('Text selected:' +$('content_fontlist_text').innerHTML );
// 						}
// // 						onChange: function(v){
// // 							console.log("change1: "+v);
// // 						}
// 					});
// 					var fontarray = Object.keys(AF_Data.fontlist);
// 					fontarray.each(function(font){
// 						if(AF_Data.fontlist[font].webfont == 'Yes'){
// 							AF_Data.listbox.add(AF_Data.fontlist[font].preview_img, AF_Data.fontlist[font].name);
// 						}
// 					});
// 					AF_Data.listbox.onChange.add(function(){
// 							tinyMCE.activeEditor.windowManager.alert('Change detected:');
// 						})
// // 					mlb.OnRender = function(e){
// //
// // 						console.log(e);
// // 					}
//
// 					// Add some values to the list box
// // 					mlb.add('Some item 1', 'val1');
// // 					mlb.add('some item 2', 'val2');
// // 					mlb.add('some item 3', 'val3');
//
// 					// Return the new listbox instance
// 					return AF_Data.listbox;
				case 'anyfont':
					AF_Data.anyfont = cm.createSplitButton('anyfont', {
						title : 'Select font',
						image : AF_Data.url + '/insert-text.gif',
						onclick : function() {
							tinyMCE.execCommand('mceAnyFont');
						},
						icons:true
					});

                AF_Data.anyfont.onRenderMenu.add(function(c, m) {
					var fontarray = Object.keys(AF_Data.fontlist);
					fontarray.each(function(font){
						if(AF_Data.fontlist[font].webfont == 'Yes'){
							m.add({
								icon:AF_Data.fontlist[font].class_name,
								title:font,//AF_Data.fontlist[font].image,
								onclick : function() {
									tinyMCE.execCommand('mcesetFont', font);
								}
							});
						}
					});
//                     m.add({title : 'Some title', 'class' : 'mceMenuItemTitle'}).setDisabled(1);
//
//                     m.add({title : 'Some item 1', onclick : function() {
//                         tinyMCE.activeEditor.windowManager.alert('Some  item 1 was clicked.');
//                     }});
//
//                     m.add({title : 'Some item 2', onclick : function() {
//                         tinyMCE.activeEditor.windowManager.alert('Some  item 2 was clicked.');
//                     }});
                });

                // Return the new splitbutton instance
                return AF_Data.anyfont;
//         }

// 				case 'stylelist':
// 					var mlb = cm.createListBox('stylelist', {
// 						title : 'Select Style',
// 						onselect : function(v) {
// 							tinyMCE.activeEditor.windowManager.alert('Value selected:' + v);
// 						}
// 					});
// // 					console.log(mlb);
// 					// Add some values to the list box
// 					mlb.add('Some item 1', 'val1');
// 					mlb.add('some item 2', 'val2');
// 					mlb.add('some item 3', 'val3');
//
// 					// Return the new listbox instance
// 					return mlb;
			}

			return null;
		},
		/**
		 * @return {Object} Name/value array containing information about the plugin.
		 */
		getInfo : function() {
			return {
				longname : 'AnyFont plugin',
				author : 'Ryan Peel',
				authorurl : 'http://2amlife.com',
				infourl : 'http://2amlife.com/projects/anyfont',
				version : "1.0"
			};
		}
	});

	tinymce.PluginManager.add('anyfont', tinymce.plugins.AnyFontPlugin);
})();


text:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#include <cvode/cvode.h>                     /* prototypes for CVODE fcts., consts.  */
#include <nvector/nvector_serial.h>          /* access to serial N_Vector            */
#include <sunmatrix/sunmatrix_band.h>        /* access to band SUNMatrix             */
#include <sunlinsol/sunlinsol_lapackband.h>  /* access to band SUNLinearSolver       */
#include <sundials/sundials_types.h>         /* definition of type realtype          */
#include <sundials/sundials_math.h>          /* definition of ABS and EXP            */

/* Problem Constants */

#define XMAX  RCONST(2.0)    /* domain boundaries         */
#define YMAX  RCONST(1.0)
#define MX    10             /* mesh dimensions           */
#define MY    5
#define NEQ   MX*MY          /* number of equations       */
#define ATOL  RCONST(1.0e-5) /* scalar absolute tolerance */
#define T0    RCONST(0.0)    /* initial time              */
#define T1    RCONST(0.1)    /* first output time         */
#define DTOUT RCONST(0.1)    /* output time increment     */
#define NOUT  10             /* number of output times    */

#define ZERO RCONST(0.0)
#define HALF RCONST(0.5)
#define ONE  RCONST(1.0)
#define TWO  RCONST(2.0)
#define FIVE RCONST(5.0)

/* User-defined vector access macro IJth */

/* IJth is defined in order to isolate the translation from the
   mathematical 2-dimensional structure of the dependent variable vector
   to the underlying 1-dimensional storage.
   IJth(vdata,i,j) references the element in the vdata array for
   u at mesh point (i,j), where 1 <= i <= MX, 1 <= j <= MY.
   The vdata array is obtained via the call vdata = N_VGetArrayPointer(v),
   where v is an N_Vector.
   The variables are ordered by the y index j, then by the x index i. */

#define IJth(vdata,i,j) (vdata[(j-1) + (i-1)*MY])

/* Type : UserData (contains grid constants) */

typedef struct {
  realtype dx, dy, hdcoef, hacoef, vdcoef;
} *UserData;

/* Private Helper Functions */

static void SetIC(N_Vector u, UserData data);
static void PrintHeader(realtype reltol, realtype abstol, realtype umax);
static void PrintOutput(realtype t, realtype umax, long int nst);
static void PrintFinalStats(void *cvode_mem);

/* Private function to check function return values */

static int check_retval(void *returnvalue, const char *funcname, int opt);

/* Functions Called by the Solver */

static int f(realtype t, N_Vector u, N_Vector udot, void *user_data);
static int Jac(realtype t, N_Vector u, N_Vector fu,
               SUNMatrix J, void *user_data,
               N_Vector tmp1, N_Vector tmp2, N_Vector tmp3);

/*
 *-------------------------------
 * Main Program
 *-------------------------------
 */

int main(void)
{
  realtype dx, dy, reltol, abstol, t, tout, umax;
  N_Vector u;
  UserData data;
  SUNMatrix A;
  SUNLinearSolver LS;
  void *cvode_mem;
  int iout, retval;
  long int nst;

  u = NULL;
  data = NULL;
  A = NULL;
  LS = NULL;
  cvode_mem = NULL;

  /* Create a serial vector */

  u = N_VNew_Serial(NEQ);  /* Allocate u vector */
  if(check_retval((void*)u, "N_VNew_Serial", 0)) return(1);

  reltol = ZERO;  /* Set the tolerances */
  abstol = ATOL;

  data = (UserData) malloc(sizeof *data);  /* Allocate data memory */
  if(check_retval((void *)data, "malloc", 2)) return(1);
  dx = data->dx = XMAX/(MX+1);  /* Set grid coefficients in data */
  dy = data->dy = YMAX/(MY+1);
  data->hdcoef = ONE/(dx*dx);
  data->hacoef = HALF/(TWO*dx);
  data->vdcoef = ONE/(dy*dy);

  SetIC(u, data);  /* Initialize u vector */

  /* Call CVodeCreate to create the solver memory and specify the
   * Backward Differentiation Formula */
  cvode_mem = CVodeCreate(CV_BDF);
  if(check_retval((void *)cvode_mem, "CVodeCreate", 0)) return(1);

  /* Call CVodeInit to initialize the integrator memory and specify the
   * user's right hand side function in u'=f(t,u), the inital time T0, and
   * the initial dependent variable vector u. */
  retval = CVodeInit(cvode_mem, f, T0, u);
  if(check_retval(&retval, "CVodeInit", 1)) return(1);

  /* Call CVodeSStolerances to specify the scalar relative tolerance
   * and scalar absolute tolerance */
  retval = CVodeSStolerances(cvode_mem, reltol, abstol);
  if (check_retval(&retval, "CVodeSStolerances", 1)) return(1);

  /* Set the pointer to user-defined data */
  retval = CVodeSetUserData(cvode_mem, data);
  if(check_retval(&retval, "CVodeSetUserData", 1)) return(1);

  /* Create banded SUNMatrix for use in linear solves -- since this will be factored,
     set the storage bandwidth to be the sum of upper and lower bandwidths */
  A = SUNBandMatrix(NEQ, MY, MY);
  if(check_retval((void *)A, "SUNBandMatrix", 0)) return(1);

  /* Create SUNLinSol_LapackBand solver object for use by CVode */
  LS = SUNLinSol_LapackBand(u, A);
  if(check_retval((void *)LS, "SUNLinSol_LapackBand", 0)) return(1);

  /* Call CVodeSetLinearSolver to attach the matrix and linear solver to CVode */
  retval = CVodeSetLinearSolver(cvode_mem, LS, A);
  if(check_retval(&retval, "CVodeSetLinearSolver", 1)) return(1);

  /* Set the user-supplied Jacobian routine Jac */
  retval = CVodeSetJacFn(cvode_mem, Jac);
  if(check_retval(&retval, "CVodeSetJacFn", 1)) return(1);

  /* In loop over output points: call CVode, print results, test for errors */

  umax = N_VMaxNorm(u);
  PrintHeader(reltol, abstol, umax);
  for(iout=1, tout=T1; iout <= NOUT; iout++, tout += DTOUT) {
    retval = CVode(cvode_mem, tout, u, &t, CV_NORMAL);
    if(check_retval(&retval, "CVode", 1)) break;
    umax = N_VMaxNorm(u);
    retval = CVodeGetNumSteps(cvode_mem, &nst);
    check_retval(&retval, "CVodeGetNumSteps", 1);
    PrintOutput(t, umax, nst);
  }

  PrintFinalStats(cvode_mem);  /* Print some final statistics   */

  N_VDestroy(u);          /* Free the u vector */
  CVodeFree(&cvode_mem);  /* Free the integrator memory */
  free(data);             /* Free the user data */

  return(0);
}

/*
 *-------------------------------
 * Functions called by the solver
 *-------------------------------
 */

/* f routine. Compute f(t,u). */

static int f(realtype t, N_Vector u,N_Vector udot, void *user_data)
{
  realtype uij, udn, uup, ult, urt, hordc, horac, verdc, hdiff, hadv, vdiff;
  realtype *udata, *dudata;
  int i, j;
  UserData data;

  udata  = N_VGetArrayPointer(u);
  dudata = N_VGetArrayPointer(udot);

  /* Extract needed constants from data */

  data = (UserData) user_data;
  hordc = data->hdcoef;
  horac = data->hacoef;
  verdc = data->vdcoef;

  /* Loop over all grid points. */

  for (j=1; j <= MY; j++) {

    for (i=1; i <= MX; i++) {

      /* Extract u at x_i, y_j and four neighboring points */

      uij = IJth(udata, i, j);
      udn = (j == 1)  ? ZERO : IJth(udata, i, j-1);
      uup = (j == MY) ? ZERO : IJth(udata, i, j+1);
      ult = (i == 1)  ? ZERO : IJth(udata, i-1, j);
      urt = (i == MX) ? ZERO : IJth(udata, i+1, j);

      /* Set diffusion and advection terms and load into udot */

      hdiff = hordc*(ult - TWO*uij + urt);
      hadv = horac*(urt - ult);
      vdiff = verdc*(uup - TWO*uij + udn);
      IJth(dudata, i, j) = hdiff + hadv + vdiff;
    }
  }

  return(0);
}

/* Jacobian routine. Compute J(t,u). */

static int Jac(realtype t, N_Vector u, N_Vector fu,
               SUNMatrix J, void *user_data,
               N_Vector tmp1, N_Vector tmp2, N_Vector tmp3)
{
  int i, j, k;
  realtype *kthCol, hordc, horac, verdc;
  UserData data;

  /*
   * The components of f = udot that depend on u(i,j) are
   * f(i,j), f(i-1,j), f(i+1,j), f(i,j-1), f(i,j+1), with
   *   df(i,j)/du(i,j) = -2 (1/dx^2 + 1/dy^2)
   *   df(i-1,j)/du(i,j) = 1/dx^2 + .25/dx  (if i > 1)
   *   df(i+1,j)/du(i,j) = 1/dx^2 - .25/dx  (if i < MX)
   *   df(i,j-1)/du(i,j) = 1/dy^2           (if j > 1)
   *   df(i,j+1)/du(i,j) = 1/dy^2           (if j < MY)
   */

  data = (UserData) user_data;
  hordc = data->hdcoef;
  horac = data->hacoef;
  verdc = data->vdcoef;

  /* set non-zero Jacobian entries */
  for (j=1; j <= MY; j++) {
    for (i=1; i <= MX; i++) {
      k = j-1 + (i-1)*MY;
      kthCol = SUNBandMatrix_Column(J,k);

      /* set the kth column of J */

      SM_COLUMN_ELEMENT_B(kthCol,k,k) = -TWO*(verdc+hordc);
      if (i != 1)  SM_COLUMN_ELEMENT_B(kthCol,k-MY,k) = hordc + horac;
      if (i != MX) SM_COLUMN_ELEMENT_B(kthCol,k+MY,k) = hordc - horac;
      if (j != 1)  SM_COLUMN_ELEMENT_B(kthCol,k-1,k)  = verdc;
      if (j != MY) SM_COLUMN_ELEMENT_B(kthCol,k+1,k)  = verdc;
    }
  }

  return(0);
}

/*
 *-------------------------------
 * Private helper functions
 *-------------------------------
 */

/* Set initial conditions in u vector */

static void SetIC(N_Vector u, UserData data)
{
  int i, j;
  realtype x, y, dx, dy;
  realtype *udata;

  /* Extract needed constants from data */

  dx = data->dx;
  dy = data->dy;

  /* Set pointer to data array in vector u. */

  udata = N_VGetArrayPointer(u);

  /* Load initial profile into u vector */

  for (j=1; j <= MY; j++) {
    y = j*dy;
    for (i=1; i <= MX; i++) {
      x = i*dx;
      IJth(udata,i,j) = x*(XMAX - x)*y*(YMAX - y)*SUNRexp(FIVE*x*y);
    }
  }
}

/* Print first lines of output (problem description) */

static void PrintHeader(realtype reltol, realtype abstol, realtype umax)
{
  printf("\n2-D Advection-Diffusion Equation\n");
  printf("Mesh dimensions = %d X %d\n", MX, MY);
  printf("Total system size = %d\n", NEQ);
#if defined(SUNDIALS_EXTENDED_PRECISION)
  printf("Tolerance parameters: reltol = %Lg   abstol = %Lg\n\n", reltol, abstol);
  printf("At t = %Lg      max.norm(u) =%14.6Le \n", T0, umax);
#elif defined(SUNDIALS_DOUBLE_PRECISION)
  printf("Tolerance parameters: reltol = %g   abstol = %g\n\n", reltol, abstol);
  printf("At t = %g      max.norm(u) =%14.6e \n", T0, umax);
#else
  printf("Tolerance parameters: reltol = %g   abstol = %g\n\n", reltol, abstol);
  printf("At t = %g      max.norm(u) =%14.6e \n", T0, umax);
#endif

  return;
}

/* Print current value */

static void PrintOutput(realtype t, realtype umax, long int nst)
{
#if defined(SUNDIALS_EXTENDED_PRECISION)
  printf("At t = %4.2Lf   max.norm(u) =%14.6Le   nst = %4ld\n", t, umax, nst);
#elif defined(SUNDIALS_DOUBLE_PRECISION)
  printf("At t = %4.2f   max.norm(u) =%14.6e   nst = %4ld\n", t, umax, nst);
#else
  printf("At t = %4.2f   max.norm(u) =%14.6e   nst = %4ld\n", t, umax, nst);
#endif

  return;
}

/* Get and print some final statistics */

static void PrintFinalStats(void *cvode_mem)
{
  int retval;
  long int nst, nfe, nsetups, netf, nni, ncfn, nje, nfeLS;

  retval = CVodeGetNumSteps(cvode_mem, &nst);
  check_retval(&retval, "CVodeGetNumSteps", 1);
  retval = CVodeGetNumRhsEvals(cvode_mem, &nfe);
  check_retval(&retval, "CVodeGetNumRhsEvals", 1);
  retval = CVodeGetNumLinSolvSetups(cvode_mem, &nsetups);
  check_retval(&retval, "CVodeGetNumLinSolvSetups", 1);
  retval = CVodeGetNumErrTestFails(cvode_mem, &netf);
  check_retval(&retval, "CVodeGetNumErrTestFails", 1);
  retval = CVodeGetNumNonlinSolvIters(cvode_mem, &nni);
  check_retval(&retval, "CVodeGetNumNonlinSolvIters", 1);
  retval = CVodeGetNumNonlinSolvConvFails(cvode_mem, &ncfn);
  check_retval(&retval, "CVodeGetNumNonlinSolvConvFails", 1);

  retval = CVodeGetNumJacEvals(cvode_mem, &nje);
  check_retval(&retval, "CVodeGetNumJacEvals", 1);
  retval = CVodeGetNumLinRhsEvals(cvode_mem, &nfeLS);
  check_retval(&retval, "CVodeGetNumLinRhsEvals", 1);

  printf("\nFinal Statistics:\n");
  printf("nst = %-6ld nfe  = %-6ld nsetups = %-6ld nfeLS = %-6ld nje = %ld\n",
	 nst, nfe, nsetups, nfeLS, nje);
  printf("nni = %-6ld ncfn = %-6ld netf = %ld\n",
	 nni, ncfn, netf);

  return;
}

/* Check function return value...
     opt == 0 means SUNDIALS function allocates memory so check if
              returned NULL pointer
     opt == 1 means SUNDIALS function returns an integer value so check if
              retval < 0
     opt == 2 means function allocates memory so check if returned
              NULL pointer */

static int check_retval(void *returnvalue, const char *funcname, int opt)
{
  int *retval;

  /* Check if SUNDIALS function returned NULL pointer - no memory allocated */

  if (opt == 0 && returnvalue == NULL) {
    fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed - returned NULL pointer\n\n",
            funcname);
    return(1); }

  /* Check if retval < 0 */

  else if (opt == 1) {
    retval = (int *) returnvalue;
    if (*retval < 0) {
      fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed with retval = %d\n\n",
              funcname, *retval);
      return(1); }}

  /* Check if function returned NULL pointer - no memory allocated */

  else if (opt == 2 && returnvalue == NULL) {
    fprintf(stderr, "\nMEMORY_ERROR: %s() failed - returned NULL pointer\n\n",
            funcname);
    return(1); }

  return(0);
}


text:
/**
 * Defines the color for a value of the chart
 */
export type OColorData = {
  value: string;
  color: string;
};


text:
The foundation of modern advanced websites.

## Samples
Here is a description for each sample:

* [layers1](samples/layers1.html) - layer one div on top of another
* [polymer/](polymer/) - folder of polymer examples

## Tutorials
The following articles were referenced:

* [css layering](http://www.barelyfitz.com/screencast/html-training/css/positioning/)

## Design
Good web design is a large topic in itself. Here are some high level sub-topics:

* [Responsive Design](http://www.w3schools.com/html/html_responsive.asp) - W3schools responsive design tutorials
* [Responsive Design Example](http://johnpolacek.github.io/scrolldeck.js/decks/responsive/) - responsive design example and description
* [Progressive Design](http://www.webdesignerdepot.com/2015/08/progressive-design-for-the-modern-web/)
* [Atomic Design](http://atomicdesign.bradfrost.com/chapter-2/#atomic-design-is-for-user-interfaces)


text:
package elec

import (
	"context"
	"net/url"
	"strconv"

	"go-common/app/interface/main/app-view/conf"
	"go-common/app/interface/main/app-view/model/elec"
	"go-common/library/ecode"
	httpx "go-common/library/net/http/blademaster"
	"go-common/library/net/metadata"

	"github.com/pkg/errors"
)

const (
	_elec          = "/api/elec/info/query"
	_elecTotal     = "/api/v2/rank/total/av/query"
	_elecMonthRank = "1"
)

// Dao is elec dao.
type Dao struct {
	client    *httpx.Client
	elec      string
	elecTotal string
}

// New elec dao
func New(c *conf.Config) (d *Dao) {
	d = &Dao{
		client:    httpx.NewClient(c.HTTPClient),
		elec:      c.Host.Elec + _elec,
		elecTotal: c.Host.Elec + _elecTotal,
	}
	return
}

// TotalInfo mid+aid total elec info
func (d *Dao) TotalInfo(c context.Context, mid int64, aid int64) (data *elec.Info, err error) {
	params := url.Values{}
	params.Set("mid", strconv.FormatInt(mid, 10))
	params.Set("av_no", strconv.FormatInt(aid, 10))
	var res struct {
		Code int        `json:"code"`
		Data *elec.Info `json:"data"`
	}
	if err = d.client.Get(c, d.elecTotal, "", params, &res); err != nil {
		return
	}
	if res.Code != ecode.OK.Code() {
		err = errors.Wrap(ecode.Int(res.Code), d.elecTotal+"?"+params.Encode())
		return
	}
	data = res.Data
	return
}

// Info elec info
func (d *Dao) Info(c context.Context, mid, paymid int64) (data *elec.Info, err error) {
	ip := metadata.String(c, metadata.RemoteIP)
	params := url.Values{}
	params.Set("mid", strconv.FormatInt(mid, 10))
	if paymid > 0 {
		params.Set("pay_mid", strconv.FormatInt(paymid, 10))
	}
	params.Set("type", _elecMonthRank)
	var res struct {
		Code int        `json:"code"`
		Data *elec.Info `json:"data"`
	}
	if err = d.client.Get(c, d.elec, ip, params, &res); err != nil {
		return
	}
	if res.Code != ecode.OK.Code() {
		if res.Code == 500011 {
			return
		}
		err = errors.Wrap(ecode.Int(res.Code), d.elec+"?"+params.Encode())
		return
	}
	data = res.Data
	return
}


text:
package net.jueb.util4j.test.classLoader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * 自定义类加载器
 * @author Administrator
 *注意:
 *1.className和对应编译的.class文件的类名称必须一致,不然会出现:java.lang.NoClassDefFoundError: test/H1 (wrong name: test/H2)
 *只有被定义过的类才能被加载
 */
public class MyClassLoder extends ClassLoader {

    public MyClassLoder() throws IOException {
		super(null);
	}

	/**
	 * @param  classNames-(二进制名称)有效类名称的示例包括: "java.lang.String"
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public void defineClassByDir(String basedir,String[] classNames) throws IOException
	{
		for (int i = 0; i < classNames.length; i++)
		{
			defineClassByDir(basedir,classNames[i]);
        }
	}
	/**
	 * 根据类名在基本目录中加载class文件
	 * @param className-(二进制名称)有效类名称的示例包括: "java.lang.String"
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public Class<?> defineClassByDir(String basedir,String className) throws IOException
	{
        Class<?> cls = null;
        StringBuffer sb = new StringBuffer(basedir);
        String classFname = className.replace('.', File.separatorChar) + ".class";
        sb.append(File.separator + classFname);
        File classFile = new File(sb.toString());
        cls = defineClassByFile(className,classFile);
        return cls;
    }

	/**
	 * 将一个 classFile读取的byte 数组转换为 Class 类的实例。
	 * @param className-(二进制名称)有效类名称的示例包括: "java.lang.String"
	 * @param classFile class文件
	 * @return
	 * @throws IOException
	 */
	private Class<?> defineClassByFile(String className,File classFile) throws IOException
	{
		FileInputStream fis=new FileInputStream(classFile);
		long len=classFile.length();
        byte[] raw = new byte[(int) len];
        fis.read(raw);
        fis.close();
        return defineClassByBytes(className, raw);
    }

	/**
	 * 根据字节数组定义一个class对象,成功则记录
	 * @param className
	 * @param raw
	 * @return
	 */
	private Class<?> defineClassByBytes(String className,byte[] raw)
	{
		System.out.println("InputStream:"+getResource(className));

		Class<?> cls = null;
		cls=defineClass(className,raw,0,raw.length);
		if(cls!=null)
		{
			System.out.println("Class:"+className+"被定义!");
		}
		return cls;
	}

	/**
	 * 只有先执行了类的定义,才能加载到该类
	 * 使用二进制名称的className加载类
	 * 父类的loadClass(String name)方法要调用该方法
	 * className-(二进制名称)有效类名称的示例包括: "java.lang.String"
	 */
	@Override
	protected Class<?> loadClass(String className, boolean resolve) throws ClassNotFoundException {
        System.out.println("开始加载类:"+className);
		Class<?> clazz=null;
		if(className.startsWith("java.")||className.startsWith("javax."))
		{//如果是系统类加载器
			System.out.println("交给系统类加载器加载:"+className);
//			clazz=super.loadClass(name);
			clazz=findSystemClass(className);
			if (clazz != null)
			{//解析类结构
				if (resolve)
					resolveClass(clazz);
				return (clazz);
			}
			return clazz;
		}
		if(clazz==null)
		{
			System.out.println("交给当前类加载器加载:"+className);
			clazz=findLoadedClass(className);
			if (clazz != null)
			{//解析类结构
				if (resolve)
				{
					resolveClass(clazz);
				}
			}
		}
		if(clazz==null)
		{
			System.out.println("交给当前类加载器定义:"+className);
			clazz=findClass(className);
		}
		System.out.println("类:"+clazz+"被"+clazz.getClassLoader()+"成功加载!");
		return clazz;
    }

	@Override
	protected Class<?> findClass(String className) throws ClassNotFoundException {
		System.out.println("当前类加载器classpath中查找并定义类:"+className);
		Class<?> clazz=null;
		byte[] bytes=findClassFileBytes(className);
		if(bytes!=null)
		{
			clazz=defineClass(className,bytes, 0, bytes.length);
		}
		if(clazz==null)
		{
			throw new ClassNotFoundException();
		}
		return clazz;
	}

	/**
	 * 根据类名获取类文件字节
	 * @param className
	 * @return
	 */
	public byte[] findClassFileBytes(String className)
	{
		//TODO
		return null;
	}
}


text:
require 'puppet/file_serving/configuration'
require 'puppet/util/loadedfile'

class Puppet::FileServing::Configuration::Parser < Puppet::Util::LoadedFile
  Mount = Puppet::FileServing::Mount
  MODULES = 'modules'

  # Parse our configuration file.
  def parse
    raise("File server configuration #{self.file} does not exist") unless FileTest.exists?(self.file)
    raise("Cannot read file server configuration #{self.file}") unless FileTest.readable?(self.file)

    @mounts = {}
    @count = 0

    File.open(self.file) { |f|
      mount = nil
      f.each_line { |line|
        # Have the count increment at the top, in case we throw exceptions.
        @count += 1

        case line
        when /^\s*#/; next # skip comments
        when /^\s*$/; next # skip blank lines
        when /\[([-\w]+)\]/
          mount = newmount($1)
        when /^\s*(\w+)\s+(.+?)(\s*#.*)?$/
          var = $1
          value = $2
          value.strip!
          raise(ArgumentError, "Fileserver configuration file does not use '=' as a separator") if value =~ /^=/
          case var
          when "path"
            path(mount, value)
          when "allow"
            allow(mount, value)
          when "deny"
            deny(mount, value)
          else
            raise ArgumentError.new("Invalid argument '#{var}'", @count, file)
          end
        else
          raise ArgumentError.new("Invalid line '#{line.chomp}'", @count, file)
        end
      }
    }

    validate

    @mounts
  end

  private

  # Allow a given pattern access to a mount.
  def allow(mount, value)
    # LAK:NOTE See http://snurl.com/21zf8  [groups_google_com]
    x = value.split(/\s*,\s*/).each { |val|
      begin
        mount.info "allowing #{val} access"
        mount.allow(val)
      rescue Puppet::AuthStoreError => detail
        raise ArgumentError.new(detail.to_s, @count, file)
      end
    }
  end

  # Deny a given pattern access to a mount.
  def deny(mount, value)
    # LAK:NOTE See http://snurl.com/21zf8  [groups_google_com]
    x = value.split(/\s*,\s*/).each { |val|
      begin
        mount.info "denying #{val} access"
        mount.deny(val)
      rescue Puppet::AuthStoreError => detail
        raise ArgumentError.new(detail.to_s, @count, file)
      end
    }
  end

  # Create a new mount.
  def newmount(name)
    raise ArgumentError, "#{@mounts[name]} is already mounted at #{name}", @count, file if @mounts.include?(name)
    case name
    when "modules"
      mount = Mount::Modules.new(name)
    when "plugins"
      mount = Mount::Plugins.new(name)
    else
      mount = Mount::File.new(name)
    end
    @mounts[name] = mount
    mount
  end

  # Set the path for a mount.
  def path(mount, value)
    if mount.respond_to?(:path=)
      begin
        mount.path = value
      rescue ArgumentError => detail
        Puppet.log_exception(detail, "Removing mount \"#{mount.name}\": #{detail}")
        @mounts.delete(mount.name)
      end
    else
      Puppet.warning "The '#{mount.name}' module can not have a path. Ignoring attempt to set it"
    end
  end

  # Make sure all of our mounts are valid.  We have to do this after the fact
  # because details are added over time as the file is parsed.
  def validate
    @mounts.each { |name, mount| mount.validate }
  end
end


text:
<?php

namespace TestCenter\Controller;

use Calz\Controller\AbstractController;

class ModuleController extends AbstractController
{
    public function __construct()
    {
        $this->service = 'TestCenter\Service\Module';
        $this->entityClass = 'TestCenter\Entity\Module';
        $this->form = 'TestCenter\Form\Module';
        /**
         * @todo Verificar a importancia do redirect para insert e update
         */
        $this->redirect = '/test-center/module/index';
        $this->nomeController = 'Modules';
    }
}


text:
cp prepare-commit-msg.sample .git/hooks/prepare-commit-msg
chmod +x .git/hooks/prepare-commit-msg


text:
<?php

/**
 * @var $this yii\web\View
 * @var $model \skeeks\cms\models\CmsContentElement
 */
$controller = $this->context;
?>

    <? if ($model->image) : ?>

            <img style="border: 2px solid #ededed; border-radius: 5px;" src="<?php echo \Yii::$app->imaging->getImagingUrl($model->image->src,
                new \skeeks\cms\components\imaging\filters\Thumbnail()); ?>"/>

    <? endif; ?>

                    <?php echo $model->name; ?>
                    <? if ($model->is_adult) : ?>

                        [18+]

                    <? endif; ?>

                     <?php echo $model->id; ?>
                    <? if ($model->created_at) : ?>
                        <span style="margin-left: 5px;" data-toggle="tooltip" title="Запись создана в базе: <?php echo \Yii::$app->formatter->asDatetime($model->created_at); ?>"> <?php echo \Yii::$app->formatter->asDate($model->created_at); ?>
                    <? endif; ?>
                    <? if ($model->created_by) : ?>
                        <span style="margin-left: 5px;" data-toggle="tooltip" title="Запись создана пользователем с ID: <?php echo $model->createdBy->id; ?>"> <?php echo $model->createdBy->shortDisplayName; ?>
                    <? endif; ?>
                    <? if ($model->tree_id) : ?>
                        <span style="margin-left: 5px;" data-toggle="tooltip" title="<?php echo $model->cmsTree->fullName; ?>"> <?php echo $model->cmsTree->name; ?>
                    <? endif; ?>

            <? if ($model->cmsContent->is_have_page) : ?>

                    <a href="<?php echo $model->url; ?>" data-toggle="tooltip" class="btn btn-default" target="_blank" title="<?php echo \Yii::t('skeeks/cms', 'Watch to site (opens new window)'); ?>">

            <? endif; ?>

    <?php

    $modelActions = $controller->modelActions;
    $deleteAction = \yii\helpers\ArrayHelper::getValue($modelActions, "delete");

    if ($deleteAction) : ?>
        <?php

        $actionData = [
            "url"             => $deleteAction->url,

            //TODO:// is deprecated
            "isOpenNewWindow" => true,
            "confirm"         => isset($deleteAction->confirm) ? $deleteAction->confirm : "",
            "method"          => isset($deleteAction->method) ? $deleteAction->method : "",
            "request"         => isset($deleteAction->request) ? $deleteAction->request : "",
            "size"            => isset($deleteAction->size) ? $deleteAction->size : "",
        ];
        $actionData = \yii\helpers\Json::encode($actionData);

        $href = \yii\helpers\Html::a('', "#", [
            'onclick'     => "new sx.classes.backend.widgets.Action({$actionData}).go(); return false;",
            'class'       => "btn btn-default",
            'data-toggle' => "tooltip",
            'title'       => "Удалить",
        ]);
        ?>

            <?php echo $href; ?>

    <?php endif; ?>


text:
package com.thoughtworks.go.server.controller;

import com.thoughtworks.go.domain.ConsoleConsumer;
import com.thoughtworks.go.domain.JobIdentifier;
import com.thoughtworks.go.domain.StageIdentifier;
import com.thoughtworks.go.domain.exception.IllegalArtifactLocationException;
import com.thoughtworks.go.server.cache.ZipArtifactCache;
import com.thoughtworks.go.server.dao.JobInstanceDao;
import com.thoughtworks.go.server.security.HeaderConstraint;
import com.thoughtworks.go.server.service.ArtifactsService;
import com.thoughtworks.go.server.service.ConsoleActivityMonitor;
import com.thoughtworks.go.server.service.ConsoleService;
import com.thoughtworks.go.server.service.RestfulService;
import com.thoughtworks.go.server.util.ErrorHandler;
import com.thoughtworks.go.server.view.artifacts.ArtifactsView;
import com.thoughtworks.go.server.view.artifacts.LocalArtifactsView;
import com.thoughtworks.go.server.web.ArtifactFolderViewFactory;
import com.thoughtworks.go.server.web.FileModelAndView;
import com.thoughtworks.go.server.web.ResponseCodeView;
import com.thoughtworks.go.util.ArtifactLogUtil;
import com.thoughtworks.go.util.SystemEnvironment;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import static com.thoughtworks.go.server.web.ZipArtifactFolderViewFactory.zipViewFactory;
import static com.thoughtworks.go.util.ArtifactLogUtil.isConsoleOutput;
import static com.thoughtworks.go.util.GoConstants.*;
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;

@Controller
public class ArtifactsController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ArtifactsController.class);

    private final JobInstanceDao jobInstanceDao;
    private final ConsoleActivityMonitor consoleActivityMonitor;
    private final ArtifactFolderViewFactory folderViewFactory;
    private final ArtifactFolderViewFactory jsonViewFactory;
    private final ArtifactFolderViewFactory zipViewFactory;
    private final Charset consoleLogCharset;
    private ArtifactsService artifactsService;
    private RestfulService restfulService;
    private ConsoleService consoleService;
    private HeaderConstraint headerConstraint;

    @Autowired
    ArtifactsController(ArtifactsService artifactsService, RestfulService restfulService, ZipArtifactCache zipArtifactCache, JobInstanceDao jobInstanceDao,
                        ConsoleActivityMonitor consoleActivityMonitor, ConsoleService consoleService, SystemEnvironment systemEnvironment) {
        this.artifactsService = artifactsService;
        this.restfulService = restfulService;
        this.jobInstanceDao = jobInstanceDao;
        this.consoleActivityMonitor = consoleActivityMonitor;
        this.consoleService = consoleService;

        this.folderViewFactory = FileModelAndView.htmlViewFactory();
        this.jsonViewFactory = FileModelAndView.jsonViewfactory();
        this.zipViewFactory = zipViewFactory(zipArtifactCache);
        this.headerConstraint = new HeaderConstraint(systemEnvironment);
        this.consoleLogCharset = systemEnvironment.consoleLogCharsetAsCharset();
    }

    /* RESTful URLs */
    @RequestMapping(value = "/repository/restful/artifact/GET/html", method = RequestMethod.GET)
    public ModelAndView getArtifactAsHtml(@RequestParam("pipelineName") String pipelineName,
                                          @RequestParam("pipelineCounter") String pipelineCounter,
                                          @RequestParam("stageName") String stageName,
                                          @RequestParam(value = "stageCounter", required = false) String stageCounter,
                                          @RequestParam("buildName") String buildName,
                                          @RequestParam("filePath") String filePath,
                                          @RequestParam(value = "sha1", required = false) String sha,
                                          @RequestParam(value = "serverAlias", required = false) String serverAlias) throws Exception {
        return getArtifact(filePath, folderViewFactory, pipelineName, pipelineCounter, stageName, stageCounter, buildName, sha, serverAlias);
    }

    @RequestMapping(value = "/repository/restful/artifact/GET/json", method = RequestMethod.GET)
    public ModelAndView getArtifactAsJson(@RequestParam("pipelineName") String pipelineName,
                                          @RequestParam("pipelineCounter") String pipelineCounter,
                                          @RequestParam("stageName") String stageName,
                                          @RequestParam(value = "stageCounter", required = false) String stageCounter,
                                          @RequestParam("buildName") String buildName,
                                          @RequestParam("filePath") String filePath,
                                          @RequestParam(value = "sha1", required = false) String sha
    ) throws Exception {
        return getArtifact(filePath, jsonViewFactory, pipelineName, pipelineCounter, stageName, stageCounter, buildName, sha, null);
    }

    @RequestMapping(value = "/repository/restful/artifact/GET/zip", method = RequestMethod.GET)
    public ModelAndView getArtifactAsZip(@RequestParam("pipelineName") String pipelineName,
                                         @RequestParam("pipelineCounter") String pipelineCounter,
                                         @RequestParam("stageName") String stageName,
                                         @RequestParam(value = "stageCounter", required = false) String stageCounter,
                                         @RequestParam("buildName") String buildName,
                                         @RequestParam("filePath") String filePath,
                                         @RequestParam(value = "sha1", required = false) String sha
    ) throws Exception {
        if (filePath.equals(".zip")) {
            filePath = "./.zip";
        }
        return getArtifact(filePath, zipViewFactory, pipelineName, pipelineCounter, stageName, stageCounter, buildName, sha, null);
    }

    @RequestMapping(value = "/repository/restful/artifact/GET/*", method = RequestMethod.GET)
    public void fetch(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.getRequestDispatcher("/repository/restful/artifact/GET/html").forward(request, response);
    }

    @RequestMapping(value = "/repository/restful/artifact/POST/*", method = RequestMethod.POST)
    public ModelAndView postArtifact(@RequestParam("pipelineName") String pipelineName,
                                     @RequestParam("pipelineCounter") String pipelineCounter,
                                     @RequestParam("stageName") String stageName,
                                     @RequestParam(value = "stageCounter", required = false) String stageCounter,
                                     @RequestParam("buildName") String buildName,
                                     @RequestParam(value = "buildId", required = false) Long buildId,
                                     @RequestParam("filePath") String filePath,
                                     @RequestParam(value = "attempt", required = false) Integer attempt,
                                     MultipartHttpServletRequest request) throws Exception {
        JobIdentifier jobIdentifier;
        if (!headerConstraint.isSatisfied(request)) {
            return ResponseCodeView.create(HttpServletResponse.SC_BAD_REQUEST, "Missing required header 'Confirm'");
        }
        if (!isValidStageCounter(stageCounter)) {
            return buildNotFound(pipelineName, pipelineCounter, stageName, stageCounter, buildName);
        }
        try {
            jobIdentifier = restfulService.findJob(pipelineName, pipelineCounter, stageName, stageCounter,
                    buildName, buildId);
        } catch (Exception e) {
            return buildNotFound(pipelineName, pipelineCounter, stageName, stageCounter,
                    buildName);
        }

        int convertedAttempt = attempt == null ? 1 : attempt;

        try {
            File artifact = artifactsService.findArtifact(jobIdentifier, filePath);
            if (artifact.exists() && artifact.isFile()) {
                return FileModelAndView.fileAlreadyExists(filePath);
            }

            MultipartFile multipartFile = multipartFile(request);
            if (multipartFile == null) {
                return FileModelAndView.invalidUploadRequest();
            }

            boolean success = saveFile(convertedAttempt, artifact, multipartFile, shouldUnzipStream(multipartFile));

            if (!success) {
                return FileModelAndView.errorSavingFile(filePath);
            }

            success = updateChecksumFile(request, jobIdentifier, filePath);

            if (!success) {
                return FileModelAndView.errorSavingChecksumFile(filePath);
            }

            return FileModelAndView.fileCreated(filePath);

        } catch (IllegalArtifactLocationException e) {
            return FileModelAndView.forbiddenUrl(filePath);
        }
    }

    private boolean updateChecksumFile(MultipartHttpServletRequest request, JobIdentifier jobIdentifier, String filePath) throws IOException, IllegalArtifactLocationException {
        MultipartFile checksumMultipartFile = getChecksumFile(request);
        if (checksumMultipartFile != null) {
            String checksumFilePath = String.format("%s/%s/%s", artifactsService.findArtifactRoot(jobIdentifier), ArtifactLogUtil.CRUISE_OUTPUT_FOLDER, ArtifactLogUtil.MD5_CHECKSUM_FILENAME);
            File checksumFile = artifactsService.getArtifactLocation(checksumFilePath);
            synchronized (checksumFilePath.intern()) {
                return artifactsService.saveOrAppendFile(checksumFile, checksumMultipartFile.getInputStream());
            }
        } else {
            LOGGER.warn("[Artifacts Upload] Checksum file not uploaded for artifact at path '{}'", filePath);
        }
        return true;
    }

    private boolean saveFile(int convertedAttempt, File artifact, MultipartFile multipartFile, boolean shouldUnzip) throws IOException {
        try (InputStream inputStream = multipartFile.getInputStream()) {
            return artifactsService.saveFile(artifact, inputStream, shouldUnzip, convertedAttempt);
        }
    }

    @RequestMapping(value = "/repository/restful/artifact/PUT/*", method = RequestMethod.PUT)
    public ModelAndView putArtifact(@RequestParam("pipelineName") String pipelineName,
                                    @RequestParam("pipelineCounter") String pipelineCounter,
                                    @RequestParam("stageName") String stageName,
                                    @RequestParam(value = "stageCounter", required = false) String stageCounter,
                                    @RequestParam("buildName") String buildName,
                                    @RequestParam(value = "buildId", required = false) Long buildId,
                                    @RequestParam("filePath") String filePath,
                                    @RequestParam(value = "agentId", required = false) String agentId,
                                    HttpServletRequest request
    ) throws Exception {
        if (filePath.contains("..")) {
            return FileModelAndView.forbiddenUrl(filePath);
        }

        if (!isValidStageCounter(stageCounter)) {
            return buildNotFound(pipelineName, pipelineCounter, stageName, stageCounter, buildName);
        }

        JobIdentifier jobIdentifier;
        try {
            jobIdentifier = restfulService.findJob(pipelineName, pipelineCounter, stageName, stageCounter, buildName, buildId);
        } catch (Exception e) {
            return buildNotFound(pipelineName, pipelineCounter, stageName, stageCounter, buildName);
        }

        if (isConsoleOutput(filePath)) {
            return putConsoleOutput(jobIdentifier, request.getInputStream());
        } else {
            return putArtifact(jobIdentifier, filePath, request.getInputStream());
        }
    }

    /* Other URLs */

    @RequestMapping(value = "/**/consoleout.json", method = RequestMethod.GET)
    public ModelAndView consoleout(@RequestParam("pipelineName") String pipelineName,
                                   @RequestParam("pipelineCounter") String pipelineCounter,
                                   @RequestParam("stageName") String stageName,
                                   @RequestParam("buildName") String buildName,
                                   @RequestParam(value = "stageCounter", required = false) String stageCounter,
                                   @RequestParam(value = "startLineNumber", required = false) Long start
    ) {
        start = start == null ? 0L : start;

        if (!isValidStageCounter(stageCounter)) {
            return buildNotFound(pipelineName, pipelineCounter, stageName, stageCounter, buildName);
        }

        try {
            JobIdentifier identifier = restfulService.findJob(pipelineName, pipelineCounter, stageName, stageCounter, buildName);
            if (jobInstanceDao.isJobCompleted(identifier) && !consoleService.doesLogExist(identifier)) {
                return logsNotFound(identifier);
            }
            ConsoleConsumer streamer = consoleService.getStreamer(start, identifier);
            return new ModelAndView(new ConsoleOutView(streamer, consoleLogCharset));
        } catch (Exception e) {
            return buildNotFound(pipelineName, pipelineCounter, stageName, stageCounter, buildName);
        }
    }

    @ErrorHandler
    public ModelAndView handleError(HttpServletRequest request, HttpServletResponse response, Exception e) {
        LOGGER.error("Error loading artifacts: ", e);
        Map model = new HashMap();
        model.put(ERROR_FOR_PAGE, "Artifact does not exist.");
        return new ModelAndView("exceptions_page", model);
    }

    ModelAndView getArtifact(String filePath, ArtifactFolderViewFactory folderViewFactory, String pipelineName, String counterOrLabel, String stageName, String stageCounter, String buildName, String sha, String serverAlias) throws Exception {
        LOGGER.info("[Artifact Download] Trying to resolve '{}' for '{}/{}/{}/{}/{}'", filePath, pipelineName, counterOrLabel, stageName, stageCounter, buildName);

        if (!isValidStageCounter(stageCounter)) {
            return buildNotFound(pipelineName, counterOrLabel, stageName, stageCounter, buildName);
        }

        long before = System.currentTimeMillis();
        ArtifactsView view;
        //Work out the job that we are trying to retrieve
        JobIdentifier translatedId;
        try {
            translatedId = restfulService.findJob(pipelineName, counterOrLabel, stageName, stageCounter, buildName);
        } catch (Exception e) {
            return buildNotFound(pipelineName, counterOrLabel, stageName, stageCounter, buildName);
        }

        if (filePath.contains("..")) {
            return FileModelAndView.forbiddenUrl(filePath);
        }

        view = new LocalArtifactsView(folderViewFactory, artifactsService, translatedId, consoleService);

        ModelAndView createdView = view.createView(filePath, sha);
        LOGGER.info("[Artifact Download] Successfully resolved '{}' for '{}/{}/{}/{}/{}'. It took: {}ms", filePath, pipelineName, counterOrLabel, stageName, stageCounter, buildName, System.currentTimeMillis() - before);
        return createdView;
    }

    private boolean shouldUnzipStream(MultipartFile multipartFile) {
        return multipartFile.getName().equals(ZIP_MULTIPART_FILENAME);
    }

    private MultipartFile multipartFile(MultipartHttpServletRequest request) {
        MultipartFile multipartFile = request.getFile(REGULAR_MULTIPART_FILENAME);
        if (multipartFile == null) {
            multipartFile = request.getFile(ZIP_MULTIPART_FILENAME);
        }
        return multipartFile;
    }

    private MultipartFile getChecksumFile(MultipartHttpServletRequest request) {
        return request.getFile(CHECKSUM_MULTIPART_FILENAME);
    }

    private ModelAndView putConsoleOutput(final JobIdentifier jobIdentifier, final InputStream inputStream) throws Exception {
        File consoleLogFile = consoleService.consoleLogFile(jobIdentifier);
        boolean updated = consoleService.updateConsoleLog(consoleLogFile, inputStream);
        if (updated) {
            consoleActivityMonitor.consoleUpdatedFor(jobIdentifier);
            return FileModelAndView.fileAppended(consoleLogFile.getPath());
        } else {
            return FileModelAndView.errorSavingFile(consoleLogFile.getPath());
        }
    }

    private ModelAndView putArtifact(JobIdentifier jobIdentifier, String filePath,
                                     InputStream inputStream) throws Exception {
        File artifact = artifactsService.findArtifact(jobIdentifier, filePath);
        if (artifactsService.saveOrAppendFile(artifact, inputStream)) {
            return FileModelAndView.fileAppended(filePath);
        } else {
            return FileModelAndView.errorSavingFile(filePath);
        }
    }

    private ModelAndView buildNotFound(String pipelineName, String counterOrLabel, String stageName,
                                       String stageCounter,
                                       String buildName) {
        return ResponseCodeView.create(SC_NOT_FOUND, String.format("Job %s/%s/%s/%s/%s not found.", pipelineName,
                counterOrLabel, stageName, stageCounter, buildName));
    }

    private ModelAndView logsNotFound(JobIdentifier identifier) {
        String notFound = String.format("Console log for %s is unavailable as it may have been purged by Go or deleted externally.", identifier.toFullString());
        return ResponseCodeView.create(SC_NOT_FOUND, notFound);
    }

    private boolean isValidStageCounter(String stageCounter) {
        if (StringUtils.isEmpty(stageCounter) || StageIdentifier.LATEST.equalsIgnoreCase(stageCounter)) {
            return true;
        }

        try {
            int value = Integer.parseInt(stageCounter);
            return value > 0;
        } catch (Exception e) {
            return false;
        }
    }
}


text:
module Rufus
  class Waiter

    DEFAULT_TIMEOUT = 5
    DEFAULT_INTERVAL = 0.2

    def initialize(selenium, opts={})
      @selenium = selenium
      @timeout  = opts.fetch(:timeout, DEFAULT_TIMEOUT)
      @interval = opts.fetch(:interval, DEFAULT_INTERVAL)
    end

    def until(&block)
      time = Time.now + @timeout
      while Time.now < time
        @selenium.reset_page_source
        value = block.call if block
        return value if value
        sleep @interval
      end
      false
    end
  end
end


text:
from bitarray import bitarray
from bitarray.util import ba2int
import pprint
from math import sqrt

def read_tiles(f):
    tiles = {}
    tile_id = None
    tile = []

    for line in [x.strip() for x in open(f)]:
        if not line:
            tiles[tile_id] = tile
            tile = []
            continue

        if line.startswith('Tile '):
            tile_id = int(line[5:-1])
            continue

        tile.append(bitarray([x == '#' for x in line]))

    if tile:
        tiles[tile_id] = tile

    return tiles

def right(tile):
    t = bitarray()

    for row in tile:
        t.append(row[-1])

    return t

def left(tile):
    t = bitarray()

    for row in tile:
        t.append(row[0])

    return t

def top(tile):
    return tile[0]

def bottom(tile):
    return tile[-1]

def flip_y(tile):
    return tile[::-1]

def rotate(tile):
    rotated = []

    for xidx in range(0, len(tile[0])):
        r = bitarray()

        for row in tile:
            r.append(row[xidx])

        rotated.append(r[::-1])

    return rotated

def test_rotate():
    assert rotate([bitarray('010'),
                   bitarray('111'),
                   bitarray('101')]) == [bitarray('110'),
                                         bitarray('011'),
                                         bitarray('110')]

    assert rotate([bitarray('110'),
                   bitarray('011'),
                   bitarray('111')]) == [bitarray('101'),
                                         bitarray('111'),
                                         bitarray('110')]

def test_flip_y():
    assert flip_y([bitarray('010'),
                   bitarray('111'),
                   bitarray('101')]) == [bitarray('101'),
                                         bitarray('111'),
                                         bitarray('010')]

def test_directionality():
    tile = [bitarray('010'),
            bitarray('110'),
            bitarray('101')]

    assert left(tile) == bitarray('011')
    assert bottom(tile) == bitarray('101')
    assert right(tile) == bitarray('001')
    assert top(tile) == bitarray('010')

def populate_definition_struct(tiles_to_parse):
    available = {
        'left': {},
        'right': {},
        'top': {},
        'bottom': {},
    }

    def populate(k, t):
        def s(k_1, k_2, val):
            k_2 = ba2int(k_2)

            if k_2 not in available[k_1]:
                available[k_1][k_2] = []

            available[k_1][k_2].append(val)

        t_def = {
            'id': k,
            'tile': t,
        }

        s('left', left(t), t_def)
        s('right', right(t), t_def)
        s('top', top(t), t_def)
        s('bottom', bottom(t), t_def)

    for t_id, tile in tiles_to_parse.items():
        mirrored = flip_y(tile)
        populate(t_id, tile)

        for _ in range(0, 3):
            tile = rotate(tile)
            populate(t_id, tile)

        populate(t_id, mirrored)

        for _ in range(0, 3):
            mirrored = rotate(mirrored)
            populate(t_id, mirrored)

    return available

def layout_tiles(tiles, definition_struct):
    dim = int(sqrt(len(tiles)))
    layout = []

    for y in range(0, dim):
        row = []
        for x in range(0, dim):
            row.append(None)

        layout.append(row)

    data = {
        'used': set(),
        'layout': layout,
    }

    for tile_id, tile in tiles.items():
        attempt_layout(tiles, tile_id, tile, data, dim, definition_struct)

        for _ in range(0, 3):
            tile = rotate(tile)
            attempt_layout(tiles, tile_id, tile, data, dim, definition_struct)

        tile = flip_y(tile)

        attempt_layout(tiles, tile_id, tile, data, dim, definition_struct)

        for _ in range(0, 3):
            tile = rotate(tile)
            attempt_layout(tiles, tile_id, tile, data, dim, definition_struct)

    return data

def print_id_layout(layout):
    print()

    for row in layout:
        for tile in row:
            print('None' if not tile else tile['id'], end='  ')

        print()

    print()

def print_solution(layout):
    print_id_layout(layout)
    print('Solution: ' + str(layout[0][0]['id'] * layout[-1][0]['id'] * layout[0][-1]['id'] * layout[-1][-1]['id']))
    img = make_image(layout)

    print('Seamonsters')

    img_flipped = flip_y(img)

    for _ in range(0, 4):
        seamonsters, waves = count_seamonsters(img)

        if seamonsters:
            print(waves)
            break

        seamonsters, waves = count_seamonsters(img_flipped)

        if seamonsters:
            print(waves)
            break

        img = rotate(img)
        img_flipped = rotate(img_flipped)
        print("rotate")

    import sys
    sys.exit()

def attempt_layout(tiles, tile_id, tile, data, dim, definition_struct, x=0, y=0):
    data['used'].add(tile_id)
    data['layout'][y][x] = {
        'id': tile_id,
        'tile': tile,
    }

    if x == dim - 1 and y == dim - 1:
        print_solution(data['layout'])

    next_x = x + 1
    next_y = y

    if next_x % dim == 0:
        next_y = y + 1
        next_x = 0

    if next_x > 0 and next_y > 0:
        r = ba2int(right(data['layout'][next_y][next_x-1]['tile']))
        b = ba2int(bottom(data['layout'][next_y-1][next_x]['tile']))

        if r in definition_struct['left'] and b in definition_struct['top']:
            possible = []

            for l_t in definition_struct['left'][r]:
                for t_t in definition_struct['top'][b]:
                    if l_t == t_t:
                        possible.append(l_t)

            for n_tile in possible:
                if n_tile['id'] in data['used']:
                    continue

                attempt_layout(tiles, n_tile['id'], n_tile['tile'], data=data, dim=dim, definition_struct=definition_struct, x=next_x, y=next_y)
    elif next_y > 0:
        r = ba2int(bottom(data['layout'][next_y-1][next_x]['tile']))

        if r in definition_struct['top']:
            for n_tile in definition_struct['top'][r]:
                if n_tile['id'] in data['used']:
                    continue

                attempt_layout(tiles, n_tile['id'], n_tile['tile'], data=data, dim=dim, definition_struct=definition_struct, x=next_x, y=next_y)
    else:
        r = ba2int(right(data['layout'][y][next_x-1]['tile']))

        if r in definition_struct['left']:
            for n_tile in definition_struct['left'][r]:
                if n_tile['id'] in data['used']:
                    continue

                attempt_layout(tiles, n_tile['id'], n_tile['tile'], data=data, dim=dim, definition_struct=definition_struct, x=next_x, y=next_y)

    data['layout'][y][x] = None
    data['used'].remove(tile_id)

def make_image(layout):
    from copy import deepcopy

    result = deepcopy(layout)

    for row in result:
        for tile in row:
            del tile['tile'][0]
            del tile['tile'][-1]

            for t_row in tile['tile']:
                del t_row[0]
                del t_row[-1]

    image = []

    for y in range(0, len(result)):
        for inner_y in range(0, 8):
            row = bitarray()

            for x in range(0, len(result)):
                row.extend(result[y][x]['tile'][inner_y])

            image.append(row)

    return image

def count_seamonsters(image):
    seamonster = [
        bitarray('00000000000000000010'),
        bitarray('10000110000110000111'),
        bitarray('01001001001001001000'),
    ]

    seamonster_row_len = len(seamonster[0])
    seamonsters = 0

    for y in range(0, len(image) - 2):
        for x in range(0, len(image[0]) - seamonster_row_len):
            found = True

            for ridx, r in enumerate(seamonster):
                if r & image[y+ridx][x:x+seamonster_row_len] != r:
                    found = False
                    break

            if found:
                print("found a seamonster at " + str(x) + ', ' + str(y))
                seamonsters += 1

                for ridx, r in enumerate(seamonster):
                    k = r[:]
                    k.invert()
                    image[y + ridx][x:x + seamonster_row_len] &= k

    c = 0

    for row in image:
        c += row.count()

    return seamonsters, c

#our_tiles = read_tiles('input/20.test')
#definition_struct_source = populate_definition_struct(our_tiles)
#print(layout_tiles(our_tiles, definition_struct=definition_struct_source))

our_tiles = read_tiles('input/20')
definition_struct_source = populate_definition_struct(our_tiles)
print(layout_tiles(our_tiles, definition_struct=definition_struct_source))


text:
CKEDITOR.plugins.setLang( 'templates', 'lt', {
	button: 'Šablonai',
	emptyListMsg: '(Šablonų sąrašas tuščias)',
	insertOption: 'Pakeisti dabartinį turinį pasirinktu šablonu',
	options: 'Template Options',
	selectPromptMsg: 'Pasirinkite norimą šabloną
(Dėmesio! esamas turinys bus prarastas):',
	title: 'Turinio šablonai'
} );


text:
include_recipe "artifactory"
include_recipe "apache2"
include_recipe "apache2::mod_proxy_http"

host_name = node['artifactory']['host_name'] || node['fqdn']

template "#{node['apache']['dir']}/sites-available/artifactory" do
	source "apache-artifactory-vhost.conf.erb"
	owner       'root'
	group       'root'
	mode        '0644'
	variables(
	:host_name        => host_name
	)

	if File.exists?("#{node['apache']['dir']}/sites-enabled/artifactory")
		notifies  :restart, 'service[apache2]'
	end
end

apache_site "artifactory" do
	enable true
end


text:
require 'feature_test'

class TestPalletedPngFeature < FeatureTest
  feature :palleted_png do
    report = Thinreports::Report.new layout: template_path
    report.start_new_page do |page|
      page.item(:image).src = path_of('palleted_png.png')
    end

    assert_pdf report.generate
  end
end


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/ozone/platform/egltest/ozone_platform_egltest.h"

#include <stdint.h>

#include "base/bind.h"
#include "base/command_line.h"
#include "base/environment.h"
#include "base/files/file_path.h"
#include "base/macros.h"
#include "base/path_service.h"
#include "base/threading/thread_checker.h"
#include "library_loaders/libeglplatform_shim.h"
#include "third_party/khronos/EGL/egl.h"
#include "ui/events/devices/device_data_manager.h"
#include "ui/events/event.h"
#include "ui/events/ozone/device/device_manager.h"
#include "ui/events/ozone/evdev/event_factory_evdev.h"
#include "ui/events/ozone/events_ozone.h"
#include "ui/events/ozone/layout/keyboard_layout_engine_manager.h"
#include "ui/events/ozone/layout/stub/stub_keyboard_layout_engine.h"
#include "ui/events/platform/platform_event_dispatcher.h"
#include "ui/gfx/vsync_provider.h"
#include "ui/ozone/common/egl_util.h"
#include "ui/ozone/common/native_display_delegate_ozone.h"
#include "ui/ozone/common/stub_overlay_manager.h"
#include "ui/ozone/public/cursor_factory_ozone.h"
#include "ui/ozone/public/gpu_platform_support.h"
#include "ui/ozone/public/gpu_platform_support_host.h"
#include "ui/ozone/public/ozone_platform.h"
#include "ui/ozone/public/ozone_switches.h"
#include "ui/ozone/public/surface_factory_ozone.h"
#include "ui/ozone/public/surface_ozone_egl.h"
#include "ui/ozone/public/system_input_injector.h"
#include "ui/platform_window/platform_window.h"
#include "ui/platform_window/platform_window_delegate.h"

namespace ui {

namespace {

const char kEglplatformShim[] = "EGLPLATFORM_SHIM";
const char kEglplatformShimDefault[] = "libeglplatform_shim.so.1";
const char kDefaultEglSoname[] = "libEGL.so.1";
const char kDefaultGlesSoname[] = "libGLESv2.so.2";

// Get the library soname to load.
std::string GetShimLibraryName() {
  std::string library;
  scoped_ptr<base::Environment> env(base::Environment::Create());
  if (env->GetVar(kEglplatformShim, &library))
    return library;
  return kEglplatformShimDefault;
}

// Touch events are reported in device coordinates. This scales the event to the
// window's coordinate space.
void ScaleTouchEvent(TouchEvent* event, const gfx::SizeF& size) {
  for (const auto& device :
       DeviceDataManager::GetInstance()->touchscreen_devices()) {
    if (device.id == event->source_device_id()) {
      gfx::SizeF touchscreen_size = gfx::SizeF(device.size);
      gfx::Transform transform;
      transform.Scale(size.width() / touchscreen_size.width(),
                      size.height() / touchscreen_size.height());
      event->UpdateForRootTransform(transform);
      return;
    }
  }
}

class EgltestWindow : public PlatformWindow, public PlatformEventDispatcher {
 public:
  EgltestWindow(PlatformWindowDelegate* delegate,
                LibeglplatformShimLoader* eglplatform_shim,
                EventFactoryEvdev* event_factory,
                const gfx::Rect& bounds);
  ~EgltestWindow() override;

  // PlatformWindow:
  gfx::Rect GetBounds() override;
  void SetBounds(const gfx::Rect& bounds) override;
  void SetTitle(const base::string16& title) override;
  void Show() override;
  void Hide() override;
  void Close() override;
  void SetCapture() override;
  void ReleaseCapture() override;
  void ToggleFullscreen() override;
  void Maximize() override;
  void Minimize() override;
  void Restore() override;
  void SetCursor(PlatformCursor cursor) override;
  void MoveCursorTo(const gfx::Point& location) override;
  void ConfineCursorToBounds(const gfx::Rect& bounds) override;
  PlatformImeController* GetPlatformImeController() override;

  // PlatformEventDispatcher:
  bool CanDispatchEvent(const PlatformEvent& event) override;
  uint32_t DispatchEvent(const PlatformEvent& event) override;

 private:
  PlatformWindowDelegate* delegate_;
  LibeglplatformShimLoader* eglplatform_shim_;
  EventFactoryEvdev* event_factory_;
  gfx::Rect bounds_;
  ShimNativeWindowId window_id_;

  DISALLOW_COPY_AND_ASSIGN(EgltestWindow);
};

EgltestWindow::EgltestWindow(PlatformWindowDelegate* delegate,
                             LibeglplatformShimLoader* eglplatform_shim,
                             EventFactoryEvdev* event_factory,
                             const gfx::Rect& bounds)
    : delegate_(delegate),
      eglplatform_shim_(eglplatform_shim),
      event_factory_(event_factory),
      bounds_(bounds),
      window_id_(SHIM_NO_WINDOW_ID) {
  window_id_ = eglplatform_shim_->ShimCreateWindow();
  delegate_->OnAcceleratedWidgetAvailable(window_id_, 1.f);
  ui::PlatformEventSource::GetInstance()->AddPlatformEventDispatcher(this);
}

EgltestWindow::~EgltestWindow() {
  ui::PlatformEventSource::GetInstance()->RemovePlatformEventDispatcher(this);
  if (window_id_ != SHIM_NO_WINDOW_ID)
    eglplatform_shim_->ShimDestroyWindow(window_id_);
}

gfx::Rect EgltestWindow::GetBounds() {
  return bounds_;
}

void EgltestWindow::SetBounds(const gfx::Rect& bounds) {
  bounds_ = bounds;
  delegate_->OnBoundsChanged(bounds);
}

void EgltestWindow::SetTitle(const base::string16& title) {
}

void EgltestWindow::Show() {
}

void EgltestWindow::Hide() {
}

void EgltestWindow::Close() {
}

void EgltestWindow::SetCapture() {
}

void EgltestWindow::ReleaseCapture() {
}

void EgltestWindow::ToggleFullscreen() {
}

void EgltestWindow::Maximize() {
}

void EgltestWindow::Minimize() {
}

void EgltestWindow::Restore() {
}

void EgltestWindow::SetCursor(PlatformCursor cursor) {
}

void EgltestWindow::MoveCursorTo(const gfx::Point& location) {
  event_factory_->WarpCursorTo(window_id_, gfx::PointF(location));
}

void EgltestWindow::ConfineCursorToBounds(const gfx::Rect& bounds) {
}

PlatformImeController* EgltestWindow::GetPlatformImeController() {
  return nullptr;
}

bool EgltestWindow::CanDispatchEvent(const ui::PlatformEvent& ne) {
  return true;
}

uint32_t EgltestWindow::DispatchEvent(const ui::PlatformEvent& native_event) {
  DCHECK(native_event);
  Event* event = static_cast<Event*>(native_event);
  if (event->IsTouchEvent()) {
    ScaleTouchEvent(static_cast<TouchEvent*>(event),
                    gfx::SizeF(bounds_.size()));
  }

  DispatchEventFromNativeUiEvent(
      native_event, base::Bind(&PlatformWindowDelegate::DispatchEvent,
                               base::Unretained(delegate_)));

  return ui::POST_DISPATCH_STOP_PROPAGATION;
}

// EGL surface wrapper for libeglplatform_shim.
//
// This just manages the native window lifetime using
// ShimGetNativeWindow & ShimReleaseNativeWindow.
class SurfaceOzoneEgltest : public SurfaceOzoneEGL {
 public:
  SurfaceOzoneEgltest(ShimNativeWindowId window_id,
                      LibeglplatformShimLoader* eglplatform_shim)
      : eglplatform_shim_(eglplatform_shim) {
    native_window_ = eglplatform_shim_->ShimGetNativeWindow(window_id);
  }
  ~SurfaceOzoneEgltest() override {
    bool ret = eglplatform_shim_->ShimReleaseNativeWindow(native_window_);
    DCHECK(ret);
  }

  intptr_t GetNativeWindow() override { return native_window_; }

  bool OnSwapBuffers() override { return true; }

  void OnSwapBuffersAsync(const SwapCompletionCallback& callback) override {
    callback.Run(gfx::SwapResult::SWAP_ACK);
  }

  bool ResizeNativeWindow(const gfx::Size& viewport_size) override {
    return true;
  }

  scoped_ptr<gfx::VSyncProvider> CreateVSyncProvider() override {
    return nullptr;
  }

  void* /* EGLConfig */ GetEGLSurfaceConfig(
      const EglConfigCallbacks& egl) override {
    EGLint broken_props[] = {
        EGL_RENDERABLE_TYPE,
        EGL_OPENGL_ES2_BIT,
        EGL_SURFACE_TYPE,
        EGL_WINDOW_BIT | EGL_PBUFFER_BIT,
        EGL_NONE,
    };
    return ChooseEGLConfig(egl, broken_props);
  }

 private:
  LibeglplatformShimLoader* eglplatform_shim_;
  intptr_t native_window_;
};

// EGL surface factory for libeglplatform_shim.
//
// This finds the right EGL/GLES2 libraries for loading, and creates
// a single native window via ShimCreateWindow for drawing
// into.
class SurfaceFactoryEgltest : public ui::SurfaceFactoryOzone {
 public:
  SurfaceFactoryEgltest(LibeglplatformShimLoader* eglplatform_shim)
      : eglplatform_shim_(eglplatform_shim) {}
  ~SurfaceFactoryEgltest() override {
    DCHECK(thread_checker_.CalledOnValidThread());
  }

  // SurfaceFactoryOzone:
  intptr_t GetNativeDisplay() override;
  scoped_ptr<SurfaceOzoneEGL> CreateEGLSurfaceForWidget(
      gfx::AcceleratedWidget widget) override;
  bool LoadEGLGLES2Bindings(
      AddGLLibraryCallback add_gl_library,
      SetGLGetProcAddressProcCallback set_gl_get_proc_address) override;

 private:
  LibeglplatformShimLoader* eglplatform_shim_;
  base::ThreadChecker thread_checker_;
};

intptr_t SurfaceFactoryEgltest::GetNativeDisplay() {
  DCHECK(thread_checker_.CalledOnValidThread());
  return eglplatform_shim_->ShimGetNativeDisplay();
}

scoped_ptr<SurfaceOzoneEGL> SurfaceFactoryEgltest::CreateEGLSurfaceForWidget(
    gfx::AcceleratedWidget widget) {
  DCHECK(thread_checker_.CalledOnValidThread());
  return make_scoped_ptr<SurfaceOzoneEGL>(
      new SurfaceOzoneEgltest(widget, eglplatform_shim_));
}

bool SurfaceFactoryEgltest::LoadEGLGLES2Bindings(
    AddGLLibraryCallback add_gl_library,
    SetGLGetProcAddressProcCallback set_gl_get_proc_address) {
  DCHECK(thread_checker_.CalledOnValidThread());
  const char* egl_soname = eglplatform_shim_->ShimQueryString(SHIM_EGL_LIBRARY);
  const char* gles_soname =
      eglplatform_shim_->ShimQueryString(SHIM_GLES_LIBRARY);
  if (!egl_soname)
    egl_soname = kDefaultEglSoname;
  if (!gles_soname)
    gles_soname = kDefaultGlesSoname;

  return ::ui::LoadEGLGLES2Bindings(add_gl_library, set_gl_get_proc_address,
                                    egl_soname, gles_soname);
}

// Test platform for EGL.
//
// This is a tiny EGL-based platform. Creation of the native window is
// handled by a separate library called eglplatform_shim.so.1 because
// this itself is platform specific and we want to test out multiple
// hardware platforms.
class OzonePlatformEgltest : public OzonePlatform {
 public:
  OzonePlatformEgltest() : shim_initialized_(false) {}
  ~OzonePlatformEgltest() override {
    if (shim_initialized_)
      eglplatform_shim_.ShimTerminate();
  }

  void LoadShim() {
    std::string library = GetShimLibraryName();

    if (eglplatform_shim_.Load(library))
      return;

    base::FilePath module_path;
    if (!PathService::Get(base::DIR_MODULE, &module_path))
      LOG(ERROR) << "failed to get DIR_MODULE from PathService";
    base::FilePath library_path = module_path.Append(library);

    if (eglplatform_shim_.Load(library_path.value()))
      return;

    LOG(FATAL) << "failed to load " << library;
  }

  void Initialize() {
    LoadShim();
    shim_initialized_ = eglplatform_shim_.ShimInitialize();
  }

  // OzonePlatform:
  ui::SurfaceFactoryOzone* GetSurfaceFactoryOzone() override {
    return surface_factory_ozone_.get();
  }
  OverlayManagerOzone* GetOverlayManager() override {
    return overlay_manager_.get();
  }
  CursorFactoryOzone* GetCursorFactoryOzone() override {
    return cursor_factory_ozone_.get();
  }
  InputController* GetInputController() override {
    return event_factory_ozone_->input_controller();
  }
  GpuPlatformSupport* GetGpuPlatformSupport() override {
    return gpu_platform_support_.get();
  }
  GpuPlatformSupportHost* GetGpuPlatformSupportHost() override {
    return gpu_platform_support_host_.get();
  }
  scoped_ptr<SystemInputInjector> CreateSystemInputInjector() override {
    return nullptr;  // no input injection support.
  }
  scoped_ptr<PlatformWindow> CreatePlatformWindow(
      PlatformWindowDelegate* delegate,
      const gfx::Rect& bounds) override {
    return make_scoped_ptr<PlatformWindow>(new EgltestWindow(
        delegate, &eglplatform_shim_, event_factory_ozone_.get(), bounds));
  }
  scoped_ptr<NativeDisplayDelegate> CreateNativeDisplayDelegate() override {
    return make_scoped_ptr(new NativeDisplayDelegateOzone());
  }
  base::ScopedFD OpenClientNativePixmapDevice() const override {
    return base::ScopedFD();
  }

  void InitializeUI() override {
    device_manager_ = CreateDeviceManager();
    overlay_manager_.reset(new StubOverlayManager());
    KeyboardLayoutEngineManager::SetKeyboardLayoutEngine(
        make_scoped_ptr(new StubKeyboardLayoutEngine()));
    event_factory_ozone_.reset(new EventFactoryEvdev(
        NULL, device_manager_.get(),
        KeyboardLayoutEngineManager::GetKeyboardLayoutEngine()));
    cursor_factory_ozone_.reset(new CursorFactoryOzone());
    gpu_platform_support_host_.reset(CreateStubGpuPlatformSupportHost());
  }

  void InitializeGPU() override {
    surface_factory_ozone_.reset(new SurfaceFactoryEgltest(&eglplatform_shim_));
    gpu_platform_support_.reset(CreateStubGpuPlatformSupport());
  }

 private:
  LibeglplatformShimLoader eglplatform_shim_;
  scoped_ptr<DeviceManager> device_manager_;
  scoped_ptr<SurfaceFactoryEgltest> surface_factory_ozone_;
  scoped_ptr<EventFactoryEvdev> event_factory_ozone_;
  scoped_ptr<CursorFactoryOzone> cursor_factory_ozone_;
  scoped_ptr<GpuPlatformSupport> gpu_platform_support_;
  scoped_ptr<GpuPlatformSupportHost> gpu_platform_support_host_;
  scoped_ptr<OverlayManagerOzone> overlay_manager_;

  bool shim_initialized_;

  DISALLOW_COPY_AND_ASSIGN(OzonePlatformEgltest);
};

}  // namespace

OzonePlatform* CreateOzonePlatformEgltest() {
  OzonePlatformEgltest* platform = new OzonePlatformEgltest;
  platform->Initialize();
  return platform;
}

}  // namespace ui


text:
var M2MAdd=NFView.extend({
    _name: "m2m_add",
    className: "modal nf-modal",
    events: {
        "click .m2m-select": "select",
        "click .m2m-cancel": "cancel"
    },

    render: function() {
        var opts={
            model: this.options.model,
            condition: this.options.condition,
            view_xml: this.options.view_xml,
            show_search: true,
            no_click: true
        };
        var view_cls=get_view_cls("list_view");
        var view=new view_cls({options:opts});
        this.list_view=view;
        var content="

";
        this.data.content=content;
        NFView.prototype.render.call(this);
    },

    select: function() {
        log("m2m_select",this);
        var ids=this.list_view.get_selected_ids();
        log("selected ids",ids);
        if (ids.length==0) {
            alert("No items selected.");
            return;
        }
        $(".modal").modal("hide");
        this.trigger("items_selected",ids);
    },

    cancel: function() {
        log("m2m_cancel",this);
        $(".modal").modal("hide");
    }
});

M2MAdd.register();


text:
// Type definitions for CodeMirror
// Project: https://github.com/marijnh/CodeMirror
// Definitions by: Sixin Li <https://github.com/sixinli>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

// See docs https://codemirror.net/doc/manual.html#addon_matchbrackets

import * as CodeMirror from "codemirror";

declare module "codemirror" {
    interface MatchBrackets {
        /**
         * Only use the character after the start position, never the one before it.
         */
        afterCursor?: boolean;

        /**
         * Causes only matches where both brackets are at the same side of the start position to be considered.
         */
        strict?: boolean;

        /**
         * Stop after scanning this amount of lines without a successful match. Defaults to 1000.
         */
        maxScanLines?: number;

        /**
         * Ignore lines longer than this. Defaults to 10000.
         */
        maxScanLineLength?: number;

        /**
         * Don't highlight a bracket in a line longer than this. Defaults to 1000.
         */
        maxHighlightLineLength?: number;
    }

    interface EditorConfiguration {
        //  When set to true or an options object, causes matching brackets to be highlighted whenever the cursor is next to them.
        matchBrackets?: MatchBrackets | boolean;
    }
}


text:
package org.synyx.minos.i18n.domain;

import org.synyx.hades.domain.AbstractPersistable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.ManyToOne;

/**
 * Domain class linking an {@link AvailableMessage} to an {@link AvailableLanguage} indicating that the
 * {@link AvailableMessage} is either new ({@link MessageStatus#NEW} or updated ({@link MessageStatus#UPDATED} and
 * therefore the translation for {@link AvailableLanguage} needs to be checked.
 *
 * @author Marc Kannegiesser - kannegiesser@synyx.de
 */
@Entity
public class MessageTranslation extends AbstractPersistable<Long> {

    private static final long serialVersionUID = -3381096806734953868L;

    @ManyToOne(optional = false)
    private AvailableMessage availableMessage;

    @ManyToOne(optional = false)
    private AvailableLanguage availableLanguage;

    @Column(nullable = false)
    @Enumerated(EnumType.STRING)
    private MessageStatus messageStatus;

    /**
     * Create a new empty instance of {@link MessageTranslation}. This constructor is needed by the OR mapper.
     */
    protected MessageTranslation() {
    }

    /**
     * Create an new instance of {@link MessageTranslation} for the given {@link AvailableMessage} and
     * {@link AvailableLanguage} setting the given {@link MessageStatus}.
     *
     * @param availableMessage the {@link AvailableMessage}.
     * @param availableLanguage the {@link AvailableLanguage}.
     * @param messageStatus the {@link MessageStatus}.
     */
    public MessageTranslation(AvailableMessage availableMessage, AvailableLanguage availableLanguage,
        MessageStatus messageStatus) {

        super();
        this.availableMessage = availableMessage;
        this.availableLanguage = availableLanguage;
        this.messageStatus = messageStatus;
    }

    /**
     * Get the {@link AvailableMessage} of this instance of {@link MessageTranslation}.
     *
     * @return the {@link AvailableMessage}.
     */
    public AvailableMessage getAvailableMessage() {

        return availableMessage;
    }

    /**
     * Set the {@link AvailableMessage} of this instance of {@link MessageTranslation}.
     *
     * @param availableMessage the {@link AvailableMessage} to set.
     */
    public void setAvailableMessage(AvailableMessage availableMessage) {

        this.availableMessage = availableMessage;
    }

    /**
     * Get the {@link AvailableLanguage} of this instance of {@link MessageTranslation}.
     *
     * @return the {@link AvailableLanguage}.
     */
    public AvailableLanguage getAvailableLanguage() {

        return availableLanguage;
    }

    /**
     * Set the {@link AvailableLanguage} of this instance of {@link MessageTranslation}.
     *
     * @param availableLanguage the {@link AvailableLanguage} to set.
     */
    public void setAvailableLanguage(AvailableLanguage availableLanguage) {

        this.availableLanguage = availableLanguage;
    }

    /**
     * Get the {@link MessageStatus} of this instance of {@link MessageTranslation}.
     *
     * @return the {@link MessageStatus}.
     */
    public MessageStatus getMessageStatus() {

        return messageStatus;
    }

    /**
     * Set the {@link MessageStatus} of this instance of {@link MessageTranslation}.
     *
     * @param messageStatus the {@link MessageStatus} to set.
     */
    public void setMessageStatus(MessageStatus messageStatus) {

        this.messageStatus = messageStatus;
    }
}


text:
function disp_text(window, text, textcolour, backcolour, rect)

%Setup boundary defaults
if ~exist('rect', 'var')
    rect=Screen('Rect',0);            % Window-coordinates, e.g. [0 0 1024 768]
end

%Get centre of writing area
xcenter=round((rect(1)+rect(3))/2);
ycenter=round((rect(2)+rect(4))/2);

%Measure text size
[normboundsrect, offsetboundsrect]=Screen('TextBounds', window, text);

%DRAW TEXT
Screen('fillrect',window, backcolour, rect);                                                                %Background colour
Screen('DrawText', window, text, xcenter-normboundsrect(3)/2, ycenter-0.75*normboundsrect(4), textcolour);  %Text
%Note: the y normboundsrect doesn't quite work properly - 0.75 above is a scaling factor that has been found to work
%for vertical centring


text:
import React from 'react';
import { Layout } from 'antd';
import { Route, Switch } from 'react-router-dom';

// pages
import SliderBar from '@/layout/sliderBar';
import NotFound from '@/pages/notFound';
import asyncComponents from '@/utils/asyncComponent';

const { Header, Footer, Content } = Layout;
const MenuData = [
  {
    url: '/app/dashboard',
    name: '首页',
  },
  {
    name: 'animate',
    subMenu: [
      {
        url: '/app/animate',
        name: 'React动画',
      },
    ],
  },
  {
    name: 'antd',
    subMenu: [
      {
        url: '/app/antd/autoCompleteTest',
        name: 'autoComplete測試',
      },
    ],
  },
  {
    name: 'dataVisualization',
    subMenu: [
      {
        url: '/app/dataVisualization/eChart',
        name: 'eChart',
      },
      {
        url: '/app/dataVisualization/rChart',
        name: 'rChart',
      },
      {
        url: '/app/dataVisualization/d3js',
        name: 'd3',
      },
    ],
  },
  {
    name: 'drag',
    subMenu: [
      {
        url: '/app/drag/demo',
        name: 'react-dnd demo',
      },
      {
        url: '/app/drag/demo1',
        name: 'react-dnd demo1',
      },
    ],
  },
  {
    name: 'keyControl',
    url: '/app/keyControl',
  },
];
const routes = [
  {
    path: '/app/dashboard',
    component: asyncComponents(() => import('@/pages/dashboard')),
  },
  {
    path: '/app/animate',
    component: asyncComponents(() => import('@/pages/animate')),
  },
  {
    path: '/app/dataVisualization/eChart',
    component: asyncComponents(() => import('@/pages/dataVisualization/eChart')),
  },
  {
    path: '/app/dataVisualization/rChart',
    component: asyncComponents(() => import('@/pages/dataVisualization/rChart')),
  },
  {
    path: '/app/antd/autoCompleteTest',
    component: asyncComponents(() => {
      const { AutoCompleteTest } = import('@/pages/antd');
      return { default: AutoCompleteTest };
    }),
  },
  {
    path: '/app/drag/demo',
    component: asyncComponents(() => import('@/pages/drag/dragComponent')),
  },
  {
    path: '/app/drag/demo1',
    component: asyncComponents(() => import('@/pages/drag/native')),
  },
  {
    path: '/app/keyControl',
    component: asyncComponents(() => import('@/pages/keyControl')),
  },
];

const AppContent = (props) => {
  const routeArr = routes.map((route, index) => (
    <Route key={route.path} path={route.path} exact={route.exact} component={route.component} />
  ));
  routeArr.push(<Route component={NotFound} />);
  return (
    <Layout className="app">
      <SliderBar {...props} MenuData={MenuData} className="primary-nav" />
      <Layout className="page">
        <Header className="page-header" />
        <Content className="page-area">
          <Switch>{routeArr}</Switch>
          <Footer className="page-footer">Hello World! its smiletosun</Footer>
        </Content>
      </Layout>
    </Layout>
  );
};

export default AppContent;


text:
/* eslint-disable import/default */

import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import ReactGA from 'react-ga';

import routes from './routes';
import configureStore from './store/configureStore';
require('./favicon.ico');
import './assets/styles/app.scss';
import './assets/styles/bootstrap-superhero.min.css';
import './assets/styles/animate.min.css';
import './assets/styles/font-awesome.min.css';
import './assets/styles/styles.scss';

import 'jquery';
import 'web-animations-js/web-animations.min';

const store = configureStore();
const history = syncHistoryWithStore(browserHistory, store);

function logPageView() {
  ReactGA.set({ page: window.location.pathname });
  ReactGA.pageview(window.location.pathname);
}

ReactGA.initialize('UA-82047208-2');

render(
  <Provider store={store}>
    <Router
      history={history}
      routes={routes}
      onUpdate={logPageView} />
  </Provider>, document.getElementById('app')
);


text:
import { useEffect, useRef } from 'react'

const usePrevious = (value) => {
  const ref = useRef()

  useEffect(() => {
    ref.current = value
  })

  return ref.current
}

export default usePrevious


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

    <string name="app_name">ScanDemoExample</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>

</resources>


text:
class UserPresenter < Burgundy::Item

  def self.validators_on(args)
    User.validators_on(args)
  end

  # TODO spec
  def strava_identity
    @strava_identity ||= item.identities.where(provider: 'strava').first!
  end

  # TODO spec
  def location
    # strava_identity.info['location']
    [strava_identity.extra['raw_info']['city'],
    strava_identity.extra['raw_info']['state'],
    strava_identity.extra['raw_info']['country']].join(', ')
  end

  # TODO spec
  def strava_profile_url
    "https://www.strava.com/athletes/#{strava_identity.extra['raw_info']['id']}"
  end

  # TODO spec
  def strava_photo_url(format=:large)
    if format == :large
      strava_identity.extra['raw_info']['profile'] # large, 124x124
    else
      strava_identity.extra['raw_info']['profile_medium'] # medium, 60x60
    end
  end

end


text:
<?php

return [
    'issue-340' => [
        'ua' => 'Mozilla/5.0 (Android; U; -GB) AppleWebKit/533.19.4 (KHTML, like Gecko) AdobeAIR/13.0',
        'properties' => [
            'Comment' => 'Adobe AIR 13.0 for Android',
            'Browser' => 'Adobe AIR',
            'Browser_Type' => 'Application',
            'Browser_Bits' => '32',
            'Browser_Maker' => 'Adobe Systems Incorporated',
            'Browser_Modus' => 'unknown',
            'Version' => '13.0',
            'Platform' => 'Android',
            'Platform_Version' => 'unknown',
            'Platform_Description' => 'Android OS',
            'Platform_Bits' => '32',
            'Platform_Maker' => 'Google Inc',
            'Alpha' => false,
            'Beta' => false,
            'Frames' => true,
            'IFrames' => true,
            'Tables' => true,
            'Cookies' => true,
            'JavaScript' => true,
            'VBScript' => false,
            'JavaApplets' => true,
            'isSyndicationReader' => false,
            'isFake' => false,
            'isAnonymized' => false,
            'isModified' => false,
            'CssVersion' => '3',
            'Device_Name' => 'general Mobile Phone',
            'Device_Maker' => 'unknown',
            'Device_Type' => 'Mobile Phone',
            'Device_Pointing_Method' => 'touchscreen',
            'Device_Code_Name' => 'general Mobile Phone',
            'Device_Brand_Name' => 'unknown',
            'RenderingEngine_Name' => 'WebKit',
            'RenderingEngine_Version' => 'unknown',
            'RenderingEngine_Maker' => 'Apple Inc',
        ],
        'lite' => false,
        'standard' => true,
        'full' => true,
    ],
];