text:
class Predictor

  # top level metadata
  attr_accessor :features, :outputs, :market, :twitter, :tweets,

    # stock metadata
    :stock, :start_day, :end_day,

    # stock price values
    :start_price, :end_price, :delta,

    # neural network
    :input_layer, :hidden_layer, :output_layer,
    :num_input_nodes, :num_hidden_nodes, :num_output_nodes,
    :input_weights, :hidden_weights,

    # back propagation NN
    :output_error, :hidden_error,
    :previous_input_weight_deltas, :previous_hidden_weight_deltas

  def set_features stock, search_term, start_day, end_day
    self.market = Market.new
    self.start_day = start_day
    self.end_day = end_day
    self.stock = stock
    quotes = market.get_endprices(stock, start_day, end_day)
    self.start_price = quotes[0].to_f
    self.end_price = quotes[1].to_f
    self.delta = end_price.to_f - start_price.to_f

    self.twitter = TwitterEngine.new
    self.tweets = twitter.get_tweets(search_term, "recent")
    self.features = twitter.get_features(tweets)
  end

  def set_stocks stock, features, start_day, end_day
    self.market = Market.new
    self.start_day = start_day
    self.end_day = end_day
    self.stock = stock
    quotes = market.get_endprices(stock, start_day, end_day)
    self.start_price = quotes[0].to_f
    self.end_price = quotes[1].to_f
    self.delta = end_price.to_f - start_price.to_f
    self.features = features
  end

  def normalize_expected value
    new_val = value + 0.5
    if new_val > 1 then new_val = 1 end
    if new_val < 0 then new_val = 0 end
    new_val
  end

  def set_new_features search_term
    self.tweets = twitter.get_tweets(search_term, "recent")
    self.features = twitter.get_features(tweets)
    build_neural_net
  end

  def reset_features features
    self.features = features
    build_neural_net
  end

  def set_default_network_values hidden_nodes
    self.num_input_nodes = features.length
    self.num_hidden_nodes = hidden_nodes
    self.num_output_nodes = 1

    self.input_weights = Array.new(num_hidden_nodes) {
      Array.new(num_input_nodes+1)
    }
    self.hidden_weights = Array.new(num_output_nodes) {
      Array.new(num_hidden_nodes+1)
    }

    random_weights(input_weights)
    random_weights(hidden_weights)

    self.previous_input_weight_deltas = Array.new(num_hidden_nodes) {
      Array.new(num_input_nodes+1, 0)
    }
    self.previous_hidden_weight_deltas = Array.new(num_output_nodes) {
      Array.new(num_hidden_nodes+1, 0)
    }
  end

  def set_network_values input_weights, hidden_weights, num_hidden_nodes, num_output_nodes
    self.input_weights = input_weights
    self.hidden_weights = hidden_weights

    self.num_hidden_nodes = num_hidden_nodes
    self.num_output_nodes = num_output_nodes
  end

  def build_input_layer
    self.input_layer = Array.new(features.length, 0)
    features.each_with_index do |count, index|
      input_layer[index] = count
    end
    input_layer[-1] = -1
  end

  def build_neural_net
    build_input_layer
    self.hidden_layer = build_new_layer(num_hidden_nodes+1, input_layer, input_weights)
    hidden_layer[-1] = -1
    self.output_layer = build_new_layer(num_output_nodes, hidden_layer, hidden_weights)
  end

  def random_weights(weights)
    (0...weights.size).each do |i|
      (0...weights[i].size).each do |j|
        weights[i][j] = rand(-0.5...0.5)
      end
    end
  end

  # goes through forward propagation algorithm
  def build_new_layer layer_size, input_layer, weights
    next_layer = Array.new(layer_size, 0)

    (0...weights.size).each do |index|
      combined_array = input_layer.zip(weights[index])
      z_value = combined_array.map{|v,w| v*w}.inject(:+)
      activation = sigmoid(z_value)
      next_layer[index] = activation
    end

    next_layer
  end

  def hypothesis
    output_layer[0]
  end

  def element_add array_1, array_2
    combined_array = input_layer.zip(weights[index])
    z_value = combined_array.map{|v,w| v*w}.inject(:+)
  end

  def back_propogation expected_value, learning_rate, momentum_rate
    self.output_error = [(expected_value - hypothesis) * d_sigmoid(hypothesis)]
    self.hidden_error = calculate_hidden_error_gradients
    update_weights(hidden_layer, input_layer, input_weights, hidden_error, learning_rate, previous_input_weight_deltas, momentum_rate)
    update_weights(output_layer, hidden_layer, hidden_weights, output_error, learning_rate, previous_hidden_weight_deltas, momentum_rate)
  end

  def reversed_hidden_weights
    reversed = Array.new(hidden_layer.size) {
      Array.new(output_layer.size)
    }
    hidden_weights.each_index do |i|
      hidden_weights[i].each_index do |j|
        reversed[j][i] = hidden_weights[i][j]
      end
    end
    reversed
  end

  def calculate_hidden_error_gradients
    reversed = reversed_hidden_weights
    hidden_layer.each_with_index.map do |node, i|
      combined_array = output_error.zip(reversed[i])
      sum_array = combined_array.map{|error, weight| error*weight}.inject(:+)
      d_sigmoid(hidden_layer[i]) * sum_array
    end
  end

  def update_weights nodes, values, weights, gradients, learning_rate, previous_deltas, momentum_rate
    weights.each_index do |i|
      weights[i].each_index do |j|
        if !values[j].nil? # last weight mismatch because of bias unit
          delta = learning_rate * gradients[i] * values[j]
          weights[i][j] += delta + momentum_rate * previous_deltas[i][j]
          previous_deltas[i][j] = delta
        end
      end
    end
  end

  def train expected_value, learning_rate, momentum_rate
    build_neural_net
    back_propogation(expected_value, learning_rate, momentum_rate)
  end

  # sigmoid function for forward propagation
  def sigmoid x
    1.0 / (1 + Math::E** -x)
  end

  # sigmoid function for back propagation
  def d_sigmoid(x)
    sigmoid(x) * (1 - sigmoid(x))
  end

end


text:
import React, { PropTypes } from 'react';
import { transparentBg } from '../styles';

// Functional stateless components
//   If the component only renders UI, can make it return instead of rendering
function Prompt(props) {
  return (

{props.header}

        <form onSubmit={props.onSubmitUser}>

            <input
              className="form-group"
              placeholder="Github Username"
              onChange={props.onUpdateUser}
              value={props.username}
              type="text"  />

            <button
              className="btn btn-block btn-success"
              type="submit">
                Continue
            </button>

        </form>

  );
};

// Make proptypes as a property of the function itself
Prompt.propTypes = {
    header: PropTypes.string.isRequired,
    username: PropTypes.string.isRequired,
    onUpdateUser: PropTypes.func.isRequired,
    onSubmitUser: PropTypes.func.isRequired,
  };

export default Prompt;

redpajama_set_name: RedPajamaGithub


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Page extends CI_Controller {

	public function index()
	{
		$this->show('default_page');
	}

	public function show($page = 'default_page')
	{
		$this->load->view($page);
	}
}


text:
#include "config.h"
#include "dispatch_table.h"

#include "types_private.h"
#include "thread_private.h"
#include <dlfcn.h>
#include <stdlib.h>

mutex_static_init (dispatch_table_mutex);

static void *
find_gl_symbol (void *handle,
                __eglMustCastToProperFunctionPointerType (*getProcAddress) (const char *procname),
                const char *symbol_name)
{
    void *symbol = dlsym (handle, symbol_name);
    if (symbol == NULL)
        symbol = getProcAddress (symbol_name);
    return symbol;
}

static void *
libgl_handle ()
{
    static void *handle = NULL;
    if (handle)
        return handle;

    static const char *default_libgl_name = "libGLESv2.so";
    const char *libgl = getenv ("GPUPROCESS_LIBGLES_PATH");

    handle = dlopen (libgl ? libgl : default_libgl_name, RTLD_LAZY);
    return handle;
}

static void *
libegl_handle ()
{
    static void *handle = NULL;
    if (handle)
        return handle;

    static const char *default_libegl_name = "libEGL.so";
    const char *libegl = getenv ("GPUPROCESS_LIBEGL_PATH");

    handle = dlopen (libegl ? libegl : default_libegl_name, RTLD_LAZY);
    return handle;
}

#include "dispatch_table_autogen.c"

dispatch_table_t *
dispatch_table_get_base ()
{
    static dispatch_table_t dispatch;
    static bool table_initialized = false;

    mutex_lock (dispatch_table_mutex);

    /* In case two threads got here at the same time, we want to return
     * the dispatch table if another thread already initialized it */
    if (table_initialized) {
        mutex_unlock (dispatch_table_mutex);
        return &dispatch;
    }

    FunctionPointerType *temp = NULL;
    temp = (FunctionPointerType *) &real_eglInitialize;
    *temp = dlsym (libegl_handle (), "eglInitialize");
    temp = (FunctionPointerType *) &real_eglGetDisplay;
    *temp = dlsym (libegl_handle (), "eglGetDisplay");

    real_eglInitialize (real_eglGetDisplay (EGL_DEFAULT_DISPLAY), NULL, NULL);
    dispatch_table_fill_base (&dispatch);

    table_initialized = true;

    mutex_unlock (dispatch_table_mutex);

    return &dispatch;
}


text:
(function(document, window, $) {
  'use strict';

  var Site = window.Site;
  var action = "save";
  var idAction = "-1";
  $(document).ready(function($) {
    Site.run();
  });

  // Fixed Header Example
  // --------------------
  (function() {
    var offsetTop = 0;
    if ($('.site-navbar').length > 0) {
      offsetTop = $('.site-navbar').eq(0).innerHeight();
    }

    // initialize datatable
    var table = $('#exampleFixedHeader').DataTable({
      responsive: true,
      fixedHeader: {
        header: true,
        headerOffset: offsetTop
      },
      "bPaginate": false,
      "sDom": "t" // just show table, no other controls
    });

    // redraw fixedHeaders as necessary
    // $(window).resize(function() {
    //   fixedHeader._fnUpdateClones(true);
    //   fixedHeader._fnUpdatePositions();
    // });
  })();

  // Individual column searching
  // ---------------------------
  (function() {
    $(document).ready(function() {
      var defaults = $.components.getDefaults("dataTable");

      var options = $.extend(true, {}, defaults, {
        initComplete: function() {
          this.api().columns().every(function() {
            var column = this;
            var select = $('<select class="form-control width-full"><option value=""></option></select>')
              .appendTo($(column.footer()).empty())
              .on('change', function() {
                var val = $.fn.dataTable.util.escapeRegex(
                  $(this).val()
                );

                column
                  .search(val ? '^' + val + '$' : '', true, false)
                  .draw();
              });

            column.data().unique().sort().each(function(d, j) {
              select.append('<option value="' + d + '">' + d + '</option>')
            });
          });
        }
      });

      $('#exampleTableSearch').DataTable(options);
    });
  })();

  // Table Tools
  // -----------
  (function() {

    $(document).ready(function() {
      var defaults = $.components.getDefaults("dataTable");

      var options = $.extend(true, {}, defaults, {
        "aoColumnDefs": [{
          'bSortable': false,
          'aTargets': [-1]
        }],
        "iDisplayLength": 5,
        "aLengthMenu": [
          [5, 10, 25, 50, -1],
          [5, 10, 25, 50, "All"]
        ],
        "sDom": '<"dt-panelmenu clearfix"Tfr>t<"dt-panelfooter clearfix"ip>',
        "oTableTools": {
          "sSwfPath": "../../../global/vendor/datatables-tabletools/swf/copy_csv_xls_pdf.swf"
        }
      });

      $('#exampleTableTools').dataTable(options);
    });
  })();

  // Table Add Row
  // -------------
  (function($) {
    var EditableTable = {

      options: {
        addButton: '#addToTable',
        table: '#tableMAC',
        dialog: {
          wrapper: '#dialog',
          cancelButton: '#dialogCancel',
          confirmButton: '#dialogConfirm',
        }
      },

      initialize: function() {
        this
          .setVars()
          .build()
          .events();
      },

      setVars: function() {
        this.$table = $(this.options.table);
        this.$addButton = $(this.options.addButton);

        // dialog
        this.dialog = {};
        this.dialog.$wrapper = $(this.options.dialog.wrapper);
        this.dialog.$cancel = $(this.options.dialog.cancelButton);
        this.dialog.$confirm = $(this.options.dialog.confirmButton);

        return this;
      },

      build: function() {
        this.datatable = this.$table.DataTable({
          aoColumns: [
        	  null, {
              "bSortable": false
            }
          ],
          language: {
            "sSearchPlaceholder": "Search..",
            "lengthMenu": "_MENU_",
            "search": "_INPUT_"
          }
        });

        window.dt = this.datatable;

        return this;
      },

      events: function() {
        var _self = this;

        this.$table
          .on('click', 'a.save-row', function(e) {
            e.preventDefault();

            _self.rowSave($(this).closest('tr'));
          })
          .on('click', 'a.cancel-row', function(e) {
            e.preventDefault();
			action = "cancel";
            _self.rowCancel($(this).closest('tr'));
          })
          .on('click', 'a.edit-row', function(e) {
            e.preventDefault();
			action = "edit";
            _self.rowEdit($(this).closest('tr'));
          })
          .on('click', 'a.remove-row', function(e) {
            e.preventDefault();
			action = "delete";
            var $row = $(this).closest('tr');
            bootbox.dialog({
              message: "Tem certeza de que deseja excluir este item?",
              title: "VOCE TEM CERTEZA?",
              buttons: {
                danger: {
                  label: "SIM",
                  className: "btn-danger",
                  callback: function() {
                    _self.rowRemove($row);
                  }
                },
                main: {
                  label: "NÃO",
                  className: "btn-primary",
                  callback: function() {}
                }
              }
            });
          });

        this.$addButton.on('click', function(e) {
          e.preventDefault();
			action = "save";
          _self.rowAdd();
        });

        this.dialog.$cancel.on('click', function(e) {
          e.preventDefault();
          $.magnificPopup.close();
        });

        return this;
      },

      // =============
      // ROW FUNCTIONS
      // =============
      rowAdd: function() {

        this.$addButton.attr({
          'disabled': 'disabled'
        });

        var actions,
          data,
          $row;

        actions = [
          '',
          '',
          '',
          ''
        ].join(' ');

        data = this.datatable.row.add(['',   actions]);
        $row = this.datatable.row(data[0]).nodes().to$();

        $row
          .addClass('adding')
          .find('td:last')
          .addClass('actions');;
        this.rowEdit($row);
        this.datatable.order([0, 'asc']).draw(); // always show fields
      },

      rowCancel: function($row) {
        var _self = this,
          $actions,
          i,
          data;

        if ($row.hasClass('adding')) {
          this.rowRemove($row);
        } else {

          data = this.datatable.row($row.get(0)).data();
          this.datatable.row($row.get(0)).data(data);

          $actions = $row.find('td.actions');
          if ($actions.get(0)) {
            this.rowSetActionsDefault($row);
          }

          this.datatable.draw();
        }
      },

      rowEdit: function($row) {
        var _self = this,
          data;

        data = this.datatable.row($row.get(0)).data();
		var valueStatus;
		var valueTipo;
        $row.children('td').each(function(i) {
          var $this = $(this);

          if ($this.hasClass('actions')) {
            _self.rowSetActionsEditing($row);
          } else {
			if(i == 0) {
			  $this.html('<input type="number" id="' + i + '" class="form-control input-normal" style="width: 80px;" value="' + data[i] + '"/>');
              idAction = data[i];
			} else if(i == 2) {
			  $this.html('<select  id="selectStatus" class="form-control" style="width: 100%;" data-plugin="select">' + rowStatusAgvs() + '</select>');
              valueStatus = data[i];
			} else if(i == 3) {
			  $this.html('<select  id="selectTipo" class="form-control" style="width: 100%;" data-plugin="select">' + rowTipoAGVS() + '</select>');
              valueTipo = data[i];
			} else {
              $this.html('<input type="text" id="' + i + '" class="form-control input-block" style="width: 100%;" value="' + data[i] + '"/>');
            }
          }
        });
		var element = document.getElementById('selectStatus');
		if(valueStatus != '')
			element.value = valueStatus;

		var element1 = document.getElementById('selectTipo');
		if(valueTipo != '')
			element1.value = valueTipo;
      },

      rowSave: function($row) {
		var link = '/ActionConfigMAC?action=' + action + '&mac64=' + document.getElementById("1").value;
		if(enviarDados(link)){
	        var _self = this,
	          $actions,
	          values = [];

	        if ($row.hasClass('adding')) {
	          this.$addButton.removeAttr('disabled');
	          $row.removeClass('adding');
	        }

	        values = $row.find('td').map(function() {
	          var $this = $(this);
	          if ($this.hasClass('actions')) {
	            _self.rowSetActionsDefault($row);
	            return _self.datatable.cell(this).data();
	          } else {
				return $.trim('<input type="text" id="1" class="form-control input-large" value="' + $this.find('input').val() + '"/>');
	          }
	        });

	        this.datatable.row($row.get(0)).data(values);

	        $actions = $row.find('td.actions');
	        if ($actions.get(1)) {
	          this.rowSetActionsDefault($row);
	        }
	        this.datatable.draw();
		}
      },

      rowRemove: function($row) {
        if ($row.hasClass('adding')) {
          this.$addButton.removeAttr('disabled');
        }
		var id = $row.get(0).cells[0].innerHTML;
		var link = "/ActionCadastroAGVS?action=delete&id=" + id;
		if(action == "delete") {
			if(enviarDados(link)) {
				this.datatable.row($row.get(0)).remove().draw();
			}
		} else {
			this.datatable.row($row.get(0)).remove().draw();
		}
      },

      rowSetActionsEditing: function($row) {
        $row.find('.on-editing').removeClass('hidden');
        $row.find('.on-default').addClass('hidden');
      },

      rowSetActionsDefault: function($row) {
        $row.find('.on-editing').addClass('hidden');
        $row.find('.on-default').removeClass('hidden');
      }

    };

    $(function() {
      EditableTable.initialize();
    });

  }).apply(this, [jQuery]);

})(document, window, jQuery);


text:
@implementation PBBAAppUtils

+ (BOOL)isCFIAppAvailable
{
    return [PBBALibraryUtils isCFIAppAvailable];
}

+ (BOOL)openBankingApp:(NSString *)secureToken
{
    NSAssert(secureToken, @"[PBBAAppUtils] 'secureToken' is a mandatory parameter.");

    return [PBBALibraryUtils openBankingApp:secureToken];
}

+ (PBBAPopupViewController *)showPBBAPopup:(UIViewController *)presenter
                               secureToken:(NSString *)secureToken
                                       brn:(NSString *)brn
                                  delegate:(id<PBBAPopupViewControllerDelegate>)delegate
{
    NSAssert(presenter, @"[PBBAAppUtils] 'presenter' is a mandatory parameter.");
    NSAssert(secureToken, @"[PBBAAppUtils] 'secureToken' is a mandatory parameter.");
    NSAssert(brn, @"[PBBAAppUtils] 'brn' is a mandatory parameter.");
    NSAssert(brn.length == 6, @"[PBBAAppUtils] 'brn' length must be 6 characters.");

    if ([PBBALibraryUtils shouldLaunchCFIApp]) {

        // Dismiss any instance of the presented PBBAPopupViewController before opening the CFI app
        if ([presenter.presentedViewController isKindOfClass:[PBBAPopupViewController class]]) {
            [presenter dismissViewControllerAnimated:NO completion:nil];
        }

        // Launch CFI app and exit early
        if ([self openBankingApp:secureToken]) {
            return nil;
        }
    }

    // Update the already presented instance of PBBAPopupViewController instead of recreating it
    if ([presenter.presentedViewController isKindOfClass:[PBBAPopupViewController class]]) {
        PBBAPopupViewController *pbbaPopupVC = (PBBAPopupViewController *) presenter.presentedViewController;
        [pbbaPopupVC updateWithSecureToken:secureToken
                                       brn:brn];

        pbbaPopupVC.delegate = delegate;

        // Exit early
        return pbbaPopupVC;
    }

    // Create a new instance of PBBAPopupViewController and try to present it
    PBBAPopupViewController *pbbaPopupVC = [[PBBAPopupViewController alloc] initWithSecureToken:secureToken
                                                                                brn:brn
                                                                                delegate:delegate];
    return [self presentPBBAPopup:pbbaPopupVC presenter:presenter];
}

+ (PBBAPopupViewController *)showPBBAErrorPopup:(UIViewController *)presenter
                                      errorCode:(NSString *)errorCode
                                     errorTitle:(NSString *)errorTitle
                                   errorMessage:(NSString *)errorMessage
                                       delegate:(id<PBBAPopupViewControllerDelegate>)delegate
{
    NSAssert(presenter, @"[PBBAAppUtils] 'presenter' is a mandatory parameter.");
    NSAssert(errorMessage, @"[PBBAAppUtils] 'errorMessage' is a mandatory parameter.");

    // Update the already presented instance of PBBAPopupViewController instead of recreating it
    if ([presenter.presentedViewController isKindOfClass:[PBBAPopupViewController class]]) {
        PBBAPopupViewController *pbbaPopupVC = (PBBAPopupViewController *) presenter.presentedViewController;
        [pbbaPopupVC updateWithErrorCode:errorCode
                              errorTitle:errorTitle
                            errorMessage:errorMessage];

        pbbaPopupVC.delegate = delegate;

        // Exit early
        return pbbaPopupVC;
    }

    // Create a new instance of PBBAPopupViewController and try to present it
    PBBAPopupViewController *pbbaPopupVC = [[PBBAPopupViewController alloc] initWithErrorCode:errorCode
                                                                                errorTitle:errorTitle
                                                                                errorMessage:errorMessage
                                                                                delegate:delegate];

    return [self presentPBBAPopup:pbbaPopupVC presenter:presenter];
}

+ (PBBAPopupViewController *)presentPBBAPopup:(PBBAPopupViewController *)pbbaPopupVC
                                    presenter:(UIViewController *)presenter
{
    [presenter presentViewController:pbbaPopupVC animated:YES completion:nil];

    // Return nil if the attempt to present the PBBAPopupViewController has failed
    return (presenter.presentedViewController == pbbaPopupVC) ? pbbaPopupVC : nil;
}

@end


text:
using System;
using System.IO;
using System.Text;
using Microsoft.Win32;

namespace DriveProxy.Utils
{
  internal enum RegistryKeyType
  {
    ClassesRoot,
    CurrentConfig,
    CurrentUser,
    LocalMachine,
    PerformanceData,
    Users,
  }

  internal enum RegistryNodeType
  {
    HKEY_CLASSES_ROOT,
    HKEY_CURRENT_CONFIG,
    HKEY_CURRENT_USER,
    HKEY_LOCAL_MACHINE,
    HKEY_PERFORMANCE_DATA,
    HKEY_USERS,
  }

  internal class Registry : IDisposable
  {
    private RegistryKey _key;
    private RegistryKeyType _keyType = RegistryKeyType.LocalMachine;

    private string _subKey = "";

    public Registry()
    {
    }

    public Registry(RegistryKeyType keyType, bool createIfDoesNotExist = false)
    {
      Open(keyType, createIfDoesNotExist);
    }

    public Registry(RegistryKeyType keyType, string subKey, bool createIfDoesNotExist = false)
    {
      Open(keyType, subKey, createIfDoesNotExist);
    }

    public RegistryKeyType KeyType
    {
      get { return _keyType; }
    }

    public RegistryKey Key
    {
      get { return _key; }
    }

    public string SubKey
    {
      get { return _subKey; }
    }

    public bool IsOpen
    {
      get
      {
        if (_key != null)
        {
          return true;
        }

        return false;
      }
    }

    public void Dispose()
    {
      try
      {
        Close();
      }
      catch (Exception exception)
      {
        Log.Error(exception, false);
      }
    }

    public void Close()
    {
      try
      {
        if (_key != null)
        {
          _key.Close();
        }
      }
      catch (Exception exception)
      {
        Log.Error(exception, false);
      }
      finally
      {
        _key = null;
      }
    }

    public void Delete()
    {
      try
      {
        ValidateIsOpen();

        Key.DeleteSubKey(SubKey);
      }
      catch (Exception exception)
      {
        Log.Error(exception);
      }
    }

    public void DeleteValue(string name)
    {
      try
      {
        ValidateIsOpen();

        if (name == null)
        {
          throw new Exception("Input parameter 'name' is blank.");
        }

        Key.DeleteValue(name);
      }
      catch (Exception exception)
      {
        Log.Error(exception);
      }
    }

    public object GetDefaultValue(object defaultValue = null)
    {
      try
      {
        return GetValue("", defaultValue);
      }
      catch (Exception exception)
      {
        Log.Error(exception);

        return null;
      }
    }

    public object GetValue(string name, object defaultValue = null)
    {
      try
      {
        ValidateIsOpen();

        if (name == null)
        {
          throw new Exception("Input parameter 'name' is blank.");
        }

        object value = Key.GetValue(name, defaultValue);

        if (value == null)
        {
          return defaultValue;
        }

        return value;
      }
      catch (Exception exception)
      {
        Log.Error(exception);

        return null;
      }
    }

    public string[] GetSubKeyNames()
    {
      try
      {
        ValidateIsOpen();

        string[] subKeyNames = _key.GetSubKeyNames();

        return subKeyNames;
      }
      catch (Exception exception)
      {
        Log.Error(exception);

        return null;
      }
    }

    public string[] GetValueNames()
    {
      try
      {
        ValidateIsOpen();

        string[] valueNames = _key.GetValueNames();

        return valueNames;
      }
      catch (Exception exception)
      {
        Log.Error(exception);

        return null;
      }
    }

    public bool Open(bool createIfDoesNotExist = false)
    {
      try
      {
        return Open(KeyType, SubKey, createIfDoesNotExist);
      }
      catch (Exception exception)
      {
        Log.Error(exception);

        return false;
      }
    }

    public bool Open(RegistryKeyType keyType, bool createIfDoesNotExist = false)
    {
      try
      {
        return Open(keyType, SubKey, createIfDoesNotExist);
      }
      catch (Exception exception)
      {
        Log.Error(exception);

        return false;
      }
    }

    public bool Open(string subKey, bool createIfDoesNotExist = false)
    {
      try
      {
        return Open(KeyType, subKey, createIfDoesNotExist);
      }
      catch (Exception exception)
      {
        Log.Error(exception);

        return false;
      }
    }

    public bool Open(RegistryKeyType keyType, string subKey, bool createIfDoesNotExist = false)
    {
      try
      {
        Close();

        this._keyType = keyType;

        _key = createIfDoesNotExist ? CreateSubKey(keyType, subKey) : OpenSubKey(keyType, subKey);

        this._subKey = subKey;

        return IsOpen;
      }
      catch (Exception exception)
      {
        Log.Error(exception);

        return false;
      }
    }

    public void SetDefaultValue(object value)
    {
      try
      {
        SetValue("", value);
      }
      catch (Exception exception)
      {
        Log.Error(exception);
      }
    }

    public void SetDefaultValue(object value, RegistryValueKind valueKind)
    {
      try
      {
        SetValue("", value, valueKind);
      }
      catch (Exception exception)
      {
        Log.Error(exception);
      }
    }

    public void SetValue(string name, object value)
    {
      try
      {
        SetValue(name, value, RegistryValueKind.Unknown);
      }
      catch (Exception exception)
      {
        Log.Error(exception);
      }
    }

    public void SetValue(string name, object value, RegistryValueKind valueKind)
    {
      try
      {
        ValidateIsOpen();

        if (name == null)
        {
          throw new Exception("Input parameter 'name' is blank.");
        }

        if (value == null)
        {
          throw new Exception("Input parameter 'value' is null.");
        }

        if (valueKind == RegistryValueKind.Unknown)
        {
          Key.SetValue(name, value);
        }
        else
        {
          Key.SetValue(name, value, valueKind);
        }
      }
      catch (Exception exception)
      {
        Log.Error(exception);
      }
    }

    public void ValidateIsOpen()
    {
      try
      {
        if (!IsOpen)
        {
          throw new Exception("The Registry object has not been opened.");
        }
      }
      catch (Exception exception)
      {
        Log.Error(exception);
      }
    }

    protected RegistryKey CreateSubKey(RegistryKeyType keyType, string subKey)
    {
      try
      {
        if (keyType == RegistryKeyType.ClassesRoot)
        {
          return Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(subKey);
        }
        if (keyType == RegistryKeyType.CurrentConfig)
        {
          return Microsoft.Win32.Registry.CurrentConfig.CreateSubKey(subKey);
        }
        if (keyType == RegistryKeyType.CurrentUser)
        {
          return Microsoft.Win32.Registry.CurrentUser.CreateSubKey(subKey);
        }
        if (keyType == RegistryKeyType.LocalMachine)
        {
          return Microsoft.Win32.Registry.LocalMachine.CreateSubKey(subKey);
        }
        if (keyType == RegistryKeyType.PerformanceData)
        {
          return Microsoft.Win32.Registry.PerformanceData.CreateSubKey(subKey);
        }
        if (keyType == RegistryKeyType.Users)
        {
          return Microsoft.Win32.Registry.Users.CreateSubKey(subKey);
        }
        throw new Exception("Input parameter 'keyType' is not implemented.");
      }
      catch (Exception exception)
      {
        Log.Error(exception);

        return null;
      }
    }

    protected RegistryKey OpenSubKey(RegistryKeyType keyType, string subKey)
    {
      try
      {
        if (subKey == null)
        {
          throw new Exception("Input parameter 'subKey' is blank.");
        }

        if (keyType == RegistryKeyType.ClassesRoot)
        {
          return Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(subKey);
        }
        if (keyType == RegistryKeyType.CurrentConfig)
        {
          return Microsoft.Win32.Registry.CurrentConfig.OpenSubKey(subKey);
        }
        if (keyType == RegistryKeyType.CurrentUser)
        {
          return Microsoft.Win32.Registry.CurrentUser.OpenSubKey(subKey);
        }
        if (keyType == RegistryKeyType.LocalMachine)
        {
          return Microsoft.Win32.Registry.LocalMachine.OpenSubKey(subKey);
        }
        if (keyType == RegistryKeyType.PerformanceData)
        {
          return Microsoft.Win32.Registry.PerformanceData.OpenSubKey(subKey);
        }
        if (keyType == RegistryKeyType.Users)
        {
          return Microsoft.Win32.Registry.Users.OpenSubKey(subKey);
        }
        throw new Exception("Input parameter 'keyType' is not implemented.");
      }
      catch (Exception exception)
      {
        Log.Error(exception);

        return null;
      }
    }

    public static void Create(RegistryKeyType keyType, string subKey)
    {
      try
      {
        if (Exists(keyType, subKey))
        {
          return;
        }

        using (var registry = new Registry(keyType, subKey, true))
        {
          if (!registry.IsOpen)
          {
            throw new Exception("Could not create registry key " + keyType + "\\" + subKey);
          }
        }
      }
      catch (Exception exception)
      {
        Log.Error(exception);
      }
    }

    public static void Delete(RegistryKeyType keyType, string subKey)
    {
      try
      {
        if (!Exists(keyType, subKey))
        {
          return;
        }

        using (var registry = new Registry(keyType, subKey))
        {
          registry.Delete();
        }
      }
      catch (Exception exception)
      {
        Log.Error(exception);
      }
    }

    public static bool Exists(RegistryKeyType keyType, string subKey)
    {
      try
      {
        using (var registry = new Registry(keyType, subKey, false))
        {
          if (registry.IsOpen)
          {
            return true;
          }

          return false;
        }
      }
      catch (Exception exception)
      {
        Log.Error(exception);

        return false;
      }
    }

    public static void WriteToFile(string filePath)
    {
      try
      {
        using (FileStream fileStream = File.Open(filePath, FileMode.Create, FileAccess.Write, FileShare.Write))
        {
          using (var streamWriter = new StreamWriter(fileStream, Encoding.Unicode))
          {
            streamWriter.WriteLine("Windows Registry Editor Version 5.00");
            streamWriter.WriteLine("");

            var registry = new Registry();

            WriteToFile(streamWriter, registry, RegistryKeyType.ClassesRoot, "");
            WriteToFile(streamWriter, registry, RegistryKeyType.CurrentUser, "");
            WriteToFile(streamWriter, registry, RegistryKeyType.LocalMachine, "");
            WriteToFile(streamWriter, registry, RegistryKeyType.Users, "");
            WriteToFile(streamWriter, registry, RegistryKeyType.CurrentConfig, "");
          }
        }
      }
      catch (Exception exception)
      {
        Log.Error(exception);
      }
    }

    protected static void WriteToFile(StreamWriter streamWriter,
                                      Registry registry,
                                      RegistryKeyType keyType,
                                      string subKey)
    {
      try
      {
        string line = "";

        try
        {
          line = "[" + ((RegistryNodeType)keyType);

          if (!String.IsNullOrEmpty(subKey))
          {
            line += "\\" + subKey;
          }

          line += "]";

          streamWriter.WriteLine(line);

          if (!registry.Open(keyType, subKey))
          {
            line = "ERROR - COULD NOT OPEN";

            streamWriter.WriteLine(line);

            return;
          }
        }
        catch (Exception exception)
        {
          line = "ERROR - " + exception.Message.ToUpper();

          streamWriter.WriteLine(line);

          return;
        }

        string[] valueNames = registry.GetValueNames();

        if (valueNames == null)
        {
          line = "ERROR - COULD NOT GET VALUE NAMES";

          streamWriter.WriteLine(line);
        }
        else
        {
          foreach (string valueName in valueNames)
          {
            if (String.IsNullOrEmpty(valueName))
            {
              line = "@=";
            }
            else
            {
              line = "\"" + valueName + "\"=";
            }

            object value = registry.GetValue(valueName);

            if (value == null)
            {
              line += "NULL";
            }
            else
            {
              line += "\"" + value + "\"";
            }

            try
            {
              streamWriter.WriteLine(line);
            }
            catch (Exception exception)
            {
              line = "ERROR - " + exception.Message.ToUpper();

              streamWriter.WriteLine(line);
            }
          }
        }

        streamWriter.WriteLine("");

        string[] subKeyNames = registry.GetSubKeyNames();

        if (subKeyNames == null)
        {
          line = "ERROR - COULD NOT GET SUBKEY NAMES";

          streamWriter.WriteLine(line);
        }
        else
        {
          foreach (string subKeyName in subKeyNames)
          {
            string subKeyPath = "";

            if (String.IsNullOrEmpty(subKey))
            {
              subKeyPath = subKeyName;
            }
            else
            {
              subKeyPath = subKey + "\\" + subKeyName;
            }

            WriteToFile(streamWriter, registry, keyType, subKeyPath);
          }
        }
      }
      catch (Exception exception)
      {
        Log.Error(exception);
      }
    }
  }
}


text:
package nl.ypmamedia.googlefaces.model;

public class Column {

    public enum Type {date, number, string};

    String header;
    Type type;

    public Column(Type type, String title) {
        super();
        this.header = title;
        this.type = type;
    }

    public String getHeader() {
        return header;
    }
    public void setHeader(String title) {
        this.header = title;
    }

    public Type getType() {
        return type;
    }
    public void setType(Type type) {
        this.type = type;
    }
}


text:
package com.ansorgit.plugins.bash.lang.psi.impl.word;

import javax.annotation.Nonnull;

import com.ansorgit.plugins.bash.lang.psi.BashVisitor;
import com.ansorgit.plugins.bash.lang.psi.api.word.BashExpansion;
import com.ansorgit.plugins.bash.lang.psi.impl.BashBaseStubElementImpl;
import com.ansorgit.plugins.bash.lang.valueExpansion.ValueExpansionUtil;
import com.ansorgit.plugins.bash.settings.BashProjectSettings;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.stubs.StubElement;

/**
 * User: jansorg
 * Date: Nov 14, 2009
 * Time: 3:04:41 PM
 */
public class BashExpansionImpl extends BashBaseStubElementImpl<StubElement> implements BashExpansion {
    public BashExpansionImpl(ASTNode astNode) {
        super(astNode, "Bash expansion");
    }

    @Override
    public void accept(@Nonnull PsiElementVisitor visitor) {
        if (visitor instanceof BashVisitor) {
            BashVisitor v = (BashVisitor) visitor;
            v.visitExpansion(this);
        } else {
            visitor.visitElement(this);
        }
    }

    public String getUnwrappedCharSequence() {
        return getText();
    }

    public boolean isStatic() {
        return true;
    }

    @Nonnull
    public TextRange getTextContentRange() {
        return TextRange.from(0, getTextLength());
    }

    public boolean isWrappable() {
        return false;
    }

    public boolean isValidExpansion() {
        return ValueExpansionUtil.isValid(getText(), BashProjectSettings.storedSettings(getProject()).isSupportBash4());
    }
}


text:
id: bd7156d8c242eddfaeb5bd13
title: Build a freeCodeCamp Forum Homepage
challengeType: 3
forumTopicId: 302349
dashedName: build-a-freecodecamp-forum-homepage
---

# --description--

**Objective:** Build a [CodePen.io](https://codepen.io) app that is functionally similar to this: <https://codepen.io/freeCodeCamp/full/JqdoMV>.

Fulfill the below [user stories](https://en.wikipedia.org/wiki/User_story). Use whichever libraries or APIs you need. Give it your own personal style.

**User Story:** I can see a list of the most recent posts on the freeCodeCamp forum.

**User Story:** For each topic, I can see the title and a list of links to users who have recently posted in it.

**User Story:** I can see the number of replies and views that each topic has had, and a timestamp of when the topic was last active.

**Hint:** To get the 30 most recent forum posts: <https://forum-proxy.freecodecamp.rocks/latest>.

When you are finished, include a link to your project on CodePen and click the "I've completed this challenge" button.

You can get feedback on your project by sharing it on the [freeCodeCamp forum](https://forum.freecodecamp.org/c/project-feedback/409).

# --solutions--

```js
// solution required
```


text:
package edu.umd.mith.sga.mss.oxford

import edu.umd.mith.sga.mss._
import java.io.File
import scala.io.Source
import scala.util.parsing.combinator._
import scalaz._, Scalaz._

case class PageInfo(
  oxfordId: String,
  shelfmarkLabel: String,
  pageNumberInfo: String \/ PageNumberInfo
)

case class PageNumberInfo(
  label: String,
  pageNumbers: List[PageNumber]
)

trait OxfordFormats {
  val HeaderPattern = """^(Filename)\s+(Description)$""".r
  val TargetPattern = """^([^\s]+\d\d\d\dt)\s+(Target Image)$""".r
  val LinePattern = """^([^\s]+\d\d\d\d)\s+([^,]+),\s+(.+)$""".r
  val FolioPattern = """^(?:(?:fol\.)|(?:p\.)) (.+)$""".r

  /** Oxford's abbreviations for page numbers differs from Tatsuo's, but this
    * object provides parsing into the same algebraic data type.
    */
  object PageNumberParser extends RegexParsers {
    override val skipWhitespace = false

    val plain: Parser[PageNumber] = "\\d+".r.map(Plain(_, ""))

    val rv: Parser[PageNumber] = ("\\d+".r ~ "[rv]".r).map {
      case n ~ "r" => Recto(n)
      case n ~ "v" => Verso(n)
    }

    val sub: Parser[PageNumber] = ("\\d+[abc]".r ~ ("\\s+".r ~> "recto|verso".r)).map {
      case n ~ "recto" => Recto(n)
      case n ~ "verso" => Verso(n)
    }

    val item: Parser[PageNumber] = plain | rv | sub

    def items: Parser[List[PageNumber]] =
      item.map(List(_)) ||| rep1sep(item, "\\s+and\\s+".r)

    def apply(s: String) = parseAll(items, s.trim)
  }

  /** Reads the Oxford "readme.txt" manifest into a list containing
    * information about each page.
    */
  def parseManifest(file: File): List[PageInfo] = {
    val manifestSource = Source.fromFile(file)
    val manifest: List[PageInfo] =
      manifestSource.getLines.map(_.trim).filter(_.nonEmpty).flatMap {
        case LinePattern(id, shelfmark, FolioPattern(pageNumberLabel)) =>
          val pageNumbers = List(Plain(pageNumberLabel, ""))
          // PageNumberParser(pageNumberLabel).getOrElse(
          //   throw new RuntimeException(f"Invalid page number: $pageNumberLabel%s.")
          // )

          PageInfo(id, shelfmark, PageNumberInfo(pageNumberLabel, pageNumbers).right).some

        case LinePattern(id, shelfmark, pageNumber) =>
          PageInfo(id, shelfmark, pageNumber.left).some

        case HeaderPattern(_, _) | TargetPattern(_, _) => None

        case line => throw new RuntimeException(f"Invalid line: $line%s.")
      }.toList

    manifestSource.close()
    manifest
  }

  /** Sanselan is very slow, so we also want to allow users to parse the output
    * of ImageMagick's `identify` application to determine image dimensions.
    */
  def parseImageInformation(file: File): Map[String, (Int, Int)] = {
    val ImageInformationLine = """^(?:.+?)/([^/]+)\.tif(?:\[\d+\])?\sTIFF\s(\d+)x(\d+)\s.*""".r

    val imageInformationSource = Source.fromFile(file)

    val imageSizes = imageInformationSource.getLines.map(_.trim).map {
      case ImageInformationLine(oxfordId, w, h) => oxfordId -> (w.toInt, h.toInt)
    }.toMap

    imageInformationSource.close()
    imageSizes
  }
}


text:
set -euf -o pipefail

BASEDIR=$(dirname "$0")
VIRTUAL_ENV_DISABLE_PROMPT=1
source ${BASEDIR}/env/bin/activate
${BASEDIR}/send_email.py "$@"


text:
package multiverse.server.util;

import java.util.concurrent.TimeUnit;
import java.util.*;
import java.util.concurrent.locks.*;

/**
 * detection or debug lock
 */
public class DLock extends ReentrantLock {
    DLock(String name) {
        super();

        setName(name);
    }

    public String toString() {
        return "[DLock lockName=" + getLockName() + ", hashCode=" + hashCode()
                + "]";
    }

    public void setName(String name) {
        lockName = name;
    }

    public String getLockName() {
        return lockName;
    }

    public void lock() {
        Thread currentThread = Thread.currentThread();

        System.out.println("lock: name=" + lockName + ", thread="
                + currentThread);
        boolean acquiredLock = false;
        rLock.lock();
        try {
            // actually acquire the lock now
            try {
                acquiredLock = super.tryLock(lockTimeoutMS,
                        TimeUnit.MILLISECONDS);
            } catch (Exception e) {
                System.err.println("dlock.lock: got exception: " + e);
                System.exit(-1);
            }
            if (acquiredLock) {
                synchronized (DLock.class) {
                    // update mapping of what locks each thread is holding
                    // eg: thread->lock mapping
                    // this is useful for when we detect a deadlock,
                    // we can see what locks each thread is holding
                    LinkedList<DLock> locks = threadLocks.get(currentThread);
                    if (locks == null) {
                        // this thread has no locks right now
                        System.out
                                .println("lock: lockName="
                                        + lockName
                                        + ", this thread has no locks yet, creating entry.  thread="
                                        + currentThread);
                        locks = new LinkedList<DLock>();
                        threadLocks.put(currentThread, locks);
                    }

                    // add entry to the lock order map
                    // we have to find the entry that maps from the last lock
                    // this thread held. we can add ourselves to that map
                    // updating: static DLock.lockOrderMap
                    DLock lastLock = null;
                    if (!locks.isEmpty()) {
                        lastLock = locks.getLast();
                    }
                    locks.add(this);

                    System.out.println("lock: lockName=" + lockName
                            + ", lastLock=" + lastLock);
                    if ((lastLock != null) && (lastLock != this)) {
                        Map<DLock, StackTraceElement[]> subMap = lockOrderMap
                                .get(lastLock);
                        if (subMap == null) {
                            // create a submap
                            subMap = new HashMap<DLock, StackTraceElement[]>();
                            lockOrderMap.put(lastLock, subMap);
                        }
                        // if there is already an entry for this ordering, dont
                        // generate a new stack trace since that can be pricey
                        if (subMap.get(this) == null) {
                            // generate
                            StackTraceElement[] dump = currentThread
                                    .getStackTrace();
                            subMap.put(this, dump);
                        }
                    }
                }
            }
        } finally {
            rLock.unlock();
        }
        if (!acquiredLock) {
            wLock.lock();
            try {
                throwException("acquire lock failed: forcing cycle detection");
                Log.error("DLock.lock: thread with lock error is: "
                        + currentThread);

                // for each thread we know of
                Log
                        .error("DLock.lock: dumping all threads currently holding locks");
                for (Thread thread : threadLocks.keySet()) {
                    LinkedList<DLock> heldLocks = threadLocks.get(thread);
                    for (DLock heldLock : heldLocks) {
                        Log.error("DLock.lock: thread " + thread
                                + ", is holding lock " + heldLock);
                        if (heldLock == this) {
                            Log
                                    .error("DLock.lock: thread has lock in question, dumping stack trace:\n"
                                            + makeStackDumpString(thread
                                                    .getStackTrace()));
                        }
                    }
                }
                Log
                        .error("DLock.lock: DONE dumping all threads currently held locks");
                Log.error("DLock.lock: detecting cycles for lock in question: "
                        + this);
                detectCycleHelper(this, new LinkedList<DLock>(),
                        new HashSet<DLock>());
                Log.error("DLock.lock: detecting all other cycles");
                detectCycle();
                Log.error("deadlock cycle detection complete, exiting process");
                System.exit(-1);
            } finally {
                wLock.unlock();
            }
        }
    }

    public void unlock() {
        wLock.lock();
        try {
            synchronized (DLock.class) {
                Thread currentThread = Thread.currentThread();

                // remove this lock from the thread's list of locks
                LinkedList<DLock> locks = threadLocks.get(currentThread);
                if (locks == null) {
                    // this thread has no locks - something is wrong
                    throwException("unlock, but thread has no previous locks");
                }
                DLock lastLock = locks.getLast();
                if (lastLock == null) {
                    // this thread has no locks
                    throwException("unlock, but thread has no previous locks");
                }
                if (lastLock == this) {
                    locks.removeLast();
                } else {
                    throwException("unlock, last lock did not match this lock");
                }
            }
            super.unlock();
        } finally {
            wLock.unlock();
        }
    }

    void throwException(String error) {
        wLock.lock();
        try {
            Log.error("DLock.throwException: lock in question is: "
                    + this + ", thread=" + Thread.currentThread().getName()
                    + ", msg=" + error);
            Log.dumpStack();
        } finally {
            wLock.unlock();
        }
    }

    /**
     * goes through the lock ordering map and looks for any cycles returns a set
     * of cycles
     */
    public static Set<List<DLock>> detectCycle() {
        synchronized (DLock.class) {
            Log.error("DLock.detectCycles: finding all child nodes");

            // find all child nodes
            Set<DLock> childNodes = getChildNodes();
            Log.error("DLock.detectCycle: found " + childNodes.size()
                    + " child nodes");

            // find all top nodes
            Set<DLock> topNodes = getTopNodes(childNodes);
            Log.error("DLock.detectCycle: found " + topNodes.size()
                    + " top nodes");

            // for each top node, do a depth first traversal
            HashSet<DLock> cycleNodes = new HashSet<DLock>();
            Set<List<DLock>> allCycles = new HashSet<List<DLock>>();
            for (DLock node : topNodes) {
                Log.error("DLock.detectCycle: doing depth first for top node "
                        + node);
                List<DLock> history = new LinkedList<DLock>();
                allCycles.addAll(detectCycleHelper(node, history, cycleNodes));
            }

            // now for each non-top-node, check for cycles.
            // for these, delete them if there is already
            // a top-node-cycle containing the full sub-cycle
            Log
                    .error("DLock.detectCycle: doing depth first for all child nodes");
            for (DLock node : childNodes) {
                Log
                        .error("DLock.detectCycle: doing depth first for child node "
                                + node);
                List<DLock> history = new LinkedList<DLock>();
                Set<List<DLock>> cycles = detectCycleHelper(node, history,
                        cycleNodes);

                // prune the cycles if it is already in the top node cycle
                for (List<DLock> cycle : cycles) {
                    if (!isSubset(cycle, allCycles)) {
                        allCycles.add(cycle);
                    }
                }
            }

            Log.error("DLock.detectCycle: printing out all detected cycles");
            for (List<DLock> cycle : allCycles) {
                printCycle(cycle);
            }
            Log.error("DLock.detectCycle: done with printout");
            return allCycles;
        }
    }

    protected static boolean isSubset(List<DLock> set, Set<List<DLock>> allSets) {
        for (List<DLock> testSet : allSets) {
            if (isSubset(set, testSet)) {
                return true;
            }
        }
        return false;
    }

    protected static boolean isSubset(List<DLock> subset, List<DLock> superset) {
        for (DLock element : subset) {
            if (!superset.contains(element)) {
                return false;
            }
        }
        return true;
    }

    // helper method, returns all child nodes (nodes that have parents)
    protected static Set<DLock> getChildNodes() {
        Set<DLock> childNodes = new HashSet<DLock>();
        for (Map<DLock, StackTraceElement[]> subMap : lockOrderMap.values()) {
            childNodes.addAll(subMap.keySet());
        }
        return childNodes;
    }

    // helper method, looks in lockOrderMap and returns all top nodes
    // assumes we have a lock
    // pass in a set of all childNodes
    protected static Set<DLock> getTopNodes(Set<DLock> childNodes) {
        Set<DLock> topNodes = new HashSet<DLock>();
        for (DLock node : lockOrderMap.keySet()) {
            if (!childNodes.contains(node)) {
                topNodes.add(node);
            }
        }
        return topNodes;
    }

    // helper method, assumes we have already locked the DLock class
    // traverses the tree, by taking 'node' and going depth first
    // for its children.
    // history is the 'stack' of nodes youre descending (path)
    // cycleNodes are the nodes that cause cycles - used to short circuit
    // returns a set of cycles
    // keeps track of the traversed nodes in 'history'
    protected static Set<List<DLock>> detectCycleHelper(DLock node,
            List<DLock> history, HashSet<DLock> cycleNodes) {
        if (Log.loggingDebug)
            Log.debug("DLock.detectCyleHelper: considering node " + node
                      + ", numCycleNodes=" + cycleNodes.size());

        // is the node we're at in the history already
        if (history.contains(node)) {
            if (Log.loggingDebug)
                Log.debug("DLock.detectCycleHelper: node " + node
                          + " already in history, cycle detected");
            history.add(node);
            // stackDump(history);
            Set<List<DLock>> cycle = new HashSet<List<DLock>>();
            cycle.add(history);
            cycleNodes.add(node);
            return cycle;
        }

        // no cycle, add this current node to the node's we've visited
        history.add(node);

        // find the children nodes of current node
        Map<DLock, StackTraceElement[]> subMap = lockOrderMap.get(node);
        if (subMap == null) {
            // we're at a leaf node, no cycles
            Log.debug("DLock.detectCycleHelper: node is leaf, returning");
            return new HashSet<List<DLock>>();
        }
        Set<DLock> childSet = subMap.keySet();
        if ((childSet == null) || (childSet.isEmpty())) {
            Log.debug("DLock.detectCycleHelper: node is leaf, returning");
            return new HashSet<List<DLock>>();
        }

        // descend into each child
        Set<List<DLock>> cycles = new HashSet<List<DLock>>();
        for (DLock child : childSet) {
            if (cycleNodes.contains(child)) {
                Log.debug("DLock.detectCycleHelper: child already causes cycle, skipping - currentNode="
                          + node + ", child=" + child);
                continue;
            }
            if (Log.loggingDebug)
                Log.debug("DLock.detectCycleHelper: currentNode=" + node
                          + ", decending, child=" + child + ", numChildren="
                          + childSet.size());
            // copy the history since its only valid going down
            List<DLock> historyCopy = new LinkedList<DLock>(history);
            Set<List<DLock>> childCycles = detectCycleHelper(child,
                    historyCopy, cycleNodes);
            cycles.addAll(childCycles);
        }
        return cycles;
    }

    /**
     * given the sequence of nodes which led to a cycle, this method will print
     * out the stack dumps for each lock sequence assumes we have synchronized
     * the DLock.class object
     */
    protected static void stackDump(List<DLock> nodes) {
        if (nodes == null) {
            System.err.println("ERROR: DLock.stackDump: nodes is null");
            return;
        }
        if (nodes.isEmpty()) {
            System.err.println("ERROR: DLock.stackDump: nodes list is empty");
            return;
        }

        System.err.println("Found Cycle, dumping history");
        Iterator<DLock> iter = nodes.iterator();
        DLock prev = null;
        DLock cur = null;
        for (prev = iter.next(); iter.hasNext(); prev = cur) {
            cur = iter.next();

            // turn the stacktrace dump into a string
            StackTraceElement[] stackArray = lockOrderMap.get(prev).get(cur);
            String stackTrace = "";
            for (int i = 0; i < stackArray.length; i++) {
                stackTrace += "  stack" + i + "=" + stackArray[i].toString()
                        + "\n";
            }

            // print it out
            System.err.println("ERROR: DLock.stackDump: had lock "
                    + prev.getLockName() + " when locked " + cur.getLockName()
                    + ", dump:\n" + stackTrace);
        }
    }

    // assumes we have the lock
    protected static void printCycle(List<DLock> cycle) {
        String s = "Cycle: ";
        DLock prev = null;
        for (DLock node : cycle) {
            s += "\nlock=" + node;

            // find the stack dump
            if (prev != null) {
                s += ", stackdump:\n";
                Map<DLock, StackTraceElement[]> subMap = lockOrderMap.get(prev);
                StackTraceElement[] trace = subMap.get(node);

                // print out the stack trace
                for (int i = 0; i < trace.length; i++) {
                    s += "  stack" + i + "=" + trace[i].toString() + "\n";
                }
            }

            prev = node;
        }
        Log.error("DLock.printCycle: " + s);
    }

    /**
     * turn the stacktrace dump into a string
     */
    public static String makeStackDumpString(StackTraceElement[] stackArray) {
        String stackTrace = "";
        for (int i = 0; i < stackArray.length; i++) {
            stackTrace += "  stack" + i + "=" + stackArray[i].toString() + "\n";
        }
        return stackTrace;
    }

    String threadName = null;

    String lockName = "unknown";

    // we keep track of the lock order so we can detect cycles in locking
    // lock we last acquired -> lock we just got -> stack trace
    static Map<DLock, Map<DLock, StackTraceElement[]>> lockOrderMap = new HashMap<DLock, Map<DLock, StackTraceElement[]>>();

    // we keep track of each thread's current locks (in order) so when
    // the thread does a new lock, we can store the entry of the current
    // lock its holding into the lockOrderMap
    static Map<Thread, LinkedList<DLock>> threadLocks = new HashMap<Thread, LinkedList<DLock>>();

    static int lockTimeoutMS = 30000;

    // the reentrant read write locks arent really used for reading writing.
    // they seperate the two classes of locks, the readlock is held while any
    // lock
    // is trying to lock. the writelock is held only when a thread has
    // discovered a deadlock
    // and is printing out information. we therefore need all readers to finish
    // updating
    // their info so when we print out the deadlock info, it is in a consistent
    // state
    static ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();

    static ReentrantReadWriteLock.ReadLock rLock = rwLock.readLock();

    static ReentrantReadWriteLock.WriteLock wLock = rwLock.writeLock();

    public static void main(String args[]) {
        DLock a = new DLock("A");
        DLock b = new DLock("B");
        a.lock();
        b.lock();
        a.lock();

        a.unlock();
        b.unlock();
        a.unlock();
        System.out.println("detecting cycles..");
        DLock.detectCycle();
        System.out.println("done");
    }

    private static final long serialVersionUID = 1L;
}


text:
import { Injectable } from '@angular/core';
import { Cordova, IonicNativePlugin, Plugin } from '@ionic-native/core';

/**
 * @name Webengage
 * @description
 * Ionic-Native wrapper that wraps Webengage Cordova plugin for Android and iOS
 *
 * @usage
 * ```typescript
 * import { Webengage, WebengageUser, WebengagePush, WebengageNotification } from '@ionic-native/webengage/ngx';
 *
 *
 * constructor(private webengage: Webengage, private webengageUser: WebengageUser, private webengagePush: WebengagePush, private webengageNotification: WebengageNotification ) { }
 *
 * ...
 *
 * this.webengage.engage();
 * ```
 */
@Plugin({
  pluginName: 'Webengage',
  plugin: 'cordova-plugin-webengage',
  pluginRef: 'webengage',
  repo: 'https://github.com/WebEngage/cordova-plugin',
  platforms: ['Android', 'iOS']
})
@Injectable({
  providedIn: 'root'
})
export class Webengage extends IonicNativePlugin {
  /**
   * Initializes WebEngage SDK
   * @param {any} [config]
   * @return {Promise<any>}
   */
  @Cordova()
  engage(config?: any): Promise<any> {
    return;
  }

  /**
   * Sets WebEngage SDK configuration
   * @param {string} key
   * @param {any} value
   * @return {Promise<any>}
   */
  @Cordova()
  options(key: string, value: any): Promise<any> {
    return;
  }

  /**
   * Tracks event
   * @param {string} eventName
   * @param {any} [attributes]
   * @return {Promise<any>}
   */
  @Cordova()
  track(eventName: string, attributes?: any): Promise<any> {
    return;
  }

  /**
   * Tracks screen
   * @param {string} eventName
   * @param {any} [screenData]
   * @return {Promise<any>}
   */
  @Cordova()
  screen(screenName: string, screenData?: any): Promise<any> {
    return;
  }
}

/**
 * @hidden
 */
@Plugin({
  pluginName: 'Webengage',
  plugin: 'cordova-plugin-webengage',
  pluginRef: 'webengage.user'
})
@Injectable({
  providedIn: 'root'
})
export class WebengageUser extends IonicNativePlugin {
  /**
   * Logs user in
   * @param {string} userId
   * @return {Promise<any>}
   */
  @Cordova()
  login(userId: string): Promise<any> {
    return;
  }

  /**
   * Logs user out
   * @return {Promise<any>}
   */
  @Cordova()
  logout(): Promise<any> {
    return;
  }

  /**
   * Sets user attribute
   * @param {string} key
   * @param {any} value
   * @return {Promise<any>}
   */
  @Cordova()
  setAttribute(key: string, value: any): Promise<any> {
    return;
  }
}

/**
 * @hidden
 */
@Plugin({
  pluginName: 'Webengage',
  plugin: 'cordova-plugin-webengage',
  pluginRef: 'webengage.push'
})
@Injectable({
  providedIn: 'root'
})
export class WebengagePush extends IonicNativePlugin {
  /**
   * Callback function is invoked when a push notification is clicked
   * @param {any} callback
   * @return {Promise<any>}
   */
  @Cordova()
  onClick(callback: any): Promise<any> {
    return;
  }

  /**
   * Sets push notification configuration
   * @param {string} key
   * @param {any} value
   * @return {Promise<any>}
   */
  @Cordova()
  options(key: string, value: any): Promise<any> {
    return;
  }
}

/**
 * @hidden
 */
@Plugin({
  pluginName: 'Webengage',
  plugin: 'cordova-plugin-webengage',
  pluginRef: 'webengage.notification'
})
@Injectable({
  providedIn: 'root'
})
export class WebengageNotification extends IonicNativePlugin {
  /**
   * Callback function is invoked when a in-app notification is shown
   * @param {any} callback
   * @return {Promise<any>}
   */
  @Cordova()
  onShown(callback: any): Promise<any> {
    return;
  }

  /**
   * Callback function is invoked when a in-app notification is clicked
   * @param {any} callback
   * @return {Promise<any>}
   */
  @Cordova()
  onClick(callback: any): Promise<any> {
    return;
  }

  /**
   * Callback function is invoked when a in-app notification is dismissed
   * @param {any} callback
   * @return {Promise<any>}
   */
  @Cordova()
  onDismiss(callback: any): Promise<any> {
    return;
  }

  /**
   * Sets in-app notification configuration
   * @param {string} key
   * @param {any} value
   * @return {Promise<any>}
   */
  @Cordova()
  options(key: string, value: any): Promise<any> {
    return;
  }
}


text:
#ifndef ALIANALYSISTASKEMCALLIGHT_H
#define ALIANALYSISTASKEMCALLIGHT_H

class TClonesArray;
class TString;
class TList;
class AliEmcalParticle;
class AliMCParticle;
class AliVCluster;
class AliVTrack;
class AliVParticle;
class AliVCaloCells;
class TH1;
class TProfile;
class AliEMCALGeometry;
class AliGenEventHeader;
class AliGenPythiaEventHeader;
class AliVCaloTrigger;
class AliAnalysisUtils;
class AliEMCALTriggerPatchInfo;
class AliAODTrack;

#include <map>
#include <set>
#include <string>
#include <vector>
#include <iostream>

#include "Rtypes.h"

#include "AliParticleContainer.h"
#include "AliMCParticleContainer.h"
#include "AliTrackContainer.h"
#include "AliClusterContainer.h"

#include "AliAnalysisTaskSE.h"
/**
 * @class AliAnalysisTaskEmcalLight
 * @brief Base task in the EMCAL framework (lighter version of AliAnalysisTaskEmcal)
 * @ingroup EMCALCOREFW
 * @author Salvatore Aiola <salvatore.aiola@cern.ch>, Yale University
 *
 * This class is the base class for Analysis Tasks using the
 * core EMCAL framework. User tasks can choose to inherit from it
 * as an alternative to AliAnalysisTaskEmcal.
 * In contrast to the normal AliAnalysisTaskSE, the main event
 * loop function to be implemented by the user is called Run.
 * This function is only called in case the event was selected
 * previously.
 *
 * A key feature is the handling of EMCAL containers (cluster/
 * particle/track). Users can create containers and attach it
 * to their analysis task.
 *
 * ~~~{.cxx}
 * AliParticleContainer *cont = task->AddParticleContainer("MCParticlesSelected");
 * cont->SetEtaLimits(-0.7, 0.7);
 * ~~~
 *
 * Note that the name in the container must match the name of the
 * TClonesArray in the input event connected to the container.
 * Containers can be accessed inside the task either by their name
 * or by their index as they were added to the task. The indices
 * of cluster- or particle-containers are not mixed. Containers
 * provide an easy access to content created by other tasks and
 * attached to the event as a TClonesArray.
 *
 * For more information refer to \subpage EMCALAnalysisTask
 */
class AliAnalysisTaskEmcalLight : public AliAnalysisTaskSE {
 public:

  /**
   * @enum EDataType_t
   * @brief Switch for the data type
   */
  enum EDataType_t {
    kUnknownDataType,
    kESD,
    kAOD
  };

  /**
   * @enum EBeamType_t
   * @brief Switch for the beam type
   */
  enum EBeamType_t {
    kNA       = -1,//!< Undefined
    kpp       = 0, //!< Proton-Proton
    kAA       = 1, //!< Nucleus-Nucleus
    kpA       = 2  //!< Proton-Nucleus
  };

  /**
   * @enum ECentralityEstimation_t
   * @brief Switch for the centrality estimation
   */
  enum ECentralityEstimation_t {
    kNoCentrality  = 0, //!< No centrality estimation
    kNewCentrality = 1, //!< New centrality estimation (AliMultSelection, see https://twiki.cern.ch/twiki/bin/viewauth/ALICE/AliMultSelectionCalibStatus for calibration status period-by-period)
    kOldCentrality = 2  //!< Old centrality estimation (AliCentrality, works only on Run-1 PbPb and pPb)
  };

  AliAnalysisTaskEmcalLight();
  AliAnalysisTaskEmcalLight(const char *name, Bool_t histo=kFALSE);
  virtual ~AliAnalysisTaskEmcalLight();

  // Containers
  AliParticleContainer       *AddParticleContainer(std::string branchName, std::string contName="");
  AliClusterContainer        *AddClusterContainer(std::string branchName, std::string contName="");
  void                        AdoptParticleContainer(AliParticleContainer* cont)    { fParticleCollArray[cont->GetName()] = cont; }
  void                        AdoptClusterContainer(AliClusterContainer* cont)      { fClusterCollArray[cont->GetName()]  = cont; }
  AliParticleContainer       *GetParticleContainer(std::string name)          const;
  AliClusterContainer        *GetClusterContainer(std::string name)           const;
  AliMCParticleContainer     *GetMCParticleContainer(std::string name)        const { return dynamic_cast<AliMCParticleContainer*>(GetParticleContainer(name)); }
  AliTrackContainer          *GetTrackContainer(std::string name)             const { return dynamic_cast<AliTrackContainer*>(GetParticleContainer(name))     ; }
  void                        RemoveParticleContainer(std::string name)             { fParticleCollArray.erase(name)                      ; }
  void                        RemoveClusterContainer(std::string name)              { fClusterCollArray.erase(name)                       ; }

  // Other input data
  void                        SetCaloCellsName(const char *n)                       { fCaloCellsName     = n                              ; }
  void                        SetCaloTriggerPatchInfoName(const char *n)            { fCaloTriggerPatchInfoName = n                       ; }
  void                        SetCaloTriggersName(const char *n)                    { fCaloTriggersName  = n                              ; }
  void                        SetCentralityEstimator(const char *c)                 { fCentEst           = c                              ; }
  void                        SetIsMonteCarlo(Bool_t i)                             { fIsMonteCarlo      = i                              ; }
  void                        SetIsPythia(Bool_t i);
  void                        SetMCEventHeaderName(const char* name);
  void                        SetForceBeamType(EBeamType_t f)                       { fForceBeamType     = f                              ; }

  // Task configuration
  void                        SetCentralityEstimation(ECentralityEstimation_t b)    { fCentralityEstimation = b                     ; }
  void                        SetMakeGeneralHistograms(Bool_t g)                    { fGeneralHistograms = g                              ; }
  void                        SetNeedEmcalGeom(Bool_t n)                            { fNeedEmcalGeom     = n                              ; }
  void                        SetCentBins(const std::vector<double>& bins)          { fCentBins = std::vector<double>(bins)               ; }
  Int_t                       GetNCentBins()                                  const { return fCentBins.size() > 1 ? fCentBins.size() - 1 : 1; }
  void                        SetSwitchOffLHC15oFaultyBranches(Bool_t b)            { fSwitchOffLHC15oFaultyBranches = b                  ; }

  // Event selection
  void                        SetTriggerSelectionBitMap(UInt_t t)                   { fTriggerSelectionBitMap = t                         ; }
  void                        SetCentRange(Double_t min, Double_t max)              { fMinCent           = min  ; fMaxCent     = max      ; }
  void                        SetVzRange(Double_t min, Double_t max)                { fMinVz             = min  ; fMaxVz       = max      ; }
  void                        SetZvertexDiffValue(Double_t cut)                     { fMaxVzDiff         = cut                            ; }
  void                        SetMinNVertCont(Int_t cut)                            { fMinNVertCont      = cut                            ; }
  void                        SetPtHardRange(Double_t min, Double_t max)            { fMinPtHard         = min  ; fMaxPtHard   = max      ; }
  void                        SetMaxMinimumBiasPtHard(Int_t max)                    { fMaxMinimumBiasPtHard = max                         ; }
  void                        AddAcceptedTriggerClass(const char* trigClass)        { fAcceptedTriggerClasses.insert(trigClass)           ; }
  void                        AddRejectedTriggerClass(const char* trigClass)        { fRejectedTriggerClasses.insert(trigClass)           ; }
  void                        ClearAcceptedTriggerClasses()                         { fAcceptedTriggerClasses.clear()                     ; }
  void                        ClearRejectedTriggerClasses()                         { fRejectedTriggerClasses.clear()                     ; }
  void                        SetMCFilter()                                         { fMCRejectFilter = kTRUE                             ; }
  void                        ResetMCFilter()                                       { fMCRejectFilter = kFALSE                            ; }
  void                        SetJetPtFactor(Float_t f)                             { fPtHardAndJetPtFactor = f                           ; }
  Float_t                     JetPtFactor()                                         { return fPtHardAndJetPtFactor                        ; }
  void                        SetClusterPtFactor(Float_t f)                         { fPtHardAndClusterPtFactor = f                       ; }
  Float_t                     ClusterPtFactor()                                     { return fPtHardAndClusterPtFactor                    ; }
  void                        SetTrackPtFactor(Float_t f)                           { fPtHardAndTrackPtFactor = f                         ; }
  Float_t                     TrackPtFactor()                                       { return fPtHardAndTrackPtFactor                      ; }
  void                        SetEventSelectionAfterRun(Bool_t b)                   { fEventSelectionAfterRun = b                         ; }
  void                        SelectGeneratorName(TString gen)                      { fSelectGeneratorName = gen                          ; }
  void                        SetInhibit(Bool_t s)                                  { fInhibit = s                                        ; }
  void                        SetEventWeightRange(Double_t min, Double_t max)       { fMinimumEventWeight = min; fMaximumEventWeight = max; }

  Bool_t IsInhibit() const { return fInhibit; }

 protected:
  void                        SetRejectionReasonLabels(TAxis* axis);
  void                        AddObjectToEvent(TObject *obj, Bool_t attempt = kFALSE);
  TClonesArray               *GetArrayFromEvent(const char *name, const char *clname=0);
  EBeamType_t                 GetBeamType();
  Bool_t                      PythiaInfoFromFile(const char* currFile, Float_t &fXsec, Float_t &fTrials, Int_t &pthard);
  Bool_t                      IsTrackInEmcalAcceptance(AliVParticle* part, Double_t edges=0.9) const;
  Bool_t                      CheckMCOutliers();

  // Overloaded AliAnalysisTaskSE methods
  void                        UserCreateOutputObjects();
  void                        UserExec(Option_t *option);
  Bool_t                      UserNotify();

  // Virtual functions, to be overloaded in derived classes
  virtual void                ExecOnce();
  virtual Bool_t              FillGeneralHistograms(Bool_t eventSelected);
  virtual Bool_t              IsEventSelected();
  virtual Bool_t              RetrieveEventObjects();
  /**
   * This function optionally fills histograms created by the users. Can
   * access data previously handled by the user Run function.
   * @return
   */
  virtual Bool_t              FillHistograms()                  { return kTRUE                 ; }
  /**
   * Run function. This is the core function of the analysis and
   * contains the user code. Therefore users have to implement this
   * function.
   *
   * @return True if event is selected, false otherwise
   */
  virtual Bool_t              Run()                             { return kTRUE                 ; }

  // Static utilities
  static void                 GetEtaPhiDiff(const AliVTrack *t, const AliVCluster *v, Double_t &phidiff, Double_t &etadiff);
  static Byte_t               GetTrackType(const AliVTrack *t);
  static Byte_t               GetTrackType(const AliAODTrack *aodTrack, UInt_t filterBit1, UInt_t filterBit2);
  static Double_t             DeltaPhi(Double_t phia, Double_t phib, Double_t rMin = -TMath::Pi()/2, Double_t rMax = 3*TMath::Pi()/2);
  static std::vector<double>  GenerateFixedBinArray(int n, double min, double max, bool last = true);
  static void                 GenerateFixedBinArray(int n, double min, double max, std::vector<double>& array, bool last = true);
  static std::vector<double>  GenerateLogFixedBinArray(int n, double min, double max, bool last = true);
  static void                 GenerateLogFixedBinArray(int n, double min, double max, std::vector<double>& array, bool last = true);
  static Double_t             GetParallelFraction(AliVParticle* part1, AliVParticle* part2);
  static Double_t             GetParallelFraction(const TVector3& vect1, AliVParticle* part2);
  static EBeamType_t          BeamTypeFromRunNumber(Int_t runnumber);

  static Double_t             fgkEMCalDCalPhiDivide;       ///<  phi value used to distinguish between DCal and EMCal

  // Task configuration
  EBeamType_t                 fForceBeamType;              ///< forced beam type
  Bool_t                      fGeneralHistograms;          ///< whether or not it should fill some general histograms
  Bool_t                      fCreateHisto;                ///< whether or not create histograms
  Bool_t                      fNeedEmcalGeom;              ///< whether or not the task needs the emcal geometry
  std::vector<double>         fCentBins;                   ///< how many centrality bins
  ECentralityEstimation_t     fCentralityEstimation;       ///< Centrality estimation

  // Input data
  Bool_t                      fIsPythia;                   ///< if it is a PYTHIA production
  Bool_t                      fIsMonteCarlo;               ///< if it is a MC production
  TString                     fMCEventHeaderName;          ///< Looks for MC event properties in a particular MC event type (useful for a MC cocktail production)
  TString                     fCaloCellsName;              ///< name of calo cell collection
  TString                     fCaloTriggersName;           ///< name of calo triggers collection
  TString                     fCaloTriggerPatchInfoName;   ///< trigger patch info array name
  TString                     fCentEst;                    ///< name of the centrality estimator

  std::map<std::string,
  AliParticleContainer*>      fParticleCollArray;          ///< particle/track collection array
  std::map<std::string,
  AliClusterContainer*>       fClusterCollArray;          ///< cluster collection array

  // Event selection
  UInt_t                      fTriggerSelectionBitMap;     ///< trigger selection bit map
  Double_t                    fMinCent;                    ///< min centrality for event selection
  Double_t                    fMaxCent;                    ///< max centrality for event selection
  Double_t                    fMinVz;                      ///< min vertex for event selection
  Double_t                    fMaxVz;                      ///< max vertex for event selection
  Double_t                    fMaxVzDiff;                  ///< upper limit for distance between primary and SPD vertex
  Double_t                    fMinNVertCont;               ///< minumum number of vertex contributors
  Double_t                    fMinPtHard;                  ///< select minimum pt hard (MC)
  Double_t                    fMaxPtHard;                  ///< select maximum pt hard (MC)
  Double_t                    fMaxMinimumBiasPtHard;       ///< maximum pt hard for the minimum bias pt hard bin (MC)
  std::set<std::string>       fAcceptedTriggerClasses;     ///< list of accepted trigger classes
  std::set<std::string>       fRejectedTriggerClasses;     ///< list of accepted trigger classes
  Bool_t                      fMCRejectFilter;             ///< enable the filtering of events by tail rejection
  Float_t                     fPtHardAndJetPtFactor;       ///< Factor between ptHard and jet pT to reject/accept event.
  Float_t                     fPtHardAndClusterPtFactor;   ///< Factor between ptHard and cluster pT to reject/accept event.
  Float_t                     fPtHardAndTrackPtFactor;     ///< Factor between ptHard and track pT to reject/accept event.
  Bool_t                      fSwitchOffLHC15oFaultyBranches; ///< Switch off faulty tree branches in LHC15o AOD trees
  Bool_t                      fEventSelectionAfterRun;     ///< If kTRUE, the event selection is performed after Run() but before FillHistograms()
  TString                     fSelectGeneratorName;        ///< Selects only events produced by a generator that has a name containing a string
  Double_t                    fMinimumEventWeight;         ///< Minimum event weight for the related bookkeping histogram
  Double_t                    fMaximumEventWeight;         ///< Minimum event weight for the related bookkeping histogram

  // Service fields
  Bool_t                      fInhibit;                    //!<!inhibit execution of the task
  Bool_t                      fLocalInitialized;           //!<!whether or not the task has been already initialized
  EDataType_t                 fDataType;                   //!<!data type (ESD or AOD)
  AliEMCALGeometry           *fGeom;                       //!<!emcal geometry
  AliVCaloCells              *fCaloCells;                  //!<!cells
  AliVCaloTrigger            *fCaloTriggers;               //!<!calo triggers
  TClonesArray               *fTriggerPatchInfo;           //!<!trigger patch info array
  Double_t                    fCent;                       //!<!event centrality
  Int_t                       fCentBin;                    //!<!event centrality bin
  Double_t                    fEPV0;                       //!<!event plane V0
  Double_t                    fEPV0A;                      //!<!event plane V0A
  Double_t                    fEPV0C;                      //!<!event plane V0C
  Double_t                    fVertex[3];                  //!<!event vertex
  Double_t                    fVertexSPD[3];               //!<!event Svertex
  Int_t                       fNVertCont;                  //!<!event vertex number of contributors
  Int_t                       fNVertSPDCont;               //!<!event SPD vertex number of contributors
  ULong_t                     fFiredTriggerBitMap;         //!<!bit map of fired triggers
  std::vector<std::string>    fFiredTriggerClasses;        //!<!trigger classes fired by the current event
  EBeamType_t                 fBeamType;                   //!<!event beam type
  AliGenEventHeader          *fMCHeader;                   //!<!event MC header
  AliGenPythiaEventHeader    *fPythiaHeader;               //!<!event Pythia header
  Int_t                       fPtHardBin;                  //!<!event pt hard bin
  Double_t                    fPtHard;                     //!<!event pt hard
  Int_t                       fNTrials;                    //!<!event trials
  Float_t                     fXsection;                   //!<!x-section from pythia header
  Float_t                     fEventWeight;                //!<!event weight
  TString                     fGeneratorName;              //!<!name of the MC generator used to produce the current event (only AOD)

  // Output
  TList                      *fOutput;                     //!<!output list

 private:
  std::map<std::string, TH1*> fHistograms;                 //!<!general QA histograms
  TH1* GetGeneralTH1(const char* name, bool warn=false);
  TH2* GetGeneralTH2(const char* name, bool warn=false);
  TProfile* GetGeneralTProfile(const char* name, bool warn=false);

  AliAnalysisTaskEmcalLight(const AliAnalysisTaskEmcalLight&);            // not implemented
  AliAnalysisTaskEmcalLight &operator=(const AliAnalysisTaskEmcalLight&); // not implemented

  /// \cond CLASSIMP
  ClassDef(AliAnalysisTaskEmcalLight, 5);
  /// \endcond
};

#endif