text:
"use strict";

interface IDataSeries {
    desc: string;
    data: IRun[];
}

interface IRun {
    date: Date;
    pass: bool;
}

interface IPerfDataSeries {
    desc: string;
    data: IPerfRun[];
}

interface IPerfRun {
    x: Date;
    y: number;
}

module Chart {

    export class Base {
        public iso8601 = d3.time.format('%Y-%m-%d');
        public chartWidth = 800;

        constructor (public element) { }
    }

    export class Bar extends Base {
        public element: ID3Selection;
        constructor(element: ID3Selection) {
            super(element);
            this.element = element;
        }

        public chartHeight = 400;
        public chartWidth = 800;
        public legendItemHeight = 30;
        public legendWidth = 150;
        public colors = ['rgb(0, 113, 188)', 'rgb(0, 174, 239)', 'rgb(145, 0, 145)'];
        public xAxisHashHeight = 10;
        public layout = 'wiggle';

        public render(data: IPerfDataSeries[]) {

            // Create stack layout
            var stackLayout = d3.layout.stack()
                                .values(function(d) { return d.data })
                                .offset(this.layout);

            var stackData = stackLayout(data);

            // Maximum measurement in the dataset
            var maxY = d3.max(stackData, function(d) => d3.max(d.data, function(d) => d.y0 + d.y));

            // Earliest day in the dataset
            var minX = d3.min(data, function(d) => d3.min(d.data, function(d) => d.x));

            // All days in the dataset (from earliest day until now)
            var days = d3.time.days(minX, new Date());

            // Area of the region containing the bars
            var areaWidth = this.chartWidth - this.legendWidth;

            var barWidth = areaWidth / days.length;

            // Create scales for X and Y axis (X based on dates, Y based on performance data)
            var x = d3.time.scale()
                        .domain([minX, d3.time.day(d3.time.day.offset(new Date(), 1))])
                        .range([0, this.chartWidth - this.legendWidth]);
            var y = d3.scale.linear()
                        .domain([0, maxY])
                        .range([0, this.chartHeight]);
            var ticks = x.ticks(d3.time.mondays, 1);

            // SVG element
            var svg = this.element.append('svg')
                        .attr('height', this.chartHeight + 25)
                        .attr('width', this.chartWidth);

            // Groups that contain bar segments for each dataset
            var barGroups = svg.selectAll('g.bars')
                    .data(stackData)
                .enter().append('g')
                    .attr('class', 'bars')
                    .style('fill', (d, i) => this.colors[<number>i])
                    .attr('transform', 'translate(' + this.legendWidth + ', 0)');

            // Legend
            var legendGroup = svg.append('g')
                    .attr('class', 'legend')

            // Legend items
            var legendItem = legendGroup.selectAll('g.legendItem')
                    .data(stackData)
               .enter().append('g')
                    .attr('class', 'legendItem')
                    .style('fill', (d, i) => this.colors[<number>i])
                    .attr('transform', (d, i) => 'translate(0, ' + (this.legendItemHeight * (2 - i)) + ')');

            legendItem.append('rect')
                        .attr('width', 25)
                        .attr('height', 25);

            legendItem.append('text')
                .text(function(d) => d.desc)
                .attr('x', 30)
                .attr('dy', '1em');

            // Bars
            var rects = barGroups.selectAll('rect')
                            .data(function(d) => d.data)
                        .enter()
                            .append('rect')
                            .attr('x', (d, i) => x(d.x))
                            .attr('y', (d, i) => this.chartHeight - y(d.y + d.y0))
                            .attr('width', barWidth)
                            .attr('height', (d, i) => y(d.y));

            // Add title (mouseover popup) to bars
            rects.append('title')
                 .text((d) => this.iso8601(d.x) + ' - ' + d.y + 'ms');

            // Add an axis marker to the bottom
            var axis = d3.svg.axis();
            axis.scale(x)
                .ticks(d3.time.mondays, 1)
                .tickSubdivide(6)
                .tickFormat(this.iso8601)
                .tickSize(10, 5, 0);

            var axisGroup = svg.append('g')
                    .attr('class', 'axis')
                    .attr('transform', 'translate(' + this.legendWidth + ',' + this.chartHeight + ')')
                    .call(axis);

            var svg;
        }
    }

    export class DailyBuild extends Base {
        public element: ID3Selection;
        constructor (element: ID3Selection) {
            super(element);
            this.element = element;
        }

        public labelWidth = 140;
        public labelGutter = 10;
        public chartWidth = 800;

        private getTextDataString(data) {
            return data.pass ? 'pass' : 'fail';
        }

        public render(data: IDataSeries[]) {
            // Minimum date in the dataset
            var minDate = d3.min(data.map(function(d) { return d3.time.day(d.data[0].date) }));

            // All the days in the dataset, from min until now.
            var days = d3.time.days(minDate, new Date());

            var boxSize = (this.chartWidth - this.labelWidth - this.labelGutter) / days.length;

            // Create our scales for x and y axis
            var x = d3.time.scale()
                        .domain([minDate, d3.time.day(new Date())])
                        .range([0, boxSize * (days.length - 1)]);

            var y = d3.scale.linear()
                        .domain([0, 1])
                        .range([0, boxSize]);

            // SVG element
            var svg = this.element.append('svg')
                            .attr('height', y(data.length  + 1))
                            .attr('width', this.chartWidth);

            svg.selectAll('text')
               .data(data)
               .enter().append('text')
                   .attr('x', this.labelWidth)
                   .attr('transform', function(d, i) { return 'translate(0,' + y(i) + ')' })
                   .attr('dy', '1em')
                   .attr('text-anchor', 'end')
                   .text(function(d) { return d.desc });

            // Groups of boxes for updated builds
            var g = svg.selectAll('g.boxes')
                    .data(data)
                .enter().append('g')
                    .attr('class', 'boxes')
                    .attr('transform', function(d, i) { return 'translate(0,' + y(i) + ')' });

            // Boxes of build info
            var rects = g.selectAll('rect')
                    .data(function(d, i) { return d.data; })
                .enter().append('rect')
                    .attr('class', (d) => 'day ' + this.getTextDataString(d))
                    .attr('x', (d, i) => this.labelWidth + this.labelGutter + x(d.date))
                    .attr('width', boxSize)
                    .attr('height', boxSize);

            rects.append('title')
                 .text( (d) => this.iso8601(d.date) + ' - ' + this.getTextDataString(d) );

            var ticks = x.ticks(d3.time.mondays, 1);

            // Date text boxes
            svg.append('g').attr('class', 'dates').selectAll('text')
                    .data(ticks)
                    .enter().append('text')
                        .text((d) => this.iso8601(d) )
                        .attr('transform', (d, i) => 'translate(' + (this.labelWidth + this.labelGutter + x(d) + 5) + ', ' + y(data.length + 1) + ')')
                        .attr('text-anchor', 'start')

            // Vertical hashes at week boundaries
            svg.append('g').attr('class', 'hashes').selectAll('line')
                .data(ticks)
                .enter().append('line')
                    .attr('x1', (d) => this.labelWidth + this.labelGutter + x(d) )
                    .attr('x2', (d) => this.labelWidth + this.labelGutter + x(d) )
                    .attr('y1', 0)
                    .attr('y2', y(data.length + 1));

            return svg;
        }
    }
}

var start = d3.time.day.offset(new Date(), -30);
var end = new Date()
var days = d3.time.days(start, end);

var buildData: IRun[] = days.map(day => ( { date: day, pass: Math.random() > 0.1 } ));
var compilerTestData: IRun[] = days.map(day => ( { date: day, pass: Math.random() > 0.1 } ));
var servicesTestData: IRun[] = days.map(day => ( { date: day, pass: Math.random() > 0.1 } ));

function decreasingRandom(start: number, deviation: number, factor: number) {
    var factorRandom = d3.random.normal(factor, 0.05);

    return function () {
        var random = d3.random.normal(start, deviation)();
        start = start * factorRandom();

        return parseFloat(random.toFixed())
    }
}

var parseRandom = decreasingRandom(400, 20, 0.97);
var typecheckRandom = decreasingRandom(500, 20, 0.97);
var emitRandom = decreasingRandom(100, 10, 0.97);

var parseData: IPerfRun[] = days.map(day => ( {x: day, y: parseRandom()}));
var typecheckData: IPerfRun[] = days.map(day => ( {x: day, y: typecheckRandom()}));
var emitData: IPerfRun[] = days.map(day => ( {x: day, y: emitRandom()}));

document.addEventListener('DOMContentLoaded', function() {
    var chart = new Chart.DailyBuild(d3.select('#passchart'));

    chart.render([
        { desc: "Build Status", data: buildData },
        { desc: "Compiler Tests", data: compilerTestData },
        { desc: "Services Tests", data: servicesTestData },
    ]);

    var normalizedData = [
        { desc: 'Emit', data: emitData },
        { desc: 'Typecheck', data: typecheckData },
        { desc: 'Parse', data: parseData }
    ]

    var perfchart = new Chart.Bar(d3.select('#performanceChart'));
    perfchart.render(normalizedData);
});


text:
import React from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import keycode from 'keycode'

const scrollKeys = [
  keycode('left'),
  keycode('right'),
  keycode('up'),
  keycode('down'),
  keycode('space'),
  keycode('pgup'),
  keycode('pgdn'),
  keycode('end'),
  keycode('home')
].reduce((scrollKeys, key) => {
  scrollKeys[key] = true
  return scrollKeys
}, {})

export const preventDefault = (e) => {
  e.preventDefault()
  e.returnValue = false
}

/**
 * Modal component
 */
class Modal extends React.Component {
  handleScrollAndEscKeys = (e) => {
    if (scrollKeys[e.keyCode]) {
      preventDefault(e)
      return false
    } else if (e.keyCode === keycode('esc')) {
      this.props.toggle(false)
    }
  }

  disableScroll () {
    window.addEventListener('DOMMouseScroll', preventDefault, false)
    window.addEventListener('wheel', preventDefault, false)
    window.addEventListener('touchmove', preventDefault, false)
    window.addEventListener('keydown', this.handleScrollAndEscKeys, false)
  }

  enableScroll () {
    window.removeEventListener('DOMMouseScroll', preventDefault, false)
    window.removeEventListener('wheel', preventDefault, false)
    window.removeEventListener('touchmove', preventDefault, false)
    window.removeEventListener('keydown', this.handleScrollAndEscKeys, false)
  }

  componentWillReceiveProps (props) {
    if (props.visible && !this.props.visible) {
      document.activeElement.blur()
      this.disableScroll()
    } else if (!props.visible && this.props.visible) {
      this.enableScroll()
    }
  }

  render () {
    const {header, body, footer, visible, toggle} = this.props
    return (

 {
          e.preventDefault()
          e.stopPropagation()
          toggle(false)
        }}
      >

 e.stopPropagation()}
          onTouchEnd={(e) => e.stopPropagation()}
        >

              {header}

              {body}

            {footer}

    )
  }
}

Modal.propTypes = {
  header: PropTypes.element,
  body: PropTypes.element,
  footer: PropTypes.element,
  visible: PropTypes.bool,
  toggle: PropTypes.func
}

Modal.defaultProps = {
  visible: false,
  toggle: () => {}
}

export default Modal

redpajama_set_name: RedPajamaGithub


text:
/*
Copyright (c) 2006-2008, Magnus Deininger
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
	  this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
	  this list of conditions and the following disclaimer in the documentation
	  and/or other materials provided with the distribution.
    * Neither the name of the project nor the names of its contributors may be
	  used to endorse or promote products derived from this software without
	  specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <einit/module.h>
#include <einit/config.h>
#include <einit/bitch.h>
#include <string.h>
#include <time.h>
#include <einit-modules/process.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <dirent.h>
#include <ctype.h>

#define EXPECTED_EIV 1

#if EXPECTED_EIV != EINIT_VERSION
#warning "This module was developed for a different version of eINIT, you might experience problems"
#endif

int linux_process_configure (struct lmodule *);

#if defined(EINIT_MODULE) || defined(EINIT_MODULE_HEADER)
const struct smodule module_linux_process_self = {
 .eiversion = EINIT_VERSION,
 .eibuild   = BUILDNUMBER,
 .version   = 1,
 .mode      = 0,
 .name      = "eINIT Process Function Library (Linux-Specific Parts)",
 .rid       = "linux-process",
 .si        = {
  .provides = NULL,
  .requires = NULL,
  .after    = NULL,
  .before   = NULL
 },
 .configure = linux_process_configure
};

module_register(module_linux_process_self);

#endif

struct process_status ** update_processes_proc_linux (struct process_status **pstat) {
 DIR *dir;
 char *path = cfg_getpath ("configuration-system-proc-path");
 struct dirent *entry;
 struct process_status **npstat = NULL;

 time_t starttime = time(NULL);

 if (pstat) {
  uint32_t i = 0;
  char buffer[BUFFERSIZE];
  struct stat st;

  for (; pstat[i]; i++) {
   esprintf (buffer, BUFFERSIZE, "%s%i", path, pstat[i]->pid);
   if (!stat (buffer, &st)) {
    npstat = (struct process_status **)set_fix_add ((void **)npstat, (void *)pstat[i], sizeof (struct process_status));
   }
  }
 }

 if (path) {
  size_t plength = strlen (path) +1;
  if ((dir = eopendir (path))) {
   char *txf = emalloc (plength);
   txf = memcpy (txf, path, plength);

   while ((entry = ereaddir (dir))) {
    uint32_t cl = 0;
    char cont = 1, recycled = 0;
    if (entry->d_name[0] == '.') continue;

    for (; entry->d_name[cl]; cl++) if (!isdigit (entry->d_name[cl])) { cont = 0; break; }

    if (cont) {
     struct process_status tmppse = {.update = starttime, .pid = atoi (entry->d_name), .cwd = NULL, .cmd = NULL};
     char linkbuffer[BUFFERSIZE];
     size_t linklen;
     txf = erealloc (txf, strlen (entry->d_name) + plength + 4);
     *(txf+plength-1) = 0;

     strcat (txf, entry->d_name);
     strcat (txf, "/cwd");

     if ((linklen = readlink (txf, linkbuffer, BUFFERSIZE-1)) != -1) {
      *(linkbuffer+linklen) = 0;

      tmppse.cwd = emalloc (linklen+1);
      memcpy (tmppse.cwd, linkbuffer, linklen+1);
     }

     if (npstat) {
      uint32_t i = 0;
      for (; npstat[i]; i++) {
       if (npstat[i]->pid == tmppse.pid) {
        recycled = 1;

        if (npstat[i]->cwd) efree (npstat[i]->cwd);
        if (npstat[i]->cmd) efree (npstat[i]->cmd);
        memcpy (npstat[i], &tmppse, sizeof(struct process_status));
       }
      }
     }

     if (!recycled) {
      npstat = (struct process_status **)set_fix_add ((void **)npstat, (void *)&tmppse, sizeof (struct process_status));
     }
    }

   }
   if (txf) efree (txf);

   eclosedir (dir);
  }
 }

 return npstat;
}

pid_t *filter_processes_files_below (struct pc_conditional * cond, pid_t * ret, struct process_status ** stat) {
 uint32_t i = 0;
 char *path = cfg_getpath ("configuration-system-proc-path");
 if (!path) path = "/proc/";

 if (stat && cond && cond->para)
  for (; stat[i]; i++) {
  uintptr_t tmppx = (stat[i]->pid);
  if (inset ((const void **)ret, (const void *)tmppx, SET_NOALLOC)) {
    continue;
   } else {
    DIR *dir;
    char tmp[BUFFERSIZE];
    esprintf (tmp, BUFFERSIZE, "%s%i/fd/", path, stat[i]->pid);

    if ((dir = eopendir (tmp))) {
     struct dirent *entry;

     while ((entry = ereaddir (dir))) {
      struct stat buf;
      esprintf (tmp, BUFFERSIZE, "%s%i/fd/%s", path, stat[i]->pid, entry->d_name);

      if (!lstat(tmp, &buf) && S_ISLNK(buf.st_mode)) {
       char ttarget[BUFFERSIZE];
       int r = readlink (tmp, ttarget, BUFFERSIZE-1);
       if (r == -1) continue;
       ttarget[r] = 0;

       if (strprefix (ttarget, cond->para)) {
        ret = (pid_t *)set_noa_add ((void **)ret, (void *)tmppx);
        goto kk;
       }
      }
     }
     kk:
     eclosedir (dir);
    }
   }
  }

 return ret;
}

char process_linux_pid_is_running (pid_t pid) {
 char tmp[BUFFERSIZE];
 struct stat st;
 esprintf (tmp, BUFFERSIZE, "/proc/%i", pid);

 return (!stat (tmp, &st));
}

int linux_process_cleanup (struct lmodule *this) {
 function_unregister ("einit-process-status-updater", 1, update_processes_proc_linux);
 function_unregister ("einit-process-filter-files-below", 1, filter_processes_files_below);
 function_unregister ("einit-process-is-running", 1, process_linux_pid_is_running);
 process_cleanup (irr);

 return 0;
}

int linux_process_configure (struct lmodule *irr) {
 module_init (irr);

 thismodule->cleanup = linux_process_cleanup;

 process_configure (irr);
 function_register ("einit-process-status-updater", 1, update_processes_proc_linux);
 function_register ("einit-process-filter-files-below", 1, filter_processes_files_below);
 function_register ("einit-process-is-running", 1, process_linux_pid_is_running);

 return 0;
}

/* passive module... */


text:
(function () {

    // Main module
    var app = angular.module('odalic-app');

    /** alert-group
     *  Description:
     *      A group of alert directives.
     *      Serves for displaying a chain of messages (e.g. when several requests may go wrong).
     *      The alerts may be set to automatically disappear after a while.
     *
     *  Usage:
     *      # Example 1
     *      - template -
     *      <!-- displays messages for 5 seconds -->
     *      <alert-group bind="myvar" disappearing="5" />
     *
     *      - controller -
     *      // initialize
     *      $scope.myvar = {];
     *
     *      // on certain event add new messages
     *      $scope.myevent = function() {
     *          $scope.myvar.push('error', 'Something went wrong...');
     *          $scope.myvar.push('success', '...but something also succeeded!');
     *      };
     *
     *      // on another event clear
     *      $scope.myevent2 = function() {
     *          $scope.myvar.clear();
     *      }
     *
     *  Arguments:
     *      bind
     *      - An object on scope. May be empty, but has to be defined.
     *      Functions:
     *          - push(type, msg): adds a new alert to the group of type 'type' with message 'msg'
     *          - clear(): removes all current alerts from the group
     *
     *      disappearing (optional)
     *      - Time interval (seconds) for individual alerts to disappear. If set to 'default' string,
     *      the duration from config.txt is used
     */
    var currentFolder = $.getPathForRelativePath('');
    app.directive('alertGroup', function () {
        return {
            restrict: 'E',
            templateUrl: currentFolder + 'alertgroup.html',
            scope: {
                bind: '='
            },
            transclude: true,
            link: function (scope, iElement, iAttrs) {
                // Implementation
                scope.messages = {
                    // Automatically disappearing alerts
                    alerttimeout: null,

                    // Messages to display
                    alerts: [],

                    // Text messages injected from template
                    txt: {},

                    // Pushing an alert message
                    push: function (type, text) {
                        var _ref = this;
                        var _alert = {
                            type: type,
                            visible: true,
                            text: text,
                            ghost: false,
                            close: function () {
                                _ref.alerts.splice(_ref.alerts.indexOf(this), 1);
                                this.ghost = true;
                            }
                        };

                        // push
                        _ref.alerts.push(_alert);

                        // automatically disappearing?
                        if (_ref.alerttimeout) {
                            window.setTimeout(function () {
                                if (!_alert.ghost) {
                                    _alert.close();
                                }

                                // Render changes
                                scope.$apply();
                            }, _ref.alerttimeout  * 1000);
                        }
                    },

                    // Clear any previous alerts
                    clear: function () {
                        this.alerts.forEach(function (item) {
                            item.close();
                        });
                    }
                };

                // Automatically disappearing alerts?
                if ('disappearing' in iAttrs) {
                    var tt = 0;
                    // Standard duration
                    if (iAttrs['disappearing'] === 'default') {
                        tt = constants.configurables.alerts.duration / 1000.0;
                    }
                    // Custom duration
                    else {
                        tt = text.safeInt(iAttrs['disappearing'], 0);
                    }
                    if (tt > 0) {
                        scope.messages.alerttimeout = tt;
                    }
                }

                // Public interface
                scope.bind.push = function (type, text) {
                    scope.messages.push(type, text);
                };

                scope.bind.clear = function () {
                    scope.messages.clear();
                };
            }
        }
    });

})();


text:
window.MathJax = {
    tex: {
        inlineMath: [['$', '$'], ['\\(', '\\)']],
        processEscapes: true,
        tags: 'ams'
    },
    options: {
        processHtmlClass: 'tex2jax_process|language-mathjax|lang-mathjax'
    },
    startup: {
        typeset: false,
        ready: function() {
            MathJax.startup.defaultReady();
            MathJax.startup.promise.then(() => {
                window.vnotex.getWorker('mathjax').setMathJaxReady();
            });
        }
    },
    svg: {
        // Make SVG self-contained.
        fontCache: 'local',
        scale: window.vxOptions.mathJaxScale > 0 ? window.vxOptions.mathJaxScale : 1
    }
};

class MathJaxRenderer extends VxWorker {
    constructor() {
        super();

        this.name = 'mathjax';

        this.initialized = false;

        this.nodesToRender = [];

        this.mathJaxScript = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js';

        this.langs = ['mathjax'];

        // Will be called when MathJax is ready.
        this.readyCallback = function() {};
    }

    registerInternal() {
        this.vnotex.on('basicMarkdownRendered', () => {
            this.render(this.vnotex.contentContainer, 'tex-to-render');
        });

        this.vnotex.getWorker('markdownit').addLangsToSkipHighlight(this.langs);
    }

    initialize(p_callback) {
        if (this.initialized) {
            return true;
        }

        this.initialized = true;
        this.readyCallback = p_callback;
        if (!!window.vxOptions.mathJaxScript) {
            this.mathJaxScript = window.vxOptions.mathJaxScript;
            console.log('override MathJax script', this.mathJaxScript);
        }
        Utils.loadScript(this.mathJaxScript, null);
        return false;
    }

    setMathJaxReady() {
        this.readyCallback();
    }

    // Fetch all nodes of @p_className to render.
    // Will fetch extra code nodes, too.
    render(p_node, p_className) {
        this.nodesToRender = [];

        // Transform extra class nodes.
        let extraNodes = this.vnotex.getWorker('markdownit').getCodeNodes(this.langs);
        this.transformExtraNodes(p_node, p_className, extraNodes);

        // Collect nodes to render.
        let nodes = p_node.getElementsByClassName(p_className);
        if (nodes.length == 0) {
            this.finishWork();
            return;
        }

        this.nodesToRender = Array.from(nodes);

        if (!this.initialize(() => {
            this.renderNodes();
            })) {
            return;
        }

        this.renderNodes();
    }

    // p_callback(svgNode).
    renderText(p_container, p_text, p_callback) {
        let func = () => {
            // Check text and remove the guards.
            let check = this.removeTextGuard(p_text);
            if (!check) {
                p_callback(null);
                return;
            }
            let options = null;
            try {
                options = MathJax.getMetricsFor(p_container, check.display);
            } catch (err) {
                console.error('failed to render MathJax', err);
                p_callback(null);
                return;
            }

            let mathNode = null;
            try {
                mathNode = MathJax.tex2svg(check.text, options);
            } catch (err) {
                console.error('failed to render MathJax', err);
            }
            p_callback(mathNode ? mathNode.firstElementChild : null);
        };

        if (!this.initialize(func)) {
            return;
        }

        func();
    }

    transformExtraNodes(p_node, p_className, p_extraNodes) {
        p_extraNodes.forEach((node) => {
            MathJaxRenderer.transformNode(node, p_className);
        });
    }

    static transformNode(p_node, p_className) {
        // Replace it with
<eqn></eqn>
.
        let eqn = document.createElement('eqn');
        eqn.classList.add(p_className);
        eqn.textContent = p_node.textContent;

        let section = document.createElement('section');
        section.appendChild(eqn);

        Utils.replaceNodeWithPreCheck(p_node, section);
    }

    renderNodes() {
        if (this.nodesToRender.length > 0) {
            try {
                MathJax.texReset();
            } catch (err) {
                console.error('MathJax is not ready', err);
                this.postProcessMathJax();
                return;
            }

            MathJax.typesetPromise(this.nodesToRender)
                .then(() => {
                    this.postProcessMathJax();
                })
                .catch((err) => {
                    console.error('failed to render MathJax', err);
                    this.postProcessMathJax();
                });
        }
    }

    postProcessMathJax() {
        this.finishWork();
    }

    // Return { text, display }.
    removeTextGuard(p_text) {
        let text = p_text.trim();
        let display = false;

        if (text.startsWith('$$') && text.endsWith('$$')) {
            text = text.substring(2, text.length - 2);
            display = true;
        } else if (text.startsWith('$') && text.endsWith('$')) {
            text = text.substring(1, text.length - 1);
        } else if (text.match(/^\\begin\s*\{\S+}[\s\S]+\\end\s*\{\S+\}$/)) {
            display = true;
        } else {
            return null;
        }

        return { text: text, display: display };
    }
}

window.vnotex.registerWorker(new MathJaxRenderer());


text:
from __future__ import annotations # isort:skip

import pytest ; pytest

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------

# Bokeh imports
from bokeh.models import CustomJS, TapTool
from bokeh.plotting import figure
from tests.support.plugins.project import SinglePlotPage
from tests.support.util.selenium import RECORD

#-----------------------------------------------------------------------------
# Tests
#-----------------------------------------------------------------------------

pytest_plugins = (
    "tests.support.plugins.project",
)

# TODO (bev):
#
# check that .names is respected
# check that .renderers is respected

@pytest.mark.selenium
class Test_TapTool:
    def test_tap_triggers_no_callback_without_hit(self, single_plot_page: SinglePlotPage) -> None:
        plot = figure(height=800, width=1000, tools='')
        plot.rect(x=[1, 2], y=[1, 1], width=1, height=1)
        plot.add_tools(TapTool(callback=CustomJS(code=RECORD("indices", "cb_data.source.selected.indices"))))
        plot.tags.append(CustomJS(name="custom-action", args=dict(p=plot), code=RECORD("junk", "10")))

        page = single_plot_page(plot)

        # make sure no indicies (even an empty list) was recorded
        page.click_canvas_at_position(plot, 50, 50)
        page.eval_custom_action()
        assert page.results == {"junk": 10}

        assert page.has_no_console_errors()

    def test_tap_triggers_callback_with_indices(self, single_plot_page: SinglePlotPage) -> None:
        plot = figure(height=800, width=1000, tools='')
        plot.rect(x=[1, 2], y=[1, 1], width=1, height=1)
        plot.add_tools(TapTool(callback=CustomJS(code=RECORD("indices", "cb_data.source.selected.indices"))))

        page = single_plot_page(plot)

        page.click_canvas_at_position(plot, 400, 500)
        assert page.results["indices"] == [0]

        page.click_canvas_at_position(plot, 600, 300)
        assert page.results["indices"] == [1]

        assert page.has_no_console_errors()

    def test_tap_reports_all_indices_on_overlap(self, single_plot_page: SinglePlotPage) -> None:
        plot = figure(height=800, width=1000, tools='')
        plot.rect(x=[1, 1], y=[1, 1], width=1, height=1)
        plot.add_tools(TapTool(callback=CustomJS(code=RECORD("indices", "cb_data.source.selected.indices"))))

        page = single_plot_page(plot)

        page.click_canvas_at_position(plot, 400, 500)
        assert set(page.results["indices"]) == {0, 1}

        assert page.has_no_console_errors()


text:
{{- $gate := .Get "gate" }}
{{- $title := .Get "title" }}

Warning

The {{ $title }} feature is currently Beta,
        and while it is enabled by default it may change in the future.

Use the Feature Gate {{- $gate }} to disable this feature.

See the Feature Gate documentation for details on how to disable features.


text:
package com.apwglobal.nice.domain;

import com.apwglobal.bd.BD;
import com.apwglobal.nice.util.UnixDate;

import java.util.Date;
import java.util.Optional;

public class IncomingPayment {

    private long transactionId;
    private long sellerId;
    private long buyerId;
    private IncomingPaymentStatus status;
    private double amount;
    private Date receiveDate;
    private double price;
    private double postageAmount;
    private int itemsCounter;
    private boolean incomplete;
    private Optional<Long> mainTransactionId;

    public IncomingPayment() { }

    private IncomingPayment(Builder builder) {
        transactionId = builder.transactionId;
        buyerId = builder.buyerId;
        sellerId = builder.sellerId;
        status = builder.status;
        amount = builder.amount;
        receiveDate = builder.receiveDate;
        price = builder.price;
        postageAmount = builder.postageAmount;
        itemsCounter = builder.itemsCounter;
        incomplete = builder.incomplete;
        mainTransactionId = builder.mainTransactionId;
    }

    public long getTransactionId() {
        return transactionId;
    }
    public long getBuyerId() {
        return buyerId;
    }
    public long getSellerId() {
        return sellerId;
    }
    public IncomingPaymentStatus getStatus() {
        return status;
    }
    public double getAmount() {
        return amount;
    }
    public Date getReceiveDate() {
        return receiveDate;
    }
    public double getPrice() {
        return price;
    }
    public double getPostageAmount() {
        return postageAmount;
    }
    public int getItemsCounter() {
        return itemsCounter;
    }
    public boolean isIncomplete() {
        return incomplete;
    }
    public Optional<Long> getMainTransactionId() {
        return mainTransactionId;
    }

    public static final class Builder {

        private long transactionId;
        private long buyerId;
        private long sellerId;
        private IncomingPaymentStatus status;
        private double amount;
        private Date receiveDate;
        private double price;
        private double postageAmount;
        private int itemsCounter;
        private boolean incomplete;
        private Optional<Long> mainTransactionId;

        public Builder() {
        }

        public Builder transactionId(long transactionId) {
            this.transactionId = transactionId;
            return this;
        }

        public Builder buyerId(long buyerId) {
            this.buyerId = buyerId;
            return this;
        }

        public Builder sellerId(long sellerId) {
            this.sellerId = sellerId;
            return this;
        }

        public Builder status(String status) {
            this.status = IncomingPaymentStatus.VALUES.get(status);
            return this;
        }

        public Builder amount(double amount) {
            this.amount = new BD(amount).doubleValue(2);
            return this;
        }

        public Builder receiveDate(long receiveDate) {
            this.receiveDate = UnixDate.toDate(receiveDate);
            return this;
        }

        public Builder price(double price) {
            this.price = new BD(price).doubleValue(2);
            return this;
        }

        public Builder postageAmount(double postageAmount) {
            this.postageAmount = new BD(postageAmount).doubleValue(2);
            return this;
        }

        public Builder itemsCounter(int itemsCounter) {
            this.itemsCounter = itemsCounter;
            return this;
        }

        public Builder incomplete(int incomplete) {
            this.incomplete = incomplete == 1;
            return this;
        }

        public Builder mainTransactionId(long mainTransactionId) {
            if (mainTransactionId == 0) {
                this.mainTransactionId = Optional.empty();
            } else {
                this.mainTransactionId = Optional.of(mainTransactionId);
            }
            return this;
        }

        public IncomingPayment build() {
            return new IncomingPayment(this);
        }
    }

    @Override
    public String toString() {
        return "IncomingPayment{" +
                "transactionId=" + transactionId +
                ", sellerId=" + sellerId +
                ", buyerId=" + buyerId +
                ", status=" + status +
                ", amount=" + amount +
                ", receiveDate=" + receiveDate +
                ", itemsCounter=" + itemsCounter +
                ", incomplete=" + incomplete +
                ", mainTransactionId=" + mainTransactionId +
                '}';
    }

}


text:
/
  String m_compilerSpec;
  String m_filePatterns;
  String m_fileType;
  StringVec m_outputFiles;
  String m_script;
/* End of serialized values */
};

#endif /* _PBXBUILDRULE_H_ */


text:
package org.neo4j.server.configuration;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.MapConfiguration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.neo4j.kernel.GraphDatabaseAPI;
import org.neo4j.server.WrappingNeoServerBootstrapper;
import org.neo4j.server.web.ServerInternalSettings;

import static org.neo4j.helpers.collection.MapUtil.stringMap;

/**
 * Used by the {@link WrappingNeoServerBootstrapper}, passing the minimum amount
 * of required configuration on to the neo4j server.
 *

 * If you want to change configuration for your
 * {@link WrappingNeoServerBootstrapper}, create an instance of this class, and
 * add configuration like so:
 *

 * {
 *     @code ServerConfigurator conf = new ServerConfigurator( myDb );
 *     conf.setProperty( ServerSettings.webserver_port.name(), "8080" );
 * }
 *

 * See the neo4j manual for information about what configuration directives the
 * server takes, or take a look at the settings in {@link ServerSettings}.
 *
 * @deprecated this will be removed in the next major version of Neo4j
 */
@Deprecated
public class ServerConfigurator extends Configurator.Adapter
{
    private final MapConfiguration config = new MapConfiguration(new HashMap<String,Object>());
    private final List<ThirdPartyJaxRsPackage> jaxRsPackages = new ArrayList<>();

    public ServerConfigurator( GraphDatabaseAPI db )
    {
        config.setProperty( ServerInternalSettings.legacy_db_location.name(), db.getStoreDir() );
    }

    @Override
    public Configuration configuration()
    {
        return config;
    }

    @Override
    public Map<String, String> getDatabaseTuningProperties()
    {
        return stringMap();
    }

    @Override
    public List<ThirdPartyJaxRsPackage> getThirdpartyJaxRsPackages()
    {
        return jaxRsPackages;
    }
}


text:
<?php

namespace Store\Bundle\BackendBundle\Controller;

use Store\Bundle\BackendBundle\Entity\Alipay;
use Store\Bundle\BackendBundle\Entity\Remittance;
use Store\Bundle\BackendBundle\Form\RemittanceType;
use Store\Bundle\BackendBundle\Form\Type\AlipayType;
use Symfony\Component\HttpFoundation\Request;

class PaymentController extends CoreController
{
    public function indexAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $user = $this->getUser();
        $store = $this->get('store.repo')->findOneBy(['userId'=>$user->getId()]);

        $alipay = new Alipay();
        $form = $this->createNewForm($request,new AlipayType(),$alipay);

        $alipays = $this->get('alipay.repo')->findBy(['storeId'=>$store->getId()]);

        if( $form->isValid())
        {
            $data = $form->getData();
            if( $data->getIsDefault())
            {
                foreach($alipays as $ali)
                {
                    if( $ali->getIsDefault())
                    {
                        $ali->setIsDefault(false);
                        $em->persist($ali);
                        $em->flush();
                    }
                }
            }

            $alipay->setStore($store);
            $em->persist($alipay);
            $em->flush();
            $this->addFlashMessage('success' , '支付宝添加成功');
            return $this->redirect($this->generateUrl('payment_manage'));
        }

        return $this->render('StoreBackendBundle:Payment:index.html.twig' ,
            [
                'form' => $form->createView() ,
                'alipays' => $alipays ,
            ]
        );
    }

    public function removeAction(Request $request , $id)
    {
        $em = $this->getDoctrine()->getManager();
        $user = $this->getUser();
        $store = $this->get('store.repo')->findOneBy(['userId'=>$user->getId()]);
        $alipay = $this->get('alipay.repo')->findOneBy(['id'=>$id,'storeId'=>$store->getId()]);

        if( $alipay)
        {
            $em->remove($alipay);
            $em->flush();
            $this->addFlashMessage('success' , '删除成功');

            return $this->redirect($this->generateUrl('payment_manage'));
        }
    }

    public function setDefaultAction(Request $request , $id)
    {
        $em = $this->getDoctrine()->getManager();
        $user = $this->getUser();
        $store = $this->get('store.repo')->findOneBy(['userId'=>$user->getId()]);
        $alipays = $this->get('alipay.repo')->findBy(['storeId'=>$store->getId()]);

        $alipay = $this->get('alipay.repo')->findOneBy(['id'=>$id,'storeId'=>$store->getId()]);

        if( $alipay)
        {
            foreach($alipays as $ali)
            {
                if( $ali->getIsDefault())
                {
                    $ali->setIsDefault(false);
                    $em->persist($ali);
                    $em->flush();
                }
            }

            $alipay->setIsDefault(true);
            $em->persist($alipay);
            $em->flush();
            $this->addFlashMessage('success' , '设置成功');

            return $this->redirect($this->generateUrl('payment_manage'));
        }
    }

}


text:
#include <aws/guardduty/model/GetMalwareScanSettingsResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::GuardDuty::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

GetMalwareScanSettingsResult::GetMalwareScanSettingsResult() :
    m_ebsSnapshotPreservation(EbsSnapshotPreservation::NOT_SET)
{
}

GetMalwareScanSettingsResult::GetMalwareScanSettingsResult(const Aws::AmazonWebServiceResult<JsonValue>& result) :
    m_ebsSnapshotPreservation(EbsSnapshotPreservation::NOT_SET)
{
  *this = result;
}

GetMalwareScanSettingsResult& GetMalwareScanSettingsResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  JsonView jsonValue = result.GetPayload().View();
  if(jsonValue.ValueExists("scanResourceCriteria"))
  {
    m_scanResourceCriteria = jsonValue.GetObject("scanResourceCriteria");

  }

  if(jsonValue.ValueExists("ebsSnapshotPreservation"))
  {
    m_ebsSnapshotPreservation = EbsSnapshotPreservationMapper::GetEbsSnapshotPreservationForName(jsonValue.GetString("ebsSnapshotPreservation"));

  }

  return *this;
}


text:
Ext.ns('MShop.panel');

MShop.panel.ConfigUi = Ext.extend(Ext.grid.EditorGridPanel, {

    stripeRows : true,
    autoExpandColumn : 'config-value',

    initComponent : function() {
        this.title = MShop.I18n.dt('client/extjs', 'Configuration');
        this.colModel = this.getColumnModel();
        this.tbar = this.getToolBar();
        this.store = this.getStore();
        this.sm = new Ext.grid.RowSelectionModel();
        this.record = Ext.data.Record.create([{
            name : 'name',
            type : 'string'
        }, {
            name : 'value',
            type : 'string'
        }]);

        if(!Ext.isObject(this.data)) {
            this.data = {};
        }

        MShop.panel.ConfigUi.superclass.initComponent.call(this);
    },

    getToolBar : function() {
        var that = this;
        return new Ext.Toolbar([{
            text : MShop.I18n.dt('client/extjs', 'Add'),

            handler : function() {
                that.store.insert(0, new that.record({
                    name : '',
                    value : ''
                }));
            }
        }, {
            text : MShop.I18n.dt('client/extjs', 'Delete'),

            handler : function() {
                Ext.each(that.getSelectionModel().getSelections(), function(selection, idx) {
                    that.store.remove(selection);
                }, this);

                var data = {};
                Ext.each(that.store.data.items, function(item, index) {
                    data[item.data.name] = item.data.value;
                }, this);

                that.data = data;
            }
        }]);
    },

    getColumnModel : function() {
        return new Ext.grid.ColumnModel({
            defaults : {
                width : 250,
                sortable : true
            },
            columns : [{
                header : MShop.I18n.dt('client/extjs', 'Name'),
                dataIndex : 'name',
                editor : {
                    xtype : 'textfield'
                }
            }, {
                header : MShop.I18n.dt('client/extjs', 'Value'),
                dataIndex : 'value',
                editor : {
                    xtype : 'textfield'
                },
                id : 'config-value'
            }]
        });
    },

    getStore : function() {
        return new Ext.data.ArrayStore({
            autoSave : true,
            fields : [{
                name : 'name',
                type : 'string'
            }, {
                name : 'value',
                type : 'string'
            }]
        });
    },

    listeners : {
        render : function(r) {
            Ext.iterate(this.data, function(key, value, object) {
                if(typeof value === "object") {
                    value = Ext.util.JSON.encode(value);
                }
                this.store.loadData([[key, value]], true);
            }, this);
        },
        beforeedit : function(e) {
            if(typeof e.value === "object") {
                e.record.data[e.field] = Ext.util.JSON.encode(e.value);
            }
        },
        afteredit : function(obj) {
            if(obj.record.data.name.trim() !== '') {
                if(obj.originalValue != obj.record.data.name) {
                    delete this.data[obj.originalValue];
                }
                if(obj.record.data.value[0] === '{') {
                    try {
                        obj.record.data.value = Ext.util.JSON.decode(obj.record.data.value);
                    } catch(err) {
                        Ext.Msg.alert(MShop.I18n.dt('client/extjs', 'Invalid data'), String.format(MShop.I18n.dt(
                            'client/extjs', 'Invalid value for configuration key "{0}"'), obj.record.data.name));

                        throw new Ext.Error('InvalidData', obj.record.data);
                    }
                }
                this.data[obj.record.data.name] = obj.record.data.value;
            }
        }
    }

});

Ext.reg('MShop.panel.configui', MShop.panel.ConfigUi);


text:
/**
 * Created by glenn on 15.08.16.
 */

(() => {
  'use strict';

  angular.module('helloApp.hello').run(runBlock);

  /* @ngInject */
  function runBlock(c8ySystem) {
    (async () => {
      await printUiVersion();

      // Put your fiddle code here.
      console.log('hello, world');
    })();

    async function printUiVersion() {
      const version = await c8ySystem.getUIVersion();

      console.log(`Cumulocity UI version: ${version}`);
    }
  }
})();


text:
package io.seata.rm.tcc.interceptor;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nonnull;

import com.alibaba.fastjson.JSON;
import io.seata.common.Constants;
import io.seata.common.exception.FrameworkException;
import io.seata.common.exception.SkipCallbackWrapperException;
import io.seata.common.executor.Callback;
import io.seata.common.util.CollectionUtils;
import io.seata.common.util.NetUtil;
import io.seata.core.context.RootContext;
import io.seata.core.model.BranchType;
import io.seata.rm.DefaultResourceManager;
import io.seata.rm.tcc.TCCFenceHandler;
import io.seata.rm.tcc.api.BusinessActionContext;
import io.seata.rm.tcc.api.BusinessActionContextParameter;
import io.seata.rm.tcc.api.BusinessActionContextUtil;
import io.seata.rm.tcc.api.ParamType;
import io.seata.rm.tcc.api.TwoPhaseBusinessAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

/**
 * Handler the TCC Participant Aspect : Setting Context, Creating Branch Record
 *
 * @author zhangsen
 */
public class ActionInterceptorHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(ActionInterceptorHandler.class);

    /**
     * Handler the TCC Aspect
     *
     * @param method         the method
     * @param arguments      the arguments
     * @param xid            the xid
     * @param businessAction the business action
     * @param targetCallback the target callback
     * @return the business result
     * @throws Throwable the throwable
     */
    public Object proceed(Method method, Object[] arguments, String xid, TwoPhaseBusinessAction businessAction,
                                       Callback<Object> targetCallback) throws Throwable {
        //Get action context from arguments, or create a new one and then reset to arguments
        BusinessActionContext actionContext = getOrCreateActionContextAndResetToArguments(method.getParameterTypes(), arguments);

        //Set the xid
        actionContext.setXid(xid);
        //Set the action name
        String actionName = businessAction.name();
        actionContext.setActionName(actionName);
        //Set the delay report
        actionContext.setDelayReport(businessAction.isDelayReport());

        //Creating Branch Record
        String branchId = doTccActionLogStore(method, arguments, businessAction, actionContext);
        actionContext.setBranchId(branchId);
        //MDC put branchId
        MDC.put(RootContext.MDC_KEY_BRANCH_ID, branchId);

        // save the previous action context
        BusinessActionContext previousActionContext = BusinessActionContextUtil.getContext();
        try {
            //share actionContext implicitly
            BusinessActionContextUtil.setContext(actionContext);

            if (businessAction.useTCCFence()) {
                try {
                    // Use TCC Fence, and return the business result
                    return TCCFenceHandler.prepareFence(xid, Long.valueOf(branchId), actionName, targetCallback);
                } catch (SkipCallbackWrapperException | UndeclaredThrowableException e) {
                    Throwable originException = e.getCause();
                    if (originException instanceof FrameworkException) {
                        LOGGER.error("[{}] prepare TCC fence error: {}", xid, originException.getMessage());
                    }
                    throw originException;
                }
            } else {
                //Execute business, and return the business result
                return targetCallback.execute();
            }
        } finally {
            try {
                //to report business action context finally if the actionContext.getUpdated() is true
                BusinessActionContextUtil.reportContext(actionContext);
            } finally {
                if (previousActionContext != null) {
                    // recovery the previous action context
                    BusinessActionContextUtil.setContext(previousActionContext);
                } else {
                    // clear the action context
                    BusinessActionContextUtil.clear();
                }
            }
        }
    }

    /**
     * Get or create action context, and reset to arguments
     *
     * @param parameterTypes the par
     * @param arguments the arguments
     * @return the action context
     * @since above 1.4.2
     */
    @Nonnull
    protected BusinessActionContext getOrCreateActionContextAndResetToArguments(Class<?>[] parameterTypes, Object[] arguments) {
        BusinessActionContext actionContext = null;

        // get the action context from arguments
        int argIndex = 0;
        for (Class<?> parameterType : parameterTypes) {
            if (BusinessActionContext.class.isAssignableFrom(parameterType)) {
                actionContext = (BusinessActionContext)arguments[argIndex];
                if (actionContext == null) {
                    // If the action context exists in arguments but is null, create a new one and reset the action context to the arguments
                    actionContext = new BusinessActionContext();
                    arguments[argIndex] = actionContext;
                } else {
                    // Reset the updated, avoid unnecessary reporting
                    actionContext.setUpdated(null);
                }
                break;
            }
            argIndex++;
        }

        // if null, create a new one
        if (actionContext == null) {
            actionContext = new BusinessActionContext();
        }
        return actionContext;
    }

    /**
     * Creating Branch Record
     *
     * @param method         the method
     * @param arguments      the arguments
     * @param businessAction the business action
     * @param actionContext  the action context
     * @return the branchId
     */
    protected String doTccActionLogStore(Method method, Object[] arguments, TwoPhaseBusinessAction businessAction,
                                         BusinessActionContext actionContext) {
        String actionName = actionContext.getActionName();
        String xid = actionContext.getXid();

        //region fetch context and init action context

        Map<String, Object> context = fetchActionRequestContext(method, arguments);
        context.put(Constants.ACTION_START_TIME, System.currentTimeMillis());

        //Init business context
        initBusinessContext(context, method, businessAction);
        //Init running environment context
        initFrameworkContext(context);

        Map<String, Object> originContext = actionContext.getActionContext();
        if (CollectionUtils.isNotEmpty(originContext)) {
            //Merge context and origin context if it exists.
            //@since: above 1.4.2
            originContext.putAll(context);
            context = originContext;
        } else {
            actionContext.setActionContext(context);
        }

        //endregion

        //Init applicationData
        Map<String, Object> applicationContext = Collections.singletonMap(Constants.TCC_ACTION_CONTEXT, context);
        String applicationContextStr = JSON.toJSONString(applicationContext);
        try {
            //registry branch record
            Long branchId = DefaultResourceManager.get().branchRegister(BranchType.TCC, actionName, null, xid,
                    applicationContextStr, null);
            return String.valueOf(branchId);
        } catch (Throwable t) {
            String msg = String.format("TCC branch Register error, xid: %s", xid);
            LOGGER.error(msg, t);
            throw new FrameworkException(t, msg);
        }
    }

    /**
     * Init running environment context
     *
     * @param context the context
     */
    protected void initFrameworkContext(Map<String, Object> context) {
        try {
            context.put(Constants.HOST_NAME, NetUtil.getLocalIp());
        } catch (Throwable t) {
            LOGGER.warn("getLocalIP error", t);
        }
    }

    /**
     * Init business context
     *
     * @param context        the context
     * @param method         the method
     * @param businessAction the business action
     */
    protected void initBusinessContext(Map<String, Object> context, Method method,
                                       TwoPhaseBusinessAction businessAction) {
        if (method != null) {
            //the phase one method name
            context.put(Constants.PREPARE_METHOD, method.getName());
        }
        if (businessAction != null) {
            //the phase two method name
            context.put(Constants.COMMIT_METHOD, businessAction.commitMethod());
            context.put(Constants.ROLLBACK_METHOD, businessAction.rollbackMethod());
            context.put(Constants.ACTION_NAME, businessAction.name());
            context.put(Constants.USE_TCC_FENCE, businessAction.useTCCFence());
        }
    }

    /**
     * Extracting context data from parameters, add them to the context
     *
     * @param method    the method
     * @param arguments the arguments
     * @return the context
     */
    protected Map<String, Object> fetchActionRequestContext(Method method, Object[] arguments) {
        Map<String, Object> context = new HashMap<>(8);

        Annotation[][] parameterAnnotations = method.getParameterAnnotations();
        for (int i = 0; i < parameterAnnotations.length; i++) {
            for (int j = 0; j < parameterAnnotations[i].length; j++) {
                if (parameterAnnotations[i][j] instanceof BusinessActionContextParameter) {
                    // get annotation
                    BusinessActionContextParameter annotation = (BusinessActionContextParameter)parameterAnnotations[i][j];
                    if (arguments[i] == null) {
                        throw new IllegalArgumentException("@BusinessActionContextParameter 's params can not null");
                    }

                    // get param
                    Object paramObject = arguments[i];
                    if (paramObject == null) {
                        continue;
                    }

                    // load param by the config of annotation, and then put into the context
                    ActionContextUtil.loadParamByAnnotationAndPutToContext(ParamType.PARAM, "", paramObject, annotation, context);
                }
            }
        }
        return context;
    }
}


text:
package com.avast.cactus.v3.test

import java.time.{Duration, Instant}

import com.avast.cactus.v3.TestMessageV3.TestEnum
import com.avast.cactus.v3.{AnyValue, ValueOneOf}
import com.avast.cactus.{GpbIgnored, GpbMap, GpbName, GpbOneOf}
import com.google.protobuf.{
  BoolValue,
  ByteString,
  BytesValue,
  DoubleValue,
  FloatValue,
  Int32Value,
  Int64Value,
  ListValue,
  StringValue,
  Duration => GpbDuration,
  Timestamp => GpbTimestamp
}

import scala.collection.immutable

case class CaseClassA(fieldString: String,
                      @GpbName("fieldIntName")
                      fieldInt: Int,
                      fieldOption: Option[Int],
                      fieldBlob: ByteString,
                      @GpbName("fieldStringsName")
                      fieldStrings2: List[String],
                      fieldGpb: CaseClassB,
                      fieldGpb2: CaseClassB,
                      fieldGpb3: CaseClassF,
                      fieldGpbOption: Option[CaseClassB],
                      fieldGpbOptionEmpty: Option[CaseClassB],
                      fieldGpbRepeated: Seq[CaseClassB],
                      fieldGpb2RepeatedRecurse: Seq[CaseClassD],
                      fieldStrings: immutable.Seq[String],
                      fieldOptionIntegers: Vector[Int],
                      fieldOptionIntegersEmpty: List[Int],
                      @GpbName("fieldIntegers2")
                      fieldIntegersString: String,
                      @GpbMap(key = "key", value = "value")
                      fieldMap: Map[String, String],
                      @GpbName("fieldMap2")
                      @GpbMap(key = "key", value = "value")
                      fieldMapDiffType: Map[String, Int])

// this is here to prevent reappearing of bug with companion object
object CaseClassA

case class CaseClassB(fieldDouble: Double, @GpbName("fieldBlob") fieldString: String)

case class CaseClassD(fieldGpb: Seq[CaseClassB], @GpbOneOf @GpbName("NamedOneOf2") oneOfNamed: OneOfNamed3)

case class CaseClassF(fieldGpb: Seq[CaseClassB], @GpbOneOf namedOneOf: Option[OneOfNamed])

case class CaseClassExtensions(boolValue: BoolValue,
                               int32Value: Int32Value,
                               @GpbName("int64Value")
                               longValue: Int64Value,
                               floatValue: Option[FloatValue],
                               doubleValue: Option[DoubleValue],
                               stringValue: Option[StringValue],
                               bytesValue: BytesValue,
                               listValue: ListValue,
                               listValue2: Seq[ValueOneOf],
                               listValue3: Option[Seq[ValueOneOf]],
                               listValue4: Option[Seq[ValueOneOf]],
                               duration: GpbDuration,
                               timestamp: GpbTimestamp,
                               struct: Map[String, ValueOneOf])

case class CaseClassExtensionsScala(boolValue: Boolean,
                                    int32Value: Int,
                                    @GpbName("int64Value")
                                    longValue: Long,
                                    floatValue: Option[Float],
                                    doubleValue: Option[Double],
                                    stringValue: Option[String],
                                    bytesValue: ByteString,
                                    listValue: Seq[ValueOneOf],
                                    duration: Duration,
                                    timestamp: Instant)

case class ExtClass(timestamp: Instant, any: AnyValue)

case class ExtClassOpt(timestamp: Instant, any: Option[AnyValue])

case class InnerClass(fieldInt: Int, fieldString: String)

sealed trait OneOfNamed

object OneOfNamed {

  case class FooInt(theInt: Int) extends OneOfNamed // to prove the name is not relevant

  case class FooString(value: String) extends OneOfNamed

}

sealed trait OneOfNamed3

object OneOfNamed3 {

  case class FooInt(value: Int) extends OneOfNamed3

  case class FooString(value: String) extends OneOfNamed3

  case class FooBytes(value: String) extends OneOfNamed3

  case object FooEmpty extends OneOfNamed3

}

case class CaseClassC(fieldString: StringWrapperClass,
                      @GpbName("fieldIntName")
                      fieldInt: Int,
                      fieldOption: Option[Int],
                      fieldBlob: ByteString,
                      @GpbName("fieldStringsName")
                      fieldStrings2: Vector[String],
                      fieldGpb: CaseClassB,
                      fieldGpbOption: Option[CaseClassB],
                      fieldGpbOptionEmpty: Option[CaseClassB],
                      fieldStrings: Array[String],
                      fieldOptionIntegers: Seq[Int],
                      fieldOptionIntegersEmpty: Seq[Int],
                      @GpbMap(key = "key", value = "value")
                      fieldMap: Map[String, String]) {

  // needed because of the array
  override def equals(obj: scala.Any): Boolean = obj match {
    case that: CaseClassC =>
      fieldString == that.fieldString &&
        fieldInt == that.fieldInt &&
        fieldOption == that.fieldOption &&
        fieldBlob == that.fieldBlob &&
        fieldStrings2 == that.fieldStrings2 &&
        fieldGpb == that.fieldGpb &&
        fieldGpbOption == that.fieldGpbOption &&
        fieldGpbOptionEmpty == that.fieldGpbOptionEmpty &&
        (fieldStrings sameElements that.fieldStrings) &&
        fieldOptionIntegers == that.fieldOptionIntegers &&
        fieldOptionIntegersEmpty == that.fieldOptionIntegersEmpty &&
        fieldMap == fieldMap

    case _ => false
  }
}

// the `fieldIgnored` field is very unusually placed, but it has to be tested too...
case class CaseClassE(fieldString: String,
                      @GpbIgnored fieldIgnored: String = "hello",
                      fieldOption: Option[String],
                      @GpbIgnored fieldIgnored2: String = "hello")

case class CaseClassG(fieldString: String,
                      fieldOption: Option[String],
                      fieldMap: Map[String, Int],
                      fieldMap2: Map[String, CaseClassMapInnerMessage])

case class CaseClassMapInnerMessage(fieldString: String, fieldInt: Int)

case class StringWrapperClass(value: String)

sealed abstract class TheEnum

object TheEnum {

  case object Unknown extends TheEnum

  case object One extends TheEnum

  case object Two extends TheEnum

}

case class CaseClassWithEnum(theEnumField: Option[TheEnum])

case class CaseClassWithRawEnum(fieldString: String,
                                fieldEnum: TestEnum,
                                fieldEnumOption: Option[TestEnum],
                                fieldMap: Map[String, TestEnum])

case class OptionalMessageClass(elem: Option[AnyValue])

case class GenericCaseClass[T](@GpbName("fieldString") fieldT: T, fieldInt: Int)

case class CaseClassWithMap(values: Map[String, Option[Instant]])

case class CaseClassWithMapEnums(values: Map[String, Option[TheEnum]])


text:
package com.amazonaws.services.lightsail.model;

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum HeaderEnum {

    Accept("Accept"),
    AcceptCharset("Accept-Charset"),
    AcceptDatetime("Accept-Datetime"),
    AcceptEncoding("Accept-Encoding"),
    AcceptLanguage("Accept-Language"),
    Authorization("Authorization"),
    CloudFrontForwardedProto("CloudFront-Forwarded-Proto"),
    CloudFrontIsDesktopViewer("CloudFront-Is-Desktop-Viewer"),
    CloudFrontIsMobileViewer("CloudFront-Is-Mobile-Viewer"),
    CloudFrontIsSmartTVViewer("CloudFront-Is-SmartTV-Viewer"),
    CloudFrontIsTabletViewer("CloudFront-Is-Tablet-Viewer"),
    CloudFrontViewerCountry("CloudFront-Viewer-Country"),
    Host("Host"),
    Origin("Origin"),
    Referer("Referer");

    private String value;

    private HeaderEnum(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return HeaderEnum corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static HeaderEnum fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (HeaderEnum enumEntry : HeaderEnum.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
package gwt.material.design.client.ui;

import gwt.material.design.client.base.HasGrid;
import gwt.material.design.client.base.HasError;
import gwt.material.design.client.constants.Orientation;

import java.util.Date;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.ui.FocusPanel;
import com.google.gwt.user.client.ui.HTMLPanel;
import gwt.material.design.client.base.HasOrientation;
import gwt.material.design.client.base.mixin.ErrorMixin;
import gwt.material.design.client.base.mixin.GridMixin;

//@formatter:off
/**
 * Material Date Picker will provide a visual calendar to your apps.
 *
 *
UiBinder Usage:

 * {@code
 * <m:MaterialDatePicker ui:field="datePicker">
 * }
 *
Java Usage:

 * {@code
 * datePicker.setDate(new Date());
 * }
 *
 * @author kevzlou7979
 * @author Ben Dol
 * @see Material Date Picker
 */
//@formatter:on
public class MaterialDatePicker extends FocusPanel implements HasGrid, HasError, HasOrientation {

    /**
     * Enum for identifying various selection types for the picker.
     *
     */
    public enum MaterialDatePickerType {
        DAY,
        MONTH_DAY,
        YEAR_MONTH_DAY,
        YEAR
    }

    /**
     * Delegate interface for handling picker events.
     */
    public interface MaterialDatePickerDelegate {
        /**
         * Called as soon as a click occurs on the calendar widget. !EXPERIMENTAL!
         * @param currDate which is currently selected.
         */
        void onCalendarClose(Date currDate);
    }

    private String placeholder;
    private String id;
    private Date date;

    private JavaScriptObject input;
    private HTMLPanel panel;
    private MaterialLabel lblError = new MaterialLabel();

    private Orientation orientation = Orientation.PORTRAIT;
    private MaterialDatePickerDelegate delegate;
    private MaterialDatePickerType selectionType = MaterialDatePickerType.DAY;

    private final GridMixin<MaterialDatePicker> gridMixin = new GridMixin<>(this);
    private final ErrorMixin<MaterialDatePicker, MaterialLabel> errorMixin = new ErrorMixin<>(this, lblError, panel);

    public MaterialDatePicker() {
    }

    @Override
    protected void onAttach() {
        super.onAttach();
        id = String.valueOf(hashCode());
        clear();
        panel = new HTMLPanel("<input placeholder='"+placeholder+"' type='date' id='"+id+"' class='datepicker'>");
        this.add(panel);
        panel.addStyleName(orientation.getCssName());
        initDatePicker(id, selectionType.name(), this);
        initClickHandler(id, this);
        panel.add(lblError);
    }

    @Override
    public void clear() {
        super.clear();
        clearErrorOrSuccess();
    }

    public static native void initDatePicker(String id, String typeName, MaterialDatePicker parent) /*-{
        var input;
        if(typeName === "MONTH_DAY") {
            input = $wnd.jQuery('#' + id).pickadate({
                container: 'body',
                selectYears: false,
                selectMonths: true
            });
        } else if(typeName === "YEAR_MONTH_DAY") {
            input = $wnd.jQuery('#' + id).pickadate({
                container: 'body',
                selectYears: true,
                selectMonths: true
            });
        } else if(typeName === "YEAR"){
            input = $wnd.jQuery('#' + id).pickadate({
                container: 'body',
                selectYears: true
            });
        } else {
            input = $wnd.jQuery('#' + id).pickadate({
                container: 'body'
            });
        }

        parent.@gwt.material.design.client.ui.MaterialDatePicker::input = input;
    }-*/;

    /**
     * Sets the type of selection options (date, month, year,...).
     * @param type if null, {@link MaterialDatePickerType#DAY} will be used as fallback.
     */
    public void setDateSelectionType(MaterialDatePickerType type) {
        if(type == null) {
            type = MaterialDatePickerType.DAY;
        }
        this.selectionType = type;
    }

    native void initClickHandler(String id, MaterialDatePicker parent) /*-{
        var input = parent.@gwt.material.design.client.ui.MaterialDatePicker::input;
        var picker = input.pickadate('picker');
        picker.on({
          close: function() {
            parent.@gwt.material.design.client.ui.MaterialDatePicker::notifyDelegate()();
          }
        });
    }-*/;

    /**
     * A delegate which implements handling of events from date picker.
     * @param delegate which will be notified on picker events.
     * @see MaterialDatePickerDelegate
     */
    public void setDelegate(MaterialDatePickerDelegate delegate) {
        this.delegate = delegate;
    }

    void notifyDelegate() {
        if(delegate != null) {
            delegate.onCalendarClose(getDate());
        }
    }

    public Date getDate() {
        return getPickerDate();
    }

    public native void clearValues() /*-{
        $wnd.jQuery('.datepicker').val("");
    }-*/;

    public Date getPickerDate() {
        try {
            DateTimeFormat sdf = DateTimeFormat.getFormat("d MMM, yyyy");
            date = sdf.parse(getDatePickerValue(id));
            return date;
        } catch(Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Sets the current date of the picker.
     * @param date - must not be null
     */
    public void setDate(Date date) {
        if(date == null) {
            return;
        }
        this.date = date;
        initDatePicker(id, selectionType.name(), this);
        DateTimeFormat sdf = DateTimeFormat.getFormat("d MMM, yyyy");
        setDatePickerValue(sdf.format(date), id);
        /*DateTimeFormat sdfSetter = DateTimeFormat.getFormat("yyyy-MM-dd");
        selectDate(sdfSetter.format(date), id, this);*/
    }

    private native void selectDate(String date, String id, MaterialDatePicker parent) /*-{
        var input = parent.@gwt.material.design.client.ui.MaterialDatePicker::input;
        var picker = input.pickadate('picker');
        if(picker) {
            picker.set('select', date, { format: 'yyyy-MM-dd' });
        }
    }-*/;

    public static native String getDatePickerValue(String id)/*-{
        return $wnd.jQuery('#' + id).val();
    }-*/;

    private static native void setDatePickerValue(String value, String id)/*-{
        var input = $wnd.jQuery('.datepicker').pickadate();

        // Use the picker object directly.
        var picker = input.pickadate('picker');
        if(picker) {
            picker.set('select', value, { format: 'yyyy-MM-dd' });
        }
    }-*/;

    public String getPlaceholder() {
        return placeholder;
    }

    public void setPlaceholder(String placeholder) {
        this.placeholder = placeholder;
    }

    public MaterialDatePickerType getSelectionType() {
        return selectionType;
    }

    public void setSelectionType(MaterialDatePickerType selectionType) {
        this.selectionType = selectionType;
    }

    /**
     * @return the orientation
     */
    @Override
    public Orientation getOrientation() {
        return orientation;
    }

    /**
     * @param orientation the orientation to set : can be Vertical or Horizontal
     */
    @Override
    public void setOrientation(Orientation orientation) {
        this.orientation = orientation;
    }

    @Override
    public void setGrid(String grid) {
        gridMixin.setGrid(grid);
    }

    @Override
    public void setOffset(String offset) {
        gridMixin.setOffset(offset);
    }

    @Override
    public void setError(String error) {
        errorMixin.setError(error);
    }

    @Override
    public void setSuccess(String success) {
        errorMixin.setSuccess(success);
    }

    @Override
    public void clearErrorOrSuccess() {
        errorMixin.clearErrorOrSuccess();
    }
}


text:
/* http://keith-wood.name/datepick.html
   Malaysian localisation for jQuery Datepicker.
   Written by Mohd Nawawi Mohamad Jamili (nawawi@ronggeng.net). */
(function($) {
	$.datepick.regional['ms'] = {
		monthNames: ['Januari','Februari','Mac','April','Mei','Jun',
		'Julai','Ogos','September','Oktober','November','Disember'],
		monthNamesShort: ['Jan','Feb','Mac','Apr','Mei','Jun',
		'Jul','Ogo','Sep','Okt','Nov','Dis'],
		dayNames: ['Ahad','Isnin','Selasa','Rabu','Khamis','Jumaat','Sabtu'],
		dayNamesShort: ['Aha','Isn','Sel','Rab','Kha','Jum','Sab'],
		dayNamesMin: ['Ah','Is','Se','Ra','Kh','Ju','Sa'],
		dateFormat: 'dd/mm/yyyy', firstDay: 0,
		renderer: $.datepick.defaultRenderer,
		prevText: '<Sebelum', prevStatus: 'Tunjukkan bulan lepas',
		prevJumpText: '<<', prevJumpStatus: 'Tunjukkan tahun lepas',
		nextText: 'Selepas>', nextStatus: 'Tunjukkan bulan depan',
		nextJumpText: '>>', nextJumpStatus: 'Tunjukkan tahun depan',
		currentText: 'hari ini', currentStatus: 'Tunjukkan bulan terkini',
		todayText: 'hari ini', todayStatus: 'Tunjukkan bulan terkini',
		clearText: 'Padam', clearStatus: 'Padamkan tarikh terkini',
		closeText: 'Tutup', closeStatus: 'Tutup tanpa perubahan',
		yearStatus: 'Tunjukkan tahun yang lain', monthStatus: 'Tunjukkan bulan yang lain',
		weekText: 'Mg', weekStatus: 'Minggu bagi tahun ini',
		dayStatus: 'DD, d MM', defaultStatus: 'Sila pilih tarikh',
		isRTL: false
	};
	$.datepick.setDefaults($.datepick.regional['ms']);
})(jQuery);


text:
using System;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;

namespace EspaceClient.FrontOffice.Domaine
{
    public partial class TypeContenu
    {

        [DataMember]
        public long ID { get; set; }

        [DataMember]
				[StringLength(50)]
        public string Code { get; set; }

        [DataMember]
				[StringLength(50)]
        public string CodeEchange { get; set; }

        [DataMember]
				[StringLength(500)]
        public string Libelle { get; set; }
    }
}


text:
using FluentNHibernate.Automapping.Alterations;
using FluentNHibernate.Infrastructure;
using NHibernate.Util;
using System;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace FluentNHibernate.Utils
{
    public static class Extensions
    {
        public static bool In<T>(this T instance, params T[] expected)
        {
            if (ReferenceEquals(instance, null))
                return false;
            return expected.Any(x => instance.Equals(x));
        }

        public static string ToLowerInvariantString(this object value)
        {
            return value.ToString().ToLowerInvariant();
        }

        public static bool Closes(this Type type, Type openGenericType)
        {
            return type.IsGenericType && type.GetGenericTypeDefinition() == openGenericType;
        }

        public static bool ClosesInterface(this Type type, Type openGenericInterface)
        {
            return type.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == openGenericInterface);
        }

        public static bool IsEnum(this Type type)
        {
            if (type.IsNullable())
                return type.GetGenericArguments()[0].IsEnum;

            return type.IsEnum;
        }

        public static bool IsNullable(this Type type)
        {
            return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
        }

        public static T InstantiateUsingParameterlessConstructor<T>(this Type type)
        {
            return (T)type.InstantiateUsingParameterlessConstructor();
        }

        public static object InstantiateUsingParameterlessConstructor(this Type type)
        {
            var constructor = ReflectHelper.GetDefaultConstructor(type);

            if (constructor == null)
                throw new MissingConstructorException(type);

            return constructor.Invoke(null);
        }

        public static bool HasInterface(this Type type, Type interfaceType)
        {
            return type.GetInterfaces().Contains(interfaceType);
        }

        public static T DeepClone<T>(this T obj)
        {
            using (var stream = new MemoryStream())
            {

#if NETFX
                var formatter = new BinaryFormatter();
#endif

#if NETCORE
                var formatter = new BinaryFormatter(new NetStandardSerialization.SurrogateSelector(), new StreamingContext());
#endif

                formatter.Serialize(stream, obj);
                stream.Seek(0, SeekOrigin.Begin);

                return (T)formatter.Deserialize(stream);
            }
        }

        public static bool IsAutoMappingOverrideType(this Type type)
        {
            return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IAutoMappingOverride<>) && type.GetGenericArguments().Length > 0;
        }
    }
}


text:
title: 'Links da Semana #49'
date: '00:00 05/30/2019'
taxonomy:
    category:
        - blog
    tag:
        - Links da Semana
---

1. As implicações e capacidades dos [índices multi coluna](https://medium.com/pgmustard/multi-column-indexes-4d17bac764c5) no PostgreSQL.

1. Lista divertida e bem explicada das [coisas que você não deve fazer](https://wiki.postgresql.org/wiki/Don't_Do_This) no PostgreSQL.

1. [Extension](https://fluca1978.github.io/2019/05/21/pgcron.html) simples do PostgreSQL para agendamento de tarefas internas. Sintaxe bem parecida com o tradicional [Crontab](https://pt.wikipedia.org/wiki/Crontab), com estar integrado ao SGBD, facilitando deploys, logs e migrações.

1. Sobre o [Índice RUM](https://habr.com/en/company/postgrespro/blog/452116/) do PostgreSQL, que é apontado por muitos como o sucessor da estrutura GIN para indexação de textos.

1. [Alerta sobre os riscos do uso dos](https://www.cybertec-postgresql.com/en/abusing-security-definer-functions/) [Security Definers](https://www.postgresql.org/docs/9.5/sql-createfunction.html) do PostgreSQL. O risco é tão grande que raramente existe algum benefício que valha a pena.

1. [Uma análise profunda e bem detalhada](https://www.2ndquadrant.com/en/blog/using-docker-hub-postgresql-images/) das imagens "oficiais" do [PostgreSQL no Docker Hub](https://hub.docker.com/_/postgres): apesar da praticidade, não são mantidas pelo time oficial do SGBD.

1. [Verificações básicas de saúde do PostgreSQL](https://www.citusdata.com/blog/2019/03/29/health-checks-for-your-postgres-database/).

1. Visões do ecossistema [PHP em 2019](https://stitcher.io/blog/php-in-2019) para contrabalancear com o clássico (e polêmico) [ataque](https://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/) escrito em 2012.

1. Porque ter [diversas classes com o mesmo nome (em namespaces diferentes)](https://www.tomasvotruba.cz/blog/2019/05/02/alias-as-a-code-smell/) pode ser um Code Smell?

1. [Solução elegante para lidar com código legado](https://geekytomato.com/command-pattern-for-legacy-code-refactoring/): Command Pattern.

1. [Análise exploratória dos dados da AirBbn em Londres](https://towardsdatascience.com/predicting-airbnb-prices-with-deep-learning-part-2-how-to-improve-your-nightly-price-50ea8bc2bd29) e quais fatores mais impactam no valor das hospedagens.

1. [Críticas ao ecossistema Python](https://pyfound.blogspot.com/2019/05/amber-brown-batteries-included-but.html) e às bibliotecas standard, que muitas vezes não evoluem com a agilidade necessária e acabam sendo substituídas por códigos externos.


text:
Make sure your operating system is at least Yosemite. My computer's operating system is El Capitan. You should have node. If not $brew install node.

## STEP 2.
Since ionic is based on "cordova" you need to install it. FYI cordova is what makes JS, HTML, CSS work on mobile.  Type in the terminal $npm -g install cordova ionic. This will install both cordova and Ionic.

## STEP 3.
To make sure ionic has installed correctly run "ionic info" in the terminal.

It should print out something like...
Your system information:
Cordova CLI: 5.0.0
Gulp version: CLI version 3.8.11
Gulp local: Local version 3.9.0
Ionic Version: 1.0.1
Ionic CLI Version: 1.6.1
Ionic App Lib Version: 0.3.3
ios-deploy version: 1.4.0
ios-sim version: 3.0.0
OS: Mac OS X Yosemite
Node Version: v0.12.2
Xcode version: Xcode 6.4 Build version 6E35b

--Note you may have a dependency warning, for stuff like  ios-sim and ios-deploy. To install those do npm install -g ios-sim and npm install -g ios-deploy. (You may have to use sudo)

## STEP 4.
You should have Xcode installed on your computer. If you don't. You can download and install Xcode from the Mac App Store or just going to the website and clicking download. The reason we need Xcode is to run an emulator on the computer.  I downloaded the 7.3 beta version. You can get away with not downloading Xcode and seeing the app in your normal chrome browser, however, it may not look/interact the same if you uploaded it to the app store.

You can see if your emulator is working by typing.
ionic emulate

If not, try typing in the following command and it should work.
sudo xcode-select -s /Applications/Xcode-Beta.app/Contents/Developer

## STEP 5.
As well as the Xcode IDE you will also need to install the command line tools, this will allow ionic to build our ios application from the terminal. The first time ionic will try to run any of the required command line tools a window will popup asking for you to install them. If for some reason it doesn't open a popup type this into the terminal:

$ xcode-select --install

## STEP 6.
It is required to run ios applications in an emulator on an iphone connected to your computer, install them now.
$ npm install -g ios-sim ios-deploy

//STARTING A PROJECT

Type in the terminal: ionic start myproject. You can now cd in myproject and it should look like...

├── bower.json
├── config.xml // cordova -- Don't worry about it
├── gulpfile.js
├── hooks // cordova commands
├── ionic.project // ionic configuration
├── package.json
├── platforms // iOS/Android builds, depending on which one you pick
├── plugins // where your cordova/ionic plugins will be installed
├── scss // scss code, which will output to www/css/
└── www // the app you will be working on

## Notes:
— If you go to the url, play.ionic.io, it allows you to play around with ionic without downloading it.

—- Ionic deploy, allows you to update the app on the users phone.

— if you CD into my app and type ionic serve it will load the app in your web browser. It is also a live reload server so if you change something, it will automatically reload.

Ionic help lists out all the commands and descriptions. You can also type ionic help <aSpecificCommandHere> to learn more about what specific command you typed it

## SOME COOL TERMINAL COMMANDS WITH IONIC
R in the terminal, it will reload the page.
C in the terminal, it enable or disable console logs.
Q in the terminal, it allows you to quit.
G in the terminal, it allows you to go to a specific URL.
ionic emulate iOS, running the app on an emulator(aka your phone)
ionic emulate iOS --target=<aThePhoneYouWanttoEmulateOn>
You can also type -cls at the end of that command. C stands for "show me console logs", l stands for "live reload", and s for "server logs"
ionic serve --lab in the terminal, it allows you see side by side, the android and IOS versions of the app.  BIG difference between android and IOS is that iOS usually has tabs at the bottom while Android has tabs at the top.

## ANOTHER WAY TO VIEW AN IONIC APP
Go to Plaforms -> iOS -> then <whateverYourAppIsCalled.xcodeproj>
This will open up xCode. Look it the top left corner, there will be a Bulldozer button. Which will allow you to select the screen size of your choosing.

Command that registers your app with the ionic platform
ionic io init - It gives you and app ID and api key. This can be found at .io.config.json file. You can also find your app id in the ionic.project file.

## Reference to ionic documentation
http://ionicframework.com/docs/api/

## BASIC CONCEPTS
<ion-pane> is the canvass
<ion-header-bar> is the header bar
<ion content> holds the content
<ion list> creates a list
<ion avatar> makes the icon smaller
ionic.Platform.ready(callback function)  -- similar to jquery's document.ready method or windows onload method.

show-delete="whatever the scope"
show-reorder="whatever in the scope"

ionic plugin add cordova-plugin-media  -- can add music to your app.
scoll allows the image to be draggable
padding class adds a small amount of padding as a default

REFRESH LOOP

<ion refresher
	pulling-text="Refresh..."
	on-refresh="doRefresh()">
</ion-refresher>

INFINITE SCROLL

<ion-infinite-scroll
 	immediate-check="false"
	on-infinite="loadMore()">
</ion-infinite-scroll>

SIMILAR TO NG-VIEW
<ion-nav-view> </ion-nav-view>

STANDARD NAV BAR
There are many classes in ionic as well. Bar-positive makes the bar blue. Fun fact is that ionic changes the
color of the font in the header correlate well with the background color.
<ion-nav-bar class="bar-positive">
	<ion-nav-back-button></ion-nav-back-button>
</ion-nav-bar>

IONIC LOADING INDICATOR
$ionicLoading can be imported as a service.
example $ionicLoading.show({template: "Loading feed..."})

Clicking into an image and going to another route.
<div class="list card"
	ng-repeat="post in feed.posts"
	ui-sref="<Name of the Function Of The State We Want To Enter">

ALLOWS THE USER TO GO BACK
<ion-nav-back-button class="hide"></ion-nav-back-button>
You must put in the nav-view-direction property of the view to forward.


text:
package com.helger.html.jscode;

import javax.annotation.Nonnull;

/**
 * Marker interface for code components that can be placed to the left of '=' in
 * an assignment. A left hand value can always be a right hand value, so this
 * interface derives from {@link IJSExpression}.
 *
 * @author Philip Helger
 */
public interface IJSAssignmentTarget extends IJSExpression
{
  @Nonnull
  JSAssignment assign (boolean bValue);

  @Nonnull
  JSAssignment assign (char cValue);

  @Nonnull
  JSAssignment assign (double dValue);

  @Nonnull
  JSAssignment assign (float fValue);

  @Nonnull
  JSAssignment assign (int nValue);

  @Nonnull
  JSAssignment assign (long nValue);

  @Nonnull
  JSAssignment assign (@Nonnull String sValue);

  @Nonnull
  JSAssignment assign (@Nonnull IJSExpression aExpr);

  @Nonnull
  JSAssignment assignPlus (char cValue);

  @Nonnull
  JSAssignment assignPlus (double dValue);

  @Nonnull
  JSAssignment assignPlus (float fValue);

  @Nonnull
  JSAssignment assignPlus (int nValue);

  @Nonnull
  JSAssignment assignPlus (long nValue);

  @Nonnull
  JSAssignment assignPlus (@Nonnull String sValue);

  @Nonnull
  JSAssignment assignPlus (@Nonnull IJSExpression aRhs);

  @Nonnull
  JSAssignment assignMinus (double dValue);

  @Nonnull
  JSAssignment assignMinus (float fValue);

  @Nonnull
  JSAssignment assignMinus (int nValue);

  @Nonnull
  JSAssignment assignMinus (long nValue);

  @Nonnull
  JSAssignment assignMinus (@Nonnull IJSExpression aExpr);

  @Nonnull
  JSAssignment assignMultiply (double dValue);

  @Nonnull
  JSAssignment assignMultiply (float fValue);

  @Nonnull
  JSAssignment assignMultiply (int nValue);

  @Nonnull
  JSAssignment assignMultiply (long nValue);

  @Nonnull
  JSAssignment assignMultiply (@Nonnull IJSExpression aRhs);

  @Nonnull
  JSAssignment assignDivide (double dValue);

  @Nonnull
  JSAssignment assignDivide (float fValue);

  @Nonnull
  JSAssignment assignDivide (int nValue);

  @Nonnull
  JSAssignment assignDivide (long nValue);

  @Nonnull
  JSAssignment assignDivide (@Nonnull IJSExpression aRhs);

  @Nonnull
  JSAssignment assignModulo (int nValue);

  @Nonnull
  JSAssignment assignModulo (long nValue);

  @Nonnull
  JSAssignment assignModulo (@Nonnull IJSExpression aRhs);
}


text:
<f:render partial="Views/Header" arguments="{person:absence.person, title:'{f:translate(id: \'approveLeave\', value: \'Approve leave\')}'}"/>

	<ehrm:flashMessages/>

	<f:form.validationResults for="absence">
		<f:if condition="{validationResults.flattenedErrors}">

				<f:for each="{validationResults.flattenedErrors}" key="propertyPath" as="errors">{propertyPath}:
					<f:for each="{errors}" as="error">

{error}

					</f:for>
				</f:for>

		</f:if>
	</f:form.validationResults>

<f:form method="post" action="update" name="absence" object="{absence}" class="compact-form form-horizontal" enctype="multipart/form-data">
	<input type="hidden" name="iscomplete" value="true" data-validate="isComplete"/>

						<f:translate id="leave.status">Status</f:translate>

						<f:translate id="{absence.requestStatus}"></f:translate>

						<f:translate id="leave.type">Type</f:translate>

						<f:translate id="{absence.absenceArrangement.label}"></f:translate>

						<f:translate id="absence.leave.startDate">Start date</f:translate>

						<f:format.date format="d-m-Y H:i">{absence.startDate}</f:format.date>

						<f:translate id="absence.leave.endDate">End date</f:translate>

						<f:format.date format="d-m-Y H:i">{absence.endDate}</f:format.date>

						<f:translate id="absence.leave.days">Days</f:translate>

						{absence.days}

						<f:translate id="absence.leave.hours">Hours</f:translate>

						{absence.hours}

						<f:translate id="reportedTo">Reported to</f:translate>

						{absence.reportedTo.name}

				<f:translate id="leave.reason">Reason</f:translate>

					{absence.reason}

				<f:translate id="leave.note">Note</f:translate>

					<f:form.textarea id="note" property="note" class="span12" rows="10"></f:form.textarea>

			 <f:translate id="Edit">Edit</f:translate>

		<f:form.hidden property="requestStatus" />
		<button type="submit" name="absence[requestStatus]" class="btn btn-success" value="accepted">
			 <f:translate id="leave.accept">accept</f:translate>
		</button>
		<button type="submit" name="absence[requestStatus]" class="btn btn-danger" value="declined">
			 <f:translate id="leave.decline">decline</f:translate>
		</button>

</f:form>


text:
404

Sorry, but the page you were trying to view does not exist.

Perhaps return to the start?


text:
module Mail
  module Encodings
    class TransferEncoding
      NAME = ''

      PRIORITY = -1

      def self.can_transport?(enc)
        enc = Encodings.get_name(enc)
        if Encodings.defined? enc
          Encodings.get_encoding(enc).new.is_a? self
        else
          false
        end
      end

      def self.can_encode?(enc)
        can_transport? enc
      end

      def self.cost(str)
        raise "Unimplemented"
      end

      def self.to_s
        self::NAME
      end

      def self.get_best_compatible(source_encoding, str)
        if self.can_transport? source_encoding then
            source_encoding
        else
            choices = []
            Encodings.get_all.each do |enc|
                choices << enc if self.can_transport? enc and enc.can_encode? source_encoding
            end
            best = nil
            best_cost = 100
            choices.each do |enc|
                this_cost = enc.cost str
                if this_cost < best_cost then
                    best_cost = this_cost
                    best = enc
                elsif this_cost == best_cost then
                    best = enc if enc::PRIORITY < best::PRIORITY
                end
            end
            best
        end
      end

      def to_s
        self.class.to_s
      end
    end
  end
end


text:
const role = require('./Role/role.module');

const moduleName   = 'users.service',
      dependencies = [ role ];

angular.module(moduleName, dependencies);

module.exports = moduleName;


text:
import React from 'react';
import { Breadcrumb, Layout, Menu } from 'antd';

const { Header, Content, Footer } = Layout;

const App: React.FC = () => (
  <Layout>

      <Menu
        theme="dark"
        mode="horizontal"
        defaultSelectedKeys={['2']}
        items={new Array(3).fill(null).map((_, index) => ({
          key: String(index + 1),
          label: `nav ${index + 1}`,
        }))}
      />

    <Content className="site-layout" style={{ padding: '0 50px', marginTop: 64 }}>
      <Breadcrumb style={{ margin: '16px 0' }}>
        <Breadcrumb.Item>Home</Breadcrumb.Item>
        <Breadcrumb.Item>List</Breadcrumb.Item>
        <Breadcrumb.Item>App</Breadcrumb.Item>
      </Breadcrumb>

        Content

    </Content>
    Ant Design ©2018 Created by Ant UED
  </Layout>
);

export default App;